Programs & Examples On #Sqlalchemy

SQLAlchemy is a Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

Flask SQLAlchemy query, specify column names

session.query().with_entities(SomeModel.col1)

is the same as

session.query(SomeModel.col1)

for alias, we can use .label()

session.query(SomeModel.col1.label('some alias name'))

Convert sqlalchemy row object to python dict

As per @zzzeek in comments:

note that this is the correct answer for modern versions of SQLAlchemy, assuming "row" is a core row object, not an ORM-mapped instance.

for row in resultproxy:
    row_as_dict = dict(row)

sqlalchemy: how to join several tables by one query?

As @letitbee said, its best practice to assign primary keys to tables and properly define the relationships to allow for proper ORM querying. That being said...

If you're interested in writing a query along the lines of:

SELECT
    user.email,
    user.name,
    document.name,
    documents_permissions.readAllowed,
    documents_permissions.writeAllowed
FROM
    user, document, documents_permissions
WHERE
    user.email = "[email protected]";

Then you should go for something like:

session.query(
    User, 
    Document, 
    DocumentsPermissions
).filter(
    User.email == Document.author
).filter(
    Document.name == DocumentsPermissions.document
).filter(
    User.email == "[email protected]"
).all()

If instead, you want to do something like:

SELECT 'all the columns'
FROM user
JOIN document ON document.author_id = user.id AND document.author == User.email
JOIN document_permissions ON document_permissions.document_id = document.id AND document_permissions.document = document.name

Then you should do something along the lines of:

session.query(
    User
).join(
    Document
).join(
    DocumentsPermissions
).filter(
    User.email == "[email protected]"
).all()

One note about that...

query.join(Address, User.id==Address.user_id) # explicit condition
query.join(User.addresses)                    # specify relationship from left to right
query.join(Address, User.addresses)           # same, with explicit target
query.join('addresses')                       # same, using a string

For more information, visit the docs.

SQLAlchemy ORDER BY DESCENDING?

You can use .desc() function in your query just like this

query = (model.Session.query(model.Entry)
        .join(model.ClassificationItem)
        .join(model.EnumerationValue)
        .filter_by(id=c.row.id)
        .order_by(model.Entry.amount.desc())
        )

This will order by amount in descending order or

query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    model.Entry.amount.desc()
)
)

Use of desc function of SQLAlchemy

from sqlalchemy import desc
query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    desc(model.Entry.amount)
)
)

For official docs please use the link or check below snippet

sqlalchemy.sql.expression.desc(column) Produce a descending ORDER BY clause element.

e.g.:

from sqlalchemy import desc

stmt = select([users_table]).order_by(desc(users_table.c.name))

will produce SQL as:

SELECT id, name FROM user ORDER BY name DESC

The desc() function is a standalone version of the ColumnElement.desc() method available on all SQL expressions, e.g.:

stmt = select([users_table]).order_by(users_table.c.name.desc())

Parameters column – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation.

See also

asc()

nullsfirst()

nullslast()

Select.order_by()

How to install mysql-connector via pip

To install the official MySQL Connector for Python, please use the name mysql-connector-python:

pip install mysql-connector-python

Some further discussion, when we pip search for mysql-connector at this time (Nov, 2018), the most related results shown as follow:

$ pip search mysql-connector | grep ^mysql-connector
mysql-connector (2.1.6)                  - MySQL driver written in Python
mysql-connector-python (8.0.13)          - MySQL driver written in Python
mysql-connector-repackaged (0.3.1)       - MySQL driver written in Python
mysql-connector-async-dd (2.0.2)         - mysql async connection
mysql-connector-python-rf (2.2.2)        - MySQL driver written in Python
mysql-connector-python-dd (2.0.2)        - MySQL driver written in Python
  • mysql-connector (2.1.6) is provided on PyPI when MySQL didn't provide their official pip install on PyPI at beginning (which was inconvenient). But it is a fork, and is stopped updating, so

    pip install mysql-connector
    

    will install this obsolete version.

  • And now mysql-connector-python (8.0.13) on PyPI is the official package maintained by MySQL, so this is the one we should install.

ImportError: No module named MySQLdb

Got so many errors related to permissions and what not. You may wanna try this :

xcode-select --install

SQLAlchemy: print the actual query

So building on @zzzeek's comments on @bukzor's code I came up with this to easily get a "pretty-printable" query:

def prettyprintable(statement, dialect=None, reindent=True):
    """Generate an SQL expression string with bound parameters rendered inline
    for the given SQLAlchemy statement. The function can also receive a
    `sqlalchemy.orm.Query` object instead of statement.
    can 

    WARNING: Should only be used for debugging. Inlining parameters is not
             safe when handling user created data.
    """
    import sqlparse
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        if dialect is None:
            dialect = statement.session.get_bind().dialect
        statement = statement.statement
    compiled = statement.compile(dialect=dialect,
                                 compile_kwargs={'literal_binds': True})
    return sqlparse.format(str(compiled), reindent=reindent)

I personally have a hard time reading code which is not indented so I've used sqlparse to reindent the SQL. It can be installed with pip install sqlparse.

How to serialize SqlAlchemy result to JSON?

Even though it's a old post, Maybe I didn't answer the question above, but I want to talk about my serialization, at least it works for me.

I use FastAPI,SqlAlchemy and MySQL, but I don't use orm model;

# from sqlalchemy import create_engine
# from sqlalchemy.orm import sessionmaker
# engine = create_engine(config.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Serialization code



import decimal
import datetime


def alchemy_encoder(obj):
    """JSON encoder function for SQLAlchemy special classes."""
    if isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    elif isinstance(obj, decimal.Decimal):
        return float(obj)

import json
from sqlalchemy import text

# db is SessionLocal() object 

app_sql = 'SELECT * FROM app_info ORDER BY app_id LIMIT :page,:page_size'

# The next two are the parameters passed in
page = 1
page_size = 10

# execute sql and return a <class 'sqlalchemy.engine.result.ResultProxy'> object
app_list = db.execute(text(app_sql), {'page': page, 'page_size': page_size})

# serialize
res = json.loads(json.dumps([dict(r) for r in app_list], default=alchemy_encoder))

If it doesn't work, please ignore my answer. I refer to it here

https://codeandlife.com/2014/12/07/sqlalchemy-results-to-json-the-easy-way/

jsonify a SQLAlchemy result set in Flask

Ok, I've been working on this for a few hours, and I've developed what I believe to be the most pythonic solution yet. The following code snippets are python3 but shouldn't be too horribly painful to backport if you need.

The first thing we're gonna do is start with a mixin that makes your db models act kinda like dicts:

from sqlalchemy.inspection import inspect

class ModelMixin:
    """Provide dict-like interface to db.Model subclasses."""

    def __getitem__(self, key):
        """Expose object attributes like dict values."""
        return getattr(self, key)

    def keys(self):
        """Identify what db columns we have."""
        return inspect(self).attrs.keys()

Now we're going to define our model, inheriting the mixin:

class MyModel(db.Model, ModelMixin):
    id = db.Column(db.Integer, primary_key=True)
    foo = db.Column(...)
    bar = db.Column(...)
    # etc ...

That's all it takes to be able to pass an instance of MyModel() to dict() and get a real live dict instance out of it, which gets us quite a long way towards making jsonify() understand it. Next, we need to extend JSONEncoder to get us the rest of the way:

from flask.json import JSONEncoder
from contextlib import suppress

class MyJSONEncoder(JSONEncoder):
    def default(self, obj):
        # Optional: convert datetime objects to ISO format
        with suppress(AttributeError):
            return obj.isoformat()
        return dict(obj)

app.json_encoder = MyJSONEncoder

Bonus points: if your model contains computed fields (that is, you want your JSON output to contain fields that aren't actually stored in the database), that's easy too. Just define your computed fields as @propertys, and extend the keys() method like so:

class MyModel(db.Model, ModelMixin):
    id = db.Column(db.Integer, primary_key=True)
    foo = db.Column(...)
    bar = db.Column(...)

    @property
    def computed_field(self):
        return 'this value did not come from the db'

    def keys(self):
        return super().keys() + ['computed_field']

Now it's trivial to jsonify:

@app.route('/whatever', methods=['GET'])
def whatever():
    return jsonify(dict(results=MyModel.query.all()))

How to update SQLAlchemy row entry?

user.no_of_logins += 1
session.commit()

SQLAlchemy: how to filter date field?

if you want to get the whole period:

    from sqlalchemy import and_, func

    query = DBSession.query(User).filter(and_(func.date(User.birthday) >= '1985-01-17'),\
                                              func.date(User.birthday) <= '1988-01-17'))

That means range: 1985-01-17 00:00 - 1988-01-17 23:59

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

ImportError: No module named sqlalchemy

Okay,I have re-installed the package via pip even that didn't help. And then I rsync'ed the entire /usr/lib/python-2.7 directory from other working machine with similar configuration to the current machine.It started working. I don't have any idea ,what was wrong with my setup. I see some difference "print sys.path" output earlier and now. but now my issue is resolved by this work around.

EDIT:Found the real solution for my setup. upgrading "sqlalchemy only doesn't solve the issue" I also need to upgrade flask-sqlalchemy that resolved the issue.

sqlalchemy IS NOT NULL select

Starting in version 0.7.9 you can use the filter operator .isnot instead of comparing constraints, like this:

query.filter(User.name.isnot(None))

This method is only necessary if pep8 is a concern.

source: sqlalchemy documentation

Bulk insert with SQLAlchemy ORM

Piere's answer is correct but one issue is that bulk_save_objects by default does not return the primary keys of the objects, if that is of concern to you. Set return_defaults to True to get this behavior.

The documentation is here.

foos = [Foo(bar='a',), Foo(bar='b'), Foo(bar='c')]
session.bulk_save_objects(foos, return_defaults=True)
for foo in foos:
    assert foo.id is not None
session.commit()

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:

http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

The code would look something like this (to count user objects):

from sqlalchemy import func

session.query(func.count(User.id)).scalar() 

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

SQLAlchemy default DateTime

You can also use sqlalchemy builtin function for default DateTime

from sqlalchemy.sql import func

DT = Column(DateTime(timezone=True), default=func.now())

SQLAlchemy: What's the difference between flush() and commit()?

Why flush if you can commit?

As someone new to working with databases and sqlalchemy, the previous answers - that flush() sends SQL statements to the DB and commit() persists them - were not clear to me. The definitions make sense but it isn't immediately clear from the definitions why you would use a flush instead of just committing.

Since a commit always flushes (https://docs.sqlalchemy.org/en/13/orm/session_basics.html#committing) these sound really similar. I think the big issue to highlight is that a flush is not permanent and can be undone, whereas a commit is permanent, in the sense that you can't ask the database to undo the last commit (I think)

@snapshoe highlights that if you want to query the database and get results that include newly added objects, you need to have flushed first (or committed, which will flush for you). Perhaps this is useful for some people although I'm not sure why you would want to flush rather than commit (other than the trivial answer that it can be undone).

In another example I was syncing documents between a local DB and a remote server, and if the user decided to cancel, all adds/updates/deletes should be undone (i.e. no partial sync, only a full sync). When updating a single document I've decided to simply delete the old row and add the updated version from the remote server. It turns out that due to the way sqlalchemy is written, order of operations when committing is not guaranteed. This resulted in adding a duplicate version (before attempting to delete the old one), which resulted in the DB failing a unique constraint. To get around this I used flush() so that order was maintained, but I could still undo if later the sync process failed.

See my post on this at: Is there any order for add versus delete when committing in sqlalchemy

Similarly, someone wanted to know whether add order is maintained when committing, i.e. if I add object1 then add object2, does object1 get added to the database before object2 Does SQLAlchemy save order when adding objects to session?

Again, here presumably the use of a flush() would ensure the desired behavior. So in summary, one use for flush is to provide order guarantees (I think), again while still allowing yourself an "undo" option that commit does not provide.

Autoflush and Autocommit

Note, autoflush can be used to ensure queries act on an updated database as sqlalchemy will flush before executing the query. https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autoflush

Autocommit is something else that I don't completely understand but it sounds like its use is discouraged: https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autocommit

Memory Usage

Now the original question actually wanted to know about the impact of flush vs. commit for memory purposes. As the ability to persist or not is something the database offers (I think), simply flushing should be sufficient to offload to the database - although committing shouldn't hurt (actually probably helps - see below) if you don't care about undoing.

sqlalchemy uses weak referencing for objects that have been flushed: https://docs.sqlalchemy.org/en/13/orm/session_state_management.html#session-referencing-behavior

This means if you don't have an object explicitly held onto somewhere, like in a list or dict, sqlalchemy won't keep it in memory.

However, then you have the database side of things to worry about. Presumably flushing without committing comes with some memory penalty to maintain the transaction. Again, I'm new to this but here's a link that seems to suggest exactly this: https://stackoverflow.com/a/15305650/764365

In other words, commits should reduce memory usage, although presumably there is a trade-off between memory and performance here. In other words, you probably don't want to commit every single database change, one at a time (for performance reasons), but waiting too long will increase memory usage.

SQLAlchemy equivalent to SQL "LIKE" statement

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

For more info go Common Filter Operators

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Flask-SQLalchemy update a row's information

This does not work if you modify a pickled attribute of the model. Pickled attributes should be replaced in order to trigger updates:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from pprint import pprint

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:////tmp/users.db'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    data = db.Column(db.PickleType())

    def __init__(self, name, data):
        self.name = name
        self.data = data

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()

# Create a user.
bob = User('Bob', {})
db.session.add(bob)
db.session.commit()

# Retrieve the row by its name.
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Modifying data is ignored.
bob.data['foo'] = 123
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Replacing data is respected.
bob.data = {'bar': 321}
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

# Modifying data is ignored.
bob.data['moo'] = 789
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

SQLAlchemy create_all() does not create tables

This is probably not the main reason why the create_all() method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

def get_db():
  if 'db' not in g:
    g.db = SQLAlchemy(current_app)
  return g.db

I also have a separate cli command that also does the create_all:

# tasks/db.py
from lib.db import get_db

@current_app.cli.command('init-db')
def init_db():
  db = get_db()
  db.create_all()

I also am using a application factory.

When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).

The fix that I came around to was to make sure that the db was a single global reference:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

db = None
def get_db():
  global db
  if not db:
    db = SQLAlchemy(current_app)
  return db

I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

How to execute raw SQL in Flask-SQLAlchemy app

docs: SQL Expression Language Tutorial - Using Text

example:

from sqlalchemy.sql import text

connection = engine.connect()

# recommended
cmd = 'select * from Employees where EmployeeGroup = :group'
employeeGroup = 'Staff'
employees = connection.execute(text(cmd), group = employeeGroup)

# or - wee more difficult to interpret the command
employeeGroup = 'Staff'
employees = connection.execute(
                  text('select * from Employees where EmployeeGroup = :group'), 
                  group = employeeGroup)

# or - notice the requirement to quote 'Staff'
employees = connection.execute(
                  text("select * from Employees where EmployeeGroup = 'Staff'"))


for employee in employees: logger.debug(employee)
# output
(0, 'Tim', 'Gurra', 'Staff', '991-509-9284')
(1, 'Jim', 'Carey', 'Staff', '832-252-1910')
(2, 'Lee', 'Asher', 'Staff', '897-747-1564')
(3, 'Ben', 'Hayes', 'Staff', '584-255-2631')

Flask-SQLAlchemy how to delete all rows in a single table

Flask-Sqlalchemy

Delete All Records

#for all records
db.session.query(Model).delete()
db.session.commit()

Deleted Single Row

here DB is the object Flask-SQLAlchemy class. It will delete all records from it and if you want to delete specific records then try filter clause in the query. ex.

#for specific value
db.session.query(Model).filter(Model.id==123).delete()
db.session.commit()

Delete Single Record by Object

record_obj = db.session.query(Model).filter(Model.id==123).first()
db.session.delete(record_obj)
db.session.commit()

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records

SQLAlchemy insert or update example

I try lots of ways and finally try this:

def db_persist(func):
    def persist(*args, **kwargs):
        func(*args, **kwargs)
        try:
            session.commit()
            logger.info("success calling db func: " + func.__name__)
            return True
        except SQLAlchemyError as e:
            logger.error(e.args)
            session.rollback()
            return False

    return persist

and :

@db_persist
def insert_or_update(table_object):
    return session.merge(table_object)

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

How to delete a record by id in Flask-SQLAlchemy

You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.

How to write DataFrame to postgres table?

For Python 2.7 and Pandas 0.24.2 and using Psycopg2

Psycopg2 Connection Module

def dbConnect (db_parm, username_parm, host_parm, pw_parm):
    # Parse in connection information
    credentials = {'host': host_parm, 'database': db_parm, 'user': username_parm, 'password': pw_parm}
    conn = psycopg2.connect(**credentials)
    conn.autocommit = True  # auto-commit each entry to the database
    conn.cursor_factory = RealDictCursor
    cur = conn.cursor()
    print ("Connected Successfully to DB: " + str(db_parm) + "@" + str(host_parm))
    return conn, cur

Connect to the database

conn, cur = dbConnect(databaseName, dbUser, dbHost, dbPwd)

Assuming dataframe to be present already as df

output = io.BytesIO() # For Python3 use StringIO
df.to_csv(output, sep='\t', header=True, index=False)
output.seek(0) # Required for rewinding the String object
copy_query = "COPY mem_info FROM STDOUT csv DELIMITER '\t' NULL ''  ESCAPE '\\' HEADER "  # Replace your table name in place of mem_info
cur.copy_expert(copy_query, output)
conn.commit()

Efficiently updating database using SQLAlchemy ORM

There are several ways to UPDATE using sqlalchemy

1) for c in session.query(Stuff).all():
       c.foo += 1
   session.commit()

2) session.query().\
       update({"foo": (Stuff.foo + 1)})
   session.commit()

3) conn = engine.connect()
   stmt = Stuff.update().\
       values(Stuff.foo = (Stuff.foo + 1))
   conn.execute(stmt)

Looking for a good Python Tree data structure

You can build a nice tree of dicts of dicts like this:

import collections

def Tree():
    return collections.defaultdict(Tree)

It might not be exactly what you want but it's quite useful! Values are saved only in the leaf nodes. Here is an example of how it works:

>>> t = Tree()
>>> t
defaultdict(<function tree at 0x2142f50>, {})
>>> t[1] = "value"
>>> t[2][2] = "another value"
>>> t
defaultdict(<function tree at 0x2142f50>, {1: 'value', 2: defaultdict(<function tree at 0x2142f50>, {2: 'another value'})}) 

For more information take a look at the gist.

How to call a SOAP web service on Android

If you can use JSON, there is a whitepaper, a video and the sample.code in Developing Application Services with PHP Servers and Android Phone Clients.

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

res.sendFile absolute path

you can use send instead of sendFile so you wont face with error! this works will help you!

fs.readFile('public/index1.html',(err,data)=>{
if(err){
  consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');

for telling browser that your response is type of PDF

res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');

if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.

res.send(data)

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

MongoDB inserts float when trying to insert integer

A slightly simpler syntax (in Robomongo at least) worked for me:

db.database.save({ Year : NumberInt(2015) });

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

How to convert a String into an ArrayList?

If you're using guava (and you should be, see effective java item #15):

ImmutableList<String> list = ImmutableList.copyOf(s.split(","));

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

For me the issue had to do with the parameters assigned to the package.

 In SSMS, Navigate to:
 "Integration Services Catalog -> SSISDB -> Project Folder Name -> Projects -> Project Name" 

Make sure you right click on your "Project Name" and then validate that 32-bit runtime is set correctly and that the parameters that are used by default are instantiated properly. Check parameter NAMES and initial values. For my package, I was using values that were not correct and so I had to repopulate the parameter defaults prior to executing my package. Check the values you are using against the defaults you have set for your parameters you have set up in your SSIS package. Once these match the issue should be resolved (for some)

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

Close Window from ViewModel

System.Environment.Exit(0); in view model would work.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Showing all session data at once?

here is code:

<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>

Comparing two input values in a form validation with AngularJS

You have to look at the bigger problem. How to write the directives that solve one problem. You should try directive use-form-error. Would it help to solve this problem, and many others.

    <form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required />
  <div use-form-error="isSame" use-error-expression="password && confirmPassword && password!=confirmPassword" ng-show="ExampleForm.$error.isSame">Passwords Do Not Match!</div>
</form>

Live example jsfiddle

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

What's the fastest algorithm for sorting a linked list?

A Radix sort is particularly suited to a linked list, since it's easy to make a table of head pointers corresponding to each possible value of a digit.

What is stability in sorting algorithms and why is it important?

A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input unsorted array. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.

However, any given sorting algo which is not stable can be modified to be stable. There can be sorting algo specific ways to make it stable, but in general, any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison operation so that the comparison of two keys considers position as a factor for objects with equal keys.

References: http://www.math.uic.edu/~leon/cs-mcs401-s08/handouts/stability.pdf http://en.wikipedia.org/wiki/Sorting_algorithm#Stability

Visual Studio Code always asking for git credentials

Last updated: 05 March, 2019

After 98 upvotes, I think I need to give a true answer with the explanation.

Why does VS code ask for a password? Because VSCode runs the auto-fetch feature, while git server doesn't have any information to authorize your identity. It happens when:

  • Your git repo has https remote url. Yes! This kind of remote will absolutely ask you every time. No exceptions here! (You can do a temporary trick to cache the authorization as the solution below, but this is not recommended.)
  • Your git repo has ssl remote url, BUT you've not copied your ssh public key onto git server. Use ssh-keygen to generate your key and copy it to git server. Done! This solution also helps you never retype password on terminal again. See a good instruction by @Fnatical here for the answer.

The updated part at the end of this answer doesn't really help you at all. (It actually makes you stagnant in your workflow.) It only stops things happening in VSCode and moves these happenings to the terminal.

Sorry if this bad answer has affected you for a long, long time.

--

the original answer (bad)

I found the solution on VSCode document:

Tip: You should set up a credential helper to avoid getting asked for credentials every time VS Code talks to your Git remotes. If you don't do this, you may want to consider Disabling Autofetch in the ... menu to reduce the number of prompts you get.

So, turn on the credential helper so that Git will save your password in memory for some time. By default, Git will cache your password for 15 minutes.

In Terminal, enter the following:

git config --global credential.helper cache
# Set git to use the credential memory cache

To change the default password cache timeout, enter the following:

git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)

UPDATE (If original answer doesn't work)

I installed VS Code and config same above, but as @ddieppa said, It didn't work for me too. So I tried to find an option in User Setting, and I saw "git.autofetch" = true, now set it's false! VS Code is no longer required to enter password repeatedly again!

In menu, click File / Preferences / User Setting And type these:

Place your settings in this file to overwrite the default settings

{
  "git.autofetch": false
}

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

What exactly does stringstream do?

You entered an alphanumeric and int, blank delimited in mystr.

You then tried to convert the first token (blank delimited) into an int.

The first token was RS which failed to convert to int, leaving a zero for myprice, and we all know what zero times anything yields.

When you only entered int values the second time, everything worked as you expected.

It was the spurious RS that caused your code to fail.

AngularJS For Loop with Numbers & Ranges

This is jzm's improved answer (i cannot comment else i would comment her/his answer because s/he included errors). The function has a start/end range value, so it's more flexible, and... it works. This particular case is for day of month:

$scope.rangeCreator = function (minVal, maxVal) {
    var arr = [];
   for (var i = minVal; i <= maxVal; i++) {
      arr.push(i);
   }
   return arr;
};


<div class="col-sm-1">
    <select ng-model="monthDays">
        <option ng-repeat="day in rangeCreator(1,31)">{{day}}</option>
    </select>
</div>

What is the best IDE for PHP?

All are good, but only Delphi for PHP (RadPHP 3.0) has a designer, drag and drop controls, GUI editeor, huge set of components including Zend Framework, Facebook, database, etc. components. It is the best in town.

RadPHP is the best of all; It has all the features the others have. Its designer is the best of all. You can design your page just like Dreamweaver (more than Dreamweaver).

If you use RadPHP you will feel like using ASP.NET with Visual Studio (but the language is PHP).

It's too bad only a few know about this.

DateTime group by date and hour

Using MySQL I usually do it that way:

SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;

Or in the same idea, if you need to output the date/hour:

SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM  your_table 
GROUP BY my_date
order by your_date_column desc;

If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

The endpoint reference (EPR) for the Operation not found is

It happens because the source WSDL in each operation has not defined the SOAPAction value.

e.g.

<soap12:operation soapAction="" style="document"/>  

His is important for axis server.

If you have created the service on netbeans or another, don't forget to set the value action on the tag @WebMethod

e.g. @WebMethod(action = "hello", operationName = "hello")

This will create the SOAPAction value by itself.

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

Npm Please try using this command again as root/administrator

I had the same problem, what I did to solve it was ran the cmd.exe as administrator even though my account was already set as an administrator.

Can angularjs routes have optional parameter values?

Actually I think OZ_ may be somewhat correct.

If you have the route '/users/:userId' and navigate to '/users/' (note the trailing /), $routeParams in your controller should be an object containing userId: "" in 1.1.5. So no the paramater userId isn't completely ignored, but I think it's the best you're going to get.

android: how to use getApplication and getApplicationContext from non activity / service class

Casting a Context object to an Activity object compiles fine.

Try this:

((Activity) mContext).getApplication(...)

Uploading Files in ASP.net without using the FileUpload server control

//create a folder in server (~/Uploads)
 //to upload
 File.Copy(@"D:\CORREO.txt", Server.MapPath("~/Uploads/CORREO.txt"));

 //to download
             Response.ContentType = ContentType;
             Response.AppendHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName("~/Uploads/CORREO.txt"));
             Response.WriteFile("~/Uploads/CORREO.txt");
             Response.End();

JavaScript calculate the day of the year (1 - 366)

If you don't want to re-invent the wheel, you can use the excellent date-fns (node.js) library:

var getDayOfYear = require('date-fns/get_day_of_year')

var dayOfYear = getDayOfYear(new Date(2017, 1, 1)) // 1st february => 32

What is an example of the Liskov Substitution Principle?

I see rectangles and squares in every answer, and how to violate the LSP.

I'd like to show how the LSP can be conformed to with a real-world example :

<?php

interface Database 
{
    public function selectQuery(string $sql): array;
}

class SQLiteDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // sqlite specific code

        return $result;
    }
}

class MySQLDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // mysql specific code

        return $result; 
    }
}

This design conforms to the LSP because the behaviour remains unchanged regardless of the implementation we choose to use.

And yes, you can violate LSP in this configuration doing one simple change like so :

<?php

interface Database 
{
    public function selectQuery(string $sql): array;
}

class SQLiteDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // sqlite specific code

        return $result;
    }
}

class MySQLDatabase implements Database
{
    public function selectQuery(string $sql): array
    {
        // mysql specific code

        return ['result' => $result]; // This violates LSP !
    }
}

Now the subtypes cannot be used the same way since they don't produce the same result anymore.

Git:nothing added to commit but untracked files present

Also instead of adding each file manually, we could do something like:

git add --all

OR

git add -A

This will also remove any files not present or deleted (Tracked files in the current working directory which are now absent).

If you only want to add files which are tracked and have changed, you would want to do

git add -u

What is the difference between git add . & git add --all?

TextView bold via xml file?

just use

android:textStyle="bold"

How can I extract a number from a string in JavaScript?

This answer will cover most of the scenario. I can across this situation when user try to copy paste the phone number

  $('#help_number').keyup(function(){
    $(this).val().match(/\d+/g).join("")
  });

Explanation:

str= "34%^gd 5-67 6-6ds"

str.match(/\d+/g)

It will give a array of string as output >> ["34", "56766"]

str.match(/\d+/g).join("")

join will convert and concatenate that array data into single string

output >> "3456766"

In my example I need the output as 209-356-6788 so I used replace

  $('#help_number').keyup(function(){
    $(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
  });

Using Node.js require vs. ES6 import/export

Not sure why (probably optimization - lazy loading?) is it working like that, but I have noticed that import may not parse code if imported modules are not used.
Which may not be expected behaviour in some cases.

Take hated Foo class as our sample dependency.

foo.ts

export default class Foo {}
console.log('Foo loaded');

For example:

index.ts

import Foo from './foo'
// prints nothing

index.ts

const Foo = require('./foo').default;
// prints "Foo loaded"

index.ts

(async () => {
    const FooPack = await import('./foo');
    // prints "Foo loaded"
})();

On the other hand:

index.ts

import Foo from './foo'
typeof Foo; // any use case
// prints "Foo loaded"

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

If you're using Radiant CMS, simply add

require 'thread'

to the top of config/boot.rb.

(Kudos to Aaron's and nathanvda's responses.)

PHP Sort a multidimensional array by element containing date

Sorting array of records/assoc_arrays by specified mysql datetime field and by order:

function build_sorter($key, $dir='ASC') {
    return function ($a, $b) use ($key, $dir) {
        $t1 = strtotime(is_array($a) ? $a[$key] : $a->$key);
        $t2 = strtotime(is_array($b) ? $b[$key] : $b->$key);
        if ($t1 == $t2) return 0;
        return (strtoupper($dir) == 'ASC' ? ($t1 < $t2) : ($t1 > $t2)) ? -1 : 1;
    };
}


// $sort - key or property name 
// $dir - ASC/DESC sort order or empty
usort($arr, build_sorter($sort, $dir));

Difference between malloc and calloc?

malloc() and calloc() are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.

Their prototypes are as follows:

void *malloc( size_t n);
void *calloc( size_t n, size_t t)

There are mainly two differences between the two:

  • Behavior: malloc() allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc(), on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.

  • Syntax: malloc() takes 1 argument (the size to be allocated), and calloc() takes two arguments (number of blocks to be allocated and size of each block).

The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.

Example:

int *arr;

// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int)); 

// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));

The same functionality as calloc() can be achieved using malloc() and memset():

// allocate memory for 10 integers with garbage values   
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int)); 

Note that malloc() is preferably used over calloc() since it's faster. If zero-initializing the values is wanted, use calloc() instead.

Inserting a Python datetime.datetime object into MySQL

For a time field, use:

import time    
time.strftime('%Y-%m-%d %H:%M:%S')

I think strftime also applies to datetime.

How to POST the data from a modal form of Bootstrap?

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action

How to delete a file after checking whether it exists

You could import the System.IO namespace using:

using System.IO;

If the filepath represents the full path to the file, you can check its existence and delete it as follows:

if(File.Exists(filepath))
{
     try
    {
         File.Delete(filepath);
    } 
    catch(Exception ex)
    {
      //Do something
    } 
}  

ASP.NET DateTime Picker

The answer to your question is that Yes there are good free/open source time picker controls that go well with ASP.NET Calendar controls.

ASP.NET calendar controls just write an HTML table.

If you are using HTML5 and .NET Framework 4.5, you can instead use an ASP.NET TextBox control and set the TextMode property to "Date", "Month", "Week", "Time", or "DateTimeLocal" -- or if you your browser doesn't support this, you can set this property to "DateTime". You can then read the Text property to get the date, or time, or month, or week as a string from the TextBox.

If you are using .NET Framework 4.0 or an older version, then you can use HTML5's <input type="[month, week, etc.]">; if your browser doesn't support this, use <input type="datetime">.

If you need the server-side code (written in either C# or Visual Basic) for the information that the user inputs in the date field, then you can try to run the element on the server by writing runat="server" inside the input tag. As with all things ASP, make sure to give this element an ID so you can access it on the server side. Now you can read the Value property to get the input date, time, month, or week as a string.

If you cannot run this element on the server, then you will need a hidden field in addition to the <input type="[date/time/month/week/etc.]". In the submit function (written in JavaScript), set the value of the hidden field to the value of the input type="date", or "time", or "month", or "week" -- then on the server-side code, read the Value property of that hidden field as string too.

Make sure that the hidden field element of the HTML can run on the server.

Python - converting a string of numbers into a list of int

number_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'

number_string = number_string.split(',')

number_string = [int(i) for i in number_string]

keyCode values for numeric keypad?

Docs says the order of events related to the onkeyxxx event:

  1. onkeydown
  2. onkeypress
  3. onkeyup

If you use like below code, it fits with also backspace and enter user interactions. After you can do what you want in onKeyPress or onKeyUp events. Code block trigger event.preventDefault function if the value is not number,backspace or enter.

onInputKeyDown = event => {
    const { keyCode } = event;
    if (
      (keyCode >= 48 && keyCode <= 57) ||
      (keyCode >= 96 && keyCode <= 105) ||
      keyCode === 8 || //Backspace key
      keyCode === 13   //Enter key
    ) {
    } else {
      event.preventDefault();
    }
  };

REST API Best practices: Where to put parameters?

As a programmer often on the client-end, I prefer the query argument. Also, for me, it separates the URL path from the parameters, adds to clarity, and offers more extensibility. It also allows me to have separate logic between the URL/URI building and the parameter builder.

I do like what manuel aldana said about the other option if there's some sort of tree involved. I can see user-specific parts being treed off like that.

Encoding Error in Panda read_csv

This works in Mac as well you can use

df= pd.read_csv('Region_count.csv', encoding ='latin1')

the getSource() and getActionCommand()

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

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

public class SeleccionListener implements ActionListener, FocusListener {}

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

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

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

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

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

My Routes are Returning a 404, How can I Fix Them?

On my Ubuntu LAMP installation, I solved this problem with the following 2 changes.

  1. Enable mod_rewrite on the apache server: sudo a2enmod rewrite.
  2. Edit /etc/apache2/apache2.conf, changing the "AllowOverride" directive for the /var/www directory (which is my main document root): AllowOverride All

Then restart the Apache server: service apache2 restart

How to assign from a function which returns more than one value?

If you want to return the output of your function to the Global Environment, you can use list2env, like in this example:

myfun <- function(x) { a <- 1:x
                       b <- 5:x
                       df <- data.frame(a=a, b=b)

                       newList <- list("my_obj1" = a, "my_obj2" = b, "myDF"=df)
                       list2env(newList ,.GlobalEnv)
                       }
    myfun(3)

This function will create three objects in your Global Environment:

> my_obj1
  [1] 1 2 3

> my_obj2
  [1] 5 4 3

> myDF
    a b
  1 1 5
  2 2 4
  3 3 3

Difference between innerText, innerHTML and value?

The only difference between innerText and innerHTML is that innerText insert string as it is into the element, while innerHTML run it as html content.

_x000D_
_x000D_
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';_x000D_
document.getElementById('innertext').innerText = ourstring;_x000D_
document.getElementById('innerhtml').innerHTML = ourstring;
_x000D_
.name{_x000D_
color:red;_x000D_
}
_x000D_
<h3>Inner text below. It inject string as it is into the element.</h3>_x000D_
<div id="innertext"></div>_x000D_
<br />_x000D_
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>_x000D_
<div id="innerhtml"></div>
_x000D_
_x000D_
_x000D_

Python "expected an indented block"

Your last for statement is missing a body.

Python expects an indented block to follow the line with the for, or to have content after the colon.

The first style is more common, so it says it expects some indented code to follow it. You have an elif at the same indent level.

Check if an image is loaded (no errors) with jQuery

Realtime network detector - check network status without refreshing the page: (it's not jquery, but tested, and 100% works:(tested on Firefox v25.0))

Code:

<script>
 function ImgLoad(myobj){
   var randomNum = Math.round(Math.random() * 10000);
   var oImg=new Image;
   oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
   oImg.onload=function(){alert('Image succesfully loaded!')}
   oImg.onerror=function(){alert('No network connection or image is not available.')}
}
window.onload=ImgLoad();
</script>

<button id="reloadbtn" onclick="ImgLoad();">Again!</button>

if connection lost just press the Again button.

Update 1: Auto detect without refreshing the page:

<script>
     function ImgLoad(myobj){
       var randomNum = Math.round(Math.random() * 10000);
       var oImg=new Image;
       oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
       oImg.onload=function(){networkstatus_div.innerHTML="";}
       oImg.onerror=function(){networkstatus_div.innerHTML="Service is not available. Please check your Internet connection!";}
}

networkchecker = window.setInterval(function(){window.onload=ImgLoad()},1000);
</script>

<div id="networkstatus_div"></div>

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Indeed, you'll get rid of those warnings by disabling Swift 3 @objc Inference. However, subtle issues may pop up. For example, KVO will stop working. This code worked perfectly under Swift 3:

for (key, value) in jsonDict {
    if self.value(forKey: key) != nil {
        self.setValue(value, forKey: key)
    }
}

After migrating to Swift 4, and setting "Swift 3 @objc Inference" to default, certain features of my project stopped working. It took me some debugging and research to find a solution for this. According to my best knowledge, here are the options:

  • Enable "Swift 3 @objc Inference" (only works if you migrated an existing project from Swift 3) enter image description here
  • Mark the affected methods and properties as @objc enter image description here
  • Re-enable ObjC inference for the entire class using @objcMembers enter image description here

Re-enabling @objc inference leaves you with the warnings, but it's the quickest solution. Note that it's only available for projects migrated from an earlier Swift version. The other two options are more tedious and require some code-digging and extensive testing.

See also https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md

Postgres and Indexes on Foreign Keys and Primary Keys

For a PRIMARY KEY, an index will be created with the following message:

NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "index" for table "table" 

For a FOREIGN KEY, the constraint will not be created if there is no index on the referenced table.

An index on referencing table is not required (though desired), and therefore will not be implicitly created.

How to get number of rows using SqlDataReader in C#

There are only two options:

  • Find out by reading all rows (and then you might as well store them)

  • run a specialized SELECT COUNT(*) query beforehand.

Going twice through the DataReader loop is really expensive, you would have to re-execute the query.

And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.

Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<> or DataTable) and then copy the data to any format you want. The in-memory operation will always be much more efficient.

Return background color of selected cell

You can use Cell.Interior.Color, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).

How to convert date in to yyyy-MM-dd Format?

UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..

Joda-Time

The accepted answer by NidhishKrishnan is correct.

For fun, here is the same kind of code in Joda-Time 2.3.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

java.util.Date date = new Date(); // A Date object coming from other code.

// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );

When run…

dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30

what does "dead beef" mean?

People normally use it to indicate dummy values. I think that it primarily was used before the idea of NULL pointers.

Why is $$ returning the same id as the parent process?

If you were asking how to get the PID of a known command it would resemble something like this:

If you had issued the command below #The command issued was ***

dd if=/dev/diskx of=/dev/disky


Then you would use:

PIDs=$(ps | grep dd | grep if | cut -b 1-5)

What happens here is it pipes all needed unique characters to a field and that field can be echoed using

echo $PIDs

How to SELECT a dropdown list item by value programmatically

combobox1.SelectedValue = x;

I suspect you may want yo hear something else, but this is what you asked for.

C# Creating an array of arrays

What you need to do is this:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

Another alternative would be to create a List<int[]> type:

List<int[]> data=new List<int[]>(){list1,list2,list3,list4};

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

Get Substring between two characters using javascript

This could be the possible solution

var str = 'RACK NO:Stock;PRODUCT TYPE:Stock Sale;PART N0:0035719061;INDEX NO:21A627 042;PART NAME:SPRING;';  
var newstr = str.split(':')[1].split(';')[0]; // return value as 'Stock'

console.log('stringvalue',newstr)

Get index of array element faster than O(n)

Why not use index or rindex?

array = %w( a b c d e)
# get FIRST index of element searched
puts array.index('a')
# get LAST index of element searched
puts array.rindex('a')

index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex

How to Automatically Start a Download in PHP?

A clean example.

<?php
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename="example.txt"');
    header("Content-Length: " . filesize("example.txt"));

    $fp = fopen("example.txt", "r");
    fpassthru($fp);
    fclose($fp);
?>

Javascript ES6 export const vs export let

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to a no matter how you declare a in the module.

However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.


To summarize:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-const semantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

In Java, how do I parse XML as a String instead of a file?

You can use the Scilca XML Progession package available at GitHub.

XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();

Postgres: How to convert a json string to text?

Mr. Curious was curious about this as well. In addition to the #>> '{}' operator, in 9.6+ one can get the value of a jsonb string with the ->> operator:

select to_jsonb('Some "text"'::TEXT)->>0;
  ?column?
-------------
 Some "text"
(1 row)

If one has a json value, then the solution is to cast into jsonb first:

select to_json('Some "text"'::TEXT)::jsonb->>0;
  ?column?
-------------
 Some "text"
(1 row)

Text Editor which shows \r\n?

I'd bet that Programmer's Notepad would give you something like that...

$.ajax( type: "POST" POST method to php

contentType: 'application/x-www-form-urlencoded'

Force re-download of release dependency using Maven

Just delete ~/.m2/repository...../actual_path where the invalid LOC is coming as it forces to re-download the deleted jar files. Dont delete the whole repository folder instead delete the specific folder from where the error is coming.

Batch file to delete files older than N days

My command is

forfiles -p "d:\logs" -s -m*.log -d-15 -c"cmd /c del @PATH\@FILE" 

@PATH - is just path in my case, so I had to use @PATH\@FILE

also forfiles /? not working for me too, but forfiles (without "?") worked fine.

And the only question I have: how to add multiple mask (for example ".log|.bak")?

All this regarding forfiles.exe that I downloaded here (on win XP)

But if you are using Windows server forfiles.exe should be already there and it is differs from ftp version. That is why I should modify command.

For Windows Server 2003 I'm using this command:

forfiles -p "d:\Backup" -s -m *.log -d -15 -c "cmd /c del @PATH"

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

for the new users on Mac os , find out .m2 folder and delete it, its on your /Users/.m2 directory.

you wont get to see .m2 folder in finder(File Explorer), for this user this command to Show Mac hidden files

$ defaults write com.apple.finder AppleShowAllFiles TRUE

after this press alt and click on finder-> relaunch, you can see /Users/.m2

to hide files again, simply use this $ defaults write com.apple.finder AppleShowAllFiles false

Run a controller function whenever a view is opened/shown

I had a similar problem with ionic where I was trying to load the native camera as soon as I select the camera tab. I resolved the issue by setting the controller to the ion-view component for the camera tab (in tabs.html) and then calling the $scope method that loads my camera (addImage).

In www/templates/tabs.html

  <ion-tab title="Camera" icon-off="ion-camera" icon-on="ion-camera" href="#/tab/chats" ng-controller="AddMediaCtrl" ng-click="addImage()">
    <ion-nav-view  name="tab-chats"></ion-nav-view>
  </ion-tab>

The addImage method, defined in AddMediaCtrl loads the native camera every time the user clicks the "Camera" tab. I did not have to change anything in the angular cache for this to work. I hope this helps.

How does the FetchMode work in Spring Data JPA

According to Vlad Mihalcea (see https://vladmihalcea.com/hibernate-facts-the-importance-of-fetch-strategy/):

JPQL queries may override the default fetching strategy. If we don’t explicitly declare what we want to fetch using inner or left join fetch directives, the default select fetch policy is applied.

It seems that JPQL query might override your declared fetching strategy so you'll have to use join fetch in order to eagerly load some referenced entity or simply load by id with EntityManager (which will obey your fetching strategy but might not be a solution for your use case).

Row count where data exists

If you need VBA, you could do something quick like this:

Sub Test()
    With ActiveSheet
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    MsgBox lastRow
    End With
End Sub

This will print the number of the last row with data in it. Obviously don't need MsgBox in there if you're using it for some other purpose, but lastRow will become that value nonetheless.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

How can I specify a branch/tag when adding a Git submodule?

(Git 2.22, Q2 2019, has introduced git submodule set-branch --branch aBranch -- <submodule_path>)

Note that if you have an existing submodule which isn't tracking a branch yet, then (if you have git 1.8.2+):

  • Make sure the parent repo knows that its submodule now tracks a branch:

      cd /path/to/your/parent/repo
      git config -f .gitmodules submodule.<path>.branch <branch>
    
  • Make sure your submodule is actually at the latest of that branch:

      cd path/to/your/submodule
      git checkout -b branch --track origin/branch
        # if the master branch already exist:
        git branch -u origin/master master
    

         (with 'origin' being the name of the upstream remote repo the submodule has been cloned from.
         A git remote -v inside that submodule will display it. Usually, it is 'origin')

  • Don't forget to record the new state of your submodule in your parent repo:

      cd /path/to/your/parent/repo
      git add path/to/your/submodule
      git commit -m "Make submodule tracking a branch"
    
  • Subsequent update for that submodule will have to use the --remote option:

      # update your submodule
      # --remote will also fetch and ensure that
      # the latest commit from the branch is used
      git submodule update --remote
    
      # to avoid fetching use
      git submodule update --remote --no-fetch 
    

Note that with Git 2.10+ (Q3 2016), you can use '.' as a branch name:

The name of the branch is recorded as submodule.<name>.branch in .gitmodules for update --remote.
A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.

But, as commented by LubosD

With git checkout, if the branch name to follow is ".", it will kill your uncommitted work!
Use git switch instead.

That means Git 2.23 (August 2019) or more.

See "Confused by git checkout"


If you want to update all your submodules following a branch:

    git submodule update --recursive --remote

Note that the result, for each updated submodule, will almost always be a detached HEAD, as Dan Cameron note in his answer.

(Clintm notes in the comments that, if you run git submodule update --remote and the resulting sha1 is the same as the branch the submodule is currently on, it won't do anything and leave the submodule still "on that branch" and not in detached head state.)

To ensure the branch is actually checked out (and that won't modify the SHA1 of the special entry representing the submodule for the parent repo), he suggests:

git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git switch $branch'

Each submodule will still reference the same SHA1, but if you do make new commits, you will be able to push them because they will be referenced by the branch you want the submodule to track.
After that push within a submodule, don't forget to go back to the parent repo, add, commit and push the new SHA1 for those modified submodules.

Note the use of $toplevel, recommended in the comments by Alexander Pogrebnyak.
$toplevel was introduced in git1.7.2 in May 2010: commit f030c96.

it contains the absolute path of the top level directory (where .gitmodules is).

dtmland adds in the comments:

The foreach script will fail to checkout submodules that are not following a branch.
However, this command gives you both:

 git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; [ "$branch" = "" ] && git checkout master || git switch $branch' –

The same command but easier to read:

git submodule foreach -q --recursive \
    'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; \
     [ "$branch" = "" ] && \
     git checkout master || git switch $branch' –
  

umläute refines dtmland's command with a simplified version in the comments:

git submodule foreach -q --recursive 'git switch $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master)'

multiple lines:

git submodule foreach -q --recursive \
  'git switch \
  $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master)'

Before Git 2.26 (Q1 2020), a fetch that is told to recursively fetch updates in submodules inevitably produces reams of output, and it becomes hard to spot error messages.

The command has been taught to enumerate submodules that had errors at the end of the operation.

See commit 0222540 (16 Jan 2020) by Emily Shaffer (nasamuffin).
(Merged by Junio C Hamano -- gitster -- in commit b5c71cc, 05 Feb 2020)

fetch: emphasize failure during submodule fetch

Signed-off-by: Emily Shaffer

In cases when a submodule fetch fails when there are many submodules, the error from the lone failing submodule fetch is buried under activity on the other submodules if more than one fetch fell back on fetch-by-oid.
Call out a failure late so the user is aware that something went wrong, and where.

Because fetch_finish() is only called synchronously by run_processes_parallel, mutexing is not required around submodules_with_errors.


Note that, with Git 2.28 (Q3 2020), Rewrite of parts of the scripted "git submodule" Porcelain command continues; this time it is "git submodule set-branch" subcommand's turn.

See commit 2964d6e (02 Jun 2020) by Shourya Shukla (periperidip).
(Merged by Junio C Hamano -- gitster -- in commit 1046282, 25 Jun 2020)

submodule: port subcommand 'set-branch' from shell to C

Mentored-by: Christian Couder
Mentored-by: Kaartic Sivaraam
Helped-by: Denton Liu
Helped-by: Eric Sunshine
Helped-by: Ðoàn Tr?n Công Danh
Signed-off-by: Shourya Shukla

Convert submodule subcommand 'set-branch' to a builtin and call it via git submodule.sh.

How to hide TabPage from TabControl

Variant 1

In order to avoid visual klikering you might need to use:

bindingSource.RaiseListChangeEvent = false 

or

myTabControl.RaiseSelectedIndexChanged = false

Remove a tab page:

myTabControl.Remove(myTabPage);

Add a tab page:

myTabControl.Add(myTabPage);

Insert a tab page at specific location:

myTabControl.Insert(2, myTabPage);

Do not forget to revers the changes:

bindingSource.RaiseListChangeEvent = true;

or

myTabControl.RaiseSelectedIndexChanged = true;

Variant 2

myTabPage.parent = null;
myTabPage.parent = myTabControl;

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

The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site

    <head>
        <base href="~/" />
    </head>

Calling a function within a Class method?

In order to have a "function within a function", if I understand what you're asking, you need PHP 5.3, where you can take advantage of the new Closure feature.

So you could have:

public function newTest() {
   $bigTest = function() {
        //Big Test Here
   }
}

Pivoting rows into columns dynamically in Oracle

First of all, dynamically pivot using pivot xml again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.

Consider we have a table like below.

enter image description here

If we need to show the values in the column YR as column names and the values in those columns from QTY, then we can use the below code.

declare
  sqlqry clob;
  cols clob;
begin
  select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
  into   cols
  from   (select distinct YR from EMPLOYEE);


  sqlqry :=
  '      
  select * from
  (
      select *
      from EMPLOYEE
  )
  pivot
  (
    MIN(QTY) for YR in (' || cols  || ')
  )';

  execute immediate sqlqry;
end;
/

RESULT

enter image description here

What issues should be considered when overriding equals and hashCode in Java?

The theory (for the language lawyers and the mathematically inclined):

equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().

In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute equals() to compute hashCode().

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:

public class Person {
    private String name;
    private int age;
    // ...

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}

Also remember:

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

Reading NFC Tags with iPhone 6 / iOS 8

The only information currently available is that Apple Pay will be available in ios8, but that doesn't shed any light on whether RFID tags or rather NFC tags specifically will be able to be detected/read.

IMO it would be a shortsighted move not to allow that possibility, but really the money is in Apple Pay, not necessarily in allowing developers access to those features - we've seen it before with tethering, Bluetooth SPP, and diminished access to certain functions.

...but then again, it's been about 5 hours since the first announcement.

Get error message if ModelState.IsValid fails?

You can do this in your view without doing anything special in your action by using Html.ValidationSummary() to show all error messages, or Html.ValidationMessageFor() to show a message for a specific property of the model.

If you still need to see the errors from within your action or controller, see the ModelState.Errors property

How do I declare a global variable in VBA?

The question is really about scope, as the other guy put it.

In short, consider this "module":

Public Var1 As variant     'Var1 can be used in all
                           'modules, class modules and userforms of 
                           'thisworkbook and will preserve any values
                           'assigned to it until either the workbook
                           'is closed or the project is reset.

Dim Var2 As Variant        'Var2 and Var3 can be used anywhere on the
Private Var3 As Variant    ''current module and will preserve any values
                           ''they're assigned until either the workbook
                           ''is closed or the project is reset.

Sub MySub()                'Var4 can only be used within the procedure MySub
    Dim Var4 as Variant    ''and will only store values until the procedure 
End Sub                    ''ends.

Sub MyOtherSub()           'You can even declare another Var4 within a
    Dim Var4 as Variant    ''different procedure without generating an
End Sub                    ''error (only possible confusion). 

You can check out this MSDN reference for more on variable declaration and this other Stack Overflow Question for more on how variables go out of scope.

Two other quick things:

  1. Be organized when using workbook level variables, so your code doesn't get confusing. Prefer Functions (with proper data types) or passing arguments ByRef.
  2. If you want a variable to preserve its value between calls, you can use the Static statement.

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

You should, as a rule, leave timestamps in the database in GMT, and only convert them to/from local time on input/output, when you can convert them to the user's (not server's) local timestamp.

It would be nice if you could do the following:

SELECT DATETIME(col, 'PDT')

...to output the timestamp for a user on Pacific Daylight Time. Unfortunately, that doesn't work. According to this SQLite tutorial, however (scroll down to "Other Date and Time Commands"), you can ask for the time, and then apply an offset (in hours) at the same time. So, if you do know the user's timezone offset, you're good.

Doesn't deal with daylight saving rules, though...

How do I subtract minutes from a date in javascript?

You can also use get and set minutes to achieve it:

var endDate = somedate;

var startdate = new Date(endDate);

var durationInMinutes = 20;

startdate.setMinutes(endDate.getMinutes() - durationInMinutes);

Tracking the script execution time in PHP

If all you need is the wall-clock time, rather than the CPU execution time, then it is simple to calculate:

//place this before any script you want to calculate time
$time_start = microtime(true); 

//sample script
for($i=0; $i<1000; $i++){
 //do anything
}

$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
// if you get weird results, use number_format((float) $execution_time, 10) 

Note that this will include time that PHP is sat waiting for external resources such as disks or databases, which is not used for max_execution_time.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

You need to use a tool to view the HTTP headers sent with the file, something like LiveHTTPHeaders or HTTPFox are what I use. If the files are sent from the webserver without a MIME type, or with a default MIME type like text/plain, that might be what this error is about.

Set focus on textbox in WPF

txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);

msdn:

There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.

You could break after the setting line and check the value of IsKeyboardFocused property. Also check if you really reach that line or maybe you set some other element to get focus after that.

How to get the caller's method name in the called method?

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)

SQL: IF clause within WHERE clause

You want the CASE statement

WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END

Email address validation in C# MVC 4 application: with or without using Regex

Why not just use the EmailAttribute?

[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }

C# Dictionary get item by index

you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

Simple JavaScript login form validation

  1. The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this:

    <form name="loginform" onsubmit="validateForm()" method="post">

    Here are some useful links:

  2. For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.

    You can read more about the differences here.

UPDATE:

You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:

<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
    <label>User name</label>
    <input type="text" name="usr" placeholder="username"> 
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>

<script>
    function validateForm() {
        var un = document.loginform.usr.value;
        var pw = document.loginform.pword.value;
        var username = "username"; 
        var password = "password";
        if ((un == username) && (pw == password)) {
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your username and password");
            return false;
        }
  }
</script>

Python List vs. Array - when to use?

The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). Most of the time, the array module is used to interface with C code. To give you a more direct answer to your question about performance:

Arrays are more efficient than lists for some uses. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory. GvR has an optimization anecdote in which the array module comes out to be the winner (long read, but worth it).

On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.

TL;DR I'd only use an array if you had an exceptional optimization need or you need to interface with C code (and can't use pyrex).

How to display and hide a div with CSS?

To hide an element, use:

display: none;
visibility: hidden;

To show an element, use:

display: block;
visibility: visible;

The difference is:

Visibility handles the visibility of the tag, the display handles space it occupies on the page.

If you set the visibility and do not change the display, even if the tags are not seen, it still occupies space.

How can I get the value of a registry key from within a batch script?

This works for me:

@echo OFF

setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USER\Software\Microsoft\Command Processor"
set VALUE_NAME=DefaultColor

FOR /F "usebackq skip=4 tokens=1-3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C
)

if defined ValueName (
    @echo Value Name = %ValueName%
    @echo Value Type = %ValueType%
    @echo Value Value = %ValueValue%
) else (
    @echo %KEY_NAME%\%VALUE_NAME% not found.
)

usebackq is needed since the command to REG QUERY uses double quotes.

skip=4 ignores all the output except for the line that has the value name, type and value, if it exists.

2^>nul prevents the error text from appearing. ^ is the escape character that lets you put the > in the for command.

When I run the script above as given, I get this output:

Value Name = DefaultColor
Value Type = REG_DWORD
Value Value = 0x0

If I change the value of VALUE_NAME to BogusValue then I get this:

"HKEY_CURRENT_USER\Software\Microsoft\Command Processor"\BogusValue not found.

JavaScript for...in vs for

Although they both are very much alike there is a minor difference :

var array = ["a", "b", "c"];
array["abc"] = 123;
console.log("Standard for loop:");
for (var index = 0; index < array.length; index++)
{
  console.log(" array[" + index + "] = " + array[index]); //Standard for loop
}

in this case the output is :

STANDARD FOR LOOP:

ARRAY[0] = A

ARRAY[1] = B

ARRAY[2] = C

console.log("For-in loop:");
for (var key in array)
{
  console.log(" array[" + key + "] = " + array[key]); //For-in loop output
}

while in this case the output is:

FOR-IN LOOP:

ARRAY[1] = B

ARRAY[2] = C

ARRAY[10] = D

ARRAY[ABC] = 123

Css Move element from left to right animated

You should try doing it with css3 animation. Check the code bellow:

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
    -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
    animation: myfirst 5s infinite;
    animation-direction: alternate;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}

@keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>

<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>

</body>
</html>

Where 'div' is your animated object.

I hope you find this useful.

Thanks.

`&mdash;` or `&#8212;` is there any difference in HTML output?

From W3 web site Common HTML entities used for typography

For the sake of portability, Unicode entity references should be reserved for use in documents certain to be written in the UTF-8 or UTF-16 character sets. In all other cases, the alphanumeric references should be used.

Translation: If you are looking for widest support, go with &mdash;

Not able to access adb in OS X through Terminal, "command not found"

For some reason when installed Android Studio 3.6.1 the adb file was actually in $ANDROID_HOME/platform-tools/platform-tools. not sure if this is a bug with my installation or what but this fixed it for me.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

Just for completeness. There is another situation causing this error:

missing META-INF/services/javax.persistence.spi.PersistenceProvider file.

For Hibernate, it's located in hibernate-entitymanager-XXX.jar, so, if hibernate-entitymanager-XXX.jar is not in your classpath, you will got this error too.

This error message is so misleading, and it costs me hours to get it correct.

See JPA 2.0 using Hibernate as provider - Exception: No Persistence provider for EntityManager.

Use PHP to convert PNG to JPG with compression?

Do this to convert safely a PNG to JPG with the transparency in white.

$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file 
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);

str_replace with array

Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :

$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
    $query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;

Demo here : http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7

Custom thread pool in Java 8 parallel stream

We can change the default parallelism using the following property:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=16

which can set up to use more parallelism.

What's the strangest corner case you've seen in C# or .NET?

Just found a nice little thing today:

public class Base
{
   public virtual void Initialize(dynamic stuff) { 
   //...
   }
}
public class Derived:Base
{
   public override void Initialize(dynamic stuff) {
   base.Initialize(stuff);
   //...
   }
}

This throws compile error.

The call to method 'Initialize' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.

If I write base.Initialize(stuff as object); it works perfectly, however this seems to be a "magic word" here, since it does exactly the same, everything is still recieved as dynamic...

Carousel with Thumbnails in Bootstrap 3.0

  1. Use the carousel's indicators to display thumbnails.
  2. Position the thumbnails outside of the main carousel with CSS.
  3. Set the maximum height of the indicators to not be larger than the thumbnails.
  4. Whenever the carousel has slid, update the position of the indicators, positioning the active indicator in the middle of the indicators.

I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.

Also, my templating engine is smarty, but I'm sure you get the idea.

The meat...

Updating the indicators:

<ol class="carousel-indicators">
    {assign var='walker' value=0}
    {foreach from=$item["imagearray"] key="key" item="value"}
        <li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
            <img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
        </li>

        {assign var='walker' value=1 + $walker}
    {/foreach}
</ol>

Changing the CSS related to the indicators:

.carousel-indicators {
    bottom:-50px;
    height: 36px;
    overflow-x: hidden;
    white-space: nowrap;
}

.carousel-indicators li {
    text-indent: 0;
    width: 34px !important;
    height: 34px !important;
    border-radius: 0;
}

.carousel-indicators li img {
    width: 32px;
    height: 32px;
    opacity: 0.5;
}

.carousel-indicators li:hover img, .carousel-indicators li.active img {
    opacity: 1;
}

.carousel-indicators .active {
    border-color: #337ab7;
}

When the carousel has slid, update the list of thumbnails:

$('#myCarousel').on('slid.bs.carousel', function() {
    var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width(); 
    var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
    var toScroll = newIndicatorPosition + indicatorPosition;
    var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
    if (adjustedScroll < 0)
        adjustedScroll = 0;

    if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
        adjustedScroll = widthEstimate - $(".carousel-indicators").width();

    $('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);

    indicatorPosition = adjustedScroll;
});

And, when your page loads, set the initial scroll position of the thumbnails:

var indicatorPosition = 0;

"for loop" with two variables?

There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.

Fortunately, there's simple answers to both. First case, you want to use zip.

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
   print(str(i) + " / " + str(j))

will output

1 / 4
2 / 5
3 / 6

Remember that you can put any iterable in zip, so you could just as easily write your exmple like:

for i, j in zip(range(x), range(y)):
    # do work here.

Actually, just realised that won't work. It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.

In the other case, you just want a nested loop.

for i in x:
    for j in y:
        print(str(i) + " / " + str(j))

gives you

1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...

You can also do this as a list comprehension.

[str(i) + " / " + str(j) for i in range(x) for j in range(y)]

Hope that helps.

How to get the date from jQuery UI datepicker

NamingException's answer worked for me. Except I used

var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()

datepicker didn't work but dtpicker did.

How to delete a selected DataGridViewRow and update a connected database table?

Well, this is how I usually delete checked rows by the user from a DataGridView, if you are associating it with a DataTable from a Dataset (ex: DataGridView1.DataSource = Dataset1.Tables["x"]), then once you will make any updates (delete, insert,update) in the Dataset, it will automatically happen in your DataGridView.

if (MessageBox.Show("Are you sure you want to delete this record(s)", "confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
        {
            try
            {
                for (int i = dgv_Championnat.RowCount -1; i > -1; i--)
                {
                    if (Convert.ToBoolean(dgv_Championnat.Rows[i].Cells[0].Value) == true)
                    {
                        Program.set.Tables["Champ"].Rows[i].Delete();
                    }
                }
                Program.command = new SqlCommandBuilder(Program.AdapterChampionnat);
                if (Program.AdapterChampionnat.Update(Program.TableChampionnat) > 0)
                {
                    MessageBox.Show("Well Deleted");
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

How to update a value, given a key in a hashmap?

It may be little late but here are my two cents.

If you are using Java 8 then you can make use of computeIfPresent method. If the value for the specified key is present and non-null then it attempts to compute a new mapping given the key and its current mapped value.

final Map<String,Integer> map1 = new HashMap<>();
map1.put("A",0);
map1.put("B",0);
map1.computeIfPresent("B",(k,v)->v+1);  //[A=0, B=1]

We can also make use of another method putIfAbsent to put a key. If the specified key is not already associated with a value (or is mapped to null) then this method associates it with the given value and returns null, else returns the current value.

In case the map is shared across threads then we can make use of ConcurrentHashMap and AtomicInteger. From the doc:

An AtomicInteger is an int value that may be updated atomically. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.

We can use them as shown:

final Map<String,AtomicInteger> map2 = new ConcurrentHashMap<>();
map2.putIfAbsent("A",new AtomicInteger(0));
map2.putIfAbsent("B",new AtomicInteger(0)); //[A=0, B=0]
map2.get("B").incrementAndGet();    //[A=0, B=1]

One point to observe is we are invoking get to get the value for key B and then invoking incrementAndGet() on its value which is of course AtomicInteger. We can optimize it as the method putIfAbsent returns the value for the key if already present:

map2.putIfAbsent("B",new AtomicInteger(0)).incrementAndGet();//[A=0, B=2]

On a side note if we plan to use AtomicLong then as per documentation under high contention expected throughput of LongAdder is significantly higher, at the expense of higher space consumption. Also check this question.

How to get UTC value for SYSDATE on Oracle

I'm using:

SELECT CAST(SYSTIMESTAMP AT TIME ZONE 'UTC' AS DATE) FROM DUAL;

It's working fine for me.

How to check currently internet connection is available or not in android

Also, be aware that sometimes the user will be connected to a Wi-Fi network, but that network might require browser-based authentication. Most airport and hotel hotspots are like that, so you application might be fooled into thinking you have connectivity, and then any URL fetches will actually retrieve the hotspot's login page instead of the page you are looking for.

Depending on the importance of performing this check, in addition to checking the connection with ConnectivityManager, I'd suggest including code to check that it's a working Internet connection and not just an illusion. You can do that by trying to fetch a known address/resource from your site, like a 1x1 PNG image or 1-byte text file.

How do you make a HTTP request with C++?

You can use embeddedRest library. It is lightweight header-only library. So it is easy to include it to your project and it does not require compilation cause there no .cpp files in it.

Request example from readme.md from repo:

#include "UrlRequest.hpp"

//...

UrlRequest request;
request.host("api.vk.com");
const auto countryId = 1;
const auto count = 1000;
request.uri("/method/database.getCities",{
    { "lang", "ru" },
    { "country_id", countryId },
    { "count", count },
    { "need_all", "1" },
});
request.addHeader("Content-Type: application/json");
auto response = std::move(request.perform());
if (response.statusCode() == 200) {
  cout << "status code = " << response.statusCode() << ", body = *" << response.body() << "*" << endl;
}else{
  cout << "status code = " << response.statusCode() << ", description = " << response.statusDescription() << endl;
}

How to set user environment variables in Windows Server 2008 R2 as a normal user?

In command line prompt:

set __COMPAT_LAYER=RUNASINVOKER
SystemPropertiesAdvanced.exe

Now you can set user environment variables.

What's the best way to limit text length of EditText in Android

Xml

android:maxLength="10"

Java:

InputFilter[] editFilters = editText.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(newFilters);

Kotlin:

editText.filters += InputFilter.LengthFilter(maxLength)

Redirecting to authentication dialog - "An error occurred. Please try again later"

For me this happened because the "test user" I created was part of a separate app. I created a test user for THIS app, and it started working fine.

Stupid on my part I know, but this could save someone else some trouble.

Removing App ID from Developer Connection

Update: You can now remove an App ID (as noted by @Guru in the comments).

In the past, this was not possible: I had the same problem, and the folks at Apple replied that they will leave all of the App ID you create associated to your login, to keep track of a sort of history related to your login.

It seems that they finally changed idea about.

How do I find the stack trace in Visual Studio?

For Visual Studio 2019, the shortcut (while debugging and stopped at a breakpoint) is:

Ctrl+Alt+C and now you can also use Ctrl+L

The screenshot is pretty old. Here is one for Visual Studio 2019 (under the debug menu):

Visual Studio 2019 Call Stack Menu Option

How can I get Apache gzip compression to work?

In my case i have used following code for enabling gzip compression in apache web server.

  # Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/x-httpd-php
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf

I have taken reference from http://www.tutsway.com/enable-gzip-compression-using-htacess.php.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can try this:

NSLog(@"%@", NSStringFromCGPoint(cgPoint));

There are a number of functions provided by UIKit that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

Error loading the SDK when Eclipse starts

There are lots of answer already given for this problem. Though this issue can happens for any API version, so just see the error line and find out android api version from path and platform name and go to the android sdk manager and delete related system image from sdk manager.

pandas loc vs. iloc vs. at vs. iat?

There are two primary ways that pandas makes selections from a DataFrame.

  • By Label
  • By Integer Location

The documentation uses the term position for referring to integer location. I do not like this terminology as I feel it is confusing. Integer location is more descriptive and is exactly what .iloc stands for. The key word here is INTEGER - you must use integers when selecting by integer location.

Before showing the summary let's all make sure that ...

.ix is deprecated and ambiguous and should never be used

There are three primary indexers for pandas. We have the indexing operator itself (the brackets []), .loc, and .iloc. Let's summarize them:

  • [] - Primarily selects subsets of columns, but can select rows as well. Cannot simultaneously select rows and columns.
  • .loc - selects subsets of rows and columns by label only
  • .iloc - selects subsets of rows and columns by integer location only

I almost never use .at or .iat as they add no additional functionality and with just a small performance increase. I would discourage their use unless you have a very time-sensitive application. Regardless, we have their summary:

  • .at selects a single scalar value in the DataFrame by label only
  • .iat selects a single scalar value in the DataFrame by integer location only

In addition to selection by label and integer location, boolean selection also known as boolean indexing exists.


Examples explaining .loc, .iloc, boolean selection and .at and .iat are shown below

We will first focus on the differences between .loc and .iloc. Before we talk about the differences, it is important to understand that DataFrames have labels that help identify each column and each row. Let's take a look at a sample DataFrame:

df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
                   'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
                   'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
                   'height':[165, 70, 120, 80, 180, 172, 150],
                   'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
                   'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'])

enter image description here

All the words in bold are the labels. The labels, age, color, food, height, score and state are used for the columns. The other labels, Jane, Nick, Aaron, Penelope, Dean, Christina, Cornelia are used as labels for the rows. Collectively, these row labels are known as the index.


The primary ways to select particular rows in a DataFrame are with the .loc and .iloc indexers. Each of these indexers can also be used to simultaneously select columns but it is easier to just focus on rows for now. Also, each of the indexers use a set of brackets that immediately follow their name to make their selections.

.loc selects data only by labels

We will first talk about the .loc indexer which only selects data by the index or column labels. In our sample DataFrame, we have provided meaningful names as values for the index. Many DataFrames will not have any meaningful names and will instead, default to just the integers from 0 to n-1, where n is the length(number of rows) of the DataFrame.

There are many different inputs you can use for .loc three out of them are

  • A string
  • A list of strings
  • Slice notation using strings as the start and stop values

Selecting a single row with .loc with a string

To select a single row of data, place the index label inside of the brackets following .loc.

df.loc['Penelope']

This returns the row of data as a Series

age           4
color     white
food      Apple
height       80
score       3.3
state        AL
Name: Penelope, dtype: object

Selecting multiple rows with .loc with a list of strings

df.loc[['Cornelia', 'Jane', 'Dean']]

This returns a DataFrame with the rows in the order specified in the list:

enter image description here

Selecting multiple rows with .loc with slice notation

Slice notation is defined by a start, stop and step values. When slicing by label, pandas includes the stop value in the return. The following slices from Aaron to Dean, inclusive. Its step size is not explicitly defined but defaulted to 1.

df.loc['Aaron':'Dean']

enter image description here

Complex slices can be taken in the same manner as Python lists.

.iloc selects data only by integer location

Let's now turn to .iloc. Every row and column of data in a DataFrame has an integer location that defines it. This is in addition to the label that is visually displayed in the output. The integer location is simply the number of rows/columns from the top/left beginning at 0.

There are many different inputs you can use for .iloc three out of them are

  • An integer
  • A list of integers
  • Slice notation using integers as the start and stop values

Selecting a single row with .iloc with an integer

df.iloc[4]

This returns the 5th row (integer location 4) as a Series

age           32
color       gray
food      Cheese
height       180
score        1.8
state         AK
Name: Dean, dtype: object

Selecting multiple rows with .iloc with a list of integers

df.iloc[[2, -2]]

This returns a DataFrame of the third and second to last rows:

enter image description here

Selecting multiple rows with .iloc with slice notation

df.iloc[:5:3]

enter image description here


Simultaneous selection of rows and columns with .loc and .iloc

One excellent ability of both .loc/.iloc is their ability to select both rows and columns simultaneously. In the examples above, all the columns were returned from each selection. We can choose columns with the same types of inputs as we do for rows. We simply need to separate the row and column selection with a comma.

For example, we can select rows Jane, and Dean with just the columns height, score and state like this:

df.loc[['Jane', 'Dean'], 'height':]

enter image description here

This uses a list of labels for the rows and slice notation for the columns

We can naturally do similar operations with .iloc using only integers.

df.iloc[[1,4], 2]
Nick      Lamb
Dean    Cheese
Name: food, dtype: object

Simultaneous selection with labels and integer location

.ix was used to make selections simultaneously with labels and integer location which was useful but confusing and ambiguous at times and thankfully it has been deprecated. In the event that you need to make a selection with a mix of labels and integer locations, you will have to make both your selections labels or integer locations.

For instance, if we want to select rows Nick and Cornelia along with columns 2 and 4, we could use .loc by converting the integers to labels with the following:

col_names = df.columns[[2, 4]]
df.loc[['Nick', 'Cornelia'], col_names] 

Or alternatively, convert the index labels to integers with the get_loc index method.

labels = ['Nick', 'Cornelia']
index_ints = [df.index.get_loc(label) for label in labels]
df.iloc[index_ints, [2, 4]]

Boolean Selection

The .loc indexer can also do boolean selection. For instance, if we are interested in finding all the rows where age is above 30 and return just the food and score columns we can do the following:

df.loc[df['age'] > 30, ['food', 'score']] 

You can replicate this with .iloc but you cannot pass it a boolean series. You must convert the boolean Series into a numpy array like this:

df.iloc[(df['age'] > 30).values, [2, 4]] 

Selecting all rows

It is possible to use .loc/.iloc for just column selection. You can select all the rows by using a colon like this:

df.loc[:, 'color':'score':2]

enter image description here


The indexing operator, [], can slice can select rows and columns too but not simultaneously.

Most people are familiar with the primary purpose of the DataFrame indexing operator, which is to select columns. A string selects a single column as a Series and a list of strings selects multiple columns as a DataFrame.

df['food']

Jane          Steak
Nick           Lamb
Aaron         Mango
Penelope      Apple
Dean         Cheese
Christina     Melon
Cornelia      Beans
Name: food, dtype: object

Using a list selects multiple columns

df[['food', 'score']]

enter image description here

What people are less familiar with, is that, when slice notation is used, then selection happens by row labels or by integer location. This is very confusing and something that I almost never use but it does work.

df['Penelope':'Christina'] # slice rows by label

enter image description here

df[2:6:2] # slice rows by integer location

enter image description here

The explicitness of .loc/.iloc for selecting rows is highly preferred. The indexing operator alone is unable to select rows and columns simultaneously.

df[3:5, 'color']
TypeError: unhashable type: 'slice'

Selection by .at and .iat

Selection with .at is nearly identical to .loc but it only selects a single 'cell' in your DataFrame. We usually refer to this cell as a scalar value. To use .at, pass it both a row and column label separated by a comma.

df.at['Christina', 'color']
'black'

Selection with .iat is nearly identical to .iloc but it only selects a single scalar value. You must pass it an integer for both the row and column locations

df.iat[2, 5]
'FL'

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

  1. Open the config.inc.php file in the WAMP phpmyadmin directory

  2. Change the line ['Servers'][$i]['password'] = '' to

    $cfg['Servers'][$i]['password'] = 'your_mysql_root_password';

  3. Clear browser cookies

  4. Then Restart all services on WAMP

This worked for me.

NB: the password to use has to be the MySQL password.....

Simple way to create matrix of random numbers

#this is a function for a square matrix so on the while loop rows does not have to be less than cols.
#you can make your own condition. But if you want your a square matrix, use this code.

import random

import numpy as np

def random_matrix(R, cols):

        matrix = []

        rows =  0

        while  rows < cols:

            N = random.sample(R, cols)

            matrix.append(N)

            rows = rows + 1

    return np.array(matrix)

print(random_matrix(range(10), 5))
#make sure you understand the function random.sample

How do I create an abstract base class in JavaScript?

I think All Those answers specially first two (by some and jordão) answer the question clearly with conventional prototype base JS concept.
Now as you want the animal class constructor to behave according to the passed parameter to the construction, I think this is very much similar to basic behavior of Creational Patterns for example Factory Pattern.

Here i made a little approach to make it work that way.

var Animal = function(type) {
    this.type=type;
    if(type=='dog')
    {
        return new Dog();
    }
    else if(type=="cat")
    {
        return new Cat();
    }
};



Animal.prototype.whoAreYou=function()
{
    console.log("I am a "+this.type);
}

Animal.prototype.say = function(){
    console.log("Not implemented");
};




var Cat =function () {
    Animal.call(this);
    this.type="cat";
};

Cat.prototype=Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

Cat.prototype.say=function()
{
    console.log("meow");
}



var Dog =function () {
    Animal.call(this);
    this.type="dog";
};

Dog.prototype=Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.say=function()
{
    console.log("bark");
}


var animal=new Animal();


var dog = new Animal('dog');
var cat=new Animal('cat');

animal.whoAreYou(); //I am a undefined
animal.say(); //Not implemented


dog.whoAreYou(); //I am a dog
dog.say(); //bark

cat.whoAreYou(); //I am a cat
cat.say(); //meow

How to echo xml file in php

Am I oversimplifying this?

$location = "http://rss.news.yahoo.com/rss/topstories";
print file_get_contents($location);

Some places (like digg.com) won't allow you to access their site without having a user-agent, in which case you would need to set that with ini_set() prior to running the file_get_contents().

Getting Current time to display in Label. VB.net

Try This.....

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

Utils to read resource text file to String (Java)

If you want to get your String from a project resource like the file testcase/foo.json in src/main/resources in your project, do this:

String myString= 
 new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));

Note that the getClassLoader() method is missing on some of the other examples.

Determine if a String is an Integer in Java

You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):

static boolean isInt(String s)
{
 try
  { int i = Integer.parseInt(s); return true; }

 catch(NumberFormatException er)
  { return false; }
}

However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:

static boolean isInt(String s)  // assuming integer is in decimal number system
{
 for(int a=0;a<s.length();a++)
 {
    if(a==0 && s.charAt(a) == '-') continue;
    if( !Character.isDigit(s.charAt(a)) ) return false;
 }
 return true;
}

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

File to byte[] in Java

I belive this is the easiest way:

org.apache.commons.io.FileUtils.readFileToByteArray(file);

How to disable spring security for particular url

<http pattern="/resources/**" security="none"/>

Or with Java configuration:

web.ignoring().antMatchers("/resources/**");

Instead of the old:

 <intercept-url pattern="/resources/**" filters="none"/>

for exp . disable security for a login page :

  <intercept-url pattern="/login*" filters="none" />

How to specify test directory for mocha?

Don't use the -g or --grep option, that pattern operates on the name of the test inside of it(), not the filesystem. The current documentation is misleading and/or outright wrong concerning this. To limit the entire command to a portion of the filesystem, you can pass a pattern as the last argument (its not a flag).

For example, this command will set your reporter to spec but will only test js files immediately inside of the server-test directory:

mocha --reporter spec server-test/*.js

This command will do the same as above, plus it will only run the test cases where the it() string/definition of a test begins with "Fnord:":

mocha --reporter spec --grep "Fnord:" server-test/*.js

CSS pseudo elements in React

Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hover via onMouseEnter and onMouseLeave to using more elements to reproduce pseudo-elements like :after and :before to just use an external stylesheet.

Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.

Imagine a large team wherein each developer is recreating CSS features like :hover. Each developer will do it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about n ways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.

So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).

Made a solution in this space called Style It that simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after:

npm install style-it --save

Functional Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return Style.it(`
      #heart {
        position: relative;
        width: 100px;
        height: 90px;
      }
      #heart:before,
      #heart:after {
        position: absolute;
        content: "";
        left: 50px;
        top: 0;
        width: 50px;
        height: 80px;
        background: red;
        -moz-border-radius: 50px 50px 0 0;
        border-radius: 50px 50px 0 0;
        -webkit-transform: rotate(-45deg);
        -moz-transform: rotate(-45deg);
        -ms-transform: rotate(-45deg);
        -o-transform: rotate(-45deg);
        transform: rotate(-45deg);
        -webkit-transform-origin: 0 100%;
        -moz-transform-origin: 0 100%;
        -ms-transform-origin: 0 100%;
        -o-transform-origin: 0 100%;
        transform-origin: 0 100%;
      }
      #heart:after {
        left: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        -o-transform: rotate(45deg);
        transform: rotate(45deg);
        -webkit-transform-origin: 100% 100%;
        -moz-transform-origin: 100% 100%;
        -ms-transform-origin: 100% 100%;
        -o-transform-origin: 100% 100%;
        transform-origin :100% 100%;
      }
    `,
      <div id="heart" />
    );
  }
}

export default Intro;

JSX Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
      {`
        #heart {
          position: relative;
          width: 100px;
          height: 90px;
        }
        #heart:before,
        #heart:after {
          position: absolute;
          content: "";
          left: 50px;
          top: 0;
          width: 50px;
          height: 80px;
          background: red;
          -moz-border-radius: 50px 50px 0 0;
          border-radius: 50px 50px 0 0;
          -webkit-transform: rotate(-45deg);
          -moz-transform: rotate(-45deg);
          -ms-transform: rotate(-45deg);
          -o-transform: rotate(-45deg);
          transform: rotate(-45deg);
          -webkit-transform-origin: 0 100%;
          -moz-transform-origin: 0 100%;
          -ms-transform-origin: 0 100%;
          -o-transform-origin: 0 100%;
          transform-origin: 0 100%;
        }
        #heart:after {
          left: 0;
          -webkit-transform: rotate(45deg);
          -moz-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
          -o-transform: rotate(45deg);
          transform: rotate(45deg);
          -webkit-transform-origin: 100% 100%;
          -moz-transform-origin: 100% 100%;
          -ms-transform-origin: 100% 100%;
          -o-transform-origin: 100% 100%;
          transform-origin :100% 100%;
        }
     `}

      <div id="heart" />
    </Style>
  }
}

export default Intro;

Heart example pulled from CSS-Tricks

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

Best way to add Activity to an Android project in Eclipse?

An easy method suggested by Google Android Developer Community.

enter image description here

How to split a string, but also keep the delimiters?

A very naive solution, that doesn't involve regex would be to perform a string replace on your delimiter along the lines of (assuming comma for delimiter):

string.replace(FullString, "," , "~,~")

Where you can replace tilda (~) with an appropriate unique delimiter.

Then if you do a split on your new delimiter then i believe you will get the desired result.

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

Is it possible only to declare a variable without assigning any value in Python?

I usually initialize the variable to something that denotes the type like

var = ""

or

var = 0

If it is going to be an object then don't initialize it until you instantiate it:

var = Var()

Read data from SqlDataReader

I would argue against using SqlDataReader here; ADO.NET has lots of edge cases and complications, and in my experience most manually written ADO.NET code is broken in at least one way (usually subtle and contextual).

Tools exist to avoid this. For example, in the case here you want to read a column of strings. Dapper makes that completely painless:

var region = ... // some filter
var vals = connection.Query<string>(
    "select Name from Table where Region=@region", // query
    new { region } // parameters
).AsList();

Dapper here is dealing with all the parameterization, execution, and row processing - and a lot of other grungy details of ADO.NET. The <string> can be replaced with <SomeType> to materialize entire rows into objects.

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

How do I clear (or redraw) the WHOLE canvas for a new layout (= try at the game) ?

Just call Canvas.drawColor(Color.BLACK), or whatever color you want to clear your Canvas with.

And: how can I update just a part of the screen ?

There is no such method that just update a "part of the screen" since Android OS is redrawing every pixel when updating the screen. But, when you're not clearing old drawings on your Canvas, the old drawings are still on the surface and that is probably one way to "update just a part" of the screen.

So, if you want to "update a part of the screen", just avoid calling Canvas.drawColor() method.

How to squash all git commits into one?

This answer improves on a couple above (please vote them up), assuming that in addition to creating the one commit (no-parents no-history), you also want to retain all of the commit-data of that commit:

  • Author (name and email)
  • Authored date
  • Commiter (name and email)
  • Committed date
  • Commmit log message

Of course the commit-SHA of the new/single commit will change, because it represents a new (non-)history, becoming a parentless/root-commit.

This can be done by reading git log and setting some variables for git commit-tree. Assuming that you want to create a single commit from master in a new branch one-commit, retaining the commit-data above:

git checkout -b one-commit master ## create new branch to reset
git reset --hard \
$(eval "$(git log master -n1 --format='\
COMMIT_MESSAGE="%B" \
GIT_AUTHOR_NAME="%an" \
GIT_AUTHOR_EMAIL="%ae" \
GIT_AUTHOR_DATE="%ad" \
GIT_COMMITTER_NAME="%cn" \
GIT_COMMITTER_EMAIL="%ce" \
GIT_COMMITTER_DATE="%cd"')" 'git commit-tree master^{tree} <<COMMITMESSAGE
$COMMIT_MESSAGE
COMMITMESSAGE
')

How can I detect when an Android application is running in the emulator?

try this link from github.

https://github.com/mofneko/EmulatorDetector

This module help you to emulator detection to your Android project suported Unity.

Basic checker

  • BlueStacks
  • Genymotion
  • Android Emulator
  • Nox App Player
  • Koplayer
  • .....

How do I create an array of strings in C?

hello you can try this bellow :

 char arr[nb_of_string][max_string_length]; 
 strcpy(arr[0], "word");

a nice example of using, array of strings in c if you want it

#include <stdio.h>
#include <string.h>


int main(int argc, char *argv[]){

int i, j, k;

// to set you array
//const arr[nb_of_string][max_string_length]
char array[3][100];

char temp[100];
char word[100];

for (i = 0; i < 3; i++){
    printf("type word %d : ",i+1);
    scanf("%s", word);
    strcpy(array[i], word);
}

for (k=0; k<3-1; k++){
    for (i=0; i<3-1; i++)
    {
        for (j=0; j<strlen(array[i]); j++)
        {
            // if a letter ascii code is bigger we swap values
            if (array[i][j] > array[i+1][j])
            {
                strcpy(temp, array[i+1]);
                strcpy(array[i+1], array[i]);
                strcpy(array[i], temp);

                j = 999;
            }

            // if a letter ascii code is smaller we stop
            if (array[i][j] < array[i+1][j])
            {
                    j = 999;
            }

        }
    }
}

for (i=0; i<3; i++)
{
    printf("%s\n",array[i]);
}

return 0;
}

Magento: get a static block as html in a phtml file

When you create a new CMS block named block_identifier from the admin panel you can use the following code to call it from your .phtml file:

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml(); 
?> 

Then clear the cache and reload your browser.

add controls vertically instead of horizontally using flow layout

I used a BoxLayout and set its second parameter as BoxLayout.Y_AXIS and it worked for me:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

How can I open a URL in Android's web browser from my application?

The Kotlin answer:

val browserIntent = Intent(Intent.ACTION_VIEW, uri)
ContextCompat.startActivity(context, browserIntent, null)

I have added an extension on Uri to make this even easier

myUri.openInBrowser(context)

fun Uri?.openInBrowser(context: Context) {
    this ?: return // Do nothing if uri is null

    val browserIntent = Intent(Intent.ACTION_VIEW, this)
    ContextCompat.startActivity(context, browserIntent, null)
}

As a bonus, here is a simple extension function to safely convert a String to Uri.

"https://stackoverflow.com".asUri()?.openInBrowser(context)

fun String?.asUri(): Uri? {
    try {
        return Uri.parse(this)
    } catch (e: Exception) {}
    return null
}

Loop in Jade (currently known as "Pug") template engine

for example:

- for (var i = 0; i < 10; ++i) {
  li= array[i]
- }

you may see https://github.com/visionmedia/jade for detailed document.

Content Type text/xml; charset=utf-8 was not supported by service

Again, I stress that namespace, svc name and contract must be correctly specified in web.config file:

 <service name="NAMESPACE.SvcFileName">
    <endpoint contract="NAMESPACE.IContractName" />
  </service>

Example:

<service name="MyNameSpace.FileService">
<endpoint contract="MyNameSpace.IFileService" />
</service>

(Unrelevant tags ommited in these samples)

Fastest way to iterate over all the chars in a String

Just for curiosity and to compare with Saint Hill's answer.

If you need to process heavy data you should not use JVM in client mode. Client mode is not made for optimizations.

Let's compare results of @Saint Hill benchmarks using a JVM in Client mode and Server mode.

Core2Quad Q6600 G0 @ 2.4GHz
JavaSE 1.7.0_40

See also: Real differences between "java -server" and "java -client"?


CLIENT MODE:

len =      2:    111k charAt(i),  105k cbuff[i],   62k new[i],   17k field access.   (chars/ms) 
len =      4:    285k charAt(i),  166k cbuff[i],  114k new[i],   43k field access.   (chars/ms) 
len =      6:    315k charAt(i),  230k cbuff[i],  162k new[i],   69k field access.   (chars/ms) 
len =      8:    333k charAt(i),  275k cbuff[i],  181k new[i],   85k field access.   (chars/ms) 
len =     12:    342k charAt(i),  342k cbuff[i],  222k new[i],  117k field access.   (chars/ms) 
len =     16:    363k charAt(i),  347k cbuff[i],  275k new[i],  152k field access.   (chars/ms) 
len =     20:    363k charAt(i),  392k cbuff[i],  289k new[i],  180k field access.   (chars/ms) 
len =     24:    375k charAt(i),  428k cbuff[i],  311k new[i],  205k field access.   (chars/ms) 
len =     28:    378k charAt(i),  474k cbuff[i],  341k new[i],  233k field access.   (chars/ms) 
len =     32:    376k charAt(i),  492k cbuff[i],  340k new[i],  251k field access.   (chars/ms) 
len =     64:    374k charAt(i),  551k cbuff[i],  374k new[i],  367k field access.   (chars/ms) 
len =    128:    385k charAt(i),  624k cbuff[i],  415k new[i],  509k field access.   (chars/ms) 
len =    256:    390k charAt(i),  675k cbuff[i],  436k new[i],  619k field access.   (chars/ms) 
len =    512:    394k charAt(i),  703k cbuff[i],  439k new[i],  695k field access.   (chars/ms) 
len =   1024:    395k charAt(i),  718k cbuff[i],  462k new[i],  742k field access.   (chars/ms) 
len =   2048:    396k charAt(i),  725k cbuff[i],  471k new[i],  767k field access.   (chars/ms) 
len =   4096:    396k charAt(i),  727k cbuff[i],  459k new[i],  780k field access.   (chars/ms) 
len =   8192:    397k charAt(i),  712k cbuff[i],  446k new[i],  772k field access.   (chars/ms) 

SERVER MODE:

len =      2:     86k charAt(i),   41k cbuff[i],   46k new[i],   80k field access.   (chars/ms) 
len =      4:    571k charAt(i),  250k cbuff[i],   97k new[i],  222k field access.   (chars/ms) 
len =      6:    666k charAt(i),  333k cbuff[i],  125k new[i],  315k field access.   (chars/ms) 
len =      8:    800k charAt(i),  400k cbuff[i],  181k new[i],  380k field access.   (chars/ms) 
len =     12:    800k charAt(i),  521k cbuff[i],  260k new[i],  545k field access.   (chars/ms) 
len =     16:    800k charAt(i),  592k cbuff[i],  296k new[i],  640k field access.   (chars/ms) 
len =     20:    800k charAt(i),  666k cbuff[i],  408k new[i],  800k field access.   (chars/ms) 
len =     24:    800k charAt(i),  705k cbuff[i],  452k new[i],  800k field access.   (chars/ms) 
len =     28:    777k charAt(i),  736k cbuff[i],  368k new[i],  933k field access.   (chars/ms) 
len =     32:    800k charAt(i),  780k cbuff[i],  571k new[i],  969k field access.   (chars/ms) 
len =     64:    800k charAt(i),  901k cbuff[i],  800k new[i],  1306k field access.   (chars/ms) 
len =    128:    1084k charAt(i),  888k cbuff[i],  633k new[i],  1620k field access.   (chars/ms) 
len =    256:    1122k charAt(i),  966k cbuff[i],  729k new[i],  1790k field access.   (chars/ms) 
len =    512:    1163k charAt(i),  1007k cbuff[i],  676k new[i],  1910k field access.   (chars/ms) 
len =   1024:    1179k charAt(i),  1027k cbuff[i],  698k new[i],  1954k field access.   (chars/ms) 
len =   2048:    1184k charAt(i),  1043k cbuff[i],  732k new[i],  2007k field access.   (chars/ms) 
len =   4096:    1188k charAt(i),  1049k cbuff[i],  742k new[i],  2031k field access.   (chars/ms) 
len =   8192:    1157k charAt(i),  1032k cbuff[i],  723k new[i],  2048k field access.   (chars/ms) 

CONCLUSION:

As you can see, server mode is much faster.

How to get the number of characters in a std::string?

if you're using std::string, there are two common methods for that:

std::string Str("Some String");
size_t Size = 0;
Size = Str.size();
Size = Str.length();

if you're using the C style string (using char * or const char *) then you can use:

const char *pStr = "Some String";
size_t Size = strlen(pStr);

Google Maps V3 marker with label

Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.

You can now create your label marker like this:

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(result.latitude, result.longitude), 
  icon: markerIcon,
  label: {
    text: 'A'
  }
});

If you would like to see the 1 character restriction removed, please vote for this issue.

Update October 2016:

This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.

Get UserDetails object from Security Context in Spring MVC controller

Let Spring 3 injection take care of this.

Thanks to tsunade21 the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView anyMethodNameGoesHere(Principal principal) {
        final String loggedInUserName = principal.getName();

 }

"Error 404 Not Found" in Magento Admin Login Page

I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.

But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin

It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Python Extension. From the Python Docs:

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python

https://docs.python.org/3/howto/regex.html

This app won't run unless you update Google Play Services (via Bazaar)

 just change it to 

compile 'com.google.android.gms:play-services-maps:9.6.0'
compile 'com.google.android.gms:play-services-location:9.6.0'

this works for me current version is 10.0.1

TypeScript or JavaScript type casting

This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:

// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;

// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicted with JSX, see the design discussion here.

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

How to AUTO_INCREMENT in db2?

You will have to create an auto-increment field with the sequence object (this object generates a number sequence).

Use the following CREATE SEQUENCE syntax:

  CREATE SEQUENCE seq_person
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1
  CACHE 10

The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.

To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):

  INSERT INTO Persons (P_Id,FirstName,LastName)
  VALUES (seq_person.nextval,'Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".

Applying Comic Sans Ms font style

The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:

http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http

810    style = "body { background-color: white; color: black; font-family: "
811        "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812        "hr { border: 0; border-bottom: 1px dashed; }\n";

E.g., try this:

font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

Count number of lines in a git repository

The best solution, to me anyway, is buried in the comments of @ephemient's answer. I am just pulling it up here so that it doesn't go unnoticed. The credit for this should go to @FRoZeN (and @ephemient).

git diff --shortstat `git hash-object -t tree /dev/null`

returns the total of files and lines in the working directory of a repo, without any additional noise. As a bonus, only the source code is counted - binary files are excluded from the tally.

The command above works on Linux and OS X. The cross-platform version of it is

git diff --shortstat 4b825dc642cb6eb9a060e54bf8d69288fbee4904

That works on Windows, too.

For the record, the options for excluding blank lines,

  • -w/--ignore-all-space,
  • -b/--ignore-space-change,
  • --ignore-blank-lines,
  • --ignore-space-at-eol

don't have any effect when used with --shortstat. Blank lines are counted.

Str_replace for multiple items

You could use preg_replace(). The following example can be run using command line php:

<?php
$s1 = "the string \\/:*?\"<>|";
$s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ;
echo "\n\$s2: \"" . $s2 . "\"\n";
?>

Output:

$s2: "the string          "

Is JavaScript's "new" keyword considered harmful?

Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.

Use of the functionality provided by the new keyword has several advantages over building each object from scratch:

  1. Prototype inheritance. While often looked at with a mix of suspicion and derision by those accustomed to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it.
  2. Performance. This is a side-effect of #1: if I want to add 10 methods to every object I create, I could just write a creation function that manually assigns each method to each new object... Or, I could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.

And yes, new has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:

function foo()
{
   // if user accidentally omits the new keyword, this will 
   // silently correct the problem...
   if ( !(this instanceof foo) )
      return new foo();

   // constructor logic follows...
}

Now you can have the advantages of new without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:

if ( !(this instanceof arguments.callee) ) 
   throw new Error("Constructor called as a function");

(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)

John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.

As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are

  1. define objects in the parent for your model, then reference a property of that object in the child: parentObj.someProp
  2. use $parent.parentScopeProperty (not always possible, but easier than 1. where possible)
  3. define a function on the parent scope, and call it from the child (not always possible)

New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use

<input type="text" ng-model="someObj.prop1">

<!--rather than
<input type="text" ng-model="prop1">`
-->


L-o-n-g answer:

JavaScript Prototypal Inheritance

Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes

It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.

Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:

prototypal inheritance

(Note that to save space, I show the anArray object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)

If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:

childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'

Suppose we then do this:

childScope.aString = 'child string'

The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.

property hiding

Suppose we then do this:

childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'

The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)

follow the prototype chain

Suppose we then do this:

childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }

The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.

more property hiding

Takeaways:

  • If we read childScope.propertyX, and childScope has propertyX, then the prototype chain is not consulted.
  • If we set childScope.propertyX, the prototype chain is not consulted.

One last scenario:

delete childScope.anArray
childScope.anArray[1] === 22  // true

We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.

after removing a child property


Angular Scope Inheritance

The contenders:

  • The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-controller, directive with scope: true, directive with transclude: true.
  • The following creates a new scope which does not inherit prototypically: directive with scope: { ... }. This creates an "isolate" scope instead.

Note, by default, directives do not create new scope -- i.e., the default is scope: false.

ng-include

Suppose we have in our controller:

$scope.myPrimitive = 50;
$scope.myObject    = {aNumber: 11};

And in our HTML:

<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>

<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>

Each ng-include generates a new child scope, which prototypically inherits from the parent scope.

ng-include child scopes

Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.

ng-include with a primitive

Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.

ng-include with an object

We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:

<input ng-model="$parent.myPrimitive">

Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).

ng-include with $parent

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.

For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,

// in the parent scope
$scope.setMyPrimitive = function(value) {
     $scope.myPrimitive = value;
}

Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)

See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.

ng-switch

ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.

See also AngularJS, bind scope of a switch-case?

ng-repeat

Ng-repeat works a little differently. Suppose we have in our controller:

$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects    = [{num: 101}, {num: 202}]

And in our HTML:

<ul><li ng-repeat="num in myArrayOfPrimitives">
       <input ng-model="num">
    </li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
       <input ng-model="obj.num">
    </li>
<ul>

For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:

childScope = scope.$new();  // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value;  // creates a new childScope property

If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num property that is independent of the myArrayOfPrimitives array:

ng-repeat with primitives

This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.

So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num) does change the object the parent scope references. So in the second ng-repeat above, we have:

ng-repeat with objects

(I colored one line gray just so that it is clear where it is going.)

This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.

See also Difficulty with ng-model, ng-repeat, and inputs and https://stackoverflow.com/a/13782671/215945

ng-controller

Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply. However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/ A service should be used to share data between controllers instead.

(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)

directives

  1. default (scope: false) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.
  2. scope: true - the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.
  3. scope: { ... } - the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope. Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp in the isolated scope: <div my-directive> and scope: { localProp: '@parentProp' }. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp> and scope: { localProp: '@theParentProp' }.
    Isolate scope's __proto__ references Object. Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
    For the picture below we have
    <my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2"> and
    scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
    Also, assume the directive does this in its linking function: scope.someIsolateProp = "I'm isolated"
    isolated scope
    For more information on isolate scopes see http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
  4. transclude: true - the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
    For the picture below, assume the same directive as above with this addition: transclude: true
    transcluded scope

This fiddle has a showScope() function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.


Summary

There are four types of scopes:

  1. normal prototypal scope inheritance -- ng-include, ng-switch, ng-controller, directive with scope: true
  2. normal prototypal scope inheritance with a copy/assignment -- ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
  3. isolate scope -- directive with scope: {...}. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.
  4. transcluded scope -- directive with transclude: true. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.

Diagrams were generated with "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

You have two options, import the self-signed cert into java's keystore for each jvm the software will run on or try the non-validating ssl factory:

jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

JavaScript property access: dot notation vs. brackets?

The bracket notation allows you to access properties by name stored in a variable:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello

obj.x would not work in this case.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Just follow these steps:

1) Install eclipse
2) Import Apache to eclipse
3) Install mysql
4) Download mysqlconnector/J
5) Unzip the zipped file navigate through it until you get the bin file in it. Then place all files that are present in the folder containing bin to C:\Program Files\mysql\mysql server5.1/ then give the same path as the address while defining the driver in eclipse.

That's all very easy guys.

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

How to split a delimited string in Ruby and convert it to an array?

>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]

Or for integers:

>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]

Or for later versions of ruby (>= 1.9 - as pointed out by Alex):

>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]

How to apply border radius in IE8 and below IE8 browsers?

PIE makes Internet Explorer 6-9 capable of rendering several of the most useful CSS3 decoration features

http://css3pie.com/

................................................................................

How can I create an object based on an interface file definition in TypeScript?

If you are using React, the parser will choke on the traditional cast syntax so an alternative was introduced for use in .tsx files

let a = {} as MyInterface;

https://www.typescriptlang.org/docs/handbook/jsx.html

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

I got this error message but was a really basic mistake, I had copy/pasted another Component as a template, removed everything from render() then imported it and added it to the parent JSX but hadn't yet renamed the component class. So then the error looked like it was coming from another component which I spent a while trying to debug it before working out it wasn't actually that Component throwing the error! Would have been helpful to have the filename as part of the error message. Hope this helps someone.

Oh a side note note I'm not sure anyone mentioned that returning undefined will throw the error:

render() {
  return this.foo // Where foo is undefined.
}

Make multiple-select to adjust its height to fit options without scroll bar

You can count option tag first, and then set the count for size attribute. For example, in PHP you can count the array and then use a foreach loop for the array.

<?php $count = count($array); ?>
<select size="<?php echo $count; ?>" style="height:100%;">
<?php foreach ($array as $item){ ?>
    <option value="valueItem">Name Item</option>
<?php } ?>
</select>

T-SQL to list all the user mappings with database roles/permissions for a Login

Is this the kind of thing you want? You might want to extend it to get more info out of the sys tables.

use master

DECLARE @name VARCHAR(50) -- database name 

DECLARE db_cursor CURSOR FOR 
select name from sys.databases

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
       print @name
      exec('USE ' +  @name + '; select rp.name, mp.name from sys.database_role_members drm
            join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
            join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)')
       FETCH NEXT FROM db_cursor INTO @name  
END  

CLOSE db_cursor  
DEALLOCATE db_cursor

How do I return the SQL data types from my query?

SELECT COLUMN_NAME,
       DATA_TYPE,
       CHARACTER_MAXIMUM_LENGTH
FROM information_schema.columns
WHERE TABLE_NAME = 'YOUR_TABLE_NAME'

You can use columns aliases for better looking output.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

How do I get the absolute directory of a file in bash?

Problem with the above answer comes with files input with "./" like "./my-file.txt"

Workaround (of many):

    myfile="./somefile.txt"
    FOLDER="$(dirname $(readlink -f "${ARG}"))"
    echo ${FOLDER}

Any way to replace characters on Swift String?

Xcode 11 • Swift 5.1

The mutating method of StringProtocol replacingOccurrences can be implemented as follow:

extension RangeReplaceableCollection where Self: StringProtocol {
    mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
        self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
    }
}

var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Late contribution but just came across something similar in Python datetime and pandas give different timestamps for the same date.

If you have timezone-aware datetime in pandas, technically, tz_localize(None) changes the POSIX timestamp (that is used internally) as if the local time from the timestamp was UTC. Local in this context means local in the specified timezone. Ex:

import pandas as pd

t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="US/Central")
# DatetimeIndex(['2013-05-18 12:00:00-05:00', '2013-05-18 13:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')

t_loc = t.tz_localize(None)
# DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')

# offset in seconds according to timezone:
(t_loc.values-t.values)//1e9
# array([-18000, -18000], dtype='timedelta64[ns]')

Note that this will leave you with strange things during DST transitions, e.g.

t = pd.date_range(start="2020-03-08 01:00:00", periods=2, freq='H', tz="US/Central")
(t.values[1]-t.values[0])//1e9
# numpy.timedelta64(3600,'ns')

t_loc = t.tz_localize(None)
(t_loc.values[1]-t_loc.values[0])//1e9
# numpy.timedelta64(7200,'ns')

In contrast, tz_convert(None) does not modify the internal timestamp, it just removes the tzinfo.

t_utc = t.tz_convert(None)
(t_utc.values-t.values)//1e9
# array([0, 0], dtype='timedelta64[ns]')

My bottom line would be: stick with timezone-aware datetime if you can or only use t.tz_convert(None) which doesn't modify the underlying POSIX timestamp. Just keep in mind that you're practically working with UTC then.

(Python 3.8.2 x64 on Windows 10, pandas v1.0.5.)

Start new Activity and finish current one in Android?

You can use finish() method or you can use:

android:noHistory="true"

And then there is no need to call finish() anymore.

<activity android:name=".ClassName" android:noHistory="true" ... />

Multiplication on command line terminal

For more advanced and precise math consider using bc(1).

echo "3 * 2.19" | bc -l 
6.57

Make A List Item Clickable (HTML/CSS)

Ditch the <a href="...">. Put the onclick (all lowercase) handler on the <li> tag itself.

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

as text:

=CONCATENATE(TEXT(cell;"d");" days ";TEXT(cell;"t");" hours ";MID(TEXT(cell;"hh:mm:ss");4;2);" minutes ";TEXT(cell;"s");" seconds")

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

How to open child forms positioned within MDI parent in VB.NET?

Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.

Sequence contains no elements?

Please use

.FirstOrDefault()

because if in the first row of the result there is no info this instruction goes to the default info.

Jquery $.ajax fails in IE on cross domain calls

@Furqan Could you please let me know whether you tested this with HTTP POST method,

Since I am also working on the same kind of situation, but I am not able to POST the data to different domain.

But after reading this it was quite simple...only thing is you have to forget about OLD browsers. I am giving code to send with POST method from same above URL for quick reference

function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    xhr = null;
}
return xhr;
}

var request = createCORSRequest("POST", "http://www.sanshark.com/");
var content = "name=sandesh&lastname=daddi";
if (request){
    request.onload = function(){
    //do something with request.responseText
   alert(request.responseText);
};

 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", content.length);
            request.send(content);
}

Xcopy Command excluding files and folders

It is same as above answers, but is simple in steps

c:\SRC\folder1

c:\SRC\folder2

c:\SRC\folder3

c:\SRC\folder4

to copy all above folders to c:\DST\ except folder1 and folder2.

Step1: create a file c:\list.txt with below content, one folder name per one line

folder1\

folder2\

Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt