Programs & Examples On #Blogs

A hip and trendy journal for the web. Should be used for rare questions about blogs, not questions on specific blogging software. See: [wordpress]

Update query PHP MySQL

Need to add quote for that need to use dot operator:

mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");

Formatting code snippets for blogging on Blogger

To post your html, javascript,c# and java you should convert special characters to HTML code. as '<' as &lt; and '>' to &gt; and e.t.c..

Add this link Code Converter to iGoogle. This will help you to convert the special characters.

Then add SyntaxHighlighter 3.0.83 new version to customize your code in blogger. But you should know How to configure the syntaxHighlighter in your blogger template.

Create a shortcut on Desktop

I use "Windows Script Host Object Model" reference to create shortcut.

Adding "Windows Script Host Object Model" to project references

and to create shortcut on specific location:

    void CreateShortcut(string linkPath, string filename)
    {
        // Create shortcut dir if not exists
        if (!Directory.Exists(linkPath))
            Directory.CreateDirectory(linkPath);

        // shortcut file name
        string linkName = Path.ChangeExtension(Path.GetFileName(filename), ".lnk");

        // COM object instance/props
        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkName);
        sc.Description = "some desc";
        //shortcut.IconLocation = @"C:\..."; 
        sc.TargetPath = linkPath;
        // save shortcut to target
        sc.Save();
    }

How to increase application heap size in Eclipse?

In the run configuration you want to customize (just click on it) open the tab Arguments and add -Xmx2048min the VM arguments section. You might want to set the -Xms as well (small heap size).

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

Appending a line break to an output file in a shell script

this also works, and prolly is more readable than the echo version:

printf "`date` User `whoami` started the script.\r\n" >> output.log

Application Crashes With "Internal Error In The .NET Runtime"

In my case the problem was related to "Referencing .NET standard library in classic asp.net projects" and these two issues

https://github.com/dotnet/standard/issues/873

https://github.com/App-vNext/Polly/issues/628

and downgrading to Polly v6 was enough to workaround it

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Placeholder in IE9

I know I'm late but I found a solution inserting in the head the tag:

_x000D_
_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <!--FIX jQuery INTERNET EXPLORER-->
_x000D_
_x000D_
_x000D_

How to select an item from a dropdown list using Selenium WebDriver with java?

Use -

new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");

Of course, you need to import org.openqa.selenium.support.ui.Select;

Iterate a list with indexes in Python

Here it is a solution using map function:

>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]

And a solution using list comprehensions:

>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]

Difference in boto3 between resource, client, and session?

I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.

Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )

sqs = boto3.client('sqs')
s3 = boto3.resource('s3')

Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.

# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')

# you have two choices of create custom client session. 
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')

Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.

import boto3 
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket') 
video_bucket = video_s3.Bucket('videobucket')

# just pass the instantiated bucket object
def list_bucket_contents(bucket):
   for object in bucket.objects.all():
      print(object.key)

list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)

Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.

For example, if you only deal with the default session, this looks similar to boto3.resource.

import boto3 
s3 = boto3.client('s3')

def list_bucket_contents(bucket_name):
   for object in s3.list_objects_v2(Bucket=bucket_name) :
      print(object.key)

list_bucket_contents('Mybucket') 

However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.

import boto3 
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')

# you must pass boto3.Session.client and the bucket name 
def list_bucket_contents(s3session, bucket_name):
   response = s3session.list_objects_v2(Bucket=bucket_name)
   if 'Contents' in response:
     for obj in response['Contents']:
        print(obj['key'])

list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket') 

How can I remove a commit on GitHub?

It is not very good to re-write the history. If we use git revert <commit_id>, it creates a clean reverse-commit of the said commit id.

This way, the history is not re-written, instead, everyone knows that there has been a revert.

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

How can I get file extensions with JavaScript?

var file = "hello.txt";
var ext = (function(file, lio) { 
  return lio === -1 ? undefined : file.substring(lio+1); 
})(file, file.lastIndexOf("."));

// hello.txt -> txt
// hello.dolly.txt -> txt
// hello -> undefined
// .hello -> hello

Setting a property with an EventTrigger

Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.

If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.

Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.

    <StackPanel x:Name="myStackPanel">

        <CheckBox x:Name="myCheckBox"
                  Content="My CheckBox" />

        <Button Content="Click to Uncheck"
                x:Name="myUncheckButton" />

        <Button Content="Click to check the box in code."
                Click="OnClick" />

        <StackPanel.Triggers>

            <EventTrigger RoutedEvent="Button.Click"
                          SourceName="myUncheckButton">
                <EventTrigger.Actions>
                    <BeginStoryboard x:Name="myBeginStoryboard">
                        <Storyboard x:Name="myStoryboard">
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
                                                            Storyboard.TargetProperty="IsChecked">
                                <DiscreteBooleanKeyFrame KeyTime="00:00:00"
                                                         Value="False" />
                            </BooleanAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>

            <EventTrigger RoutedEvent="CheckBox.Click"
                          SourceName="myCheckBox">
                <EventTrigger.Actions>
                    <StopStoryboard BeginStoryboardName="myBeginStoryboard" />
                </EventTrigger.Actions>
            </EventTrigger>

        </StackPanel.Triggers>
    </StackPanel>

To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.

We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.

    private void OnClick(object sender, RoutedEventArgs e)
    {
        myStoryboard.Remove(myStackPanel);
        myCheckBox.IsChecked = true;
    }

Fixed height and width for bootstrap carousel

To have a consistent flow of the images on different devices, you'd have to specify the width and height value for each carousel image item, for instance here in my example the image would take the full width but with a height of "400px" (you can specify your personal value instead)

<div class="item">
        <img src="image.jpg" style="width:100%; height: 400px;">
      </div>

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

Because Java bytecode does not retain the names of method or constructor arguments.

Resizing an image in an HTML5 canvas

i got this image by right clicking the canvas element in firefox and saving as.

alt text

var img = new Image();
img.onload = function () {
    console.debug(this.width,this.height);
    var canvas = document.createElement('canvas'), ctx;
    canvas.width = 188;
    canvas.height = 150;
    document.body.appendChild(canvas);
    ctx = canvas.getContext('2d');
    ctx.drawImage(img,0,0,188,150);
};
img.src = 'original.jpg';

so anyway, here is a 'fixed' version of your example:

var img = new Image();
// added cause it wasnt defined
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);

var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
// adding it to the body

document.body.appendChild(canvasCopy);

var copyContext = canvasCopy.getContext("2d");

img.onload = function()
{
        var ratio = 1;

        // defining cause it wasnt
        var maxWidth = 188,
            maxHeight = 150;

        if(img.width > maxWidth)
                ratio = maxWidth / img.width;
        else if(img.height > maxHeight)
                ratio = maxHeight / img.height;

        canvasCopy.width = img.width;
        canvasCopy.height = img.height;
        copyContext.drawImage(img, 0, 0);

        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;
        // the line to change
        // ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
        // the method signature you are using is for slicing
        ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);
};

// changed for example
img.src = 'original.jpg';

Display UIViewController as Popup in iPhone

Modal Popups in Interface Builder (Storyboards)

Step 1

On the ViewController you want as your modal popup, make the background color of the root UIView clear. Set Clear Color on root view Tip: Do not use the root UIView as your popup. Add a new UIView that is smaller to be your popup.

Step 2

Create a Segue to the ViewController that has your popup. Select "Present Modally". Segue

Two Methods To Create Popup From Here

Method One - Using the Segue

Select the Segue and change Presentation to "Over Current Context": Over Current Context

Method Two - Using the View Controller

Select the ViewController Scene that is your popup. In Attributes Inspector, under View Controller section, set Presentation to "Over Current Context": ViewController

Either method will work. That should do it!

Finished Product

Purge or recreate a Ruby on Rails database

Use like

rake db:drop db:create db:migrate db:seed

All in one line. This is faster since the environment doesn't get reloaded again and again.

db:drop - will drop database.

db:create - will create database (host/db/password will be taken from config/database.yml)

db:migrate - will run existing migrations from directory (db/migration/.rb)*.

db:seed - will run seed data possible from directory (db/migration/seed.rb)..

I usually prefer:

rake db:reset

to do all at once.

Cheers!

PostgreSQL function for last inserted ID

You can use RETURNING id after insert query.

INSERT INTO distributors (id, name) VALUES (DEFAULT, 'ALI') RETURNING id;

and result:

 id 
----
  1

In the above example id is auto-increment filed.

Scatter plot with error bars

To summarize Laryx Decidua's answer:

define and use a function like the following

plot.with.errorbars <- function(x, y, err, ylim=NULL, ...) {
  if (is.null(ylim))
    ylim <- c(min(y-err), max(y+err))
  plot(x, y, ylim=ylim, pch=19, ...)
  arrows(x, y-err, x, y+err, length=0.05, angle=90, code=3)
}

where one can override the automatic ylim, and also pass extra parameters such as main, xlab, ylab.

How can I round a number in JavaScript? .toFixed() returns a string?

Why not * the result by 1 i.e

someNumber.toFixed(2) * 1

Create a file if one doesn't exist - C

You typically have to do this in a single syscall, or else you will get a race condition.

This will open for reading and writing, creating the file if necessary.

FILE *fp = fopen("scores.dat", "ab+");

If you want to read it and then write a new version from scratch, then do it as two steps.

FILE *fp = fopen("scores.dat", "rb");
if (fp) {
    read_scores(fp);
}

// Later...

// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
    error();
write_scores(fp);

Change Text Color of Selected Option in a Select Box

You could do it like this.

jsFiddle

JS

var select = document.getElementById('mySelect');
select.onchange = function () {
    select.className = this.options[this.selectedIndex].className;
}

CSS

.redText {
    background-color:#F00;
}
.greenText {
    background-color:#0F0;
}
.blueText {
    background-color:#00F;
}

You could use option { background-color: #FFF; } if you want the list to be white.

HTML

<select id="mySelect" class="greenText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

Since this is a select it doesn't really make sense to use .yellowText as none selected if that's what you were getting at as something must be selected.

How to know the version of pip itself

For windows just type:

python -m pip --version

Error loading the SDK when Eclipse starts

Feel tired deleting the android-wear related packages each time upgrading the sdk?

Try to make some changes to devices.xml as following, you can edit the files by hand, or use some batching tools like repl.

repl is written by me, add this line to sources.list and install:

echo 'http://deb.bodz.net/ unstable/' >>/etc/apt/sources.list
alias sagu='sudo apt-get update'
alias sagi='sudo apt-get install'
sagu
sagi repl

Then, remove those <d:skin> lines and replace ###dpi to hdpi or whatever.

repl -r --filter=devices.xml --mode=regexp -- '<d:skin>.*</d:skin>' '' .
repl -r --filter=devices.xml -- '280dpi' 'hdpi' .
repl -r --filter=devices.xml -- '360dpi' 'xhdpi' .

How to test multiple variables against a value?

You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:

if x == 1 or y == 1 or z == 1:

x and y are otherwise evaluated on their own (False if 0, True otherwise).

You can shorten that using a containment test against a tuple:

if 1 in (x, y, z):

or better still:

if 1 in {x, y, z}:

using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).

When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.

This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.

However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.

x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).

So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.

The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.

How to remove constraints from my MySQL table?

  1. Go to structure view of the table
  2. You will see 2 option at top a.Table structure b.Relation view.
  3. Now click on Relation view , here you can drop your foreign key constraint. You will get all relation here.

Difference between /res and /assets directories

I know this is old, but just to make it clear, there is an explanation of each in the official android documentation:

from http://developer.android.com/tools/projects/index.html

assets/

This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

res/raw/

For arbitrary raw asset files. Saving asset files here instead of in the assets/ directory only differs in the way that you access them. These files are processed by aapt and must be referenced from the application using a resource identifier in the R class. For example, this is a good place for media, such as MP3 or Ogg files.

Global constants file in Swift

According to the swift docs global variables are declared in file scope.

Global variables are variables that are defined outside of any function, method, closure, or type context

Just create a swift file (E.g: Constnats.swift) and declare your constants there:

// Constants.swift

let SOME_NOTIF = "aaaaNotification"

and call it from anywhere in your project without the need to mention struct,enum or class name.

// MyViewController.swift

NotificationCenter.default.post(name: SOME_NOTIF, object: nil)

I think this is much better for code readability.

default select option as blank

Solution that works by only using CSS:

A: Inline CSS

_x000D_
_x000D_
<select>_x000D_
    <option style="display:none;"></option>_x000D_
    <option>Option 1</option>_x000D_
    <option>Option 2</option>_x000D_
    <option>Option 3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

B: CSS Style Sheet

If you have a CSS file at hand, you can target the first option using:

_x000D_
_x000D_
select.first-opt-hidden option:first-of-type {_x000D_
  display:none;_x000D_
}
_x000D_
<select class="first-opt-hidden">_x000D_
    <option></option>_x000D_
    <option>Option 1</option>_x000D_
    <option>Option 2</option>_x000D_
    <option>Option 3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How can I see an the output of my C programs using Dev-C++?

Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.

#include <stdio.h>
#include <stdlib.h>
int main()
 {
      int a,b,c;
      a=5;b=6;
      c=a*b;
      printf("%d",c);
      system("PAUSE");
      return 0;
 }

Hope this helped.

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

How do I use namespaces with TypeScript external modules?

The proper way to organize your code is to use separate directories in place of namespaces. Each class will be in it's own file, in it's respective namespace folder. index.ts will only re-export each file; no actual code should be in the index.ts file. Organizing your code like this makes it far easier to navigate, and is self-documenting based on directory structure.

// index.ts
import * as greeter from './greeter';
import * as somethingElse from './somethingElse';

export {greeter, somethingElse};

// greeter/index.ts
export * from './greetings.js';
...

// greeter/greetings.ts
export const helloWorld = "Hello World";

You would then use it as such:

import { greeter } from 'your-package'; //Import it like normal, be it from an NPM module or from a directory.
// You can also use the following syntax, if you prefer:
import * as package from 'your-package';

console.log(greeter.helloWorld);

Swift do-try-catch syntax

I was also disappointed by the lack of type a function can throw, but I get it now thanks to @rickster and I'll summarize it like this: let's say we could specify the type a function throws, we would have something like this:

enum MyError: ErrorType { case ErrorA, ErrorB }

func myFunctionThatThrows() throws MyError { ...throw .ErrorA...throw .ErrorB... }

do {
    try myFunctionThatThrows()
}
case .ErrorA { ... }
case .ErrorB { ... }

The problem is that even if we don't change anything in myFunctionThatThrows, if we just add an error case to MyError:

enum MyError: ErrorType { case ErrorA, ErrorB, ErrorC }

we are screwed because our do/try/catch is no longer exhaustive, as well as any other place where we called functions that throw MyError

How to print out a variable in makefile

If you simply want some output, you want to use $(info) by itself. You can do that anywhere in a Makefile, and it will show when that line is evaluated:

$(info VAR="$(VAR)")

Will output VAR="<value of VAR>" whenever make processes that line. This behavior is very position dependent, so you must make sure that the $(info) expansion happens AFTER everything that could modify $(VAR) has already happened!

A more generic option is to create a special rule for printing the value of a variable. Generally speaking, rules are executed after variables are assigned, so this will show you the value that is actually being used. (Though, it is possible for a rule to change a variable.) Good formatting will help clarify what a variable is set to, and the $(flavor) function will tell you what kind of a variable something is. So in this rule:

print-% : ; $(info $* is a $(flavor $*) variable set to [$($*)]) @true
  • $* expands to the stem that the % pattern matched in the rule.
  • $($*) expands to the value of the variable whose name is given by by $*.
  • The [ and ] clearly delineate the variable expansion. You could also use " and " or similar.
  • $(flavor $*) tells you what kind of variable it is. NOTE: $(flavor) takes a variable name, and not its expansion. So if you say make print-LDFLAGS, you get $(flavor LDFLAGS), which is what you want.
  • $(info text) provides output. Make prints text on its stdout as a side-effect of the expansion. The expansion of $(info) though is empty. You can think of it like @echo, but importantly it doesn't use the shell, so you don't have to worry about shell quoting rules.
  • @true is there just to provide a command for the rule. Without that, make will also output print-blah is up to date. I feel @true makes it more clear that it's meant to be a no-op.

Running it, you get

$ make print-LDFLAGS
LDFLAGS is a recursive variable set to [-L/Users/...]

What are Bearer Tokens and token_type in OAuth 2?

Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.

https://tools.ietf.org/html/rfc6750

Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.

If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.

However, it will be hard way since the mac spec is still changing rapidly.

https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05

Twitter Bootstrap vs jQuery UI?

Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,

  • Widgets: jQuery UI wins here. The date widget it provides is immensely useful, and Twitter Bootstrap provides nothing of the sort.
  • Scaffolding: Bootstrap wins here. Twitter's grid both fluid and fixed are top notch. jQuery UI doesn't even provide this direction leaving page layout up to the end user.
  • Out of the box professionalism: Bootstrap using CSS3 is leagues ahead, jQuery UI looks dated by comparison.
  • Icons: I'll go tie on this one. Bootstrap has nicer icons imho than jQuery UI, but I don't like the terms one bit, Glyphicons Halflings are normally not available for free, but an arrangement between Bootstrap and the Glyphicons creators have made this possible at no cost to you as developers. As a thank you, we ask you to include an optional link back to Glyphicons whenever practical.
  • Images & Thumbnails: goes to Bootstrap, jQuery UI doesn't even help here.

Other notes,

  • It's important to understand how these two technologies compete in the spheres too. There is a lot of overlap, but if you want simple scaffolding and fixed/fluid creation Bootstrap isn't another technology, it's the best technology. If you want any single widget, jQuery UI probably isn't even in the top three. Today, jQuery UI is mainly just a toy for consistency and proof of concept for a client-side widget creation using a unified framework.

How can I delete one element from an array by value

Another option:

a = [2,4,6,3,8]

a -= [3]

which results in

=> [2, 4, 6, 8] 

Is there a command to list all Unix group names?

On Linux, macOS and Unix to display the groups to which you belong, use:

id -Gn

which is equivalent to groups utility which has been obsoleted on Unix (as per Unix manual).

On macOS and Unix, the command id -p is suggested for normal interactive.

Explanation of the parameters:

-G, --groups - print all group IDs

-n, --name - print a name instead of a number, for -ugG

-p - Make the output human-readable.

Apache won't start in wamp

I was having the same problem, the mysql service was starting but not the apache service, the main problem about that is one of your virtual hosts isn't config. correctly, all i did was deleted the virtual host that i created "D:\wamp\bin\apache\apache2.4.23\conf\extra\httpd-vhosts, restarted all services apache service started working correctly and so i just went to localhost and added a virtual host automatically and so it worked!!

Selenium WebDriver and DropDown Boxes

Try the following:

import org.openqa.selenium.support.ui.Select;

Select droplist = new Select(driver.findElement(By.Id("selection")));   
droplist.selectByVisibleText("Germany");

How can I convert a cv::Mat to a gray scale in OpenCv?

May be helpful for late comers.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
    return -1;
}else{
    Mat image;
    Mat grayImage;

    image = imread(argv[1], IMREAD_COLOR);
    if (!image.data) {
        cout << "Could not open the image file" << endl;
        return -1;
    }
    else {
        int height = image.rows;
        int width = image.cols;

        cvtColor(image, grayImage, CV_BGR2GRAY);


        namedWindow("Display window", WINDOW_AUTOSIZE);
        imshow("Display window", image);

        namedWindow("Gray Image", WINDOW_AUTOSIZE);
        imshow("Gray Image", grayImage);
        cvWaitKey(0);
        image.release();
        grayImage.release();
        return 0;
    }

  }

}

how to break the _.each function in underscore.js

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

Creating and writing lines to a file

' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")

' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close

' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
    Line = File.ReadLine
    WScript.Echo(Line)
Loop
File.Close

' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

JWT authentication for ASP.NET Web API

Here's a very minimal and secure implementation of a Claims based Authentication using JWT token in an ASP.NET Core Web API.

first of all, you need to expose an endpoint that returns a JWT token with claims assigned to a user:

 /// <summary>
        /// Login provides API to verify user and returns authentication token.
        /// API Path:  api/account/login
        /// </summary>
        /// <param name="paramUser">Username and Password</param>
        /// <returns>{Token: [Token] }</returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromBody] UserRequestVM paramUser, CancellationToken ct)
        {

            var result = await UserApplication.PasswordSignInAsync(paramUser.Email, paramUser.Password, false, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                UserRequestVM request = new UserRequestVM();
                request.Email = paramUser.Email;


                ApplicationUser UserDetails = await this.GetUserByEmail(request);
                List<ApplicationClaim> UserClaims = await this.ClaimApplication.GetListByUser(UserDetails);

                var Claims = new ClaimsIdentity(new Claim[]
                                {
                                    new Claim(JwtRegisteredClaimNames.Sub, paramUser.Email.ToString()),
                                    new Claim(UserId, UserDetails.UserId.ToString())
                                });


                //Adding UserClaims to JWT claims
                foreach (var item in UserClaims)
                {
                    Claims.AddClaim(new Claim(item.ClaimCode, string.Empty));
                }

                var tokenHandler = new JwtSecurityTokenHandler();
                  // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                var encryptionkey = Configuration["Jwt:Encryptionkey"];
                var key = Encoding.ASCII.GetBytes(encryptionkey);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Issuer = Configuration["Jwt:Issuer"],
                    Subject = Claims,

                // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                    Expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(Configuration["Jwt:ExpiryTimeInMinutes"])),

                    //algorithm to sign the token
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)

                };

                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return Ok(new
                {
                    token = tokenString
                });
            }

            return BadRequest("Wrong Username or password");
        }

now you need to Add Authentication to your services in your ConfigureServices inside your startup.cs to add JWT authentication as your default authentication service like this:

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
             .AddJwtBearer(cfg =>
             {
                 cfg.RequireHttpsMetadata = false;
                 cfg.SaveToken = true;
                 cfg.TokenValidationParameters = new TokenValidationParameters()
                 {
                     //ValidateIssuerSigningKey = true,
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Encryptionkey"])),
                     ValidateAudience = false,
                     ValidateLifetime = true,
                     ValidIssuer = configuration["Jwt:Issuer"],
                     //ValidAudience = Configuration["Jwt:Audience"],
                     //IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"])),
                 };
             });

now you can add policies to your authorization services like this:

services.AddAuthorization(options =>
            {
                options.AddPolicy("YourPolicyNameHere",
                                policy => policy.RequireClaim("YourClaimNameHere"));
            });

ALTERNATIVELY, You can also (not necessary) populate all of your claims from your database as this will only run once on your application startup and add them to policies like this:

  services.AddAuthorization(async options =>
            {
                var ClaimList = await claimApplication.GetList(applicationClaim);
                foreach (var item in ClaimList)
                {                        
                    options.AddPolicy(item.ClaimCode, policy => policy.RequireClaim(item.ClaimCode));                       
                }
            });

now you can put the Policy filter on any of the methods that you want to be authorized like this:

 [HttpPost("update")]
        [Authorize(Policy = "ACC_UP")]
        public async Task<IActionResult> Update([FromBody] UserRequestVM requestVm, CancellationToken ct)
        {
//your logic goes here
}

Hope this helps

Storing a file in a database as opposed to the file system?

If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler.

Getting Started with FILESTREAM Storage

How to use NULL or empty string in SQL

SELECT *
FROM   Table
WHERE  column like '' or column IS NULL OR LEN(column) = 0

Beamer: How to show images as step-by-step images

You can simply specify a series of images like this:

\includegraphics<1>{A}
\includegraphics<2>{B}
\includegraphics<3>{C}

This will produce three slides with the images A to C in exactly the same position.

What is the default maximum heap size for Sun's JVM from Java SE 6?

To answer this question it's critical whether the Java VM is in CLIENT or SERVER mode. You can specify "-client" or "-server" options. Otherwise java uses internal rules; basically win32 is always client and Linux is always server, but see the table here:

http://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html

Sun/Oracle jre6u18 doc says re client: the VM gets 1/2 of physical memory if machine has <= 192MB; 1/4 of memory if machine has <= 1Gb; max 256Mb. In my test on a 32bit WindowsXP system with 2Gb phys mem, Java allocated 256Mb, which agrees with the doc.

Sun/Oracle jre6u18 doc says re server: same as client, then adds confusing language: for 32bit JVM the default max is 1Gb, and for 64 bit JVM the default is 32Gb. In my test on a 64bit linux machine with 8Gb physical, Java allocates 2Gb, which is 1/4 of physical; on a 64bit linux machine with 128Gb physical Java allocates 32Gb, again 1/4 of physical.

Thanks to this SO post for guiding me:

Definition of server-class machine changed recently?

How to see if an object is an array without using reflection?

Simply obj instanceof Object[] (tested on JShell).

How to create a printable Twitter-Bootstrap page

Replace every col-md- with col-xs-

eg: replace every col-md-6 to col-xs-6.

This is the thing that worked for me to get me rid of this problem you can see what you have to replace.

Why can I not create a wheel in python?

Throwing in another answer: Try checking your PYTHONPATH.

First, try to install wheel again:

pip install wheel

This should tell you where wheel is installed, eg:

Requirement already satisfied: wheel in /usr/local/lib/python3.5/dist-packages

Then add the location of wheel to your PYTHONPATH:

export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.5/dist-packages/wheel

Now building a wheel should work fine.

python setup.py bdist_wheel

Query-string encoding of a Javascript Object

Just use the following:

encodeURIComponent(JSON.stringify(obj))

_x000D_
_x000D_
// elastic search example_x000D_
let story ={_x000D_
  "query": {_x000D_
    "bool": {_x000D_
      "must": [_x000D_
        {_x000D_
          "term": { _x000D_
            "revision.published": 0, _x000D_
          }_x000D_
        },_x000D_
        {_x000D_
          "term": { _x000D_
            "credits.properties.by.properties.name": "Michael Guild"_x000D_
          }_x000D_
        },_x000D_
        {_x000D_
          "nested": {_x000D_
            "path": "taxonomy.sections",_x000D_
            "query": {_x000D_
              "bool": {_x000D_
                "must": [_x000D_
                  {_x000D_
                    "term": {_x000D_
                      "taxonomy.sections._id": "/science"_x000D_
                    }_x000D_
                  },_x000D_
                  {_x000D_
                    "term": {_x000D_
                      "taxonomy.sections._website": "staging"_x000D_
                    }_x000D_
                  }_x000D_
                ]_x000D_
              }_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
      ]_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
const whateva = encodeURIComponent(JSON.stringify(story))_x000D_
console.log(whateva)
_x000D_
_x000D_
_x000D_

SQL Query - Concatenating Results into One String

For SQL Server 2005 and above use Coalesce for nulls and I am using Cast or Convert if there are numeric values -

declare @CodeNameString  nvarchar(max)
select  @CodeNameString = COALESCE(@CodeNameString + ',', '')  + Cast(CodeName as varchar) from AccountCodes  ORDER BY Sort
select  @CodeNameString

Detect URLs in text with JavaScript

Function can be further improved to render images as well:

function renderHTML(text) { 
    var rawText = strip(text)
    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   

    return rawText.replace(urlRegex, function(url) {   

    if ( ( url.indexOf(".jpg") > 0 ) || ( url.indexOf(".png") > 0 ) || ( url.indexOf(".gif") > 0 ) ) {
            return '<img src="' + url + '">' + '<br/>'
        } else {
            return '<a href="' + url + '">' + url + '</a>' + '<br/>'
        }
    }) 
} 

or for a thumbnail image that links to fiull size image:

return '<a href="' + url + '"><img style="width: 100px; border: 0px; -moz-border-radius: 5px; border-radius: 5px;" src="' + url + '">' + '</a>' + '<br/>'

And here is the strip() function that pre-processes the text string for uniformity by removing any existing html.

function strip(html) 
    {  
        var tmp = document.createElement("DIV"); 
        tmp.innerHTML = html; 
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
        return tmp.innerText.replace(urlRegex, function(url) {     
        return '\n' + url 
    })
} 

pip cannot install anything

This is the full text of the blog post linked below:

If you've tried installing a package with pip recently, you may have encountered this error:

Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not fetch URL https://pypi.python.org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Cannot fetch index base URL https://pypi.python.org/simple/
  Could not fetch URL https://pypi.python.org/simple/Django/1.5.1: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/Django/1.5.1 when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not find any downloads that satisfy the requirement Django==1.5.1 (from -r requirements.txt (line 1))
No distributions at all found for Django==1.5.1 (from -r requirements.txt (line 1))
Storing complete log in /Users/paul/.pip/pip.log

This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work.

The easy workaround for now, is to install pip 1.2.1, which does not require SSL:

curl -O https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
tar xvfz pip-1.2.1.tar.gz
cd pip-1.2.1
python setup.py install

If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.

HTTP 404 when accessing .svc file in IIS

There are 2 .net framework version are given under the features in add role/ features in server 2012

a. 3.5

b. 4.5

Depending up on used framework you can enable HTTP-Activation under WCF services. :)

How do I pipe or redirect the output of curl -v?

This simple example shows how to capture curl output, and use it in a bash script

test.sh

function main
{
  \curl -vs 'http://google.com'  2>&1
  # note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file. 
}

# capture output of curl to a variable
OUT=$(main)

# search output for something using grep.
echo
echo "$OUT" | grep 302 
echo
echo "$OUT" | grep title 

JavaScript or jQuery browser back button click detector

there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.

Detect if user pressed "Back" button on current page:

Detect if current page is visited after pressing "Back" button on previous("Forward") page:

Loading basic HTML in Node.js

Adding another option - based on the excepted answer.

For Typescript:

import { Injectable } from '@nestjs/common';
import { parse } from 'node-html-parser';
import * as fs from 'fs';
import * as path from 'path'


@Injectable()
export class HtmlParserService {


  getDocument(id: string): string {

      const htmlRAW = fs.readFileSync(
          path.join(__dirname, "../assets/files/some_file.html"),
          "utf8"
      );


      const parsedHtml = parse(htmlRAW);
      const className  = '.'+id;
      
      //Debug
      //console.log(parsedHtml.querySelectorAll(className));

      return parsedHtml.querySelectorAll(className).toString();
  }
}

(*) Example above is using with nestjs and node-html-parser.

How to save and load numpy.array() data properly?

For a short answer you should use np.save and np.load. The advantages of these is that they are made by developers of the numpy library and they already work (plus are likely already optimized nicely) e.g.

import numpy as np
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

np.save(path/'x', x)
np.save(path/'y', y)

x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')

print(x is x_loaded) # False
print(x == x_loaded) # [[ True  True  True  True  True]]

Expanded answer:

In the end it really depends in your needs because you can also save it human readable format (see this Dump a NumPy array into a csv file) or even with other libraries if your files are extremely large (see this best way to preserve numpy arrays on disk for an expanded discussion).

However, (making an expansion since you use the word "properly" in your question) I still think using the numpy function out of the box (and most code!) most likely satisfy most user needs. The most important reason is that it already works. Trying to use something else for any other reason might take you on an unexpectedly LONG rabbit hole to figure out why it doesn't work and force it work.

Take for example trying to save it with pickle. I tried that just for fun and it took me at least 30 minutes to realize that pickle wouldn't save my stuff unless I opened & read the file in bytes mode with wb. Took time to google, try thing, understand the error message etc... Small detail but the fact that it already required me to open a file complicated things in unexpected ways. To add that it required me to re-read this (which btw is sort of confusing) Difference between modes a, a+, w, w+, and r+ in built-in open function?.

So if there is an interface that meets your needs use it unless you have a (very) good reason (e.g. compatibility with matlab or for some reason your really want to read the file and printing in python really doesn't meet your needs, which might be questionable). Furthermore, most likely if you need to optimize it you'll find out later down the line (rather than spend ages debugging useless stuff like opening a simple numpy file).

So use the interface/numpy provide. It might not be perfect it's most likely fine, especially for a library that's been around as long as numpy.

I already spent the saving and loading data with numpy in a bunch of way so have fun with it, hope it helps!

import numpy as np
import pickle
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

# using save (to npy), savez (to npz)
np.save(path/'x', x)
np.save(path/'y', y)
np.savez(path/'db', x=x, y=y)
with open(path/'db.pkl', 'wb') as db_file:
    pickle.dump(obj={'x':x, 'y':y}, file=db_file)

## using loading npy, npz files
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
db = np.load(path/'db.npz')
with open(path/'db.pkl', 'rb') as db_file:
    db_pkl = pickle.load(db_file)

print(x is x_loaded)
print(x == x_loaded)
print(x == db['x'])
print(x == db_pkl['x'])
print('done')

Some comments on what I learned:

  • np.save as expected, this already compresses it well (see https://stackoverflow.com/a/55750128/1601580), works out of the box without any file opening. Clean. Easy. Efficient. Use it.
  • np.savez uses a uncompressed format (see docs) Save several arrays into a single file in uncompressed .npz format. If you decide to use this (you were warned to go away from the standard solution so expect bugs!) you might discover that you need to use argument names to save it, unless you want to use the default names. So don't use this if the first already works (or any works use that!)
  • Pickle also allows for arbitrary code execution. Some people might not want to use this for security reasons.
  • human readable files are expensive to make etc. Probably not worth it.
  • there is something called hdf5 for large files. Cool! https://stackoverflow.com/a/9619713/1601580

Note this is not an exhaustive answer. But for other resources check this:

Spark read file from S3 using sc.textFile ("s3n://...)

There is a Spark JIRA, SPARK-7481, open as of today, oct 20, 2016, to add a spark-cloud module which includes transitive dependencies on everything s3a and azure wasb: need, along with tests.

And a Spark PR to match. This is how I get s3a support into my spark builds

If you do it by hand, you must get hadoop-aws JAR of the exact version the rest of your hadoop JARS have, and a version of the AWS JARs 100% in sync with what Hadoop aws was compiled against. For Hadoop 2.7.{1, 2, 3, ...}

hadoop-aws-2.7.x.jar 
aws-java-sdk-1.7.4.jar
joda-time-2.9.3.jar
+ jackson-*-2.6.5.jar

Stick all of these into SPARK_HOME/jars. Run spark with your credentials set up in Env vars or in spark-default.conf

the simplest test is can you do a line count of a CSV File

val landsatCSV = "s3a://landsat-pds/scene_list.gz"
val lines = sc.textFile(landsatCSV)
val lineCount = lines.count()

Get a number: all is well. Get a stack trace. Bad news.

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

You can add property to your model as follows:

    public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }

and then your view will be simpler and will contain no logic at all:

    <div class="details @Model.DetailsClass"/>

This will work even with many classes and will not render class if it is null:

    <div class="@Model.Class1 @Model.Class2"/>

with 2 not null properties will render:

    <div class="class1 class2"/>

if class1 is null

    <div class=" class2"/>

Simulate user input in bash script

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"

How to Maximize a firefox browser window using Selenium WebDriver with node.js

First instantiate a firefox driver

WebDriver driver = new FirefoxDriver();

then maximize it

 driver.manage().window().maximize();

How to enable scrolling of content inside a modal?

Set height for modal-body and not for the whole modal to get a perfect scroll on modal overlay. I get it work like this:

.MyModal {
    height: 450px;
    overflow-y: auto;
}

Here you can set height as per your requirements.

XPath to select multiple tags

You can avoid the repetition with an attribute test instead:

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self:: axis is namespace restrictive, local-name() is not. If the OP's intention is to capture c|d|e regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.

You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.

checking memory_limit in PHP

If you are interested in CLI memory limit:

cat /etc/php/[7.0]/cli/php.ini | grep "memory_limit"

FPM / "Normal"

cat /etc/php/[7.0]/fpm/php.ini | grep "memory_limit"

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

How might I convert a double to the nearest integer value?

I know this question is old, but I came across it in my search for the answer to my similar question. I thought I would share the very useful tip that I have been given.

When converting to int, simply add .5 to your value before downcasting. As downcasting to int always drops to the lower number (e.g. (int)1.7 == 1), if your number is .5 or higher, adding .5 will bring it up into the next number and your downcast to int should return the correct value. (e.g. (int)(1.8 + .5) == 2)

Reading a key from the Web.Config using ConfigurationManager

There will be two Web.config files. I think you may have confused with those two files.

Check this image:

click this link and check this image

In this image you can see two Web.config files. You should add your constants to the one which is in the project folder not in the views folder

Hope this may help you

How to elegantly check if a number is within a range?

I would do a Range object, something like this:

public class Range<T> where T : IComparable
{
    public T InferiorBoundary{get;private set;}
    public T SuperiorBoundary{get;private set;}

    public Range(T inferiorBoundary, T superiorBoundary)
    {
        InferiorBoundary = inferiorBoundary;
        SuperiorBoundary = superiorBoundary;
    }

    public bool IsWithinBoundaries(T value){
        return InferiorBoundary.CompareTo(value) > 0 && SuperiorBoundary.CompareTo(value) < 0;
    }
}

Then you use it this way:

Range<int> myRange = new Range<int>(1,999);
bool isWithinRange = myRange.IsWithinBoundaries(3);

That way you can reuse it for another type.

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Command line: search and replace in all filenames matched by grep

If your sed(1) has a -i option, then use it like this:

for i in *; do
  sed -i 's/foo/bar/' $i
done

If not, there are several ways variations on the following depending on which language you want to play with:

ruby -i.bak -pe 'sub(%r{foo}, 'bar')' *
perl -pi.bak -e 's/foo/bar/' *

How to change the current URL in javascript?

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

http://mywebsite.com/8815/1.html

It supports numbers with leading zeros:

http://mywebsite.com/0001.html

Example

Spring Boot REST API - request timeout?

You can configure the Async thread executor for your Springboot REST services. The setKeepAliveSeconds() should consider the execution time for the requests chain. Set the ThreadPoolExecutor's keep-alive seconds. Default is 60. This setting can be modified at runtime, for example through JMX.

@Bean(name="asyncExec")
public Executor asyncExecutor()
{
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(3);
    executor.setMaxPoolSize(3);
    executor.setQueueCapacity(10);
    executor.setThreadNamePrefix("AsynchThread-");
    executor.setAllowCoreThreadTimeOut(true);
    executor.setKeepAliveSeconds(10);
    executor.initialize();

    return executor;
}

Then you can define your REST endpoint as follows

@Async("asyncExec")
@PostMapping("/delayedService")
public CompletableFuture<String> doDelay()
{ 
    String response = service.callDelayedService();
    return CompletableFuture.completedFuture(response);
}

Does :before not work on img elements?

I think the best way to look at why this doesn't work is that :before and :after insert their content before or after the content within the tag you're applying them to. So it works with divs or spans (or most other tags) because you can put content inside them.

<div>
:before
Content
:after
</div>

However, an img is a self-contained, self-closing tag, and since it has no separate closing tag, you can't put anything inside of it. (That would need to look like <img>Content</img>, but of course that doesn't work.)

I know this is an old topic, but it pops up first on Google, so hopefully this will help others learn.

Meaning of $? (dollar question mark) in shell scripts

This is the exit status of the last executed command.

For example the command true always returns a status of 0 and false always returns a status of 1:

true
echo $? # echoes 0
false
echo $? # echoes 1

From the manual: (acessible by calling man bash in your shell)

$?       Expands to the exit status of the most recently executed foreground pipeline.

By convention an exit status of 0 means success, and non-zero return status means failure. Learn more about exit statuses on wikipedia.

There are other special variables like this, as you can see on this online manual: https://www.gnu.org/s/bash/manual/bash.html#Special-Parameters

Find the server name for an Oracle database

SELECT  host_name
FROM    v$instance

Vue equivalent of setTimeout?

after encountering the same issue, I ended up on this thread. For future generation's sake: The current up-most voted answer, attempts to bind "this" to a variable in order to avoid changing the context when invoking the function which is defined in the setTimeout.

An alternate and more recommended approach(using Vue.JS 2.2 & ES6) is to use an arrow function in order to bind the context to the parent (Basically "addToBasket"'s "this" and the "setTimeout"'s "this" would still refer to the same object):

addToBasket: function(){
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        setTimeout(() => {
            this.basketAddSuccess = false;
        }, 2000);
    }

How to import existing Git repository into another?

Probably the simplest way would be to pull the XXX stuff into a branch in YYY and then merge it into master:

In YYY:

git remote add other /path/to/XXX
git fetch other
git checkout -b ZZZ other/master
mkdir ZZZ
git mv stuff ZZZ/stuff                      # repeat as necessary for each file/dir
git commit -m "Moved stuff to ZZZ"
git checkout master                
git merge ZZZ --allow-unrelated-histories   # should add ZZZ/ to master
git commit
git remote rm other
git branch -d ZZZ                           # to get rid of the extra branch before pushing
git push                                    # if you have a remote, that is

I actually just tried this with a couple of my repos and it works. Unlike Jörg's answer it won't let you continue to use the other repo, but I don't think you specified that anyway.

Note: Since this was originally written in 2009, git has added the subtree merge mentioned in the answer below. I would probably use that method today, although of course this method does still work.

PHP class: Global variable as property in class

What about using constructor?

class myClass {

   $myNumber = NULL;

   public function __construct() {
      global myNumber;

      $this->myNumber = &myNumber; 
   }

   public function foo() {
      echo $this->myNumber;
   }

}

Or much better this way (passing the global variable as parameter when inicializin the object - read only)

class myClass {

   $myNumber = NULL;

   public function __construct($myNumber) {
      $this->myNumber = $myNumber; 
   }

   public function foo() {
      echo $this->myNumber;
   }

}
$instance = new myClass($myNumber);

Linq Select Group By

    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }

org.xml.sax.SAXParseException: Content is not allowed in prolog

Actually in addition to Yuriy Zubarev's Post

When you pass a nonexistent xml file to parser. For example you pass

new File("C:/temp/abc")

when only C:/temp/abc.xml file exists on your file system

In either case

builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
document = builder.parse(new File("C:/temp/abc"));

or

DOMParser parser = new DOMParser();
parser.parse("file:C:/temp/abc");

All give the same error message.

Very disappointing bug, because the following trace

javax.servlet.ServletException
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
...
Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
... 40 more

doesn't say anything about the fact of 'file name is incorrect' or 'such a file does not exist'. In my case I had absolutely correct xml file and had to spent 2 days to determine the real problem.

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

How to make Git "forget" about a file that was tracked but is now in .gitignore?

If you cannot git rm a tracked file because other people might need it (warning, even if you git rm --cached, when someone else gets this change, their files will be deleted in their filesystem). These are often done due to config file overrides, authentication credentials, etc. Please look at https://gist.github.com/1423106 for ways people have worked around the problem.

To summarize:

  • Have your application look for an ignored file config-overide.ini and use that over the committed file config.ini (or alternately, look for ~/.config/myapp.ini, or $MYCONFIGFILE)
  • Commit file config-sample.ini and ignore file config.ini, have a script or similar copy the file as necessary if necessary.
  • Try to use gitattributes clean/smudge magic to apply and remove the changes for you, for instance smudge the config file as a checkout from an alternate branch and clean the config file as a checkout from HEAD. This is tricky stuff, I don't recommend it for the novice user.
  • Keep the config file on a deploy branch dedicated to it that is never merged to master. When you want to deploy/compile/test you merge to that branch and get that file. This is essentially the smudge/clean approach except using human merge policies and extra-git modules.
  • Anti-recommentation: Don't use assume-unchanged, it will only end in tears (because having git lie to itself will cause bad things to happen, like your change being lost forever).

How do format a phone number as a String in Java?

The worst possible solution would be:

StringBuilder sb = new StringBuilder();
long tmp = phoneFmt;
sb.append("(");
sb.append(tmp / 10000000);
tmp = tmp % 10000000;
sb.append(")-");
sb.apppend(tmp / 10000);
tmp = tmp % 10000000;
sb.append("-");
sb.append(tmp);

How To Show And Hide Input Fields Based On Radio Button Selection

Use display:none/block, instead of visibility, and add a margin-top/bottom for the space you want to see ONLY when the inputs are shown

 function yesnoCheck() {
        if (document.getElementById('yesCheck').checked) {
           document.getElementById('ifYes').style.display = 'block';
        } else {
           document.getElementById('ifYes').style.display = 'none';
        }
    }

and your HTML line for the ifYes tag

<div id="ifYes" style="display:none;margin-top:3%;">If yes, explain:

What is the effect of extern "C" in C++?

Just wanted to add a bit of info, since I haven't seen it posted yet.

You'll very often see code in C headers like so:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.

Although, I have also seen C++ code such as:

extern "C" {
#include "legacy_C_header.h"
}

which I imagine accomplishes much the same thing.

Not sure which way is better, but I have seen both.

log4j logging hierarchy order

Hierarchy of log4j logging levels are as follows in Highest to Lowest order :

  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL
  • OFF

TRACE log level provides highest logging which would be helpful to troubleshoot issues. DEBUG log level is also very useful to trouble shoot the issues.

You can also refer this link for more information about log levels : https://logging.apache.org/log4j/2.0/manual/architecture.html

How to Export-CSV of Active Directory Objects?

csvde -f test.csv

This command will perform a CSV dump of every entry in your Active Directory server. You should be able to see the full DN's of users and groups.

You will have to go through that output file and get rid off the unnecessary content.

Trigger a Travis-CI rebuild without pushing a commit?

I should mention here that we now have a means of triggering a new build on the web. See https://blog.travis-ci.com/2017-08-24-trigger-custom-build for details.

TL;DR Click on "More options", and choose "Trigger build".

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

Dynamically display a CSV file as an HTML table on a web page

Just improved phihag's code because it runs into a infinite loop if file not exists.

<?php

$filename = "so-csv.csv";

echo "<html><body><table>\n\n";

if (file_exists($filename)) {
$f = fopen($filename, "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
}

else{ echo "<tr><td>No file exists ! </td></tr>" ;}
echo "\n</table></body></html>";
?>

How to align a <div> to the middle (horizontally/width) of the page

In my case, the phone screen size is unknown, and here is what I did.

HTML

<div class="loadingImg"></div>

CSS

.loadingImg{
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 9999999;
    border: 0;
    background: url('../images/loading.gif') no-repeat center;
    background-size: 50px 50px;
    display: block;
    margin: 0 auto;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

JavaScript (before you need to show this DIV)

$(".loadingImg").css("height",$(document).height());
$(".loadingImg").css("width",$(document).width());
$(".loadingImg").show();

Removing all script tags from html with JS Regular Expression

jQuery uses a regex to remove script tags in some cases and I'm pretty sure its devs had a damn good reason to do so. Probably some browser does execute scripts when inserting them using innerHTML.

Here's the regex:

/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi

And before people start crying "but regexes for HTML are evil": Yes, they are - but for script tags they are safe because of the special behaviour - a <script> section may not contain </script> at all unless it should end at this position. So matching it with a regex is easily possible. However, from a quick look the regex above does not account for trailing whitespace inside the closing tag so you'd have to test if </script    etc. will still work.

Should we pass a shared_ptr by reference or by value?

This question has been discussed and answered by Scott, Andrei and Herb during Ask Us Anything session at C++ and Beyond 2011. Watch from 4:34 on shared_ptr performance and correctness.

Shortly, there is no reason to pass by value, unless the goal is to share ownership of an object (eg. between different data structures, or between different threads).

Unless you can move-optimise it as explained by Scott Meyers in the talk video linked above, but that is related to actual version of C++ you can use.

A major update to this discussion has happened during GoingNative 2012 conference's Interactive Panel: Ask Us Anything! which is worth watching, especially from 22:50.

How to search for a string in text files?

found = False

def check():
    datafile = file('example.txt')
    for line in datafile:
        if blabla in line:
            found = True
            break
    return found

if check():
    print "true"
else:
    print "false"

Fix height of a table row in HTML Table

This works, as long as you remove the height attribute from the table.

<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
  <tr><td height='9px' bgcolor="#990000">Upper</td></tr>
  <tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>

Windows command to convert Unix line endings?

Late to the party, but there is still no correct answer using a FOR /F loop.
(But you don't need a FOR loop at all, the solution from @TampaHaze works too and is much simpler)

The answer from @IR relevant has some drawbacks.
It drops the exclamation marks and can also drop carets.

@echo off
(
    setlocal Disabledelayedexpansion
    for /f "tokens=* delims=" %%L in ('findstr /n "^" "%~1"') do (
        set "line=%%L"
        setlocal enabledelayedexpansion
        set "line=!line:*:=!"
        (echo(!line!)
        endlocal
    )
) > file.dos

The trick is to use findstr /n to prefix each line with <line number>:, this avoids skipping of empty lines or lines beginning with ;.
To remove the <number>: the FOR "tokens=1,* delims=:" option can't be used, because this would remove all leading colons in a line, too.

Therefore the line number is removed by set "line=!line:*:=!", this requires EnableDelayedExpansion.
But with EnableDelayedExpansion the line set "line=%%L" would drop all exclamation marks and also carets (only when exclams are in the line).

That's why I disable the delayed expansion before and only enable it for the two lines, where it is required.

The (echo(!line!) looks strange, but has the advantage, that echo( can display any content in !line! and the outer parenthesis avoids accidentials whitespaces at the line end.

Getting the class of the element that fired an event using JQuery

Try:

$(document).ready(function() {
    $("a").click(function(event) {
       alert(event.target.id+" and "+$(event.target).attr('class'));
    });
});

Completely removing phpMyAdmin

I had same problem. Try the following command. This solved my problem.

sudo apt-get install libapache2-mod-php5

Using BigDecimal to work with currencies

Use BigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP) when you want to round up to the 2 decimal points for cents. Be aware of rounding off error when you do calculations though. You need to be consistent when you will be doing the rounding of money value. Either do the rounding right at the end just once after all calculations are done, or apply rounding to each value before doing any calculations. Which one to use would depend on your business requirement, but generally, I think doing rounding right at the end seems to make a better sense to me.

Use a String when you construct BigDecimal for money value. If you use double, it will have a trailing floating point values at the end. This is due to computer architecture regarding how double/float values are represented in binary format.

Extracting jar to specified directory

jars use zip compression so you can use any unzip utility.

Example:

$ unzip myJar.jar -d ./directoryToExtractTo

How to change password using TortoiseSVN?

If your administrator changed your password, and Windows 10 still stores your old password you will not be asked for a new password. Windows 10 will use the stored old password, and authentication will fail.

You can delete your old password by

  1. Click Start > Control Panel > User Accounts > Manage your credentials
  2. Windows credentials
  3. Modify or delete the stored password

If you delete a password, when you try to use SVN, you will be asked for the new password.

Difference between using bean id and name in Spring configuration file

Is there difference in defining Id & name in ApplicationContext xml ? No As of 3.1(spring), id is also defined as an xsd:string type. It means whatever characters allowed in defining name are also allowed in Id. This was not possible prior to Spring 3.1.

Why to use name when it is same as Id ? It is useful for some situations, such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself.

For example, the configuration metadata for subsystem A may refer to a DataSource via the name subsystemA-dataSource. The configuration metadata for subsystem B may refer to a DataSource via the name subsystemB-dataSource. When composing the main application that uses both these subsystems the main application refers to the DataSource via the name myApp-dataSource. To have all three names refer to the same object you add to the MyApp configuration metadata the following 

<bean id="myApp-dataSource" name="subsystemA-dataSource,subsystemB-dataSource" ..../>

Alternatively, You can have separate xml configuration files for each sub-system and then you can make use of
alias to define your own names.

<alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/>
<alias name="subsystemA-dataSource" alias="myApp-dataSource" />

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

Emulate a 403 error page

To minimize the duty of the server make it simple:

.htaccess

ErrorDocument 403 "Forbidden"

PHP

header('HTTP/1.0 403 Forbidden');

die(); // or your message: die('Forbidden');

Currency formatting in Python

I've come to look at the same thing and found python-money not really used it yet but maybe a mix of the two would be good

In C#, why is String a reference type that behaves like a value type?

It is not a value type because performance (space and time!) would be terrible if it were a value type and its value had to be copied every time it were passed to and returned from methods, etc.

It has value semantics to keep the world sane. Can you imagine how difficult it would be to code if

string s = "hello";
string t = "hello";
bool b = (s == t);

set b to be false? Imagine how difficult coding just about any application would be.

Make Div overlay ENTIRE page (not just viewport)?

I had quite a bit of trouble as I didn't want to FIX the overlay in place as I wanted the info inside the overlay to be scrollable over the text. I used:

<html style="height=100%">
   <body style="position:relative">
      <div id="my-awesome-overlay" 
           style="position:absolute; 
                  height:100%; 
                  width:100%; 
                  display: block">
           [epic content here]
      </div>
   </body>
</html>

Of course the div in the middle needs some content and probably a transparent grey background but I'm sure you get the gist!

How to get all selected values from <select multiple=multiple>?

You can use selectedOptions

_x000D_
_x000D_
var selectedValues = Array.from(document.getElementById('select-meal-type').selectedOptions).map(el=>el.value);
console.log(selectedValues);
_x000D_
<select id="select-meal-type" multiple="multiple">
    <option value="1">Breakfast</option>
    <option value="2" selected>Lunch</option>
    <option value="3">Dinner</option>
    <option value="4" selected>Snacks</option>
    <option value="5">Dessert</option>
</select>
_x000D_
_x000D_
_x000D_

How to display a gif fullscreen for a webpage background?

You can set up a background with your GIF file and set the body this way:

body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}

Change background image URL with your GIF. With background-position: center you can put the image to the center and with background-size: cover you set the picture to fit all the screen. You can also set background-size: contain if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.

Here's more info about the property:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

Hope it helps :)

Copying formula to the next row when inserting a new row

Make the area with your data and formulas a Table:

enter image description here

Then adding new information in the next line will copy all formulas in that table for the new line. Data validation will also be applied for the new row as it was for the whole column. This is indeed Excel being smarter with your data.

NO VBA required...

Convert list or numpy array of single element to float in python

Just access the first item of the list/array, using the index access and the index 0:

>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4

This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:

>>> float(list_[0])
4.0

How to convert rdd object to dataframe in spark

One needs to create a schema, and attach it to the Rdd.

Assuming val spark is a product of a SparkSession.builder...

    import org.apache.spark._
    import org.apache.spark.sql._       
    import org.apache.spark.sql.types._

    /* Lets gin up some sample data:
     * As RDD's and dataframes can have columns of differing types, lets make our
     * sample data a three wide, two tall, rectangle of mixed types.
     * A column of Strings, a column of Longs, and a column of Doubules 
     */
    val arrayOfArrayOfAnys = Array.ofDim[Any](2,3)
    arrayOfArrayOfAnys(0)(0)="aString"
    arrayOfArrayOfAnys(0)(1)=0L
    arrayOfArrayOfAnys(0)(2)=3.14159
    arrayOfArrayOfAnys(1)(0)="bString"
    arrayOfArrayOfAnys(1)(1)=9876543210L
    arrayOfArrayOfAnys(1)(2)=2.71828

    /* The way to convert an anything which looks rectangular, 
     * (Array[Array[String]] or Array[Array[Any]] or Array[Row], ... ) into an RDD is to 
     * throw it into sparkContext.parallelize.
     * http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.SparkContext shows
     * the parallelize definition as 
     *     def parallelize[T](seq: Seq[T], numSlices: Int = defaultParallelism)
     * so in our case our ArrayOfArrayOfAnys is treated as a sequence of ArraysOfAnys.
     * Will leave the numSlices as the defaultParallelism, as I have no particular cause to change it. 
     */
    val rddOfArrayOfArrayOfAnys=spark.sparkContext.parallelize(arrayOfArrayOfAnys)

    /* We'll be using the sqlContext.createDataFrame to add a schema our RDD.
     * The RDD which goes into createDataFrame is an RDD[Row] which is not what we happen to have.
     * To convert anything one tall and several wide into a Row, one can use Row.fromSeq(thatThing.toSeq)
     * As we have an RDD[somethingWeDontWant], we can map each of the RDD rows into the desired Row type. 
     */     
    val rddOfRows=rddOfArrayOfArrayOfAnys.map(f=>
        Row.fromSeq(f.toSeq)
    )

    /* Now to construct our schema. This needs to be a StructType of 1 StructField per column in our dataframe.
     * https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.types.StructField shows the definition as
     *   case class StructField(name: String, dataType: DataType, nullable: Boolean = true, metadata: Metadata = Metadata.empty)
     * Will leave the two default values in place for each of the columns:
     *        nullability as true, 
     *        metadata as an empty Map[String,Any]
     *   
     */

    val schema = StructType(
        StructField("colOfStrings", StringType) ::
        StructField("colOfLongs"  , LongType  ) ::
        StructField("colOfDoubles", DoubleType) ::
        Nil
    )

    val df=spark.sqlContext.createDataFrame(rddOfRows,schema)
    /*
     *      +------------+----------+------------+
     *      |colOfStrings|colOfLongs|colOfDoubles|
     *      +------------+----------+------------+
     *      |     aString|         0|     3.14159|
     *      |     bString|9876543210|     2.71828|
     *      +------------+----------+------------+
    */ 
    df.show 

Same steps, but with fewer val declarations:

    val arrayOfArrayOfAnys=Array(
        Array("aString",0L         ,3.14159),
        Array("bString",9876543210L,2.71828)
    )

    val rddOfRows=spark.sparkContext.parallelize(arrayOfArrayOfAnys).map(f=>Row.fromSeq(f.toSeq))

    /* If one knows the datatypes, for instance from JDBC queries as to RDBC column metadata:
     * Consider constructing the schema from an Array[StructField].  This would allow looping over 
     * the columns, with a match statement applying the appropriate sql datatypes as the second
     *  StructField arguments.   
     */
    val sf=new Array[StructField](3)
    sf(0)=StructField("colOfStrings",StringType)
    sf(1)=StructField("colOfLongs"  ,LongType  )
    sf(2)=StructField("colOfDoubles",DoubleType)        
    val df=spark.sqlContext.createDataFrame(rddOfRows,StructType(sf.toList))
    df.show

Properties order in Margin

Margin="1,2,3,4"
  1. Left,
  2. Top,
  3. Right,
  4. Bottom

It is also possible to specify just two sizes like this:

Margin="1,2"
  1. Left AND right
  2. Top AND bottom

Finally you can specify a single size:

Margin="1"
  1. used for all sides

The order is the same as in WinForms.

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

Express.js Response Timeout

In case you would like to use timeout middleware and exclude a specific route:

var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests

app.use('/my_route', function(req, res, next) {
    req.clearTimeout(); // clear request timeout
    req.setTimeout(20000); //set a 20s timeout for this request
    next();
}).get('/my_route', function(req, res) {
    //do something that takes a long time
});

How to position the Button exactly in CSS

I'd use absolute positioning:

#play_button {
    position:absolute;
transition: .5s ease;
    left: 202px;
    top: 198px;

}

How to create multiple page app using react

The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:

    entry: {
            outputone: './source/fileone.jsx',
            outputtwo: './source/filetwo.jsx'
            },
    output: {
            path: path.resolve(__dirname, './wwwroot/js/dist'),
            filename: '[name].js'      
            },

This will generate 2 files: outputone.js und outputtwo.js in the target folder.

How do I rename a column in a database table using SQL?

Unfortunately, for a database independent solution, you will need to know everything about the column. If it is used in other tables as a foreign key, they will need to be modified as well.

ALTER TABLE MyTable ADD MyNewColumn OLD_COLUMN_TYPE;
UPDATE MyTable SET MyNewColumn = MyOldColumn;
-- add all necessary triggers and constraints to the new column...
-- update all foreign key usages to point to the new column...
ALTER TABLE MyTable DROP COLUMN MyOldColumn;

For the very simplest of cases (no constraints, triggers, indexes or keys), it will take the above 3 lines. For anything more complicated it can get very messy as you fill in the missing parts.

However, as mentioned above, there are simpler database specific methods if you know which database you need to modify ahead of time.

Excel: VLOOKUP that returns true or false?

You can use:

=IF(ISERROR(VLOOKUP(lookup value,table array,column no,FALSE)),"FALSE","TRUE")

How can I sharpen an image in OpenCV?

Try with this:

cv::bilateralFilter(img, 9, 75, 75);

You might find more information here.

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

How to add an item to an ArrayList in Kotlin?

You can add element to arrayList using add() method in Kotlin. For example,

arrayList.add(10)

Above code will add element 10 to arrayList.

However, if you are using Array or List, then you can not add element. This is because Array and List are Immutable. If you want to add element, you will have to use MutableList.

Several workarounds:

  1. Using System.arraycopy() method: You can achieve same target by creating new array and copying all the data from existing array into new one along with new values. This way you will have new array with all desired values(Existing and New values)
  2. Using MutableList:: Convert array into mutableList using toMutableList() method. Then, add element into it.
  3. Using Array.copyof(): Somewhat similar as System.arraycopy() method.

Is it possible to use global variables in Rust?

It's possible but no heap allocation allowed directly. Heap allocation is performed at runtime. Here are a few examples:

static SOME_INT: i32 = 5;
static SOME_STR: &'static str = "A static string";
static SOME_STRUCT: MyStruct = MyStruct {
    number: 10,
    string: "Some string",
};
static mut db: Option<sqlite::Connection> = None;

fn main() {
    println!("{}", SOME_INT);
    println!("{}", SOME_STR);
    println!("{}", SOME_STRUCT.number);
    println!("{}", SOME_STRUCT.string);

    unsafe {
        db = Some(open_database());
    }
}

struct MyStruct {
    number: i32,
    string: &'static str,
}

In-place type conversion of a NumPy array

You can change the array type without converting like this:

a.dtype = numpy.float32

but first you have to change all the integers to something that will be interpreted as the corresponding float. A very slow way to do this would be to use python's struct module like this:

def toi(i):
    return struct.unpack('i',struct.pack('f',float(i)))[0]

...applied to each member of your array.

But perhaps a faster way would be to utilize numpy's ctypeslib tools (which I am unfamiliar with)

- edit -

Since ctypeslib doesnt seem to work, then I would proceed with the conversion with the typical numpy.astype method, but proceed in block sizes that are within your memory limits:

a[0:10000] = a[0:10000].astype('float32').view('int32')

...then change the dtype when done.

Here is a function that accomplishes the task for any compatible dtypes (only works for dtypes with same-sized items) and handles arbitrarily-shaped arrays with user-control over block size:

import numpy

def astype_inplace(a, dtype, blocksize=10000):
    oldtype = a.dtype
    newtype = numpy.dtype(dtype)
    assert oldtype.itemsize is newtype.itemsize
    for idx in xrange(0, a.size, blocksize):
        a.flat[idx:idx + blocksize] = \
            a.flat[idx:idx + blocksize].astype(newtype).view(oldtype)
    a.dtype = newtype

a = numpy.random.randint(100,size=100).reshape((10,10))
print a
astype_inplace(a, 'float32')
print a

Run a script in Dockerfile

WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh 

Get real path from URI, Android KitKat new storage access framework

Before new gallery access in KitKat I got my real path in sdcard with this method

That was never reliable. There is no requirement that the Uri that you are returned from an ACTION_GET_CONTENT or ACTION_PICK request has to be indexed by the MediaStore, or even has to represent a file on the file system. The Uri could, for example, represent a stream, where an encrypted file is decrypted for you on the fly.

How could I manage to obtain the real path in sdcard?

There is no requirement that there is a file corresponding to the Uri.

Yes, I really need a path

Then copy the file from the stream to your own temporary file, and use it. Better yet, just use the stream directly, and avoid the temporary file.

I have changed my Intent.ACTION_GET_CONTENT for Intent.ACTION_PICK

That will not help your situation. There is no requirement that an ACTION_PICK response be for a Uri that has a file on the filesystem that you can somehow magically derive.

jQuery validate: How to add a rule for regular expression validation?

You can use the addMethod()

e.g

$.validator.addMethod('postalCode', function (value) { 
    return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value); 
}, 'Please enter a valid US or Canadian postal code.');

good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

Have you tried to remove the proxy username and password? A similar poster encountered that issue:

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Failing that I found the following worked:

  1. Delete project in Eclipse (but do not delete the contents on disk)
  2. Delete all files in your Maven repository
  3. Re-download all Maven dependencies:

mvn dependency:resolve

  1. Start up Eclipse
  2. Ensure that Eclipse is configured to use your external Maven installation (Window->Preferences->Maven->Installations)
  3. Re-import the existing project(s) into Eclipse
  4. Ensure that there are no Maven Eclipse plugin errors on the final screen of the project import

Measure execution time for a Java method

As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself

long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization 
long start2 = System.nanoTime();
myCall(); 
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;

System.out.println(diff + " ns");

By the way, you will measure different values for the same call due to

  • other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
  • cache fillings (cold, warm)
  • jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))

In Java, how to append a string more efficiently?

You can use StringBuffer or StringBuilder for this. Both are for dynamic string manipulation. StringBuffer is thread-safe where as StringBuilder is not.

Use StringBuffer in a multi-thread environment. But if it is single threaded StringBuilder is recommended and it is much faster than StringBuffer.

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

Python - difference between two strings

The answer to my comment above on the Original Question makes me think this is all he wants:

loopnum = 0
word = 'afrykanerskojezyczny'
wordlist = ['afrykanerskojezycznym','afrykanerskojezyczni','nieafrykanerskojezyczni']
for i in wordlist:
    wordlist[loopnum] = word
    loopnum += 1

This will do the following:

For every value in wordlist, set that value of the wordlist to the origional code.

All you have to do is put this piece of code where you need to change wordlist, making sure you store the words you need to change in wordlist, and that the original word is correct.

Hope this helps!

How can I format a nullable DateTime with ToString()?

you can use simple line:

dt2.ToString("d MMM yyyy") ?? ""

Get only the Date part of DateTime in mssql

We can use this method:

CONVERT(VARCHAR(10), GETDATE(), 120)

Last parameter changes the format to only to get time or date in specific formats.

angular js unknown provider

Yet another possibility.

I had unknown Provider <- <- nameOfMyService. The error was caused by the following syntax:

module.factory(['', function() { ... }]);

Angular was looking for the '' dependency.

Override console.log(); for production

Put this at the top of the file:

var console = {};
console.log = function(){};

For some browsers and minifiers, you may need to apply this onto the window object.

window.console = console;

Why can't I use background image and color together?

Actually there is a way you can use a background color with a background image. In this case, the background part will be filled with that specified color instead of a white/transparent one.

In order to achieve that, you need to set the background property like this:

.bg-image-with-color {
    background: url("example.png") no-repeat, #ff0000;
}

Note the comma and the color code after no-repeat; this sets the background color you wish.

I discovered this in this YouTube video, however I'm not affiliated with that channel or video in any means.

What database does Google use?

Google primarily uses Bigtable.

Bigtable is a distributed storage system for managing structured data that is designed to scale to a very large size.

For more information, download the document from here.

Google also uses Oracle and MySQL databases for some of their applications.

Any more information you can add is highly appreciated.

Deleting multiple elements from a list

I can actually think of two ways to do it:

  1. slice the list like (this deletes the 1st,3rd and 8th elements)

    somelist = somelist[1:2]+somelist[3:7]+somelist[8:]

  2. do that in place, but one at a time:

    somelist.pop(2) somelist.pop(0)

Simple working Example of json.net in VB.net

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

Unknown version of Tomcat was specified in Eclipse

I am on MacOS and installed tomcat using homebrew, Following path fixed my problem

/usr/local/Cellar/tomcat/9.0.14/libexec

Singleton design pattern vs Singleton beans in Spring container

There is a very fundamental difference between the two. In case of Singleton design pattern, only one instance of a class will be created per classLoader while that is not the case with Spring singleton as in the later one shared bean instance for the given id per IoC container is created.

For example, if I have a class with the name "SpringTest" and my XML file looks something like this :-

<bean id="test1" class="com.SpringTest" scope="singleton">
        --some properties here
</bean>    
<bean id="test2" class="com.SpringTest" scope="singleton">
        --some properties here   
</bean>

So now in the main class if you will check the reference of the above two it will return false as according to Spring documentation:-

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container

So as in our case, the classes are the same but the id's that we have provided are different hence resulting in two different instances being created.

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

Kubernetes how to make Deployment to update image

Another option which is more suitable for debugging but worth mentioning is to check in revision history of your rollout:

$ kubectl rollout history deployment my-dep
deployment.apps/my-dep
 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>

To see the details of each revision, run:

 kubectl rollout history deployment my-dep --revision=2

And then returning to the previous revision by running:

 $kubectl rollout undo deployment my-dep --to-revision=2

And then returning back to the new one.
Like running ctrl+z -> ctrl+y (:

(*) The CHANGE-CAUSE is <none> because you should run the updates with the --record flag - like mentioned here:

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record

(**) There is a discussion regarding deprecating this flag.

Oracle pl-sql escape character (for a " ' ")

In SQL, you escape a quote by another quote:

SELECT 'Alex''s Tea Factory' FROM DUAL

What is the difference between "INNER JOIN" and "OUTER JOIN"?

I don't see much details about performance and optimizer in the other answers.

Sometimes it is good to know that only INNER JOIN is associative which means the optimizer has the most option to play with it. It can reorder the join order to make it faster keeping the same result. The optimizer can use the most join modes.

Generally it is a good practice to try to use INNER JOIN instead of the different kind of joins. (Of course if it is possible considering the expected result set.)

There are a couple of good examples and explanation here about this strange associative behavior:

How to access a dictionary element in a Django template?

Similar to the answer by @russian_spy :

<ul>
{% for choice in choices.items %} 
  <li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>

This might be suitable for breaking down more complex dictionaries.

How to count the number of letters in a string without the spaces?

MattBryant's answer is a good one, but if you want to exclude more types of letters than just spaces, it will get clunky. Here's a variation on your current code using Counter that will work:

from collections import Counter
import string

def count_letters(word, valid_letters=string.ascii_letters):
    count = Counter(word) # this counts all the letters, including invalid ones
    return sum(count[letter] for letter in valid_letters) # add up valid letters

Example output:

>>> count_letters("The grey old fox is an idiot.") # the period will be ignored
22

Capitalize words in string

If you're using lodash in your JavaScript application, You can use _.capitalize:

_x000D_
_x000D_
console.log( _.capitalize('ÿöur striñg') );_x000D_
 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Simple InputBox function

It would be something like this

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript" 
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
$_userInput = $inputObject.eval("getInput") 

return $_userInput
}

Then you can call the function similar to this.

$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null ) 
{
 echo "Input was [$userInput]"
}
else
{
 echo "User cancelled the form!"
}

This is the most simple way to do this that I can think of.

Default interface methods are only supported starting with Android N

As CommonsWare mentioned, for reference add this inside the android {...} closure in the build.gradle for your app module to resolve issue:

android {
...
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
...
}

Best way to compare 2 XML documents in Java

Below code works for me

String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLAssert.assertXMLEqual(actualxml, xmlInDb);

find . -type f -exec chmod 644 {} ;

A good alternative is this:

find . -type f | xargs chmod -v 644

and for directories:

find . -type d | xargs chmod -v 755

and to be more explicit:

find . -type f | xargs -I{} chmod -v 644 {}

How to position the div popup dialog to the center of browser screen?

Here, this ones working. :)

http://jsfiddle.net/nDNXc/1/

upd: Just in case jsfiddle is not responding here is the code...
CSS:

.holder{        
    width:100%;
    display:block;
}
.content{
    background:#fff;
    padding: 28px 26px 33px 25px;
}
.popup{
    border-radius: 7px;
    background:#6b6a63;
    margin:30px auto 0;
    padding:6px;  
    // here it comes
    position:absolute;
    width:800px;
    top: 50%;
    left: 50%;
    margin-left: -400px; // 1/2 width
    margin-top: -40px; // 1/2 height
}

HTML:

<div class="holder">     
    <div id="popup" class="popup">            
        <div class="content">some lengthy text</div>
    </div>
</div>

How to redirect to previous page in Ruby On Rails?

I like Jaime's method with one exception, it worked better for me to re-store the referer every time:

def edit
    session[:return_to] = request.referer
...

The reason is that if you edit multiple objects, you will always be redirected back to the first URL you stored in the session with Jaime's method. For example, let's say I have objects Apple and Orange. I edit Apple and session[:return_to] gets set to the referer of that action. When I go to edit Oranges using the same code, session[:return_to] will not get set because it is already defined. So when I update the Orange, I will get sent to the referer of the previous Apple#edit action.

Graphviz's executables are not found (Python 3.4)

I had the same issue on Ubuntu(14.04) with Jupyter.

To solve it I've added the dot library to python sys.path

First: check if dot is installed,

Then: find his path whereis dot -> /local/notebook/miniconda2/envs/ik2/bin/dot

Finally in python script : sys.path.append("/local/notebook/miniconda2/envs/ik2/bin/dot")

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

Why is there no Constant feature in Java?

Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of const in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.

Wikipedia offers the following information on the subject:

Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.

How to calculate md5 hash of a file using javascript

While there are JS implementations of the MD5 algorithm, older browsers are generally unable to read files from the local filesystem.

I wrote that in 2009. So what about new browsers?

With a browser that supports the FileAPI, you *can * read the contents of a file - the user has to have selected it, either with an <input> element or drag-and-drop. As of Jan 2013, here's how the major browsers stack up:

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

jQuery get input value after keypress

Use .keyup instead of keypress.

Also use $(this).val() or just this.value to access the current input value.

DEMO here

Info about .keypress from jQuery docs,

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Get the week start date and week end date from week number

Another way to do it:

declare @week_number int = 6280 -- 2020-05-07
declare @start_weekday int = 0 -- Monday
declare @end_weekday int = 6 -- next Sunday

select 
    dateadd(week, @week_number, @start_weekday), 
    dateadd(week, @week_number, @end_weekday)

Explanation:

  • @week_number is the week number since the initial calendar date '1900-01-01'. It can be computed this way: select datediff(week, 0, @wedding_date) as week_number
  • @start_weekday for the week first day: 0 for Monday, -1 if Sunday
  • @end_weekday for the week last day: 6 for next Sunday, 5 if Saturday
  • dateadd(week, @week_number, @end_weekday): adds the given number of weeks and the given number of days into the initial calendar date '1900-01-01'

int to string in MySQL

If you have a column called "col1" which is int, you cast it to String like this:

CONVERT(col1,char)

e.g. this allows you to check an int value is containing another value (here 9) like this:

CONVERT(col1,char) LIKE '%9%'

Generate a unique id

Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"

StringBuilder builder = new StringBuilder();
Enumerable
   .Range(65, 26)
    .Select(e => ((char)e).ToString())
    .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
    .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
    .OrderBy(e => Guid.NewGuid())
    .Take(11)
    .ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();

It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.

0.001% duplicates in 100 million.

Get the last insert id with doctrine 2?

Here i post my code, after i have pushed myself for one working day to find this solution.

Function to get the last saved record :

private function getLastId($query) {
        $conn = $this->getDoctrine()->getConnection();
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $lastId = $stmt->fetch()['id'];
        return $lastId;
    }

Another Function which call the above function

private function clientNum() {
        $lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
        $noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
        return $noClient;
    }

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

Generate GUID in MySQL for existing Data?

I faced mostly the same issue. Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints. And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:

UNHEX(REPLACE(uuid(), '-', ''))

But for me it worked, when i used such a query with nested inner select:

UNHEX(REPLACE((SELECT uuid()), '-', ''))

Then is produced unique result for every entry.

Comparing strings, c++

string cat = "cat";
string human = "human";

cout << cat.compare(human) << endl; 

This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.

I find the return value described in cplusplus.com is more accurate which are-:

0 : They compare equal

<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.

negative value if *this appears before the character sequence specified by the arguments, in lexicographical order

zero if both character sequences compare equivalent

positive value if *this appears after the character sequence specified by the arguments, in lexicographical order

Angular IE Caching issue for $http

To avoid caching, one option is to give different URL for the same resource or data. To generate different URL, you can add a random query string to the end of the URL. This technique works for JQuery, Angular or other type ajax requests.

myURL = myURL +"?random="+new Date().getTime();

How to assign a value to a TensorFlow variable?

Also, it has to be noted that if you're using your_tensor.assign(), then the tf.global_variables_initializer need not be called explicitly since the assign operation does it for you in the background.

Example:

In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)

In [214]: with tf.Session() as sess:
     ...:     sess.run(w_new)
     ...:     print(w_new.eval())

# output
34 

However, this will not initialize all variables, but it will only initialize the variable on which assign was executed on.

Android Pop-up message

Use This And Call This In OnCreate Method In Which Activity You Want

public void popupMessage(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("No Internet Connection. Check Your Wifi Or enter code hereMobile Data.");
        alertDialogBuilder.setIcon(R.drawable.ic_no_internet);
        alertDialogBuilder.setTitle("Connection Failed");
        alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d("internet","Ok btn pressed");
                finishAffinity();
                System.exit(0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

Difference Between $.getJSON() and $.ajax() in jQuery

The only difference I see is that getJSON performs a GET request instead of a POST.

@property retain, assign, copy, nonatomic in Objective-C

The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:

nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)

readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.

retain vs. copy vs. assign

  • "assign" is the default. In the setter that is created by @synthesize, the value will simply be assigned to the attribute. My understanding is that "assign" should be used for non-pointer attributes.
  • "retain" is needed when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count) the object. You will need to release the object when you are finished with it.
  • "copy" is needed when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Initializing a member array in constructor initializer

  1. How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible?

Yes. It's using a struct that contains an array. You say you already know about that, but then I don't understand the question. That way, you do initialize an array in the constructor, without assignments in the body. This is what boost::array does.

Does the C++03 standard say anything special about initializing aggregates (including arrays) in ctor initializers? Or the invalidness of the above code is a corollary of some other rules?

A mem-initializer uses direct initialization. And the rules of clause 8 forbid this kind of thing. I'm not exactly sure about the following case, but some compilers do allow it.

struct A {
  char foo[6];
  A():foo("hello") { } /* valid? */
};

See this GCC PR for further details.

Do C++0x initializer lists solve the problem?

Yes, they do. However your syntax is invalid, I think. You have to use braces directly to fire off list initialization

struct A {
  int foo[3];
  A():foo{1, 2, 3} { }
  A():foo({1, 2, 3}) { } /* invalid */
};

How do I run a Python script from C#?

If you're willing to use IronPython, you can execute scripts directly in C#:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Get IronPython here.

Hunk #1 FAILED at 1. What's that mean?

Follow the instructions here, it solved my problem.

you have to run the command like as follow; patch -p0 --dry-run < path/to/your/patchFile/yourPatch.patch

Date object to Calendar [Java]

something like

movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);

Permutations between two lists of unequal length

the best way to find out all the combinations for large number of lists is:

import itertools
from pprint import pprint

inputdata = [
    ['a', 'b', 'c'],
    ['d'],
    ['e', 'f'],
]
result = list(itertools.product(*inputdata))
pprint(result)

the result will be:

[('a', 'd', 'e'),
 ('a', 'd', 'f'),
 ('b', 'd', 'e'),
 ('b', 'd', 'f'),
 ('c', 'd', 'e'),
 ('c', 'd', 'f')]

Adding a simple UIAlertView

As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.

Programmatically close aspx page from code behind

 protected void btnOK_Click(object sender, EventArgs e)
        {

          // Your code goes here.
          if(isSuccess)
          {
                  string  close =    @"<script type='text/javascript'>
                                window.returnValue = true;
                                window.close();
                                </script>";
            base.Response.Write(close);
            }

        }