Programs & Examples On #Countdownlatch

A countdown latch is a synchronization primitive that allows one or more threads to wait until a certain number of operations are completed on other threads.

How is CountDownLatch used in Java Multithreading?

CoundDownLatch enables you to make a thread wait till all other threads are done with their execution.

Pseudo code can be:

// Main thread starts
// Create CountDownLatch for N threads
// Create and start N threads
// Main thread waits on latch
// N threads completes there tasks are returns
// Main thread resume execution

How to extend a class in python?

class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

An instance of ChildClass will then inherit the sayHi() method.

Sorting rows in a data table

Use LINQ - The beauty of C#

DataTable newDataTable = baseTable.AsEnumerable()
                   .OrderBy(r=> r.Field<int>("ColumnName"))
                   .CopyToDataTable();

Date only from TextBoxFor()

You can use below code to print time in HH:mm format, In my case Property type is TimeSpan So the value is coming in HH:mm:tt format but I have to show in above format ie. HH:mm

So you can use this code:

@Html.TextBoxFor(x =>x.mTimeFrom, null, new {@Value =Model.mTimeFrom.ToString().Substring(0,5), @class = "form-control success" })

Passing a method parameter using Task.Factory.StartNew

class Program
{
    static void Main(string[] args)
    {
        Task.Factory.StartNew(() => MyMethod("param value"));
    }

    private static void MyMethod(string p)
    {
        Console.WriteLine(p);
    }
}

Converting a char to uppercase

You can use Character#toUpperCase() for this.

char fUpper = Character.toUpperCase(f);
char lUpper = Character.toUpperCase(l);

It has however some limitations since the world is aware of many more characters than can ever fit in 16bit char range. See also the following excerpt of the javadoc:

Note: This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the toUpperCase(int) method.

Android REST client, Sample?

"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.

The only reference implementation I know (please comment if you know more) is available at Datadroid (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.

The second link asks for the "best" REST framework, which is discussed heavily on stackoverflow. For me the application size is important, followed by the performance of the implementation.

  • Normally I use the plain org.json implemantation, which is part of Android since API level 1 and therefore does not increase application size.
  • For me very interesting was the information found on JSON parsers performance in the comments: as of Android 3.0 Honeycomb, GSON's streaming parser is included as android.util.JsonReader. Unfortunately, the comments aren't available any more.
  • Spring Android (which I use sometimes) supports Jackson and GSON. The Spring Android RestTemplate Module documentation points to a sample app.

Therefore I stick to org.json or GSON for complexer scenarios. For the architecture of an org.json implementation, I am using a static class which represents the server use cases (e.g. findPerson, getPerson). I call this functionality from a service and use utility classes which are doing the mapping (project specific) and the network IO (my own REST template for plain GET or POST). I try to avoid the usage of reflection.

Javascript geocoding from address to latitude and longitude numbers not working

Try using this instead:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

It's bit hard to navigate Google's api but here is the relevant documentation.

One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

$.each(results[0].address_components, function(){
    $("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});

What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.
If you're only interrested in the whole formated address then you can follow Google's example

css divide width 100% to 3 column

I have found that 6 decimal places is sometimes required (at least in Chrome) for the 1/3 to return a perfect result.

E.g., 1140px / 3 = 380px

If you had 3 elements within the 1140 container, they would need to have a width set to 33.333333% before Chrome's inspector tool shows that they are at 380px. Any less amount of decimal places, and Chrome returns a lesser width of 379.XXXpx

How can I dynamically add a directive in AngularJS?

You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:

.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    scope: { text: '@' },
    template: '<p ng-click="add()">{{text}}</p>',
    controller: function ( $scope, $element ) {
      $scope.add = function () {
        var el = $compile( "<test text='n'></test>" )( $scope );
        $element.parent().append( el );
      };
    }
  };
});

You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.

Creating a singleton in Python

It is slightly similar to the answer by fab but not exactly the same.

The singleton contract does not require that we be able to call the constructor multiple times. As a singleton should be created once and once only, shouldn't it be seen to be created just once? "Spoofing" the constructor arguably impairs legibility.

So my suggestion is just this:

class Elvis():
    def __init__(self):
        if hasattr(self.__class__, 'instance'):
            raise Exception()
        self.__class__.instance = self
        # initialisation code...

    @staticmethod
    def the():
        if hasattr(Elvis, 'instance'):
            return Elvis.instance
        return Elvis()

This does not rule out the use of the constructor or the field instance by user code:

if Elvis() is King.instance:

... if you know for sure that Elvis has not yet been created, and that King has.

But it encourages users to use the the method universally:

Elvis.the().leave(Building.the())

To make this complete you could also override __delattr__() to raise an Exception if an attempt is made to delete instance, and override __del__() so that it raises an Exception (unless we know the program is ending...)

Further improvements


My thanks to those who have helped with comments and edits, of which more are welcome. While I use Jython, this should work more generally, and be thread-safe.

try:
    # This is jython-specific
    from synchronize import make_synchronized
except ImportError:
    # This should work across different python implementations
    def make_synchronized(func):
        import threading
        func.__lock__ = threading.Lock()

        def synced_func(*args, **kws):
            with func.__lock__:
                return func(*args, **kws)

        return synced_func

class Elvis(object): # NB must be subclass of object to use __new__
    instance = None

    @classmethod
    @make_synchronized
    def __new__(cls, *args, **kwargs):
        if cls.instance is not None:
            raise Exception()
        cls.instance = object.__new__(cls, *args, **kwargs)
        return cls.instance

    def __init__(self):
        pass
        # initialisation code...

    @classmethod
    @make_synchronized
    def the(cls):
        if cls.instance is not None:
            return cls.instance
        return cls()

Points of note:

  1. If you don't subclass from object in python2.x you will get an old-style class, which does not use __new__
  2. When decorating __new__ you must decorate with @classmethod or __new__ will be an unbound instance method
  3. This could possibly be improved by way of use of a metaclass, as this would allow you to make the a class-level property, possibly renaming it to instance

Check whether a value exists in JSON object

You could improve on the answer from Ponmudi VN:

  • Shorter Code
  • Look for a key and a value

See this fiddle: https://jsfiddle.net/solarbaypilot/sn3wtea2/

function _isContains(json, keyname, value) {

return Object.keys(json).some(key => {
        return typeof json[key] === 'object' ? 
        _isContains(json[key], keyname, value) : key === keyname && json[key] === value;
    });
}

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};


document.getElementById('dog').innerHTML = _isContains(JSONObject, "name", "dog");
document.getElementById('puppy').innerHTML = _isContains(JSONObject, "name", "puppy");

datetime dtypes in pandas read_csv

Why it does not work

There is no datetime dtype to be set for read_csv as csv files can only contain strings, integers and floats.

Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string.

Pandas way of solving this

The pandas.read_csv() function has a keyword argument called parse_dates

Using this you can on the fly convert strings, floats or integers into datetimes using the default date_parser (dateutil.parser.parser)

headers = ['col1', 'col2', 'col3', 'col4']
dtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'}
parse_dates = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes, parse_dates=parse_dates)

This will cause pandas to read col1 and col2 as strings, which they most likely are ("2016-05-05" etc.) and after having read the string, the date_parser for each column will act upon that string and give back whatever that function returns.

Defining your own date parsing function:

The pandas.read_csv() function also has a keyword argument called date_parser

Setting this to a lambda function will make that particular function be used for the parsing of the dates.

GOTCHA WARNING

You have to give it the function, not the execution of the function, thus this is Correct

date_parser = pd.datetools.to_datetime

This is incorrect:

date_parser = pd.datetools.to_datetime()

Pandas 0.22 Update

pd.datetools.to_datetime has been relocated to date_parser = pd.to_datetime

Thanks @stackoverYC

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

Node.js/Express.js App Only Works on Port 3000

If you are using Nodemon my guess is the PORT 3000 is set in the nodemonConfig. Check if that is the case.

How to find out if a Python object is a string?

For a nice duck-typing approach for string-likes that has the bonus of working with both Python 2.x and 3.x:

def is_string(obj):
    try:
        obj + ''
        return True
    except TypeError:
        return False

wisefish was close with the duck-typing before he switched to the isinstance approach, except that += has a different meaning for lists than + does.

Git: How configure KDiff3 as merge tool and diff tool

To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool will be

git config --global merge.guitool kdiff3 

That is because "git mergetool" learned to take the "--[no-]gui" option, just like "git difftool" does.

See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 87c15d1, 30 Oct 2018)

mergetool: accept -g/--[no-]gui as arguments

In line with how difftool accepts a -g/--[no-]gui option, make mergetool accept the same option in order to use the merge.guitool variable to find the default mergetool instead of merge.tool.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I must have arrived at the party late, none of the solutions here seemed helpful to me - too messy and felt like too much of a workaround.

What I ended up doing is using Angular 4.0.0-beta.6's ngComponentOutlet.

This gave me the shortest, simplest solution all written in the dynamic component's file.

  • Here is a simple example which just receives text and places it in a template, but obviously you can change according to your need:
import {
  Component, OnInit, Input, NgModule, NgModuleFactory, Compiler
} from '@angular/core';

@Component({
  selector: 'my-component',
  template: `<ng-container *ngComponentOutlet="dynamicComponent;
                            ngModuleFactory: dynamicModule;"></ng-container>`,
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  dynamicComponent;
  dynamicModule: NgModuleFactory<any>;

  @Input()
  text: string;

  constructor(private compiler: Compiler) {
  }

  ngOnInit() {
    this.dynamicComponent = this.createNewComponent(this.text);
    this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
  }

  protected createComponentModule (componentType: any) {
    @NgModule({
      imports: [],
      declarations: [
        componentType
      ],
      entryComponents: [componentType]
    })
    class RuntimeComponentModule
    {
    }
    // a module for just this Type
    return RuntimeComponentModule;
  }

  protected createNewComponent (text:string) {
    let template = `dynamically created template with text: ${text}`;

    @Component({
      selector: 'dynamic-component',
      template: template
    })
    class DynamicComponent implements OnInit{
       text: any;

       ngOnInit() {
       this.text = text;
       }
    }
    return DynamicComponent;
  }
}
  • Short explanation:
    1. my-component - the component in which a dynamic component is rendering
    2. DynamicComponent - the component to be dynamically built and it is rendering inside my-component

Don't forget to upgrade all the angular libraries to ^Angular 4.0.0

Hope this helps, good luck!

UPDATE

Also works for angular 5.

Difference between git pull and git pull --rebase

Suppose you have two commits in local branch:

      D---E master
     /
A---B---C---F origin/master

After "git pull", will be:

      D--------E  
     /          \
A---B---C---F----G   master, origin/master

After "git pull --rebase", there will be no merge point G. Note that D and E become different commits:

A---B---C---F---D'---E'   master, origin/master

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

For fitting y = A + B log x, just fit y against (log x).

>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> numpy.polyfit(numpy.log(x), y, 1)
array([ 8.46295607,  6.61867463])
# y ˜ 8.46 log(x) + 6.62

For fitting y = AeBx, take the logarithm of both side gives log y = log A + Bx. So fit (log y) against x.

Note that fitting (log y) as if it is linear will emphasize small values of y, causing large deviation for large y. This is because polyfit (linear regression) works by minimizing ?i (?Y)2 = ?i (YiYi)2. When Yi = log yi, the residues ?Yi = ?(log yi) ˜ ?yi / |yi|. So even if polyfit makes a very bad decision for large y, the "divide-by-|y|" factor will compensate for it, causing polyfit favors small values.

This could be alleviated by giving each entry a "weight" proportional to y. polyfit supports weighted-least-squares via the w keyword argument.

>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> numpy.polyfit(x, numpy.log(y), 1)
array([ 0.10502711, -0.40116352])
#    y ˜ exp(-0.401) * exp(0.105 * x) = 0.670 * exp(0.105 * x)
# (^ biased towards small values)
>>> numpy.polyfit(x, numpy.log(y), 1, w=numpy.sqrt(y))
array([ 0.06009446,  1.41648096])
#    y ˜ exp(1.42) * exp(0.0601 * x) = 4.12 * exp(0.0601 * x)
# (^ not so biased)

Note that Excel, LibreOffice and most scientific calculators typically use the unweighted (biased) formula for the exponential regression / trend lines. If you want your results to be compatible with these platforms, do not include the weights even if it provides better results.


Now, if you can use scipy, you could use scipy.optimize.curve_fit to fit any model without transformations.

For y = A + B log x the result is the same as the transformation method:

>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> scipy.optimize.curve_fit(lambda t,a,b: a+b*numpy.log(t),  x,  y)
(array([ 6.61867467,  8.46295606]), 
 array([[ 28.15948002,  -7.89609542],
        [ -7.89609542,   2.9857172 ]]))
# y ˜ 6.62 + 8.46 log(x)

For y = AeBx, however, we can get a better fit since it computes ?(log y) directly. But we need to provide an initialize guess so curve_fit can reach the desired local minimum.

>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t),  x,  y)
(array([  5.60728326e-21,   9.99993501e-01]),
 array([[  4.14809412e-27,  -1.45078961e-08],
        [ -1.45078961e-08,   5.07411462e+10]]))
# oops, definitely wrong.
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t),  x,  y,  p0=(4, 0.1))
(array([ 4.88003249,  0.05531256]),
 array([[  1.01261314e+01,  -4.31940132e-02],
        [ -4.31940132e-02,   1.91188656e-04]]))
# y ˜ 4.88 exp(0.0553 x). much better.

comparison of exponential regression

How do I center an anchor element in CSS?

You can try this code:

/**code starts here**/

a.class_name { display : block;text-align : center; }

UIScrollView scroll to bottom programmatically

Solution to scroll to last item of a table View :

Swift 3 :

if self.items.count > 0 {
        self.tableView.scrollToRow(at:  IndexPath.init(row: self.items.count - 1, section: 0), at: UITableViewScrollPosition.bottom, animated: true)
}

JSON to PHP Array using file_get_contents

The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.

One you have valid json you can use this code to convert it to an array.

json_decode($json, true);

Array
(
    [bpath] => http://www.sampledomain.com/
    [clist] => Array
        (
            [0] => Array
                (
                    [cid] => 11
                    [display_type] => grid
                    [ctitle] => abc
                    [acount] => 71
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6865
                                    [adate] => 2 Hours ago
                                    [atitle] => test
                                    [adesc] => test desc
                                    [aimg] => 
                                    [aurl] => ?nid=6865
                                    [weburl] => news.php?nid=6865
                                    [cmtcount] => 0
                                )

                            [1] => Array
                                (
                                    [aid] => 6857
                                    [adate] => 20 Hours ago
                                    [atitle] => test1
                                    [adesc] => test desc1
                                    [aimg] => 
                                    [aurl] => ?nid=6857
                                    [weburl] => news.php?nid=6857
                                    [cmtcount] => 0
                                )

                        )

                )

            [1] => Array
                (
                    [cid] => 1
                    [display_type] => grid
                    [ctitle] => test1
                    [acount] => 2354
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6851
                                    [adate] => 1 Days ago
                                    [atitle] => test123
                                    [adesc] => test123 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6851
                                    [weburl] => news.php?nid=6851
                                    [cmtcount] => 7
                                )

                            [1] => Array
                                (
                                    [aid] => 6847
                                    [adate] => 2 Days ago
                                    [atitle] => test12345
                                    [adesc] => test12345 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6847
                                    [weburl] => news.php?nid=6847
                                    [cmtcount] => 7
                                )

                        )

                )

        )

)

Is there a Google Voice API?

There is a C# Google Voice API... there is limited documentation, however the download has an application that 'works' using the API that is included:

https://sourceforge.net/projects/gvoicedotnet/

Matplotlib: ValueError: x and y must have same first dimension

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

Dynamic SELECT TOP @var In SQL Server

Or you just put the variable in parenthesis

DECLARE @top INT = 10;

SELECT TOP (@Top) *
FROM <table_name>;

How do I print part of a rendered HTML page in JavaScript?

You could use a print stylesheet, but this will affect all print functions.

You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print(), then after that remove it.

Adjusting the Xcode iPhone simulator scale and size

In Xcode 9 there is a new "Actual Size" option. In the Simulator to the Window menu and choose Scale > Actual Size to trigger it. This takes into account your current screen resolution to ensure the on-screen device matches the physical dimensions of a real device.

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

ol {
  font-weight: bold;
}

ol > li > * {
  font-weight: normal;
}

So you have no "style" attributes in your HTML

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Fastest Way of Inserting in Entity Framework

SqlBulkCopy is super quick

This is my implementation:

// at some point in my calling code, I will call:
var myDataTable = CreateMyDataTable();
myDataTable.Rows.Add(Guid.NewGuid,tableHeaderId,theName,theValue); // e.g. - need this call for each row to insert

var efConnectionString = ConfigurationManager.ConnectionStrings["MyWebConfigEfConnection"].ConnectionString;
var efConnectionStringBuilder = new EntityConnectionStringBuilder(efConnectionString);
var connectionString = efConnectionStringBuilder.ProviderConnectionString;
BulkInsert(connectionString, myDataTable);

private DataTable CreateMyDataTable()
{
    var myDataTable = new DataTable { TableName = "MyTable"};
// this table has an identity column - don't need to specify that
    myDataTable.Columns.Add("MyTableRecordGuid", typeof(Guid));
    myDataTable.Columns.Add("MyTableHeaderId", typeof(int));
    myDataTable.Columns.Add("ColumnName", typeof(string));
    myDataTable.Columns.Add("ColumnValue", typeof(string));
    return myDataTable;
}

private void BulkInsert(string connectionString, DataTable dataTable)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlTransaction transaction = null;
        try
        {
            transaction = connection.BeginTransaction();

            using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
            {
                sqlBulkCopy.DestinationTableName = dataTable.TableName;
                foreach (DataColumn column in dataTable.Columns) {
                    sqlBulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                }

                sqlBulkCopy.WriteToServer(dataTable);
            }
            transaction.Commit();
        }
        catch (Exception)
        {
            transaction?.Rollback();
            throw;
        }
    }
}

Using the Jersey client to do a POST operation

Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.

Example taken from the blog post:

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
    .post(ClientResponse.class, formData);

That any help?

Npm install cannot find module 'semver'

I'm facing the same issue here.

If this occurs right after you run brew install yarn try running yarn global add npm and voilà - fixed!

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

In short, yes, the order is preserved. In long:

In general the following definitions will always apply to objects like lists:

A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa" can exist and != "a").

A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).

Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.

This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the + sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.

If we have

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]

Then

list1 + list2

Is the same as

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

Which evaluates to

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

Much like

"abdcde" + "fghijk"

Produces

"abdcdefghijk"

github changes not staged for commit

In my case the problem was the subfolder that I was tying to push was a git folder itself

So I did the following

  1. Go inside the subfolder that you want to push and run this:
rm -rf .git
  1. Then run this:
 git rm --cached <subfolderName>
  1. Then come to main project folder and run this (make sure to add / after folder name)
    git add <folderName>/
    git commit -m "Commit message"
    git push -f origin <branchName>

AngularJS - Passing data between pages

app.factory('persistObject', function () {

        var persistObject = [];

        function set(objectName, data) {
            persistObject[objectName] = data;
        }
        function get(objectName) {
            return persistObject[objectName];
        }

        return {
            set: set,
            get: get
        }
    });

Fill it with data like this

persistObject.set('objectName', data); 

Get the object data like this

persistObject.get('objectName'); 

Can you install and run apps built on the .NET framework on a Mac?

.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

First of all you should know which statements are affected by the automatic semicolon insertion (also known as ASI for brevity):

  • empty statement
  • var statement
  • expression statement
  • do-while statement
  • continue statement
  • break statement
  • return statement
  • throw statement

The concrete rules of ASI, are described in the specification §11.9.1 Rules of Automatic Semicolon Insertion

Three cases are described:

  1. When an offending token is encountered that is not allowed by the grammar, a semicolon is inserted before it if:
  • The token is separated from the previous token by at least one LineTerminator.
  • The token is }

e.g.:

    { 1
    2 } 3

is transformed to

    { 1
    ;2 ;} 3;

The NumericLiteral 1 meets the first condition, the following token is a line terminator.
The 2 meets the second condition, the following token is }.

  1. When the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete Program, then a semicolon is automatically inserted at the end of the input stream.

e.g.:

    a = b
    ++c

is transformed to:

    a = b;
    ++c;
  1. This case occurs when a token is allowed by some production of the grammar, but the production is a restricted production, a semicolon is automatically inserted before the restricted token.

Restricted productions:

    UpdateExpression :
        LeftHandSideExpression [no LineTerminator here] ++
        LeftHandSideExpression [no LineTerminator here] --
    
    ContinueStatement :
        continue ;
        continue [no LineTerminator here] LabelIdentifier ;
    
    BreakStatement :
        break ;
        break [no LineTerminator here] LabelIdentifier ;
    
    ReturnStatement :
        return ;
        return [no LineTerminator here] Expression ;
    
    ThrowStatement :
        throw [no LineTerminator here] Expression ; 

    ArrowFunction :
        ArrowParameters [no LineTerminator here] => ConciseBody

    YieldExpression :
        yield [no LineTerminator here] * AssignmentExpression
        yield [no LineTerminator here] AssignmentExpression

The classic example, with the ReturnStatement:

    return 
      "something";

is transformed to

    return;
      "something";

jquery onclick change css background image

You need to use background-image instead of backgroundImage. For example:

$(function() {
  $('.home').click(function() {
    $(this).css('background-image', 'url(images/tabs3.png)');
  });
}):

How to get a substring of text?

If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)

Force browser to refresh css, javascript, etc

Make sure this isn't happening from your DNS. For example Cloudflare has it where you can turn on development mode where it forces a purge on your stylesheets and images as Cloudflare offers accelerated cache. This will disable it and force it to update everytime someone visits your site.

org.hibernate.MappingException: Unknown entity

use below line of code in the case of spring boot applications.

@EntityScan(basePackageClasses=YourClassName.class)

Xcode Product -> Archive disabled

Select active scheme to Generic iOs Device.

select to Generic iOs Device

Program to find largest and smallest among 5 numbers without using array

You could use list (or vector), which is not an array:

#include<list>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    list<int> l;
    l.push_back(3); 
    l.push_back(9); 
    l.push_back(30);    
    l.push_back(0); 
    l.push_back(5); 

    list<int>::iterator it_max = max_element(l.begin(), l.end());
    list<int>::iterator it_min = min_element(l.begin(), l.end());

    cout << "Max: " << *it_max << endl;
    cout << "Min: " << *it_min << endl;
}

how to install multiple versions of IE on the same system?

I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.

How do I get the fragment identifier (value after hash #) from a URL?

You may do it by using following code:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

How do I use the CONCAT function in SQL Server 2008 R2?

Just for completeness - in SQL 2008 you would use the plus + operator to perform string concatenation.

Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.

CSS text-overflow in a table cell?

Why does this happen?

It seems this section on w3.org suggests that text-overflow applies only to block elements:

11.1.  Overflow Ellipsis: the ‘text-overflow’ property

text-overflow      clip | ellipsis | <string>  
Initial:           clip   
APPLIES TO:        BLOCK CONTAINERS               <<<<
Inherited:         no  
Percentages:       N/A  
Media:             visual  
Computed value:    as specified  

The MDN says the same.

This jsfiddle has your code (with a few debug modifications), which works fine if it's applied to a div instead of a td. It also has the only workaround I could quickly think of, by wrapping the contents of the td in a containing div block. However, that looks like "ugly" markup to me, so I'm hoping someone else has a better solution. The code to test this looks like this:

_x000D_
_x000D_
td, div {_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  border: 1px solid red;_x000D_
  width: 80px;_x000D_
}
_x000D_
Works, but no tables anymore:_x000D_
<div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div>_x000D_
_x000D_
Works, but non-semantic markup required:_x000D_
<table><tr><td><div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div></td></tr></table>
_x000D_
_x000D_
_x000D_

How to remove multiple deleted files in Git repository

When I have a lot of files I've deleted that are unstaged for commit, you can git rm them all in one show with:

for i in `git status | grep deleted | awk '{print $3}'`; do git rm $i; done

As question answerer mentioned, be careful with git rm.

Java escape JSON String?

Try to replace all the " and ' with a \ before them. Do this just for the msget object(String, I guess). Don't forget that \ must be escaped too.

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Another reason this can happen:

The component you are using formControl in is not declared in a module that imports the ReactiveFormsModule.

So check the module that declares the component that throws this error.

a tag as a submit button?

Give the form an id, and then:

document.getElementById("yourFormId").submit();

Best practice would probably be to give your link an id too, and get rid of the event handler:

document.getElementById("yourLinkId").onclick = function() {
    document.getElementById("yourFormId").submit();
}

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

How to use onClick event on react Link component?

You should use this:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

Multiple arguments to function called by pthread_create()?

use

struct arg_struct *args = (struct arg_struct *)arguments;

in place of

struct arg_struct *args = (struct arg_struct *)args;

Java program to find the largest & smallest number in n numbers without using arrays

public static void main(String[] args) {
    int smallest = 0;
    int large = 0;
    int num;
    System.out.println("enter the number");//how many number you want to enter
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    num = input.nextInt();
    smallest = num; //assume first entered number as small one
    // i starts from 2 because we already took one num value
    for (int i = 2; i < n; i++) {
        num = input.nextInt();
        //comparing each time entered number with large one
        if (num > large) {
            large = num;
        }
        //comparing each time entered number with smallest one
        if (num < smallest) {
            smallest = num;
        }
    }
    System.out.println("the largest is:" + large);
    System.out.println("Smallest no is : " + smallest);
}

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

mongo - couldn't connect to server 127.0.0.1:27017

After exhausting lots and lots of sulotions, I did-

sudo brew services start mongodb-community rather than sudo service mongod start and it worked.

So, first try

sudo brew services start mongodb-community

and then to start the mongo shell, do-

mongo

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Generally I face the same problem when I copy some snippets from internet with some special chars that breaks the Intellisense.

It happened a few times with me, I discovered the problem after deleting the file and creating a new one, now when I face the same problem, fist I restart the Visual Studio, if this doesn't resolve the problem, I remove the last snippet I copied from internet and do it by hand, them the problem is gone.

How to include *.so library in Android Studio?

I have solved a similar problem using external native lib dependencies that are packaged inside of jar files. Sometimes these architecture dependend libraries are packaged alltogether inside one jar, sometimes they are split up into several jar files. so i wrote some buildscript to scan the jar dependencies for native libs and sort them into the correct android lib folders. Additionally this also provides a way to download dependencies that not found in maven repos which is currently usefull to get JNA working on android because not all native jars are published in public maven repos.

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0'

    lintOptions {
        abortOnError false
    }


    defaultConfig {
        applicationId "myappid"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]
        }
    }
}

def urlFile = { url, name ->
    File file = new File("$buildDir/download/${name}.jar")
    file.parentFile.mkdirs()
    if (!file.exists()) {
        new URL(url).withInputStream { downloadStream ->
            file.withOutputStream { fileOut ->
                fileOut << downloadStream
            }
        }
    }
    files(file.absolutePath)
}
dependencies {
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'net.java.dev.jna:jna:4.2.0'
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-arm.jar?raw=true', 'jna-android-arm')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-armv7.jar?raw=true', 'jna-android-armv7')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-aarch64.jar?raw=true', 'jna-android-aarch64')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86.jar?raw=true', 'jna-android-x86')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86-64.jar?raw=true', 'jna-android-x86_64')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips.jar?raw=true', 'jna-android-mips')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips64.jar?raw=true', 'jna-android-mips64')
}
def safeCopy = { src, dst ->
    File fdst = new File(dst)
    fdst.parentFile.mkdirs()
    fdst.bytes = new File(src).bytes

}

def archFromName = { name ->
    switch (name) {
        case ~/.*android-(x86-64|x86_64|amd64).*/:
            return "x86_64"
        case ~/.*android-(i386|i686|x86).*/:
            return "x86"
        case ~/.*android-(arm64|aarch64).*/:
            return "arm64-v8a"
        case ~/.*android-(armhf|armv7|arm-v7|armeabi-v7).*/:
            return "armeabi-v7a"
        case ~/.*android-(arm).*/:
            return "armeabi"
        case ~/.*android-(mips).*/:
            return "mips"
        case ~/.*android-(mips64).*/:
            return "mips64"
        default:
            return null
    }
}

task extractNatives << {
    project.configurations.compile.each { dep ->
        println "Scanning ${dep.name} for native libs"
        if (!dep.name.endsWith(".jar"))
            return
        zipTree(dep).visit { zDetail ->
            if (!zDetail.name.endsWith(".so"))
                return
            print "\tFound ${zDetail.name}"
            String arch = archFromName(zDetail.toString())
            if(arch != null){
                println " -> $arch"
                safeCopy(zDetail.file.absolutePath,
                        "$buildDir/native-libs/$arch/${zDetail.file.name}")
            } else {
                println " -> No valid arch"
            }
        }
    }
}

preBuild.dependsOn(['extractNatives'])

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

If you are using vitamio library and this fatal error occur.

Then make sure that in your project gradle targetSdkVersion must be less than 23.

thanks.

How to SELECT by MAX(date)?

I use this solution having max(date_entered) and it works very well

SELECT 
  report_id, 
  computer_id, 
  date_entered
FROM reports
GROUP BY computer_id having max(date_entered)

Graphviz: How to go from .dot to a graph?

For window user, Please run complete command to convert *.dot file to png:

C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" -Tpng sampleTest.dot > sampletest.png.....

I have found a bug in solgraph that it is utilizing older version of solidity-parser that does not seem to be intelligent enough to capture new enhancement done for solidity programming language itself e.g. emit keyword for Event

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

I encountered the same problem but none of your answers solved it. But I found this link. I had to edit /etc/phpmyadmin/config.inc.php:

$cfg['Servers'][$i]['table_uiprefs'] = 'pma_table_uiprefs';

into

$cfg['Servers'][$i]['pma__table_uiprefs'] = ‘pma__table_uiprefs’;

My problem was solved, hope it can help others.

connect local repo with remote repo

I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.

Get the current first responder without using a private API

You can choose the following UIView extension to get it (credit by Daniel):

extension UIView {
    var firstResponder: UIView? {
        guard !isFirstResponder else { return self }
        return subviews.first(where: {$0.firstResponder != nil })
    }
}

Difference between Inheritance and Composition

Inheritance brings out IS-A relation. Composition brings out HAS-A relation. Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.
Classic example being of a duck class which implements a flying behaviour.

public interface Flyable{
 public void fly();
}

public class Duck {
 Flyable fly;

 public Duck(){
  fly = new BackwardFlying();
 }
}

Thus we can have multiple classes which implement flying eg:

public class BackwardFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies backward ");
  }
}
public class FastFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies 100 miles/sec");
  }
}

Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.

How to hide .php extension in .htaccess

The other option for using PHP scripts sans extension is

Options +MultiViews

Or even just following in the directories .htaccess:

DefaultType application/x-httpd-php

The latter allows having all filenames without extension script being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

What's the difference between `raw_input()` and `input()` in Python 3?

I'd like to add a little more detail to the explanation provided by everyone for the python 2 users. raw_input(), which, by now, you know that evaluates what ever data the user enters as a string. This means that python doesn't try to even understand the entered data again. All it will consider is that the entered data will be string, whether or not it is an actual string or int or anything.

While input() on the other hand tries to understand the data entered by the user. So the input like helloworld would even show the error as 'helloworld is undefined'.

In conclusion, for python 2, to enter a string too you need to enter it like 'helloworld' which is the common structure used in python to use strings.

ngOnInit not being called when Injectable class is Instantiated

I don't know about all the lifecycle hooks, but as for destruction, ngOnDestroy actually get called on Injectable when it's provider is destroyed (for example an Injectable supplied by a component).

From the docs :

Lifecycle hook that is called when a directive, pipe or service is destroyed.

Just in case anyone is interested in destruction check this question:

String comparison technique used by Python

This is a lexicographical ordering. It just puts things in dictionary order.

Plotting multiple curves same graph and same scale

I'm not sure what you want, but i'll use lattice.

x = rep(x,2)
y = c(y1,y2)
fac.data = as.factor(rep(1:2,each=5))
df = data.frame(x=x,y=y,z=fac.data)
# this create a data frame where I have a factor variable, z, that tells me which data I have (y1 or y2)

Then, just plot

xyplot(y ~x|z, df)
# or maybe
xyplot(x ~y|z, df)

Rename Oracle Table or View

Past 10g the current answer no longer works for renaming views. The only method that still works is dropping and recreating the view. The best way I can think of to do this would be:

SELECT TEXT FROM ALL_VIEWS WHERE owner='some_schema' and VIEW_NAME='some_view';

Add this in front of the SQL returned

Create or replace view some_schema.new_view_name as ...

Drop the old view

Drop view some_schema.some_view;

How to add/update an attribute to an HTML element using JavaScript?

What do you want to do with the attribute? Is it an html attribute or something of your own?

Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This is not a new answer but will help somebody who's not sure how to set primary key for their table. Use this in a new query and run. This will set UniqueID column as primary key.

USE [YourDatabaseName]
GO

Alter table  [dbo].[YourTableNname]
Add Constraint PK_YourTableName_UniqueID Primary Key Clustered (UniqueID);
GO

"inappropriate ioctl for device"

Odd errors like "inappropriate ioctl for device" are usually a result of checking $! at some point other than just after a system call failed. If you'd show your code, I bet someone would rapidly point out your error.

How to insert element into arrays at specific position?

Here is my version:

/**
 * 
 * Insert an element after an index in an array
 * @param array $array  
 * @param string|int $key 
 * @param mixed $value
 * @param string|int $offset
 * @return mixed
 */
function array_splice_associative($array, $key, $value, $offset) {
    if (!is_array($array)) {
        return $array;
    }
    if (array_key_exists($key, $array)) {
        unset($array[$key]);
    }
    $return = array();
    $inserted = false;
    foreach ($array as $k => $v) {
        $return[$k] = $v;
        if ($k == $offset && !$inserted) {
            $return[$key] = $value;
            $inserted = true;
        }
    }
    if (!$inserted) {
        $return[$key] = $value;
    }


    return $return;
}

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

How to check if an integer is within a range of numbers in PHP?

The expression:

 ($min <= $value) && ($value <= $max)

will be true if $value is between $min and $max, inclusively

See the PHP docs for more on comparison operators

shorthand c++ if else statement

try this:

bigInt.sign = number < 0 ? 0 : 1

Different ways of clearing lists

If you're clearing the list, you, obviously, don't need the list anymore. If so, you can just delete the entire list by simple del method.

a = [1, 3, 5, 6]
del a # This will entirely delete a(the list).

But in case, you need it again, you can reinitialize it. Or just simply clear its elements by

del a[:]

C# Listbox Item Double Click Event

void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    int index = this.listBox1.IndexFromPoint(e.Location);
    if (index != System.Windows.Forms.ListBox.NoMatches)
    {
        MessageBox.Show(index.ToString());
    }
}

This should work...check

Remote origin already exists on 'git push' to a new repository

This can also happen when you forget to make a first commit.

How to run Pip commands from CMD

Simple solution that worked for me is, set the path of python in environment variables,it is done as follows

  1. Go to My Computer
  2. Open properties
  3. Open Advanced Settings
  4. Open Environment Variables
  5. Select path
  6. Edit it

In the edit option click add and add following two paths to it one by one:

C:\Python27

C:\Python27\Scripts

and now close cmd and run it as administrator, by that pip will start working.

How do you redirect to a page using the POST verb?

HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Well, I can think of a CSS hack that will resolve this issue.

You could add the following line in your CSS file:

* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; } 

The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

How to Scroll Down - JQuery

This can be used in to solve this problem

<div id='scrol'></div> 

in javascript use this

jQuery("div#scrol").scrollTop(jQuery("div#scrol")[0].scrollHeight);

jQuery: more than one handler for same event

Both handlers get called.

You may be thinking of inline event binding (eg "onclick=..."), where a big drawback is only one handler may be set for an event.

jQuery conforms to the DOM Level 2 event registration model:

The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

android set button background programmatically

For not changing the size of button on setting the background color:

button.getBackground().setColorFilter(button.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

this didn't change the size of the button and works with the old android versions too.

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Removing specific rows from a dataframe

Here's a solution to your problem using dplyr's filter function.

Although you can pass your data frame as the first argument to any dplyr function, I've used its %>% operator, which pipes your data frame to one or more dplyr functions (just filter in this case).

Once you are somewhat familiar with dplyr, the cheat sheet is very handy.

> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
   sub day
1    1   1
2    1   2
3    1   3
4    1   4
5    2   1
6    2   2
7    2   3
8    2   4
9    3   1
10   3   2
11   3   3
12   3   4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
   sub day
1    1   1
2    1   3
3    1   4
4    2   1
5    2   2
6    2   3
7    2   4
8    3   1
9    3   2
10   3   3

Converting String Array to an Integer Array

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));

Format date with Moment.js

The 2nd argument to moment() is a parsing format rather than an display format.

For that, you want the .format() method:

moment(testDate).format('MM/DD/YYYY');

Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.

Is there a quick change tabs function in Visual Studio Code?

Visual Studio Code v1.35.0 let's you set the (Ctrl+Tab) / (Shift+Ctrl+Tab) key sequences to sequentially switch between editors by binding those keys sequences to the commands "View: Open Next Editor" and "View: Open Previous Editor", respectively.

On macOS:

  1. Navigate to: Code > Preferences > Keyboard Shortcuts
  2. Search or navigate down to the following two options:
    • View: Open Next Editor
    • View: Open Previous Editor
  3. Change both keybindings to the desired key sequence.
    • View: Open Next Editor -> (Ctrl+Tab)
    • View: Open Previous Editor -> (Shift+Ctrl+Tab)
  4. You will likely run into a conflicting binding. If so, take note of the command and reassign or remove the existing key binding.

If you mess up, you can always revert back to the default state for a given binding by right-clicking on any keybinding and selecting "Reset Keybinding".

Server certificate verification failed: issuer is not trusted

Run "svn help commit" to all available options. You will see that there is one option responsible for accepting server certificates:

--trust-server-cert : accept unknown SSL server certificates without prompting (but only with --non-interactive)

Add it to your svn command arguments and you will not need to run svn manually to accept it permanently.

How to reload .bash_profile from the command line?

if the .bash_profile does not exist you can try run the following command:

. ~/.bashrc 

or

 source ~/.bashrc

instead of .bash_profile. You can find more information about bashrc

What is the difference between SessionState and ViewState?

Session State contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It's a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state.
View State on the other hand is information specific to particular web page. It is stored in a hidden field so that it isn't visible to the user. It is used to maintain the user's illusion that the page remembers what he did on it the last time - dont give him a clean page every time he posts back. Check this page for more.

Reference jars inside a jar

You will need a custom class loader for this, have a look at One Jar.

One-JAR lets you package a Java application together with its dependency Jars into a single executable Jar file.

It has an ant task which can simplify the building of it as well.

REFERENCE (from background)

Most developers reasonably assume that putting a dependency Jar file into their own Jar file, and adding a Class-Path attribute to the META-INF/MANIFEST will do the trick:


jarname.jar
| /META-INF
| |  MANIFEST.MF
| |    Main-Class: com.mydomain.mypackage.Main
| |    Class-Path: commons-logging.jar
| /com/mydomain/mypackage
| |  Main.class
| commons-logging.jar

Unfortunately this is does not work. The Java Launcher$AppClassLoader does not know how to load classes from a Jar inside a Jar with this kind of Class-Path. Trying to use jar:file:jarname.jar!/commons-logging.jar also leads down a dead-end. This approach will only work if you install (i.e. scatter) the supporting Jar files into the directory where the jarname.jar file is installed.

Fastest way to copy a file in Node.js

I was not able to get the createReadStream/createWriteStream method working for some reason, but using the fs-extra npm module it worked right away. I am not sure of the performance difference though.

npm install --save fs-extra

var fs = require('fs-extra');

fs.copySync(path.resolve(__dirname, './init/xxx.json'), 'xxx.json');

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

I guess it depends on what you want. For simple objects, I guess you could use the second methods. When your objects grow larger and you're planning on using similar objects, I guess the first method would be better. That way you can also extend it using prototypes.

Example:

function Circle(radius) {
    this.radius = radius;
}
Circle.prototype.getCircumference = function() {
    return Math.PI * 2 * this.radius;
};
Circle.prototype.getArea = function() {
    return Math.PI * this.radius * this.radius;
}

I am not a big fan of the third method, but it's really useful for dynamically editing properties, for example var foo='bar'; var bar = someObject[foo];.

Shortcut to exit scale mode in VirtualBox

To exit Scale Mode, press:

Right Ctrl (Host Key) + c


Note that your (Host Key) may be different from Right Ctrl. To check the current binding, go to VirtualBox Preferences > Input > Virtual Machine > Host Key Combination.

Why is this rsync connection unexpectedly closed on Windows?

This error message probably means that you either mistyped the server name or forgot to start an ssh server at server. Make absolutely certain that an ssh server is running on the server at port 22, and that it's not firewalled. You can test that with ssh user@server.

How to pass the password to su/sudo/ssh without overriding the TTY?

For ssh you can use sshpass: sshpass -p yourpassphrase ssh user@host.

You just need to download sshpass first :)

$ apt-get install sshpass
$ sshpass -p 'password' ssh username@server

Draw radius around a point in Google map

In spherical geometry shapes are defined by points, lines and angles between those lines. You have only those rudimentary values to work with.

Therefore a circle (in terms of a a shape projected onto a sphere) is something that must be approximated using points. The more points, the more it'll look like a circle.

Having said that, realize that google maps is projecting the earth onto a flat surface (think "unrolling" the earth and stretching+flattening until it looks "square"). And if you have a flat coordinate system you can draw 2D objects on it all you want.

In other words you can draw a scaled vector circle on a google map. The catch is, google maps doesn't give it to you out of the box (they want to stay as close to GIS values as is pragmatically possible). They only give you GPolygon which they want you to use to approximate a circle. However, this guy did it using vml for IE and svg for other browsers (see "SCALED CIRCLES" section).

Now, going back to your question about Google Latitude using a scaled circle image (and this is probably the most useful to you): if you know the radius of your circle will never change (eg it's always 10 miles around some point), then the easiest solution would be to use a GGroundOverlay, which is just an image url + the GLatLngBounds the image represents. The only work you need to do then is cacluate the GLatLngBounds representing your 10 mile radius. Once you have that, the google maps api handles scaling your image as the user zooms in and out.

Go to beginning of line without opening new line in VI

Try this Vi/Vim cheatsheet solution to many problems.

For normal mode :
0 - [zero] to beginning of line, first column.
$ - to end of line

How to extract Month from date in R

Her is another R base approach:

From your example: Some date:

Some_date<-"01/01/1979"

We tell R, "That is a Date"

Some_date<-as.Date(Some_date)

We extract the month:

months(Some_date)

output: [1] "January"

Finally, we can convert it to a numerical variable:

as.numeric(as.factor(months(Some_date)))

outpt: [1] 1

Why plt.imshow() doesn't display the image?

plt.imshow just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show.

Python: 'break' outside loop

Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.

What are you trying to do? Perhaps you should use sys.exit() or return instead?

Is it possible to have a default parameter for a mysql stored procedure?

If you look into CREATE PROCEDURE Syntax for latest MySQL version you'll see that procedure parameter can only contain IN/OUT/INOUT specifier, parameter name and type.

So, default values are still unavailable in latest MySQL version.

Is it possible to run selenium (Firefox) web driver without a GUI?

An optional is to use pyvirtualdisplay like this:

from pyvirtualdisplay import Display

display = Display(visible=0, size=[800, 600])
display.start()

#do selenium job here

display.close()

A shorter version is:

with Display() as display:
    # selenium job here

This is generally a python encapsulate of xvfb, and more convinient somehow.

By the way, although PhantomJS is a headless browser and no window will be open if you use it, it seems that PhantomJS still needs a gui environment to work.

I got Error Code -6 when I use PhantomJS() instead of Firefox() in headless mode (putty-connected console). However everything is ok in desktop environment.

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

Sending SMS from PHP

You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.

Repository access denied. access via a deployment key is read-only

Recently I faced the same issue. I got the following error:

repository access denied. access via a deployment key is read-only.

You can have two kinds of SSH keys:

  1. For your entire account which will work for all repositories
  2. Per repository SSH key which can only be used for that specific repository.

I simply removed my repository SSH key and added a new SSH key to my account and it worked well.

I hope it helps someone. Cheers

Eclipse/Java code completion not working

For those running Xfce + having IBus plugin activated, there might be keyboard shortcut conflict.

See more info on my blog: http://peter-butkovic.blogspot.de/2013/05/keyboard-shortcut-ctrlspace-caught-in.html

UPDATE:

as suggested by @nhahtdh's comment, adding the some more info to answer directly: IBus plugin in Xfce uses by default Ctrl+Space shortcut for keyboard layout switching. To change it, go to: Options and change it to whatever else you prefer.

Checking if a collection is empty in Java: which is the best method?

I would use the first one. It is clear to see right away what it does. I dont think the null check is necessary here.

Using a SELECT statement within a WHERE clause

In your case scenario, Why not use GROUP BY and HAVING clause instead of JOINING table to itself. You may also use other useful function. see this link

Algorithm for Determining Tic Tac Toe Game Over

Another option: generate your table with code. Up to symmetry, there are only three ways to win: edge row, middle row, or diagonal. Take those three and spin them around every way possible:

def spin(g): return set([g, turn(g), turn(turn(g)), turn(turn(turn(g)))])
def turn(g): return tuple(tuple(g[y][x] for y in (0,1,2)) for x in (2,1,0))

X,s = 'X.'
XXX = X, X, X
sss = s, s, s

ways_to_win = (  spin((XXX, sss, sss))
               | spin((sss, XXX, sss))
               | spin(((X,s,s),
                       (s,X,s),
                       (s,s,X))))

These symmetries can have more uses in your game-playing code: if you get to a board you've already seen a rotated version of, you can just take the cached value or cached best move from that one (and unrotate it back). This is usually much faster than evaluating the game subtree.

(Flipping left and right can help the same way; it wasn't needed here because the set of rotations of the winning patterns is mirror-symmetric.)

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Reading Properties file in Java

if your config.properties is not in src/main/resource directory and it is in root directory of the project then you need to do somethinglike below :-

Properties prop = new Properties();          
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);

How to view UTF-8 Characters in VIM or Gvim

Try to reload the document using:

:e! ++enc=utf8

If that works you should maybe change the fileencodings settings in your .vimrc.

Can someone post a well formed crossdomain.xml sample?

This is what I've been using for development:

<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

This is a very liberal approach, but is fine for my application.

As others have pointed out below, beware the risks of this.

How to install plugin for Eclipse from .zip

This is the easiest way that I found to install a plugin locally at eclipse -

enter image description here

Save PHP array to MySQL?

You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html
I think this is the best solution, and will help you maintain your code more readable by avoiding crazy functions.
I expect this is helpful for you.

How to uninstall a windows service and delete its files without rebooting

(so Windows releases it's hold on the file)

Instead, do Ctrl+Alt+Del right after the Stop of the service and kill the .exe of the service. Than, you can uninstall the service without rebooting. This happened to me in the past and it solves the part that you need to reboot.

How to set the title text color of UIButton?

set title color

btnGere.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)

How to display an IFRAME inside a jQuery UI dialog

There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:

$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});

Another would be to load the content of your external link into the dialog container using ajax.

$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});

Both works fine but depends on the external content.

Can I set background image and opacity in the same property?

Two methods:

  1. Convert to PNG and make the original image 0.2 opacity
  2. (Better method) have a <div> that is position: absolute; before #main and the same height as #main, then apply the background-image and opacity: 0.2; filter: alpha(opacity=20);.

How to find and restore a deleted file in a Git repository

If the deletion has not been committed, the command below will restore the deleted file in the working tree.

$ git checkout -- <file>

You can get a list of all the deleted files in the working tree using the command below.

$ git ls-files --deleted

If the deletion has been committed, find the commit where it happened, then recover the file from this commit.

$ git rev-list -n 1 HEAD -- <file>
$ git checkout <commit>^ -- <file>

In case you are looking for the path of the file to recover, the following command will display a summary of all deleted files.

$ git log --diff-filter=D --summary

What is the difference between join and merge in Pandas?

One of the difference is that merge is creating a new index, and join is keeping the left side index. It can have a big consequence on your later transformations if you wrongly assume that your index isn't changed with merge.

For example:

import pandas as pd

df1 = pd.DataFrame({'org_index': [101, 102, 103, 104],
                    'date': [201801, 201801, 201802, 201802],
                    'val': [1, 2, 3, 4]}, index=[101, 102, 103, 104])
df1

       date  org_index  val
101  201801        101    1
102  201801        102    2
103  201802        103    3
104  201802        104    4

-

df2 = pd.DataFrame({'date': [201801, 201802], 'dateval': ['A', 'B']}).set_index('date')
df2

       dateval
date          
201801       A
201802       B

-

df1.merge(df2, on='date')

     date  org_index  val dateval
0  201801        101    1       A
1  201801        102    2       A
2  201802        103    3       B
3  201802        104    4       B

-

df1.join(df2, on='date')
       date  org_index  val dateval
101  201801        101    1       A
102  201801        102    2       A
103  201802        103    3       B
104  201802        104    4       B

CSS/HTML: What is the correct way to make text italic?

OK, the first thing to note is that <i> has been deprecated, and shouldn't be used <i> has not been deprecated, but I still do not recommend using it—see the comments for details. This is because it goes entirely against keeping presentation in the presentation layer, which you've pointed out. Similarly, <span class="italic"> seems to break the mold too.

So now we have two real ways of doing things: <em> and <span class="footnote">. Remember that em stands for emphasis. When you wish to apply emphasis to a word, phrase or sentence, stick it in <em> tags regardless of whether you want italics or not. If you want to change the styling in some other way, use CSS: em { font-weight: bold; font-style: normal; }. Of course, you can also apply a class to the <em> tag: if you decide you want certain emphasised phrases to show up in red, give them a class and add it to the CSS:

Fancy some <em class="special">shiny</em> text?

em { font-weight: bold; font-style: normal; }
em.special { color: red; }

If you're applying italics for some other reason, go with the other method and give the section a class. That way, you can change its styling whenever you want without adjusting the HTML. In your example, footnotes should not be emphasised—in fact, they should be de-emphasised, as the point of a footnote is to show unimportant but interesting or useful information. In this case, you're much better off applying a class to the footnote and making it look like one in the presentation layer—the CSS.

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

How do I run all Python unit tests in a directory?

Because Test discovery seems to be a complete subject, there is some dedicated framework to test discovery :

More reading here : https://wiki.python.org/moin/PythonTestingToolsTaxonomy

How do I add a library project to Android Studio?

Open the build gradle module app file and add your dependency. If you download the library, just import and build as gradle.

Otherwise add repositories in side gradle module app:

repositories {
        maven { url 'http://clinker.47deg.com/nexus/content/groups/public' }
}

The first repositories will download the library for you.

And compile the downloaded library:

 compile ('com.fortysevendeg.swipelistview:swipelistview:1.0-SNAPSHOT@aar') {
        transitive = true
    }

If you are creating a library, you just need to import the project as import new module.

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Instead of using urllib.request.urlopen() remove request for python 2.

urllib.urlopen() you do not have to request in python 2.x for what you are trying to do. Hope it works for you. This was tested using python 2.7 I was receiving the same error message and this resolved it.

Fastest way to convert a dict's keys & values from `unicode` to `str`?

I know I'm late on this one:

def convert_keys_to_string(dictionary):
    """Recursively converts dictionary keys to strings."""
    if not isinstance(dictionary, dict):
        return dictionary
    return dict((str(k), convert_keys_to_string(v)) 
        for k, v in dictionary.items())

Android: How to enable/disable option menu item on button click?

  @Override
        public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {

                case R.id.item_id:

                       //Your Code....

                        item.setEnabled(false);
                        break;
              }
            return super.onOptionsItemSelected(item);
     }

If "0" then leave the cell blank

An accrual ledger should note zeroes, even if that is the hyphen displayed with an Accounting style number format. However, if you want to leave the line blank when there are no values to calculate use a formula like the following,

 =IF(COUNT(F16:G16), SUM(G16, INDEX(H$1:H15, MATCH(1e99, H$1:H15)), -F16), "")

That formula is a little tricky because you seem to have provided your sample formula from somewhere down into the entries of the ledger's item rows without showing any layout or sample data. The formula I provided should be able to be put into H16 and then copied or filled to other locations in column H but I offer no guarantees without seeing the layout.

If you post some sample data or a publicly available link to a screenshot showing your data layout more specific assistance could be offered. http://imgur.com/ is a good place to host a screenshot and it is likely that someone with more reputation will insert the image into your question for you.

How to get longitude and latitude of any address?

I came up with the following which takes account of rubbish passed in and file_get_contents failing....

function get_lonlat(  $addr  ) {
    try {
            $coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
            $e=json_decode($coordinates);
            // call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
            if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
            // $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
            if ( $coordinates == false   ||  $err_res ==  true  ) {
                $a = array( 'lat'=>0,'lng'=>0);
                $coordinates  = new stdClass();
                foreach (  $a  as $key => $value)
                {
                    $coordinates->$key = $value;
                }
            } else {
                // call to google ok so just return longitude/latitude.
                $coordinates = $e;

                $coordinates  =  $coordinates->results[0]->geometry->location;
            }

            return $coordinates;
    }
    catch (Exception $e) {
    }

then to get the cords: where $pc is the postcode or address.... $address = get_lonlat( $pc ); $l1 = $address->lat; $l2 = $address->lng;

How do I convert array of Objects into one Object in JavaScript?

You can use the mapKeys lodash function for that. Just one line of code!

Please refer to this complete code sample (copy paste this into repl.it or similar):

import _ from 'lodash';
// or commonjs:
// const _ = require('lodash');

let a = [{ id: 23, title: 'meat' }, { id: 45, title: 'fish' }, { id: 71, title: 'fruit' }]
let b = _.mapKeys(a, 'id');
console.log(b);
// b:
// { '23': { id: 23, title: 'meat' },
//   '45': { id: 45, title: 'fish' },
//   '71': { id: 71, title: 'fruit' } }

Do HttpClient and HttpClientHandler have to be disposed between requests?

The general consensus is that you do not (should not) need to dispose of HttpClient.

Many people who are intimately involved in the way it works have stated this.

See Darrel Miller's blog post and a related SO post: HttpClient crawling results in memory leak for reference.

I'd also strongly suggest that you read the HttpClient chapter from Designing Evolvable Web APIs with ASP.NET for context on what is going on under the hood, particularly the "Lifecycle" section quoted here:

Although HttpClient does indirectly implement the IDisposable interface, the standard usage of HttpClient is not to dispose of it after every request. The HttpClient object is intended to live for as long as your application needs to make HTTP requests. Having an object exist across multiple requests enables a place for setting DefaultRequestHeaders and prevents you from having to re-specify things like CredentialCache and CookieContainer on every request as was necessary with HttpWebRequest.

Or even open up DotPeek.

How to customize a Spinner in Android

I have build a small demo project on this you could have a look to it Link to project

How to change Android version and code version number?

Go in the build.gradle and set the version code and name inside the defaultConfig element

defaultConfig {
    minSdkVersion 9
    targetSdkVersion 19
    versionCode 1
    versionName "1.0"
}

screenshot

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).


On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

Convert row to column header for Pandas DataFrame,

It would be easier to recreate the data frame. This would also interpret the columns types from scratch.

headers = df.iloc[0]
new_df  = pd.DataFrame(df.values[1:], columns=headers)

ArrayList or List declaration in Java

Basically it allows Java to store several types of objects in one structure implementation, by generic type declaration (like class MyStructure<T extends TT>), which is one of Javas main features.

Object-oriented approaches are based in modularity and reusability by separation of concerns - the ability to use a structure with any kind of types of object (as long as it obeys a few rules).

You could just instantiate things as followed:

ArrayList list = new ArrayList();

instead of

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

By declaring and using generic types you are informing a structure of the kind of objects it will manage and the compiler will be able to inform you if you're inserting an illegal type into that structure, for instance. Let's say:

// this works
List list1 = new ArrayList();
list1.add(1);
list1.add("one");

// does not work
List<String> list2 = new ArrayList<>();
list2.add(1); // compiler error here
list2.add("one");

If you want to see some examples check the documentation documentation:

/**
 * Generic version of the Box class.
 * @param <T> the type of the value being boxed
 */
public class Box<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Then you could instantiate things like:

class Paper  { ... }
class Tissue { ... }

// ...
Box<Paper> boxOfPaper = new Box<>();
boxOfPaper.set(new Paper(...));

Box<Tissue> boxOfTissues = new Box<>();
boxOfTissues.set(new Tissue(...));

The main thing to draw from this is you're specifying which type of object you want to box.

As for using Object l = new ArrayList<>();, you're not accessing the List or ArrayList implementation so you won't be able to do much with the collection.

How to hide TabPage from TabControl

Visiblity property has not been implemented on the Tabpages, and there is no Insert method also.

You need to manually insert and remove tab pages.

Here is a work around for the same.

http://www.dotnetspider.com/resources/18344-Hiding-Showing-Tabpages-Tabcontrol.aspx

Maven command to determine which settings.xml file Maven is using

Your comment to cletus' (correct) answer implies that there are multiple Maven settings files involved.

Maven always uses either one or two settings files. The global settings defined in (${M2_HOME}/conf/settings.xml) is always required. The user settings file (defined in ${user.home}/.m2/settings.xml) is optional. Any settings defined in the user settings take precedence over the corresponding global settings.

You can override the location of the global and user settings from the command line, the following example will set the global settings to c:\global\settings.xml and the user settings to c:\user\settings.xml:

mvn install --settings c:\user\settings.xml 
    --global-settings c:\global\settings.xml

Currently there is no property or means to establish what user and global settings files were used from with Maven. To access these values, you would have to modify MavenCli and/or DefaultMavenSettingsBuilder to inject the file locations into the resolved Settings object.

Javascript array value is undefined ... how do I test for that

There are more (many) ways to Rome:

//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null

cheers!

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

how to get domain name from URL

Extracting the Domain name accurately can be quite tricky mainly because the domain extension can contain 2 parts (like .com.au or .co.uk) and the subdomain (the prefix) may or may not be there. Listing all domain extensions is not an option because there are hundreds of these. EuroDNS.com for example lists over 800 domain name extensions.

I therefore wrote a short php function that uses 'parse_url()' and some observations about domain extensions to accurately extract the url components AND the domain name. The function is as follows:

function parse_url_all($url){
    $url = substr($url,0,4)=='http'? $url: 'http://'.$url;
    $d = parse_url($url);
    $tmp = explode('.',$d['host']);
    $n = count($tmp);
    if ($n>=2){
        if ($n==4 || ($n==3 && strlen($tmp[($n-2)])<=3)){
            $d['domain'] = $tmp[($n-3)].".".$tmp[($n-2)].".".$tmp[($n-1)];
            $d['domainX'] = $tmp[($n-3)];
        } else {
            $d['domain'] = $tmp[($n-2)].".".$tmp[($n-1)];
            $d['domainX'] = $tmp[($n-2)];
        }
    }
    return $d;
}

This simple function will work in almost every case. There are a few exceptions, but these are very rare.

To demonstrate / test this function you can use the following:

$urls = array('www.test.com', 'test.com', 'cp.test.com' .....);
echo "<div style='overflow-x:auto;'>";
echo "<table>";
echo "<tr><th>URL</th><th>Host</th><th>Domain</th><th>Domain X</th></tr>";
foreach ($urls as $url) {
    $info = parse_url_all($url);
    echo "<tr><td>".$url."</td><td>".$info['host'].
    "</td><td>".$info['domain']."</td><td>".$info['domainX']."</td></tr>";
}
echo "</table></div>";

The output will be as follows for the URL's listed:

enter image description here

As you can see, the domain name and the domain name without the extension are consistently extracted whatever the URL that is presented to the function.

I hope that this helps.

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How to kill a process in MacOS?

I recently faced similar issue where the atom editor will not close. Neither was responding. Kill / kill -9 / force exit from Activity Monitor - didn't work. Finally had to restart my mac to close the app.

How to do a LIKE query with linq?

You can use contains:

string[] example = { "sample1", "sample2" };
var result = (from c in example where c.Contains("2") select c);
// returns only sample2

Make one div visible and another invisible

I don't think that you really want an iframe, do you?

Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?

For your white box / extra space issue, try

style="display: none;"

instead of

style="visibility: hidden;"

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

Delete specific line from a text file?

No rocket scien code require .Hope this simple and short code will help.

List linesList = File.ReadAllLines("myFile.txt").ToList();            
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());

OR use this

public void DeleteLinesFromFile(string strLineToDelete)
    {
        string strFilePath = "Provide the path of the text file";
        string strSearchText = strLineToDelete;
        string strOldText;
        string n = "";
        StreamReader sr = File.OpenText(strFilePath);
        while ((strOldText = sr.ReadLine()) != null)
        {
            if (!strOldText.Contains(strSearchText))
            {
                n += strOldText + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(strFilePath, n);
    }

jquery get all input from specific form

The below code helps to get the details of elements from the specific form with the form id,

$('#formId input, #formId select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements from all the forms which are place in the loading page,

$('form input, form select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,

$('input, select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

NOTE: We add the more element tag name what we need in the object list like as below,

Example: to get name of attribute "textarea",

$('input, select, textarea').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

get the latest fragment in backstack

You can use the getName() method of FragmentManager.BackStackEntry which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag).

int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);

You need to make sure that you added the fragment to the backstack like this:

fragmentTransaction.addToBackStack(tag);

Set width of a "Position: fixed" div relative to parent div

Here is a little hack that we ran across while fixing some redraw issues on a large app.

Use -webkit-transform: translateZ(0); on the parent. Of course this is specific to Chrome.

http://jsfiddle.net/senica/bCQEa/

-webkit-transform: translateZ(0);

Button Listener for button in fragment in android

Use your code

public class FragmentOne extends Fragment implements OnClickListener{

    View view;
    Fragment fragmentTwo;
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container, false);
        Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
        buttonSayHi.setOnClickListener(this);
        return view;
    }

But I think is better handle the buttons in this way:

@Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.buttonSayHi:
            /** Do things you need to..
               fragmentTwo = new FragmentTwo();

               fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
               fragmentTransaction.addToBackStack(null);

               fragmentTransaction.commit();  
            */
            break;
        }   
    }

How can I get the baseurl of site?

Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)

String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) 
+ Configuration.VirtualPathRoot;

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

I am also facing the same problem and finally, I got the solution...

  1. Open MySQL Installer.
  2. After that you see the Reconfigure option in the front of the MySQL Server. Click on it.
  3. After that you have to click on the Next buttons without changing any default settings.

How can I conditionally import an ES6 module?

obscuring it in an eval worked for me, hiding it from the static analyzer ...

if (typeof __CLI__ !== 'undefined') {
  eval("require('fs');")
}

Switch statement fallthrough in C#?

Switch fallthrough is historically one of the major source of bugs in modern softwares. The language designer decided to make it mandatory to jump at the end of the case, unless you are defaulting to the next case directly without processing.

switch(value)
{
    case 1:// this is still legal
    case 2:
}

python - checking odd/even numbers and changing outputs on number size

there are a lot of ways to check if an int value is odd or even. I'll show you the two main ways:

number = 5

def best_way(number):
    if number%2==0:
        print "even"
    else:
        print "odd"

def binary_way(number):
    if str(bin(number))[len(bin(number))-1]=='0':
        print "even"
    else:
        print "odd"
best_way(number)
binary_way(number)

hope it helps

Please initialize the log4j system properly. While running web service

If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.

static Logger log = Logger.getLogger(MyClass.class);

Thanks,

cursor.fetchall() vs list(cursor) in Python

list(cursor) works because a cursor is an iterable; you can also use cursor in a loop:

for row in cursor:
    # ...

A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall() has to return the full list instead.

There is little point in using list(cursor) over cursor.fetchall(); the end effect is then indeed the same, but you wasted an opportunity to stream results instead.

Replace words in a string - Ruby

First, you don't declare the type in Ruby, so you don't need the first string.

To replace a word in string, you do: sentence.gsub(/match/, "replacement").

Detect when a window is resized using JavaScript ?

If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:

Super Super compact

var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }

All 3 possible combinations together (ES6)

var t
window.onresize = () => {
    resizing(this, this.innerWidth, this.innerHeight) //1
    if (typeof t == 'undefined') resStarted() //2
    clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}

function resizing(target, w, h) {
    console.log(`Youre resizing: width ${w} height ${h}`)
}    
function resStarted() { 
    console.log('Resize Started') 
}
function resEnded() { 
    console.log('Resize Ended') 
}

preg_match(); - Unknown modifier '+'

Try this code:

preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);
print_r($match);

Using / as a delimiter means you also need to escape it here, like so: <\/a>.

UPDATE

preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);
echo'['.$match[1].']';

Might not be the best way...

What are all the differences between src and data-src attributes?

The first <img /> is invalid - src is a required attribute. data-src is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.

How to download a folder from github?

You can download the complete folder under Clone or Download options (Git URL or Download Zip)

  1. There is a button of Download Zip

  2. By using command you can download the complete folder on your machine but for that you need git on your machine. You can find the Git url uner

    git clone https://github.com/url

What do numbers using 0x notation mean?

It's a hexadecimal number.

0x6400 translates to 4*16^2 + 6*16^3 = 25600

Copy tables from one database to another in SQL Server

On SQL Server? and on the same database server? Use three part naming.

INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar

This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.

How to give color to each class in scatter plot in R?

Here is how I do it in 2018. Who knows, maybe an R newbie will see it one day and fall in love with ggplot2.

library(ggplot2)

ggplot(data = iris, aes(Petal.Length, Petal.Width, color = Species)) +
  geom_point() +
  scale_color_manual(values = c("setosa" = "red", "versicolor" = "blue", "virginica" = "yellow"))

Add item to array in VBScript

Slight change to the FastArray from above:

'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """" 

t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
 If i>ub Then 
    ReDim Preserve a(Int((ub+10)*1.1))
    ub = UBound(a)
 End If
 a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"

MsgBox s

There is no point in checking UBound(a) in every cycle of the for if we know exactly when it changes.

I've changed it so that it checks does UBound(a) just before the for starts and then only every time the ReDim is called

On my computer the old method took 7.52 seconds for an imax of 10 millions.

The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)

What do parentheses surrounding an object/function/class declaration mean?

The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.

As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

Modifying a query string without reloading the page

Then the history API is exactly what you are looking for. If you wish to support legacy browsers as well, then look for a library that falls back on manipulating the URL's hash tag if the browser doesn't provide the history API.

BigDecimal equals() versus compareTo()

The answer is in the JavaDoc of the equals() method:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

In other words: equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.

As to why equals() behaves this way, this has been answered in this SO question.

Include an SVG (hosted on GitHub) in MarkDown

The purpose of raw.github.com is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.

When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.

Examples

All of the ways stated below will work.

I copied the SVG image from the question to a repo on github in order to create the examples below

Linking to files using relative paths (Works, but obviously only on github.com / github.io)

Code

![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">

Result

See the working example on github.com.

Linking to RAW files

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text

Linking to RAW files using ?sanitize=true

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">

Result

Alt text

Linking to files hosted on github.io

Code

![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text


Some comments regarding changes that happened along the way:

  • Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>) are removed.

    To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true to the SVG's raw URL.

  • As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.

  • The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017

Iterate through <select> options

$.each($("#MySelect option"), function(){
                    alert($(this).text() + " - " + $(this).val());                    
                });

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    img.remove();
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    img.remove();
    newImg.attr('id', old_id);
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

$("#resetlink").click(function(){
    clearInterval(timerRocket);
    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.
});

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()
};

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    img.css(orig).hide();
    (callback || function() {})();
});

New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

Get property value from C# dynamic object by string (reflection?)

string json = w.JSON;

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

DynamicJsonConverter.DynamicJsonObject obj = 
      (DynamicJsonConverter.DynamicJsonObject)serializer.Deserialize(json, typeof(object));

Now obj._Dictionary contains a dictionary. Perfect!

This code must be used in conjunction with Deserialize JSON into C# dynamic object? + make the _dictionary variable from "private readonly" to public in the code there

Lightbox to show videos from Youtube and Vimeo?

Check out Fancybox. If you need the video to autoplay this example site was helpful!

CSS transition when class removed

In my case i had some problem with opacity transition so this one fix it:

#dropdown {
    transition:.6s opacity;
}
#dropdown.ns {
    opacity:0;
    transition:.6s all;
}
#dropdown.fade {
    opacity:1;
}

Mouse Enter

$('#dropdown').removeClass('ns').addClass('fade');

Mouse Leave

$('#dropdown').addClass('ns').removeClass('fade');

Counting the number of files in a directory using Java

If you have directories containing really (>100'000) many files, here is a (non-portable) way to go:

String directoryPath = "a path";

// -f flag is important, because this way ls does not sort it output,
// which is way faster
String[] params = { "/bin/sh", "-c",
    "ls -f " + directoryPath + " | wc -l" };
Process process = Runtime.getRuntime().exec(params);
BufferedReader reader = new BufferedReader(new InputStreamReader(
    process.getInputStream()));
String fileCount = reader.readLine().trim() - 2; // accounting for .. and .
reader.close();
System.out.println(fileCount);

How do I compile C++ with Clang?

Also, for posterity -- Clang (like GCC) accepts the -x switch to set the language of the input files, for example,

$ clang -x c++ some_random_file.txt

This mailing list thread explains the difference between clang and clang++ well: Difference between clang and clang++

python, sort descending dataframe with pandas

from pandas import DataFrame
import pandas as pd

d = {'one':[2,3,1,4,5],
 'two':[5,4,3,2,1],
 'letter':['a','a','b','b','c']}

df = DataFrame(d)

test = df.sort_values(['one'], ascending=False)
test

How to generate java classes from WSDL file

I have quite complex WCF web service and I've tried a few different tools, but in most cases I couldn't connect to my web service. Finally I've used this one:

http://easywsdl.com/

This is only one tool which generetes classes that works without ANY changes!

No connection could be made because the target machine actively refused it 127.0.0.1:3446

With similar pattern, my rest client is calling the service API, the service called successfully when debugging, but not working on the published code. Error was: Unable to connect to the remote server.

Inner Exception: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it serviceIP:443 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

Resolution: Set the proxy in Web config.

<system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="http://proxy_ip:portno/" usesystemdefault="True"/>
    </defaultProxy>
</system.net>

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99