Programs & Examples On #Population

"Object doesn't support property or method 'find'" in IE

Just for the purpose of mentioning underscore's find method works in IE with no problem.

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

TypeError: a bytes-like object is required, not 'str' in python and CSV

I had the same issue with Python3. My code was writing into io.BytesIO().

Replacing with io.StringIO() solved.

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

You need to do the following:

public class CountryInfoResponse {

   @JsonProperty("geonames")
   private List<Country> countries; 

   //getter - setter
}

RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();

It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)

How to implement the Java comparable interface?

Implement Comparable<Animal> interface in your class and provide implementation of int compareTo(Animal other) method in your class.See This Post

How to save data file into .RData?

Alternatively, when you want to save individual R objects, I recommend using saveRDS.

You can save R objects using saveRDS, then load them into R with a new variable name using readRDS.

Example:

# Save the city object
saveRDS(city, "city.rds")

# ...

# Load the city object as city
city <- readRDS("city.rds")

# Or with a different name
city2 <- readRDS("city.rds")

But when you want to save many/all your objects in your workspace, use Manetheran's answer.

Check array position for null/empty

You can use boost::optional (or std::optional for newer versions), which was developed in particular for decision of your problem:

boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
   if(y[i]) { //check for null
      p[i].SetPoint(Recto.Height()-x,*y[i]);
      ....
   }
}

P.S. Do not use C-type array -> use std::array or std::vector:

std::array<int, 50> y;   //not int y[50] !!!

Nested ifelse statement

Try something like the following:

# some sample data
idnat <- sample(c("french","foreigner"),100,TRUE)
idbp <- rep(NA,100)
idbp[idnat=="french"] <- sample(c("mainland","overseas","colony"),sum(idnat=="french"),TRUE)

# recoding
out <- ifelse(idnat=="french" & !idbp %in% c("overseas","colony"), "mainland",
              ifelse(idbp %in% c("overseas","colony"),"overseas",
                     "foreigner"))
cbind(idnat,idbp,out) # check result

Your confusion comes from how SAS and R handle if-else constructions. In R, if and else are not vectorized, meaning they check whether a single condition is true (i.e., if("french"=="french") works) and cannot handle multiple logicals (i.e., if(c("french","foreigner")=="french") doesn't work) and R gives you the warning you're receiving.

By contrast, ifelse is vectorized, so it can take your vectors (aka input variables) and test the logical condition on each of their elements, like you're used to in SAS. An alternative way to wrap your head around this would be to build a loop using if and else statements (as you've started to do here) but the vectorized ifelse approach will be more efficient and involve generally less code.

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

How should we manage jdk8 stream for null values

An example how to avoid null e.g. use filter before groupingBy

Filter out the null instances before groupingBy.

Here is an example

MyObjectlist.stream()
            .filter(p -> p.getSomeInstance() != null)
            .collect(Collectors.groupingBy(MyObject::getSomeInstance));

Shell script not running, command not found

Make sure you are not using "PATH" as a variable, which will override the existing PATH for environment variables.

ng-repeat finish event

Maybe a bit simpler approach with ngInit and Lodash's debounce method without the need of custom directive:

Controller:

$scope.items = [1, 2, 3, 4];

$scope.refresh = _.debounce(function() {
    // Debounce has timeout and prevents multiple calls, so this will be called 
    // once the iteration finishes
    console.log('we are done');
}, 0);

Template:

<ul>
    <li ng-repeat="item in items" ng-init="refresh()">{{item}}</li>
</ul>

Update

There is even simpler pure AngularJS solution using ternary operator:

Template:

<ul>
    <li ng-repeat="item in items" ng-init="$last ? doSomething() : null">{{item}}</li>
</ul>

Be aware that ngInit uses pre-link compilation phase - i.e. the expression is invoked before child directives are processed. This means that still an asynchronous processing might be required.

Nesting queries in SQL

If it has to be "nested", this would be one way, to get your job done:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

C# error: "An object reference is required for the non-static field, method, or property"

It looks like you want:

public static string GetRandomBits()

Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.

How to create text file and insert data to that file on Android

I'm using Kotlin here

Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example

var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
 strwrt=FileWriter(File("sdcard/${NamaFile}"))
            strwrt.write(teks)
            strwrt.close()

after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.

How do I split a string into an array of characters?

You can use the regular expression /(?!$)/:

"overpopulation".split(/(?!$)/)

The negative look-ahead assertion (?!$) will match right in front of every character.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

"cannot be used as a function error"

Your compiler is right. You can't use the growthRate variable you declared in main as a function.

Maybe you should pick different names for your variables so they don't override function names?

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

How to efficiently calculate a running standard deviation?

Statistics::Descriptive is a very decent Perl module for these types of calculations:

#!/usr/bin/perl

use strict; use warnings;

use Statistics::Descriptive qw( :all );

my $data = [
    [ 0.01, 0.01, 0.02, 0.04, 0.03 ],
    [ 0.00, 0.02, 0.02, 0.03, 0.02 ],
    [ 0.01, 0.02, 0.02, 0.03, 0.02 ],
    [ 0.01, 0.00, 0.01, 0.05, 0.03 ],
];

my $stat = Statistics::Descriptive::Full->new;
# You also have the option of using sparse data structures

for my $ref ( @$data ) {
    $stat->add_data( @$ref );
    printf "Running mean: %f\n", $stat->mean;
    printf "Running stdev: %f\n", $stat->standard_deviation;
}
__END__

Output:

C:\Temp> g
Running mean: 0.022000
Running stdev: 0.013038
Running mean: 0.020000
Running stdev: 0.011547
Running mean: 0.020000
Running stdev: 0.010000
Running mean: 0.020000
Running stdev: 0.012566

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Assign an initial value to radio button as checked

You can just use:

<input type="radio" checked />

Using just the attribute checked without stating a value is the same as checked="checked".

Python 3 string.join() equivalent?

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'

How to define an empty object in PHP

Short answer

$myObj = new stdClass();

// OR 

$myObj = (object) [
    "foo" => "Foo value",
    "bar" => "Bar value"
];

Long answer

I love how easy is to create objects of anonymous type in JavaScript:

//JavaScript
var myObj = {
    foo: "Foo value",
    bar: "Bar value"
};
console.log(myObj.foo); //Output: Foo value

So I always try to write this kind of objects in PHP like javascript does:

//PHP >= 5.4
$myObj = (object) [
    "foo" => "Foo value",
    "bar" => "Bar value"
];

//PHP < 5.4
$myObj = (object) array(
    "foo" => "Foo value",
    "bar" => "Bar value"
);

echo $myObj->foo; //Output: Foo value

But as this is basically an array you can't do things like assign anonymous functions to a property like js does:

//JavaScript
var myObj = {
    foo: "Foo value",
    bar: function(greeting) {
        return greeting + " bar";
    }
};
console.log(myObj.bar("Hello")); //Output: Hello bar

//PHP >= 5.4
$myObj = (object) [
    "foo" => "Foo value",
    "bar" => function($greeting) {
        return $greeting . " bar";
    }
];
var_dump($myObj->bar("Hello")); //Throw 'undefined function' error
var_dump($myObj->bar); //Output: "object(Closure)"

Well, you can do it, but IMO isn't practical / clean:

$barFunc = $myObj->bar;
echo $barFunc("Hello"); //Output: Hello bar

Also, using this synthax you can find some funny surprises, but works fine for most cases.

Find a value anywhere in a database

Based on bnkdev's answer I modified Narayana's Code to search all columns even numeric ones.

It'll run slower, but this version actually finds all matches not just those found in text columns.

I can't thank this guy enough. Saved me days of searching by hand!

CREATE PROC SearchAllTables 
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)                  
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(CONVERT(varchar(max), ' + @ColumnName + '), 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE CONVERT(varchar(max), ' + @ColumnName + ') LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM #Results
END

R - test if first occurrence of string1 is followed by string2

> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE

basically, look for everything at the beginning except _, and then the _2.

+1 to @Ananda_Mahto for suggesting grepl instead of grep.

How can I count text lines inside an DOM element? Can I?

You should be able to split('\n').length and get the line breaks.

update: this works on FF/Chrome but not IE.

<html>
<head>
<script src="jquery-1.3.2.min.js"></script>
<script>
    $(document).ready(function() {
        var arr = $("div").text().split('\n');
        for (var i = 0; i < arr.length; i++)
            $("div").after(i + '=' + arr[i] + '<br/>');
    });
</script>
</head>
<body>
<div>One
Two
Three</div>
</body>
</html>

Move an item inside a list?

Use the insert method of a list:

l = list(...)
l.insert(index, item)

Alternatively, you can use a slice notation:

l[index:index] = [item]

If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:

l.insert(newindex, l.pop(oldindex))

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

This will do the trick for you:

  1. Update your angular cli by running the command ng update @angular/cli @angular/core
  2. Run or build your project by running the commands ng s or ng build respectively.

Which characters make a URL invalid?

I need to select character to split urls in string, so I decided to create list of characters which could not be found in URL by myself:

>>> allowed = "-_.~!*'();:@&=+$,/?%#[]?@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
>>> from string import printable
>>> ''.join(set(printable).difference(set(allowed)))
'`" <\x0b\n\r\x0c\\\t{^}|>'

So, the possible choices are the newline, tab, space, backslash and "<>{}^|. I guess I'll go with the space or newline. :)

NameError: global name is not defined

That's How Python works. Try this :

from sqlitedbx import SqliteDBzz

Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

As long as it's supposed to return a reference to the object, returning a NULL should be good.

However, if it's returning the whole bloody thing (like in C++ if you do: 'return blah;' rather than 'return &blah;' (or 'blah' is a pointer), then you can't return a NULL, because it's not of type 'object'. In that case, throwing an exception, or returning a blank object that doesn't have a success flag set is how I would approach the problem.

What are the JavaScript KeyCodes?

One possible answer will be given when you run this snippet.

_x000D_
_x000D_
document.write('<table>')_x000D_
for (var i = 0; i < 250; i++) {_x000D_
  document.write('<tr><td>' + i + '</td><td>' + String.fromCharCode(i) + '</td></tr>')_x000D_
}_x000D_
document.write('</table>')
_x000D_
td {_x000D_
  border: solid 1px;_x000D_
  padding: 1px 12px;_x000D_
  text-align: right;_x000D_
}_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
* {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.1em;_x000D_
}
_x000D_
_x000D_
_x000D_

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

Rails has an except/except! method that returns the hash with those keys removed. If you're already using Rails, there's no sense in creating your own version of this.

class Hash
  # Returns a hash that includes everything but the given keys.
  #   hash = { a: true, b: false, c: nil}
  #   hash.except(:c) # => { a: true, b: false}
  #   hash # => { a: true, b: false, c: nil}
  #
  # This is useful for limiting a set of parameters to everything but a few known toggles:
  #   @person.update(params[:person].except(:admin))
  def except(*keys)
    dup.except!(*keys)
  end

  # Replaces the hash without the given keys.
  #   hash = { a: true, b: false, c: nil}
  #   hash.except!(:c) # => { a: true, b: false}
  #   hash # => { a: true, b: false }
  def except!(*keys)
    keys.each { |key| delete(key) }
    self
  end
end

How to access a dictionary key value present inside a list?

Index the list then the dict.

print L[1]['d']

Remove Project from Android Studio

MAKE IT SIMPLE

  1. Open Project
  2. Go to AndroidStudioProjects Folder
  3. Right click on the project name to delete
  4. click Delete

Delete Android Studio Project

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).

Benefits

  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

How to change lowercase chars to uppercase using the 'keyup' event?

Solution 1 (Elegant approach with great user experience)

HTML

<input id="inputID" class="uppercase" name="inputName" value="" />

CSS

.uppercase{
    text-transform: uppercase;
}

JS

$('#inputID').on('blur', function(){
    this.value = this.value.toUpperCase();
});

By using CSS text-transform: uppercase; you'll eliminate the animation of lower to uppercase as the user types into the field.

Use blur event to handle converting to uppercase. This happens behind the scene as CSS took care of the user's visually appealing masking.

Solution 2 (Great, but less elegant)

If you insist on using keyup, here it is...

$('#inputID').on('keyup', function(){
    var caretPos = this.selectionStart;
    this.value = this.value.toUpperCase();
    this.setSelectionRange(caretPos, caretPos);
});

User would notice the animation of lowercase to uppercase as they type into the field. It gets the job done.

Solution 3 (Just get the job done)

$('#inputID').on('keyup', function(){
    this.value = this.value.toUpperCase();
});

This method is most commonly suggested but I do not recommend.

The downside of this solution is you'll be annoying the user as the cursor's caret position keeps jumping to the end of the text after every key input. Unless you know your users will never encounter typos or they will always clear the text and retype every single time, this method works.

Where can I find "make" program for Mac OS X Lion?

Xcode 4.3.2 didn't install "Command Line Tools" by default. I had to open Xcode Preferences / Downloads / Components Tab. It had a list of optional components with an "Install" button beside each. This includes "Command Line Tools" and components to support developing for older versions of iOS.

Now "make" is available and you can check by opening terminal and typing:make -v

The result should look like:GNU Make 3.81

You may need "make" even if you don't need Xcode, such as a Perl developer installing Perl Modules using cpan -i on the commandline.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

try to do the following:

  1. Make sure Office interop assemblies are installed.
  2. Check the version of the assemblies on development and production.
  3. Create Desktop folder under systemprofile.
  4. set the DCOM security explicitly for the service user.

you can find more details here

How to open a web page automatically in full screen mode

Only works in IE:

window.open ("mapage.html","","fullscreen=yes");  
window.open('','_parent','');  
window.close();

How to use font-awesome icons from node-modules

You will need to copy the files as part of your build process. For example, you can use a npm postinstall script to copy the files to the correct directory:

"postinstall": "cp -R node_modules/font-awesome/fonts ./public/"

For some build tools, there are preexisting font-awesome packages. For example, webpack has font-awesome-webpack which lets you simple require('font-awesome-webpack').

if else in a list comprehension

You can also put the conditional expression in brackets inside the list comprehension:

    l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
    print [[x+5,x+1][x >= 45] for x in l]

[false,true][condition] is the syntax

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. Variables are considered low level entities not suitable for higher levels of abstraction, thus the desire of many language designers to introduce similar but more powerful concepts like in Clojure, F#, Scala, where let might mean a value, or a variable that can be assigned, but not changed, which in turn lets the compiler catch more programming errors and optimize code better.

JavaScript has had var from the beginning, so they just needed another keyword, and just borrowed from dozens of other languages that use let already as a traditional keyword as close to var as possible, although in JavaScript let creates block scope local variable instead.

AngularJS toggle class using ng-class

How to use conditional in ng-class:

Solution 1:

<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>

Solution 2:

<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>

Solution 3 (angular v.1.1.4+ introduced support for ternary operator):

<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>

Plunker

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

How to select the Date Picker In Selenium WebDriver

You can try this, see if it works for you.

Rather than choosing date from date picker, you can enable the date box using javascript & enter the required date, this would avoid excessive time required to traverse through all date elements till you reach one you require to select.

Code for from date

((JavascriptExecutor)driver).executeScript ("document.getElementById('fromDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement fromDateBox= driver.findElement(By.id("fromDate"));
fromDateBox.clear();
fromDateBox.sendKeys("8-Dec-2014"); //Enter date in required format

Code for to date

((JavascriptExecutor)driver).executeScript ("document.getElementById('toDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement toDateBox= driver.findElement(By.id("toDate"));
toDateBox.clear();
toDateBox.sendKeys("15-Dec-2014"); //Enter date in required format

simple way to display data in a .txt file on a webpage?

You can add it as script file. save the txt file with js suffix

in the head section add

_x000D_
_x000D_
<script src="fileName.js"></script>
_x000D_
_x000D_
_x000D_

Getting full JS autocompletion under Sublime Text

I developed a new plugin called JavaScript Enhancements, that you can find on Package Control. It uses Flow (javascript static type checker from Facebook) under the hood.

Furthermore, it offers smart javascript autocomplete (compared to my other plugin JavaScript Completions), real-time errors, code refactoring and also a lot of features about creating, developing and managing javascript projects.

See the Wiki to know all the features that it offers!

An introduction to this plugin could be found in this css-tricks.com article: Turn Sublime Text 3 into a JavaScript IDE

Just some quick screenshots:

Android: show/hide a view using an animation

This can reasonably be achieved in a single line statement in API 12 and above. Below is an example where v is the view you wish to animate;

v.animate().translationXBy(-1000).start();

This will slide the View in question off to the left by 1000px. To slide the view back onto the UI we can simply do the following.

v.animate().translationXBy(1000).start();

I hope someone finds this useful.

Setting default value for TypeScript object passed as argument

Actually, there appears to now be a simple way. The following code works in TypeScript 1.5:

function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
  const name = first + ' ' + last;
  console.log(name);
}

sayName({ first: 'Bob' });

The trick is to first put in brackets what keys you want to pick from the argument object, with key=value for any defaults. Follow that with the : and a type declaration.

This is a little different than what you were trying to do, because instead of having an intact params object, you have instead have dereferenced variables.

If you want to make it optional to pass anything to the function, add a ? for all keys in the type, and add a default of ={} after the type declaration:

function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
    var name = first + " " + last;
    alert(name);
}

sayName();

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Using pure Eloquent, implement it like so. This code returns all logged in users whose accounts are active. $users = \App\User::where('status', 'active')->where('logged_in', true)->get();

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

JPA : How to convert a native query result set to POJO class collection

JPA provides an SqlResultSetMapping that allows you to map whatever returns from your native query into an Entity or a custom class.

EDIT JPA 1.0 does not allow mapping to non-entity classes. Only in JPA 2.1 a ConstructorResult has been added to map return values a java class.

Also, for OP's problem with getting count it should be enough to define a result set mapping with a single ColumnResult

Properly Handling Errors in VBA (Excel)

I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.

Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.

Option Explicit
Public booRefAdded As Boolean 'one time check for references

Public Sub Add_References()
Dim lngDLLmsadoFIND As Long

If Not booRefAdded Then
    lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found

        On Error GoTo RefErr:
            'Add Microsoft ActiveX Data Objects 2.8
            Application.VBE.ActiveVBProject.references.AddFromFile _
            Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"

        On Error GoTo 0

    Exit Sub

RefErr:
        Select Case Err.Number
            Case 0
                'no error
            Case 1004
                 'Enable Trust Centre Settings
                 MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
                 "Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
                 "1. Tick - 'Disable all macros with notification'" & Chr(10) & _
                 "2. Tick - 'Trust access to the VBA project objects model'")
                 End
            Case 32813
                 'Err.Number 32813 means reference already added
            Case 48
                 'Reference doesn't exist
                 If lngDLLmsadoFIND = 0 Then
                    MsgBox ("Cannot Find Required Reference")
                    End
                Else
                    For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
                           Resume
                    Next lngDLLmsadoFIND
                End If

            Case Else
                 MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
                End
        End Select

        On Error GoTo 0
End If
booRefAdded = TRUE
End Sub

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

A transport-level error has occurred when receiving results from the server

One of the reason I found for this error is 'Packet Size=xxxxx' in connection string. if the value of xxxx is too large, we will see this error. Either remove this value and let SQL server handle it or keep it low, depending on the network capabilities.

Append a dictionary to a dictionary

dict.update() looks like it will do what you want...

>> orig.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
>>> 

Perhaps, though, you don't want to update your original dictionary, but work on a copy:

>>> dest = orig.copy()
>>> dest.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2}
>>> dest
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}

How to make a flex item not fill the height of the flex container?

The align-items, or respectively align-content attribute controls this behaviour.

align-items defines the items' positioning perpendicularly to flex-direction.

The default flex-direction is row, therfore vertical placement can be controlled with align-items.

There is also the align-self attribute to control the alignment on a per item basis.

_x000D_
_x000D_
#a {_x000D_
  display:flex;_x000D_
_x000D_
  align-items:flex-start;_x000D_
  align-content:flex-start;_x000D_
  }_x000D_
_x000D_
#a > div {_x000D_
  _x000D_
  background-color:red;_x000D_
  padding:5px;_x000D_
  margin:2px;_x000D_
  }_x000D_
 #a > #c {_x000D_
  align-self:stretch;_x000D_
 }
_x000D_
<div id="a">_x000D_
  _x000D_
  <div id="b">left</div>_x000D_
  <div id="c">middle</div>_x000D_
  <div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

css-tricks has an excellent article on the topic. I recommend reading it a couple of times.

Accessing last x characters of a string in Bash

Another workaround is to use grep -o with a little regex magic to get three chars followed by the end of line:

$ foo=1234567890
$ echo $foo | grep -o ...$
890

To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep with this regex:

$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd

You can also use different ranges, such as 5,10 to get the last five to ten chars.

Rmi connection refused with localhost

it seems that you should set your command as an String[],for example:

String[] command = new String[]{"rmiregistry","2020"};
Runtime.getRuntime().exec(command);

it just like the style of main(String[] args).

Convert hex to binary

Here's a fairly raw way to do it using bit fiddling to generate the binary strings.

The key bit to understand is:

(n & (1 << i)) and 1

Which will generate either a 0 or 1 if the i'th bit of n is set.


import binascii

def byte_to_binary(n):
    return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8)))

def hex_to_binary(h):
    return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h))

print hex_to_binary('abc123efff')

>>> 1010101111000001001000111110111111111111

Edit: using the "new" ternary operator this:

(n & (1 << i)) and 1

Would become:

1 if n & (1 << i) or 0

(Which TBH I'm not sure how readable that is)

How to send a stacktrace to log4j?

Just because it happened to me and can be useful. If you do this

try {
   ...
} catch (Exception e) {
    log.error( "failed! {}", e );
}

you will get the header of the exception and not the whole stacktrace. Because the logger will think that you are passing a String. Do it without {} as skaffman said

Write variable to file, including name

Do you just want to know how to write a line to a file? First, you need to open the file:

f = open("filename.txt", 'w')

Then, you need to write the string to the file:

f.write("dict = {'one': 1, 'two': 2}" + '\n')

You can repeat this for each line (the +'\n' adds a newline if you want it).

Finally, you need to close the file:

f.close()

You can also be slightly more clever and use with:

with open("filename.txt", 'w') as f:
   f.write("dict = {'one': 1, 'two': 2}" + '\n')
   ### repeat for all desired lines

This will automatically close the file, even if exceptions are raised.

But I suspect this is not what you are asking...

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

For Android Studio on Mac :

Navigation Bar :

Android Studio > Preferences > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run

For Android Studio on Windows :

File > Settings > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run

How to see the CREATE VIEW code for a view in PostgreSQL?

If you want an ANSI SQL-92 version:

select view_definition from information_schema.views where table_name = 'view_name';

Get a filtered list of files in a directory

Keep it simple:

import os
relevant_path = "[path to folder]"
included_extensions = ['jpg','jpeg', 'bmp', 'png', 'gif']
file_names = [fn for fn in os.listdir(relevant_path)
              if any(fn.endswith(ext) for ext in included_extensions)]

I prefer this form of list comprehensions because it reads well in English.

I read the fourth line as: For each fn in os.listdir for my path, give me only the ones that match any one of my included extensions.

It may be hard for novice python programmers to really get used to using list comprehensions for filtering, and it can have some memory overhead for very large data sets, but for listing a directory and other simple string filtering tasks, list comprehensions lead to more clean documentable code.

The only thing about this design is that it doesn't protect you against making the mistake of passing a string instead of a list. For example if you accidentally convert a string to a list and end up checking against all the characters of a string, you could end up getting a slew of false positives.

But it's better to have a problem that's easy to fix than a solution that's hard to understand.

Partly cherry-picking a commit with Git

Assuming the changes you want are at the head of the branch you want the changes from, use git checkout

for a single file :

git checkout branch_that_has_the_changes_you_want path/to/file.rb

for multiple files just daisy chain :

git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb

What is the difference between <section> and <div>?

<section></section>

The HTML <section> element represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading. Each <section> should be identified, typically by including a heading (<h1>-<h6> element) as a child of the <section> element. For Details Please following link.

References :


<div></div>

The HTML <div> element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as <article> or <nav>) is appropriate.

References: - http://www.w3schools.com/tags/tag_div.asp - https://developer.mozilla.org/en/docs/Web/HTML/Element/div


Here are some links that discuss more about the differences between them:

How to change the default message of the required field in the popover of form-control in bootstrap?

Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Here,

this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field

oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.

log4net vs. Nlog

If you go here you can find a comprehensive matrix that includes both the NLog and Log4Net libs as well as Enterprise Lib and other products.

Somebody could argue that the matrix is done in a way to underline the features of the only commercial lib present in the matrix. I think it's true but it was useful anyway to drive my choice versus NLog.

Regards

json_encode(): Invalid UTF-8 sequence in argument

Updated.. I solved this issue by stating the charset on PDO connection as below:

"mysql:host=$host;dbname=$db;charset=utf8"

All data received was then in the correct charset for the rest of the code to use

Why extend the Android Application class?

To add onto the other answers that state that you might wish store variables in the application scope, for any long-running threads or other objects that need binding to your application where you are NOT using an activity (application is not an activity).. such as not being able to request a binded service.. then binding to the application instance is preferred. The only obvious warning with this approach is that the objects live for as long as the application is alive, so more implicit control over memory is required else you'll encounter memory-related problems like leaks.

Something else you may find useful is that in the order of operations, the application starts first before any activities. In this timeframe, you can prepare any necessary housekeeping that would occur before your first activity if you so desired.

2018-10-19 11:31:55.246 8643-8643/: application created
2018-10-19 11:31:55.630 8643-8643/: activity created

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);

Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
    Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
    Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});

how to parse JSON file with GSON

You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.

private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() {
}.getType();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list
data.toScreen(); // prints to screen some values

Java math function to convert positive int to negative and negative to positive?

We can reverse Java number int or double using this :

int x = 5;
int y = -7;

x = x - (x*2); // reverse to negative
y = y - (y*2); // reverse to positif

Simple algorithm to reverse number :)

A simple algorithm for polygon intersection

You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.

One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton

Alan Murta has a complete implementation of a polygon clipper GPC.

Edit:

Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Run below 2 commands in PowerShell window

  1. Set-ExecutionPolicy unrestricted

  2. Unblock-File -Path D:\PowerShell\Script.ps1

List of IP addresses/hostnames from local network in Python

Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).

https://github.com/vivkv/scanip

Is it possible to get only the first character of a String?

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

Compare given date with today

Expanding on Josua's answer from w3schools:

//create objects for the dates to compare
$date1=date_create($someDate);
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
//now convert the $diff object to type integer
$intDiff = $diff->format("%R%a");
$intDiff = intval($intDiff);
//now compare the two dates
if ($intDiff > 0)  {echo '$date1 is in the past';}
else {echo 'date1 is today or in the future';}

I hope this helps. My first post on stackoverflow!

What is the difference between the kernel space and the user space?

By Sunil Yadav, on Quora:

The Linux Kernel refers to everything that runs in Kernel mode and is made up of several distinct layers. At the lowest layer, the Kernel interacts with the hardware via the HAL. At the middle level, the UNIX Kernel is divided into 4 distinct areas. The first of the four areas handles character devices, raw and cooked TTY and terminal handling. The second area handles network device drivers, routing protocols and sockets. The third area handles disk device drivers, page and buffer caches, file system, virtual memory, file naming and mapping. The fourth and last area handles process dispatching, scheduling, creation and termination as well as signal handling. Above all this we have the top layer of the Kernel which includes system calls, interrupts and traps. This level serves as the interface to each of the lower level functions. A programmer uses the various system calls and interrupts to interact with the features of the operating system.

Android studio Gradle build speed up

For faster builds, increase the maximum heap size for the Gradle daemon to more than 2048 MB.

To do this set
org.gradle.jvmargs=-Xmx2048M
in the project gradle.properties.

android: changing option menu items programmatically

To disable certain items:

MenuItem item = menu.findItem(R.id.ID_ASSING_TO_THE_ITEM_IN_MENU_XML);
item.setEnabled(false);

Input placeholders for Internet Explorer

i use jquery.placeholderlabels. It's based on this and can be demoed here.

works in ie7, ie8, ie9.

behavior mimics current firefox and chrome behavior - where the the "placeholder" text remains visible on focus and only disappears once something is typed in the field.

Illegal mix of collations MySQL Error

Use following statement for error

be careful about your data take backup if data have in table.

 ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

How to select a single column with Entity Framework?

I'm a complete noob on Entity but this is how I would do it in theory...

var name = yourDbContext.MyTable.Find(1).Name;

If It's A Primary Key.

-- OR --

var name = yourDbContext.MyTable.SingleOrDefault(mytable => mytable.UserId == 1).Name;

-- OR --

For whole Column:

var names = yourDbContext.MyTable
.Where(mytable => mytable.UserId == 1)
.Select(column => column.Name); //You can '.ToList();' this....

But "oh Geez Rick, What do I know..."

Uncaught TypeError: (intermediate value)(...) is not a function

Error Case:

var userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

Output:

TypeError: (intermediate value)(intermediate value) is not a function

Fix: You are missing a semi-colon (;) to separate the expressions

userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}; // Without a semi colon, the error is produced

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

How can get the text of a div tag using only javascript (no jQuery)

Actually you dont need to call document.getElementById() function to get access to your div.

You can use this object directly by id:

text = test.textContent || test.innerText;
alert(text);

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

I found the simplest solution is to add two registry entries as follows (run this in a command prompt with admin privileges):

reg add HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 /v SchUseStrongCrypto /t REG_DWORD /d 1 /reg:32

reg add HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 /v SchUseStrongCrypto /t REG_DWORD /d 1 /reg:64

These entries seem to affect how the .NET CLR chooses a protocol when making a secure connection as a client.

There is more information about this registry entry here:

https://docs.microsoft.com/en-us/security-updates/SecurityAdvisories/2015/2960358#suggested-actions

Not only is this simpler, but assuming it works for your case, far more robust than a code-based solution, which requires developers to track protocol and development and update all their relevant code. Hopefully, similar environment changes can be made for TLS 1.3 and beyond, as long as .NET remains dumb enough to not automatically choose the highest available protocol.

NOTE: Even though, according to the article above, this is only supposed to disable RC4, and one would not think this would change whether the .NET client is allowed to use TLS1.2+ or not, for some reason it does have this effect.

NOTE: As noted by @Jordan Rieger in the comments, this is not a solution for POODLE, since it does not disable the older protocols a -- it merely allows the client to work with newer protocols e.g. when a patched server has disabled the older protocols. However, with a MITM attack, obviously a compromised server will offer the client an older protocol, which the client will then happily use.

TODO: Try to disable client-side use of TLS1.0 and TLS1.1 with these registry entries, however I don't know if the .NET http client libraries respect these settings or not:

https://docs.microsoft.com/en-us/windows-server/security/tls/tls-registry-settings#tls-10

https://docs.microsoft.com/en-us/windows-server/security/tls/tls-registry-settings#tls-11

How to install maven on redhat linux

I made the following script:

#!/bin/bash

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi

Remove certain characters from a string

One issue with REPLACE will be where city names contain the district name. You can use something like.

SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM   dbo.tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004' 

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

Convert NaN to 0 in javascript

_x000D_
_x000D_
    var i = [NaN, 1,2,3];

    var j = i.map(i =>{ return isNaN(i) ? 0 : i});
    
    console.log(j)
_x000D_
_x000D_
_x000D_

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

PHP preg functions needs your regex to be wrapped with a delimiter character, which can be any character. You can't use this delimiter character without escaping inside the regex. This should work (here the delimiter character is /):

preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', '2008-09-01 12:35:45');

// or this, to allow matching 0:00:00 time too.
preg_match('/\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}/', '2008-09-01 12:35:45');

If you need to match lines that contain only datetime, add ^ and $ at the beginning and end of the regex.

preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', '2008-09-01 12:35:45');

Link to PHP Manual's preg_match()

How can I get the corresponding table header (th) from a table cell (td)?

You can do it by using the td's index:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');

expected assignment or function call: no-unused-expressions ReactJS

I encountered the same error, with the below code.

    return this.state.employees.map((employee) => {
      <option value={employee.id}>
        {employee.name}
      </option>
    });

Above issue got resolved, when I changed curly braces to parenthesis, as indicated in the below modified code snippet.

      return this.state.employees.map((employee) => (
          <option value={employee.id}>
            {employee.name}
          </option>
        ));

Is it possible to sort a ES6 map object?

As far as I see it's currently not possible to sort a Map properly.

The other solutions where the Map is converted into an array and sorted this way have the following bug:

var a = new Map([[1, 2], [3,4]])
console.log(a);    // a = Map(2) {1 => 2, 3 => 4}

var b = a;
console.log(b);    // b = Map(2) {1 => 2, 3 => 4}

a = new Map();     // this is when the sorting happens
console.log(a, b); // a = Map(0) {}     b = Map(2) {1 => 2, 3 => 4}

The sorting creates a new object and all other pointers to the unsorted object get broken.

How do I use shell variables in an awk script?

Use either of these depending how you want backslashes in the shell variables handled (avar is an awk variable, svar is a shell variable):

awk -v avar="$svar" '... avar ...' file
awk 'BEGIN{avar=ARGV[1];ARGV[1]=""}... avar ...' "$svar" file

See http://cfajohnson.com/shell/cus-faq-2.html#Q24 for details and other options. The first method above is almost always your best option and has the most obvious semantics.

Android Horizontal RecyclerView scroll Direction

You can do it with just xml.

the app:reverseLayout="true" do the job!

<android.support.v7.widget.RecyclerView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:divider="@null"
                        android:orientation="horizontal"
                        app:reverseLayout="true"
                        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

Force unmount of NFS-mounted directory

I had the same problem, and neither umount /path -f, neither umount.nfs /path -f, neither fuser -km /path, works

finally I found a simple solution >.<

sudo /etc/init.d/nfs-common restart, then lets do the simple umount ;-)

jQuery Mobile: Stick footer to bottom of page

You can add this in your css file:

[data-role=page]{height: 100% !important; position:relative !important;}
[data-role=footer]{bottom:0; position:absolute !important; top: auto !important; width:100%;}  

So the page data-role now have 100% height, and footer is in absolute position.

Also Yappo have wrote an excellent plugin that you can find here: jQuery Mobile in a iScroll plugin http://yappo.github.com/projects/jquery.mobile.iscroll/livedemo.html

hope you found the answer!

An answer update

You can now use the data-position="fixed" attribute to keep your footer element on the bottom.
Docs and demos: http://view.jquerymobile.com/master/demos/toolbar-fixed/

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

In jQuery, how do I get the value of a radio button when they all have the same name?

You might want to change selector:

$('input[name=q12_3]:checked').val()

What is the easiest way to remove the first character from a string?

If you always want to strip leading brackets:

"[12,23,987,43".gsub(/^\[/, "")

If you just want to remove the first character, and you know it won't be in a multibyte character set:

"[12,23,987,43"[1..-1]

or

"[12,23,987,43".slice(1..-1)

MySQL CONCAT returns NULL if any field contain NULL

To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:

SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

The error is telling you it cannot find the class because it is not available in your application.

If you are using Maven, make sure you have the dependency for jstl artifact:

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
</dependency>

If you are not using it, just make sure you include the JAR in your classpath. See this answer for download links.

Eclipse error: indirectly referenced from required .class files?

I got this exception because eclipse was working in a different version of jdk, just changed to the correct, clean and build and worked!

How can I draw vertical text with CSS cross-browser?

I've had problems trying to do it in pure CSS - depending on the font it can look a bit rubbish. As an alternative you can use SVG/VML to do it. There are libraries that help make it cross browser with ease e.g. Raphael and ExtJS. In ExtJS4 the code looks like this:

    var drawComp = Ext.create('Ext.draw.Component', {
        renderTo: Ext.getBody(), //or whatever..
        height: 100, width: 100 //ditto..
    });
    var text = Ext.create('Ext.draw.Component', {
        type: "text",
        text: "The text to draw",
        rotate: {
            x: 0, y: 0, degrees: 270
        },
        x: -50, y: 10 //or whatever to fit (you could calculate these)..
    });
    text.show(true);

This will work in IE6+ and all modern browsers, however, unfortunately I think you need at least FF3.0.

BACKUP LOG cannot be performed because there is no current database backup

You can use following SQL to restore if you've already created database

RESTORE DATABASE [YourDB]
FROM DISK = 'C:\YourDB.bak'
WITH MOVE 'YourDB' TO 'C:\YourDB.mdf',
MOVE 'YourDB_Log' TO 'C:\YourDB.ldf', REPLACE

pgadmin4 : postgresql application server could not be contacted.

Got this issue after I upgraded PostgreSQL 9.4 to 9.6. The 9.4 binary package had PgAdmin 3 while 9.6 came with PgAdmin 4. I resolved it after a clean installation (I completely uninstalled and reinstalled) of PostgreSQL.

However, under different circumstances, you could try running the pgAdmin 4 application as an Administrator. This should fix the error.

Set element focus in angular way

About this solution, we could just create a directive and attach it to the DOM element that has to get the focus when a given condition is satisfied. By following this approach we avoid coupling controller to DOM element ID's.

Sample code directive:

gbndirectives.directive('focusOnCondition', ['$timeout',
    function ($timeout) {
        var checkDirectivePrerequisites = function (attrs) {
          if (!attrs.focusOnCondition && attrs.focusOnCondition != "") {
                throw "FocusOnCondition missing attribute to evaluate";
          }
        }

        return {            
            restrict: "A",
            link: function (scope, element, attrs, ctrls) {
                checkDirectivePrerequisites(attrs);

                scope.$watch(attrs.focusOnCondition, function (currentValue, lastValue) {
                    if(currentValue == true) {
                        $timeout(function () {                                                
                            element.focus();
                        });
                    }
                });
            }
        };
    }
]);

A possible usage

.controller('Ctrl', function($scope) {
   $scope.myCondition = false;
   // you can just add this to a radiobutton click value
   // or just watch for a value to change...
   $scope.doSomething = function(newMyConditionValue) {
       // do something awesome
       $scope.myCondition = newMyConditionValue;
  };

});

HTML

<input focus-on-condition="myCondition">

How to delete empty folders using windows command prompt?

This is a hybird of the above. It removes ALL files older than X days and removes any empty folders for the given path. To use simply set the days, folderpath and drive

@echo off
SETLOCAL
set days=30
set folderpath=E:\TEST\
set drive=E:

::Delete files
forfiles -p %folderpath% -s -d -%days% -c "cmd /c del /q @path "

::Delete folders
cd %folderpath%
%drive%
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"`

Function pointer to member function

Building on @IllidanS4 's answer, I have created a template class that allows virtually any member function with predefined arguments and class instance to be passed by reference for later calling.



template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs&&... rargs) = 0;
    //virtual RET call() = 0;
};

template<class T, class RET, class... RArgs> class CallbackCalltimeArgs : public Callback_t<RET, RArgs...> {
public:
    T * owner;
    RET(T::*x)(RArgs...);
    RET call(RArgs&&... rargs) {
        return (*owner.*(x))(std::forward<RArgs>(rargs)...);
    };
    CallbackCalltimeArgs(T* t, RET(T::*x)(RArgs...)) : owner(t), x(x) {}
};

template<class T, class RET, class... Args> class CallbackCreattimeArgs : public Callback_t<RET> {
public:
    T* owner;
    RET(T::*x)(Args...);
    RET call() {
        return (*owner.*(x))(std::get<Args&&>(args)...);
    };
    std::tuple<Args&&...> args;
    CallbackCreattimeArgs(T* t, RET(T::*x)(Args...), Args&&... args) : owner(t), x(x),
        args(std::tuple<Args&&...>(std::forward<Args>(args)...)) {}
};

Test / example:

class container {
public:
    static void printFrom(container* c) { c->print(); };
    container(int data) : data(data) {};
    ~container() {};
    void print() { printf("%d\n", data); };
    void printTo(FILE* f) { fprintf(f, "%d\n", data); };
    void printWith(int arg) { printf("%d:%d\n", data, arg); };
private:
    int data;
};

int main() {
    container c1(1), c2(20);
    CallbackCreattimeArgs<container, void> f1(&c1, &container::print);
    Callback_t<void>* fp1 = &f1;
    fp1->call();//1
    CallbackCreattimeArgs<container, void, FILE*> f2(&c2, &container::printTo, stdout);
    Callback_t<void>* fp2 = &f2;
    fp2->call();//20
    CallbackCalltimeArgs<container, void, int> f3(&c2, &container::printWith);
    Callback_t<void, int>* fp3 = &f3;
    fp3->call(15);//20:15
}

Obviously, this will only work if the given arguments and owner class are still valid. As far as readability... please forgive me.

Edit: removed unnecessary malloc by making the tuple normal storage. Added inherited type for the reference. Added option to provide all arguments at calltime instead. Now working on having both....

Edit 2: As promised, both. Only restriction (that I see) is that the predefined arguments must come before the runtime supplied arguments in the callback function. Thanks to @Chipster for some help with gcc compliance. This works on gcc on ubuntu and visual studio on windows.

#ifdef _WIN32
#define wintypename typename
#else
#define wintypename
#endif

template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs... rargs) = 0;
    virtual ~Callback_t() = default;
};

template<class RET, class... RArgs> class CallbackFactory {
private:
    template<class T, class... CArgs> class Callback : public Callback_t<RET, RArgs...> {
    private:
        T * owner;
        RET(T::*x)(CArgs..., RArgs...);
        std::tuple<CArgs...> cargs;
        RET call(RArgs... rargs) {
            return (*owner.*(x))(std::get<CArgs>(cargs)..., rargs...);
        };
    public:
        Callback(T* t, RET(T::*x)(CArgs..., RArgs...), CArgs... pda);
        ~Callback() {};
    };
public:
    template<class U, class... CArgs> static Callback_t<RET, RArgs...>* make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...));
};
template<class RET2, class... RArgs2> template<class T2, class... CArgs2> CallbackFactory<RET2, RArgs2...>::Callback<T2, CArgs2...>::Callback(T2* t, RET2(T2::*x)(CArgs2..., RArgs2...), CArgs2... pda) : x(x), owner(t), cargs(std::forward<CArgs2>(pda)...) {}
template<class RET, class... RArgs> template<class U, class... CArgs> Callback_t<RET, RArgs...>* CallbackFactory<RET, RArgs...>::make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...)) {
    return new wintypename CallbackFactory<RET, RArgs...>::Callback<U, CArgs...>(owner, func, std::forward<CArgs>(cargs)...);
}

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

Where is localhost folder located in Mac or Mac OS X?

If you use apachectl to start or stop, then you can find it with this command

apachectl -t -D DUMP_RUN_CFG

Proper MIME type for .woff2 fonts

Apache

In Apache, you can add the woff2 mime type via your .htaccess file as stated by this link.

AddType  application/font-woff2  .woff2

IIS

In IIS, simply add the following mimeMap tag into your web.config file inside the staticContent tag.

<configuration>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />

How to add jQuery in JS file

it is not possible to import js file inside another js file

The way to use jquery inside js is

import the js in the html or whatever view page you are using inside which you are going to include the js file

view.html

 <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
 <script src="<%=request.getContextPath()%>/js/default.js"></script>

default.js

$('document').ready(function() {
    $('li#user').click(function() {
         $(this).addClass('selectedEmp');
    });
});

this will definitely work for you

Parse an URL in JavaScript

function parse_url(str, component) {
  //       discuss at: http://phpjs.org/functions/parse_url/
  //      original by: Steven Levithan (http://blog.stevenlevithan.com)
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //         input by: Lorenzo Pisani
  //         input by: Tony
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //             note: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: blog post at http://blog.stevenlevithan.com/archives/parseuri
  //             note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
  //             note: a seriously malformed URL.
  //             note: Besides function name, is essentially the same as parseUri as well as our allowing
  //             note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
  //        example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
  //        returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}

  var query, key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',
      'relative', 'path', 'directory', 'file', 'query', 'fragment'
    ],
    ini = (this.php_js && this.php_js.ini) || {},
    mode = (ini['phpjs.parse_url.mode'] &&
      ini['phpjs.parse_url.mode'].local_value) || 'php',
    parser = {
      php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
    };

  var m = parser[mode].exec(str),
    uri = {},
    i = 14;
  while (i--) {
    if (m[i]) {
      uri[key[i]] = m[i];
    }
  }

  if (component) {
    return uri[component.replace('PHP_URL_', '')
      .toLowerCase()];
  }
  if (mode !== 'php') {
    var name = (ini['phpjs.parse_url.queryKey'] &&
      ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
    parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
    uri[name] = {};
    query = uri[key[12]] || '';
    query.replace(parser, function($0, $1, $2) {
      if ($1) {
        uri[name][$1] = $2;
      }
    });
  }
  delete uri.source;
  return uri;
}

reference

How do I execute .js files locally in my browser?

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

How do I resize a Google Map with JavaScript after it has loaded?

If you're using Google Maps v2, call checkResize() on your map after resizing the container. link

UPDATE

Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

How to return a string value from a Bash function

You could have the function take a variable as the first arg and modify the variable with the string you want to return.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

Prints "foo bar rab oof".

Edit: added quoting in the appropriate place to allow whitespace in string to address @Luca Borrione's comment.

Edit: As a demonstration, see the following program. This is a general-purpose solution: it even allows you to receive a string into a local variable.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar=''
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This prints:

+ return_var=
+ pass_back_a_string return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local lvar=
+ pass_back_a_string lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

Edit: demonstrating that the original variable's value is available in the function, as was incorrectly criticized by @Xichen Li in a comment.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "echo in pass_back_a_string, original $1 is \$$1"
    eval "$1='foo bar rab oof'"
}

return_var='original return_var'
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar='original lvar'
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This gives output:

+ return_var='original return_var'
+ pass_back_a_string return_var
+ eval 'echo in pass_back_a_string, original return_var is $return_var'
++ echo in pass_back_a_string, original return_var is original return_var
in pass_back_a_string, original return_var is original return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local 'lvar=original lvar'
+ pass_back_a_string lvar
+ eval 'echo in pass_back_a_string, original lvar is $lvar'
++ echo in pass_back_a_string, original lvar is original lvar
in pass_back_a_string, original lvar is original lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

PHP Warning: Unknown: failed to open stream

In my mind true way is:

# add READ permission to all directories and files under your DocumentRoot
sudo chmod +r /path/to/DocumentRoot/ -R

# add EXECUTE permission to all DIRECTORIES under your DocumentRoot
find /path/to/DocumentRoot/ -type d -exec chmod +x {} \;

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

How to convert HTML to PDF using iTextSharp

Here's the link I used as a guide. Hope this helps!

Converting HTML to PDF using ITextSharp

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string strHtml = string.Empty;
            //HTML File path -http://aspnettutorialonline.blogspot.com/
            string htmlFileName = Server.MapPath("~") + "\\files\\" + "ConvertHTMLToPDF.htm";
            //pdf file path. -http://aspnettutorialonline.blogspot.com/
            string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf";

            //reading html code from html file
            FileStream fsHTMLDocument = new FileStream(htmlFileName, FileMode.Open, FileAccess.Read);
            StreamReader srHTMLDocument = new StreamReader(fsHTMLDocument);
            strHtml = srHTMLDocument.ReadToEnd();
            srHTMLDocument.Close();

            strHtml = strHtml.Replace("\r\n", "");
            strHtml = strHtml.Replace("\0", "");

            CreatePDFFromHTMLFile(strHtml, pdfFileName);

            Response.Write("pdf creation successfully with password -http://aspnettutorialonline.blogspot.com/");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
    public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
    {
        try
        {
            object TargetFile = FileName;
            string ModifiedFileName = string.Empty;
            string FinalFileName = string.Empty;

            /* To add a Password to PDF -http://aspnettutorialonline.blogspot.com/ */
            TestPDF.HtmlToPdfBuilder builder = new TestPDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
            TestPDF.HtmlPdfPage first = builder.AddPage();
            first.AppendHtml(HtmlStream);
            byte[] file = builder.RenderPdf();
            File.WriteAllBytes(TargetFile.ToString(), file);

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
            ModifiedFileName = TargetFile.ToString();
            ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");

            string password = "password";
            iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, password, "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
            //http://aspnettutorialonline.blogspot.com/
            reader.Close();
            if (File.Exists(TargetFile.ToString()))
                File.Delete(TargetFile.ToString());
            FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
            File.Copy(ModifiedFileName, FinalFileName);
            if (File.Exists(ModifiedFileName))
                File.Delete(ModifiedFileName);

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

You can download the sample file. Just place the html you want to convert in the files folder and run. It will automatically generate the pdf file and place it in the same folder. But in your case, you can specify your html path in the htmlFileName variable.

How to trigger the window resize event in JavaScript?

With jQuery, you can try to call trigger:

$(window).trigger('resize');

TypeError: $.ajax(...) is not a function?

Neither of the answers here helped me. The problem was: I was using the slim build of jQuery, which had some things removed, ajax being one of them.

The solution: Just download the regular (compressed or not) version of jQuery here and include it in your project.

How to commit changes to a new branch

If you haven't committed changes

If your changes are compatible with the other branch

This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.

As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:

git checkout -b branch_name
git add <files>
git commit -m "message"

If your changes are incompatible with the other branch

If you get the error:

error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches

Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:

git stash
git checkout -b branch_name
git stash pop

It will be as if you had made those changes after creating the new branch. Then you can commit as usual:

git add <files>
git commit -m "message"

If you have committed changes

If you want to keep the commits in the original branch

See the answer by Carl Norum with cherry-picking, which is the right tool in this case:

git checkout <target name>
git cherry-pick <original branch>

If you don't want to keep the commits in the original branch

See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:

git branch -f <original branch> <earlier commit id>

If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.

Identifying country by IP address

No you can't - IP addresses get reallocated and reassigned from time to time, so the mapping of IP to location will also change over time.

If you want to find out the location that an IP address currently maps to you can either download a geolocation database, such as GeoLite from MaxMind, or use an API like http://ipinfo.io (my own service) which will also give you additional details:

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "loc": "37.385999999999996,-122.0838",
  "org": "AS15169 Google Inc.",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "phone": 650
}

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Passing bash variable to jq

Consider also passing in the shell variable (EMAILID) as a jq variable (here also EMAILID, for the sake of illustration):

   projectID=$(jq -r --arg EMAILID "$EMAILID" '
        .resource[]
        | select(.username==$EMAILID) 
        | .id' file.json)

Postscript

For the record, another possibility would be to use jq's env function for accessing environment variables. For example, consider this sequence of bash commands:

[email protected]  # not exported
EMAILID="$EMAILID" jq -n 'env.EMAILID'

The output is a JSON string:

"[email protected]"

Dynamic button click event handler

Just to round out Reed's answer, you can either get the Button objects from the Form or other container and add the handler, or you could create the Button objects programmatically.
If you get the Button objects from the Form or other container, then you can iterate over the Controls collection of the Form or other container control, such as Panel or FlowLayoutPanel and so on. You can then just add the click handler with
AddHandler ctrl.Click, AddressOf Me.Button_Click (variables as in the code below),
but I prefer to check the type of the Control and cast to a Button so as I'm not adding click handlers for any other controls in the container (such as Labels). Remember that you can add handlers for any event of the Button at this point using AddHandler.
Alternatively, you can create the Button objects programmatically, as in the second block of code below.
Then, of course, you have to write the handler method, as in the third code block below.

Here is an example using Form as the container, but you're probably better off using a Panel or some other container control.

Dim btn as Button = Nothing
For Each ctrl As Control in myForm.Controls
    If TypeOf ctrl Is Button Then
        btn = DirectCast(ctrl, Button)
        AddHandler btn.Click, AddressOf Me.Button_Click   ' From answer by Reed.
    End If
 Next

Alternatively creating the Buttons programmatically, this time adding to a Panel container.

Dim Panel1 As new Panel()
For i As Integer = 1 to 100
    btn = New Button()
    ' Set Button properties or call a method to do so.
    Panel1.Controls.Add(btn)  ' Add Button to the container.
    AddHandler btn.Click, AddressOf Me.Button_Click   ' Again from the answer by Reed.
Next

Then your handler will look something like this

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    ' Handle your Button clicks here
End Sub

Python: tf-idf-cosine: to find document similarity

WIth the Help of @excray's comment, I manage to figure it out the answer, What we need to do is actually write a simple for loop to iterate over the two arrays that represent the train data and test data.

First implement a simple lambda function to hold formula for the cosine calculation:

cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

And then just write a simple for loop to iterate over the to vector, logic is for every "For each vector in trainVectorizerArray, you have to find the cosine similarity with the vector in testVectorizerArray."

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA

train_set = ["The sky is blue.", "The sun is bright."] #Documents
test_set = ["The sun in the sky is bright."] #Query
stopWords = stopwords.words('english')

vectorizer = CountVectorizer(stop_words = stopWords)
#print vectorizer
transformer = TfidfTransformer()
#print transformer

trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray
cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

for vector in trainVectorizerArray:
    print vector
    for testV in testVectorizerArray:
        print testV
        cosine = cx(vector, testV)
        print cosine

transformer.fit(trainVectorizerArray)
print
print transformer.transform(trainVectorizerArray).toarray()

transformer.fit(testVectorizerArray)
print 
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()

Here is the output:

Fit Vectorizer to train set [[1 0 1 0]
 [0 1 0 1]]
Transform Vectorizer to test set [[0 1 1 1]]
[1 0 1 0]
[0 1 1 1]
0.408
[0 1 0 1]
[0 1 1 1]
0.816

[[ 0.70710678  0.          0.70710678  0.        ]
 [ 0.          0.70710678  0.          0.70710678]]

[[ 0.          0.57735027  0.57735027  0.57735027]]

WCF service startup error "This collection already contains an address with scheme http"

Did you see this - http://kb.discountasp.net/KB/a799/error-accessing-wcf-service-this-collection-already.aspx

You can resolve this error by changing the web.config file.

With ASP.NET 4.0, add the following lines to your web.config:

<system.serviceModel> 
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
</system.serviceModel> 

With ASP.NET 2.0/3.0/3.5, add the following lines to your web.config:

<system.serviceModel> 
     <serviceHostingEnvironment> 
          <baseAddressPrefixFilters> 
               <add prefix="http://www.YourHostedDomainName.com"/> 
          </baseAddressPrefixFilters> 
     </serviceHostingEnvironment> 
</system.serviceModel> 

Build a basic Python iterator

I see some of you doing return self in __iter__. I just wanted to note that __iter__ itself can be a generator (thus removing the need for __next__ and raising StopIteration exceptions)

class range:
  def __init__(self,a,b):
    self.a = a
    self.b = b
  def __iter__(self):
    i = self.a
    while i < self.b:
      yield i
      i+=1

Of course here one might as well directly make a generator, but for more complex classes it can be useful.

C#: Printing all properties of an object

Don't think so. I've always had to write them or use someone else's work to get that info. Has to be reflection as far as i'm aware.

EDIT:
Check this out. I was investigating some debugging on long object graphs and noticed this when i Add Watches, VS throws in this class: Mscorlib_CollectionDebugView<>. It's an internal type for displaying collections nicely for viewing in the watch windows/code debug modes. Now coz it's internal you can reference it, but u can use Reflector to copy (from mscorlib) the code and have your own (the link above has a copy/paste example). Looks really useful.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

For same error code i had quite different reason, I'm sharing here to help

I had web api action like below

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)

Cannot instantiate the type List<Product>

List can be instantiated by any class implementing the interface.By this way,Java provides us polymorphic behaviour.See the example below:

List<String> list = new ArrayList<String>();

Instead of instantiating an ArrayList directly,I am using a List to refer to ArrayList object so that we are using only the List interface methods and do not care about its actual implementation.

Examples of classes implementing List are ArrayList,LinkedList,Vector.You probably want to create a List depending upon your requirements.

Example:- a LinkedList is more useful when you hve to do a number of inertion or deletions .Arraylist is more performance intensive as it is backed by a fixed size array and array contents have to be changed by moving or regrowing the array.

Again,using a List we can simply change our object instantiation without changing any code further in your programs.

Suppose we are using ArrayList<String> value = new ArrayList<String>();

we may use a specific method of ArrrayList and out code will not be robust

By using List<String> value = new ArrayList<String>();

we are making sure we are using only List interface methods..and if we want to change it to a LinkedList we simply have to change the code :

List<String> value = new ArrayList<String>(); 

------ your code uses List interface methods.....

value = new LinkedList<String>(); 

-----your code still uses List interface methods and we do not have to change anything---- and we dont have to change anything in our code further

By the way a LinkedList also works a Deque which obviously also you cannot instantiate as it is also an interface

How do I get user IP address in django?

You can use django-ipware which supports Python 2 & 3 and handles IPv4 & IPv6.

Install:

pip install django-ipware

Simple Usage:

# In a view or a middleware where the `request` object is available

from ipware import get_client_ip
ip, is_routable = get_client_ip(request)
if ip is None:
    # Unable to get the client's IP address
else:
    # We got the client's IP address
    if is_routable:
        # The client's IP address is publicly routable on the Internet
    else:
        # The client's IP address is private

# Order of precedence is (Public, Private, Loopback, None)

Advanced Usage:

  • Custom Header - Custom request header for ipware to look at:

    i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
    i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])
    
  • Proxy Count - Django server is behind a fixed number of proxies:

    i, r = get_client_ip(request, proxy_count=1)
    
  • Trusted Proxies - Django server is behind one or more known & trusted proxies:

    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2'))
    
    # For multiple proxies, simply add them to the list
    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2', '177.3.3.3'))
    
    # For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
    

Note: read this notice.

How to "grep" for a filename instead of the contents of a file?

You need to use find instead of grep in this case.

You can also use find in combination with grep or egrep:

$ find | grep "f[[:alnum:]]\.frm"

JSON to pandas DataFrame

Just a new version of the accepted answer, as python3.x does not support urllib2

from requests import request
import json
from pandas.io.json import json_normalize

path1 = '42.974049,-81.205203|42.974298,-81.195755'
response=request(url='http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false', method='get')
elevations = response.json()
elevations
data = json.loads(elevations)
json_normalize(data['results'])

jQuery.animate() with css class only, without explicit styles

The jQueryUI provides a extension to animate function that allows you to animate css class.

edit: Example here

There are also methods to add/remove/toggle class which you might also be interested in.

initializing strings as null vs. empty string

I would prefere

if (!myStr.empty())
{
    //do something
}

Also you don't have to write std::string a = "";. You can just write std::string a; - it will be empty by default

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

How do I convert an enum to a list in C#?

List <SomeEnum> theList = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList();

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

Can I have H2 autocreate a schema in an in-memory database?

If you are using Spring Framework with application.yml and having trouble to make the test find the SQL file on the INIT property, you can use the classpath: notation.

For example, if you have a init.sql SQL file on the src/test/resources, just use:

url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;

Why does ++[[]][+[]]+[+[]] return the string "10"?

  1. Unary plus given string converts to number
  2. Increment operator given string converts and increments by 1
  3. [] == ''. Empty String
  4. +'' or +[] evaluates 0.

    ++[[]][+[]]+[+[]] = 10 
    ++[''][0] + [0] : First part is gives zeroth element of the array which is empty string 
    1+0 
    10
    

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

Creating a batch file, for simple javac and java command execution

The only other thing I would add is to make it a tad more flexible. Most times I'll have a trivial java file I want to run like - Main.java, Simple.java, Example.java, or Playground.java (you get the idea).

I use the following to strike off a javac and corresponding java.

@echo off
javac %~n1.java
java %~n1

The %~n1 gets the filename (sans extension) of the first argument passed to the batch file. So this way I can run it using tab completion and not have to worry about it working with either the .class or .java extension.

So both of the following will have the same result:

run.bat Main.class
and
run.bat Main.java

Doesn't 100% answer the original posters question, but I think it is a good next step/evolution for simple javac/java programs.

Excel concatenation quotes

Use CHAR:

=Char(34)&"This is in quotes"&Char(34)

Should evaluate to:

"This is in quotes"

How to search in a List of Java object

If you always search based on value3, you could store the objects in a Map:

Map<String, List<Sample>> map = new HashMap <>();

You can then populate the map with key = value3 and value = list of Sample objects with that same value3 property.

You can then query the map:

List<Sample> allSamplesWhereValue3IsDog = map.get("Dog");

Note: if no 2 Sample instances can have the same value3, you can simply use a Map<String, Sample>.

Twitter bootstrap modal-backdrop doesn't disappear

I am working with Meteor and I just got the same problem. The cause of my bug was this:

{{#if tourmanager}}
    {{>contactInformation tourmanager}}
{{else}}
    <a href="#addArtistTourmanagerModal" data-toggle="modal"><i class="fa fa-plus"></i> Tourmanager toevoegen</a>
    {{>addArtistTourmanagerModal}}
{{/if}}

As you can see I added the modal in the else, so when my modal updated the contactinformation the if had another state. This caused the modal template to be left out of the DOM just before it would close.

The solution: move the modal out of the if-else:

{{#if tourmanager}}
    {{>contactInformation tourmanager}}
{{else}}
    <a href="#addArtistTourmanagerModal" data-toggle="modal"><i class="fa fa-plus"></i> Tourmanager toevoegen</a>
    {{>addArtistTourmanagerModal}}
{{/if}}

How to improve performance of ngRepeat over a huge dataset (angular.js)?

If all your rows have equal height, you should definitely take a look at the virtualizing ng-repeat: http://kamilkp.github.io/angular-vs-repeat/

This demo looks very promising (and it supports inertial scrolling)

Temporary tables in stored procedures

For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.

Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.

e.g. create proc worker AS BEGIN -- do something here END

create proc wrapper AS
BEGIN
    Create table #...
    BEGIN TRY
       exec worker
       exec worker2 -- using same temp table
       -- etc
    END TRY
    END CATCH
       -- handle transaction cleanup here
       drop table #...
    END CATCH 
END

One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.

Open-Source Examples of well-designed Android Applications?

Use the Sample applications provided with your API version. If not provided, visit http://developer.android.com/tools/samples/index.html for getting the instructions of getting the application sample codes.

Install Qt on Ubuntu

Install Qt

sudo apt-get install build-essential

sudo apt-get install qtcreator

sudo apt-get install qt5-default

Install documentation and examples If Qt Creator is installed thanks to the Ubuntu Sofware Center or thanks to the synaptic package manager, documentation for Qt Creator is not installed. Hitting the F1 key will show you the following message : "No documentation available". This can easily be solved by installing the Qt documentation:

sudo apt-get install qt5-doc

sudo apt-get install qt5-doc-html qtbase5-doc-html

sudo apt-get install qtbase5-examples

Restart Qt Creator to make the documentation available.

Error while loading shared libraries

Problem:

radiusd: error while loading shared libraries: libfreeradius-radius-2.1.10.so: cannot open shared object file: No such file or directory

Reason:

Actually, the libraries have been installed in a place where dynamic linker cannot find it.

Solution:

While this is not a guarantee but using the following command may help you solve the “cannot open shared object file” error:

sudo /sbin/ldconfig -v

http://www.lucidarme.me/how-install-documentation-for-qt-creator/

https://ubuntuforums.org/showthread.php?t=2199929

https://itsfoss.com/error-while-loading-shared-libraries/

ModelSim-Altera error

Disable scrolling in all mobile devices

html, body {
  overflow-x: hidden;
}
body {
  position: relative;
}

The position relative is important, and i just stumbled about it. Could not make it work without it.

Connecting to remote URL which requires authentication using Java

I'd like to provide an answer for the case that you do not have control over the code that opens the connection. Like I did when using the URLClassLoader to load a jar file from a password protected server.

The Authenticator solution would work but has the drawback that it first tries to reach the server without a password and only after the server asks for a password provides one. That's an unnecessary roundtrip if you already know the server would need a password.

public class MyStreamHandlerFactory implements URLStreamHandlerFactory {

    private final ServerInfo serverInfo;

    public MyStreamHandlerFactory(ServerInfo serverInfo) {
        this.serverInfo = serverInfo;
    }

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        switch (protocol) {
            case "my":
                return new MyStreamHandler(serverInfo);
            default:
                return null;
        }
    }

}

public class MyStreamHandler extends URLStreamHandler {

    private final String encodedCredentials;

    public MyStreamHandler(ServerInfo serverInfo) {
        String strCredentials = serverInfo.getUsername() + ":" + serverInfo.getPassword();
        this.encodedCredentials = Base64.getEncoder().encodeToString(strCredentials.getBytes());
    }

    @Override
    protected URLConnection openConnection(URL url) throws IOException {
        String authority = url.getAuthority();
        String protocol = "http";
        URL directUrl = new URL(protocol, url.getHost(), url.getPort(), url.getFile());

        HttpURLConnection connection = (HttpURLConnection) directUrl.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);

        return connection;
    }

}

This registers a new protocol my that is replaced by http when credentials are added. So when creating the new URLClassLoader just replace http with my and everything is fine. I know URLClassLoader provides a constructor that takes an URLStreamHandlerFactory but this factory is not used if the URL points to a jar file.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

The answer of the user load step worked for me. Sometimes is need edit the file in /etc/mysql/my.cnf add line to client

[client]
password = your_mysql_root_password
port  = 3306
host  = 127.0.0.1
socket  = /var/lib/mysql/mysql.sock

How to unescape HTML character entities in Java?

In my case i use the replace method by testing every entity in every variable, my code looks like this:

text = text.replace("&Ccedil;", "Ç");
text = text.replace("&ccedil;", "ç");
text = text.replace("&Aacute;", "Á");
text = text.replace("&Acirc;", "Â");
text = text.replace("&Atilde;", "Ã");
text = text.replace("&Eacute;", "É");
text = text.replace("&Ecirc;", "Ê");
text = text.replace("&Iacute;", "Í");
text = text.replace("&Ocirc;", "Ô");
text = text.replace("&Otilde;", "Õ");
text = text.replace("&Oacute;", "Ó");
text = text.replace("&Uacute;", "Ú");
text = text.replace("&aacute;", "á");
text = text.replace("&acirc;", "â");
text = text.replace("&atilde;", "ã");
text = text.replace("&eacute;", "é");
text = text.replace("&ecirc;", "ê");
text = text.replace("&iacute;", "í");
text = text.replace("&ocirc;", "ô");
text = text.replace("&otilde;", "õ");
text = text.replace("&oacute;", "ó");
text = text.replace("&uacute;", "ú");

In my case this worked very well.

How to get data from Magento System Configuration

you should you use following code

$configValue = Mage::getStoreConfig(
                   'sectionName/groupName/fieldName',
                   Mage::app()->getStore()
               ); 

Mage::app()->getStore() this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.

if we have more then one store or multiple views configured then this will insure that we are getting values for current store

Get current date in DD-Mon-YYY format in JavaScript/Jquery

I've made a custom date string format function, you can use that.

var  getDateString = function(date, format) {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        getPaddedComp = function(comp) {
            return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
        },
        formattedDate = format,
        o = {
            "y+": date.getFullYear(), // year
            "M+": months[date.getMonth()], //month
            "d+": getPaddedComp(date.getDate()), //day
            "h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
             "H+": getPaddedComp(date.getHours()), //hour
            "m+": getPaddedComp(date.getMinutes()), //minute
            "s+": getPaddedComp(date.getSeconds()), //second
            "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
            "b+": (date.getHours() >= 12) ? 'PM' : 'AM'
        };

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                formattedDate = formattedDate.replace(RegExp.$1, o[k]);
            }
        }
        return formattedDate;
    };

And now suppose you've :-

    var date = "2014-07-12 10:54:11";

So to format this date you write:-

var formattedDate = getDateString(new Date(date), "d-M-y")

How to set min-font-size in CSS

.class {
    font-size: clamp(minimum-size, prefered-size, maximum-size)
}

using this you could set it up so prefered and max values are 5vw but the minimum is 15px or something so it won't go over 5vw but if 5vw < 15px it will stick to 15px

Generate your own Error code in swift 3

You should use NSError object.

let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invalid access token"])

Then cast NSError to Error object

Setting background colour of Android layout element

If you want to change a color quickly (and you don't have Hex numbers memorized) android has a few preset colors you can access like this:

android:background="@android:color/black"

There are 15 colors you can choose from which is nice for testing things out quickly, and you don't need to set up additional files.

Setting up a values/colors.xml file and using straight Hex like explained above will still work.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

<table>
     <ng-container *ngFor="let group of groups">
         <tr><td><h2>{{group.name}}</h2></td></tr>
         <tr *ngFor="let item of group.items"><td>{{item}}</td></tr>
     </ng-container>
</table>

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

In my case I had a multi module project just like you. I had to change a group Id of one of the external libraries my project was depending on as shown below.

From:

<dependencyManagement>
    <dependency>
        <groupId>org.thirdparty</groupId>
        <artifactId>calculation-api</artifactId>
        <version>2.0</version>
        <type>jar</type>
        <scope>provided</scope>
    </dependency>
<dependencyManagement>

To:

<dependencyManagement>
   <dependency>
      <groupId>org.thirdparty.module</groupId>
        <artifactId>calculation-api</artifactId>
        <version>2.0</version>
        <type>jar</type>
        <scope>provided</scope>
    </dependency>
<dependencyManagement>

Pay attention to the <groupId> section. It turned out that I was forgetting to modifiy the corresponding section of the submodules that define this dependency in their pom files.

It drove me very crazy because the module was available locally.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Python sys.argv lists and indexes

sys.argv is the list of arguments passed to the Python program. The first argument, sys.argv[0], is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0] exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1] is thus the first argument you actually pass to the program.

Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1].

Vbscript list all PDF files in folder and subfolders

You'll want to use the GetExtensionName method on the FileSystemObject object.

Set x = CreateObject("scripting.filesystemobject")
WScript.Echo x.GetExtensionName("foo.pdf")

In your example, try using this

For Each objFile in colFiles
    If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
        Wscript.Echo objFile.Name
    End If
Next

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

Importing larger sql files into MySQL

The question is a few months old but for other people looking --

A simpler way to import a large file is to make a sub directory 'upload' in your folder c:/wamp/apps/phpmyadmin3.5.2 and edit this line in the config.inc.php file in the same directory to include the folder name $cfg['UploadDir'] = 'upload';

Then place the incoming .sql file in the folder /upload.

Working from inside the phpmyadmin console, go to the new database and import. You will now see an additional option to upload files from that folder. Chose the correct file and be a little patient. It works.

If you still get a time out error try adding $cfg['ExecTimeLimit'] = 0; to the same config.inc.php file.

I have had difficulty importing an .sql file where the user name was root and the password differed from my the root password on my new server. I simply took off the password before I exported the .sql file and the import worked smoothly.

Returning an array using C

How about this deliciously evil implementation?

array.h

#define IMPORT_ARRAY(TYPE)    \
    \
struct TYPE##Array {    \
    TYPE* contents;    \
    size_t size;    \
};    \
    \
struct TYPE##Array new_##TYPE##Array() {    \
    struct TYPE##Array a;    \
    a.contents = NULL;    \
    a.size = 0;    \
    return a;    \
}    \
    \
void array_add(struct TYPE##Array* o, TYPE value) {    \
    TYPE* a = malloc((o->size + 1) * sizeof(TYPE));    \
    TYPE i;    \
    for(i = 0; i < o->size; ++i) {    \
        a[i] = o->contents[i];    \
    }    \
    ++(o->size);    \
    a[o->size - 1] = value;    \
    free(o->contents);    \
    o->contents = a;    \
}    \
void array_destroy(struct TYPE##Array* o) {    \
    free(o->contents);    \
}    \
TYPE* array_begin(struct TYPE##Array* o) {    \
    return o->contents;    \
}    \
TYPE* array_end(struct TYPE##Array* o) {    \
    return o->contents + o->size;    \
}

main.c

#include <stdlib.h>
#include "array.h"

IMPORT_ARRAY(int);

struct intArray return_an_array() {
    struct intArray a;
    a = new_intArray();
    array_add(&a, 1);
    array_add(&a, 2);
    array_add(&a, 3);
    return a;
}

int main() {
    struct intArray a;
    int* it;
    int* begin;
    int* end;
    a = return_an_array();
    begin = array_begin(&a);
    end = array_end(&a);
    for(it = begin; it != end; ++it) {
        printf("%d ", *it);
    }
    array_destroy(&a);
    getchar();
    return 0;
}

MySQL, Concatenate two columns

You can use php built in CONCAT() for this.

SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;

change filed name as your requirement

then the result is

enter image description here

and if you want to concat same filed using other field which same then

SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1 

then this is output enter image description here

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

Ajax LARAVEL 419 POST error

You may also get that error when CSRF "token" for the active user session is out of date, even if the token was specified in ajax request.

Can I store images in MySQL

You'll need to save as a blob, LONGBLOB datatype in mysql will work.

Ex:

CREATE TABLE 'test'.'pic' (
    'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
    'caption' VARCHAR(45) NOT NULL,
    'img' LONGBLOB NOT NULL,
  PRIMARY KEY ('idpic')
)

As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

I found this url to be very useful: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/2cdcab2e-ea49-4fd5-b2b8-13824ab4619b/help-server-not-listening-on-1433

In particular, my problem was that I did not enable the TCP/IP in Sql Server Configuration Manager->SQL Server Network Configuration->Protocols for SQLEXPRESS.

Once you open it, you have to go to the IP Addresses tab and for me, changing IPAll to TCP port 1433 and deleting the TCP Dynamic Ports value worked.

Follow the other steps to make sure 1433 is listening (Use netstat -an to make sure 0.0.0.0:1433 is LISTENING.), and that you can telnet to the port from the client machine.

Finally, I second the suggestion to remove the \SQLEXPRESS from the connection.

EDIT: I should note I am using SQL Server 2014 Express.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Serhii's suggestion works and here is some more detail.

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Hope this helps, Glenn

Bootstrap Carousel : Remove auto slide

From the official docs:

interval The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.

You can either pass this value with javascript or using a data-interval="false" attribute.

How to add CORS request in header in Angular 5

please import requestoptions from angular cors

    import {RequestOptions, Request, Headers } from '@angular/http';

and add request options in your code like given below

    let requestOptions = new RequestOptions({ headers:null, withCredentials: 
    true });

send request option in your api request

code snippet below-

     let requestOptions = new RequestOptions({ headers:null, 
     withCredentials: true });
     return this.http.get(this.config.baseUrl + 
     this.config.getDropDownListForProject, requestOptions)
     .map(res => 
     {
      if(res != null)
      { 
        return res.json();
        //return true;
      }
    })
  .catch(this.handleError);
   }  

and add CORS in your backend PHP code where all api request will land first.

try this and let me know if it is working or not i had a same issue i was adding CORS from angular5 that was not working then i added CORS to backend and it worked for me

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Android Activity without ActionBar

If you're using AppCompat, declare your activity in AndroidManifest.xml as follows:

<activity
    android:name=".SomeActivity"
    ...
    android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

How to set environment via `ng serve` in Angular 6

For Angular 2 - 5 refer the article Multiple Environment in angular

For Angular 6 use ng serve --configuration=dev

Note: Refer the same article for angular 6 as well. But wherever you find --env instead use --configuration. That's works well for angular 6.

Make Font Awesome icons in a circle?

_x000D_
_x000D_
i.fa {_x000D_
  display: inline-block;_x000D_
  border-radius: 60px;_x000D_
  box-shadow: 0px 0px 2px #888;_x000D_
  padding: 0.5em 0.6em;_x000D_
_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<i class="fa fa-wrench"></i>
_x000D_
_x000D_
_x000D_


JsFiddle of old answer: http://fiddle.jshell.net/4LqeN/

Java: Retrieving an element from a HashSet

One of the easiest ways is to convert to Array:

for(int i = 0; i < set.size(); i++) {
    System.out.println(set.toArray()[i]);
}

how to install gcc on windows 7 machine?

  1. Extract the package to C:\ from here and install it

  2. Copy the path C:\MinGW\bin which contains gcc.exe.

  3. go to Control Panel->System->Advanced>Environment variables, and add or modify PATH. (just concatenate with ';')

  4. Then, open a cmd.exe command prompt (Windows + R and type cmd, if already opened, please close and open a new one, to get the path change)

  5. change the folder to your file path by cd D:\c code Path

  6. type gcc main.c -o helloworld.o. It will compile the code. for C++ use g++

7 type ./helloworld to run the program.

If zlib1.dll is missing, download from here

Convert a float64 to an int in Go

You can use int() function to convert float64 type data to an int. Similarly you can use float64()

Example:

func check(n int) bool { 
    // count the number of digits 
    var l int = countDigit(n)
    var dup int = n 
    var sum int = 0 

    // calculates the sum of digits 
    // raised to power 
    for dup > 0 { 
        **sum += int(math.Pow(float64(dup % 10), float64(l)))** 
        dup /= 10 
    } 

    return n == sum
} 

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

Another option would be to check the error code generated using try-catch block and first catching a WebException.

In my case, the error code was "SendFailure" because of certificate issue on HTTPS url, once I hit HTTP, that got resolved.

https://docs.microsoft.com/en-us/dotnet/api/system.net.webexceptionstatus?redirectedfrom=MSDN&view=netframework-4.8

Removing Java 8 JDK from Mac

in Mac Remove Java Version using this 3 Commands

java -version

sudo rm -rf /Library/Java/*

sudo rm -rf /Library/PreferencePanes/Java*

sudo rm -rf /Library/Internet\ Plug-Ins/Java*

Run

java -version

//See java was successfully uninstalled.

java -version sudo rm -rf /Library/Java/* sudo rm -rf /Library/PreferencePanes/Java* sudo rm -rf /Library/Internet\ Plug-Ins/Java*

Run java -version

Install Java 8 Link

enter image description here

Download Package and click next next next

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

How to load a jar file at runtime

Reloading existing classes with existing data is likely to break things.

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

Of course debugging systems can do fancier things, but are more hacky and less reliable.

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

List to array conversion to use ravel() function

Use numpy.asarray:

import numpy as np
myarray = np.asarray(mylist)

creating a random number using MYSQL

This should give what you want:

FLOOR(RAND() * 401) + 100

Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min> generates a number between <min> and <max> inclusive.

Update

This full statement should work:

SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number` 
FROM users

Comparing the contents of two files in Sublime Text

No one is talking about Linux but all above answers will work. Just use Ctrl to select more than one file. If you are looking to compare side by side, Meld is lovely.

How to center a navigation bar with CSS or HTML?

The best way to fix it I have looked for the code or trick how to center nav menu and found the real solutions it works for all browsers and for my friends ;)

Here is how I have done:

body {
    margin: 0;
    padding: 0;
}

div maincontainer {
    margin: 0 auto;
    width: ___px;
    text-align: center;
}

ul {
    margin: 0;
    padding: 0;
}

ul li {
    margin-left: auto;
    margin-right: auto;
}

and do not forget to set doctype html5

Line Break in XML?

<song>
  <title>Song Tigle</title>
  <lyrics>
    <line>The is the very first line</line>
    <line>Number two and I'm still feeling fine</line>
    <line>Number three and a pattern begins</line>
    <line>Add lines like this and everyone wins!</line>
  </lyrics>
</song>

(Sung to the tune of Home on the Range)

If it was mine I'd wrap the choruses and verses in XML elements as well.

How to install ADB driver for any android device?

UNIVERSAL ADB DRIVER

I have thesame issue before but i solved it easily by just following this steps:

*connect your android phone in a debugging mode (to enable debugging mode goto settings scroll down About Phone scroll down tap seven times Build Number and it will automatically enable developer option turn on developer options and check USB debugging)

download Universal ADB Driver Installer

*choose Adb Driver Installer (Universal)

*install it *it will automatically detect your android device(any kind of brand) *chose the device and install

How to pass an object into a state using UI-router?

In version 0.2.13, You should be able to pass objects into $state.go,

$state.go('myState', {myParam: {some: 'thing'}})

$stateProvider.state('myState', {
                url: '/myState/{myParam:json}',
                params: {myParam: null}, ...

and then access the parameter in your controller.

$stateParams.myParam //should be {some: 'thing'}

myParam will not show up in the URL.

Source:

See the comment by christopherthielen https://github.com/angular-ui/ui-router/issues/983, reproduced here for convenience:

christopherthielen: Yes, this should be working now in 0.2.13.

.state('foo', { url: '/foo/:param1?param2', params: { param3: null } // null is the default value });

$state.go('foo', { param1: 'bar', param2: 'baz', param3: { id: 35, name: 'what' } });

$stateParams in 'foo' is now { param1: 'bar', param2: 'baz', param3: { id: 35, name: 'what' } }

url is /foo/bar?param2=baz.

Find and extract a number from a string

var match=Regex.Match(@"a99b",@"\d+");
if(match.Success)
{
    int val;
    if(int.TryParse(match.Value,out val))
    {
        //val is set
    }
}

Adding whitespace in Java

String text = "text";
text += new String(" ");

Create a dictionary with list comprehension

In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

What properties can I use with event.target?

//Do it like---
function dragStart(this_,event) {
    var row=$(this_).attr('whatever');
    event.dataTransfer.setData("Text", row);
}

Type or namespace name does not exist

I have experienced same problem with System.Data.SQLite. The source of the problem is the dll you have used should have same .NET version with your project.

For example if you have used (in my case) SQLite for .NET 4.5, your platform target should be .NET 4.5 too.

You can find platform target by: Project > (project name) Properties > Build.

How to get annotations of a member variable?

package be.fery.annotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;

@Entity
public class User {
    @Id
    private Long id;

    @Column(name = "ADDRESS_ID")
    private Address address;

    @PrePersist
    public void doStuff(){

    }
}

And a testing class:

    package be.fery.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationIntrospector {

    public AnnotationIntrospector() {
        super();
    }

    public Annotation[] findClassAnnotation(Class<?> clazz) {
        return clazz.getAnnotations();
    }

    public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {

        Annotation[] annotations = null;
        try {
            Class<?>[] params = null;
            Method method = clazz.getDeclaredMethod(methodName, params);
            if (method != null) {
                annotations = method.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
        Annotation[] annotations = null;
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                annotations = field.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        AnnotationIntrospector ai = new AnnotationIntrospector();
        Annotation[] annotations;
        Class<User> userClass = User.class;
        String methodDoStuff = "doStuff";
        String fieldId = "id";
        String fieldAddress = "address";

        // Find class annotations
        annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
        System.out.println("Annotation on class '" + userClass.getName()
                + "' are:");
        showAnnotations(annotations);

        // Find method annotations
        annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
        System.out.println("Annotation on method '" + methodDoStuff + "' are:");
        showAnnotations(annotations);

        // Find field annotations
        annotations = ai.findFieldAnnotation(User.class, fieldId);
        System.out.println("Annotation on field '" + fieldId + "' are:");
        showAnnotations(annotations);

        annotations = ai.findFieldAnnotation(User.class, fieldAddress);
        System.out.println("Annotation on field '" + fieldAddress + "' are:");
        showAnnotations(annotations);

    }

    public static void showAnnotations(Annotation[] ann) {
        if (ann == null)
            return;
        for (Annotation a : ann) {
            System.out.println(a.toString());
        }
    }

}

Hope it helps...

;-)

Getting last day of the month in a given string date

Use GregorianCalendar. Set the date of the object, and then use getActualMaximum(Calendar.DAY_IN_MONTH).

http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (but it was the same in Java 1.4)

Box shadow for bottom side only

Specify negative value to spread value. This works for me:

box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);