Programs & Examples On #Java ee 6

Use this tag for questions relating specifically to Java Enterprise Edition 6.

What is javax.inject.Named annotation supposed to be used for?

@Inject instead of Spring’s @Autowired to inject a bean.
@Named instead of Spring’s @Component to declare a bean.

Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar is in your classpath)

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

Adding reference to:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>${jersey1.version}</version>
</dependency>

As long as adding clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true); on client creation solved the issue for me:

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
Client client = Client.create(clientConfig);

Java Round up Any Number

10 years later but that problem still caught me.

So this is the answer to those that are too late as me.

This does not work

int b = (int) Math.ceil(a / 100);

Cause the result a / 100 turns out to be an integer and it's rounded so Math.ceil can't do anything about it.

You have to avoid the rounded operation with this

int b = (int) Math.ceil((float) a / 100);

Now it works.

React ignores 'for' attribute of the label element

The for attribute is called htmlFor for consistency with the DOM property API. If you're using the development build of React, you should have seen a warning in your console about this.

Alter column, add default constraint

I confirm like the comment from JohnH, never use column types in the your object names! It's confusing. And use brackets if possible.

Try this:

ALTER TABLE [TableName]
ADD  DEFAULT (getutcdate()) FOR [Date]; 

Finding the position of bottom of a div with jquery

var top = ($('#bottom').position().top) + ($('#bottom').height());

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

Determine the number of rows in a range

I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called rows that will give you the number of rows.

So, if you have a named data range called Data that has 7 rows, then =ROWS(Data) will show 7 in that cell.

Setting up Gradle for api 26 (Android)

Appart from setting maven source url to your gradle, I would suggest to add both design and appcompat libraries. Currently the latest version is 26.1.0

maven {
    url "https://maven.google.com"
}

...

compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'

Twitter bootstrap progress bar animation on page load

Bootstrap uses CSS3 transitions so progress bars are automatically animated when you set the width of .bar trough javascript / jQuery.

http://jsfiddle.net/3j5Je/ ..see?

Missing visible-** and hidden-** in Bootstrap v4

i like the bootstrap3 style as the device width of bootstrap4
so i modify the css as below
<pre>
.visible-xs, .visible-sm, .visible-md, .visible-lg { display:none !important; }
.visible-xs-block, .visible-xs-inline, .visible-xs-inline-block,
.visible-sm-block, .visible-sm-inline, .visible-sm-inline-block,
.visible-md-block, .visible-md-inline, .visible-md-inline-block,
.visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { display:none !important; }
@media (max-width:575px) {
table.visible-xs                { display:table !important; }
tr.visible-xs                   { display:table-row !important; }
th.visible-xs, td.visible-xs    { display:table-cell !important; }

.visible-xs                 { display:block !important; }
.visible-xs-block { display:block !important; }
.visible-xs-inline { display:inline !important; }
.visible-xs-inline-block { display:inline-block !important; }
}

@media (min-width:576px) and (max-width:767px) {
table.visible-sm { display:table !important; }
tr.visible-sm { display:table-row !important; }
th.visible-sm,
td.visible-sm { display:table-cell !important; }

.visible-sm { display:block !important; }
.visible-sm-block { display:block !important; }
.visible-sm-inline { display:inline !important; }
.visible-sm-inline-block { display:inline-block !important; }
}

@media (min-width:768px) and (max-width:991px) {
table.visible-md { display:table !important; }
tr.visible-md { display:table-row !important; }
th.visible-md,
td.visible-md { display:table-cell !important; }

.visible-md { display:block !important; }
.visible-md-block { display:block !important; }
.visible-md-inline { display:inline !important; }
.visible-md-inline-block { display:inline-block !important; }
}

@media (min-width:992px) and (max-width:1199px) {
table.visible-lg { display:table !important; }
tr.visible-lg { display:table-row !important; }
th.visible-lg,
td.visible-lg { display:table-cell !important; }

.visible-lg { display:block !important; }
.visible-lg-block { display:block !important; }
.visible-lg-inline { display:inline !important; }
.visible-lg-inline-block { display:inline-block !important; }
}

@media (min-width:1200px) {
table.visible-xl { display:table !important; }
tr.visible-xl { display:table-row !important; }
th.visible-xl,
td.visible-xl { display:table-cell !important; }

.visible-xl { display:block !important; }
.visible-xl-block { display:block !important; }
.visible-xl-inline { display:inline !important; }
.visible-xl-inline-block { display:inline-block !important; }
}

@media (max-width:575px)                        { .hidden-xs{display:none !important;} }
@media (min-width:576px) and (max-width:767px)  { .hidden-sm{display:none !important;} }
@media (min-width:768px) and (max-width:991px)  { .hidden-md{display:none !important;} }
@media (min-width:992px) and (max-width:1199px) { .hidden-lg{display:none !important;} }
@media (min-width:1200px)                       { .hidden-xl{display:none !important;} }
</pre>

How to test an SQL Update statement before running it?

Autocommit OFF ...

MySQL

set autocommit=0;

It sets the autommit off for the current session.

You execute your statement, see what it has changed, and then rollback if it's wrong or commit if it's what you expected !

EDIT: The benefit of using transactions instead of running select query is that you can check the resulting set easierly.

How to call multiple functions with @click in vue?

This simple way to do v-on:click="firstFunction(); secondFunction();"

Where do I call the BatchNormalization function in Keras?

This thread is misleading. Tried commenting on Lucas Ramadan's answer, but I don't have the right privileges yet, so I'll just put this here.

Batch normalization works best after the activation function, and here or here is why: it was developed to prevent internal covariate shift. Internal covariate shift occurs when the distribution of the activations of a layer shifts significantly throughout training. Batch normalization is used so that the distribution of the inputs (and these inputs are literally the result of an activation function) to a specific layer doesn't change over time due to parameter updates from each batch (or at least, allows it to change in an advantageous way). It uses batch statistics to do the normalizing, and then uses the batch normalization parameters (gamma and beta in the original paper) "to make sure that the transformation inserted in the network can represent the identity transform" (quote from original paper). But the point is that we're trying to normalize the inputs to a layer, so it should always go immediately before the next layer in the network. Whether or not that's after an activation function is dependent on the architecture in question.

fe_sendauth: no password supplied

After making changes to the pg_hba.conf or postgresql.conf files, the cluster needs to be reloaded to pick up the changes.

From the command line: pg_ctl reload

From within a db (as superuser): select pg_reload_conf();

From PGAdmin: right-click db name, select "Reload Configuration"

Note: the reload is not sufficient for changes like enabling archiving, changing shared_buffers, etc -- those require a cluster restart.

CodeIgniter 404 Page Not Found, but why?

In my case I was using it on localhost and forgot to change RewriteBase in .htaccess.

Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

android - listview get item view by position

Listview lv = (ListView) findViewById(R.id.previewlist);

    final BaseAdapter adapter = new PreviewAdapter(this, name, age);

    confirm.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


            View view = null;

            String value;
            for (int i = 0; i < adapter.getCount(); i++) {

                view = adapter.getView(i, view, lv);

                Textview et = (TextView) view.findViewById(R.id.passfare);


                value=et.getText().toString();

                 Toast.makeText(getApplicationContext(), value,
                 Toast.LENGTH_SHORT).show();
            }



        }
    });

Why aren't Xcode breakpoints functioning?

I believe that a project can also become corrupted in regards to breakpoints. I have a project, for example, that WILL NOT break on any breakpoints that it remembers from the previous session. I first wrote about this here

How to get all options in a drop-down list by Selenium WebDriver using C#?

Use IList<IWebElement> instead of List<IWebElement>.

For instance:

IList<IWebElement> options = elem.FindElements(By.TagName("option"));
foreach (IWebElement option in options)
{
    Console.WriteLine(option.Text);
}

Accessing Imap in C#

MailSystem.NET contains all your need for IMAP4. It's free & open source.

(I'm involved in the project)

How to check whether a string contains a substring in Ruby

user_input = gets.chomp
user_input.downcase!

if user_input.include?('substring')
  # Do something
end

This will help you check if the string contains substring or not

puts "Enter a string"
user_input = gets.chomp  # Ex: Tommy
user_input.downcase!    #  tommy


if user_input.include?('s')
    puts "Found"
else
    puts "Not found"
end

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

I did some more research and found this place to give me what I needed - feels clean and relates to update data when refreshed from server: https://blog.angular-university.io/angular-material-data-table/

Most credits to the page above. Below is a sample of how a mat-selector can be used to update a mat-table bound to a datasource on change of selection. I am using Angular 7. Sorry for being extensive, trying to be complete but concise - I have ripped out as many non-needed parts as possible. With this hoping to help someone else getting forward faster!

organization.model.ts:

export class Organization {
    id: number;
    name: String;
}

organization.service.ts:

import { Observable, empty } from 'rxjs';
import { of } from 'rxjs';

import { Organization } from './organization.model';

export class OrganizationService {
  getConstantOrganizations(filter: String): Observable<Organization[]> {
    if (filter === "All") {
      let Organizations: Organization[] = [
        { id: 1234, name: 'Some data' }
      ];
      return of(Organizations);
     } else {
       let Organizations: Organization[] = [
         { id: 5678, name: 'Some other data' }
       ];
     return of(Organizations);
  }

  // ...just a sample, other filterings would go here - and of course data instead fetched from server.
}

organizationdatasource.model.ts:

import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, finalize } from "rxjs/operators";

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';

export class OrganizationDataSource extends DataSource<Organization> {
  private organizationsSubject = new BehaviorSubject<Organization[]>([]);

  private loadingSubject = new BehaviorSubject<boolean>(false);

  public loading$ = this.loadingSubject.asObservable();

  constructor(private organizationService: OrganizationService, ) {
    super();
  }

  loadOrganizations(filter: String) {
    this.loadingSubject.next(true);

    return this.organizationService.getOrganizations(filter).pipe(
      catchError(() => of([])),
      finalize(() => this.loadingSubject.next(false))
    ).subscribe(organization => this.organizationsSubject.next(organization));
  }

  connect(collectionViewer: CollectionViewer): Observable<Organization[]> {
    return this.organizationsSubject.asObservable();
  }

  disconnect(collectionViewer: CollectionViewer): void {
    this.organizationsSubject.complete();
    this.loadingSubject.complete();
  }
}

organizations.component.html:

<div class="spinner-container" *ngIf="organizationDataSource.loading$ | async">
    <mat-spinner></mat-spinner>
</div>

<div>
  <form [formGroup]="formGroup">
    <mat-form-field fxAuto>
      <div fxLayout="row">
        <mat-select formControlName="organizationSelectionControl" (selectionChange)="updateOrganizationSelection()">
          <mat-option *ngFor="let organizationSelectionAlternative of organizationSelectionAlternatives"
            [value]="organizationSelectionAlternative">
            {{organizationSelectionAlternative.name}}
          </mat-option>
        </mat-select>
      </div>
    </mat-form-field>
  </form>
</div>

<mat-table fxLayout="column" [dataSource]="organizationDataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.name}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="number">
    <mat-header-cell *matHeaderCellDef>Number</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.number}}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

organizations.component.scss:

.spinner-container {
    height: 360px;
    width: 390px;
    position: fixed;
}

organization.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
import { OrganizationDataSource } from './organizationdatasource.model';

@Component({
  selector: 'organizations',
  templateUrl: './organizations.component.html',
  styleUrls: ['./organizations.component.scss']
})
export class OrganizationsComponent implements OnInit {
  public displayedColumns: string[];
  public organizationDataSource: OrganizationDataSource;
  public formGroup: FormGroup;

  public organizationSelectionAlternatives = [{
    id: 1,
    name: 'All'
  }, {
    id: 2,
    name: 'With organization update requests'
  }, {
    id: 3,
    name: 'With contact update requests'
  }, {
    id: 4,
    name: 'With order requests'
  }]

  constructor(
    private formBuilder: FormBuilder,
    private organizationService: OrganizationService) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      'organizationSelectionControl': []
    })

    const toSelect = this.organizationSelectionAlternatives.find(c => c.id == 1);
    this.formGroup.get('organizationSelectionControl').setValue(toSelect);

    this.organizationDataSource = new OrganizationDataSource(this.organizationService);
    this.displayedColumns = ['name', 'number' ];
    this.updateOrganizationSelection();
  }

  updateOrganizationSelection() {
    this.organizationDataSource.loadOrganizations(this.formGroup.get('organizationSelectionControl').value.name);
  }
}

How do I encrypt and decrypt a string in python?

You can do this easily by using the library cryptocode. Here is how you install:

pip install cryptocode

Encrypting a message (example code):

import cryptocode

encoded = cryptocode.encrypt("mystring","mypassword")
## And then to decode it:
decoded = cryptocode.decrypt(encoded, "mypassword")

Documentation can be found here

SQL Client for Mac OS X that works with MS SQL Server

I use the Navicat clients for MySQL and PostgreSQL and am happy with them. "good" is obviously subjective... how do you judge your DB clients?

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

IE11 does implement String.prototype.includes so why not using the official Polyfill?

  if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
      if (typeof start !== 'number') {
        start = 0;
      }

      if (start + search.length > this.length) {
        return false;
      } else {
        return this.indexOf(search, start) !== -1;
      }
    };
  }

Source: polyfill source

How to add a second css class with a conditional value in razor MVC 4

You can use String.Format function to add second class based on condition:

<div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">

How to urlencode data for curl command?

Use Perl's URI::Escape module and uri_escape function in the second line of your bash script:

...

value="$(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "$2")"
...

Edit: Fix quoting problems, as suggested by Chris Johnsen in the comments. Thanks!

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

How can I get a list of all values in select box?

You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

http://jsfiddle.net/WfBRr/5/

Storing data into list with class

  public IEnumerable<CustInfo> SaveCustdata(CustInfo cust)
        {
            try
            {
                var customerinfo = new CustInfo
                {
                    Name = cust.Name,
                    AccountNo = cust.AccountNo,
                    Address = cust.Address
                };
                List<CustInfo> custlist = new List<CustInfo>();
                custlist.Add(customerinfo);
                return custlist;
            }
            catch (Exception)
            {
                return null;
            }
        }

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

C# DataTable.Select() - How do I format the filter criteria to include null?

The way to check for null is to check for it:

DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");

You can use and and or in the Select statement.

Android Facebook style slide

Here is yet another (very nice) open source library!

The good feature about this one is that it is easily integrated with ActionBarSherlock.

Here's the github project link

Here's the Google Play download link

Can I animate absolute positioned element with CSS transition?

You forgot to define the default value for left so it doesn't know how to animate.

.test {
    left: 0;
    transition:left 1s linear;
}

See here: http://jsfiddle.net/shomz/yFy5n/5/

How to lay out Views in RelativeLayout programmatically?

From what I've been able to piece together, you have to add the view using LayoutParams.

LinearLayout linearLayout = new LinearLayout(this);

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

parentView.addView(linearLayout, relativeParams);

All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);

Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

python numpy machine epsilon

It will already work, as David pointed out!

>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
... 
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

Conditional step/stage in Jenkins pipeline

Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

stage('feature-branch-stuff') {
    when {
        branch 'feature/*'
    }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    when {
        expression {
            return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    when { 
        environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


The directive beforeAgent true can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:

when { beforeAgent true; expression { return isStageConfigured(config) } }

Release post and docs


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.

Codeigniter displays a blank page instead of error messages

I was having same problem, i installed latest xamp version and found my site is not working, after research and wasting time i found that.

I need to turn on following tag in php.ini file short_open_tag=On

Make sure to restart apache after doing this.

Hope this helps, most of these problems are related to php.ini file or fresh installation if your site was already running as other people facing similar issue.

How to avoid Python/Pandas creating an index in a saved csv?

If you want a good format the next statement is the best:

dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)

In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.

Implementing INotifyPropertyChanged - does a better way exist?

Without using something like postsharp, the minimal version I use uses something like:

public class Data : INotifyPropertyChanged
{
    // boiler-plate
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    // props
    private string name;
    public string Name
    {
        get { return name; }
        set { SetField(ref name, value, "Name"); }
    }
}

Each property is then just something like:

private string name;
public string Name
{
    get { return name; }
    set { SetField(ref name, value, "Name"); }
}

which isn't huge; it can also be used as a base-class if you want. The bool return from SetField tells you if it was a no-op, in case you want to apply other logic.


or even easier with C# 5:

protected bool SetField<T>(ref T field, T value,
    [CallerMemberName] string propertyName = null)
{...}

which can be called like this:

set { SetField(ref name, value); }

with which the compiler will add the "Name" automatically.


C# 6.0 makes the implementation easier:

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

...and now with C#7:

protected void OnPropertyChanged(string propertyName)
   => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

protected bool SetField<T>(ref T field, T value,[CallerMemberName] string propertyName =  null)
{
    if (EqualityComparer<T>.Default.Equals(field, value)) return false;
    field = value;
    OnPropertyChanged(propertyName);
    return true;
}

private string name;
public string Name
{
    get => name;
    set => SetField(ref name, value);
}

And, with C# 8 and Nullable reference types, it would look like this:

public event PropertyChangedEventHandler? PropertyChanged;

protected void OnPropertyChanged(string? propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

protected bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
    if (EqualityComparer<T>.Default.Equals(field, value)) return false;
    field = value;
    OnPropertyChanged(propertyName);
    return true;
}

private string name;
public string Name
{
    get => name;
    set => SetField(ref name, value);
}

List<Map<String, String>> vs List<? extends Map<String, String>>

As you mentioned, there could be two below versions of defining a List:

  1. List<? extends Map<String, String>>
  2. List<?>

2 is very open. It can hold any object type. This may not be useful in case you want to have a map of a given type. In case someone accidentally puts a different type of map, for example, Map<String, int>. Your consumer method might break.

In order to ensure that List can hold objects of a given type, Java generics introduced ? extends. So in #1, the List can hold any object which is derived from Map<String, String> type. Adding any other type of data would throw an exception.

Unused arguments in R

One approach (which I can't imagine is good programming practice) is to add the ... which is traditionally used to pass arguments specified in one function to another.

> multiply <- function(a,b) a*b
> multiply(a = 2,b = 4,c = 8)
Error in multiply(a = 2, b = 4, c = 8) : unused argument(s) (c = 8)
> multiply2 <- function(a,b,...) a*b
> multiply2(a = 2,b = 4,c = 8)
[1] 8

You can read more about ... is intended to be used here

json_decode() expects parameter 1 to be string, array given

here is the solution for similar problem which i was facing while extracting name from user profile facebook json object

$uname=json_encode($userprof);
$uname=json_decode($uname);
echo "Welcome " . $uname -> name  ;

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

Is there an eval() function in Java?

As previous answers, there is no standard API in Java for this.

You can add groovy jar files to your path and groovy.util.Eval.me("4*5") gets your job done.

What is the difference between IQueryable<T> and IEnumerable<T>?

We use IEnumerable and IQueryable to manipulate the data that is retrieved from database. IQueryable inherits from IEnumerable, so IQueryable does contain all the IEnumerable features. The major difference between IQueryable and IEnumerable is that IQueryable executes query with filters whereas IEnumerable executes the query first and then it filters the data based on conditions.

Find more detailed differentiation below :

IEnumerable

  1. IEnumerable exists in the System.Collections namespace
  2. IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data
  3. IEnumerable is suitable for querying data from in-memory collections like List, Array
  4. IEnumerable is beneficial for LINQ to Object and LINQ to XML queries

IQueryable

  1. IQueryable exists in the System.Linq namespace
  2. IQueryable executes a 'select query' on server-side with all filters
  3. IQueryable is suitable for querying data from out-memory (like remote database, service) collections
  4. IQueryable is beneficial for LINQ to SQL queries

So IEnumerable is generally used for dealing with in-memory collection, whereas, IQueryable is generally used to manipulate collections.

Simplest way to restart service on a remote computer

As of Powershell v3, PSsessions allow for any native cmdlet to be run on a remote machine

$session = New-PSsession -Computername "YourServerName"
Invoke-Command -Session $Session -ScriptBlock {Restart-Service "YourServiceName"}
Remove-PSSession $Session

See here for more information

Running MSBuild fails to read SDKToolsPath

ToolsVersion="4.0" does it for me in my MSBuild project:

<Project DefaultTargets="Do" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

Remove credentials from Git

If your credentials are stored in the credential helper (generally the case), the portable way to remove a password persisted for a specific host is to call git credential reject:

  • in one line:

    $ echo "url=https://appharbor.com" | git credential reject
    
  • or interactively:

    $ git credential reject
    protocol=https
    host=gitlab.com
    [email protected]
    ?
    
    • ? is the Enter symbol, just hit Enter key twice at the end of input, don't copy/paste it
    • The username doesn't seem recognized by wincred, so avoid to filter by username on Windows

After that, to enter your new password, type git fetch.

https://git-scm.com/docs/git-credential

Auto highlight text in a textbox control

In ASP.NET:

textbox.Attributes.Add("onfocus","this.select();");

Extracting specific selected columns to new DataFrame as a copy

Generic functional form

def select_columns(data_frame, column_names):
    new_frame = data_frame.loc[:, column_names]
    return new_frame

Specific for your problem above

selected_columns = ['A', 'C', 'D']
new = select_columns(old, selected_columns)

PHP Excel Header

Just try to add exit; at the end of your PHP script.

Eclipse: Set maximum line length for auto formatting?

In preferences Java -> Code Style -> Formatter, edit the profile. Under the Line Wrapping tab is the primary option for line width (Maximum line width:). In the Comments tab you have a separate option Maximum line width for comments:, which will also need to be changed to affect comment wrapping.

You will need to make your own profile to make these changes in if you using one of the [Built-in] ones. Just click "New..." on the formatter preferences page.

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

Delete from two tables in one query

there's another way which is not mentioned here (I didn't fully test it's performance yet), you could set array for all tables -> rows you want to delete as below

// set your tables array
$array = ['table1', 'table2', 'table3'];


// loop through each table
for($i = 0; $i < count($array); $i++){

 // get each single array
 $single_array = $array[$i];

 // build your query
 $query = "DELETE FROM $single_array WHERE id = 'id'";

 // prepare the query and get the connection
 $data = con::GetCon()->prepare($query);

 // execute the action
 $data->execute();
}

then you could redirect the user to the home page.

header('LOCATION:' . $home_page);

hope this will help someone :)

Thanks

Multiline editing in Visual Studio Code

On Windows, you hold Ctrl+Alt while pressing the up ? or down ? arrow keys to add cursors.

Mac: ? Opt+? Cmd+?/?

Linux: Shift+Alt+?/?

Note that third-party software may interfere with these shortcuts, preventing them from working as intended (particularly Intel's HD Graphics software on Windows; see comments for more details).

If you experience this issue, you can either disable the Intel/other software hotkeys, or modify the VS Code shortcuts (described below).

Press Esc to reset to a single cursor.

Multiline cursors in Visual Studio Code

Or, as Isidor Nikolic points out, you can hold Alt and left click to place cursors arbitrarily.

Arbitrarily placed multiline cursors in Visual Studio Code

You can view and edit keyboard shortcuts via:

File ? Preferences ? Keyboard Shortcuts

Documentation:

https://code.visualstudio.com/docs/customization/keybindings

Official VS Code Keyboard shortcut cheat sheets:

https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf
https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf
https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

Finding the handle to a WPF window

you can use :

Process.GetCurrentProcess().MainWindowHandle

How to draw a custom UIView that is just a circle - iPhone app

You could use QuartzCore and do something this --

self.circleView = [[UIView alloc] initWithFrame:CGRectMake(10,20,100,100)];
self.circleView.alpha = 0.5;
self.circleView.layer.cornerRadius = 50;  // half the width/height
self.circleView.backgroundColor = [UIColor blueColor];

What does the "@" symbol do in Powershell?

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is denoted @().

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

You need to do this in transaction to ensure two simultaneous clients won't insert same fieldValue twice:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
    DECLARE @id AS INT
    SELECT @id = tableId FROM table WHERE fieldValue=@newValue
    IF @id IS NULL
    BEGIN
       INSERT INTO table (fieldValue) VALUES (@newValue)
       SELECT @id = SCOPE_IDENTITY()
    END
    SELECT @id
COMMIT TRANSACTION

you can also use Double-checked locking to reduce locking overhead

DECLARE @id AS INT
SELECT @id = tableID FROM table (NOLOCK) WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
    BEGIN TRANSACTION
        SELECT @id = tableID FROM table WHERE fieldValue=@newValue
        IF @id IS NULL
        BEGIN
           INSERT INTO table (fieldValue) VALUES (@newValue)
           SELECT @id = SCOPE_IDENTITY()
        END
    COMMIT TRANSACTION
END
SELECT @id

As for why ISOLATION LEVEL SERIALIZABLE is necessary, when you are inside a serializable transaction, the first SELECT that hits the table creates a range lock covering the place where the record should be, so nobody else can insert the same record until this transaction ends.

Without ISOLATION LEVEL SERIALIZABLE, the default isolation level (READ COMMITTED) would not lock the table at read time, so between SELECT and UPDATE, somebody would still be able to insert. Transactions with READ COMMITTED isolation level do not cause SELECT to lock. Transactions with REPEATABLE READS lock the record (if found) but not the gap.

Regex pattern for checking if a string starts with a certain substring?

The following will match on any string that starts with mailto, ftp or http:

 RegEx reg = new RegEx("^(mailto|ftp|http)");

To break it down:

  • ^ matches start of line
  • (mailto|ftp|http) matches any of the items separated by a |

I would find StartsWith to be more readable in this case.

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

The issue is fixed by adding repository url under distributionManagement tab in main pom.xml.

Jenkin maven goal : clean deploy -U -Dmaven.test.skip=true

<distributionManagement>
    <repository>
        <id>releases</id>
        <url>http://domain:port/content/repositories/releases</url>
    </repository>
    <snapshotRepository>
        <id>snapshots</id>
        <url>http://domain:port/content/repositories/snapshots</url>
    </snapshotRepository>
</distributionManagement>

better way to drop nan rows in pandas

bool_series=pd.notnull(dat["x"])
dat=dat[bool_series]

When is TCP option SO_LINGER (0) required?

For my suggestion, please read the last section: “When to use SO_LINGER with timeout 0”.

Before we come to that a little lecture about:

  • Normal TCP termination
  • TIME_WAIT
  • FIN, ACK and RST

Normal TCP termination

The normal TCP termination sequence looks like this (simplified):

We have two peers: A and B

  1. A calls close()
    • A sends FIN to B
    • A goes into FIN_WAIT_1 state
  2. B receives FIN
    • B sends ACK to A
    • B goes into CLOSE_WAIT state
  3. A receives ACK
    • A goes into FIN_WAIT_2 state
  4. B calls close()
    • B sends FIN to A
    • B goes into LAST_ACK state
  5. A receives FIN
    • A sends ACK to B
    • A goes into TIME_WAIT state
  6. B receives ACK
    • B goes to CLOSED state – i.e. is removed from the socket tables

TIME_WAIT

So the peer that initiates the termination – i.e. calls close() first – will end up in the TIME_WAIT state.

To understand why the TIME_WAIT state is our friend, please read section 2.7 in "UNIX Network Programming" third edition by Stevens et al (page 43).

However, it can be a problem with lots of sockets in TIME_WAIT state on a server as it could eventually prevent new connections from being accepted.

To work around this problem, I have seen many suggesting to set the SO_LINGER socket option with timeout 0 before calling close(). However, this is a bad solution as it causes the TCP connection to be terminated with an error.

Instead, design your application protocol so the connection termination is always initiated from the client side. If the client always knows when it has read all remaining data it can initiate the termination sequence. As an example, a browser knows from the Content-Length HTTP header when it has read all data and can initiate the close. (I know that in HTTP 1.1 it will keep it open for a while for a possible reuse, and then close it.)

If the server needs to close the connection, design the application protocol so the server asks the client to call close().

When to use SO_LINGER with timeout 0

Again, according to "UNIX Network Programming" third edition page 202-203, setting SO_LINGER with timeout 0 prior to calling close() will cause the normal termination sequence not to be initiated.

Instead, the peer setting this option and calling close() will send a RST (connection reset) which indicates an error condition and this is how it will be perceived at the other end. You will typically see errors like "Connection reset by peer".

Therefore, in the normal situation it is a really bad idea to set SO_LINGER with timeout 0 prior to calling close() – from now on called abortive close – in a server application.

However, certain situation warrants doing so anyway:

  • If the a client of your server application misbehaves (times out, returns invalid data, etc.) an abortive close makes sense to avoid being stuck in CLOSE_WAIT or ending up in the TIME_WAIT state.
  • If you must restart your server application which currently has thousands of client connections you might consider setting this socket option to avoid thousands of server sockets in TIME_WAIT (when calling close() from the server end) as this might prevent the server from getting available ports for new client connections after being restarted.
  • On page 202 in the aforementioned book it specifically says: "There are certain circumstances which warrant using this feature to send an abortive close. One example is an RS-232 terminal server, which might hang forever in CLOSE_WAIT trying to deliver data to a stuck terminal port, but would properly reset the stuck port if it got an RST to discard the pending data."

I would recommend this long article which I believe gives a very good answer to your question.

How can I read and manipulate CSV file data in C++?

More information would be useful.

But the simplest form:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream  data("plop.csv");

    std::string line;
    while(std::getline(data,line))
    {
        std::stringstream  lineStream(line);
        std::string        cell;
        while(std::getline(lineStream,cell,','))
        {
            // You have a cell!!!!
        }
    }
 }

Also see this question: CSV parser in C++

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

jQuery - multiple $(document).ready ...?

Both will get called, first come first served. Take a look here.

$(document).ready(function(){
    $("#page-title").html("Document-ready was called!");
  });

$(document).ready(function(){
    $("#page-title").html("Document-ready 2 was called!");
  });

Output:

Document-ready 2 was called!

Firebase TIMESTAMP to date and Time

Here is a safe method to convert a value from firebase Timestamp type to JS Date in case the value is not Timestamp the method returns it as it is

Works for Angular 7/8/9

import firebase from 'firebase';
import Timestamp = firebase.firestore.Timestamp;

export function convertTimestampToDate(timestamp: Timestamp | any): Date | any {
  return timestamp instanceof Timestamp
    ? new Timestamp(timestamp.seconds, timestamp.nanoseconds).toDate()
    : timestamp;
}

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

All the above mentioned solutions to the problem are correct. But if you are using lazy loading, FormsModule needs to be imported in the child module which has forms in it. Adding it in app.module.ts won't help.

How to create a zip file in Java

Here is an example code to compress a Whole Directory(including sub files and sub directories), it's using the walk file tree feature of Java NIO.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
    public static void compress(String dirPath) {
        final Path sourceDir = Paths.get(dirPath);
        String zipFileName = dirPath.concat(".zip");
        try {
            final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
                    try {
                        Path targetFile = sourceDir.relativize(file);
                        outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                        byte[] bytes = Files.readAllBytes(file);
                        outputStream.write(bytes, 0, bytes.length);
                        outputStream.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To use this, just call

ZipCompress.compress("target/directoryToCompress");

and you'll get a zip file directoryToCompress.zip

How do I start an activity from within a Fragment?

I do it like this, to launch the SendFreeTextActivity from a (custom) menu fragment that appears in multiple activities:

In the MenuFragment class:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_menu, container, false);

    final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
    sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "sendFreeTextButton clicked");
            Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
            MenuFragment.this.startActivity(intent);
        }
    });
    ...

IOS - How to segue programmatically using swift

Swift 3 - Also works with SpriteKit

You can use NSNotification.

Example:

1.) Create a segue in the storyboard and name the identifier "segue"

2.) Create a function in the ViewController you are segueing from.

func goToDifferentView() {

    self.performSegue(withIdentifier: "segue", sender: self)

}

3.) In the ViewDidLoad() of your ViewController you are segueing from create the observer.

NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: "segue" as NSNotification.Name, object: nil)

Update - Last time I used this I had to change the .addObserver call to the following code to silence the errors.

NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: NSNotification.Name(rawValue: "segue"), object: nil)

4.) In the ViewController or Scene you are segueing to, add the Post Method wherever you want the segue to be triggered.

NotificationCenter.default.post(name: "segue" as NSNotification.Name, object: nil)

Update - Last time I used this I had to change the .post call to the following code to silence the errors.

NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "segue"), object: nil) as Notification)

How to execute shell command in Javascript

Another post on this topic with a nice jQuery/Ajax/PHP solution:

shell scripting and jQuery

Preloading images with JavaScript

I recommend you use a try/catch to prevent some possible issues:

OOP:

    var preloadImage = function (url) {
        try {
            var _img = new Image();
            _img.src = url;
        } catch (e) { }
    }

Standard:

    function preloadImage (url) {
        try {
            var _img = new Image();
            _img.src = url;
        } catch (e) { }
    }

Also, while I love DOM, old stupid browsers may have problems with you using DOM, so avoid it altogether IMHO contrary to freedev's contribution. Image() has better support in old trash browsers.

Get original URL referer with PHP?

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

Mysql Compare two datetime fields

The query you want to show as an example is:

SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';

04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.

If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.

To make things a bit clearer, try this:

SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;

That will show you the date, and its 12hr time.

How to run the sftp command with a password from Bash script?

Bash program to wait for sftp to ask for a password then send it along:

#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "

You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

How to define optional methods in Swift protocol?

Since there are some answers about how to use optional modifier and @objc attribute to define optional requirement protocol, I will give a sample about how to use protocol extensions define optional protocol.

Below code is Swift 3.*.

/// Protocol has empty default implementation of the following methods making them optional to implement:
/// `cancel()`
protocol Cancelable {

    /// default implementation is empty.
    func cancel()
}

extension Cancelable {

    func cancel() {}
}

class Plane: Cancelable {
  //Since cancel() have default implementation, that is optional to class Plane
}

let plane = Plane()
plane.cancel()
// Print out *United Airlines can't cancelable*

Please notice protocol extension methods can't invoked by Objective-C code, and worse is Swift team won't fix it. https://bugs.swift.org/browse/SR-492

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

You can do it with a separate UPDATE statement

UPDATE report.TEST target
SET    is Deleted = 'Y'
WHERE  NOT EXISTS (SELECT 1
                   FROM   main.TEST source
                   WHERE  source.ID = target.ID);

I don't know of any way to integrate this into your MERGE statement.

How can I debug git/git-shell related problems?

For older git versions (1.8 and before)

I could find no suitable way to enable SSH debugging in an older git and ssh versions. I looked for environment variables using ltrace -e getenv ... and couldn't find any combination of GIT_TRACE or SSH_DEBUG variables that would work.

Instead here's a recipe to temporarily inject 'ssh -v' into the git->ssh sequence:

$ echo '/usr/bin/ssh -v ${@}' >/tmp/ssh
$ chmod +x /tmp/ssh
$ PATH=/tmp:${PATH} git clone ...
$ rm -f /tmp/ssh

Here's output from git version 1.8.3 with ssh version OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013 cloning a github repo:

$ (echo '/usr/bin/ssh -v ${@}' >/tmp/ssh; chmod +x /tmp/ssh; PATH=/tmp:${PATH} \
   GIT_TRACE=1 git clone https://github.com/qneill/cliff.git; \
   rm -f /tmp/ssh) 2>&1 | tee log
trace: built-in: git 'clone' 'https://github.com/qneill/cliff.git'
trace: run_command: 'git-remote-https' 'origin' 'https://github.com/qneill/cliff.git'
Cloning into 'cliff'...
OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /home/q.neill/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to github.com ...
...
Transferred: sent 4120, received 724232 bytes, in 0.2 seconds
Bytes per second: sent 21590.6, received 3795287.2
debug1: Exit status 0
trace: run_command: 'rev-list' '--objects' '--stdin' '--not' '--all'
trace: exec: 'git' 'rev-list' '--objects' '--stdin' '--not' '--all'
trace: built-in: git 'rev-list' '--objects' '--stdin' '--not' '--all'

How can I find the version of the Fedora I use?

cat /etc/*release

It's universal for almost any major distribution.

How to get row count in an Excel file using POI library?

To find last data row, in case you created table template in excel where it is filled partially or in between rows are empty. Logic:

int count = 0;
int emptyrow=0;
int irow=0;
while (rowIterator.hasNext()) {
    row = (Row) rowIterator.next();
    if (count != 0 && !checkIfRowIsEmpty(row)) { }
    else{
        if(count!=0 && emptyrow==irow){
            emptyrow++;
        }else{
            emptyrow=0;
            irow=0;
        }
    }
    if(emptyrow>0){
        irow++;
    }
    if(emptyrow>3){
        break;
    }
    count++;
}

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

Is there such a thing as min-font-size and max-font-size?

I got some smooth results with these. It flows smoothly between the 3 width ranges, like a continuous piecewise function.

@media screen and (min-width: 581px) and (max-width: 1760px){
    #expandingHeader {
        line-height:5.2vw;
        font-size: 5.99vw;
    }
    #tagLine {
        letter-spacing: .15vw;
        font-size: 1.7vw;
        line-height:1.0vw;
    }
}

@media screen and (min-width: 1761px){
    #expandingHeader {
        line-height:.9em;
        font-size: 7.03em;

    }
    #tagLine {
        letter-spacing: .15vw;
        font-size: 1.7vw;
        line-height:1.0vw;
    }
}

@media screen and (max-width: 580px){
    #expandingHeader {
        line-height:.9em;
        font-size: 2.3em;
    }
    #tagLine {
        letter-spacing: .1em;
        font-size: .65em;
        line-height: .10em;
    }
}

Recommended way to get hostname in Java

Strictly speaking - you have no choice but calling either hostname(1) or - on Unix gethostname(2). This is the name of your computer. Any attempt to determine the hostname by an IP address like this

InetAddress.getLocalHost().getHostName()

is bound to fail in some circumstances:

  • The IP address might not resolve into any name. Bad DNS setup, bad system setup or bad provider setup may be the reason for this.
  • A name in DNS can have many aliases called CNAMEs. These can only be resolved in one direction properly: name to address. The reverse direction is ambiguous. Which one is the "official" name?
  • A host can have many different IP addresses - and each address can have many different names. Two common cases are: One ethernet port has several "logical" IP addresses or the computer has several ethernet ports. It is configurable whether they share an IP or have different IPs. This is called "multihomed".
  • One Name in DNS can resolve to several IP Addresses. And not all of those addresses must be located on the same computer! (Usecase: A simple form of load-balancing)
  • Let's not even start talking about dynamic IP addresses.

Also don't confuse the name of an IP-address with the name of the host (hostname). A metaphor might make it clearer:

There is a large city (server) called "London". Inside the city walls much business happens. The city has several gates (IP addresses). Each gate has a name ("North Gate", "River Gate", "Southampton Gate"...) but the name of the gate is not the name of the city. Also you cannot deduce the name of the city by using the name of a gate - "North Gate" would catch half of the bigger cities and not just one city. However - a stranger (IP packet) walks along the river and asks a local: "I have a strange address: 'Rivergate, second left, third house'. Can you help me?" The local says: "Of course, you are on the right road, simply go ahead and you will arrive at your destination within half an hour."

This illustrates it pretty much I think.

The good news is: The real hostname is usually not necessary. In most cases any name which resolves into an IP address on this host will do. (The stranger might enter the city by Northgate, but helpful locals translate the "2nd left" part.)

In the remaining corner cases you must use the definitive source of this configuration setting - which is the C function gethostname(2). That function is also called by the program hostname.

Get record counts for all tables in MySQL database

There's a bit of a hack/workaround to this estimate problem.

Auto_Increment - for some reason this returns a much more accurate row count for your database if you have auto increment set up on tables.

Found this when exploring why show table info did not match up with the actual data.

SELECT
table_schema 'Database',
SUM(data_length + index_length) AS 'DBSize',
SUM(TABLE_ROWS) AS DBRows,
SUM(AUTO_INCREMENT) AS DBAutoIncCount
FROM information_schema.tables
GROUP BY table_schema;


+--------------------+-----------+---------+----------------+
| Database           | DBSize    | DBRows  | DBAutoIncCount |
+--------------------+-----------+---------+----------------+
| Core               |  35241984 |   76057 |           8341 |
| information_schema |    163840 |    NULL |           NULL |
| jspServ            |     49152 |      11 |            856 |
| mysql              |   7069265 |   30023 |              1 |
| net_snmp           |  47415296 |   95123 |            324 |
| performance_schema |         0 | 1395326 |           NULL |
| sys                |     16384 |       6 |           NULL |
| WebCal             |    655360 |    2809 |           NULL |
| WxObs              | 494256128 |  530533 |        3066752 |
+--------------------+-----------+---------+----------------+
9 rows in set (0.40 sec)

You could then easily use PHP or whatever to return the max of the 2 data columns to give the "best estimate" for row count.

i.e.

SELECT
table_schema 'Database',
SUM(data_length + index_length) AS 'DBSize',
GREATEST(SUM(TABLE_ROWS), SUM(AUTO_INCREMENT)) AS DBRows
FROM information_schema.tables
GROUP BY table_schema;

Auto Increment will always be +1 * (table count) rows off, but even with 4,000 tables and 3 million rows, that's 99.9% accurate. Much better than the estimated rows.

The beauty of this is that the row counts returned in performance_schema are erased for you, as well, because greatest does not work on nulls. This may be an issue if you have no tables with auto increment, though.

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

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

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

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How to change port number for apache in WAMP

Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.

Get href attribute on jQuery

Very simply, use this as the context: http://api.jquery.com/jQuery/#selector-context

var a_href = $('div.cpt', this).find('h2 a').attr('href');

Which says, find 'div.cpt' only inside this

Redirecting 404 error with .htaccess via 301 for SEO etc

You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:

ErrorDocument 404 /index.php

An error page redirect must be relative to root so you cannot use www.mydomain.com.

If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.

Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

You can use distinct to remove duplicates

List<Blog> blogList = ....// add your list here

blogList.stream().distinct().collect(Collectors.toList());

What are the differences between JSON and JSONP?

JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){
  alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

How to get a complete list of object's methods and attributes?

Here is a practical addition to the answers of PierreBdR and Moe:

  • For Python >= 2.6 and new-style classes, dir() seems to be enough.
  • For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir(), look for __class__, and then to go for its __bases__:

    # code borrowed from the rlcompleter module
    # tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
    
    # or: from rlcompleter import get_class_members
    def get_class_members(klass):
        ret = dir(klass)
        if hasattr(klass,'__bases__'):
            for base in klass.__bases__:
                ret = ret + get_class_members(base)
        return ret
    
    
    def uniq( seq ): 
        """ the 'set()' way ( use dict when there's no set ) """
        return list(set(seq))
    
    
    def get_object_attrs( obj ):
        # code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
        ret = dir( obj )
        ## if "__builtins__" in ret:
        ##    ret.remove("__builtins__")
    
        if hasattr( obj, '__class__'):
            ret.append('__class__')
            ret.extend( get_class_members(obj.__class__) )
    
            ret = uniq( ret )
    
        return ret
    

(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs() as for dir(), and for old-style classes the main addition to the dir() output seem to be the __class__ attribute.)

Tar error: Unexpected EOF in archive

May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.

$ gunzip myarchive.tar.gz

And then untar the resulting tar file using

$ tar xvf myarchive.tar

Hope this helps.

Install php-mcrypt on CentOS 6

Updated Answer for centos 7

 ## RHEL/CentOS 7 64-Bit ##
 # wget http://dl.fedoraproject.org/pub/epel/beta/7/x86_64/epel-release-7-0.2.noarch.rpm
 # rpm -ivh epel-release-7-0.2.noarch.rpm

For CentOS 6

 ## RHEL/CentOS 6 32-Bit ##
 # wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
 # rpm -ivh epel-release-6-8.noarch.rpm

 ## RHEL/CentOS 6 64-Bit ##
 # wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
 # rpm -ivh epel-release-6-8.noarch.rpm

Install

 yum install php-mcrypt

Edit: See comments for updated repositories.

Django DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

Update ViewPager dynamically?

I use EventBus library to update Fragment content in ViewPager. The logic is simple, just like document of EventBus how to do. It is no need to control FragmentPagerAdapter instance. The code is here:

1: Define events

Define which message which is needed to update.

public class UpdateCountEvent {
    public final int count;

    public UpdateCountEvent(int count) {
        this.count = count;
    }
}

2.Prepare subscribers

Write below code in the Fragment which is needed update.

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);  
    super.onStop();
}

public void onEvent(UpdateCountEvent event) {//get update message
    Toast.makeText(getActivity(), event.count, Toast.LENGTH_SHORT).show();
}

3.Post events

Write below code in other Activity or other Fragment which needs to update parameter

//input update message
EventBus.getDefault().post(new UpdateCountEvent(count));

$date + 1 year?

To add one year to todays date use the following:

$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

For the other examples you must initialize $StartingDate with a timestamp value for example:

$StartingDate = mktime();  // todays date as a timestamp

Try this

$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 365 day"));

or

$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 1 year"));

Validate date in dd/mm/yyyy format using JQuery Validate

This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

console.log(dateRegex.test('21/01/1986'));

enter image description here

http://regexper.com/....

How to redirect to a different domain using NGINX?

server {
    server_name .mydomain.com;
    return 301 http://www.adifferentdomain.com$request_uri;
}

http://wiki.nginx.org/HttpRewriteModule#return

and

http://wiki.nginx.org/Pitfalls#Taxing_Rewrites

How to get the cookie value in asp.net website

add this function to your global.asax

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    if (authCookie == null)
    {
        return;
    }
    FormsAuthenticationTicket authTicket = null;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }
    if (authTicket == null)
    {
        return;
    }
    string[] roles = authTicket.UserData.Split(new char[] { '|' });
    FormsIdentity id = new FormsIdentity(authTicket);
    GenericPrincipal principal = new GenericPrincipal(id, roles);

    Context.User = principal;
}

then you can use HttpContext.Current.User.Identity.Name to get username. hope it helps

SFTP in Python? (platform independent)

You should check out pysftp https://pypi.python.org/pypi/pysftp it depends on paramiko, but wraps most common use cases to just a few lines of code.

import pysftp
import sys

path = './THETARGETDIRECTORY/' + sys.argv[1]    #hard-coded
localpath = sys.argv[1]

host = "THEHOST.com"                    #hard-coded
password = "THEPASSWORD"                #hard-coded
username = "THEUSERNAME"                #hard-coded

with pysftp.Connection(host, username=username, password=password) as sftp:
    sftp.put(localpath, path)

print 'Upload done.'

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

Page scroll when soft keyboard popped up

You can try using the following code to solve your problem:

 <activity
     android:name=".DonateNow"
     android:label="@string/title_activity_donate_now"
     android:screenOrientation="portrait"
     android:theme="@style/AppTheme"
     android:windowSoftInputMode="stateVisible|adjustPan">
 </activity>

Selecting empty text input using jQuery

You could also do it by defining your own selector:

$.extend($.expr[':'],{
    textboxEmpty: function(el){
        return $(el).val() === "";
    }
});

And then access them like this:

alert($(':text:textboxEmpty').length); //alerts the number of text boxes in your selection

How to read and write excel file

If you go for third party library option, try using Aspose.Cells API that enables Java Applications to create (read/write) and manage Excel spreadsheets efficiently without requiring Microsoft Excel.

e.g

Sample code:

1.

//Load sample workbook
Workbook wb = new Workbook(dirPath + "sample.xlsx");

//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);

//Access cells iterator
Iterator itrat = ws.getCells().iterator();

//Print cells name in iterator
while(itrat.hasNext())
{
    Cell cell = (Cell)itrat.next();

    System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
}
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
//your code goes here.
}

Hope, this helps a bit.

PS. I am working as Support developer/ Evangelist at Aspose.

UIView Infinite 360 degree rotation animation?

Kudos to Richard J. Ross III for the idea, but I found that his code wasn't quite what I needed. The default for options, I believe, is to give you UIViewAnimationOptionCurveEaseInOut, which doesn't look right in a continuous animation. Also, I added a check so that I could stop my animation at an even quarter turn if I needed (not infinite, but of indefinite duration), and made the acceleration ramp up during the first 90 degrees, and decelerate during the last 90 degrees (after a stop has been requested):

// an ivar for your class:
BOOL animating;

- (void)spinWithOptions:(UIViewAnimationOptions)options {
   // this spin completes 360 degrees every 2 seconds
   [UIView animateWithDuration:0.5
                         delay:0
                       options:options
                    animations:^{
                       self.imageToMove.transform = CGAffineTransformRotate(imageToMove.transform, M_PI / 2);
                    }
                    completion:^(BOOL finished) {
                       if (finished) {
                          if (animating) {
                             // if flag still set, keep spinning with constant speed
                             [self spinWithOptions: UIViewAnimationOptionCurveLinear];
                          } else if (options != UIViewAnimationOptionCurveEaseOut) {
                             // one last spin, with deceleration
                             [self spinWithOptions: UIViewAnimationOptionCurveEaseOut];
                          }
                       }
                    }];
}

- (void)startSpin {
   if (!animating) {
      animating = YES;
      [self spinWithOptions: UIViewAnimationOptionCurveEaseIn];
   }
}

- (void)stopSpin {
    // set the flag to stop spinning after one last 90 degree increment
    animating = NO;
}

Update

I added the ability to handle requests to start spinning again (startSpin), while the previous spin is winding down (completing). Sample project here on Github.

PHP multidimensional array search by value

/**
 * searches a simple as well as multi dimension array
 * @param type $needle
 * @param type $haystack
 * @return boolean
 */
public static function in_array_multi($needle, $haystack){
    $needle = trim($needle);
    if(!is_array($haystack))
        return False;

    foreach($haystack as $key=>$value){
        if(is_array($value)){
            if(self::in_array_multi($needle, $value))
                return True;
            else
               self::in_array_multi($needle, $value);
        }
        else
        if(trim($value) === trim($needle)){//visibility fix//
            error_log("$value === $needle setting visibility to 1 hidden");
            return True;
        }
    }

    return False;
}

Difference between hamiltonian path and euler path

Graph Theory Definitions

(In descending order of generality)

  • Walk: a sequence of edges where the end of one edge marks the beginning of the next edge

  • Trail: a walk which does not repeat any edges. All trails are walks.

  • Path: a walk where each vertex is traversed at most once. (paths used to refer to open walks, the definition has changed now) The property of traversing vertices at most once means that edges are also crossed at most once, hence all paths are trails.

Hamiltonian paths & Eulerian trails

  • Hamiltonian path: visits every vertex in the graph (exactly once, because it is a path)

  • Eulerian trail: visits every edge in the graph exactly once (because it is a trail, vertices may well be crossed more than once.)

How to open html file?

You can read HTML page using 'urllib'.

 #python 2.x

  import urllib

  page = urllib.urlopen("your path ").read()
  print page

PHP - include a php file and also send query parameters

Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :

if(condition){
    $someVar=someValue;
    include "myFile.php";
}

As long as the variable is named $someVar in the myFile.php

Which equals operator (== vs ===) should be used in JavaScript comparisons?

The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...

Date minus 1 year?

Use strtotime() function:

  $time = strtotime("-1 year", time());
  $date = date("Y-m-d", $time);

Java JTextField with input hint

Here is a fully working example based on Adam Gawne-Cain's earlier Posting. His solution is simple and actually works exceptionally well.

I've used the following text in a Grid of multiple Fields:

H__|__WWW__+__XXXX__+__WWW__|__H

this makes it possible to easily verify the x/y alignment of the hinted text.

A couple of observations:
- there are any number of solutions out there, but many only work superficially and/or are buggy
- sun.tools.jconsole.ThreadTab.PromptingTextField is a simple solution, but it only shows the prompting text when the Field doesn't have the focus & it's private, but nothing a little cut-and-paste won't fix.

The following works on JDK 8 and upwards:

import java.awt.*;
import java.util.stream.*;
import javax.swing.*;
/**
 * @author DaveTheDane, based on a suggestion from Adam Gawne-Cain
 */
public final class JTextFieldPromptExample extends JFrame {

    private static JTextField newPromptedJTextField (final String text, final String prompt) {

        final String promptPossiblyNullButNeverWhitespace = prompt == null || prompt.trim().isEmpty()  ?  null  :  prompt;

        return new JTextField(text) {
            @Override
            public void paintComponent(final Graphics    USE_g2d_INSTEAD) {
                final Graphics2D     g2d =  (Graphics2D) USE_g2d_INSTEAD;

                super.paintComponent(g2d);

//              System.out.println("Paint.: " + g2d);

                if (getText().isEmpty()
                &&  promptPossiblyNullButNeverWhitespace != null) {
                    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                    final Insets      ins = getInsets();
                    final FontMetrics fm  = g2d.getFontMetrics();

                    final int cB = getBackground().getRGB();
                    final int cF = getForeground().getRGB();
                    final int m  = 0xfefefefe;
                    final int c2 = ((cB & m) >>> 1) + ((cF & m) >>> 1); // "for X in (A, R, G, B) {Xnew = (Xb + Xf) / 2}"
                    /*
                     * The hint text color should be halfway between the foreground and background colors so it is always gently visible.
                     * The variables c0,c1,m,c2 calculate the halfway color's ARGB fields simultaneously without overflowing 8 bits.
                     * Swing sets the Graphics' font to match the JTextField's font property before calling the "paint" method,
                     * so the hint font will match the JTextField's font.
                     * Don't think there are any side effects because Swing discards the Graphics after painting.
                     * Adam Gawne-Cain, Aug 6 2019 at 15:55
                     */
                    g2d.setColor(new Color(c2, true));
                    g2d.drawString(promptPossiblyNullButNeverWhitespace, ins.left, getHeight() - fm.getDescent() - ins.bottom);
                    /*
                     * y Coordinate based on Descent & Bottom-inset seems to align Text spot-on.
                     * DaveTheDane, Apr 10 2020
                     */
                }
            }
        };
    }

    private static final GridBagConstraints GBC_LEFT  = new GridBagConstraints();
    private static final GridBagConstraints GBC_RIGHT = new GridBagConstraints();
    /**/    static {
        GBC_LEFT .anchor    = GridBagConstraints.LINE_START;
        GBC_LEFT .fill      = GridBagConstraints.HORIZONTAL;
        GBC_LEFT .insets    = new Insets(8, 8, 0, 0);

        GBC_RIGHT.gridwidth = GridBagConstraints.REMAINDER;
        GBC_RIGHT.fill      = GridBagConstraints.HORIZONTAL;
        GBC_RIGHT.insets    = new Insets(8, 8, 0, 8);
    }

    private <C extends Component> C addLeft (final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_LEFT);
        return                  component;
    }
    private <C extends Component> C addRight(final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_RIGHT);
        return                  component;
    }

    private static final String ALIGN = "H__|__WWW__+__XXXX__+__WWW__|__H";

    private final GridBagLayout gbl = new GridBagLayout();

    public JTextFieldPromptExample(final String title) {
        super(title);
        this.setLayout(gbl);

        final java.util.List<JTextField> texts = Stream.of(
                addLeft (newPromptedJTextField(ALIGN + ' ' + "Top-Left"    , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Top-Right"   , ALIGN)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Middle-Left" , ALIGN)),
                addRight(newPromptedJTextField(                       null , ALIGN)),

                addLeft (new        JTextField("x"        )),
                addRight(newPromptedJTextField("x",   ""  )),

                addLeft (new        JTextField(null       )),
                addRight(newPromptedJTextField(null,  null)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Bottom-Left" , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Bottom-Right", ALIGN)) ).collect(Collectors.toList());

        final JButton button = addRight(new JButton("Get texts"));
        /**/                   addRight(Box.createVerticalStrut(0)); // 1 last time forces bottom inset

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(740, 260));
        this.pack();
        this.setResizable(false);
        this.setVisible(true);

        button.addActionListener(e -> {
            texts.forEach(text -> System.out.println("Text..: " + text.getText()));
        });
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> new JTextFieldPromptExample("JTextField with Prompt"));
    }
}

How do you stop tracking a remote branch in Git?

This is not an answer to the question, but I couldn't figure out how to get decent code formatting in a comment above... so auto-down-reputation-be-damned here's my comment.

I have the recipe submtted by @Dobes in a fancy shmancy [alias] entry in my .gitconfig:

# to untrack a local branch when I can't remember 'git config --unset'
cbr = "!f(){ git symbolic-ref -q HEAD 2>/dev/null | sed -e 's|refs/heads/||'; }; f"
bruntrack = "!f(){ br=${1:-`git cbr`};  \
    rm=`git config --get branch.$br.remote`; \
    tr=`git config --get branch.$br.merge`; \
    [ $rm:$tr = : ] && echo \"# untrack: not a tracking branch: $br\" && return 1; \
    git config --unset branch.$br.remote; git config --unset branch.$br.merge; \
    echo \"# untrack: branch $br no longer tracking $rm:$tr\"; return 0; }; f"

Then I can just run

$ git bruntrack branchname

jQuery ajax request with json response, how to?

Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode method. Try this.

PHP change

$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string

JS (Change the dataType from json to html or just don't set it jQuery will figure it out)

$.ajax({
   type: "POST", 
   dataType: "html", 
   url: "main.php", 
   data: "action=loadall&id=" + id,
   success: function(response){
      $('#main').html(response);
   }
});

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

"replace" function examples

Be aware that the third parameter (value) in the examples given above: the value is a constant (e.g. 'Z' or c(20,30)).

Defining the third parameter using values from the data frame itself can lead to confusion.

E.g. with a simple data frame such as this (using dplyr::data_frame):

tmp <- data_frame(a=1:10, b=sample(LETTERS[24:26], 10, replace=T))

This will create somthing like this:

       a     b
   (int) (chr)
1      1     X
2      2     Y
3      3     Y
4      4     X
5      5     Z

..etc

Now suppose you want wanted to do, was to multiply the values in column 'a' by 2, but only where column 'b' is "X". My immediate thought would be something like this:

with(tmp, replace(a, b=="X", a*2))

That will not provide the desired outcome, however. The a*2 will defined as a fixed vector rather than a reference to the 'a' column. The vector 'a*2' will thus be

[1]  2  4  6  8 10 12 14 16 18 20

at the start of the 'replace' operation. Thus, the first row where 'b' equals "X", the value in 'a' will be placed by 2. The second time, it will be replaced by 4, etc ... it will not be replaced by two-times-the-value-of-a in that particular row.

Getter and Setter declaration in .NET

The first one is the "short" form - you use it, when you do not want to do something fancy with your getters and setters. It is not possible to execute a method or something like that in this form.

The second and third form are almost identical, albeit the second one is compressed to one line. This form is discouraged by stylecop because it looks somewhat weird and does not conform to C' Stylguides.

I would use the third form if I expectd to use my getters / setters for something special, e.g. use a lazy construct or so.

Token Authentication vs. Cookies

For Googlers:

  • DO NOT mix statefulness with state transfer mechanisms

STATEFULNESS

  • Stateful = save authorization info on server side, this is the traditional way
  • Stateless = save authorization info on client side, along with a signature to ensure integrity

MECHANISMS

  • Cookie = a special header with special treatment (access, storage, expiration, security, auto-transfer) by browsers
  • Custom Headers = e.g. Authorization, are just headers without any special treatment, client has to manage all aspects of the transfer
  • Other. Other transfer mechanisms may be utilized, e.g. query string was a choice to transfer auth ID for a while but was abandoned for its insecurity

STATEFULNESS COMPARISON

  • "Stateful authorization" means the server stores and maintains user authorization info on server, making authorizations part of the application state
  • This means client only need to keep an "auth ID" and the server can read auth detail from its database
  • This implies that server keeps a pool of active auths (users that are logged in) and will query this info for every request
  • "Stateless authorization" means the server does not store and maintain user auth info, it simply does not know which users are signed in, and rely on the client to produce auth info
  • Client will store complete auth info like who you are (user ID), and possibly permissions, expiration time, etc., this is more than just auth ID, so it is given a new name token
  • Obviously client cannot be trusted, so auth data is stored along with a signature generated from hash(data + secret key), where secret key is only known to server, so the integrity of token data can be verified
  • Note that token mechanism merely ensures integrity, but not confidentiality, client has to implement that
  • This also means for every request client has to submit a complete token, which incurs extra bandwidth

MECHANISM COMPARISON

  • "Cookie" is just a header, but with some preloaded operations on browsers
  • Cookie can be set by server and auto-saved by client, and will auto-send for same domain
  • Cookie can be marked as httpOnly thus prevent client JavaScript access
  • Preloaded operations may not be available on platforms other than browsers (e.g. mobile), which may lead to extra efforts
  • "Custom headers" are just custom headers without preloaded operations
  • Client is responsible to receive, store, secure, submit and update the custom header section for each requests, this may help prevent some simple malicious URL embedding

SUM-UP

  • There is no magic, auth state has to be stored somewhere, either at server or client
  • You may implement stateful/stateless with either cookie or other custom headers
  • When people talk about those things their default mindset is mostly: stateless = token + custom header, stateful = auth ID + cookie; these are NOT the only possible options
  • They have pros and cons, but even for encrypted tokens you should not store sensitive info

Link

How to initialize log4j properly?

This is an alternative way using .yaml

Logic Structure:

Configuration:
    Properties:
    Appenders:
    Loggers:

Sample:

Configutation:
    name: Default

    Properties:
        Property:
            name: log-path
            value: "logs"

    Appenders:

        Console:
        name: Console_Appender
        target: SYSTEM_OUT
        PatternLayout:
            pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

       File:
          name: File_Appender
          fileName: ${log-path}/logfile.log
          PatternLayout:
            pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

    Loggers:

        Root:
            level: debug
            AppenderRef:
              - ref: Console_Appender

        Logger:
            - name: <package>.<subpackage>.<subsubpackage>.<...>
              level: debug
              AppenderRef:
                 - ref: File_Appender
                 level: error             

Ref: LOG4J 2 CONFIGURATION: USING YAML

Why is NULL undeclared?

NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

MySQL: How to add one day to datetime field in query

Have a go with this, as this is how I would do it :)

SELECT * 
FROM fab_scheduler
WHERE custid = '123456'
AND CURDATE() = DATE(DATE_ADD(eventdate, INTERVAL 1 DAY))

Navigation Controller Push View Controller

UIViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboardId"];
[self.navigationController pushViewController:vc animated:YES];

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

I had the same problem. I tried all of the answers above (and some from other websites). In the end, my issue was that my cache wasn't configured. I found that info in my error log and fixed it by changing the line in the file:

C:\MAMP\bin\apache\conf\extra\http-ssl.conf

There I removed the double quotes from the line:

SSLSessionCache "shmcb:/some/example/path/ssl_scache(512000)"

to:

SSLSessionCache shmcb:/some/example/path/ssl_scache(512000)

and saved with Ctrl+S and closed the file.

Here's the link that helped me: https://wiki.apache.org/httpd/SSLSessionCache

Binding Combobox Using Dictionary as the Datasource

SortedDictionary<string, int> userCache = new SortedDictionary<string, int>
{
  {"a", 1},
  {"b", 2},
  {"c", 3}
};
comboBox1.DataSource = new BindingSource(userCache, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";

But why are you setting the ValueMember to "Value", shouldn't it be bound to "Key" (and DisplayMember to "Value" as well)?

How is __eq__ handled in Python and in what order?

I'm writing an updated answer for Python 3 to this question.

How is __eq__ handled in Python and in what order?

a == b

It is generally understood, but not always the case, that a == b invokes a.__eq__(b), or type(a).__eq__(a, b).

Explicitly, the order of evaluation is:

  1. if b's type is a strict subclass (not the same type) of a's type and has an __eq__, call it and return the value if the comparison is implemented,
  2. else, if a has __eq__, call it and return it if the comparison is implemented,
  3. else, see if we didn't call b's __eq__ and it has it, then call and return it if the comparison is implemented,
  4. else, finally, do the comparison for identity, the same comparison as is.

We know if a comparison isn't implemented if the method returns NotImplemented.

(In Python 2, there was a __cmp__ method that was looked for, but it was deprecated and removed in Python 3.)

Let's test the first check's behavior for ourselves by letting B subclass A, which shows that the accepted answer is wrong on this count:

class A:
    value = 3
    def __eq__(self, other):
        print('A __eq__ called')
        return self.value == other.value

class B(A):
    value = 4
    def __eq__(self, other):
        print('B __eq__ called')
        return self.value == other.value

a, b = A(), B()
a == b

which only prints B __eq__ called before returning False.

How do we know this full algorithm?

The other answers here seem incomplete and out of date, so I'm going to update the information and show you how how you could look this up for yourself.

This is handled at the C level.

We need to look at two different bits of code here - the default __eq__ for objects of class object, and the code that looks up and calls the __eq__ method regardless of whether it uses the default __eq__ or a custom one.

Default __eq__

Looking __eq__ up in the relevant C api docs shows us that __eq__ is handled by tp_richcompare - which in the "object" type definition in cpython/Objects/typeobject.c is defined in object_richcompare for case Py_EQ:.

    case Py_EQ:
        /* Return NotImplemented instead of False, so if two
           objects are compared, both get a chance at the
           comparison.  See issue #1393. */
        res = (self == other) ? Py_True : Py_NotImplemented;
        Py_INCREF(res);
        break;

So here, if self == other we return True, else we return the NotImplemented object. This is the default behavior for any subclass of object that does not implement its own __eq__ method.

How __eq__ gets called

Then we find the C API docs, the PyObject_RichCompare function, which calls do_richcompare.

Then we see that the tp_richcompare function, created for the "object" C definition is called by do_richcompare, so let's look at that a little more closely.

The first check in this function is for the conditions the objects being compared:

  • are not the same type, but
  • the second's type is a subclass of the first's type, and
  • the second's type has an __eq__ method,

then call the other's method with the arguments swapped, returning the value if implemented. If that method isn't implemented, we continue...

    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        checked_reverse_op = 1;
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Next we see if we can lookup the __eq__ method from the first type and call it. As long as the result is not NotImplemented, that is, it is implemented, we return it.

    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
        res = (*f)(v, w, op);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Else if we didn't try the other type's method and it's there, we then try it, and if the comparison is implemented, we return it.

    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);
    }

Finally, we get a fallback in case it isn't implemented for either one's type.

The fallback checks for the identity of the object, that is, whether it is the same object at the same place in memory - this is the same check as for self is other:

    /* If neither object implements it, provide a sensible default
       for == and !=, but raise an exception for ordering. */
    switch (op) {
    case Py_EQ:
        res = (v == w) ? Py_True : Py_False;
        break;

Conclusion

In a comparison, we respect the subclass implementation of comparison first.

Then we attempt the comparison with the first object's implementation, then with the second's if it wasn't called.

Finally we use a test for identity for comparison for equality.

What is the most efficient way to create HTML elements using jQuery?

I think you're using the best method, though you could optimize it to:

 $("<div/>");

HTML tag <a> want to add both href and onclick working

No jQuery needed.

Some people say using onclick is bad practice...

This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.

<a id="myButton" href="http://google.com">Click me!</a>
<script>
    window.addEventListener("load", () => {
        document.querySelector("#myButton").addEventListener("click", e => {
            alert("Clicked!");
            // Can also cancel the event and manually navigate
            // e.preventDefault();
            // window.location = e.target.href;
        });
    });
</script>

I'm getting Key error in python

For dict, just use

if key in dict

and don't use searching in key list

if key in dict.keys()

The latter will be more time-consuming.

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Both are the same thing but many of the databases are not providing the varying char mainly postgreSQL is providing. So for the multi database like Oracle Postgre and DB2 it is good to use the Varchar

Can you explain the HttpURLConnection connection process?

Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().

http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection

How can I create directories recursively?

os.makedirs is what you need. For chmod or chown you'll have to use os.walk and use it on every file/dir yourself.

jquery $.each() for objects

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

Can you run GUI applications in a Docker container?

You can simply install a vncserver along with Firefox :)

I pushed an image, vnc/firefox, here: docker pull creack/firefox-vnc

The image has been made with this Dockerfile:

# Firefox over VNC
#
# VERSION               0.1
# DOCKER-VERSION        0.2

FROM    ubuntu:12.04
# Make sure the package repository is up to date
RUN     echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list
RUN     apt-get update

# Install vnc, xvfb in order to create a 'fake' display and firefox
RUN     apt-get install -y x11vnc xvfb firefox
RUN     mkdir ~/.vnc
# Setup a password
RUN     x11vnc -storepasswd 1234 ~/.vnc/passwd
# Autostart firefox (might not be the best way to do it, but it does the trick)
RUN     bash -c 'echo "firefox" >> /.bashrc'

This will create a Docker container running VNC with the password 1234:

For Docker version 18 or newer:

docker run -p 5900:5900 -e HOME=/ creack/firefox-vnc x11vnc -forever -usepw -create

For Docker version 1.3 or newer:

docker run -p 5900 -e HOME=/ creack/firefox-vnc x11vnc -forever -usepw -create

For Docker before version 1.3:

docker run -p 5900 creack/firefox-vnc x11vnc -forever -usepw -create

Select datatype of the field in postgres

If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:

select column_name,
case 
    when domain_name is not null then domain_name
    when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
    when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
    else data_type
end as myType
from information_schema.columns
where table_name='test'

with result:

column_name |     myType
-------------+-------------------
 test_id     | test_domain
 test_vc     | varchar(15)
 test_n      | numeric(15,3)
 big_n       | bigint
 ip_addr     | inet

join list of lists in python

I had a similar problem when I had to create a dictionary that contained the elements of an array and their count. The answer is relevant because, I flatten a list of lists, get the elements I need and then do a group and count. I used Python's map function to produce a tuple of element and it's count and groupby over the array. Note that the groupby takes the array element itself as the keyfunc. As a relatively new Python coder, I find it to me more easier to comprehend, while being Pythonic as well.

Before I discuss the code, here is a sample of data I had to flatten first:

{ "_id" : ObjectId("4fe3a90783157d765d000011"), "status" : [ "opencalais" ],
  "content_length" : 688, "open_calais_extract" : { "entities" : [
  {"type" :"Person","name" : "Iman Samdura","rel_score" : 0.223 }, 
  {"type" : "Company",  "name" : "Associated Press",    "rel_score" : 0.321 },          
  {"type" : "Country",  "name" : "Indonesia",   "rel_score" : 0.321 }, ... ]},
  "title" : "Indonesia Police Arrest Bali Bomb Planner", "time" : "06:42  ET",         
  "filename" : "021121bn.01", "month" : "November", "utctime" : 1037836800,
  "date" : "November 21, 2002", "news_type" : "bn", "day" : "21" }

It is a query result from Mongo. The code below flattens a collection of such lists.

def flatten_list(items):
  return sorted([entity['name'] for entity in [entities for sublist in  
   [item['open_calais_extract']['entities'] for item in items] 
   for entities in sublist])

First, I would extract all the "entities" collection, and then for each entities collection, iterate over the dictionary and extract the name attribute.

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

At the moment, this can be done as follows

$ANDROID_HOME/build-tools/28.0.3/aapt dump badging /<path to>/<app name>.apk

In General, it will be:

$ANDROID_HOME/build-tools/<version_of_build_tools>/aapt dump badging /<path to>/<app name>.apk

Convert a date format in epoch

You can also use the new Java 8 API

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class StackoverflowTest{
    public static void main(String args[]){
        String strDate = "Jun 13 2003 23:11:52.454 UTC";
        DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
        ZonedDateTime     zdt  = ZonedDateTime.parse(strDate,dtf);        
        System.out.println(zdt.toInstant().toEpochMilli());  // 1055545912454  
    }
}

The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.

The main advantage is that you are now thread safe.

Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Isnull() syntax is built in for this kind of thing.

declare @Int int = null;

declare @Values table ( id int, def varchar(8) )

insert into @Values values (8, 'I am 8');

-- fails
select *
from @Values
where id = @Int

-- works fine
select *
from @Values
where id = isnull(@Int, 8);

For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.

declare @Int int = null;

declare @Values table ( id int, def varchar(16) )

insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');

select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Google Chrome form autofill and its yellow background

I fixed this issue for a password field i have like this:

Set the input type to text instead of password

Remove the input text value with jQuery

Convert the input type to password with jQuery

<input type="text" class="remove-autofill">

$('.js-remove-autofill').val('');    
$('.js-remove-autofill').attr('type', 'password');

C programming in Visual Studio

Yes it is, none of the Visual Stdio editions have C mentioned, but it is included with the C++ compiler (you therefore need to look under C++). The main difference between using C and C++ is the naming system (i.e. using .c and not .cpp).

You do have to be careful not to create a C++ project and rename it to C though, that does not work.

Coding C from the command line:

Much like you can use gcc on Linux (or if you have MinGW installed) Visual Studio has a command to be used from command prompt (it must be the Visual Studio Developer Command Prompt though). As mentioned in the other answer you can use cl to compile your c file (make sure it is named .c)

Example:

cl myfile.c

Or to check all the accepted commands:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27030.1 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>

Coding C from the IDE:

Without doubt one of the best features of Visual Studio is the convenient IDE.

Although it takes more configuring, you get bonuses such as basic debugging before compiling (for example if you forget a ;)

To create a C project do the following:

Start a new project, go under C++ and select Empty Project, enter the Name of your project and the Location you want it to install to, then click Ok. Now wait for the project to be created.

enter image description here

Next under Solutions Explorer right click Source Files, select Add then New Item. You should see something like this:

enter image description here

Rename Source.cpp to include a .c extension (Source.c for example). Select the location you want to keep it in, I would recommend always keeping it within the project folder itself (in this case C:\Users\Simon\Desktop\Learn\My First C Code)

It should open up the .c file, ready to be modified. Visual Studio can now be used as normal, happy coding!

How to display a Yes/No dialog box on Android?

Steves answer is correct though outdated with fragments. Here is an example with FragmentDialog.

The class:

public class SomeDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
            .setTitle("Title")
            .setMessage("Sure you wanna do this!")
            .setNegativeButton(android.R.string.no, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do nothing (will close dialog)
                }
            })
            .setPositiveButton(android.R.string.yes,  new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do something
                }
            })
            .create();
    }
}

To start dialog:

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            // Create and show the dialog.
            SomeDialog newFragment = new SomeDialog ();
            newFragment.show(ft, "dialog");

You could also let the class implement onClickListener and use that instead of embedded listeners.

How to start mongodb shell?

You need to find the bin folder and then open a command prompt on that folder Then just type mongo.exe and press enter to start the shell

Or you can supply the full path to mongo.exe from any folder to start the shell:

c:\MongoDB\bin\mongo.exe

Then if you have multiple databases, you can do enter command >use <database_name> to use that db

Let me know if it helps or have issues

Verify if file exists or not in C#

You could use:

System.IO.File.Exists(@"c:\temp\test.txt");

Adding options to a <select> using jQuery?

This is very simple:

$('#select_id').append('<option value="five" selected="selected">Five</option>');

or

$('#select_id').append($('<option>', {
                    value: 1,
                    text: 'One'
                }));

How can I check which version of Angular I'm using?

You could also check your package.json:

"dependencies": {
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
  }

(The caret ^ will update you to the most recent major version (the first number). ^4.3.0 will match any 4.x.x release including 4.4.0, but will hold off on 5.0.0. The tilde ~ matches the most recent minor version (the middle number). ~4.3.0 will match all 4.3.x versions, but will miss 4.4.0.)

Getting a list item by index

list1[0];

Assuming list's type has an indexer defined.

Android - Start service on boot

Well here is a complete example of an AutoStart Application

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pack.saltriver" android:versionCode="1" android:versionName="1.0">

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <receiver android:name=".autostart">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity android:name=".hello"></activity>
        <service android:enabled="true" android:name=".service" />
    </application>
</manifest>

autostart.java

public class autostart extends BroadcastReceiver 
{
    public void onReceive(Context context, Intent arg1) 
    {
        Intent intent = new Intent(context,service.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
        Log.i("Autostart", "started");
    }
}

service.java

public class service extends Service
{
    private static final String TAG = "MyService";
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onStart(Intent intent, int startid)
    {
        Intent intents = new Intent(getBaseContext(),hello.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
}

hello.java - This will pop-up everytime you start the device after executing the Applicaton once.

public class hello extends Activity 
{   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
    }
}

Why does the 260 character path length limit exist in Windows?

Another way to cope with it is to use Cygwin, depending on what do you want to do with the files (i.e. if Cygwin commands suit your needs)

For example it allows to copy, move or rename files that even Windows Explorer can't. Or of course deal with the contents of them like md5sum, grep, gzip, etc.

Also for programs that you are coding, you could link them to the Cygwin DLL and it would enable them to use long paths (I haven't tested this though)

In nodeJs is there a way to loop through an array without using array size?

To print 'item1' , 'item2', this code would work.

var myarray = ['hello', ' hello again'];

for (var item in myarray) {
    console.log(myarray[item])
}

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

select right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ + right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ + right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

Escape string Python for MySQL

Use sqlalchemy's text function to remove the interpretation of special characters:

Note the use of the function text("your_insert_statement") below. What it does is communicate to sqlalchemy that all of the questionmarks and percent signs in the passed in string should be considered as literals.

import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re

engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
     % ("your_username", "your_password", "your_hostname_mysql_server:3306",
     "your_database"),
     pool_size=3, pool_recycle=3600)

conn = engine.connect()

myfile = open('access2.log', 'r')
lines = myfile.readlines()

penguins = []
for line in lines:
   elements = re.split('\s+', line)

   print "item: " +  elements[0]
   linedate = datetime.fromtimestamp(float(elements[0]))
   mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")

   penguins.append(text(
     "insert into your_table (foobar) values('%%%????')"))

for penguin in penguins:
    print penguin
    conn.execute(penguin)

conn.close()

What is use of c_str function In c++

It's used to make std::string interoperable with C code that requires a null terminated char*.

List of Java processes

ps axuwww | grep java | grep -v grep

The above will

  • show you all processes with long lines (arg: www)
  • filter (grep) only lines what contain the word java, and
  • filter out the line "grep java" :)

(btw, this example is not the effective one, but simple to remember) ;)

you can pipe the above to another commands, for example:

ps axuwww | grep java | grep -v grep | sed '.....'  | while read something
do
    something_another $something
done

etc...

Defining a `required` field in Bootstrap

To make a field required, use required or required="true"

I think required="required" has been deprecated in version 3 of bootstrap.

How to cast List<Object> to List<MyClass>

With Java 8 Streams:

Sometimes brute force casting is fine:

List<MyClass> mythings = (List<MyClass>) (Object) objects

But here's a more versatile solution:

List<Object> objects = Arrays.asList("String1", "String2");

List<String> strings = objects.stream()
                       .map(element->(String) element)
                       .collect(Collectors.toList());

There's a ton of benefits, but one is that you can cast your list more elegantly if you can't be sure what it contains:

objects.stream()
    .filter(element->element instanceof String)
    .map(element->(String)element)
    .collect(Collectors.toList());

How to silence output in a Bash script?

If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :

--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT  CONNECT ON DATABASE nova  TO user;

--ACCESS SCHEMA
REVOKE ALL     ON SCHEMA public FROM PUBLIC;
GRANT  USAGE   ON SCHEMA public  TO user;

--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

Where to find the win32api module for Python?

I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.

UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs

pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

This was the fix for me when trying to install Laravel on a fresh WSL installation:

sudo apt-get install php7.2-gd

sudo apt-get install php7.2-intl

sudo apt-get install php7.2-xsl

sudo apt-get install php7.2-zip

Javascript ajax call on page onload

Or with Prototype:

Event.observe(this, 'load', function() { new Ajax.Request(... ) );

Or better, define the function elsewhere rather than inline, then:

Event.observe(this, 'load', functionName );

You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();").

However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.

Postgres DB Size Command

You can use below query to find the size of all databases of PostgreSQL.

Reference is taken from this blog.

SELECT 
    datname AS DatabaseName
    ,pg_catalog.pg_get_userbyid(datdba) AS OwnerName
    ,CASE 
        WHEN pg_catalog.has_database_privilege(datname, 'CONNECT')
        THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(datname))
        ELSE 'No Access For You'
    END AS DatabaseSize
FROM pg_catalog.pg_database
ORDER BY 
    CASE 
        WHEN pg_catalog.has_database_privilege(datname, 'CONNECT')
        THEN pg_catalog.pg_database_size(datname)
        ELSE NULL
    END DESC;

Write a file on iOS

May be this is useful to you.

//Method writes a string to a text file
-(void) writeToTextFile{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSUTF8StringEncoding 
                                      error:nil];

}


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];

}

Calculate last day of month in JavaScript

Try this:

function _getEndOfMonth(time_stamp) {
    let time = new Date(time_stamp * 1000);
    let month = time.getMonth() + 1;
    let year = time.getFullYear();
    let day = time.getDate();
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day = 30;
            break;
        case 2:
            if (_leapyear(year))
                day = 29;
            else
                day = 28;
            break
    }
    let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')
    return m.unix() + constants.DAY - 1;
}

function _leapyear(year) {
    return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

@JoinColumn could be used on both sides of the relationship. The question was about using @JoinColumn on the @OneToMany side (rare case). And the point here is in physical information duplication (column name) along with not optimized SQL query that will produce some additional UPDATE statements.

According to documentation:

Since many to one are (almost) always the owner side of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)

@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk")
    public Troop getTroop() {
    ...
} 

Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side.

To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy element and set the many to one @JoinColumn as insertable and updatable to false. This solution is not optimized and will produce some additional UPDATE statements.

@Entity
public class Troop {
    @OneToMany
    @JoinColumn(name="troop_fk") //we need to duplicate the physical information
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk", insertable=false, updatable=false)
    public Troop getTroop() {
    ...
}

Handling a timeout error in python sockets

When you do from socket import * python is loading a socket module to the current namespace. Thus you can use module's members as if they are defined within your current python module.

When you do import socket, a module is loaded in a separate namespace. When you are accessing its members, you should prefix them with a module name. For example, if you want to refer to a socket class, you will need to write client_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM).

As for the problem with timeout - all you need to do is to change except socket.Timeouterror: to except timeout:, since timeout class is defined inside socket module and you have imported all its members to your namespace.

Difference between add(), replace(), and addToBackStack()

The FragmentManger's function add and replace can be described as these 1. add means it will add the fragment in the fragment back stack and it will show at given frame you are providing like

getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)

2.replace means that you are replacing the fragment with another fragment at the given frame

getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)

The Main utility between the two is that when you are back stacking the replace will refresh the fragment but add will not refresh previous fragment.

tmux set -g mouse-mode on doesn't work

this should work:

setw -g mode-mouse on

then resource then config file

tmux source-file ~/.tmux.conf

or kill the server

How to download file in swift?

A simple, robust and elegant download manager supporting simultaneous downloads with closure syntax for progress and completion tracking. Written in Swift with Here

And Use like it

func downloadGIF(url: String) {
    let filename = url
    let range: Range<String.Index> = filename.range(of:"media/")!
    let lastrange: Range<String.Index> = filename.range(of:"/200w_d")!
    let finalPath = String(filename[range.lowerBound..<lastrange.lowerBound])
    filename[range.lowerBound..<lastrange.lowerBound]
    let replaceFirstWords = finalPath.replace(string: "media/", replacement: "SocialStatus_GIF_")
    let destinationUrl = "\(replaceFirstWords).gif"

    let request = URLRequest(url: URL(string: imageData.bg_image)!)
    viewProgress.isHidden = false
    self.btnDownload.isHidden = true
    setSharingButtonFalse()
    let downloadKey = self.downloadManager.downloadFile(withRequest: request,
                                                        withName: destinationUrl,
                                                        shouldDownloadInBackground: true,
                                                        onProgress:  { [weak self] (progress) in
                                                            self?.viewProgress.progress = CGFloat(progress)
                                                            let val = progress * 100
                                                            print("val 1 == \(val)")
                                                            DispatchQueue.main.async {
                                                                self?.viewProgress.setProgressText("\(Int(val))")
                                                            }

    }) { [weak self] (error, url) in
        if let error = error {
            print("Error = \(error as NSError)")
            self!.isDownloaded = false
            self!.viewProgress.isHidden = true
            self!.setSharingButtonTrue()
            self?.viewProgress.setProgressText("\(0)")
            print("handle error since couldn't save GIF")
        } else {
            if let url = url {
                self!.isDownloaded = true
                self!.saveGIFDownloaded()
                self!.viewProgress.isHidden = true
                self!.setSharingButtonTrue()
                self!.createAlbum()
                self!.saveGIF(url: url.absoluteURL)

            }
        }
    }

}

How to count the number of columns in a table using SQL?

Maybe something like this:

SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'

this will count number of columns in a the table FOO

You can also just

select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';

where the owner is schema and note that Table Names are upper case

Java - removing first character of a string

Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :

String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica

How to append to a file in Node?

Node.js 0.8 has fs.appendFile:

fs.appendFile('message.txt', 'data to append', (err) => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});

Documentation

Reset select2 value and show placeholder

With Select2 version 4.0.9 this works for me:

$( "#myselect2" ).val('').trigger('change');

How can you sort an array without mutating the original array?

Try the following

function sortCopy(arr) { 
  return arr.slice(0).sort();
}

The slice(0) expression creates a copy of the array starting at element 0.

Failed to execute 'atob' on 'Window'

you don't need to pass the entire encoded string to atob method, you need to split the encoded string and pass the required string to atob method

_x000D_
_x000D_
const token= "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJob3NzYW0iLCJUb2tlblR5cGUiOiJCZWFyZXIiLCJyb2xlIjoiQURNSU4iLCJpc0FkbWluIjp0cnVlLCJFbXBsb3llZUlkIjoxLCJleHAiOjE2MTI5NDA2NTksImlhdCI6MTYxMjkzNzA1OX0.8f0EeYbGyxt9hjggYW1vR5hMHFVXL4ZvjTA6XgCCAUnvacx_Dhbu1OGh8v5fCsCxXQnJ8iAIZDIgOAIeE55LUw"
console.log(atob(token.split(".")[1]));
_x000D_
_x000D_
_x000D_

How to calculate the sum of the datatable column in asp.net?

If you have a ADO.Net DataTable you could do

int sum = 0;
foreach(DataRow dr in dataTable.Rows)
{
   sum += Convert.ToInt32(dr["Amount"]);
}

If you want to query the database table, you could use

Select Sum(Amount) From DataTable

How to set margin of ImageView using code, not xml

We can create Linear LayoutParams & use resources.getDimensionPixelSize for dp value.

    val mContext = parent.context
    val mImageView = AppCompatImageView(mContext)
    mImageView.setBackgroundResource(R.drawable.payment_method_selector)

    val height = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_height)
    val width = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_width)
    val padding = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small_tiny)
    val margin = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small)

    mImageView.layoutParams = LinearLayout.LayoutParams(width, height).apply {
        setMargins(margin, margin, 0, 0)
    }
    mImageView.setPadding(padding, padding, padding, padding)

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

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

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

Difference between uint32 and uint32_t

uint32_t is standard, uint32 is not. That is, if you include <inttypes.h> or <stdint.h>, you will get a definition of uint32_t. uint32 is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.

Auto-Submit Form using JavaScript

You need to specify a frame, a target otherwise your script will vanish on first submit!

Change document.myForm with document.forms["myForm"]:

<form name="myForm" id="myForm" target="_myFrame" action="test.php" method="POST">
    <p>
        <input name="test" value="test" />
    </p>
    <p>
        <input type="submit" value="Submit" />
    </p>
</form>

<script type="text/javascript">
    window.onload=function(){
        var auto = setTimeout(function(){ autoRefresh(); }, 100);

        function submitform(){
          alert('test');
          document.forms["myForm"].submit();
        }

        function autoRefresh(){
           clearTimeout(auto);
           auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
        }
    }
</script>

convert iso date to milliseconds in javascript

var date = new Date()
console.log(" Date in MS last three digit = "+  date.getMilliseconds())
console.log(" MS = "+ Date.now())

Using this we can get date in milliseconds

Is there shorthand for returning a default value if None in Python?

You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).

How to have a drop down <select> field in a rails form?

In your model,

class Contact
  self.email_providers = %w[Gmail Yahoo MSN]
  validates :email_provider, :inclusion => email_providers
end

In your form,

<%= f.select :email_provider, 
    options_for_select(Contact.email_providers, @contact.email_provider) %>

the second arg of the options_for_select will have any current email_provider selected.

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

How to import a csv file into MySQL workbench?

If the server resides on a remote machine, make sure the file in in the remote machine and not in your local machine.

If the file is in the same machine where the mysql server is, make sure the mysql user has permissions to read/write the file, or copy teh file into the mysql schema directory:

In my case in ubuntu it was: /var/lib/mysql/db_myschema/myfile.csv

Also, not relative to this problem, but if you have problems with the new lines, use sublimeTEXT to change the line endings to WINDOWS format, save the file and retry.