Programs & Examples On #Macrodef

Invalid length parameter passed to the LEFT or SUBSTRING function

CHARINDEX will return 0 if no spaces are in the string and then you look for a substring of -1 length.

You can tack a trailing space on to the end of the string to ensure there is always at least one space and avoid this problem.

SELECT SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode + ' ' ) -1)

How do I compare two strings in Perl?

And if you'd like to extract the differences between the two strings, you can use String::Diff.

How do I reset a sequence in Oracle?

Altering the sequence's INCREMENT value, incrementing it, and then altering it back is pretty painless, plus you have the added benefit of not having to re-establish all of the grants as you would had you dropped/recreated the sequence.

Delegation: EventEmitter or Observable in Angular

Update 2016-06-27: instead of using Observables, use either

  • a BehaviorSubject, as recommended by @Abdulrahman in a comment, or
  • a ReplaySubject, as recommended by @Jason Goemaat in a comment

A Subject is both an Observable (so we can subscribe() to it) and an Observer (so we can call next() on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer).

BehaviorSubject is a variant of Subject. It has the notion of "the current value". We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.

The code below and the plunker use BehaviorSubject.

ReplaySubject is another variant of Subject. If you want to wait until a value is actually produced, use ReplaySubject(1). Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use first() on the subscription. You do not have to unsubscribe if you use first().

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class NavService {
  // Observable navItem source
  private _navItemSource = new BehaviorSubject<number>(0);
  // Observable navItem stream
  navItem$ = this._navItemSource.asObservable();
  // service command
  changeNav(number) {
    this._navItemSource.next(number);
  }
}
import {Component}    from '@angular/core';
import {NavService}   from './nav.service';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription:Subscription;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.subscription = this._navService.navItem$
       .subscribe(item => this.item = item)
  }
  ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
  }
}
@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>`
})
export class Navigation {
  item = 1;
  constructor(private _navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this._navService.changeNav(item);
  }
}

Plunker


Original answer that uses an Observable: (it requires more code and logic than using a BehaviorSubject, so I don't recommend it, but it may be instructive)

So, here's an implementation that uses an Observable instead of an EventEmitter. Unlike my EventEmitter implementation, this implementation also stores the currently selected navItem in the service, so that when an observing component is created, it can retrieve the current value via API call navItem(), and then be notified of changes via the navChange$ Observable.

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Observer} from 'rxjs/Observer';

export class NavService {
  private _navItem = 0;
  navChange$: Observable<number>;
  private _observer: Observer;
  constructor() {
    this.navChange$ = new Observable(observer =>
      this._observer = observer).share();
    // share() allows multiple subscribers
  }
  changeNav(number) {
    this._navItem = number;
    this._observer.next(number);
  }
  navItem() {
    return this._navItem;
  }
}

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.item = this._navService.navItem();
    this.subscription = this._navService.navChange$.subscribe(
      item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item:number;
  constructor(private _navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this._navService.changeNav(item);
  }
}

Plunker


See also the Component Interaction Cookbook example, which uses a Subject in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.

How to get the next auto-increment id in mysql

using the answer of ravi404:

CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
    RETURNS BIGINT
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN

    DECLARE Value BIGINT;

    SELECT
        AUTO_INCREMENT INTO Value
    FROM
        information_schema.tables
    WHERE
        table_name = TableName AND
        table_schema = DATABASE();

    RETURN Value;

END

using in your insert query, to create a SHA1 Hash. ex.:

INSERT INTO
    document (Code, Title, Body)
VALUES (                
    sha1( getAutoincrementalNextval ('document') ),
    'Title',
    'Body'
);

How to decrease prod bundle size?

Use latest angular cli version and use command ng build --prod --build-optimizer It will definitely reduce the build size for prod env.

This is what the build optimizer does under the hood:

The build optimizer has two main jobs. First, we are able to mark parts of your application as pure,this improves the tree shaking provided by the existing tools, removing additional parts of your application that aren’t needed.

The second thing the build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decrease the size of your JavaScript bundles, and increase the boot speed of your application for your users.

Note : One update for Angular 5 and up, the ng build --prod automatically take care of above process :)

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Java Replace Character At Specific Position Of String?

Petar Ivanov's answer to replace a character at a specific index in a string question

String are immutable in Java. You can't change them.

You need to create a new string with the character replaced.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

I have tried www.wheresmymac.com they are cheap and they have great bandwith so their is low latency. You need teamviewer to log into the virtual system though

Generate your own Error code in swift 3

I know you have already satisfied with an answer but if you are interested to know the right approach, then this might be helpful for you. I would prefer not to mix http-response error code with the error code in the error object (confused? please continue reading a bit...).

The http response codes are standard error codes about a http response defining generic situations when response is received and varies from 1xx to 5xx ( e.g 200 OK, 408 Request timed out,504 Gateway timeout etc - http://www.restapitutorial.com/httpstatuscodes.html )

The error code in a NSError object provides very specific identification to the kind of error the object describes for a particular domain of application/product/software. For example your application may use 1000 for "Sorry, You can't update this record more than once in a day" or say 1001 for "You need manager role to access this resource"... which are specific to your domain/application logic.

For a very small application, sometimes these two concepts are merged. But they are completely different as you can see and very important & helpful to design and work with large software.

So, there can be two techniques to handle the code in better way:

1. The completion callback will perform all the checks

completionHandler(data, httpResponse, responseError) 

2. Your method decides success and error situation and then invokes corresponding callback

if nil == responseError { 
   successCallback(data)
} else {
   failureCallback(data, responseError) // failure can have data also for standard REST request/response APIs
}

Happy coding :)

Recursively find all files newer than a given time

Given a unix timestamp (seconds since epoch) of 1494500000, do:

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)"

To grep those files for "foo":

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)" -exec grep -H 'foo' '{}' \;

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Should IBOutlets be strong or weak under ARC?

From WWDC 2015 there is a session on Implementing UI Designs in Interface Builder. Around the 32min mark he says that you always want to make your @IBOutlet strong.

How to set Status Bar Style in Swift 3

I was struggling with this too, so if you are presenting a FULLSCREEN modal view controller, make sure to set .modalPresentationStyle as .fullscreen and then, on your presenting view controller, just override .preferredStatusBarStyle to .lightContent.

So:

let navigationController = UINavigationController(rootViewController: viewController)
navigationController.modalPresentationStyle = .fullScreen // <=== make sure to set navigation modal presentation style
present(navigationController, animated: true, completion: nil)

on your custom view controller, override status bar style:

    override var preferredStatusBarStyle: UIStatusBarStyle {
        .lightContent
    }

Update index after sorting data-frame

You can set new indices by using set_index:

df2.set_index(np.arange(len(df2.index)))

Output:

   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I have faced it on 04/2020. These are the options that I tried and the last solution get me through.

Problem:

Requests module works fine when I use in Spyder IDE but when I try to execute the script in windows it fails with SSL error. It works fine for HTTP requests but for HTTPS requests i got SSL error.

  1. I tired with Veify=True, False , also with Certs. Same error.
  2. Removed Certifi - conda remove certifi - Did not work Updated
  3. openssl , certifi - Still same error ( Refer : https://github.com/ContinuumIO/anaconda-issues/issues/494) Added
  4. the path variables - Same error
  5. Created new environment in Anaconda - same error

Solution that fixed it:

Solution from: https://github.com/conda/conda/issues/8273

I have copied the following files from Anaconda3\Library\bin to \Anaconda3\DLL

libcrypto-1_1-x64.* libssl-1_1-x64.*

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

Get variable from PHP to JavaScript

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>

How to test for $null array in PowerShell

If your solution requires returning 0 instead of true/false, I've found this to be useful:

PS C:\> [array]$foo = $null
PS C:\> ($foo | Measure-Object).Count
0

This operation is different from the count property of the array, because Measure-Object is counting objects. Since there are none, it will return 0.

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

Have you add a default route to this class?

public class RouteConfig {
    public static void RegisterRoutes (RouteCollection routes) {`
        //"HomePage" is the root view of your app
        routes.MapRoute (
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new {
                controller = "Home", action = "HomePage", id = UrlParameter.Optional
            }
        );
    }
}

` After that in Global.asax.cs add this line to Application_Start() method:

RouteConfig.RegisterRoutes (RouteTable.Routes);

I had this problem after I made an upgrade from MVC4 to MVC5 following this post and I had that line commented for a reason that I've forgot.

Hope this helps!

How to find sum of several integers input by user using do/while, While statement or For statement

#include<iostream>
int main()
{//initialize variables
    int limit;
    int num;
    int sum=0;
    int counter=0;

    cout<<"Enter limit of numbers you wish to see"<<" ";
    cin>>limit;
    cout<<endl;

while(counter<limit)
{

   cout<<"Enter number "<<endl;
  cin>>num;

  sum=sum+num;
  counter++;
}
cout<<"The sum of numbers is "<<" "<<endl

return 0;
}

PHP mail not working for some reason

Check your SMTP settings in your php.ini file. Your host should have some documentation about what credentials to use. Perhaps you can check your error log file, it might have more information available.

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

Fatal error: Call to undefined function mysql_connect()

PHP.INI

Check if you forgot to enable the options below(loads the modules for mysql among others):

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "ext"

MySQL - sum column value(s) based on row from the same table

SUM CASE using example:

    SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(IF(p.`PaymentMethod`='Cash',Amount,0)) AS Cash_,
  SUM(IF(p.`PaymentMethod`='Check',Amount,0)) AS Check_,
  SUM(IF(p.`PaymentMethod`='Credit Card',Amount,0)) AS Credit_Card_,
  SUM( CASE PaymentMethod 
      WHEN 'Cash' THEN Amount
      WHEN 'Check' THEN Amount
      WHEN 'Credit Card' THEN Amount
     END) AS Total
FROM
  `payments` AS p 
GROUP BY p.`ProductID`;

SQL FIDDLE: http://www.sqlfiddle.com/#!9/23d07d/18

Result and Table view

How do you clone a Git repository into a specific folder?

Clone:

git clone [email protected]:jittre/name.git

Clone the "specific branch":

git clone -b [branch-name] [email protected]:jittre/name.git

Intercept page exit event

I have users who have not been completing all required data.

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
    <cfset unloadCheck=1>
    $("#myInput").change(function(){
        verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
        if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
        else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
    });
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
    verify();
    window.onbeforeunload = confirmExit;
    function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>

Loop through JSON in EJS

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296

OrderBy pipe issue

I modified @Thierry Templier's response so the pipe can sort custom objects in angular 4:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "sort"
})
export class ArraySortPipe  implements PipeTransform {
  transform(array: any, field: string): any[] {
    if (!Array.isArray(array)) {
      return;
    }
    array.sort((a: any, b: any) => {
      if (a[field] < b[field]) {
        return -1;
      } else if (a[field] > b[field]) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

And to use it:

*ngFor="let myObj of myArr | sort:'fieldName'"

Hopefully this helps someone.

Vertical Align text in a Label

The vertical-align style is used in table cells, so that won't do anything for you here.

To align the labels to the input boxes, you can use line-height:

line-height: 25px;

Difference between subprocess.Popen and os.system

subprocess.Popen() is strict super-set of os.system().

Why compile Python code?

We use compiled code to distribute to users who do not have access to the source code. Basically to stop inexperienced programers accidentally changing something or fixing bugs without telling us.

When to use RabbitMQ over Kafka?

The most voted answer covers most part but I would like to high light use case point of view. Can kafka do that rabbit mq can do, answer is yes but can rabbit mq do everything that kafka does, the answer is no.

The thing that rabbit mq cannot do that makes kafka apart, is distributed message processing. With this now read back the most voted answer and it will make more sense.

To elaborate, take a use case where you need to create a messaging system that has super high throughput for example "likes" in facebook and You have chosen rabbit mq for that. You created an exchange and queue and a consumer where all publishers (in this case FB users) can publish 'likes' messages. Since your throughput is high, you will create multiple threads in consumer to process messages in parallel but you still bounded by the hardware capacity of the machine where consumer is running. Assuming that one consumer is not sufficient to process all messages - what would you do?

  • Can you add one more consumer to queue - no you cant do that.
  • Can you create a new queue and bind that queue to exchange that publishes 'likes' message, answer is no cause you will have messages processed twice.

That is the core problem that kafka solves. It lets you create distributed partitions (Queue in rabbit mq) and distributed consumer that talk to each other. That ensures your messages in a topic get processed by consumers distributed in various nodes (Machines).

Kafka brokers ensure that messages get load balanced across all partitions of that topic. Consumer group make sure that all consumer talk to each other and message does not get processed twice.

But in real life you will not face this problem unless your throughput is seriously high because rabbit mq can also process data very fast even with one consumer.

How to install numpy on windows using pip install?

Install miniconda (here)

After installed, open Anaconda Prompt (search this in Start Menu)

Write:

pip install numpy

After installed, test:

import numpy as np

jQuery attr('onclick')

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

There are more than 90 implemented distribution functions in SciPy v1.6.0. You can test how some of them fit to your data using their fit() method. Check the code below for more details:

enter image description here

import matplotlib.pyplot as plt
import numpy as np
import scipy
import scipy.stats
size = 30000
x = np.arange(size)
y = scipy.int_(np.round_(scipy.stats.vonmises.rvs(5,size=size)*47))
h = plt.hist(y, bins=range(48))

dist_names = ['gamma', 'beta', 'rayleigh', 'norm', 'pareto']

for dist_name in dist_names:
    dist = getattr(scipy.stats, dist_name)
    params = dist.fit(y)
    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]
    if arg:
        pdf_fitted = dist.pdf(x, *arg, loc=loc, scale=scale) * size
    else:
        pdf_fitted = dist.pdf(x, loc=loc, scale=loc) * size
    plt.plot(pdf_fitted, label=dist_name)
    plt.xlim(0,47)
plt.legend(loc='upper right')
plt.show()

References:

- Fitting distributions, goodness of fit, p-value. Is it possible to do this with Scipy (Python)?

- Distribution fitting with Scipy

And here a list with the names of all distribution functions available in Scipy 0.12.0 (VI):

dist_names = [ 'alpha', 'anglit', 'arcsine', 'beta', 'betaprime', 'bradford', 'burr', 'cauchy', 'chi', 'chi2', 'cosine', 'dgamma', 'dweibull', 'erlang', 'expon', 'exponweib', 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'frechet_r', 'frechet_l', 'genlogistic', 'genpareto', 'genexpon', 'genextreme', 'gausshyper', 'gamma', 'gengamma', 'genhalflogistic', 'gilbrat', 'gompertz', 'gumbel_r', 'gumbel_l', 'halfcauchy', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb', 'johnsonsu', 'ksone', 'kstwobign', 'laplace', 'logistic', 'loggamma', 'loglaplace', 'lognorm', 'lomax', 'maxwell', 'mielke', 'nakagami', 'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rdist', 'reciprocal', 'rayleigh', 'rice', 'recipinvgauss', 'semicircular', 't', 'triang', 'truncexpon', 'truncnorm', 'tukeylambda', 'uniform', 'vonmises', 'wald', 'weibull_min', 'weibull_max', 'wrapcauchy'] 

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Entity Framework: table without primary key

We encountered this problem as well, and while we had a column that had nulls, what was important was that we had a dependent column that did not have nulls and that the combination of these two columns was unique.

So to quote the response given by Pratap Reddy, it worked fine for us.

Python Git Module experiences?

PTBNL's Answer is quite perfect for me. I make a little more for Windows user.

import time
import subprocess
def gitAdd(fileName, repoDir):
    cmd = 'git add ' + fileName
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 

def gitCommit(commitMessage, repoDir):
    cmd = 'git commit -am "%s"'%commitMessage
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 
def gitPush(repoDir):
    cmd = 'git push '
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    pipe.wait()
    return 

temp=time.localtime(time.time())
uploaddate= str(temp[0])+'_'+str(temp[1])+'_'+str(temp[2])+'_'+str(temp[3])+'_'+str(temp[4])

repoDir='d:\\c_Billy\\vfat\\Programming\\Projector\\billyccm' # your git repository , windows your need to use double backslash for right directory.
gitAdd('.',repoDir )
gitCommit(uploaddate, repoDir)
gitPush(repoDir)

How do I mock an open used in a with statement (using the Mock framework in Python)?

The top answer is useful but I expanded on it a bit.

If you want to set the value of your file object (the f in as f) based on the arguments passed to open() here's one way to do it:

def save_arg_return_data(*args, **kwargs):
    mm = MagicMock(spec=file)
    mm.__enter__.return_value = do_something_with_data(*args, **kwargs)
    return mm
m = MagicMock()
m.side_effect = save_arg_return_array_of_data

# if your open() call is in the file mymodule.animals 
# use mymodule.animals as name_of_called_file
open_name = '%s.open' % name_of_called_file

with patch(open_name, m, create=True):
    #do testing here

Basically, open() will return an object and with will call __enter__() on that object.

To mock properly, we must mock open() to return a mock object. That mock object should then mock the __enter__() call on it (MagicMock will do this for us) to return the mock data/file object we want (hence mm.__enter__.return_value). Doing this with 2 mocks the way above allows us to capture the arguments passed to open() and pass them to our do_something_with_data method.

I passed an entire mock file as a string to open() and my do_something_with_data looked like this:

def do_something_with_data(*args, **kwargs):
    return args[0].split("\n")

This transforms the string into a list so you can do the following as you would with a normal file:

for line in file:
    #do action

What does "select 1 from" do?

The statement SELECT 1 FROM SomeTable just returns a column containing the value 1 for each row in your table. If you add another column in, e.g. SELECT 1, cust_name FROM SomeTable then it makes it a little clearer:

            cust_name
----------- ---------------
1           Village Toys
1           Kids Place
1           Fun4All
1           Fun4All
1           The Toy Store

How to center an image horizontally and align it to the bottom of the container?

#header2
{
   display: table-cell;
   vertical-align: bottom;
   background-color:Red;
}


<div style="text-align:center; height:300px; width:50%;" id="header2">
<div class="right" id="header-content2">
  <p>this is a test</p>
</div>
</div>

Getting Current date, time , day in laravel

//vanilla php
Class Date {
    public static function date_added($time){
         date_default_timezone_set('Africa/Lagos');//or choose your location
        return date('l F Y g:i:s ',$time);

    }


}

Can scripts be inserted with innerHTML?

Here a solution that does not use eval, and works with scripts, linked scripts , as well as with modules.

The function accepts 3 parameters :

  • html : String with the html code to insert
  • dest : reference to the target element
  • append : boolean flag to enable appending at the end of the target element html
function insertHTML(html, dest, append=false){
    // if no append is requested, clear the target element
    if(!append) dest.innerHTML = '';
    // create a temporary container and insert provided HTML code
    let container = document.createElement('div');
    container.innerHTML = html;
    // cache a reference to all the scripts in the container
    let scripts = container.querySelectorAll('script');
    // get all child elements and clone them in the target element
    let nodes = container.childNodes;
    for( let i=0; i< nodes.length; i++) dest.appendChild( nodes[i].cloneNode(true) );
    // force the found scripts to execute...
    for( let i=0; i< scripts.length; i++){
        let script = document.createElement('script');
        script.type = scripts[i].type || 'text/javascript';
        if( scripts[i].hasAttribute('src') ) script.src = scripts[i].src;
        script.innerHTML = scripts[i].innerHTML;
        document.head.appendChild(script);
        document.head.removeChild(script);
    }
    // done!
    return true;
}

What is the equivalent to getch() & getche() in Linux?

#include <termios.h>
#include <stdio.h>

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}

Output:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g

The type is defined in an assembly that is not referenced, how to find the cause?

It just happened to me that different projects were referencing different copies of the same dll. I made sure all referenced the same file on disk, and the error disappeared as I expected.

How can I see the size of files and directories in linux?

All you need is -l and --block-size flags

Size of all files and directories under working directory (in MBs)

ls -l --block-size=M

Size of all files and directories under working directory (in GBs)

ls -l --block-size=G

Size of a specific file or directory

ls -l --block-size=M my_file.txt
ls -l --block-size=M my_dir/

ls --help

-l use a long listing format

--block-size=SIZE: scale sizes by SIZE before printing them; e.g., '--block-size=M' prints sizes in units of 1,048,576 bytes; see SIZE format below

SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB, ... (powers of 1000).


Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

Android Studio - local path doesn't exist

I managed to find a temporary workaround. Do all by yourself using command line :

// build apk
./gradlew assemble --daemon

// debug apk is unaligned so we need to align it
zipalign -f 4 app/build/apk/app-debug-unaligned.apk app/build/apk/app-debug.apk

// reinstall it using adb
adb install -r app/build/apk/app-debug.apk

This is temporary, but I hope they will fix this for 0.2.5

Edit : not fixed in 0.2.5

Edit2 : fixed for now by adding in my module.iml file (in facet/configuration) :

<option name="APK_PATH" value="/build/apk/appname-debug-unaligned.apk" />

What's a concise way to check that environment variables are set in a Unix shell script?

Your question is dependent on the shell that you are using.

Bourne shell leaves very little in the way of what you're after.

BUT...

It does work, just about everywhere.

Just try and stay away from csh. It was good for the bells and whistles it added, compared the Bourne shell, but it is really creaking now. If you don't believe me, just try and separate out STDERR in csh! (-:

There are two possibilities here. The example above, namely using:

${MyVariable:=SomeDefault}

for the first time you need to refer to $MyVariable. This takes the env. var MyVariable and, if it is currently not set, assigns the value of SomeDefault to the variable for later use.

You also have the possibility of:

${MyVariable:-SomeDefault}

which just substitutes SomeDefault for the variable where you are using this construct. It doesn't assign the value SomeDefault to the variable, and the value of MyVariable will still be null after this statement is encountered.

Mongoose, Select a specific field with find

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name -_id');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

Or explicitly via an object:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

How to generate UML diagrams (especially sequence diagrams) from Java code?

I've noticed SequenceDiagram plugin for Intellij is also a good option.

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

What is the equivalent of Java's System.out.println() in Javascript?

console.log().

Chrome, Safari, and IE 8+ come with built-in consoles (as part of a larger set of development tools). If you're using Firefox, getfirebug.com.

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

SQL: How to properly check if a record exists

Other option:

SELECT CASE
    WHEN EXISTS (
        SELECT 1
        FROM [MyTable] AS [MyRecord])
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END

Comparing two vectors in an if statement

all is one option:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

But you may have to watch out for recycling:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

The documentation for length says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all.

In angular $http service, How can I catch the "status" of error?

Response status comes as second parameter in callback, (from docs):

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

How do I detect if a user is already logged in Firebase?

If you are allowing anonymous users as well as those logged in with email you can use firebase.auth().currentUser.isAnonymous, which will return either true or false.

Looking for a 'cmake clean' command to clear up CMake output

A solution that I found recently is to combine the out-of-source build concept with a Makefile wrapper.

In my top-level CMakeLists.txt file, I include the following to prevent in-source builds:

if ( ${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR} )
    message( FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there. You may need to remove CMakeCache.txt." )
endif()

Then, I create a top-level Makefile, and include the following:

# -----------------------------------------------------------------------------
# CMake project wrapper Makefile ----------------------------------------------
# -----------------------------------------------------------------------------

SHELL := /bin/bash
RM    := rm -rf
MKDIR := mkdir -p

all: ./build/Makefile
    @ $(MAKE) -C build

./build/Makefile:
    @  ($(MKDIR) build > /dev/null)
    @  (cd build > /dev/null 2>&1 && cmake ..)

distclean:
    @  ($(MKDIR) build > /dev/null)
    @  (cd build > /dev/null 2>&1 && cmake .. > /dev/null 2>&1)
    @- $(MAKE) --silent -C build clean || true
    @- $(RM) ./build/Makefile
    @- $(RM) ./build/src
    @- $(RM) ./build/test
    @- $(RM) ./build/CMake*
    @- $(RM) ./build/cmake.*
    @- $(RM) ./build/*.cmake
    @- $(RM) ./build/*.txt

ifeq ($(findstring distclean,$(MAKECMDGOALS)),)
    $(MAKECMDGOALS): ./build/Makefile
    @ $(MAKE) -C build $(MAKECMDGOALS)
endif

The default target all is called by typing make, and invokes the target ./build/Makefile.

The first thing the target ./build/Makefile does is to create the build directory using $(MKDIR), which is a variable for mkdir -p. The directory build is where we will perform our out-of-source build. We provide the argument -p to ensure that mkdir does not scream at us for trying to create a directory that may already exist.

The second thing the target ./build/Makefile does is to change directories to the build directory and invoke cmake.

Back to the all target, we invoke $(MAKE) -C build, where $(MAKE) is a Makefile variable automatically generated for make. make -C changes the directory before doing anything. Therefore, using $(MAKE) -C build is equivalent to doing cd build; make.

To summarize, calling this Makefile wrapper with make all or make is equivalent to doing:

mkdir build
cd build
cmake ..
make 

The target distclean invokes cmake .., then make -C build clean, and finally, removes all contents from the build directory. I believe this is exactly what you requested in your question.

The last piece of the Makefile evaluates if the user-provided target is or is not distclean. If not, it will change directories to build before invoking it. This is very powerful because the user can type, for example, make clean, and the Makefile will transform that into an equivalent of cd build; make clean.

In conclusion, this Makefile wrapper, in combination with a mandatory out-of-source build CMake configuration, make it so that the user never has to interact with the command cmake. This solution also provides an elegant method to remove all CMake output files from the build directory.

P.S. In the Makefile, we use the prefix @ to suppress the output from a shell command, and the prefix @- to ignore errors from a shell command. When using rm as part of the distclean target, the command will return an error if the files do not exist (they may have been deleted already using the command line with rm -rf build, or they were never generated in the first place). This return error will force our Makefile to exit. We use the prefix @- to prevent that. It is acceptable if a file was removed already; we want our Makefile to keep going and remove the rest.

Another thing to note: This Makefile may not work if you use a variable number of CMake variables to build your project, for example, cmake .. -DSOMEBUILDSUSETHIS:STRING="foo" -DSOMEOTHERBUILDSUSETHISTOO:STRING="bar". This Makefile assumes you invoke CMake in a consistent way, either by typing cmake .. or by providing cmake a consistent number of arguments (that you can include in your Makefile).

Finally, credit where credit is due. This Makefile wrapper was adapted from the Makefile provided by the C++ Application Project Template.

What is the difference between Sessions and Cookies in PHP?

A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.

A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

Detect if a page has a vertical scrollbar?

Let's bring this question back from the dead ;) There is a reason Google doesn't give you a simple solution. Special cases and browser quirks affect the calculation, and it is not as trivial as it seems to be.

Unfortunately, there are problems with the solutions outlined here so far. I don't mean to disparage them at all - they are great starting points and touch on all the key properties needed for a more robust approach. But I wouldn't recommend copying and pasting the code from any of the other answers because

  • they don't capture the effect of positioned content in a way that is reliable cross-browser. The answers which are based on body size miss this entirely (the body is not the offset parent of such content unless it is positioned itself). And those answers checking $( document ).width() and .height() fall prey to jQuery's buggy detection of document size.
  • Relying on window.innerWidth, if the browser supports it, makes your code fail to detect scroll bars in mobile browsers, where the width of the scroll bar is generally 0. They are just shown temporarily as an overlay and don't take up space in the document. Zooming on mobile also becomes a problem that way (long story).
  • The detection can be thrown off when people explicitly set the overflow of both the html and body element to non-default values (what happens then is a little involved - see this description).
  • In most answers, body padding, borders or margins are not detected and distort the results.

I have spent more time than I would have imagined on a finding a solution that "just works" (cough). The algorithm I have come up with is now part of a plugin, jQuery.isInView, which exposes a .hasScrollbar method. Have a look at the source if you wish.

In a scenario where you are in full control of the page and don't have to deal with unknown CSS, using a plugin may be overkill - after all, you know which edge cases apply, and which don't. However, if you need reliable results in an unknown environment, then I don't think the solutions outlined here will be enough. You are better off using a well-tested plugin - mine or anybody elses.

Display tooltip on Label's hover?

You could use the title attribute in html :)

<label title="This is the full title of the label">This is the...</label>

When you keep the mouse over for a brief moment, it should pop up with a box, containing the full title.

If you want more control, I suggest you look into the Tipsy Plugin for jQuery - It can be found at http://onehackoranother.com/projects/jquery/tipsy/ and is fairly simple to get started with.

round up to 2 decimal places in java?

This is long one but a full proof solution, never fails

Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;

if 4.25, Output 4.25

if 4.20, Output 4.20

if 4.24, Output 4.20

if 4.26, Output 4.30

if you want to round upto 2 decimal places,then use

DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));

if up to 3 places, new DecimalFormat("#.###")

if up to n places, new DecimalFormat("#.nTimes #")

 public double roundToMultipleOfFive(double x)
            {

                x=input.nextDouble();
                String str=String.valueOf(x);
                int pos=0;
                for(int i=0;i<str.length();i++)
                {
                    if(str.charAt(i)=='.')
                    {
                        pos=i;
                        break;
                    }
                }

                int after=Integer.parseInt(str.substring(pos+1,str.length()));
                int Q=after/5;
                int R =after%5;

                if((Q%2)==0)
                {
                    after=after-R;
                }
                else
                {
                   if(5-R==5)
                   {
                     after=after;
                   }
                   else after=after+(5-R);
                }

                       return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));

            }

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

I used the code below and tried to show the sitemap.xml file

router.get('/sitemap.xml', function (req, res) {
    res.sendFile('sitemap.xml', { root: '.' });
});

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

If you're going to be adding the TimeOut directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!

How to retrieve SQL result column value using column name in Python?

import pymysql

# Open database connection
db = pymysql.connect("localhost","root","","gkdemo1")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT * from user")

# Get the fields name (only once!)
field_name = [field[0] for field in cursor.description]

# Fetch a single row using fetchone() method.
values = cursor.fetchone()

# create the row dictionary to be able to call row['login']
**row = dict(zip(field_name, values))**

# print the dictionary
print(row)

# print specific field
print(**row['login']**)

# print all field
for key in row:
    print(**key," = ",row[key]**)

# close database connection
db.close()

How do I print the content of a .txt file in Python?

It's pretty simple

#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)

Presenting snapshot from my visual studio IDE.

enter image description here

The right way of setting <a href=""> when it's a local file

../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.

Converting java.util.Properties to HashMap<String,String>

I would use following Guava API: com.google.common.collect.Maps#fromProperties

Properties properties = new Properties();
Map<String, String> map = Maps.fromProperties(properties);

How to perform a fade animation on Activity transition?

you can also use this code in your style.xml file so you don't need to write anything else in your activity.java

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>

<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

It takes some time to return results, easily many tens of seconds, but wmic works well and can be scripted:

wmic product where "Name like '%Word%'" get Name, Version, IdentifyingNumber

result:

IdentifyingNumber                       Name                                      Version
{90140000-001B-0409-0000-0000000FF1CE}  Microsoft Office Word MUI (English) 2010  14.0.6029.1000

The IdentifingNumber is the ProductCode. I didn't see a property for UpgradeCode, but perhaps it might be buried under something else. See http://quux.wiki.zoho.com/WMIC-Snippets.html for many other examples, including uninstall:

wmic path win32_product where "name = 'HP Software Update'" call Uninstall

What does the Ellipsis object do?

In Python 3, you can¹ use the Ellipsis literal ... as a “nop” placeholder for code that hasn't been written yet:

def will_do_something():
    ...

This is not magic; any expression can be used instead of ..., e.g.:

def will_do_something():
    1

(Can't use the word “sanctioned”, but I can say that this use was not outrightly rejected by Guido.)

¹ 'can' not in {'must', 'should'}

The split() method in Java does not work on a dot (.)

    private String temp = "mahesh.hiren.darshan";

    String s_temp[] = temp.split("[.]");

  Log.e("1", ""+s_temp[0]);

How can I determine if a String is non-null and not only whitespace in Groovy?

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

How to access the php.ini from my CPanel?

Go to main screen. Under 'Software/Services' > 'php.ini EZConfig'.

Add carriage return to a string

string s2 = s1.Replace(",", ",\r\n");

the getSource() and getActionCommand()

I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").

I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:

public class SeleccionListener implements ActionListener, FocusListener {}

So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:

public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
        System.out.println("Aceptar pressed");
    }

In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).

public void focusGained(FocusEvent focusEvent) {
    if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
        System.out.println("Data radio button");
    }

In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)

How to get domain URL and application name?

The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath() (and thus NOT getServletPath() as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}.

<p>The context path is: ${pageContext.request.contextPath}.</p>

If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base> tag:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2204870</title>
        <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
        <script src="js/global.js"></script>
        <link rel="stylesheet" href="css/global.css">
    </head>
    <body>
        <ul>
            <li><a href="home.jsp">Home</a></li>
            <li><a href="faq.jsp">FAQ</a></li>
            <li><a href="contact.jsp">Contact</a></li>
        </ul>
    </body>
</html>

All links in the page will then automagically be relative to the <base> so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /, then they will not be relative to the <base> anymore, but to the domain root instead.

How to use default Android drawables

Better you copy and move them to your own resources. Some resources might not be available on previous Android versions. Here is a link with all drawables available on each Android version thanks to @fiXedd

Android: TextView: Remove spacing and padding on top and bottom

See this:

Align ImageView with EditText horizontally

It seems that the background image of EditText has some transparent pixels which also add padding.

A solution is to change the default background of EditText to something else (or nothing, but no background for a EditText is probably not acceptable). That's can be made setting android:background XML attribute.

android:background="@drawable/myEditBackground"

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

Deleting Row in SQLite in Android

To delete rows from a table, you need to provide selection criteria that identify the rows to the delete() method. The mechanism works the same as the selection arguments to the query() method. It divides the selection specification into a selection clause(where clause) and selection arguments.

    SQLiteDatabase db  = this.getWritableDatabase();
     // Define 'where' part of query.
    String selection = Contract.COLUMN_COMPANY_ID + " =?  and "
                       + Contract.CLOUMN_TYPE +" =? ";
   // Specify arguments in placeholder order.
    String[] selectionArgs = { cid,mode };
    // Issue SQL statement.
    int deletedRows = db.delete(Contract.TABLE_NAME, 
                       selection, selectionArgs);
    return deletedRows;// no.of rows deleted.

The return value for the delete() method indicates the number of rows that were deleted from the database.

Temporary tables in stored procedures

Use @temp tables whenever possible--that is, you only need one primary key and you do not need to access the data from a subordinate stored proc.

Use #temp tables if you need to access the data from a subordinate stored proc (it is an evil global variable to the stored proc call chain) and you have no other clean way to pass the data between stored procs. Also use it if you need a secondary index (although, really ask yourself if it is a #temp table if you need more than one index)

If you do this, always declare your #temp table at the top of the function. SQL will force a recompile of your stored proc when it sees the create table statement....so if you have the #temp table declaration in the middle of the stored proc, you stored proc must stop processing and recompile.

How to lookup JNDI resources on WebLogic?

I had a similar problem to this one. It got solved by deleting the java:comp/env/ prefix and using jdbc/myDataSource in the context lookup. Just as someone pointed out in the comments.

Build error, This project references NuGet

Quick solution that worked like a charm for me and others:

If you are using VS 2015+, just remove the following lines from the .csproj file of your project:

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>

In VS 2015+ Solution Explorer:

  1. Right-click project name -> Unload Project
  2. Right-click project name -> Edit .csproj
  3. Remove the lines specified above from the file and save
  4. Right-click project name -> Reload Project

Assign static IP to Docker container

If you want your container to have it's own virtual ethernet socket (with it's own MAC address), iptables, then use the Macvlan driver. This may be necessary to route traffic out to your/ISPs router.

https://docs.docker.com/engine/userguide/networking/get-started-macvlan

Double % formatting question for printf in Java

%d is for integers use %f instead, it works for both float and double types:

double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000

Divide a number by 3 without using *, /, +, -, % operators

Here it is in Python with, basically, string comparisons and a state machine.

def divide_by_3(input):
  to_do = {}
  enque_index = 0
  zero_to_9 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  leave_over = 0
  for left_over in (0, 1, 2):
    for digit in zero_to_9:
      # left_over, digit => enque, leave_over
      to_do[(left_over, digit)] = (zero_to_9[enque_index], leave_over)
      if leave_over == 0:
        leave_over = 1
      elif leave_over == 1:
        leave_over = 2
      elif leave_over == 2 and enque_index != 9:
        leave_over = 0
        enque_index = (1, 2, 3, 4, 5, 6, 7, 8, 9)[enque_index]
  answer_q = []
  left_over = 0
  digits = list(str(input))
  if digits[0] == "-":
    answer_q.append("-")
  digits = digits[1:]
  for digit in digits:
    enque, left_over = to_do[(left_over, int(digit))]
    if enque or len(answer_q):
      answer_q.append(enque)
  answer = 0
  if len(answer_q):
    answer = int("".join([str(a) for a in answer_q]))
  return answer

Import existing Gradle Git project into Eclipse

The simpliest way is to use sts gradle integration and import project

http://static.springsource.org/sts/docs/2.7.0.M1/reference/html/gradle/gradle-sts-tutorial.html

Don't forget to click "Build Model" button.

How do I check if a string is a number (float)?

I also used the function you mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of your function, that will return false on those type of input and will not fail "1e3" variants:

def is_float(text):
    try:
        float(text)
        # check for nan/infinity etc.
        if text.isalpha():
            return False
        return True
    except ValueError:
        return False

How do I remove all .pyc files from a project?

For windows users:

del /S *.pyc

How to specify test directory for mocha?

I am on Windows 7 using node.js v0.10.0 and mocha v1.8.2 and npm v1.2.14. I was just trying to get mocha to use the path test/unit to find my tests, After spending to long and trying several things I landed,

Using the "test/unit/*.js" option does not work on windows. For good reasons that windows shell doesn't expand wildcards like unixen.

However using "test/unit" does work, without the file pattern. eg. "mocha test/unit" runs all files found in test/unit folder.

This only still runs one folder files as tests but you can pass multiple directory names as parameters.

Also to run a single test file you can specify the full path and filename. eg. "mocha test/unit/mytest1.js"

I actually setup in package.json for npm "scripts": { "test": "mocha test/unit" },

So that 'npm test' runs my unit tests.

Python: How to remove empty lists from a list?

A few options:

filter(lambda x: len(x) > 0, list1)  # Doesn't work with number types
filter(None, list1)  # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)

sample session:

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>

How to get main window handle from process id?

Old question but appears to have a lot of traffic, here is a simple solution:

IntPtr GetMainWindowHandle(IntPtr aHandle) {
        return System.Diagnostics.Process.GetProcessById(aHandle.ToInt32()).MainWindowHandle;
}

How to reset AUTO_INCREMENT in MySQL?

I tried to alter the table and set auto_increment to 1 but it did not work. I resolved to delete the column name I was incrementing, then create a new column with your preferred name and set that new column to increment from the onset.

Comparing Java enum members: == or equals()?

I want to complement polygenelubricants answer:

I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.

To have type compatibility check at compilation time, declare and use a custom function in your enum.

public boolean isEquals(enumVariable) // compare constant from left
public static boolean areEqual(enumVariable, enumVariable2) // compare two variable

With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.

I also recommend to add an UNDEFINED value for enum.

How to replace a character from a String in SQL?

This will replace all ? with ':

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
WHERE city LIKE '%?%'

If you need to update more than one column, you can either change city each time you execute to a different column name, or list the columns like so:

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
      ,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'

HTML how to clear input using javascript?

Try this :

<script type="text/javascript">
function clearThis(target){
    if(target.value == "[email protected]")
    {
        target.value= "";
    }
}
</script>

How do I add a Font Awesome icon to input field?

to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution

in html:

   <span class="button1 search"></span>
<input name="username">

in css:

.button1 {
    background-color: #B9D5AD;
    border-radius: 0.2em 0 0 0.2em;
    box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5); 
    pointer-events: none;
    margin:1px 12px;    
    border-radius: 0.2em;    
    color: #333333;
    cursor: pointer;
    position: absolute;
    padding: 3px;
    text-decoration: none;   

}

Simplest way to form a union of two lists

If it is a list, you can also use AddRange method.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4, 5};

listA.AddRange(listB); // listA now has elements of listB also.

If you need new list (and exclude the duplicate), you can use Union

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Union(listB);

If you need new list (and include the duplicate), you can use Concat

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Concat(listB);

If you need common items, you can use Intersect.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4};  
var listFinal = listA.Intersect(listB); //3,4

How to tell Maven to disregard SSL errors (and trusting all certs)?

You can disable SSL certificate checking by adding one or more of these command line parameters:

  • -Dmaven.wagon.http.ssl.insecure=true - enable use of relaxed SSL check for user generated certificates.
  • -Dmaven.wagon.http.ssl.allowall=true - enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.
  • -Dmaven.wagon.http.ssl.ignore.validity.dates=true - ignore issues with certificate dates.

Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/

Here's the oneliner for an easy copy-and-paste:

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true

Ajay Gautam suggested that you could also add the above to the ~/.mavenrc file as not to have to specify it every time at command line:

$ cat ~/.mavenrc 
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

Converting HTML to Excel?

We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.

Kubernetes how to make Deployment to update image

I am using Azure DevOps to deploy the containerize applications, I am easily manage to overcome this problem by using the build ID

Everytime its builds and generate the new Build ID, I use this build ID as tag for docker image here is example

imagename:buildID

once your image is build (CI) successfully, in CD pipeline in deployment yml file I have give image name as

imagename:env:buildID

here evn:buildid is the azure devops variable which having value of build ID.

so now every time I have new changes to build(CI) and deploy(CD).

please comment if you need build definition for CI/CD.

How to join a slice of strings into a single string?

Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.

How to install PyQt4 on Windows using pip?

Earlier PyQt .exe installers were available directly from the website download page. Now with the release of PyQt4.12 , installers have been deprecated. You can make the libraries work somehow by compiling them but that would mean going to great lengths of trouble.

Otherwise you can use the previous distributions to solve your purpose. The .exe windows installers can be downloaded from :

https://sourceforge.net/projects/pyqt/files/PyQt4/PyQt-4.11.4/

What does ENABLE_BITCODE do in xcode 7?

Bitcode refers to to the type of code: "LLVM Bitcode" that is sent to iTunes Connect. This allows Apple to use certain calculations to re-optimize apps further (e.g: possibly downsize executable sizes). If Apple needs to alter your executable then they can do this without a new build being uploaded.

This differs from: Slicing which is the process of Apple optimizing your app for a user's device based on the device's resolution and architecture. Slicing does not require Bitcode. (Ex: only including @2x images on a 5s)

App Thinning is the combination of slicing, bitcode, and on-demand resources

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.

Apple Documentation on App Thinning

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Capturing URL parameters in request.GET

When a URL is like domain/search/?q=haha, you would use request.GET.get('q', '').

q is the parameter you want, and '' is the default value if q isn't found.

However, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments).

Such as:

(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),

Then in your views.py you would have

def profile_page(request, username):
    # Rest of the method

How do I make a Git commit in the past?

To make a commit that looks like it was done in the past you have to set both GIT_AUTHOR_DATE and GIT_COMMITTER_DATE:

GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git commit -m '...'

where date -d'...' can be exact date like 2019-01-01 12:00:00 or relative like 5 months ago 24 days ago.

To see both dates in git log use:

git log --pretty=fuller

This also works for merge commits:

GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git merge <branchname> --no-ff

How to decode a QR-code image in (preferably pure) Python?

The following code works fine with me:

brew install zbar
pip install pyqrcode
pip install pyzbar

For QR code image creation:

import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)

For QR code decoding:

from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)

that prints the result:

[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]

PHP - Fatal error: Unsupported operand types

$total_ratings is an array, which you can't use for a division.

From above:

$total_ratings = mysqli_fetch_array($result);

What's the difference between the atomic and nonatomic attributes?

Atomic means only one thread can access the variable at a time (static type). Atomic is thread-safe, but it is slow.

Nonatomic means multiple threads can access the variable at same time (dynamic type). Nonatomic is thread-unsafe, but it is fast.

How to get year/month/day from a date object?

info

If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)

code

var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);

output

2016/10/06

fiddle

https://jsfiddle.net/Hastig/1xuu7z7h/

credit

More info from and credit to this answer

more

To learn more about .slice the try it yourself editor at w3schools helped me understand better how to use it.

event.preventDefault() function not working in IE

I know this is quite an old post but I just spent some time trying to make this work in IE8.

It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.

Let's say that we have this code:

$('a').on('click', function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
});

In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.

Even if I set returnValue property directly to false:

$('a').on('click', function(event) {
    event.returnValue = false;
    event.preventDefault();
});

This also won't work, because I just set some property of jQuery custom event object.

Only solution that works for me is to set property returnValue of global variable event like this:

$('a').on('click', function(event) {
    if (window.event) {
        window.event.returnValue = false;
    }
    event.preventDefault();
});

Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.

UPDATE:

As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one. But I haven't tested it in my IE8 yet.

`React/RCTBridgeModule.h` file not found

I receive this error in any new module I create with create-react-native-module. None of the posted solutions worked for me.

What worked for me was first making sure to run yarn in the newly created module folder in order to create node_modules/ (this step is probably obvious). Then, in XCode, select Product -> Scheme -> React instead of the default selection of MyModuleName.

How to reset a timer in C#?

For clarity since some other comments are incorrect, when using System.Timers setting Enabled to true will reset the elapsed time. I just tested the behavior with the below:

Timer countDown= new Timer(3000);

Main()
{
    TextBox.TextDidChange += TextBox_TextDidChange;
    countdown.Elapsed += CountDown_Elapsed;
}

void TextBox_TextDidChange(Object sender, EventArgs e)
{
    countdown.Enabled = true;
}

void CountDown_Elapsed(object sender, EventArgs e)
{
    System.Console.WriteLine("Elapsed");
}

I would input text to the text box repeatedly and the timer would only run 3 seconds after the last keystroke. It's hinted at in the docs as well, as you'll see: calling Timers.Start() simply sets Enabled to true.

And to be sure, which I should've just went straight to from the beginning, you'll see in the .NET reference source that if enabling an already Enabled timer it calls the private UpdateTimer() method, which internally calls Change().

Firing a Keyboard Event in Safari, using JavaScript

Did you dispatch the event correctly?

function simulateKeyEvent(character) {
  var evt = document.createEvent("KeyboardEvent");
  (evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
                    0, 0, 0, 0,
                    0, character.charCodeAt(0)) 
  var canceled = !body.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

If you use jQuery, you could do:

function simulateKeyPress(character) {
  jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}

How do I get the information from a meta tag with JavaScript?

Way - [ 1 ]

function getMetaContent(property, name){
    return document.head.querySelector("["+property+"="+name+"]").content;
}
console.log(getMetaContent('name', 'csrf-token'));

You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 2 ]

function getMetaContent(name){
    return document.getElementsByTagName('meta')[name].getAttribute("content");
}
console.log(getMetaContent('csrf-token'));

You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 3 ]

function getMetaContent(name){
    name = document.getElementsByTagName('meta')[name];
    if(name != undefined){
        name = name.getAttribute("content");
        if(name != undefined){
            return name;
        }
    }
    return null;
}
console.log(getMetaContent('csrf-token'));

Instead getting error, you get null, that is good.

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

For Rails (at least in my case) if you are using the angularjs-rails gem, please remember to add the sanitize module

//= require angular
//= require angular-sanitize

And then load it up in your app...

var myDummyApp = angular.module('myDummyApp', ['ngSanitize']);

Then you can do the following:

On the template:

%span{"ng-bind-html"=>"phone_with_break(x)"}

And eventually:

$scope.phone_with_break = function (x) {
  if (x.phone != "") {
   return x.phone + "<br>";
  }
  return '';
}

How to get the size of a file in MB (Megabytes)?

You can retrieve the length of the file with File#length(), which will return a value in bytes, so you need to divide this by 1024*1024 to get its value in mb.

How to render html with AngularJS templates

You shoud follow the Angular docs and use $sce - $sce is a service that provides Strict Contextual Escaping services to AngularJS. Here is a docs: http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe

Let's take an example with asynchroniously loading Eventbrite login button

In your controller:

someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin', 
  function($scope, $sce, eventbriteLogin) {

    eventbriteLogin.fetchButton(function(data){
      $scope.buttonLogin = $sce.trustAsHtml(data);
    });
  }]);

In your view just add:

<span ng-bind-html="buttonLogin"></span>

In your services:

someAppServices.factory('eventbriteLogin', function($resource){
   return {
        fetchButton: function(callback){
            Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){
                callback(widget_html);
            })
      }
    }
});

Reverse colormap in matplotlib

The solution is pretty straightforward. Suppose you want to use the "autumn" colormap scheme. The standard version:

cmap = matplotlib.cm.autumn

To reverse the colormap color spectrum, use get_cmap() function and append '_r' to the colormap title like this:

cmap_reversed = matplotlib.cm.get_cmap('autumn_r')

Javascript: Unicode string to hex

Here you go. :D

"??".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
"6f225b57"

for non unicode

"hi".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
"6869"

ASCII (utf-8) binary HEX string to string

"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

String to ASCII (utf-8) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")

--- unicode ---

String to UNICODE (utf-16) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")

UNICODE (utf-16) binary HEX string to string

"00680065006c006c006f00200077006f0072006c00640021".match(/.{1,4}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

C# - How to get Program Files (x86) on Windows 64 bit

One-liner using the new method in .NET. Will always return x86 Program Files folder.

Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable("ProgramFiles(x86)") : Environment.GetEnvironmentVariable("ProgramFiles"))

Save PHP array to MySQL?

Serialize and unserialize are pretty common for that. You could also use JSON via json_encode and json_decode for a less PHP-specific format.

How to pass parameters in $ajax POST?

Try using GET method,

var request = $.ajax({
    url: 'url',
    type: 'GET',
    data: { field1: "hello", field2 : "hello2"} ,
    contentType: 'application/json; charset=utf-8'
});

request.done(function(data) {
      // your success code here
});

request.fail(function(jqXHR, textStatus) {
      // your failure code here
});

You cannot see parameters in URL with POST method.

Edit:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

RegEx for valid international mobile phone number

Even though it is about international numbers I would want the code to be like :

/^(\+|\d)[0-9]{7,16}$/;

As you can have international numbers starting with '00' as well.

Why I prefer 15 digits : http://en.wikipedia.org/wiki/E.164

How to generate a HTML page dynamically using PHP?

I've been working kind of similar to this and I have some code that might help you. The live example is here and below, is the code I'm using for you to have it as reference.

create-page.php

<?php

// Session is started.
session_start();

// Name of the template file.
$template_file = 'couples-template.php';

// Root folder if working in subdirectory. Name is up to you ut must match with server's folder.
$base_path = '/couple/';

// Path to the directory where you store the "couples-template.php" file.
$template_path = '../template/';

// Path to the directory where php will store the auto-generated couple's pages.
$couples_path = '../couples/';

// Posted data.
$data['groom-name'] = str_replace(' ', '', $_POST['groom-name']);
$data['bride-name'] = str_replace(' ', '', $_POST['bride-name']);
// $data['groom-surname'] = $_POST['groom-surname'];
// $data['bride-surname'] = $_POST['bride-surname'];
$data['wedding-date'] = $_POST['wedding-date'];
$data['email'] = $_POST['email'];
$data['code'] = str_replace(array('/', '-', ' '), '', $_POST['wedding-date']).strtoupper(substr($data['groom-name'], 0, 1)).urlencode('&').strtoupper(substr($data['bride-name'], 0, 1));

// Data array (Should match with data above's order).
$placeholders = array('{groom-name}', '{bride-name}', '{wedding-date}', '{email}', '{code}');

// Get the couples-template.php as a string.
$template = file_get_contents($template_path.$template_file);

// Fills the template.
$new_file = str_replace($placeholders, $data, $template);

// Generates couple's URL and makes it frendly and lowercase.
$couples_url = str_replace(' ', '', strtolower($data['groom-name'].'-'.$data['bride-name'].'.php'));

// Save file into couples directory.
$fp = fopen($couples_path.$couples_url, 'w');
fwrite($fp, $new_file);
fclose($fp);

// Set the variables to pass them to success page.
$_SESSION['couples_url'] = $couples_url;
// If working in root directory.
$_SESSION['couples_path'] = str_replace('.', '', $couples_path);
// If working in a sub directory.
//$_SESSION['couples_path'] = substr_replace($base_path, '', -1).str_replace('.', '',$couples_path);

header('Location: success.php');

?>

Hope this file can help and work as reference to start and boost your project.

How to check if String value is Boolean type in Java?

Can also do it by regex:

Pattern queryLangPattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = queryLangPattern.matcher(booleanParam);
return matcher.matches();

How to get all possible combinations of a list’s elements?

flag = 0
requiredCals =12
from itertools import chain, combinations

def powerset(iterable):
    s = list(iterable)  # allows duplicate elements
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

stuff = [2,9,5,1,6]
for i, combo in enumerate(powerset(stuff), 1):
    if(len(combo)>0):
        #print(combo , sum(combo))
        if(sum(combo)== requiredCals):
            flag = 1
            break
if(flag==1):
    print('True')
else:
    print('else')

How do I enable/disable log levels in Android?

You should use

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "my log message");
    }

Selenium Webdriver submit() vs click()

I was a great fan of submit() but not anymore.

In the web page that I test, I enter username and password and click Login. When I invoked usernametextbox.submit(), password textbox is cleared (becomes empty) and login keeps failing.

After breaking my head for sometime, when I replaced usernametextbox.submit() with loginbutton.click(), it worked like a magic.

Typescript export vs. default export

Here's example with simple object exporting.

var MyScreen = {

    /* ... */

    width : function (percent){

        return window.innerWidth / 100 * percent

    }

    height : function (percent){

        return window.innerHeight / 100 * percent

    }


};

export default MyScreen

In main file (Use when you don't want and don't need to create new instance) and it is not global you will import this only when it needed :

import MyScreen from "./module/screen";
console.log( MyScreen.width(100) );

add a temporary column with a value

You mean staticly define a value, like this:

SELECT field1, 
       field2,
       'example' AS newfield
  FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

Simple conversion between java.util.Date and XMLGregorianCalendar

From java.util.Date to XMLGregorianCalendar you can simply do:

import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import java.util.GregorianCalendar;
......
GregorianCalendar gcalendar = new GregorianCalendar();
gcalendar.setTime(yourDate);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcalendar);

Code edited after the first comment of @f-puras, by cause i do a mistake.

Hidden Features of C#?

Lambda Expressions

Func<int, int, int> add = (a, b) => (a + b);

Obscure String Formats

Console.WriteLine("{0:D10}", 2); // 0000000002

Dictionary<string, string> dict = new Dictionary<string, string> { 
    {"David", "C#"}, 
    {"Johann", "Perl"}, 
    {"Morgan", "Python"}
};

Console.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" );

Console.WriteLine( "-".PadRight( 21, '-' ) );

foreach (string key in dict.Keys)
{
    Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] );             
}

Fix CSS hover on iPhone/iPad/iPod

Where, I solved this problem by adding the visibility attribute to the CSS code, it works on my website

Original code:

_x000D_
_x000D_
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
_x000D_
_x000D_

Fixed iOS touch code:

_x000D_
_x000D_
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
_x000D_
_x000D_

Warning: Permanently added the RSA host key for IP address

If you are accessing your repositories over the SSH protocol, you will receive a warning message each time your client connects to a new IP address for github.com. As long as the IP address from the warning is in the range of IP addresses , you shouldn't be concerned. Specifically, the new addresses that are being added this time are in the range from 192.30.252.0 to 192.30.255.255. The warning message looks like this:

Warning: Permanently added the RSA host key for IP address '$IP' to the list of 

https://github.com/blog/1606-ip-address-changes

Get Max value from List<myType>

How about this way:

List<int> myList = new List<int>(){1, 2, 3, 4}; //or any other type
myList.Sort();
int greatestValue = myList[ myList.Count - 1 ];

You basically let the Sort() method to do the job for you instead of writing your own method. Unless you don't want to sort your collection.

Loop through all the files with a specific extension

Loop through all files ending with: .img, .bin, .txt suffix, and print the file name:

for i in *.img *.bin *.txt;
do
  echo "$i"
done

Or in a recursive manner (find also in all subdirectories):

for i in `find . -type f -name "*.img" -o -name "*.bin" -o -name "*.txt"`;
do
  echo "$i"
done

Edit seaborn legend

If you just want to change the legend title, you can do the following:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=True
)

g._legend.set_title("New Title")

Autocompletion in Vim

You can start from built-in omnifunc setting.

Just put:

filetype plugin on
au FileType php setl ofu=phpcomplete#CompletePHP
au FileType ruby,eruby setl ofu=rubycomplete#Complete
au FileType html,xhtml setl ofu=htmlcomplete#CompleteTags
au FileType c setl ofu=ccomplete#CompleteCpp
au FileType css setl ofu=csscomplete#CompleteCSS

on the bottom of your .vimrc, then type <Ctrl-X><Ctrl-O> in insert mode.

I always rely on this CSS completion.

Add Whatsapp function to website, like sms, tel

This is possible by creating the following link:

whatsapp://send?text=Hello this has been opened from the browser&phone=+PHONENUMBER&abid=+PHONENUMBER

Thanks to:

https://forum.ionicframework.com/t/open-whatsapp-intent-with-msg-specific-contact/73903/4

I have tested this on iOS, Windows Phone and Android

Vue - Deep watching an array of objects and calculating the change?

The component solution and deep-clone solution have their advantages, but also have issues:

  1. Sometimes you want to track changes in abstract data - it doesn't always make sense to build components around that data.

  2. Deep-cloning your entire data structure every time you make a change can be very expensive.

I think there's a better way. If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
  },
  methods: {
    handleChange (newVal) {
      // Handle changes here!
      console.log(newVal);
    },
  },
  created () {
    this.list.forEach((val) => {
      this.$watch(() => val, this.handleChange, {deep: true});
    });
  },
});

With this structure, handleChange() will receive the specific list item that changed - from there you can do any handling you like.

I have also documented a more complex scenario here, in case you are adding/removing items to your list (rather than only manipulating the items already there).

link button property to open in new tab?

When the LinkButton Enabled property is false it just renders a standard hyperlink. When you right click any disabled hyperlink you don't get the option to open in anything.

try

lbnkVidTtile1.Enabled = true;

I'm sorry if I misunderstood. Could I just make sure that you understand the purpose of a LinkButton? It is to give the appearance of a HyperLink but the behaviour of a Button. This means that it will have an anchor tag, but there is JavaScript wired up that performs a PostBack to the page. If you want to link to another page then it is recommended here that you use a standard HyperLink control.

node.js http 'get' request with query string parameters

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured network.

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

Finding first blank row, then writing to it

very old thread but .. i was lookin for an "easier"... a smaller code

i honestly dont understand any of the answers above :D - i´m a noob

but this should do the job. (for smaller sheets)

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Add

reads every cell in col 1 from bottom up and stops at first empty cell

intRow = 1
Do until objExcel.Cells(intRow, 1).Value = ""
   intRow = intRow + 1
Loop

then you can write your info like this

objExcel.Cells(intRow, 1).Value = "first emtpy row, col 1"
objExcel.Cells(intRow, 2).Value = "first emtpy row, col 2"

etc...

and then i recognize its an vba thread ... lol

Create File If File Does Not Exist

This will enable appending to file using StreamWriter

 using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}

This is default mode, not append to file and create a new file.

using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
                           or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}

Anyhow if you want to check if the file exists and then do other things,you can use

using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
            {...}

git: fatal: I don't handle protocol '??http'

Mostly it is due to some invisible unicode characters which can come if you hit "Ctrl+V" or "Ctrl+Shift+V" in the terminal. Don't copy and paste the whole command. Instead , type git clone and then copy and paste the url using Right Click + Paste.

babel-loader jsx SyntaxError: Unexpected token

Add "babel-preset-react"

npm install babel-preset-react

and add "presets" option to babel-loader in your webpack.config.js

(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)

Here is an example webpack.config.js:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
      {
        presets:['react']
      }
}

Recently Babel 6 was released and there was a major change: https://babeljs.io/blog/2015/10/29/6.0.0

If you are using react 0.14, you should use ReactDOM.render() (from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog

UPDATE 2018

Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:

npm install babel-loader babel-preset-react

Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['react']
        }
      }
    ],
  }

Difference between os.getenv and os.environ.get

While there is no functional difference between os.environ.get and os.getenv, there is a massive difference between os.putenv and setting entries on os.environ. os.putenv is broken, so you should default to os.environ.get simply to avoid the way os.getenv encourages you to use os.putenv for symmetry.

os.putenv changes the actual OS-level environment variables, but in a way that doesn't show up through os.getenv, os.environ, or any other stdlib way of inspecting environment variables:

>>> import os
>>> os.environ['asdf'] = 'fdsa'
>>> os.environ['asdf']
'fdsa'
>>> os.putenv('aaaa', 'bbbb')
>>> os.getenv('aaaa')
>>> os.environ.get('aaaa')

You'd probably have to make a ctypes call to the C-level getenv to see the real environment variables after calling os.putenv. (Launching a shell subprocess and asking it for its environment variables might work too, if you're very careful about escaping and --norc/--noprofile/anything else you need to do to avoid startup configuration, but it seems a lot harder to get right.)

Is there a java setting for disabling certificate validation?

In Axis webservice and if you have to disable the certificate checking then use below code:

AxisProperties.setProperty("axis.socketSecureFactory","org.apache.axis.components.net.SunFakeTrustSocketFactory");

Opening a new tab to read a PDF file

Will open your pdf in a new tab with pdf viewer and can download too

<a className=""
   href="/project_path_to_your_pdf_asset/failename.pdf"
   target="_blank"
>
   View PDF
</a>

Windows command to get service status?

Well I'm not sure about whether you can email the results of that from a batch file. If I may make an alternate suggestion that would solve your problem vbscript. I am far from great with vbscript but you can use it to query the services running on the local machine. The script below will email you the status of all of the services running on the machine the script gets run on. You'll obviously want to replace the smtp server and the email address. If you're part of a domain and you run this script as a privileged user (they have to be an administrator on the remote machine) you can query remote machines as well by replacing localhost with the fqdn.

Dim objComputer, objMessage
Dim strEmail

' If there is an error getting the status of a service it will attempt to move on to the next one
On Error Resume Next

' Email Setup
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Service Status Report"
objMessage.From = "[email protected]"
objMessage.To = "[email protected]"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.example.net"

'Server port (typically 25)
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

Set objComputer = GetObject("WinNT://localhost")
objComputer.Filter = Array("Service")

For Each aService In objComputer
strEmail = strEmail &chr(10) & aService.Name & "=" & aService.Status
Next

objMessage.TextBody = strEmail
objMessage.Configuration.Fields.Update
objMessage.Send

Hope this helps you! Enjoy!

Edit: Ahh one more thing a service status of 4 means the service is running, a service status of 1 means it's not. I'm not sure what 2 or 3 means but I'm willing to bet they are stopping/starting.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

In ASP.NET Core MVC.

    public IActionResult Foo()
    {
        var data = GetData();

        var settings = new JsonSerializerSettings 
        { 
            ContractResolver = new CamelCasePropertyNamesContractResolver() 
        });

        return Json(data, settings);
    }

How to save all console output to file in R?

You have to sink "output" and "message" separately (the sink function only looks at the first element of type)

Now if you want the input to be logged too, then put it in a script:

script.R

1:5 + 1:3   # prints and gives a warning
stop("foo") # an error

And at the prompt:

con <- file("test.log")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")

# This will echo all input and not truncate 150+ character lines...
source("script.R", echo=TRUE, max.deparse.length=10000)

# Restore output to console
sink() 
sink(type="message")

# And look at the log...
cat(readLines("test.log"), sep="\n")

setting request headers in selenium

Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.

Here are a couple of possibilities that I can propose:

  1. Use another driver/library instead of selenium
  2. Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
  3. Use browsermob-proxy or some other proxy.

I'd go with option 3 in most of cases. It's not hard.

Note that Ghostdriver has an API for it but it's not supported by other drivers.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

OK, so first of all the http://angular-ui.github.io/bootstrap/ has a <modal> directive and the $dialog service and both of those can be used to open modal windows.

The difference is that with the <modal> directive content of a modal is embedded in a hosting template (one that triggers modal window opening). The $dialog service is far more flexible and allow you to load modal's content from a separate file as well as trigger modal windows from any place in AngularJS code (this being a controller, a service or another directive).

Not sure what you mean exactly by "using JavaScript code" but assuming that you mean any place in AngularJS code the $dialog service is probably a way to go.

It is very easy to use and in its simplest form you could just write:

$dialog.dialog({}).open('modalContent.html');  

To illustrate that it can be really triggered by any JavaScript code here is a version that triggers modal with a timer, 3 seconds after a controller was instantiated:

function DialogDemoCtrl($scope, $timeout, $dialog){
  $timeout(function(){
    $dialog.dialog({}).open('modalContent.html');  
  }, 3000);  
}

This can be seen in action in this plunk: http://plnkr.co/edit/u9HHaRlHnko492WDtmRU?p=preview

Finally, here is the full reference documentation to the $dialog service described here: https://github.com/angular-ui/bootstrap/blob/master/src/dialog/README.md

SQL: How to get the id of values I just INSERTed?

Again no language agnostic response, but in Java it goes like this:

Connection conn = Database.getCurrent().getConnection();  
PreparedStatement ps =  conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
try {  
    ps.executeUpdate();  
    ResultSet rs = ps.getGeneratedKeys();  
    rs.next();  
    long primaryKey = rs.getLong(1);  
} finally {  
    ps.close();  
}  

WebView and Cookies on Android

I figured out what's going on.

When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.

You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.

  WebView webview = new WebView(this);      
  webview.setWebViewClient(new WebViewClient() {  
      @Override  
      public boolean shouldOverrideUrlLoading(WebView view, String url)  
      {  
        view.loadUrl(url); //this is controversial - see comments and other answers
        return true;  
      }  
    });                 
  setContentView(webview);      
  webview.loadUrl([MY URL]);

This fixes the problem.

How to write loop in a Makefile?

THE major reason to use make IMHO is the -j flag. make -j5 will run 5 shell commands at once. This is good if you have 4 CPUs say, and a good test of any makefile.

Basically, you want make to see something like:

.PHONY: all
all: job1 job2 job3

.PHONY: job1
job1: ; ./a.out 1

.PHONY: job2
job2: ; ./a.out 2

.PHONY: job3
job3: ; ./a.out 3

This is -j friendly (a good sign). Can you spot the boiler-plate? We could write:

.PHONY: all job1 job2 job3
all: job1 job2 job3
job1 job2 job3: job%:
    ./a.out $*

for the same effect (yes, this is the same as the previous formulation as far as make is concerned, just a bit more compact).

A further bit of parameterisation so that you can specify a limit on the command-line (tedious as make does not have any good arithmetic macros, so I'll cheat here and use $(shell ...))

LAST := 1000
NUMBERS := $(shell seq 1 ${LAST})
JOBS := $(addprefix job,${NUMBERS})
.PHONY: all ${JOBS}
all: ${JOBS} ; echo "$@ success"
${JOBS}: job%: ; ./a.out $*

You run this with make -j5 LAST=550, with LAST defaulting to 1000.

Get column index from column name in python pandas

To modify DSM's answer a bit, get_loc has some weird properties depending on the type of index in the current version of Pandas (1.1.5) so depending on your Index type you might get back an index, a mask, or a slice. This is somewhat frustrating for me because I don't want to modify the entire columns just to extract one variable's index. Much simpler is to avoid the function altogether:

list(df.columns).index('pear')

Very straightforward and probably fairly quick.

How to create the branch from specific commit in different branch

You can do this locally as everyone mentioned using

git checkout -b <branch-name> <sha1-of-commit>

Alternatively, you can do this in github itself, follow the steps:

1- In the repository, click on the Commits.

2- on the commit you want to branch from, click on <> to browse the repository at this point in the history.

commits history

3- Click on the tree: xxxxxx in the upper left. Just type in a new branch name there click Create branch xxx as shown below.

create new branch

Now you can fetch the changes from that branch locally and continue from there.

Ignoring SSL certificate in Apache HttpClient 4.3

When using http client 4.5 I had to use the javasx.net.ssl.HostnameVerifier to allow any hostname (for testing purposes). Here is what I ended up doing:

CloseableHttpClient httpClient = null;
    try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        HostnameVerifier hostnameVerifierAllowAll = new HostnameVerifier() 
            {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifierAllowAll);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope("192.168.30.34", 8443),
            new UsernamePasswordCredentials("root", "password"));

        httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslSocketFactory)
            .setDefaultCredentialsProvider(credsProvider)
            .build();

        HttpGet httpGet = new HttpGet("https://192.168.30.34:8443/axis/services/getStuff?firstResult=0&maxResults=1000");

        CloseableHttpResponse response = httpClient.execute(httpGet);

        int httpStatus = response.getStatusLine().getStatusCode();
        if (httpStatus >= 200 && httpStatus < 300) { [...]
        } else {
            throw new ClientProtocolException("Unexpected response status: " + httpStatus);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            logger.error("Error while closing the HTTP client: ", ex);
        }
    }

How to use relative paths without including the context root name?

Instead using entire link we can make as below (solution concerns jsp files)

With JSTL we can make it like: To link resource like css, js:

     <link rel="stylesheet" href="${pageContext.request.contextPath}/style/sample.css" />
     <script src="${pageContext.request.contextPath}/js/sample.js"></script>   

To simply make a link:

     <a id=".." class=".." href="${pageContext.request.contextPath}/jsp/sample.jsp">....</a>

It's worth to get familiar with tags

   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

There is also jsp method to do it like below, but better way like above:

   <link rel="stylesheet" href="<%=request.getContextPath()%>/style/sample.css" />
   <script type="text/javascript" src="<%=request.getContextPath()%>/js/sample.js"></script>

To simply make a link:

   <a id=".." class=".." href="<%=request.getContextPath()%>/jsp/sample.jsp">....</a>

How to assign string to bytes array

For converting from a string to a byte slice, string -> []byte:

[]byte(str)

For converting an array to a slice, [20]byte -> []byte:

arr[:]

For copying a string to an array, string -> [20]byte:

copy(arr[:], str)

Same as above, but explicitly converting the string to a slice first:

copy(arr[:], []byte(str))

  • The built-in copy function only copies to a slice, from a slice.
  • Arrays are "the underlying data", while slices are "a viewport into underlying data".
  • Using [:] makes an array qualify as a slice.
  • A string does not qualify as a slice that can be copied to, but it qualifies as a slice that can be copied from (strings are immutable).
  • If the string is too long, copy will only copy the part of the string that fits.

This code:

var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)\n", arr, arr)

...gives the following output:

array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)

I also made it available at the Go Playground

Android java.exe finished with non-zero exit value 1

Had the same error encountered which was due to conflicting drawable resources. I did a clean project and the error was no longer encountered.

Handle Guzzle exception and get HTTP body

None of the above responses are working for error that has no body but still has some describing text. For me, it was SSL certificate problem: unable to get local issuer certificate error. So I looked right into the code, because doc does't really say much, and did this (in Guzzle 7.1):

try {
    // call here
} catch (\GuzzleHttp\Exception\RequestException $e) {
    if ($e->hasResponse()) {
        $response = $e->getResponse();
        // message is in $response->getReasonPhrase()
    } else {
        $response = $e->getHandlerContext();
        if (isset($response['error'])) {
            // message is in $response['error']
        } else {
            // Unknown error occured!
        }
    }
}

javascript regex for special characters

a sleaker way to match special chars:

/\W|_/g

\W Matches any character that is not a word character (alphanumeric & underscore).

Underscore is considered a special character so add boolean to either match a special character or _

Set folder browser dialog start location

To set the directory selected path and the retrieve the new directory:

dlgBrowseForLogDirectory.SelectedPath = m_LogDirectory;
if (dlgBrowseForLogDirectory.ShowDialog() == DialogResult.OK)
{
     txtLogDirectory.Text = dlgBrowseForLogDirectory.SelectedPath;
}

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

Get Image Height and Width as integer values?

Try like this:

list($width, $height) = getimagesize('path_to_image');

Make sure that:

  1. You specify the correct image path there
  2. The image has read access
  3. Chmod image dir to 755

Also try to prefix path with $_SERVER["DOCUMENT_ROOT"], this helps sometimes when you are not able to read files.

Can a Byte[] Array be written to a file in C#?

Yep, why not?

fs.Write(myByteArray, 0, myByteArray.Length);

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:

ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() ); 

Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.

Code that does AES encyrption:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Test 
{
    final String ALGORITHM = "AES";                       //symmetric algorithm for data encryption
    final String PADDING_MODE = "/CBC/PKCS5Padding";      //Padding for symmetric algorithm
    final String CHAR_ENCODING = "UTF-8";                 //character encoding
    //final String CRYPTO_PROVIDER = "SunMSCAPI";             //provider for the crypto

    int AES_KEY_SIZE = 256;  //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files  installed

    private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
    {
        byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);

        //get the symmetric key generator
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(AES_KEY_SIZE); //set the key size

        //generate the key
        SecretKey skey = keyGen.generateKey();

        //convert to binary
        byte[] rawAesKey = skey.getEncoded();

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);

        //set it to encrypt mode, with the generated key
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        //get the initialization vector being used (to be returned)
        byte[] aesIV = aesCipher.getIV();

        //encrypt the data
        byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);    

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);

        //set it to decrypt mode with the AES key, and IV
        aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));

        //decrypt and return the data
        byte[] decryptedData = aesCipherDec.doFinal(encryptedData);

        return new String(decryptedData, CHAR_ENCODING);
    }

    public static void main(String[] args)
    {
        String text = "Lets encrypt me";

        Test test = new Test();

        try {
            System.out.println(test.doCrypto(text));
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Does this code work for you?

You might also want to try specifying your bouncy castle provider in this line:

Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");

And see if it could be an error associated with bouncy castle.

SecurityException: Permission denied (missing INTERNET permission?)

I also had this problem. it was weird that it worked on my lollipop emulator, but not on my actual kitkat device.

Android Studio will now force you to write the permission upper case, and that's the problem.

Add

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

Above the application tab and it will work.

What's the proper way to compare a String to an enum value?

Doing an static import of the GestureTypes and then using the valuesOf() method could make it look much cleaner:

enum GestureTypes{ROCK,PAPER,SCISSORS};

and

import static com.example.GestureTypes.*;
public class GestureFactory {

    public static Gesture getInstance(final String gesture) {
        if (ROCK == valueOf(gesture))
            //do somthing
        if (PAPER == valueOf(gesture))
            //do somthing
    }
}

How to position one element relative to another with jQuery?

This is what worked for me in the end.

var showMenu = function(el, menu) {
    //get the position of the placeholder element  
    var pos = $(el).offset();    
    var eWidth = $(el).outerWidth();
    var mWidth = $(menu).outerWidth();
    var left = (pos.left + eWidth - mWidth) + "px";
    var top = 3+pos.top + "px";
    //show the menu directly over the placeholder  
    $(menu).css( { 
        position: 'absolute',
        zIndex: 5000,
        left: left, 
        top: top
    } );

    $(menu).hide().fadeIn();
};

SQL subquery with COUNT help

This is probably the easiest way, not the prettiest though:

SELECT *,
    (SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
    FROM eventsTable
    WHERE columnName = 'Business'

This will also work without having to use a group by

SELECT *, COUNT(*) OVER () as RowCount
    FROM eventsTables
    WHERE columnName = 'Business'

What is the difference between . (dot) and $ (dollar sign)?

The $ operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.

For example, let's say you've got a line that reads:

putStrLn (show (1 + 1))

If you want to get rid of those parentheses, any of the following lines would also do the same thing:

putStrLn (show $ 1 + 1)
putStrLn $ show (1 + 1)
putStrLn $ show $ 1 + 1

The primary purpose of the . operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.

Going back to the same example:

putStrLn (show (1 + 1))
  1. (1 + 1) doesn't have an input, and therefore cannot be used with the . operator.
  2. show can take an Int and return a String.
  3. putStrLn can take a String and return an IO ().

You can chain show to putStrLn like this:

(putStrLn . show) (1 + 1)

If that's too many parentheses for your liking, get rid of them with the $ operator:

putStrLn . show $ 1 + 1

Delete rows containing specific strings in R

You can use this function if it's multiple string df[!grepl("REVERSE|GENJJS", df$Name),]

Best way to pass parameters to jQuery's .load()

As Davide Gualano has been told. This one

$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")

use GET method for sending the request, and this one

$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.

For example: url length limits the amount of sending data in GET method.

How to make div occupy remaining height?

Demo

One way is to set the the div to position:absolute and give it a top of 50px and bottom of 0px;

#div2
{
    position:absolute;
    bottom:0px;
    top:50px
}

Unable to merge dex

[ UNABLE TO MERGE DEX SOLVED ] After hours of stack overflowing I resolved the " UNABLE TO MERGE DEX ERROR "

  1. Update all the com.android.support lines in your gradle to v27.1.0

Cause - Android has updated it support libraries to v27.1.0, so you have to change all the android support lines in your gradle file to 27.1.0 from 26.1.0

  1. Make sure that the repositories section includes a maven section with the "https://maven.google.com" endpoint. For example:

    allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } }

Cause :- Android cannot update the support libraries in the SDK manager and now it uses maven.google.com to update , so you have to include this to use 27.1.0 support libraries

After Change Version: 1. Clean Project 2. Rebuild Project

Run script on mac prompt "Permission denied"

You should run the script as 'superuser', just add 'sudo' in front of the command and type your password when prompted.

So try:

sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme

If this doesn't work, try adapting the permissions:

sudo chmod 755 /dvtcolorconvert.rb
sudo chmod 755 ~/Themes/ObsidianCode.xccolortheme

NSRange to Range<String.Index>

In Swift 2.0 assuming func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {:

var oldString = textfield.text!
let newRange = oldString.startIndex.advancedBy(range.location)..<oldString.startIndex.advancedBy(range.location + range.length)
let newString = oldString.stringByReplacingCharactersInRange(newRange, withString: string)

"java.lang.OutOfMemoryError: PermGen space" in Maven build

This very annoying error so what I did: Under Windows:

Edit system environment variables - > Edit Variables -> New

then fill

MAVEN_OPTS
-Xms512m -Xmx2048m -XX:MaxPermSize=512m

enter image description here

Then restart the console and run the maven build again. No more Maven space/perm size problems.

Android checkbox style

The correct way to do it for Material design is :

Style :

<style name="MyCheckBox" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/foo</item>
    <item name="colorControlActivated">@color/bar</item>
</style>  

Layout :

<CheckBox  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Check Box"
    android:theme="@style/MyCheckBox"/>

It will preserve Material animations on Lollipop+.

How to find third or n?? maximum salary from salary table?

You can try this:

select top(1) EXPORT_NO
from DC_HDR 
order by CASE when  (ROW_NUMBER() over(order by EXPORT_NO desc))=3 then EXPORT_NO else 0 end desc

How to compile C++ under Ubuntu Linux?

Yes, use g++ to compile. It will automatically add all the references to libstdc++ which are necessary to link the program.

g++ source.cpp -o source

If you omit the -o parameter, the resultant executable will be named a.out. In any case, executable permissions have already been set, so no need to chmod anything.

Also, the code will give you undefined behaviour (and probably a SIGSEGV) as you are dereferencing a NULL pointer and trying to call a member function on an object that doesn't exist, so it most certainly will not print anything. It will probably crash or do some funky dance.

Why does dividing two int not yield the right value when assigned to double?

With very few exceptions (I can only think of one), C++ determines the entire meaning of an expression (or sub-expression) from the expression itself. What you do with the results of the expression doesn't matter. In your case, in the expression a / b, there's not a double in sight; everything is int. So the compiler uses integer division. Only once it has the result does it consider what to do with it, and convert it to double.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

Return rows in random order

SQL Server / MS Access Syntax:

SELECT TOP 1 * FROM table_name ORDER BY RAND()

MySQL Syntax:

SELECT * FROM table_name ORDER BY RAND() LIMIT 1

Determine if JavaScript value is an "integer"?

Use jQuery's IsNumeric method.

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

if ($.isNumeric(id)) {
   //it's numeric
}

CORRECTION: that would not ensure an integer. This would:

if ( (id+"").match(/^\d+$/) ) {
   //it's all digits
}

That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works

Shell Script Syntax Error: Unexpected End of File

echo"==================PS COMMAND SNAPSHOT=============================================================="

needs to be

echo "==================PS COMMAND SNAPSHOT=============================================================="

Else, a program or command named echo"===... is searched.

more problems:

If you do a grep (-A1: + 1 line context)

grep -A1 "if " cldtest.sh 

you find some embedded ifs, and 4 if/then blocks.

grep "fi " cldtest.sh 

only reveals 3 matching fi statements. So you forgot one fi too.

I agree with camh, that correct indentation from the beginning helps to avoid such errors. Finding the desired way later means double work in such spaghetti code.