Programs & Examples On #Tdbgrid

TDBGrid is a VCL control used to display and manipulate records from a TDataset in a tabular fashioned way. It is defined in DbGrids.pas unit.

Class JavaLaunchHelper is implemented in two places

I have found the other workaround: to exclude libinstrument.dylib from project path. To do so, go to the Preferences -> Build, Execution and Deployment -> Compiler -> Excludes -> + and here add file by the path in error message.

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

I was playing around with C# code an I accidentally found the solution to your problem haha

This is the code for the Principal view:

`@model dynamic 
 @Html.Partial("_Partial", Model as IDictionary<string, object>)`

Then in the Partial view:

`@model dynamic 
 @if (Model != null) { 
   foreach (var item in Model) 
   { 
    <div>@item.text</div> 
   } 
  }`

It worked for me, I hope this will help you too!!

What is the difference between private and protected members of C++ classes?

private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.

You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.

Getting permission denied (public key) on gitlab

The problem for me was, that I switched UsePAM from yes to no in the SSH configuration file under /etc/ssh/sshd_config. With UsePAM yes everything works perfectly.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

how to change the dist-folder path in angular-cli after 'ng build'

Beware: The correct answer is below. This no longer works

Create a file called .ember-cli in your project, and include in it these contents:

{
   "output-path": "./location/to/your/dist/"
}

Laravel 5 Class 'form' not found

Just type the following command in terminal at the project directory and installation is done according the Laravel version:

composer require "laravelcollective/html"

Then add these lines in config/app.php

'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
],

'aliases' => [
    // ...
   'Form' => Collective\Html\FormFacade::class,
   'Html' => Collective\Html\HtmlFacade::class,
    // ...
],

How to host a Node.Js application in shared hosting

I installed Node.js on bluehost.com (a shared server) using:

wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node

This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.

then

./node/bin/npm install jt-js-sample

Returns:
npm WARN engine [email protected]: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
[email protected] node_modules/jt-js-sample
+-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

I can now use the commands:

# ~/node/bin/node -v
v0.12.4

# ~/node/bin/npm -v
2.10.1

For security reasons, I have renamed my node directory to something else.

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.

Open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox.

How do I concatenate a boolean to a string in Python?

The recommended way is to let str.format handle the casting (docs). Methods with %s substitution may be deprecated eventually (see PEP3101).

>>> answer = True
>>> myvar = "the answer is {}".format(answer)
>>> print(myvar)
the answer is True

In Python 3.6+ you may use literal string interpolation:

 >>> print(f"the answer is {answer}")
the answer is True

Understanding __get__ and __set__ and Python descriptors

Before going into the details of descriptors it may be important to know how attribute lookup in Python works. This assumes that the class has no metaclass and that it uses the default implementation of __getattribute__ (both can be used to "customize" the behavior).

The best illustration of attribute lookup (in Python 3.x or for new-style classes in Python 2.x) in this case is from Understanding Python metaclasses (ionel's codelog). The image uses : as substitute for "non-customizable attribute lookup".

This represents the lookup of an attribute foobar on an instance of Class:

enter image description here

Two conditions are important here:

  • If the class of instance has an entry for the attribute name and it has __get__ and __set__.
  • If the instance has no entry for the attribute name but the class has one and it has __get__.

That's where descriptors come into it:

  • Data descriptors which have both __get__ and __set__.
  • Non-data descriptors which only have __get__.

In both cases the returned value goes through __get__ called with the instance as first argument and the class as second argument.

The lookup is even more complicated for class attribute lookup (see for example Class attribute lookup (in the above mentioned blog)).

Let's move to your specific questions:

Why do I need the descriptor class?

In most cases you don't need to write descriptor classes! However you're probably a very regular end user. For example functions. Functions are descriptors, that's how functions can be used as methods with self implicitly passed as first argument.

def test_function(self):
    return self

class TestClass(object):
    def test_method(self):
        ...

If you look up test_method on an instance you'll get back a "bound method":

>>> instance = TestClass()
>>> instance.test_method
<bound method TestClass.test_method of <__main__.TestClass object at ...>>

Similarly you could also bind a function by invoking its __get__ method manually (not really recommended, just for illustrative purposes):

>>> test_function.__get__(instance, TestClass)
<bound method test_function of <__main__.TestClass object at ...>>

You can even call this "self-bound method":

>>> test_function.__get__(instance, TestClass)()
<__main__.TestClass at ...>

Note that I did not provide any arguments and the function did return the instance I had bound!

Functions are Non-data descriptors!

Some built-in examples of a data-descriptor would be property. Neglecting getter, setter, and deleter the property descriptor is (from Descriptor HowTo Guide "Properties"):

class Property(object):
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

Since it's a data descriptor it's invoked whenever you look up the "name" of the property and it simply delegates to the functions decorated with @property, @name.setter, and @name.deleter (if present).

There are several other descriptors in the standard library, for example staticmethod, classmethod.

The point of descriptors is easy (although you rarely need them): Abstract common code for attribute access. property is an abstraction for instance variable access, function provides an abstraction for methods, staticmethod provides an abstraction for methods that don't need instance access and classmethod provides an abstraction for methods that need class access rather than instance access (this is a bit simplified).

Another example would be a class property.

One fun example (using __set_name__ from Python 3.6) could also be a property that only allows a specific type:

class TypedProperty(object):
    __slots__ = ('_name', '_type')
    def __init__(self, typ):
        self._type = typ

    def __get__(self, instance, klass=None):
        if instance is None:
            return self
        return instance.__dict__[self._name]

    def __set__(self, instance, value):
        if not isinstance(value, self._type):
            raise TypeError(f"Expected class {self._type}, got {type(value)}")
        instance.__dict__[self._name] = value

    def __delete__(self, instance):
        del instance.__dict__[self._name]

    def __set_name__(self, klass, name):
        self._name = name

Then you can use the descriptor in a class:

class Test(object):
    int_prop = TypedProperty(int)

And playing a bit with it:

>>> t = Test()
>>> t.int_prop = 10
>>> t.int_prop
10

>>> t.int_prop = 20.0
TypeError: Expected class <class 'int'>, got <class 'float'>

Or a "lazy property":

class LazyProperty(object):
    __slots__ = ('_fget', '_name')
    def __init__(self, fget):
        self._fget = fget

    def __get__(self, instance, klass=None):
        if instance is None:
            return self
        try:
            return instance.__dict__[self._name]
        except KeyError:
            value = self._fget(instance)
            instance.__dict__[self._name] = value
            return value

    def __set_name__(self, klass, name):
        self._name = name

class Test(object):
    @LazyProperty
    def lazy(self):
        print('calculating')
        return 10

>>> t = Test()
>>> t.lazy
calculating
10
>>> t.lazy
10

These are cases where moving the logic into a common descriptor might make sense, however one could also solve them (but maybe with repeating some code) with other means.

What is instance and owner here? (in __get__). What is the purpose of these parameters?

It depends on how you look up the attribute. If you look up the attribute on an instance then:

  • the second argument is the instance on which you look up the attribute
  • the third argument is the class of the instance

In case you look up the attribute on the class (assuming the descriptor is defined on the class):

  • the second argument is None
  • the third argument is the class where you look up the attribute

So basically the third argument is necessary if you want to customize the behavior when you do class-level look-up (because the instance is None).

How would I call/use this example?

Your example is basically a property that only allows values that can be converted to float and that is shared between all instances of the class (and on the class - although one can only use "read" access on the class otherwise you would replace the descriptor instance):

>>> t1 = Temperature()
>>> t2 = Temperature()

>>> t1.celsius = 20   # setting it on one instance
>>> t2.celsius        # looking it up on another instance
20.0

>>> Temperature.celsius  # looking it up on the class
20.0

That's why descriptors generally use the second argument (instance) to store the value to avoid sharing it. However in some cases sharing a value between instances might be desired (although I cannot think of a scenario at this moment). However it makes practically no sense for a celsius property on a temperature class... except maybe as purely academic exercise.

Adding a leading zero to some values in column in MySQL

A previous answer using LPAD() is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.

UPDATE
    mytable
SET
    mycolumn = CONCAT(
        REPEAT(
            "0",
            8 - LENGTH(mycolumn)
        ),
        mycolumn
    )
WHERE
    LENGTH(mycolumn) < 8;

Split / Explode a column of dictionaries into separate columns with pandas

Merlin's answer is better and super easy, but we don't need a lambda function. The evaluation of dictionary can be safely ignored by either of the following two ways as illustrated below:

Way 1: Two steps

# step 1: convert the `Pollutants` column to Pandas dataframe series
df_pol_ps = data_df['Pollutants'].apply(pd.Series)

df_pol_ps:
    a   b   c
0   46  3   12
1   36  5   8
2   NaN 2   7
3   NaN NaN 11
4   82  NaN 15

# step 2: concat columns `a, b, c` and drop/remove the `Pollutants` 
df_final = pd.concat([df, df_pol_ps], axis = 1).drop('Pollutants', axis = 1)

df_final:
    StationID   a   b   c
0   8809    46  3   12
1   8810    36  5   8
2   8811    NaN 2   7
3   8812    NaN NaN 11
4   8813    82  NaN 15

Way 2: The above two steps can be combined in one go:

df_final = pd.concat([df, df['Pollutants'].apply(pd.Series)], axis = 1).drop('Pollutants', axis = 1)

df_final:
    StationID   a   b   c
0   8809    46  3   12
1   8810    36  5   8
2   8811    NaN 2   7
3   8812    NaN NaN 11
4   8813    82  NaN 15

vagrant login as root by default

This is useful:

sudo passwd root

for anyone who's been caught out by the need to set a root password in vagrant first

How to import CSV file data into a PostgreSQL table?

DBeaver Community Edition (dbeaver.io) makes it trivial to connect to a database, then import a CSV file for upload to a PostgreSQL database. It also makes it easy to issue queries, retrieve data, and download result sets to CSV, JSON, SQL, or other common data formats.

It is a FOSS multi-platform database tool for SQL programmers, DBAs and analysts that supports all popular databases: MySQL, PostgreSQL, SQLite, Oracle, DB2, SQL Server, Sybase, MS Access, Teradata, Firebird, Hive, Presto, etc. It's a viable FOSS competitor to TOAD for Postgres, TOAD for SQL Server, or Toad for Oracle.

I have no affiliation with DBeaver. I love the price (FREE!) and full functionality, but I wish they would open up this DBeaver/Eclipse application more and make it easy to add analytics widgets to DBeaver / Eclipse, rather than requiring users to pay for the $199 annual subscription just to create graphs and charts directly within the application. My Java coding skills are rusty and I don't feel like taking weeks to relearn how to build Eclipse widgets, (only to find that DBeaver has probably disabled the ability to add third-party widgets to the DBeaver Community Edition.)

Can DBeaver power users who are Java developers provide some insight about the steps to create analytics widgets to add into the Community Edition of DBeaver?

What is an idempotent operation?

retry-safe.

Is usually the easiest way to understand its meaning in computer science.

Git: How to return from 'detached HEAD' state

I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:

git checkout 1.87.1                                    
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. 
Example:

  git checkout -b <new-branch-name>

HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'

In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).

git checkout master did not work:

$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...

git checkout master --force (or git checkout master -f) worked:

git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

Python integer division yields float

Take a look at PEP-238: Changing the Division Operator

The // operator will be available to request floor division unambiguously.

How stable is the git plugin for eclipse?

It still seems barely usable, to tell the truth, especially in comparison to the CVS and SVN plugins. Is it really GIT so different that developer with four years of CVS and SVN plugin experience should be completely lost with completely different GUI, unheard commands, two or even single word error messages and "features" like overwriting the shared repository without warning? Do not use it, use command line interface. If you do not like command line interface, do not use GIT at all.

Can regular JavaScript be mixed with jQuery?

Why is MichalBE getting downvoted? He's right - using jQuery (or any library) just to fire a function on page load is overkill, potentially costing people money on mobile connections and slowing down the user experience. If the original poster doesn't want to use onload in the body tag (and he's quite right not to), add this after the draw() function:

if (draw) window.onload = draw;

Or this, by Simon Willison, if you want more than one function to be executed:

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

Java check if boolean is null

boolean is a primitive type, and therefore can not be null.

Its boxed type, Boolean, can be null.

The function is probably returning a Boolean as opposed to a boolean, so assigning the result to a Boolean-type variable will allow you to test for nullity.

Running AngularJS initialization code when view is loaded

When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
    } else {
        //create a new object
    }
    $scope.isSaving = false;
}
...
$scope.init();

Since your controller runs before ng-init, this also solves your second issue.

Fiddle


As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

var init = function () {
    // do something
}
...
init();

See jsFiddle


If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.

var init = function () {
    // do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
                    if( newVal && newVal.length > 0) {
                        unwatch();
                        init();
                    }
                });

Removing u in list

arr = [str(r) for r in arr]

This basically converts all your elements in string. Hence removes the encoding. Hence the u which represents encoding gets removed Will do the work easily and efficiently

Angular 2 Scroll to top on Route Change

If you need simply scroll page to top, you can do this (not the best solution, but fast)

document.getElementById('elementId').scrollTop = 0;

How do I set up Vim autoindentation properly for editing Python files?

I use:

$ cat ~/.vimrc
syntax on
set showmatch
set ts=4
set sts=4
set sw=4
set autoindent
set smartindent
set smarttab
set expandtab
set number

But but I'm going to try Daren's entries

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

If you (or a helpful admin) runs Set-ExecutionPolicy as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)

NB.: On a 64-bit OS you need to run Set-ExecutionPolicy for 32-bit and 64-bit PowerShell separately.

Find JavaScript function definition in Chrome

Lets say we're looking for function named foo:

  1. (open Chrome dev-tools),
  2. Windows: ctrl + shift + F, or macOS: cmd + optn + F. This opens a window for searching across all scripts.
  3. check "Regular expression" checkbox,
  4. search for foo\s*=\s*function (searches for foo = function with any number of spaces between those three tokens),
  5. press on a returned result.

Another variant for function definition is function\s*foo\s*\( for function foo( with any number of spaces between those three tokens.

Get the time difference between two datetimes

EPOCH TIME DIFFERENCE USING MOMENTJS:

To Get Difference between two epoch times:

Syntax: moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()

Difference in Hours: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()

Difference in minutes: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()

Note: You could remove .toFixed() if you need precise values.

Code:

const moment = require('moment')

console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')

Refer working example here: https://repl.it/repls/MoccasinDearDimension

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

The short version of the most voted answer has problems with TB values.

I adjusted it appropriately to handle also tb values and still without a loop and also added a little error checking for negative values. Here's my solution:

static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(long value, int decimalPlaces = 0)
{
    if (value < 0)
    {
        throw new ArgumentException("Bytes should not be negative", "value");
    }
    var mag = (int)Math.Max(0, Math.Log(value, 1024));
    var adjustedSize = Math.Round(value / Math.Pow(1024, mag), decimalPlaces);
    return String.Format("{0} {1}", adjustedSize, SizeSuffixes[mag]);
}

Create directory if it does not exist

From your situation it sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number, Get-NextRevisionNumber. Or you could do something like this:

foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
    # Select all the Revision folders from the project folder.
    $Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory

    # The next revision number is just going to be one more than the highest number.
    # You need to cast the string in the first pipeline to an int so Sort-Object works.
    # If you sort it descending the first number will be the biggest so you select that one.
    # Once you have the highest revision number you just add one to it.
    $NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1

    # Now in this we kill two birds with one stone.
    # It will create the "Reports" folder but it also creates "Revision#" folder too.
    New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory

    # Move on to the next project folder.
    # This untested example loop requires PowerShell version 3.0.
}

PowerShell 3.0 installation.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I installed EntityFramework 6.2 instead of 6.3 and it worked.

Perhaps it is the .NetCoreApp v2.1 or .NETFramework v4.6.1.

Swift convert unix time to date and time

Swift:

extension Double {
    func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = dateStyle
        dateFormatter.timeStyle = timeStyle
        return dateFormatter.string(from: Date(timeIntervalSince1970: self))
    }
}

Pandas - Get first row value of a given column

To access a single value you can use the method iat that is much faster than iloc:

df['Btime'].iat[0]

Output:

1.2

Easy way to test a URL for 404 in PHP?

This function return the status code of an URL in PHP 7:

/**
 * @param string $url
 * @return int
 */
function getHttpResponseCode(string $url): int
{
    $headers = get_headers($url);
    return substr($headers[0], 9, 3);
}

Example:

echo getHttpResponseCode('https://www.google.com');
//displays: 200

Access-control-allow-origin with multiple domains

Look into the Thinktecture IdentityModel library -- it has full CORS support:

http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

And it can dynamically emit the ACA-Origin you want.

What is the difference between include and require in Ruby?

What's the difference between "include" and "require" in Ruby?

Answer:

The include and require methods do very different things.

The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

Source

So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require.

Oddly enough, Ruby's require is analogous to C's include, while Ruby's include is almost nothing like C's include.

How to open an Excel file in C#?

It's easier to help you if you say what's wrong as well, or what fails when you run it.

But from a quick glance you've confused a few things.

The following doesn't work because of a couple of issues.

if (Directory("C:\\csharp\\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.

Android: How to Programmatically set the size of a Layout

Java

This should work:

// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);

If you want to convert dip to pixels, use this:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());

Kotlin

How to change the Push and Pop animations in a navigation based app

I know this thread is old, but I thought I'd put in my two cents. You don't need to make a custom animation, there's a simple (maybe hacky) way of doing it. Instead of using push, create a new navigation controller, make the new view controller the root view controller of that nav controller, and then present the nav controller from the original nav controller. Present is easily customizable with many styles, and no need to make a custom animation.

For example:

UIViewcontroller viewControllerYouWantToPush = UIViewController()
UINavigationController newNavController = UINavigationController(root: viewControllerYouWantToView)
newNavController.navBarHidden = YES;
self.navigationController.present(newNavController)

And you can change the presentation style however you want.

How to write inside a DIV box with javascript

HTML:

<div id="log"></div>

JS:

document.getElementById("log").innerHTML="WHATEVER YOU WANT...";

git with IntelliJ IDEA: Could not read from remote repository

what @yabin ya says is a cool solution, just remind you that: if u still get the same problem,go to Settings-Version Control-GitHub and uncheck the Clone git repositories using ssh.

How to serialize object to CSV file?

It would be interesting to have a csv serializer as it would take up the minimal space compared to other serializing method.

The closest support for java object to csv is stringutils provided by spring utils project

arrayToCommaDelimitedString(Object[] arr) but it is far from being a serializer.

Here is a simple utility which uses reflection to serialize value objects

public class CSVWriter
{
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
    if(data.length==0)
    {
        return "";
    }

    Class classType = data[0].getClass();
    StringBuilder builder = new StringBuilder();

    Method[] methods = classType.getDeclaredMethods();

    for(Method m : methods)
    {
        if(m.getParameterTypes().length==0)
        {
            if(m.getName().startsWith("get"))
            {
                builder.append(m.getName().substring(3)).append(',');
            }
            else if(m.getName().startsWith("is"))
            {
                builder.append(m.getName().substring(2)).append(',');
            }

        }

    }
    builder.deleteCharAt(builder.length()-1);
    builder.append('\n');
    for(Object d : data)
    {
        for(Method m : methods)
        {
            if(m.getParameterTypes().length==0)
            {
                if(m.getName().startsWith("get") || m.getName().startsWith("is"))
                {
                    System.out.println(m.invoke(d).toString());
                    builder.append(m.invoke(d).toString()).append(',');
                }
            }
        }
        builder.append('\n');
    }
    builder.deleteCharAt(builder.length()-1);
    return builder.toString();
}

public static boolean generateCSV(File csvFileName,Object[] data)
{
    FileWriter fw = null;
    try
    {
        fw = new FileWriter(csvFileName);
        if(!csvFileName.exists())
            csvFileName.createNewFile();
        fw.write(produceCsvData(data));
        fw.flush();
    }
    catch(Exception e)
    {
        System.out.println("Error while generating csv from data. Error message : " + e.getMessage());
        e.printStackTrace();
        return false;
    }
    finally
    {
        if(fw!=null)
        {
            try
            {
                fw.close();
            }
            catch(Exception e)
            {
            }
            fw=null;
        }
    }
    return true;
}

}

Here is an example value object

public class Product {
private String name;
private double price;
private int identifier;
private boolean isVatApplicable;
public Product(String name, double price, int identifier,
        boolean isVatApplicable) {
    super();
    this.name = name;
    this.price = price;
    this.identifier = identifier;
    this.isVatApplicable = isVatApplicable;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public double getPrice() {
    return price;
}
public void setPrice(long price) {
    this.price = price;
}
public int getIdentifier() {
    return identifier;
}
public void setIdentifier(int identifier) {
    this.identifier = identifier;
}
public boolean isVatApplicable() {
    return isVatApplicable;
}
public void setVatApplicable(boolean isVatApplicable) {
    this.isVatApplicable = isVatApplicable;
}

}

and the code to run the util

public class TestCSV 
{
public static void main(String... a)
{
    Product[] list = new Product[5];
    list[0] = new Product("dvd", 24.99, 967, true);
    list[1] = new Product("pen", 4.99, 162, false);
    list[2] = new Product("ipad", 624.99, 234, true);
    list[3] = new Product("crayons", 4.99,127, false);
    list[4] = new Product("laptop", 1444.99, 997, true);
    CSVWriter.generateCSV(new File("C:\\products.csv"),list);
}

}

Output:

Name    VatApplicable   Price   Identifier
dvd     true            24.99   967
pen     false           4.99    162
ipad    true            624.99  234
crayons false           4.99    127
laptop  true            1444.99 997

What's the regular expression that matches a square bracket?

How about using backslash \ in front of the square bracket. Normally square brackets match a character class.

Google Play Services Library update and missing symbol @integer/google_play_services_version

In my case, I needed to copy the google-play-services_lib FOLDER in the same DRIVE of the source codes of my apps

  • F:\Products\Android\APP*.java <- My Apps are here so I copied to folder below
  • F:\Products\Android\libs\google-play-services_lib

Correct way to delete cookies server-side

Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

This is the best way to clear a multi-select or list box:

 $("#drp_assign_list option[value]").remove();

Programmatically find the number of cores on a machine

hwloc (http://www.open-mpi.org/projects/hwloc/) is worth looking at. Though requires another library integration into your code but it can provide all the information about your processor (number of cores, the topology, etc.)

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

In June 2018, in an effort to raise security and comply with modern standards, the insecure TLS 1.0 & 1.1 protocols will no longer be supported for SSL connections to Central. This should only affect users of Java 6 (and Java 7) that are also using https to access central, which by our metrics is less than .2% of users.

For more details and workarounds, see the blog and faq here: https://blog.sonatype.com/enhancing-ssl-security-and-http/2-support-for-central

Convert JSON format to CSV format for MS Excel

I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3 into CSV and prompt you to download/open in Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JSON to CSV</title>
    <script src="scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">
    var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }

    DownloadJSON2CSV(json3.d);

    function DownloadJSON2CSV(objArray)
    {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            // Here is an example where you would wrap the values in double quotes
            // for (var index in array[i]) {
            //    line += '"' + array[i][index] + '",';
            // }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';
        }
        window.open( "data:text/csv;charset=utf-8," + escape(str))
    }

    </script>

</head>
<body>
    <h1>This page does nothing....</h1>
</body>
</html>

How should I escape commas and speech marks in CSV files so they work in Excel?

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!

Cannot connect to MySQL 4.1+ using old authentication

IF,

  1. You are using a shared hosting, and don't have root access.
  2. you are getting the said error while connecting to a remote database ie: not localhost.
  3. and your using Xampp.
  4. and the code is running fine on live server, but the issue is only on your development machine running xampp.

Then,

It is highly recommended that you install xampp 1.7.0 . Download Link

Note: This is not a solution to the above problem, but a FIX which would allow you to continue with your development.

jQuery issue in Internet Explorer 8

Some people stumbling on this post might get this issue with jquery and IE8 because they're using >= jQuery v2. Use this code:

<!--[if lt IE 9]>
    <script src="jquery-1.9.0.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="jquery-2.0.0.js"></script>
<!--<![endif]-->

Print Pdf in C#

The best way to print pdf automatically from C# is using printer's "direct pdf". You just need to copy the pdf file to printer's network sharename. The rest will be taken care by printer itself.

The speed is 10 times faster than any other methods. However, the requirements are the printer model supporting for direct pdf printing and having at least 128 MB Dram which is easy for any modern printer.

CodeIgniter Active Record - Get number of returned rows

function getCount(){
    return $this->db->get('table_name')->num_rows();
}

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

What is mutex and semaphore in Java ? What is the main difference?

Semaphore can be counted, while mutex can only count to 1.

Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connections

Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a "Mutual Exclusion Semaphore".

Best way to unselect a <select> in jQuery?

There are lots of answers here but unfortunately all of them are quite old and therefore rely on attr/removeAttr which is really not the way to go.

@coffeeyesplease correctly mentions that a good, cross-browser solution is to use

$("select").val([]);

Another good cross-browser solution is

// Note the use of .prop instead of .attr
$("select option").prop("selected", false);

You can see it run a self-test here. Tested on IE 7/8/9, FF 11, Chrome 19.

.htaccess rewrite to redirect root URL to subdirectory

Two ways out of possible solutions to achieve this are: 1. Create a .htaccess file in root folder as under (just replace example.com and my_dir with your corresponding values):

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_dir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_dir/index.php [L] 
</IfModule>
  1. Use RedirectMatch to only redirect the root URL “/” to another folder or URL,

    RedirectMatch ^/$ http://www.example.com/my_dir

What is the difference between “int” and “uint” / “long” and “ulong”?

u means unsigned, so ulong is a large number without sign. You can store a bigger value in ulong than long, but no negative numbers allowed.

A long value is stored in 64-bit,with its first digit to show if it's a positive/negative number. while ulong is also 64-bit, with all 64 bit to store the number. so the maximum of ulong is 2(64)-1, while long is 2(63)-1.

Comparing arrays in JUnit assertions, concise built-in way?

I prefer to convert arrays to strings:

Assert.assertEquals(
                Arrays.toString(values),
                Arrays.toString(new int[] { 7, 8, 9, 3 }));

this way I can see clearly where wrong values are. This works effectively only for small sized arrays, but I rarely use arrays with more items than 7 in my unit tests.

This method works for primitive types and for other types when overload of toString returns all essential information.

how to compare the Java Byte[] array?

Java byte compare,

public static boolean equals(byte[] a, byte[] a2) {
        if (a == a2)
            return true;
        if (a == null || a2 == null)
            return false;

        int length = a.length;
        if (a2.length != length)
            return false;

        for (int i = 0; i < length; i++)
            if (a[i] != a2[i])
                return false;

        return true;
    }

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 6.1: in the home window click on the server instance(connection)/ or create a new one. In the thus opened 'connection' tab click on 'server' -> 'data import'. The rest of the steps remain as in Vishy's answer.

Count all values in a matrix greater than a value

This is very straightforward with boolean arrays:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

If anyone gets this issue while using the integrated terminal in Visual Studio Code then there is a good chance it's updating. Restart Visual Studio Code and you will likely see the "New Version" tab and it should all start working again.

LINQ select in C# dictionary

One way would be to first flatten the list with a SelectMany:

subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

VS 2010 Express is no longer linked to any VS Express pages (that I found). I did find this link to the ISO which I used and it fixed the errors mentioned here.

http://download.microsoft.com/download/1/E/5/1E5F1C0A-0D5B-426A-A603-1798B951DDAE/VS2010Express1.iso

Note: Also make sure you have x86 everything (Python + Postgresql) or you'll get other errors. I did not try x64 everything.

What's the difference between ASCII and Unicode?

Beyond how UTF is a superset of ASCII, another good difference to know between ASCII and UTF is in terms of disk file encoding and data representation and storage in random memory. Programs know that given data should be understood as an ASCII or UTF string either by detecting special byte order mark codes at the start of the data, or by assuming from programmer intent that the data is text and then checking it for patterns that indicate it is in one text encoding or another.

Using the conventional prefix notation of 0x for hexadecimal data, basic good reference is that ASCII text starts with byte values 0x00 to 0x7F representing one of the possible ASCII character values. UTF text is normally indicated by starting with the bytes 0xEF 0xBB 0xBF for UTF8. For UTF16, start bytes 0xFE 0xFF, or 0xFF 0xFE are used, with the endian-ness order of the text bytes indicated by the order of the start bytes. The simple presence of byte values that are not in the ASCII range of possible byte values also indicates that data is probably UTF.

There are other byte order marks that use different codes to indicate data should be interpreted as text encoded in a certain encoding standard.

How to write to a JSON file in the correct format

With formatting

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(JSON.pretty_generate(tempHash))
end

Output

{
    "key_a":"val_a",
    "key_b":"val_b"
}

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

As per keras tutorial, you can simply use the same tf.device scope as in regular tensorflow:

with tf.device('/gpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on GPU:0

with tf.device('/cpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on CPU:0

How do I shutdown, restart, or log off Windows via a bat file?

If you are on a remote machine, you may also want to add the -f option to force the reboot. Otherwise your session may close and a stubborn app can hang the system.

I use this whenever I want to force an immediate reboot:

shutdown -t 0 -r -f

For a more friendly "give them some time" option, you can use this:

shutdown -t 30 -r

As you can see in the comments, the -f is implied by the timeout.

Brutus 2006 is a utility that provides a GUI for these options.

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

look this happend to me when I created new file inside a folder with the same name of class in the project { folder name : Folder } and there is class name { Folder } so the namespace was the namespace.Folder so that the compiler assume that the cass defined in two places

in new file :

namespace APP.Folder
{
    partial class NewFile
    {
       // ....
    }
}

in the other file (the file that hase the problem):

    namespace APP
{
    partial class Folder
    {
      // ....
    }
}

-- so you can edit the folder name or remove the .Folder from the namespace at the new file

HTML not loading CSS file

I have struggled with this same problem (Ubuntu 16.04, Bluefish editor, FireFox, Google Chrome.

Solution: Clear browsing data in Chrome "Settings > Advanced Settings > Clear Browsing Data", In Firefox, "Open Menu image top right tool bar 'Preferences' > Advanced ", look for this image in the menu: Cached Web Content click the button "Clear Now". Browser's cache the .css file and if it has not changed they usually won't reload it. So when you change your .css file clear this web cache and it should work unless a problem exists in your .css file. Peace, Stan

How to choose the id generation strategy when using JPA and Hibernate

The API Doc are very clear on this.

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:

increment

generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

guid

uses a database-generated GUID string on MS SQL Server and MySQL.

native

selects identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. It is usually used in conjunction with a primary key association.

sequence-identity

a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.

If you are building a simple application with not much concurrent users, you can go for increment, identity, hilo etc.. These are simple to configure and did not need much coding inside the db.

You should choose sequence or guid depending on your database. These are safe and better because the id generation will happen inside the database.

Update: Recently we had an an issue with idendity where primitive type (int) this was fixed by using warapper type (Integer) instead.

What is difference between png8 and png24

There is only one PNG format, but it supports 5 color types.

PNG-8 refers to palette variant, which supports only 256 colors, but is usually smaller in size. PNG-8 can be a GIF substitute.

PNG-24 refers to true color variant, which supports more colors, but might be bigger. PNG-24 can be used instead of JPEG, if lossless image format is needed.

Any modern web browser will support both variants.

What is the difference between <html lang="en"> and <html lang="en-US">?

XML Schema requires that the xml namespace be declared and imported before using xml:lang (and other xml namespace values) RELAX NG predeclares the xml namespace, as in XML, so no additional declaration is needed.

Finding moving average from data points in Python

ravgs = [sum(data[i:i+5])/5. for i in range(len(data)-4)]

This isn't the most efficient approach but it will give your answer and I'm unclear if your window is 5 points or 10. If its 10, replace each 5 with 10 and the 4 with 9.

How to search for file names in Visual Studio?

In the search dropdown on the standard toolbar, you can use the "open file" macro, >of, to find files. Click in said dropdown (or hit Ctrl-D) then start typing (minus the quotes) ">of CoreEdit.cs", and you'll get a dynamic list that narrows as you type.

Select the values of one property on all objects of an array in PowerShell

To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.

  • Outside of a pipeline[1], use (PSv3+):

    $objects.Name
    as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.

    • Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.

    • Alternatively, in PSv2, use the foreach statement, whose output you can also assign directly to a variable:

      $results = foreach ($obj in $objects) { $obj.Name }

    • If collecting all output from a (pipeline) command in memory first is feasible, you can also combine pipelines with member enumeration; e.g.:

       (Get-ChildItem -File | Where-Object Length -lt 1gb).Name
      
    • Tradeoffs:

      • Both the input collection and output array must fit into memory as a whole.
      • If the input collection is itself the result of a command (pipeline) (e.g., (Get-ChildItem).Name), that command must first run to completion before the resulting array's elements can be accessed.
  • In a pipeline, in case you must pass the results to another command, notably if the original input doesn't fit into memory as a whole, use:

    $objects | Select-Object -ExpandProperty Name

    • The need for -ExpandProperty is explained in Scott Saad's answer (you need it to get only the property value).
    • You get the usual pipeline benefits of the pipeline's streaming behavior, i.e. one-by-one object processing, which typically produces output right away and keeps memory use constant (unless you ultimately collect the results in memory anyway).
    • Tradeoff:
      • Use of the pipeline is comparatively slow.

For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.


Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object syntax called an operation statement (again, PSv3+): ; e.g., the following PSv3+ solution is easy to append to an existing command:

$objects | % Name      # short for: $objects | ForEach-Object -Process { $_.Name }

The PSv4+ .ForEach() array method, more comprehensively discussed in this article, is yet another, well-performing alternative, but note that it requires collecting all input in memory first, just like member enumeration:

# By property name (string):
$objects.ForEach('Name')

# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
  • This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower than member enumeration, though still noticeably faster than the pipeline.

  • For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).

  • The script-block variant ({ ... }) allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based ForEach-Object cmdlet (%).

Note: The .ForEach() array method, like its .Where() sibling (the in-memory equivalent of Where-Object), always returns a collection (an instance of [System.Collections.ObjectModel.Collection[psobject]]), even if only one output object is produced.
By contrast, member enumeration, Select-Object, ForEach-Object and Where-Object return a single output object as-is, without wrapping it in a collection (array).


Comparing the performance of the various approaches

Here are sample timings for the various approaches, based on an input collection of 10,000 objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:

Important

  • The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by Get-ChildItem) or [pscustomobject] instances (e.g., as output by Convert-FromCsv).
    The reason is that [pscustomobject] properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.

  • The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.

  • For brevity, alias % is used for the ForEach-Object cmdlet.

General conclusions, applicable to both regular .NET type and [pscustomobject] input:

  • The member-enumeration ($collection.Name) and foreach ($obj in $collection) solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.

  • Surprisingly, % Name performs much worse than % { $_.Name } - see this GitHub issue.

  • PowerShell Core consistently outperforms Windows Powershell here.

Timings with regular .NET types:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.005
1.06   foreach($o in $objects) { $o.Name }           0.005
6.25   $objects.ForEach('Name')                      0.028
10.22  $objects.ForEach({ $_.Name })                 0.046
17.52  $objects | % { $_.Name }                      0.079
30.97  $objects | Select-Object -ExpandProperty Name 0.140
32.76  $objects | % Name                             0.148
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.012
1.32   foreach($o in $objects) { $o.Name }           0.015
9.07   $objects.ForEach({ $_.Name })                 0.105
10.30  $objects.ForEach('Name')                      0.119
12.70  $objects | % { $_.Name }                      0.147
27.04  $objects | % Name                             0.312
29.70  $objects | Select-Object -ExpandProperty Name 0.343

Conclusions:

  • In PowerShell Core, .ForEach('Name') clearly outperforms .ForEach({ $_.Name }). In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.

Timings with [pscustomobject] instances:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.006
1.11   foreach($o in $objects) { $o.Name }           0.007
1.52   $objects.ForEach('Name')                      0.009
6.11   $objects.ForEach({ $_.Name })                 0.038
9.47   $objects | Select-Object -ExpandProperty Name 0.058
10.29  $objects | % { $_.Name }                      0.063
29.77  $objects | % Name                             0.184
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.008
1.14   foreach($o in $objects) { $o.Name }           0.009
1.76   $objects.ForEach('Name')                      0.015
10.36  $objects | Select-Object -ExpandProperty Name 0.085
11.18  $objects.ForEach({ $_.Name })                 0.092
16.79  $objects | % { $_.Name }                      0.138
61.14  $objects | % Name                             0.503

Conclusions:

  • Note how with [pscustomobject] input .ForEach('Name') by far outperforms the script-block based variant, .ForEach({ $_.Name }).

  • Similarly, [pscustomobject] input makes the pipeline-based Select-Object -ExpandProperty Name faster, in Windows PowerShell virtually on par with .ForEach({ $_.Name }), but in PowerShell Core still about 50% slower.

  • In short: With the odd exception of % Name, with [pscustomobject] the string-based methods of referencing the properties outperform the scriptblock-based ones.


Source code for the tests:

Note:

  • Download function Time-Command from this Gist to run these tests.

    • Assuming you have looked at the linked code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install it directly as follows:

      irm https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1 | iex
      
  • Set $useCustomObjectInput to $true to measure with [pscustomobject] instances instead.

$count = 1e4 # max. input object count == 10,000
$runs  = 10  # number of runs to average 

# Note: Using [pscustomobject] instances rather than instances of 
#       regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false

# Create sample input objects.
if ($useCustomObjectInput) {
  # Use [pscustomobject] instances.
  $objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
  # Use instances of a regular .NET type.
  # Note: The actual count of files and folders in your file-system
  #       may be less than $count
  $objects = Get-ChildItem / -Recurse -ErrorAction Ignore | Select-Object -First $count
}

Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."

# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
              { $objects | % Name },
              { $objects | % { $_.Name } },
              { $objects.ForEach('Name') },
              { $objects.ForEach({ $_.Name }) },
              { $objects.Name },
              { foreach($o in $objects) { $o.Name } }

# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*

[1] Technically, even a command without |, the pipeline operator, uses a pipeline behind the scenes, but for the purpose of this discussion using the pipeline refers only to commands that do use | and therefore involve multiple commands connected by a pipeline.

How to get the nvidia driver version from the command line?

[NOTE: I am not deleting my answer on purpose, so people see how not to do it]

If you use:

me@over_there:~$  dpkg --status nvidia-current | grep Version | cut -f 1 -d '-' | sed 's/[^.,0-9]//g'
260.19.06

you will get the version of the nVIDIA driver package installed through your distribution's packaging mechanism. But this may not be the version that is actually running as part of your kernel right now.

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

How to convert a file into a dictionary?

If you love one liners, try:

d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')

Input FILE = Path to file, SEP = Key-Value separator character

Not the most elegant or efficient way of doing it, but quite interesting nonetheless :)

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

While the json begins with "[" and ends with "]" that means this is the Json Array, use JSONArray instead:

JSONArray jsonArray = new JSONArray(JSON);

And then you can map it with the List Test Object if you need:

ObjectMapper mapper = new ObjectMapper();
List<TestExample> listTest = mapper.readValue(String.valueOf(jsonArray), List.class);

Why are unnamed namespaces used and what are their benefits?

Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static keyword in C/C++.
static keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static keyword because of which unnamed namespace has advantage over static. static keyword can be used with variable, function and objects but not with user defined class.
For example:

static int x;  // Correct 

But,

static class xyz {/*Body of class*/} //Wrong
static structure {/*Body of structure*/} //Wrong

But same can be possible with unnamed namespace. For example,

 namespace {
           class xyz {/*Body of class*/}
           static structure {/*Body of structure*/}
  } //Correct

How to get nth jQuery element

For iterations using a selector doesn't seem to make any sense though:

var some = $( '...' );

for( i = some.length -1; i>=0; --i )
{
   // Have to transform in a jquery object again:
   //
   var item = $( some[ i ] );

   // use item at will
   // ...
}

Angular 2 Show and Hide an element

Depending on your needs, *ngIf or [ngClass]="{hide_element: item.hidden}" where CSS class hide_element is { display: none; }

*ngIf can cause issues if you're changing state variables *ngIf is removing, in those cases using CSS display: none; is required.

Is there a better alternative than this to 'switch on type'?

If you were using C# 4, you could make use of the new dynamic functionality to achieve an interesting alternative. I'm not saying this is better, in fact it seems very likely that it would be slower, but it does have a certain elegance to it.

class Thing
{

  void Foo(A a)
  {
     a.Hop();
  }

  void Foo(B b)
  {
     b.Skip();
  }

}

And the usage:

object aOrB = Get_AOrB();
Thing t = GetThing();
((dynamic)t).Foo(aorB);

The reason this works is that a C# 4 dynamic method invocation has its overloads resolved at runtime rather than compile time. I wrote a little more about this idea quite recently. Again, I would just like to reiterate that this probably performs worse than all the other suggestions, I am offering it simply as a curiosity.

Bitwise operation and usage

Think of 0 as false and 1 as true. Then bitwise and(&) and or(|) work just like regular and and or except they do all of the bits in the value at once. Typically you will see them used for flags if you have 30 options that can be set (say as draw styles on a window) you don't want to have to pass in 30 separate boolean values to set or unset each one so you use | to combine options into a single value and then you use & to check if each option is set. This style of flag passing is heavily used by OpenGL. Since each bit is a separate flag you get flag values on powers of two(aka numbers that have only one bit set) 1(2^0) 2(2^1) 4(2^2) 8(2^3) the power of two tells you which bit is set if the flag is on.

Also note 2 = 10 so x|2 is 110(6) not 111(7) If none of the bits overlap(which is true in this case) | acts like addition.

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

Open up terminal first and then go to directory of web server

cd /Library/WebServer/Documents

and then type this and what you will do is you will give read and write permission

sudo chmod -R o+w /Library/WebServer/Documents

This will surely work!

Importing a long list of constants to a Python file

Python isn't preprocessed. You can just create a file myconstants.py:

MY_CONSTANT = 50

And importing them will just work:

import myconstants
print myconstants.MY_CONSTANT * 2

Force LF eol in git repo and working copy

To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

# Ensure all C and PHP files use LF.
*.c         eol=lf
*.php       eol=lf

which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

$ echo "* text=auto" >> .gitattributes
$ rm .git/index     # Remove the index to force Git to
$ git reset         # re-scan the working directory
$ git status        # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"

or as per GitHub docs:

git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.

See also: @Charles Bailey post.

In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

manual.pdf      -text

Or mark it explicitly as binary:

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

To see some more advanced git normalization file, check .gitattributes at Drupal core:

# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048

# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.

# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
#   - Exposed by default in `git diff --color` on the CLI.
#   - Validate with `git diff --check`.
#   - Deny applying with `git apply --whitespace=error-all`.
#   - Fix automatically with `git apply --whitespace=fix`.

*.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2

# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot     -text diff
*.exe     -text diff
*.gif     -text diff
*.gz      -text diff
*.ico     -text diff
*.jpeg    -text diff
*.jpg     -text diff
*.otf     -text diff
*.phar    -text diff
*.png     -text diff
*.svgz    -text diff
*.ttf     -text diff
*.woff    -text diff
*.woff2   -text diff

See also:

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Here is a way that I would do it:

public ResponseEntity < ? extends BaseResponse > message(@PathVariable String player) { //REST Endpoint.

 try {
  Integer.parseInt(player);
  return new ResponseEntity < ErrorResponse > (new ErrorResponse("111", "player is not found"), HttpStatus.BAD_REQUEST);
 } catch (Exception e) {


 }
 Message msg = new Message(player, "Hello " + player);
 return new ResponseEntity < Message > (msg, HttpStatus.OK);

}

@RequestMapping(value = "/getAll/{player}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity < List < ? extends BaseResponse >> messageAll(@PathVariable String player) { //REST Endpoint.

 try {
  Integer.parseInt(player);
  List < ErrorResponse > errs = new ArrayList < ErrorResponse > ();
  errs.add(new ErrorResponse("111", "player is not found"));
  return new ResponseEntity < List < ? extends BaseResponse >> (errs, HttpStatus.BAD_REQUEST);
 } catch (Exception e) {


 }
 Message msg = new Message(player, "Hello " + player);
 List < Message > msgList = new ArrayList < Message > ();
 msgList.add(msg);
 return new ResponseEntity < List < ? extends BaseResponse >> (msgList, HttpStatus.OK);

}

Android widget: How to change the text of a button

You can use the setText() method. Example:

import android.widget.Button;

Button p1_button = (Button)findViewById(R.id.Player1);
p1_button.setText("Some text");

Also, just as a point of reference, Button extends TextView, hence why you can use setText() just like with an ordinary TextView.

What does Html.HiddenFor do?

It creates a hidden input on the form for the field (from your model) that you pass it.

It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

Consider the following ViewModel class:

public class ViewModel
{
    public string Value { get; set; }
    public int Id { get; set; }
}

Now you want the edit page to store the ID but have it not be seen:

<% using(Html.BeginForm() { %>
    <%= Html.HiddenFor(model.Id) %><br />
    <%= Html.TextBoxFor(model.Value) %>
<% } %>

This results in the equivalent of the following HTML:

<form name="form1">
    <input type="hidden" name="Id">2</input>
    <input type="text" name="Value" value="Some Text" />
</form>

Missing MVC template in Visual Studio 2015

Visual Studio 2015 (Community update 3, in my scenario) uses a default template for the MVC project. You don't have to select it.

I found this tutorial and I think it answers the question: https://docs.asp.net/en/latest/tutorials/first-mvc-app/start-mvc.html

check out the old versions of this: http://www.asp.net/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part1

http://www.asp.net/mvc/overview/getting-started/introduction/getting-started

Times have changed. Including .NET

Integer value in TextView

just found an advance and most currently used method to set string in textView

textView.setText(String.valueOf(YourIntegerNumber));

CSS3 Transparency + Gradient

I just came across this more recent example . To simplify and use the most recent examples, giving the css a selector class of 'grad',(I've included backwards compatibility)

.grad {
    background-color: #F07575; /* fallback color if gradients are not supported */
    background-image: -webkit-linear-gradient(top left, red, rgba(255,0,0,0));/* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
    background-image: -moz-linear-gradient(top left, red, rgba(255,0,0,0));/* For Firefox (3.6 to 15) */
    background-image: -o-linear-gradient(top left, red, rgba(255,0,0,0));/* For old Opera (11.1 to 12.0) */
    background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0)); /* Standard syntax; must be last */
}

from https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

diff current working copy of a file with another branch's committed copy

You're trying to compare your working tree with a particular branch name, so you want this:

git diff master -- foo

Which is from this form of git-diff (see the git-diff manpage)

   git diff [--options] <commit> [--] [<path>...]
       This form is to view the changes you have in your working tree
       relative to the named <commit>. You can use HEAD to compare it with
       the latest commit, or a branch name to compare with the tip of a
       different branch.

FYI, there is also a --cached (aka --staged) option for viewing the diff of what you've staged, rather than everything in your working tree:

   git diff [--options] --cached [<commit>] [--] [<path>...]
       This form is to view the changes you staged for the next commit
       relative to the named <commit>.
       ...
       --staged is a synonym of --cached.

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

How do I copy the contents of a String to the clipboard in C#?

Using the solution showed in this question, System.Windows.Forms.Clipboard.SetText(...), results in the exception:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

To prevent this, you can add the attribute:

[STAThread]

to

static void Main(string[] args)

getting the reason why websockets closed with close code 1006

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

How to specify the bottom border of a <tr>?

What I want to say here is like some kind of add-on on @Suciu Lucian's answer.

The weird situation I ran into is that when I apply the solution of @Suciu Lucian in my file, it works in Chrome but not in Safari (and did not try in Firefox). After I studied the guide of styling table border published by w3.org, I found something alternative:

table.myTable{
  border-spacing: 0;
}

table.myTable td{
  border-bottom:1px solid red;
}

Yes you have to style the td instead of the tr.

How to get only numeric column values?

The other answers indicating using IsNumeric in the where clause are correct, as far as they go, but it's important to remember that it returns 1 if the value can be converted to any numeric type. As such, oddities such as "1d3" will make it through the filter.

If you need only values composed of digits, search for that explicitly:

SELECT column1 FROM table WHERE column1 not like '%[^0-9]%'

The above is filtering to reject any column which contains a non-digit character

Note that in any case, you're going to incur a table scan, indexes are useless for this sort of query.

Xcode process launch failed: Security

Hey so the accepted answer works, except if you need to debug the initial launch of the app. However I think that answer is more of a work around, and not an actual solution. From my understanding this message occurs when you have some weirdness in your provisioning profile / cert setup so make extra sure everything is in tip-top shape in that dept. before ramming your head against the wall repeatedly.

What worked for me was as follows from the apple docs:

Provisioning Profiles Known Issue If you have upgraded to the GM seed from other betas you may see your apps crashing due to provisioning profile issues.

Workaround:

  1. Connect the device via USB to your Mac

  2. Launch Xcode Choose Window ->Devices

  3. Right click on the device in left column, choose "Show Provisioning Profiles"

  4. Click on the provisioning profile in question

  5. Press the "-" button Continue to removing all affected profiles.

  6. Re-install the app

Make sure you right click on the image of the device not the name of the device or you won't see the provisioning profiles option. I restored my new phone from an old backup and there was a lot of cruft hanging around, i also had 2 different dev. certs active (not sure why) but i deleted one, made a new profile got rid of all the profiles on device and it worked.

Hope this helps someone else.

Difference between Visibility.Collapsed and Visibility.Hidden

Even though a bit old thread, for those who still looking for the differences:

Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.

If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.

As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.

In Maven how to exclude resources from the generated jar?

Another possibility is to use the Maven Shade Plugin, e.g. to exclude a logging properties file used only locally in your IDE:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>${maven-shade-plugin-version}</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>log4j2.xml</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
        </execution>
    </executions>
</plugin>

This will however exclude the files from every artifact, so it might not be feasible in every situation.

Delete all files in directory (but not directory) - one liner solution

For deleting all files from directory say "C:\Example"

File file = new File("C:\\Example");      
String[] myFiles;    
if (file.isDirectory()) {
    myFiles = file.list();
    for (int i = 0; i < myFiles.length; i++) {
        File myFile = new File(file, myFiles[i]); 
        myFile.delete();
    }
}

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Build the full path filename in Python

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')

IntelliJ does not show project folders

When importing your project/module be sure to check these two boxes:

enter image description here

how to start the tomcat server in linux?

Go to your Tomcat Directory with : cd/home/user/apache-tomcat6.0

  • sh bin/startup.sh.>> tail -f logs/catelina.out.>>

C++: Converting Hexadecimal to Decimal

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    int x, y;
    std::stringstream stream;

    std::cin >> x;
    stream << x;
    stream >> std::hex >> y;
    std::cout << y;

    return 0;
}

Function ereg_replace() is deprecated - How to clear this bug?

http://php.net/ereg_replace says:

Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.

Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

_x000D_
_x000D_
textarea { height: auto; }
_x000D_
<textarea rows="10"></textarea>
_x000D_
_x000D_
_x000D_

This will trigger the browser to set the height of the textarea EXACTLY to the amount of rows plus the paddings around it. Setting the CSS height to an exact amount of pixels leaves arbitrary whitespaces.

How to display hexadecimal numbers in C?

Try:

printf("%04x",a);
  • 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified.
  • 4 (width) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is right justified within this width by padding on the left with the pad character. By default this is a blank space, but the leading zero we used specifies a zero as the pad char. The value is not truncated even if the result is larger.
  • x - Specifier for hexadecimal integer.

More here

Simple excel find and replace for formulas

If the formulas are identical you can use Find and Replace with Match entire cell contents checked and Look in: Formulas. Select the range, go into Find and Replace, make your entries and `Replace All.

enter image description here

Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.

The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.

Function RegexFormulaReplace(formula As String)
    Dim regex As New RegExp
    regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
'   Test if a match is found
    If regex.Test(formula) = True Then
        RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
    Else
        RegexFormulaReplace = CVErr(xlErrValue)
    End If
    Set regex = Nothing
End Function

In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer tab of the main ribbon, select VBA and then References from the main toolbar. Scroll down to find the reference to the library and check the box next to it.

How to import existing Git repository into another?

I think you can do this using 'git mv' and 'git pull'.

I'm a fair git noob - so be careful with your main repository - but I just tried this in a temp dir and it seems to work.

First - rename the structure of XXX to match how you want it to look when it's within YYY:

cd XXX
mkdir tmp
git mv ZZZ tmp/ZZZ
git mv tmp ZZZ

Now XXX looks like this:

XXX
 |- ZZZ
     |- ZZZ

Now use 'git pull' to fetch the changes across:

cd ../YYY
git pull ../XXX

Now YYY looks like this:

YYY
 |- ZZZ
     |- ZZZ
 |- (other folders that already were in YYY)

MVC - Set selected value of SelectList

You can use below method, which is quite simple.

new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());

This will auto-select the first item in your list. You can modify the above query by adding a where clause.

pip install - locale.Error: unsupported locale setting

Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don't need to call this command manually every time, when you connecting via ssh for example.

How to break out of a loop from inside a switch?

You could potentially use goto, but I would prefer to set a flag that stops the loop. Then break out of the switch.

Get pixel's RGB using PIL

GIFs store colors as one of x number of possible colors in a palette. Read about the gif limited color palette. So PIL is giving you the palette index, rather than the color information of that palette color.

Edit: Removed link to a blog post solution that had a typo. Other answers do the same thing without the typo.

Using json_encode on objects in PHP (regardless of scope)

All the properties of your object are private. aka... not available outside their class's scope.

Solution for PHP >= 5.4

Use the new JsonSerializable Interface to provide your own json representation to be used by json_encode

class Thing implements JsonSerializable {
    ...
    public function jsonSerialize() {
        return [
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()
        ];
    }
    ...
}

Solution for PHP < 5.4

If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function inside your Class that utilizes json_encode() on a data structure you create for this purpose.

class Thing {
    ...
    public function to_json() {
        return json_encode(array(
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()                
        ));
    }
    ...
}

A more detailed writeup

Change action bar color in android

Maybe this can help you also. It's from the website:

http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

First things first you need to have a custom theme declared for your application (or activity, depending on your needs). Something like…

<!-- Somewhere in AndroidManifest.xml -->
<application ... android:theme="@style/ThemeSelector">

Then, declare your custom theme for two cases, API versions with and without the Holo Themes. For the old themes we’ll customize the windowTitleBackgroundStyle attribute, and for the newer ones the ActionBarStyle.

<!-- res/values/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Light">
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
    </style>

    <style name="WindowTitleBackground">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

<!-- res/values-v11/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

That’s it!

React hooks useState Array

use state is not always needed you can just simply do this

let paymentList = [
    {"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]

then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.

<div className="card-body">
            <div className="table-responsive">
                <table className="table table-striped">
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            paymentList.map((payment, key) => (
                                <tr key={key}>
                                    <td>{payment.txnid}</td>
                                    <td>{payment.fname}</td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            </div>
        </div>

How do I rename all folders and files to lowercase on Linux?

for f in `find`; do mv -v "$f" "`echo $f | tr '[A-Z]' '[a-z]'`"; done

How do I send an HTML Form in an Email .. not just MAILTO

You are making sense, but you seem to misunderstand the concept of sending emails.

HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.

Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST superglobal) and use the email sending function (mail()).

Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.

A simple example code:

form.html:

<form method="post" action="email.php">
    <input type="text" name="subject" /><br />
    <textarea name="message"></textarea>
</form>

email.php:

<?php
    mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>

Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).

SQL Server loop - how do I loop through a set of records

I think this is the easy way example to iterate item.

declare @cateid int
select CateID into [#TempTable] from Category where GroupID = 'STOCKLIST'

while (select count(*) from #TempTable) > 0
begin
    select top 1 @cateid = CateID from #TempTable
    print(@cateid)

    --DO SOMETHING HERE

    delete #TempTable where CateID = @cateid
end

drop table #TempTable

React JS - Uncaught TypeError: this.props.data.map is not a function

If you're using react hooks you have to make sure that data was initialized as an array. Here's is how it must look like:

const[data, setData] = useState([])

Calling stored procedure from another stored procedure SQL Server

Simply call test2 from test1 like:

EXEC test2 @newId, @prod, @desc;

Make sure to get @id using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:

SELECT @newId = SCOPE_IDENTITY()

Angular 2 @ViewChild annotation returns undefined

I had a similar issue, where the ViewChild was inside of a switch clause that wasn't loading the viewChild element before it was being referenced. I solved it in a semi-hacky way but wrapping the ViewChild reference in a setTimeout that executed immediately (i.e. 0ms)

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

SQLite DateTime comparison

I have a situation where I want data from up to two days ago and up until the end of today. I arrived at the following.

WHERE dateTimeRecorded between date('now', 'start of day','-2 days') 
                           and date('now', 'start of day', '+1 day') 

Ok, technically I also pull in midnight on tomorrow like the original poster, if there was any data, but my data is all historical.

The key thing to remember, the initial poster excluded all data after 2009-11-15 00:00:00. So, any data that was recorded at midnight on the 15th was included but any data after midnight on the 15th was not. If their query was,

select * 
  from table_1 
  where mydate between Datetime('2009-11-13 00:00:00') 
                   and Datetime('2009-11-15 23:59:59')

Use of the between clause for clarity.

It would have been slightly better. It still does not take into account leap seconds in which an hour can actually have more than 60 seconds, but good enough for discussions here :)

How do I disable a jquery-ui draggable?

It took me a little while to figure out how to disable draggable on drop—use ui.draggable to reference the object being dragged from inside the drop function:

$("#drop-target").droppable({
    drop: function(event, ui) {
        ui.draggable.draggable("disable", 1); // *not* ui.draggable("disable", 1);
        …
    }
});

HTH someone

Importing json file in TypeScript

In your TS Definition file, e.g. typings.d.ts`, you can add this line:

declare module "*.json" {
const value: any;
export default value;
}

Then add this in your typescript(.ts) file:-

import * as data from './colors.json';
const word = (<any>data).name;

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

Make a UIButton programmatically in Swift

For Swift 3 Xcode 8.......

let button = UIButton(frame: CGRect(x: 0, y: 0, width: container.width, height: container.height))
        button.addTarget(self, action: #selector(self.barItemTapped), for: .touchUpInside)


func barItemTapped(sender : UIButton) {
    //Write button action here
}

Prevent jQuery UI dialog from setting focus to first textbox

I'd the same issue and solved it by inserting an empty input before the datepicker, that steals the focus every time the dialog is opened. This input is hidden on every opening of the dialog and shown again on closing.

Any free WPF themes?

If you find any ... let me know!

Seriously, as Josh Smith points out in this post, it's amazing there isn't a CodePlex community or something for this. Heck, it is amazing that there aren't more for purchase!

The only one that I have found (for sale) is reuxables. A little pricey, if you ask me, but you do get 9 themes/61 variations.

UPDATE 1:

After I posted my answer, I thought, heck, I should go see if any CodePlex project exists for this already. I didn't find any specific project just for themes, but I did discover the WPF Contrib project ... which does have 1 theme that they never released.

UPDATE 2:

Rudi Grobler (above) just created CodePlex community for this ... starting with converted themes he mentions above. See his blog post for more info. Way to go Rudi!

UPDATE 3:

As another answer below has mentioned, since this question and my answer were written, the WPF Toolkit has incorporated some free themes, in particular, the themes from the Silverlight Toolkit. Rudi's project goes a little further and adds several more ... but depending on your situation, the WPF Toolkit might be all you need (and you might be installing it already).

how to convert java string to Date object

    try 
    {  
      String datestr="06/27/2007";
      DateFormat formatter; 
      Date date; 
      formatter = new SimpleDateFormat("MM/dd/yyyy");
      date = (Date)formatter.parse(datestr);  
    } 
    catch (Exception e)
    {}

month is MM, minutes is mm..

Rename specific column(s) in pandas

Use the pandas.DataFrame.rename funtion. Check this link for description.

data.rename(columns = {'gdp': 'log(gdp)'}, inplace = True)

If you intend to rename multiple columns then

data.rename(columns = {'gdp': 'log(gdp)', 'cap': 'log(cap)', ..}, inplace = True)

Reinitialize Slick js after successful ajax call

You should use the unslick method:

function getSliderSettings(){
  return {
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1
  }
}

$.ajax({
  type: 'get',
  url: '/public/index',
  dataType: 'script',
  data: data_send,
  success: function() {
    $('.skills_section').slick('unslick'); /* ONLY remove the classes and handlers added on initialize */
    $('.my-slide').remove(); /* Remove current slides elements, in case that you want to show new slides. */
    $('.skills_section').slick(getSliderSettings()); /* Initialize the slick again */
  }
});

vertical-align with Bootstrap 3

Following the accepted answer, if you do not wish to customize the markup, for separation of concerns or simply because you use a CMS, the following solution works fine:

_x000D_
_x000D_
.valign {_x000D_
  font-size: 0;_x000D_
}_x000D_
_x000D_
.valign > [class*="col"] {_x000D_
  display: inline-block;_x000D_
  float: none;_x000D_
  font-size: 14px;_x000D_
  font-size: 1rem;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row valign">_x000D_
   <div class="col-xs-5">_x000D_
      <div style="height:5em;border:1px solid #000">Big</div>_x000D_
   </div>_x000D_
   <div class="col-xs-5">_x000D_
       <div style="height:3em;border:1px solid #F00">Small</div>_x000D_
   </div>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

The limitation here is that you cannot inherit font size from the parent element because the row sets the font size to 0 in order to remove white space.

How to add an image to a JPanel?

I can see many answers, not really addressing the three questions of the OP.

1) A word on performance: byte arrays are likely unefficient unless you can use an exact pixel byte ordering which matches to your display adapters current resolution and color depth.

To achieve the best drawing performance, simply convert your image to a BufferedImage which is generated with a type corresponding to your current graphics configuration. See createCompatibleImage at https://docs.oracle.com/javase/tutorial/2d/images/drawonimage.html

These images will be automatically cached on the display card memory after drawing a few times without any programming effort (this is standard in Swing since Java 6), and therefore the actual drawing will take negligible amount of time - if you did not change the image.

Altering the image will come with an additional memory transfer between main memory and GPU memory - which is slow. Avoid "redrawing" the image into a BufferedImage therefore, avoid doing getPixel and setPixel at all means.

For example, if you are developing a game, instead of drawing all the game actors to a BufferedImage and then to a JPanel, it is a lot faster to load all actors as smaller BufferedImages, and draw them one by one in your JPanel code at their proper position - this way there is no additional data transfer between the main memory and GPU memory except of the initial transfer of the images for caching.

ImageIcon will use a BufferedImage under the hood - but basically allocating a BufferedImage with the proper graphics mode is the key, and there is no effort to do this right.

2) The usual way of doing this is to draw a BufferedImage in an overridden paintComponent method of the JPanel. Although Java supports a good amount of additional goodies such as buffer chains controlling VolatileImages cached in the GPU memory, there is no need to use any of these since Java 6 which does a reasonably good job without exposing all of these details of GPU acceleration.

Note that GPU acceleration may not work for certain operations, such as stretching translucent images.

3) Do not add. Just paint it as mentioned above:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, this); 
}

"Adding" makes sense if the image is part of the layout. If you need this as a background or foreground image filling the JPanel, just draw in paintComponent. If you prefer brewing a generic Swing component which can show your image, then it is the same story (you may use a JComponent and override its paintComponent method) - and then add this to your layout of GUI components.

4) How to convert the array to a Bufferedimage

Converting your byte arrays to PNG, then loading it is quite resource intensive. A better way is to convert your existing byte array to a BufferedImage.

For that: do not use for loops and copy pixels. That is very very slow. Instead:

  • learn the preferred byte structure of the BufferedImage (nowadays it is safe to assume RGB or RGBA, which is 4 bytes per pixel)
  • learn the scanline and scansize in use (e.g. you might have a 142 pixels wide image - but in the real life that will be stored as a 256 pixel wide byte array since it is faster to process that and mask the unused pixes by the GPU hardware)
  • then once you have an array build according to these principles, the setRGB array method of the BufferedImage can copy your array to the BufferedImage.

iPhone UIView Animation Best Practice

From the UIView reference's section about the beginAnimations:context: method:

Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.

Eg of Block-based Animation based on Tom's Comment

[UIView transitionWithView:mysuperview 
                  duration:0.75
                   options:UIViewAnimationTransitionFlipFromRight
                animations:^{ 
                    [myview removeFromSuperview]; 
                } 
                completion:nil];

How can I scroll a div to be visible in ReactJS?

I had a NavLink that I wanted to when clicked will scroll to that element like named anchor does. I implemented it this way.

 <NavLink onClick={() => this.scrollToHref('plans')}>Our Plans</NavLink>
  scrollToHref = (element) =>{
    let node;
    if(element === 'how'){
      node = ReactDom.findDOMNode(this.refs.how);
      console.log(this.refs)
    }else  if(element === 'plans'){
      node = ReactDom.findDOMNode(this.refs.plans);
    }else  if(element === 'about'){
      node = ReactDom.findDOMNode(this.refs.about);
    }

    node.scrollIntoView({block: 'start', behavior: 'smooth'});

  }

I then give the component I wanted to scroll to a ref like this

<Investments ref="plans"/>

Google Drive as FTP Server

What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.

The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.

I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.

This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter

How to normalize a signal to zero mean and unit variance?

It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)

This should work:

%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)

%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)

Import Excel Data into PostgreSQL 9.3

You can do that easily by DataGrip .

  1. First save your excel file as csv formate . Open the excel file then SaveAs as csv format
  2. Go to datagrip then create the table structure according to the csv file . Suggested create the column name as the column name as Excel column
  3. right click on the table name from the list of table name of your database then click of the import data from file . Then select the converted csv file . enter image description here

.

onclick="location.href='link.html'" does not load page in Safari

Use jQuery....I know you say you're trying to teach someone javascript, but teach him a cleaner technique... for instance, I could:

<select id="navigation">
    <option value="unit_01.htm">Unit 1</option>
    <option value="#5.2">Bookmark 2</option>
</select>

And with a little jQuery, you could do:

$("#navigation").change(function()
{
    document.location.href = $(this).val();
});

Unobtrusive, and with clean separation of logic and UI.

How to remove docker completely from ubuntu 14.04

Probably your problem is that for Docker that has been installed from default Ubuntu repository, the package name is docker.io

Or package name may be something like docker-ce. Try running

dpkg -l | grep -i docker

to identify what installed package you have

So you need to change package name in commands from https://stackoverflow.com/a/31313851/2340159 to match package name. For example, for docker.io it would be:

sudo apt-get purge -y docker.io
sudo apt-get autoremove -y --purge docker.io
sudo apt-get autoclean

It adds:

The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command:

sudo rm -rf /var/lib/docker

Remove docker from apparmor.d:

sudo rm /etc/apparmor.d/docker

Remove docker group:

sudo groupdel docker

Dynamically generating a QR code with PHP

I have been using google qrcode api for sometime, but I didn't quite like this because it requires me to be on the Internet to access the generated image.

I did a little comand-line research and found out that linux has a command line tool qrencode for generating qr-codes.

I wrote this little script. And the good part is that the generated image is less than 1KB in size. Well the supplied data is simply a url.

$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));

$imgData = "data:image/png;base64,".base64_encode($img);

Then in the html I load the image:

<img class="emrQRCode" src="<?=$imgData ?>" />

You just need to have installed it. [most imaging apps on linux would have installed it under the hood without you realizing.

How to check java bit version on Linux?

Go to this JVM online test and run it.

Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.

Oracle find a constraint

To get a more detailed description (which table/column references which table/column) you can run the following query:

SELECT   uc.constraint_name||CHR(10)
   ||      '('||ucc1.TABLE_NAME||'.'||ucc1.column_name||')' constraint_source
   ,       'REFERENCES'||CHR(10)
   ||      '('||ucc2.TABLE_NAME||'.'||ucc2.column_name||')' references_column
FROM user_constraints uc ,
  user_cons_columns ucc1 ,
  user_cons_columns ucc2
WHERE uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION        = ucc2.POSITION -- Correction for multiple column primary keys.
AND uc.constraint_type   = 'R'
AND uc.constraint_name   = 'SYS_C00381400'
ORDER BY ucc1.TABLE_NAME ,
  uc.constraint_name;

From here.

docker error: /var/run/docker.sock: no such file or directory

In Linux, first of all execute sudo service docker start in terminal.

Loop Through All Subfolders Using VBA

And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

Convert JSON to Map

If you need pure Java without any dependencies, you can use build in Nashorn API from Java 8. It is deprecated in Java 11.

This is working for me:

...
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
...

public class JsonUtils {

    public static Map parseJSON(String json) throws ScriptException {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");

        String script = "Java.asJSONCompatible(" + json + ")";

        Object result = engine.eval(script);

        return (Map) result;
    }
}

Sample usage

JSON:

{
    "data":[
        {"id":1,"username":"bruce"},
        {"id":2,"username":"clark"},
        {"id":3,"username":"diana"}
    ]
}

Code:

...
import jdk.nashorn.internal.runtime.JSONListAdapter;
...

public static List<String> getUsernamesFromJson(Map json) {
    List<String> result = new LinkedList<>();

    JSONListAdapter data = (JSONListAdapter) json.get("data");

    for(Object obj : data) {
        Map map = (Map) obj;
        result.add((String) map.get("username"));
    }

    return result;
}

sql server #region

No, #region does not exist in the T-SQL language.

You can get code-folding using begin-end blocks:

-- my region
begin
    -- code goes here
end

I'm not sure I'd recommend using them for this unless the code cannot be acceptably refactored by other means though!

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

Android open pdf file

The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}   

What is the difference between range and xrange functions in Python 2.X?

Remember, use the timeit module to test which of small snippets of code is faster!

$ python -m timeit 'for i in range(1000000):' ' pass'
10 loops, best of 3: 90.5 msec per loop
$ python -m timeit 'for i in xrange(1000000):' ' pass'
10 loops, best of 3: 51.1 msec per loop

Personally, I always use range(), unless I were dealing with really huge lists -- as you can see, time-wise, for a list of a million entries, the extra overhead is only 0.04 seconds. And as Corey points out, in Python 3.0 xrange() will go away and range() will give you nice iterator behavior anyway.

How to install plugin for Eclipse from .zip

It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.

If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.

Cordova : Requirements check failed for JDK 1.8 or greater

I agree with @Hozington. This should be the bug on Cordova code of detecting Java version. What I did is:

  1. Keep the JDK 10
  2. Install the JDK 8
  3. Change the JAVA_HOME to the path of JDK 8, and change the path variable as well.
  4. restart the "cmd" and run cordova build again.

And the error disappeared!

C++ Erase vector element by value rather than by position?

Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.

#include <iostream>
#include <range/v3/all.hpp>

int main(int argc, char const *argv[])
{
    std::vector<int> vi{2,4,6,8,10};
    for (auto& i : vi) {
        std::cout << i << std::endl;
    }
    std::cout << "-----" << std::endl;
    std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
    for (auto& i : vim) {
        std::cout << i << std::endl;
    }
    return 0;
}

outputs

2
4
6
8
10
-----
2
4
6
10

bootstrap datepicker today as default

Set after Init

 $('#dp-ex-3').datepicker({ autoclose: true, language: 'es' });
$('#dp-ex-3').datepicker('update', new Date());

This example is working.

How to set the JDK Netbeans runs on?

Where you already have a project in NetBeans and you wish to change the compiler (e.g. from 1.7 to 1.) then you would need to also change the Java source compiler for that project.

Right-click on the project and choose properties as outlined below:

Java Project Properties

Then check that the project has the necessary source circled below:

Project Source Compiler

then check that the Java compiler is correct for the project:

enter image description here

How to create the branch from specific commit in different branch

Try

git checkout <commit hash>
git checkout -b new_branch

The commit should only exist once in your tree, not in two separate branches.

This allows you to check out that specific commit and name it what you will.

Accessing constructor of an anonymous class

Peter Norvig's The Java IAQ: Infrequently Answered Questions

http://norvig.com/java-iaq.html#constructors - Anonymous class contructors

http://norvig.com/java-iaq.html#init - Construtors and initialization

Summing, you can construct something like this..

public class ResultsBuilder {
    Set<Result> errors;
    Set<Result> warnings;

...

    public Results<E> build() {
        return new Results<E>() {
            private Result[] errorsView;
            private Result[] warningsView;
            {
                errorsView = ResultsBuilder.this.getErrors();
                warningsView = ResultsBuilder.this.getWarnings();
            }

            public Result[] getErrors() {
                return errorsView;
            }

            public Result[] getWarnings() {
                return warningsView;
            }
        };
    }

    public Result[] getErrors() {
        return !isEmpty(this.errors) ? errors.toArray(new Result[0]) : null;
    }

    public Result[] getWarnings() {
        return !isEmpty(this.warnings) ? warnings.toArray(new Result[0]) : null;
    }
}

Determining Referer in PHP

There is no reliable way to check this. It's really under client's hand to tell you where it came from. You could imagine to use cookie or sessions informations put only on some pages of your website, but doing so your would break user experience with bookmarks.

Convert string (without any separator) to list

Instead of converting to a list, you could just iterate over the first string and create a second string by adding each of the digit characters you find to that new string.

Unable to Cast from Parent Class to Child Class

As of C# 7.0, you can use the is keyword to do this :

With those class defined :

class Base { /* Define base class */ }
class Derived : Base { /* Define derived class */ }

You can then do somehting like :

void Funtion(Base b)
{
    if (b is Derived d)
    {
        /* Do something with d which is now a variable of type Derived */
    }
}

Which would be equivalent to :

void Funtion(Base b)
{
    Defined d;
    if (b is Derived)
    {
        d = (Defined)b;
        /* Do something with d */
    }
}

You could now call :

Function(new Derived()); // Will execute code defined in if

As well as

Function(new Base()); // Won't execute code defined in if

That way you can be sure that your downcast will be valid and won't throw an exception !

How to pass an array into a SQL Server stored procedure

As others have noted above, one way to do this is to convert your array to a string and then split the string inside SQL Server.

As of SQL Server 2016, there's a built-in way to split strings called

STRING_SPLIT()

It returns a set of rows that you can insert into your temp table (or real table).

DECLARE @str varchar(200)
SET @str = "123;456;789;246;22;33;44;55;66"
SELECT value FROM STRING_SPLIT(@str, ';')

would yield:

value
-----
  123
  456
  789
  246
   22
   33
   44
   55
   66

If you want to get fancier:

DECLARE @tt TABLE (
    thenumber int
)
DECLARE @str varchar(200)
SET @str = "123;456;789;246;22;33;44;55;66"

INSERT INTO @tt
SELECT value FROM STRING_SPLIT(@str, ';')

SELECT * FROM @tt
ORDER BY thenumber

would give you the same results as above (except the column name is "thenumber"), but sorted. You can use the table variable like any other table, so you can easily join it with other tables in the DB if you want.

Note that your SQL Server install has to be at compatibility level 130 or higher in order for the STRING_SPLIT() function to be recognized. You can check your compatibility level with the following query:

SELECT compatibility_level
FROM sys.databases WHERE name = 'yourdatabasename';

Most languages (including C#) have a "join" function you can use to create a string from an array.

int[] myarray = {22, 33, 44};
string sqlparam = string.Join(";", myarray);

Then you pass sqlparam as your parameter to the stored procedure above.

PHP: How to use array_filter() to filter array keys?

PHP 5.6 introduced a third parameter to array_filter(), flag, that you can set to ARRAY_FILTER_USE_KEY to filter by key instead of value:

$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed  = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);

Clearly this isn't as elegant as array_intersect_key($my_array, array_flip($allowed)), but it does offer the additional flexibility of performing an arbitrary test against the key, e.g. $allowed could contain regex patterns instead of plain strings.

You can also use ARRAY_FILTER_USE_BOTH to have both the value and the key passed to your filter function. Here's a contrived example based upon the first, but note that I'd not recommend encoding filtering rules using $allowed this way:

$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed  = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
    $my_array,
    function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
        return isset($allowed[$key]) && (
            $allowed[$key] === true || $allowed[$key] === $val
        );
    },
    ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']

How to set a default row for a query that returns no rows?

One approach for Oracle:

SELECT val
FROM myTable
UNION ALL
SELECT 'DEFAULT'
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTable)

Or alternatively in Oracle:

SELECT NVL(MIN(val), 'DEFAULT')
FROM myTable

Or alternatively in SqlServer:

SELECT ISNULL(MIN(val), 'DEFAULT')
FROM myTable

These use the fact that MIN() returns NULL when there are no rows.

Is there a way to disable initial sorting for jquery DataTables?

As per latest api docs:

$(document).ready(function() {
    $('#example').dataTable({
        "order": []
    });
});

More Info

Display A Popup Only Once Per User

This example uses jquery-cookie

Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):

if($.cookie('popup') != 'seen'){
    $.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
    $j("#popup").delay(2000).fadeIn();
    $j('#popup-close').click(function(e) // You are clicking the close button
        {
        $j('#popup').fadeOut(); // Now the pop up is hiden.
    });
    $j('#popup').click(function(e) 
        {
        $j('#popup').fadeOut(); 
    });
};

PHP import Excel into database (xls & xlsx)

I wrote an inherited class:

_x000D_
_x000D_
<?php_x000D_
class ExcelReader extends Spreadsheet_Excel_Reader { _x000D_
 _x000D_
 function GetInArray($sheet=0) {_x000D_
_x000D_
  $result = array();_x000D_
_x000D_
   for($row=1; $row<=$this->rowcount($sheet); $row++) {_x000D_
    for($col=1;$col<=$this->colcount($sheet);$col++) {_x000D_
     if(!$this->sheets[$sheet]['cellsInfo'][$row][$col]['dontprint']) {_x000D_
      $val = $this->val($row,$col,$sheet);_x000D_
      $result[$row][$col] = $val;_x000D_
     }_x000D_
    }_x000D_
   }_x000D_
  return $result;_x000D_
 }_x000D_
_x000D_
}_x000D_
?>
_x000D_
_x000D_
_x000D_

So I can do this:

_x000D_
_x000D_
<?php_x000D_
_x000D_
 $data = new ExcelReader("any_excel_file.xls");_x000D_
 print_r($data->GetInArray());_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

http post - how to send Authorization header?

I believe you need to map the result before you subscribe to it. You configure it like this:

  updateProfileInformation(user: User) {
    var headers = new Headers();
    headers.append('Content-Type', this.constants.jsonContentType);

    var t = localStorage.getItem("accessToken");
    headers.append("Authorization", "Bearer " + t;
    var body = JSON.stringify(user);

    return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
      .map((response: Response) => {
        var result = response.json();
        return result;
      })
      .catch(this.handleError)
      .subscribe(
      status => this.statusMessage = status,
      error => this.errorMessage = error,
      () => this.completeUpdateUser()
      );
  }

Download text/csv content as files from server in Angular

Most of the references on the web about this issue point out to the fact that you cannot download files via ajax call 'out of the box'. I have seen (hackish) solutions that involve iframes and also solutions like @dcodesmith's that work and are perfectly viable.

Here's another solution I found that works in Angular and is very straighforward.

In the view, wrap the csv download button with <a> tag the following way :

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

(Notice the target="_self there, it's crucial to disable Angular's routing inside the ng-app more about it here)

Inside youre controller you can define csv_link the following way :

$scope.csv_link = '/orders' + $window.location.search;

(the $window.location.search is optional and onlt if you want to pass additionaly search query to your server)

Now everytime you click the button, it should start downloading.

Add numpy array as column to Pandas data frame

import numpy as np
import pandas as pd
import scipy.sparse as sparse

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)

yields

   0  1  2     newcol
0  1  2  3  [0, 1, 0]
1  4  5  6  [0, 0, 1]
2  7  8  9  [1, 0, 0]

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

How to download a file from a website in C#

You can use this code to Download file from a WebSite to Desktop:

using System.Net;

WebClient client = new WebClient ();
client.DownloadFileAsync(new Uri("http://www.Address.com/File.zip"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "File.zip");

Change the location of an object programmatically

When the parent panel has locked property set to true, we could not change the location property and the location property will act like read only by that time.

How to get the mouse position without events (without moving the mouse)?

var x = 0;
var y = 0;

document.addEventListener('mousemove', onMouseMove, false)

function onMouseMove(e){
    x = e.clientX;
    y = e.clientY;
}

function getMouseX() {
    return x;
}

function getMouseY() {
    return y;
}

Remove empty array elements

Remove empty array elements

function removeEmptyElements(&$element)
{
    if (is_array($element)) {
        if ($key = key($element)) {
            $element[$key] = array_filter($element);
        }

        if (count($element) != count($element, COUNT_RECURSIVE)) {
            $element = array_filter(current($element), __FUNCTION__);
        }

        return $element;
    } else {
        return empty($element) ? false : $element;
    }
}

$data = array(
    'horarios' => array(),
    'grupos' => array(
        '1A' => array(
            'Juan' => array(
                'calificaciones' => array(
                    'Matematicas' => 8,
                    'Español' => 5,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => 10,
                    'marzo' => '',
                )
            ),
            'Damian' => array(
                'calificaciones' => array(
                    'Matematicas' => 10,
                    'Español' => '',
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => '',
                    'marzo' => 5,
                )
            ),
        ),
        '1B' => array(
            'Mariana' => array(
                'calificaciones' => array(
                    'Matematicas' => null,
                    'Español' => 7,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => null,
                    'febrero' => 5,
                    'marzo' => 5,
                )
            ),
        ),
    )
);

$data = array_filter($data, 'removeEmptyElements');
var_dump($data);

¡it works!

Replace new lines with a comma delimiter with Notepad++?

USE Chrome's Search Bar

1-press CTRL F
2-paste the copied text in search bar
3-press CTRL A followed by CTRL C to copy the text again from search
4-paste in Notepad++
5-replace 'space' with ','

1-click for image
2-click for image

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

How to create a Calendar table for 100 years in Sql

As this is only tagged sql (which does not indicate any specific DBMS), here is a solution for Postgres:

select d::date 
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);

If you need that a lot, it's more efficient to store that in an table (which can e.g. be indexed):

create table calendar 
as
select d::date as the_date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);

Replace missing values with column mean

dplyr's mutate_all or mutate_at could be useful here:

library(dplyr)                                                             

set.seed(10)                                                               
df <- data.frame(a = sample(c(NA, 1:3)    , replace = TRUE, 10),           
                 b = sample(c(NA, 101:103), replace = TRUE, 10),                            
                 c = sample(c(NA, 201:203), replace = TRUE, 10))                            

df         

#>     a   b   c
#> 1   2 102 203
#> 2   1 102 202
#> 3   1  NA 203
#> 4   2 102 201
#> 5  NA 101 201
#> 6  NA 101 202
#> 7   1  NA 203
#> 8   1 101  NA
#> 9   2 101 203
#> 10  1 103 201

df %>% mutate_all(~ifelse(is.na(.x), mean(.x, na.rm = TRUE), .x))          

#>        a       b        c
#> 1  2.000 102.000 203.0000
#> 2  1.000 102.000 202.0000
#> 3  1.000 101.625 203.0000
#> 4  2.000 102.000 201.0000
#> 5  1.375 101.000 201.0000
#> 6  1.375 101.000 202.0000
#> 7  1.000 101.625 203.0000
#> 8  1.000 101.000 202.1111
#> 9  2.000 101.000 203.0000
#> 10 1.000 103.000 201.0000

df %>% mutate_at(vars(a, b),~ifelse(is.na(.x), mean(.x, na.rm = TRUE), .x))

#>        a       b   c
#> 1  2.000 102.000 203
#> 2  1.000 102.000 202
#> 3  1.000 101.625 203
#> 4  2.000 102.000 201
#> 5  1.375 101.000 201
#> 6  1.375 101.000 202
#> 7  1.000 101.625 203
#> 8  1.000 101.000  NA
#> 9  2.000 101.000 203
#> 10 1.000 103.000 201

How do you remove the title text from the Android ActionBar?

In your Manifest

<activity android:name=".ActivityHere"
     android:label="">

What are Covering Indexes and Covered Queries in SQL Server?

Here's an article in devx.com that says:

Creating a non-clustered index that contains all the columns used in a SQL query, a technique called index covering

I can only suppose that a covered query is a query that has an index that covers all the columns in its returned recordset. One caveat - the index and query would have to be built as to allow the SQL server to actually infer from the query that the index is useful.

For example, a join of a table on itself might not benefit from such an index (depending on the intelligence of the SQL query execution planner):

PersonID ParentID Name
1        NULL     Abe
2        NULL     Bob
3        1        Carl
4        2        Dave

Let's assume there's an index on PersonID,ParentID,Name - this would be a covering index for a query like:

SELECT PersonID, ParentID, Name FROM MyTable

But a query like this:

SELECT PersonID, Name FROM MyTable LEFT JOIN MyTable T ON T.PersonID=MyTable.ParentID

Probably wouldn't benifit so much, even though all of the columns are in the index. Why? Because you're not really telling it that you want to use the triple index of PersonID,ParentID,Name.

Instead, you're building a condition based on two columns - PersonID and ParentID (which leaves out Name) and then you're asking for all the records, with the columns PersonID, Name. Actually, depending on implementation, the index might help the latter part. But for the first part, you're better off having other indexes.

Find TODO tags in Eclipse

Sometimes Window ? Show View does not show the Tasks. Just go to Window ? Show View -> Others and type Tasks in the dialog box.

How do I apply a diff patch on Windows?

Apply Patch

With TortoiseMerge:

  1. Find and open an existing SVN repo directory
  2. Create a new directory named "merges", if it does not exist already
  3. Copy the file onto which you want to apply the .patch file
  4. ADD and COMMIT to the svn repository before you continue to the next step
  5. Right click on merges and choose Apply patch...
  6. Double click the file from list
  7. The patched file with diff is displayed on the right pane
  8. Click on that pane and hit Save or export with File->Save As...

Alternative screeny if you Open from TortoiseMerge. In the screeny below, directory refers to the "merges" directory mentioned at step 2 above: Screeny

Screenshot of WinMerge GUI: Screeny

Do HTTP POST methods send data as a QueryString?

A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.

How to set 777 permission on a particular folder?

  1. Right click the folder, click on Properties.
  2. Click on the Security tab
  3. Add the name Everyone to the user list.

How can I generate a list of consecutive numbers?

In Python 3, you can use the builtin range function like this

>>> list(range(9))
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Note 1: Python 3.x's range function, returns a range object. If you want a list you need to explicitly convert that to a list, with the list function like I have shown in the answer.

Note 2: We pass number 9 to range function because, range function will generate numbers till the given number but not including the number. So, we give the actual number + 1.

Note 3: There is a small difference in functionality of range in Python 2 and 3. You can read more about that in this answer.

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end