For Windows
pip install mysql-connector
For Ubuntu /Linux
sudo apt-get install python3-pymysql
TL:DR;
List all containers:
docker ps -a
Remove the concerned container by id:
docker container rm <container_id>
Another possible solution specially if you want batch delete
deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3]))
session.execute(deleted_objects)
session.commit()
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
Pandas 0.24.0+ solution
In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
import csv
from io import StringIO
from sqlalchemy import create_engine
def psql_insert_copy(table, conn, keys, data_iter):
# gets a DBAPI connection that can provide a cursor
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join('"{}"'.format(k) for k in keys)
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
table_name, columns)
cur.copy_expert(sql=sql, file=s_buf)
engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)
column_obj != None
will produce a IS NOT NULL
constraint:
In a column context, produces the clause
a != b
. If the target isNone
, produces aIS NOT NULL
.
or use isnot()
(new in 0.7.9):
Implement the
IS NOT
operator.Normally,
IS NOT
is generated automatically when comparing to a value ofNone
, which resolves toNULL
. However, explicit usage ofIS NOT
may be desirable if comparing to boolean values on certain platforms.
Demo:
>>> from sqlalchemy.sql import column
>>> column('YourColumn') != None
<sqlalchemy.sql.elements.BinaryExpression object at 0x10c8d8b90>
>>> str(column('YourColumn') != None)
'"YourColumn" IS NOT NULL'
>>> column('YourColumn').isnot(None)
<sqlalchemy.sql.elements.BinaryExpression object at 0x104603850>
>>> str(column('YourColumn').isnot(None))
'"YourColumn" IS NOT NULL'
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.
You can start by installing the below given command in the conda environment:
conda install pip
Followed by installing all pip packages you need in the environment.
After installing all the conda and pip packages to export the environment use:
conda env export -n <env-name> > environment.yml
This will create the required file in the folder
If you want to avoid tuples, another way is by calling the first
, one
or all
methods:
query = db.engine.execute("SELECT * FROM blogs "
"WHERE id = 1 ")
assert query.first().name == "Welcome to my blog"
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
You likely want to use onupdate=datetime.now
so that UPDATEs also change the last_updated
field.
SQLAlchemy has two defaults for python executed functions.
default
sets the value on INSERT, only onceonupdate
sets the value to the callable result on UPDATE as well.Query for just a single known column:
session.query(MyTable.col1).count()
Here is mine. Just in case if you are using "pymysql":
import pymysql
from pandas import DataFrame
host = 'localhost'
port = 3306
user = 'yourUserName'
passwd = 'yourPassword'
db = 'yourDatabase'
cnx = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
cur = cnx.cursor()
query = """ SELECT * FROM yourTable LIMIT 10"""
cur.execute(query)
field_names = [i[0] for i in cur.description]
get_data = [xx for xx in cur]
cur.close()
cnx.close()
df = DataFrame(get_data)
df.columns = field_names
An example here:
movies = Movie.query.filter(Movie.rating != 0).order_by(desc(Movie.rating)).all()
I query the db for movies with rating <> 0, and then I order them by rating with the higest rating first.
Take a look here: Select, Insert, Delete in Flask-SQLAlchemy
I faced the same problem. Turns out I forgot to install the following package:
pip install flask_sqlalchemy
After installing the package, everything worked perfectly. Hope, it helped some other noob like me.
I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6
and whose no_of_logins == 30
when you start.
# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?
If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1
, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:
# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
from app import SQLAlchemyDB as db
Chance.query.filter(Chance.repo_id==repo_id,
Chance.status=="1",
db.func.date(Chance.apply_time)<=end,
db.func.date(Chance.apply_time)>=start).count()
it is equal to:
select
count(id)
from
Chance
where
repo_id=:repo_id
and status='1'
and date(apple_time) <= end
and date(apple_time) >= start
wish can help you.
Assuming you use the declarative style (i.e. ORM classes), it is pretty easy:
query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()
db_session
is your database session here, while User
is the ORM class with __tablename__
equal to "users"
.
or_()
function can be useful in case of unknown number of OR query components.
For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_()
function we must do something like this:
query = Book.query
if filter.title and filter.author:
query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
query = query.filter(Book.author.ilike(filter.author))
With or_()
function it can be rewritten to:
query = Book.query
not_null_filters = []
if filter.title:
not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
not_null_filters.append(Book.author.ilike(filter.author))
if len(not_null_filters) > 0:
query = query.filter(or_(*not_null_filters))
assuming certain column names...
INSERT one
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.commit()
INSERT multiple
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.commit()
UPDATE
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.commit()
or using a fancy one-liner using MERGE
record = dbsession.merge(Toner( **kwargs))
I work with a lot of systems that have been mucked by developers "following directions they found on the Internet". It is extremely common that your pip
and your python
are not looking at the same paths/site-packages. For this reason, when I encounter oddness I start by doing this:
$ python -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']
$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
That is a happy system.
Below is an unhappy system. (Or at least it's a blissfully ignorant system that causes others to be unhappy.)
$ pip --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)
$ python -c 'import sys; print(sys.path)'
['', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']
$ which pip pip2 pip3
/usr/local/bin/pip
/usr/local/bin/pip3
It is unhappy because pip
is (python3.6 and) using /usr/local/lib/python3.6/site-packages
while python
is (python2.7 and) using /usr/local/lib/python2.7/site-packages
When I want to make sure I'm installing requirements to the right python, I do this:
$ which -a python python2 python3
/usr/local/bin/python
/usr/bin/python
/usr/local/bin/python2
/usr/local/bin/python3
$ /usr/bin/python -m pip install -r requirements.txt
You've heard, "If it ain't broke, don't try to fix it." The DevOps version of that is, "If you didn't break it and you can work around it, don't try to fix it."
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 dict
s:
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 @property
s, 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()))
Just assigning the value and committing them will work for all the data types but JSON and Pickled attributes. Since pickled type is explained above I'll note down a slightly different but easy way to update JSONs.
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
data = db.Column(db.JSON)
def __init__(self, name, data):
self.name = name
self.data = data
Let's say the model is like above.
user = User("Jon Dove", {"country":"Sri Lanka"})
db.session.add(user)
db.session.flush()
db.session.commit()
This will add the user into the MySQL database with data {"country":"Sri Lanka"}
Modifying data will be ignored. My code that didn't work is as follows.
user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
db.session.merge(user)
db.session.flush()
db.session.commit()
Instead of going through the painful work of copying the JSON to a new dict (not assigning it to a new variable as above), which should have worked I found a simple way to do that. There is a way to flag the system that JSONs have changed.
Following is the working code.
from sqlalchemy.orm.attributes import flag_modified
user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
flag_modified(user, "data")
db.session.merge(user)
db.session.flush()
db.session.commit()
This worked like a charm. There is another method proposed along with this method here Hope I've helped some one.
How about using classes?
# config.py
class MYSQL:
PORT = 3306
DATABASE = 'mydb'
DATABASE_TABLES = ['tb_users', 'tb_groups']
# main.py
from config import MYSQL
print(MYSQL.PORT) # 3306
Expanding on Abdul's answer, you can obtain a KeyedTuple
instead of a discrete collection of rows by joining the columns:
q = Session.query(*User.__table__.columns + Document.__table__.columns).\
select_from(User).\
join(Document, User.email == Document.author).\
filter(User.email == 'someemail').all()
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
.
The built in serializer chokes with utf-8 cannot decode invalid start byte for some inputs. Instead, I went with:
def row_to_dict(row):
temp = row.__dict__
temp.pop('_sa_instance_state', None)
return temp
def rows_to_list(rows):
ret_rows = []
for row in rows:
ret_rows.append(row_to_dict(row))
return ret_rows
@website_blueprint.route('/api/v1/some/endpoint', methods=['GET'])
def some_api():
'''
/some_endpoint
'''
rows = rows_to_list(SomeModel.query.all())
response = app.response_class(
response=jsonplus.dumps(rows),
status=200,
mimetype='application/json'
)
return response
As @snapshoe says
flush()
sends your SQL statements to the database
commit()
commits the transaction.
When session.autocommit == False
:
commit()
will call flush()
if you set autoflush == True
.
When session.autocommit == True
:
You can't call commit()
if you haven't started a transaction (which you probably haven't since you would probably only use this mode to avoid manually managing transactions).
In this mode, you must call flush()
to save your ORM changes. The flush effectively also commits your data.
Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:
.order_by(model.Entry.amount.desc())
This is handy since it avoids an import
, and you can use it on other places such as in a relation definition, etc.
For more information, you can refer this
SQLAlchemy introduced that in version 1.0.0
:
Bulk operations - SQLAlchemy docs
With these operations, you can now do bulk inserts or updates!
For instance (if you want the lowest overhead for simple table INSERTs), you can use Session.bulk_insert_mappings()
:
loadme = [(1, 'a'),
(2, 'b'),
(3, 'c')]
dicts = [dict(bar=t[0], fly=t[1]) for t in loadme]
s = Session()
s.bulk_insert_mappings(Foo, dicts)
s.commit()
Or, if you want, skip the loadme
tuples and write the dictionaries directly into dicts
(but I find it easier to leave all the wordiness out of the data and load up a list of dictionaries in a loop).
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)))
Each column has like()
method, which can be used in query.filter()
. Given a search string, add a %
character on either side to search as a substring in both directions.
tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()
You can also declare it HTML safe from the code:
from flask import Markup
value = Markup('<strong>The HTML String</strong>')
Then pass that value to the templates and they don't have to |safe
it.
You can easily import your model and run this:
from models import User
# User is the name of table that has a column name
users = User.query.all()
for user in users:
print user.name
Django makes great use of inversion of control. For instance, the database server is selected by the configuration file, then the framework provides appropriate database wrapper instances to database clients.
The difference is that Python has first-class types. Data types, including classes, are themselves objects. If you want something to use a particular class, simply name the class. For example:
if config_dbms_name == 'postgresql':
import psycopg
self.database_interface = psycopg
elif config_dbms_name == 'mysql':
...
Later code can then create a database interface by writing:
my_db_connection = self.database_interface()
# Do stuff with database.
Instead of the boilerplate factory functions that Java and C++ need, Python does it with one or two lines of ordinary code. This is the strength of functional versus imperative programming.
filter_by
uses keyword arguments, whereas filter
allows pythonic filtering arguments like filter(User.name=="john")
In general, you can pass any query to mysql
from shell with -e option.
mysql -u username -p -D dbname -e "DROP DATABASE dbname"
You could try to do it in this way.
for u in session.query(User).all():
print(u._asdict())
It use a built-in method in the query object that return a dictonary object of the query object.
references: https://docs.sqlalchemy.org/en/latest/orm/query.html
You can also count on multiple groups and their intersection:
self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()
The query above will return counts for all possible combinations of values from both columns.
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)
Datatable.Clone
is slow for large tables. I'm currently using this:
Dim target As DataTable =
New DataView(source, "1=2", Nothing, DataViewRowState.CurrentRows)
.ToTable()
Note that this only copies the structure of source table, not the data.
You can create a base class with @RequestMapping("rest")
annotations and extend all you other classes with this base class.
@RequestMapping("rest")
public abstract class BaseController {}
Now all classes that extend this base class will be accessible at rest/**
.
If you do not want to compile it yourself you can go to:
Applications?Ubuntu Software Center?Edit?Software Sources?Updates
there you can check hardy-proposed is ticked(for 14.10 will be utopic-proposed)
Source
then simply go to terminal and type:
sudo apt-get install mysql-workbench
As a note, you will get other updates to, witch may not be stable!!!
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
A little late to this party. I agree that Pylot is the best up-and-coming open source tool out there. It's simple to use and is actively worked on by a great guy (Corey Goldberg). As the founder of OpenQA, I'm also happy that Pylot now is listed on our home page and uses some of our infrastructure (namely the forums).
However, I also recently decided that the entire concept of load testing was flawed: emulating HTTP traffic, with applications as complex as they have become, is a pain in the butt. That's why I created the commercial tool BrowserMob. It's an external load testing service that uses Selenium to control real web browsers when playing back load.
The approach obviously requires a ton more hardware than normal load testing techniques, but hardware is actually pretty cheap when you are using cloud computing. And a nice side effect of this is that the scripting is much easier than normal load testing. You don't have to do any advanced regex matching (like JMeter requires) to extract out cookies, .NET session state, Ajax request parameters, etc. Since you're using real browsers, they just do what they are supposed to do.
Sorry to blatantly pitch a commercial product, but hopefully the concept is interesting to some folks and at least gets them thinking about some new ways to deal with load testing when you have access to a bunch of extra hardware!
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
Here is a code snippet taken from a blog article written by Anubhav Goyal:
// this code will mark the forms authentication cookie and the
// session cookie as Secure.
if (Response.Cookies.Count > 0)
{
foreach (string s in Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || "asp.net_sessionid".Equals(s, StringComparison.InvariantCultureIgnoreCase))
{
Response.Cookies[s].Secure = true;
}
}
}
Adding this to the EndRequest event handler in the global.asax should make this happen for all page calls.
Note: An edit was proposed to add a break;
statement inside a successful "secure" assignment. I've rejected this edit based on the idea that it would only allow 1 of the cookies to be forced to secure and the second would be ignored. It is not inconceivable to add a counter or some other metric to determine that both have been secured and to break at that point.
Don't use grep. Download Silver Searcher or ripgrep. They're both outstanding, and way faster than grep or ack with tons of options.
You can use the react-moment package
-> https://www.npmjs.com/package/react-moment
Put in your file the next line:
import moment from "moment";
date_create: moment().format("DD-MM-YYYY hh:mm:ss")
Right-click the title-bar icon of the Explorer window. You'll get the current folder's context menu, where you'll find the "command window here" item.
(Note that to see that menu item, you need to have the corresponding "power toy" installed, or you can create the right registry keys yourself to add that item to folders' context menus.)
Had a similar need. $compile
does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)
http://jsbin.com/ebuhuv/7/edit - my exploration test.
One thing to note (per my example), one of my requirements was that the template would change based on a type
attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.
This updates the answers with the latest Fetch API and doesn't need jQuery.
Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.
Basic Fetch
It could be as simple as:
fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
.then(response => console.log(response.text()))
Fetch with Error Handling
After adding error handling, it could look like:
fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
.then(response => {
if (response.ok) return response;
else throw Error(`Server returned ${response.status}: ${response.statusText}`)
})
.then(response => console.log(response.text()))
.catch(err => {
alert(err);
});
PHP Code
This is the server-side code in upload.php.
<?php
// gets entire POST body
$data = file_get_contents('php://input');
// write the data out to the file
$fp = fopen("path/to/file", "wb");
fwrite($fp, $data);
fclose($fp);
?>
This post is right from SAP on Sep 20, 2012.
In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.
If you want to download that version you can find it here.
Further, service packs etc. when released can be found here.
I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.
Just use format(number, qtyDecimals) sample: format(1000, 2) result 1000.00
Another method for checking equality regardless of value order works by using http://php.net/manual/en/function.array-intersect.php, like so:
$array1 = array(2,5,3);
$array2 = array(5,2,3);
if($array1 === array_intersect($array1, $array2) && $array2 === array_intersect($array2, $array1)) {
echo 'Equal';
} else {
echo 'Not equal';
}
Here's a version that works also with multidimensional arrays using http://php.net/manual/en/function.array-uintersect.php:
$array1 = array(
array(5, 2),
array(3, 6),
array(2, 9, 4)
);
$array2 = array(
array(3, 6),
array(2, 9, 4),
array(5, 2)
);
if($array1 === array_uintersect($array1, $array2, 'compare') && $array2 === array_uintersect($array2, $array1, 'compare')) {
echo 'Equal';
} else {
echo 'Not equal';
}
function compare($v1, $v2) {
if ($v1===$v2) {
return 0;
}
if ($v1 > $v2) return 1;
return -1;
}
the simple way is passing through constructor
RadioButton radioButton = new RadioButton(this,null,R.style.radiobutton_material_quiz);
You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.
You can start with something like this:
<form name="someform"enctype="multipart/form-data" action="uploader.php" method="POST">
<input type=file name="file1" />
<input type=button onclick="val()" value="xxxx" />
</form>
<script>
function val() {
alert(document.someform.file1.value)
}
</script>
I agree with alexmac - do it server-side as well.
I had a similar issue, but had painted myself into a corner with GUI tools.
I had a subproject with a few files in it that I had so far just copied around instead of checking into their own git repo. I created a repo in the subfolder, was able to commit, push, etc just fine. But in the parent repo the subfolder wasn't treated as a submodule, and its files were still being tracked by the parent repo - no good.
To get out of this mess I had to tell Git to stop tracking the subfolder (without deleting the files):
proj> git rm -r --cached ./ui/jslib
Then I had to tell it there was a submodule there (which you can't do if anything there is currently being tracked by git):
proj> git submodule add ./ui/jslib
The ideal way to handle this involves a couple more steps. Ideally, the existing repo is moved out to its own directory, free of any parent git modules, committed and pushed, and then added as a submodule like:
proj> git submodule add [email protected]:user/jslib.git ui/jslib
That will clone the git repo in as a submodule - which involves the standard cloning steps, but also several other more obscure config steps that git takes on your behalf to get that submodule to work. The most important difference is that it places a simple .git file there, instead of a .git directory, which contains a path reference to where the real git dir lives - generally at parent project root .git/modules/jslib.
If you don't do things this way they'll work fine for you, but as soon as you commit and push the parent, and another dev goes to pull that parent, you just made their life a lot harder. It will be very difficult for them to replicate the structure you have on your machine so long as you have a full .git dir in a subfolder of a dir that contains its own .git dir.
So, move, push, git add submodule, is the cleanest option.
The form
element has an autocomplete
attribute that you can set to off
. As of the CSS the !important
directive after a property keeps it from being overriden:
background-color: white !important;
Only IE6 doesn't understand it.
If I misunderstood you, there's also the outline
property that you could find useful.
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
In a pinch, just type 'notepad (filename)' and notepad will pop up with the file you want to edit in it. Otherwise Vim or some such will have to be installed.
Here is a hack to disable "paste" popup. You have to override EditText
method:
@Override
public int getSelectionStart() {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getMethodName().equals("canPaste")) {
return -1;
}
}
return super.getSelectionStart();
}
Similar can be done for the other actions.
Or, the file is of a filetype and/or architecture that you just cannot run with your hardware and/or there is also no fallback binfmt_misc entry to handle the particular format in some other way. Use file(1)
to determine.
I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();" without explicit user action to turn off Bluetooth.
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
bluetooth.disable();
I only used the below permission.
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
You can use the event.target.result to reset the input from a component directly.
event.target.value = ""
You could look into psh here: http://gnp.github.io/psh/
It's a full on shell (you can use it in replacement of bash for example), but uses perl syntax.. so you can create methods on the fly etc.
To start it right after installation, I generate a batch file with installutil followed by sc start
It's not ideal, but it works....
If you don't want to use List:
var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
You could try this extension method that I haven't actually tested:
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
And use it like:
Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);
Some DBMSs will let you use an alias instead of having to repeat the entire expression.
Teradata is one such example.
I avoid ordinal position notation as recommended by Bill for reasons documented in this SO question.
The easy and robust alternative is to always repeat the expression in the GROUP BY clause.
DRY does NOT apply to SQL.
An initial
keyword is being added in CSS3 to allow authors to explicitly specify this initial value.
Set the session.save_path
in your php.ini
. Make sure that you are using an existing directory.
If still you found any issue then give write & execution permission to that folder for the user by which you are going to use that folder.[This is specially used in case of IIS]
Will output the tag of the latest tagged commit across all branches
git describe --tags $(git rev-list --tags --max-count=1)
Have a look at this archived question: TortoiseSVN for Mac? at superuser. (Original question was removed, so only archive remains.)
Have a look at this page for more likely up to date alternatives to TortoiseSVN for Mac: Alternative to: TortoiseSVN
does
$('#elem').css('-webkit-transition','none !important');
in your js kill it?
obviously repeat for each.
If you're hosting website on a specific port in IIS like 4321 then you'd have to allow this port through Windows Firewall too. Here're the steps that I followed along with the imanabidi's answer to get it work for me:
As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:
System.Drawing.Image.PropertyItems Property
I say "it’s the most flexible" because .NET does not try to interpret or coalesce the data in any way. For each EXIF you basically get an array of bytes. This may be good or bad depending on how much control you actually want.
Also, I should point out that the property list does not in fact directly correspond to the EXIF values. EXIF itself is stored in multiple tables with overlapping ID’s, but .NET puts everything in one list and redefines ID’s of some items. But as long as you don’t care about the precise EXIF ID’s, you should be fine with the .NET mapping.
Edit: It's possible to do it without loading the full image following this answer: https://stackoverflow.com/a/552642/2097240
You should be able to use \n
inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n
for proper formatting like so:
var example: String = "Hello World \nThis is a new line"
Which, if printed to the console, should become:
Hello World
This is a new line
However, there are some other considerations to make depending on how you will be using this string, such as:
\r\n
instead, which is the Windows newline.Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.
You are not changing the value of line. It should be something like this.
import java.io.BufferedReader;
import java.io.FileReader;
public class InsertValuesIntoTestDb {
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("test.csv"));
while((line = br.readLine()) != null){
String[] b = line.split(splitBy);
System.out.println(b[0]);
}
br.close();
}
}
readLine returns each line and only returns null when there is nothing left. The above code sets line and then checks if it is null.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
Or, you could use the margin attribute like this:
{
background:#222;
width:100%;
height:100px;
margin-left: 10px;
margin-right: 10px;
display:block;
}
In case someone is interested, I was looking for something similar and ended writing the following:
public static string NormalizeStringForUrl(string name)
{
String normalizedString = name.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();
foreach (char c in normalizedString)
{
switch (CharUnicodeInfo.GetUnicodeCategory(c))
{
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.DecimalDigitNumber:
stringBuilder.Append(c);
break;
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.DashPunctuation:
stringBuilder.Append('_');
break;
}
}
string result = stringBuilder.ToString();
return String.Join("_", result.Split(new char[] { '_' }
, StringSplitOptions.RemoveEmptyEntries)); // remove duplicate underscores
}
You need to first change the constraint and then animate the update.
This should be in the superview.
self.nameInputConstraint.constant = 8
Swift 2
UIView.animateWithDuration(0.5) {
self.view.layoutIfNeeded()
}
Swift 3, 4, 5
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
Just to add up my bit:
Remember, you're gonna need to have at least 2 areas in your MVC application to get the routeValues: { area="" }
working; otherwise the area value will be used as a query-string parameter and you link will look like this: /?area=
If you don't have at least 2 areas, you can fix this behavior by:
1. editing the default route in RouteConfig.cs
like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
OR
2. Adding a dummy area to your MVC project.
If you have the option pre-existing in a fixed-with <select>
, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.
title
attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE
For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php
$datetime = "20130409163705";
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want
Result:
09/04/2013 16:37:05
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.
Use this code:
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
finish();
context: refer to current activity context,
please make sure that you have added activity in android manifest file.
Following code for adding activity in android manifest file
<Activity name=".SecondActivity">
</Activity>
dancavallaro has it right, %*
for all command line parameters (excluding the script name itself). You might also find these useful:
%0
- the command used to call the batch file (could be foo
, ..\foo
, c:\bats\foo.bat
, etc.)
%1
is the first command line parameter,
%2
is the second command line parameter,
and so on till %9
(and SHIFT
can be used for those after the 9th).
%~nx0
- the actual name of the batch file, regardless of calling method (some-batch.bat)
%~dp0
- drive and path to the script (d:\scripts)
%~dpnx0
- is the fully qualified path name of the script (d:\scripts\some-batch.bat)
More info examples at https://www.ss64.com/nt/syntax-args.html and https://www.robvanderwoude.com/parameters.html
You can use reset_index
to turn the index back into a column:
monthly_mean.reset_index().plot(x='index', y='A')
This blog shows how to update the registry so the Android SDK can find your Java SDK on a 64-bit machine.
http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/
This worked for me:
DELETE from m_productprice
WHERE m_pricelist_version_id='1000020'
AND m_product_id IN (SELECT m_product_id
FROM m_product
WHERE upc = '7094');
I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :
[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...
A more functional approach would be by using dict.get
input_nums = [int(in_str) for in_str in input_str.split())
strikes = list(map(number_map.get, input_nums.split()))
One can observe that the conversion is a little clumsy, better would be to use the abstraction of function composition:
def compose2(f, g):
return lambda x: f(g(x))
strikes = list(map(compose2(number_map.get, int), input_str.split()))
Example:
list(map(compose2(number_map.get, int), ["1", "2", "7"]))
Out[29]: [-3, -2, None]
Obviously in Python 3 you would avoid the explicit conversion to a list
. A more general approach for function composition in Python can be found here.
(Remark: I came here from the Design of Computer Programs Udacity class, to write:)
def word_score(word):
"The sum of the individual letter point scores for this word."
return sum(map(POINTS.get, word))
I solved that deleting the Gemfile.lock
if you are using bootstrap u can just use the hidden-sm ( lg or md or xs) depending on what u want. u can then go into the css file and specify the percentages u want it to show on. in the sample below it will be hiding on large screens, medium ones and extra small ones but show on small screens by taking half of the screen.
<div class="col-sm-12 hidden-lg hidden-md hidden-xs">what ever you want</div>
I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.
If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth
and element.offsetHeight
.
db.zipcodes.find({city : "NEW YORK"}); // Case-sensitive
db.zipcodes.find({city : /NEW york/i}); // Note the 'i' flag for case-insensitivity
random.uniform(a, b)
appears to be what your looking for. From the docs:
Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
See here.
Apostrophes in the strings.xml should be written as
\'
In my case I had an error with this string in my strings.xml and I fixed it.
<item>Most arguments can be ended with three words, "I don\'t care".</item>
Here you see my app builds properly with that code.
Here is the actual string in my app.
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
The trick of appending "*" can be made to work when the new extension is shorter. You need to pad the new extension with blanks, which can only be done by enclosing the destination file name in quotes. For example:
xcopy foo.shtml "foo.html *"
This will copy and rename without prompting.
"That's not a bug, it's a feature!" (I once saw a VW Beetle in the Microsoft parking lot with the vanity plate "FEATURE".) These semantics for rename go all the way back to when I wrote DOS v.1. Characters in the new name are substituted one by one for characters in the old name, unless a wildcard character (? or *) is present in the new name. Without adding the blank(s) to the new name, remaining characters are copied from the old name.
SELECT author FROM lyrics WHERE author LIKE 'B%';
Make sure you have an index on author
, though!
$http
service returns a promise
which has two callback methods as shown below.
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'filename.csv'
})[0].click();
}).
error(function(data, status, headers, config) {
// handle error
});
You may have to use =IF(ISNUMBER(A1),A1,1)
in some situations where you are looking for number values in cell.
Highlight the cell, use Dat => Text to Columns and the DELIMITER is space. Result will appear in as many columns as the split find the space.
Solution for your example code using PowerMockito.whenNew
FooTest.java
package foo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
//Both @PrepareForTest and @RunWith are needed for `whenNew` to work
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Foo.class })
public class FooTest {
// Class Under Test
Foo cut;
@Mock
Bar barMock;
@Before
public void setUp() throws Exception {
cut = new Foo();
}
@After
public void tearDown() {
cut = null;
}
@Test
public void testFoo() throws Exception {
// Setup
PowerMockito.whenNew(Bar.class).withNoArguments()
.thenReturn(this.barMock);
// Test
cut.foo();
// Validations
Mockito.verify(this.barMock, Mockito.times(1)).someMethod();
}
}
As of January 31, 2013 Github markdown supports relative links to files.
[a relative link](markdown_file.md)
However, there are a few deficiencies that have been discussed in this comment thread.
As an alternative, you can use Gitdown to construct full URLs to the repository and even make them branch aware, e.g.
{"gitdown": "gitinfo", "name": "url"} // https://github.com/gajus/gitdown
{"gitdown": "gitinfo", "name": "branch"} // master
Gitdown is a GitHub markdown preprocessor. It streamlines common tasks associated with maintaining a documentation page for a GitHub repository, e.g. generating table of contents, including variables, generating URLs and getting information about the repository itself at the time of processing the input. Gitdown seamlessly integrates with your building scripts.
I am the author of the Gitdown library.
And an idea with a negative check.
/^(?!\d*$|[a-z]*$)[a-z\d]+$/i
^(?!
at start look ahead if string does not\d*$
contain only digits |
or[a-z]*$
contain only letters[a-z\d]+$
matches one or more letters or digits until $
end.Have a look at this regex101 demo
(the i
flag turns on caseless matching: a-z
matches a-zA-Z
)
Simple:
if(pll_current_language() == 'en'){
//do your work here
}
Styling checkboxes (and many other input elements for that mater) is not really possible with pure css if you want to drastically change the visual appearance.
Your best bet is to implement something like jqTransform does which actually replaces you inputs with images and applies javascript behaviour to it to mimic a checkbox (or other element for that matter)
The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.
Launch Powershell or CMD, enter ssh yourAccountName@diskstation
The first time it will cache off your certificate.
Further detailed explanations can be found on the synology docs page:
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
Kenny is right, just want to clear some things out.
border.xml
and put it in the folder res/drawable/
add the code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
set back ground like android:background="@drawable/border"
wherever you want the border
Mine first didn't work cause i put the border.xml
in the wrong folder!
I have a plunker that adds it to the string prototype: string.format It is not just as short as some of the other examples, but a lot more flexible.
Usage is similar to c# version:
var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy");
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array
Also, added support for using names & object properties
var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"});
//result: Meet you on Thursday, ask for Frank
I think this table is short and usefull:
Supplier () -> x
Consumer x -> ()
Callable () -> x throws ex
Runnable () -> ()
Function x -> y
BiFunction x,y -> z
Predicate x -> boolean
UnaryOperator x1 -> x2
BinaryOperator x1,x2 -> x3
As said on the other answers, the appropriate option for this problem is a Runnable
Loop through the dictionary to find the index and then remove it.
Assuming the question is about a DOMString as input and the goal is to get an Array, that when interpreted as string (e.g. written to a file on disk), would be UTF-8 encoded:
Now that nearly all modern browsers support Typed Arrays, it'd be ashamed if this approach is not listed:
.readAsArrayBuffer()
function of a File ReaderExample:
// Create a Blob with an Euro-char (U+20AC)
var b = new Blob(['€']);
var fr = new FileReader();
fr.onload = function() {
ua = new Uint8Array(fr.result);
// This will log "3|226|130|172"
// E2 82 AC
// In UTF-16, it would be only 2 bytes long
console.log(
fr.result.byteLength + '|' +
ua[0] + '|' +
ua[1] + '|' +
ua[2] + ''
);
};
fr.readAsArrayBuffer(b);
Play with that on JSFiddle. I haven't benchmarked this yet but I can imagine this being efficient for large DOMStrings as input.
Disclaimer: the following answer is for git before git 2.13. For git 2.13 and over, check out another answer further down.
Warning
As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.
This will stash everything that you haven't previously added. Just git add
the things you want to keep, then run it.
git stash --keep-index
For example, if you want to split an old commit into more than one changeset, you can use this procedure:
git rebase -i <last good commit>
edit
.git reset HEAD^
git add <files you want to keep in this change>
git stash --keep-index
git add
any changes.git commit
git stash pop
git rebase --continue
Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.@#]/;
I'm going to take a guess. I think the column name that contains "Number"
is something like " Number"
or "Number "
. Notice that I'm assuming you might have a residual space in the column name somewhere. Do me a favor and run print "<{}>".format(data.columns[1])
and see what you get. Is it something like < Number>
? If so, then my guess was correct. You should be able to fix it with this:
data.columns = data.columns.str.strip()
Return false from the anonymous function:
$(xml).find("strengths").each(function() {
// Code
// To escape from this block based on a condition:
if (something) return false;
});
From the documentation of the each method:
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).
l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.
Here is the latest simplest solution - no need to change anything, just add three lines of CSS rules to your container of the div where you wish to center at. I love Flex Box
#LoveFlexBox
.main {_x000D_
/* I changed height to 200px to make it easy to see the alignment. */_x000D_
height: 200px;_x000D_
vertical-align: middle;_x000D_
border: 1px solid #000000;_x000D_
padding: 2px;_x000D_
_x000D_
/* Just add the following three rules to the container of which you want to center at. */_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
/* This is true vertical center, no math needed. */_x000D_
}_x000D_
.inner {_x000D_
border: 1px solid #000000;_x000D_
}_x000D_
.second {_x000D_
border: 1px solid #000000;_x000D_
}
_x000D_
<div class="main">_x000D_
<div class="inner">This box should be centered in the larger box_x000D_
<div class="second">Another box in here</div>_x000D_
</div>_x000D_
<div class="inner">This box should be centered in the larger box_x000D_
<div class="second">Another box in here</div>_x000D_
</div>_x000D_
</div>
_x000D_
Bonus
the justify-content
value can be set to the following few options:
flex-start
, which will align the child div to where the flex flow starts in its parent container. In this case, it will stay on top.
center
, which will align the child div to the center of its parent container. This is really neat, because you don't need to add an additional div to wrap around all children to put the wrapper in a parent container to center the children. Because of that, this is the true vertical center (in the column
flex-direction
. similarly, if you change the flow-direction
to row
, it will become horizontally centered.
flex-end
, which will align the child div to where the flex flow ends in its parent container. In this case, it will move to bottom.
space-between
, which will spread all children from the beginning of the flow to the end of the flow. If the demo, I added another child div, to show they are spread out.
space-around
, similar to space-between
, but with half of the space in the beginning and end of the flow.
Also, consider to use a repository manager such as Nexus and configure all your repositories there.
1. From Package Explorer
open the Filters...
dialog:
2. Then uncheck .* resources
option:
As of Chrome 52, the UI has changed. When the Developer Tools dialog is open, you select the vertical ellipsis and can then choose the docking position:
Select the icon on the left to open the Chrome Developer Tools in a new window:
Click and hold the button next to the close button of the Developer Tool in order to reveal the "Undock into separate window" option.
Note: A "press" is not enough in that state.
To get the headers as an object which is handier (improvement of Raja's answer):
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
if (b.length) {
var [ key, value ] = b.split(': ');
a[key] = value;
}
return a;
}, {});
console.log(headers);
You can use process monitor written by Mark Russinovich. This is a fantastic little application that will allow you to attach to any running process on the system and see all of the system calls that process is currently making.
https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx
A Bean is a POJO(Plain Old Java Object), which is managed by the spring container.
Spring containers create only one instance of the bean by default. ?This bean it is cached in memory so all requests for the bean will return a shared reference to the same bean.
The @Bean annotation returns an object that spring registers as a bean in application context.?The logic inside the method is responsible for creating the instance.
When do we use @Bean annotation?
When automatic configuration is not an option. For example when we want to wire components from a third party library, because the source code is not available so we cannot annotate the classes with @Component.
A Real time scenario could be that someone wants to connect to Amazon S3 bucket. Because the source is not available he would have to create a @bean.
@Bean
public AmazonS3 awsS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsKeyId, accessKey);
return AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(region))
.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
}
Source for the code above -> https://www.devglan.com/spring-mvc/aws-s3-java
Because I mentioned @Component Annotation above.
@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and class path scanning.
Component annotation registers the class as a single bean.
You can chain as much conditions as you want. If you do:
var x = (false)?("1true"):((true)?"2true":"2false");
You will get x="2true"
So it could be expressed as:
var variable = (condition) ? (true block) : ((condition)?(true block):(false block))
You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid">Save</button>
</form>
In case you have a dump made with sqlplus and the output is garbled as someone did not set those 3 values before, there's a way out.
Just a couple hours ago DB admin send me that ugly looking output of query executed in sqlplus (I dunno, maybe he hates me...). I had to find a way out: this is an awk script to parse that output to make it at least more readable. It's far not perfect, but I did not have enough time to polish it properly. Anyway, it does the job quite well.
awk ' function isDashed(ln){return ln ~ /^---+/};function addLn(){ln2=ln1; ln1=ln0;ln0=$0};function isLoaded(){return l==1||ln2!=""}; function printHeader(){hdr=hnames"\n"hdash;if(hdr!=lastHeader){lastHeader=hdr;print hdr};hnames="";hdash=""};function isHeaderFirstLn(){return isDashed(ln0) && !isDashed(ln1) && !isDashed(ln2) }; function isDataFirstLn(){return isDashed(ln2)&&!isDashed(ln1)&&!isDashed(ln0)} BEGIN{_d=1;h=1;hnames="";hdash="";val="";ln2="";ln1="";ln0="";fheadln=""} { addLn(); if(!isLoaded()){next}; l=1; if(h==1){if(!isDataFirstLn()){if(_d==0){hnames=hnames" "ln1;_d=1;}else{hdash=hdash" "ln1;_d=0}}else{_d=0;h=0;val=ln1;printHeader()}}else{if(!isHeaderFirstLn()){val=val" "ln1}else{print val;val="";_d=1;h=1;hnames=ln1}} }END{if(val!="")print val}'
In case anyone else would like to try improve this script, below are the variables: hnames -- column names in the header, hdash - dashed below the header, h -- whether I'm currently parsing header (then ==1), val -- the data, _d - - to swap between hnames and hdash, ln0 - last line read, ln1 - line read previously (it's the one i'm actually working with), ln2 - line read before ln1
Happy parsing!
Oh, almost forgot... I use this to prettify sqlplus output myself:
[oracle@ora ~]$ cat prettify_sql
set lines 256
set trimout on
set tab off
set pagesize 100
set colsep " | "
colsep is optional, but it makes output look like sqlite which is easier to parse using scripts.
EDIT: A little preview of parsed and non-parsed output
I had this problem when trying to consume a value returned from a stored procedure.
console.log(result[0]);
would output "[ RowDataPacket { datetime: '2019-11-15 16:37:05' } ]".
I found that
console.log(results[0][0].datetime);
Gave me the value I wanted.
No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.
If you want to use AJAX, the easiest way will be to utilise jQuery:
$.post("someScript.php", function(data) {
console.log(data); //"data" contains whatever someScript.php returned
});
If everything you want to drop is owned by the same user, then you can use:
drop owned by the_user;
This will drop everything that the user owns.
That includes materialized views, views, sequences, triggers, schemas, functions, types, aggregates, operators, domains and so on (so, really: everything) that the_user
owns (=created).
You have to replace the_user
with the actual username, currently there is no option to drop everything for "the current user". The upcoming 9.5 version will have the option drop owned by current_user
.
More details in the manual: http://www.postgresql.org/docs/current/static/sql-drop-owned.html
I guess you want to do the "Iterating over Keys and Values"
As the doc here says, just add "|keys" in the variable you want and it will magically happen.
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}
It never hurts to search before asking :)
@Iulian Pinzaru's answer was almost exactly what I needed, but it doesn't work if your objects have any null values. This version fixes that.
function deepSearch (object, key, predicate) {
if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) return object
for (let i = 0; i < Object.keys(object).length; i++) {
const nextObject = object[Object.keys(object)[i]];
if (nextObject && typeof nextObject === "object") {
let o = deepSearch(nextObject, key, predicate)
if (o != null) return o
}
}
return null
}
//Get
var bla = $('#txt_name').val();
//Set
$('#txt_name').val(bla);
FYI: The other solutions will only log statements from the default database—usually postgres
—to log others; start with their solution; then:
ALTER DATABASE your_database_name
SET log_statement = 'all';
Based on the answer given by @LazerBanana i will put my own example of a Set sorted by the Id of the Object:
Set<Clazz> yourSet = [...];
yourSet.stream().sorted(new Comparator<Clazz>() {
@Override
public int compare(Clazz o1, Clazz o2) {
return o1.getId().compareTo(o2.getId());
}
}).collect(Collectors.toList()); // Returns the sorted List (using toSet() wont work)
Works in all modern browsers
.rotate{
animation: loading 3s linear infinite;
@keyframes loading {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
}
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
Change visible="false"
to style="visibility:hidden"
on your tags..
or better use a class to show/hide the labels..
.hidden{
visibility:hidden;
}
then on your labels add class="hidden"
and with your script remove the class
document.getElementById("endTimeLabel").className = 'hidden'; // to hide
and
document.getElementById("endTimeLabel").className = ''; // to show
Peter's post is pretty much spot on, but if you want to learn how to navigate to it yourself here are the instructions:
On the left hand menu, you need to click "more", then you'll see "Developer", click on it. Afterwards you'll be presented with a page where your apps are listed under "My Applications" click on "See my applications". You can find all your API Key, secrets, and IDs there.
AppDomain.UnhandledException Event
This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.
public App()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.
For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.
Visual Studio 2015:
Project
=>
Your Application Properties
. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.
static void Main(string[] args)
{
if(args == null || args.Length == 0)
{
Console.WriteLine("Please specify arguments!");
}
else
{
Console.WriteLine(args[0]); // First
Console.WriteLine(args[1]); // Second Argument
}
}
Do it like this:
Go to Settings -> General -> Profiles - tap on your Profile - tap on the Trust button.
but iOS10 has a little change,
Users should go to Settings - General - Device Management - tap on your Profile - tap on Trust button.
Reference: iOS10AdaptationTips
Here is a script that will do it for you .....
You can add a list of users (or just one user) if you want, all in one go and each will have a different password. As a bonus you are presented at the end of the script with a list of each users password. .... If you want you can add some user maintenance options
like:
chage -m 18 $user
chage -M 28 $user
to the script that will set the password age and so on.
=======
#!/bin/bash
# Checks if you have the right privileges
if [ "$USER" = "root" ]
then
# CHANGE THIS PARAMETERS FOR A PARTICULAR USE
PERS_HOME="/home/"
PERS_SH="/bin/bash"
# Checks if there is an argument
[ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
# checks if there a regular file
[ -f "$1" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
TMPIN=$(mktemp)
# Remove blank lines and delete duplicates
sed '/^$/d' "$1"| sort -g | uniq > "$TMPIN"
NOW=$(date +"%Y-%m-%d-%X")
LOGFILE="AMU-log-$NOW.log"
for user in $(more "$TMPIN"); do
# Checks if the user already exists.
cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
OUT=$?
if [ $OUT -eq 0 ];then
echo >&2 "ERROR: User account: \"$user\" already exists."
echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
else
# Create a new user
/usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
# passwdgen must be installed
pass=$(passwdgen -paq --length 8)
echo $pass | passwd --stdin $user
# save user and password in a file
echo -e $user"\t"$pass >> "$LOGFILE"
echo "The user \"$user\" has been created and has the password: $pass"
fi
done
rm -f "$TMPIN"
exit 0
else
echo >&2 "ERROR: You must be a root user to execute this script."
exit 1
fi
===========
Hope this helps.
Cheers, Carel
The user comments on the array_unique() documentation have many solutions to this. Here is one of them:
kenrbnsn at rbnsn dot com
27-Sep-2005 12:09Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.
This function uses the serialize, array_unique, and unserialize functions to do the work.
function multi_unique($array) { foreach ($array as $k=>$na) $new[$k] = serialize($na); $uniq = array_unique($new); foreach($uniq as $k=>$ser) $new1[$k] = unserialize($ser); return ($new1); }
This is from http://ca3.php.net/manual/en/function.array-unique.php#57202.
Go to /opt/google/chrome
.
Open google-chrome
.
Append current home for data directory. Replace this:
exec -a "$0" "$HERE/chrome" "$@"
With this:
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir $HOME
For reference visit site this site, “How to run chrome as root user in Ubuntu.”
See https://github.com/php-pm/php-pm.
Works fine with symphony.
But I'm fighting with it, trying run a slim app
The problem is that you don't have a route for /
. Change your definition to this:
ShopMyShopBundle_homepage:
pattern: /
defaults: { _controller: ShopMyShopBundle:Main:index }
requirements:
_method: GET
You could also use server side script and set javascript variables from it.
Example in php
download http://code.google.com/p/php-mobile-detect/ and then set javascript variables.
<script>
//set defaults
var device_type = 'desktop';
</script>
<?php
require_once( 'Mobile_Detect.php');
$detect = new Mobile_Detect();
?>
<script>
device_type="<?php echo ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'mobile') : 'desktop'); ?>";
alert( device_type);
</script>
The answer of 'ChrisG' is correct, but we need to refresh MainWindowTitle every time and it's better to check for empty.... like this:
var proc = Process.Start("popup.exe");
while (string.IsNullOrEmpty(proc.MainWindowTitle))
{
System.Threading.Thread.Sleep(100);
proc.Refresh();
}
you can declare a Numpy array dynamically for 1 dimension as shown below:
import numpy as np
n = 2
new_table = np.empty(shape=[n,1])
new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)
The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)
output is shown below:
[[2.] [3.]]
I like to stick with the standard meaning of the words used: An article
would apply to, well, articles. I would define blog posts, documents, and news articles as articles
. Sections on the other hand, would refer to layout/ux items: sidebar, header, footer would be sections. However this is all my own personal interpretation -- as you pointed out, the specification for these elements are not well defined.
Supporting this, the w3c defines an article
element as a section of content that can independently stand on its own. A blog post could stand on it's own as a valuable and consumable item of content. However, a header would not.
Here is an interesting article about one mans madness in trying to differenciate between the two new elements. The basic point of the article, that I also feel is correct, is to try and use what ever element you feel best actually represents what it contains.
What’s more problematic is that article and section are so very similar. All that separates them is the word “self-contained”. Deciding which element to use would be easy if there were some hard and fast rules. Instead, it’s a matter of interpretation. You can have multiple articles within a section, you can have multiple sections within and article, you can nest sections within sections and articles within sections. It’s up to you to decide which element is the most semantically appropriate in any given situation.
Here is a very good answer to the same question here on SO
React Router V5
If you want the pathName as a string ('/' or 'users'), you can use the following:
// React Hooks: React Router DOM
let history = useHistory();
const location = useLocation();
const pathName = location.pathname;
Sure you can query your Database with SHOW TABLES
and then loop through all the records but that is extra code lines and work.
PHP has a built in function to list all tables into an array for you :
mysql_list_tables - you can find more information about it at The PHP API page
If you just want to read an image in Python using the specified libraries only, I will go with
matplotlib
In matplotlib :
import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')
Another way to check on connection attempts is to look at the server's event log. On my Windows 2008 R2 Enterprise machine I opened the server manager (right-click on Computer and select Manage. Then choose Diagnostics -> Event Viewer -> Windows Logs -> Applcation. You can filter the log to isolate the MSSQLSERVER events. I found a number that looked like this
Login failed for user 'bogus'. The user is not associated with a trusted SQL Server connection. [CLIENT: 10.12.3.126]
AppCompat
supportOther answers suspecting if android:tint
will work on only 21+ devices only, AppCompat(v23.2.0 and above) now provides a backward compatible handling of tint attribute.
So, the course of action would be to use AppCompatImageView
and app:srcCompat
(in AppCompat namespace) instead of android:src
(Android namespace).
Here is an example(AndroidX: This is androidx.appcompat.widget.AppCompatImageView ;)):
<android.support.v7.widget.AppCompatImageView
android:id="@+id/credits_material_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:scaleType="fitCenter"
android:tint="#ffd2ee"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:srcCompat="@drawable/ic_dollar_coin_stack" />
And don't forget to enable vector drawable support in gradle:
vectorDrawables.useSupportLibrary = true
The answer is yes, if you write return statement the controls goes back to to the caller method immediately. With an exception of finally block, which gets executed after the return statement.
and finally can also override the value you have returned, if you return inside of finally block. LINK: Try-catch-finally-return clarification
Return Statement definition as per:
Java Docs:
a return statement can be used to branch out of a control flow block and exit the method
MSDN Documentation:
The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.
Wikipedia:
A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address. The return address is saved, usually on the process's call stack, as part of the operation of making the subroutine call. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.
Simple, time based, without dependencies:
(new Date()).getTime().toString(36)
Output: jzlatihl
plus random number (Thanks to @Yaroslav Gaponov's answer)
(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
Output jzlavejjperpituute
Try this
Dim app As Excel.Application = Nothing
Dim Active_Cell As Excel.Range = Nothing
Try
app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
Active_Cell = app.ActiveCell
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
' .address will return the cell reference :)
For anyone like me finding this question the following might be useful.
I had a similar problem and initially tried using location.go and location.replaceState as suggested in other answers here. However I ran into problems when I had to navigate to another page on the app because the navigation was relative to the current route and the current route wasn't being updated by location.go or location.replaceState (the router doesn't know anything about what these do to the URL)
In essence I needed a solution that DIDN'T reload the page/component when the route parameter changed but DID update the route state internally.
I ended up using query parameters. You can find more about it here: https://angular-2-training-book.rangle.io/handout/routing/query_params.html
So if you need to do something like save an order and get an order ID you can update your page URL like shown below. Updating a centre location and related data on a map would be similar
// let's say we're saving an order. Initally the URL is just blah/orders
save(orderId) {
// [Here we would call back-end to save the order in the database]
this.router.navigate(['orders'], { queryParams: { id: orderId } });
// now the URL is blah/orders?id:1234. We don't reload the orders
// page or component so get desired behaviour of not seeing any
// flickers or resetting the page.
}
and you keep track of it within the ngOnInit method like:
ngOnInit() {
this.orderId = this.route
.queryParamMap
.map(params => params.get('id') || null);
// orderID is up-to-date with what is saved in database now, or if
// nothing is saved and hence no id query paramter the orderId variable
// is simply null.
// [You can load the order here from its ID if this suits your design]
}
If you need to go direct to the order page with a new (unsaved) order you can do:
this.router.navigate(['orders']);
Or if you need to go direct to the order page for an existing (saved) order you can do:
this.router.navigate(['orders'], { queryParams: { id: '1234' } });
You can omit the import statements and refer to them using the entire path. Eg:
java.util.Date javaDate = new java.util.Date()
my.own.Date myDate = new my.own.Date();
But I would say that using two classes with the same name and a similiar function is usually not the best idea unless you can make it really clear which is which.
I just wanted to add, that you can also use de-structuring to refactor the code and make it look neater.
inputChangeHandler: function ({ target: { id, value }) {
this.setState({ [id]: value });
},
Using pure bash :
$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt
another solution with bash regex :
$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
echo ${BASH_REMATCH[1]}
another solution using grep
and look-around advanced regex :
$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"
another solution using sed :
$ echo "US/Central - 10:26 PM (CST)" |
sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'
another solution using perl :
$ echo "US/Central - 10:26 PM (CST)" |
perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'
and last one using awk :
$ echo "US/Central - 10:26 PM (CST)" |
awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'
I don't know this for sure, but I think this is supposed to be handled by the browser based on the user's date/time settings. Try setting your computer to display dates in that format.
The symbol you posted is the placeholder symbol for a broken byte sequence. Basically, it's not a real symbol but an error in your string.
What is the exact byte value of the symbol? Blindly applying utf8_encode is not a good idea, it's better to find out first where the byte(s) came from and what they mean.
I solved this by adding .to_json
and some heading information
@result = HTTParty.post(@urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
There are some good examples of doing this over at the R Wiki. I'll steal a couple here:
Merge Method
Since your keys are named the same the short way to do an inner join is merge():
merge(df1,df2)
a full inner join (all records from both tables) can be created with the "all" keyword:
merge(df1,df2, all=TRUE)
a left outer join of df1 and df2:
merge(df1,df2, all.x=TRUE)
a right outer join of df1 and df2:
merge(df1,df2, all.y=TRUE)
you can flip 'em, slap 'em and rub 'em down to get the other two outer joins you asked about :)
Subscript Method
A left outer join with df1 on the left using a subscript method would be:
df1[,"State"]<-df2[df1[ ,"Product"], "State"]
The other combination of outer joins can be created by mungling the left outer join subscript example. (yeah, I know that's the equivalent of saying "I'll leave it as an exercise for the reader...")
my solution is:
That all, hope it works for you
CTRL-W >
and
CTRL-W <
to make the window wider or narrower.
None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.
If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.
See this page with information on how to create a user style
In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
Speed comparion (using Wouter's method)
In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))
In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop
In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop
You need to create a comparator. I am not sure why each value needs its own map but here is what the comparator would look like:
class ListMapComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
Map<String, String> test1 = (Map<String, String>) obj1;
Map<String, String> test2 = (Map<String, String>) obj2;
return test1.get("name").compareTo(test2.get("name"));
}
}
You can see it working with your above example with this:
public class MapSort {
public List<Map<String, String>> testMap() {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> myMap1 = new HashMap<String, String>();
myMap1.put("name", "Josh");
Map<String, String> myMap2 = new HashMap<String, String>();
myMap2.put("name", "Anna");
Map<String, String> myMap3 = new HashMap<String, String>();
myMap3.put("name", "Bernie");
list.add(myMap1);
list.add(myMap2);
list.add(myMap3);
return list;
}
public static void main(String[] args) {
MapSort ms = new MapSort();
List<Map<String, String>> testMap = ms.testMap();
System.out.println("Before Sort: " + testMap);
Collections.sort(testMap, new ListMapComparator());
System.out.println("After Sort: " + testMap);
}
}
You will have some type safe warnings because I did not worry about these. Hope that helps.
Here it was caused by avast antivirus. You can disable the avast firewall and let only windows firewall active.
You can do:
for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done
Make sure the file finalfile.txt
does not exist before you run the above command.
If you are allowed to use awk
you can do:
awk 'FNR==1{print ""}1' *.txt > finalfile.txt
Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!
DEFAULT
is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL
constraint:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'
Then you could issue these statements
-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);
-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);
-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;
-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);
Alternatively, you can also use DEFAULT
in UPDATE
statements, according to the SQL-1992 standard:
-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;
-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;
Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL
constraint will cause an error with statements 4, 6
, while 1-3, 5
are still valid statements. So to answer your question: No, they're not redundant.
I used this and works for me.
<div class="col-sm-3">
<img src="xxx.png" style="width: auto; height: 195px;">
</div>
Short answer
The purpose of meshgrid
is to help remplace Python loops (slow interpreted code) by vectorized operations within C NumPy library.
Borrowed from this site.
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
meshgrid
is used to create pairs of coordinates between -4 and +4 with .25 increments in each direction X and Y. Each pair is then used to find R, and Z from it. This way of preparing "a grid" of coordinates is frequently used in plotting 3D surfaces, or coloring 2D surfaces.
Details: Python for-loop vs NumPy vector operation
To take a more simple example, let's say we have two sequences of values,
a = [2,7,9,20]
b = [1,6,7,9] ?
and we want to perform an operation on each possible pair of values, one taken from the first list, one taken from the second list. We also want to store the result. For example, let's say we want to get the sum of the values for each possible pair.
Slow and laborious method
c = []
for i in range(len(b)):
row = []
for j in range(len(a)):
row.append (a[j] + b[i])
c.append (row)
print (c)
Result:
[[3, 8, 10, 21],
[8, 13, 15, 26],
[9, 14, 16, 27],
[11, 16, 18, 29]]
Python is interpreted, these loops are relatively slow to execute.
Fast and easy method
meshgrid
is intended to remove the loops from the code. It returns two arrays (i and j below) which can be combined to scan all the existing pairs like this:
i,j = np.meshgrid (a,b)
c = i + j
print (c)
Result:
[[ 3 8 10 21]
[ 8 13 15 26]
[ 9 14 16 27]
[11 16 18 29]]
Meshgrid under the hood
The two arrays prepared by meshgrid
are:
(array([[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20]]),
array([[1, 1, 1, 1],
[6, 6, 6, 6],
[7, 7, 7, 7],
[9, 9, 9, 9]]))
These arrays are created by repeating the values provided. One contains the values in identical rows, the other contains the other values in identical columns. The number of rows and column is determined by the number of elements in the other sequence.
The two arrays created by meshgrid
are therefore shape compatible for a vector operation. Imagine x and y sequences in the code at the top of page having a different number of elements, X and Y resulting arrays will be shape compatible anyway, not requiring any broadcast.
Origin
numpy.meshgrid
comes from MATLAB, like many other NumPy functions. So you can also study the examples from MATLAB to see meshgrid
in use, the code for the 3D plotting looks the same in MATLAB.
A while
loop can be simulated in cmd.exe
with:
:still_more_files
if %countfiles% leq 21 (
rem change countfile here
goto :still_more_files
)
For example, the following script:
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 0"
:more_to_process
if %x% leq 5 (
echo %x%
set /a "x = x + 1"
goto :more_to_process
)
endlocal
outputs:
0
1
2
3
4
5
For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:
@echo off
set backupdir=c:\test
:more_files_to_process
for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
if %num% gtr 20 (
cscript /nologo c:\deletefile.vbs %backupdir%
goto :more_files_to_process
)
As of 2020, using ContentResult
is still the right approach as proposed above, but the usage is as follows:
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ?",
ContentType = "text/plain; charset=utf-8"
}
Other method by using pandas
import pandas as pd
LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])
You can then export results in any format you want
This will do:
▢
It is ?
(known as a "WHITE SQUARE WITH ROUNDED CORNERS" on fileformat.info)
Or
◻
as ?
(known as a "WHITE MEDIUM SQUARE" on the same website)
Two with shadow:
❏
❑
as ? and ? . The difference between them is the shadows' shape. You can see it if you zoom in or if you print it out. (They are known as "LOWER RIGHT DROP-SHADOWED WHITE SQUARE" and "LOWER RIGHT SHADOWED WHITE SQUARE", respectively).
You can also use
☐
which is ?
(known as a "BALLOT BOX").
A sample is at http://jsfiddle.net/S2QCt/267/
(a note: on the Mac, ▢
is quite nice, because it is bigger and somewhat more elegant than ☐
On Windows, ☐
looks more standard, while ▢
is somewhat small.)
The accepted answer (as of 2019 JULY 29) is only still valid if you have not started using the more recent SVG-with-JS approach of FontAwesome. In which case you need to follow the instructions on their CSS Pseudo-Elements HowTo. Basically there are three things to watch out for:
Update PHP 7.4
Curly brace access syntax is deprecated since PHP 7.4
Update 2019
Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.
Simply iterate its using {}
Example:
$videos{0}->id
This way your object is not destroyed and you can easily iterate through object.
For PHP 5.6 and below use this
$videos{0}['id']
Both array() and the stdClass objects can be accessed using the
current()
key()
next()
prev()
reset()
end()
functions.
So, if your object looks like
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
Then you can just do;
$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object
If you need the key for some reason, you can do;
reset($obj); //Ensure that we're at the first element
$key = key($obj);
Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4
2022 Update:
After PHP 7.4, using current()
, end()
, etc functions on objects is deprecated.
In newer versions of PHP, use the ArrayIterator class:
$objIterator = new ArrayIterator($obj);
$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object
$key = $objIterator->key(); // and gets the key
I have also discovered that, when using JNI, invoking a Java method from C++, if you pass parameters to the invoked Java method in the wrong order, you will get this error when you attempt to use the parameters inside the called method (because they won't be the right type). I was initially taken aback that JNI does not do this checking for you as part of the class signature checking when you invoke the method, but I assume they don't do this kind of checking because you may be passing polymorphic parameters and they have to assume you know what you are doing.
Example C++ JNI Code:
void invokeFooDoSomething() {
jobject javaFred = FredFactory::getFred(); // Get a Fred jobject
jobject javaFoo = FooFactory::getFoo(); // Get a Foo jobject
jobject javaBar = FooFactory::getBar(); // Get a Bar jobject
jmethodID methodID = getDoSomethingMethodId() // Get the JNI Method ID
jniEnv->CallVoidMethod(javaFoo,
methodID,
javaFred, // Woops! I switched the Fred and Bar parameters!
javaBar);
// << Insert error handling code here to discover the JNI Exception >>
// ... This is where the IncompatibleClassChangeError will show up.
}
Example Java Code:
class Bar { ... }
class Fred {
public int size() { ... }
}
class Foo {
public void doSomething(Fred aFred, Bar anotherObject) {
if (name.size() > 0) { // Will throw a cryptic java.lang.IncompatibleClassChangeError
// Do some stuff...
}
}
}
If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none
Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:
If you found display of [hidden] class is overridden, you need to add this css code to your style:
[hidden] {
display: none !important;
}
I was initially running:
sudo scp
Once I ran just scp
, without sudo
, it copied everything fine:
scp
It seems to me that sudo scp
command wasn't reading my current user's SSH public key at ~/.ssh/id_rsa.pub
.
By using to_string
print(df.Name.to_string(index=False))
Adam
Bob
Cathy
REASSIGN OWNED
commandNote: As @trygvis mentions in the answer below, the REASSIGN OWNED
command is available since at least version 8.2, and is a much easier method.
Since you're changing the ownership for all tables, you likely want views and sequences too. Here's what I did:
Tables:
for tbl in `psql -qAt -c "select tablename from pg_tables where schemaname = 'public';" YOUR_DB` ; do psql -c "alter table \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done
Sequences:
for tbl in `psql -qAt -c "select sequence_name from information_schema.sequences where sequence_schema = 'public';" YOUR_DB` ; do psql -c "alter sequence \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done
Views:
for tbl in `psql -qAt -c "select table_name from information_schema.views where table_schema = 'public';" YOUR_DB` ; do psql -c "alter view \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done
You could probably DRY that up a bit since the alter statements are identical for all three.
You need to create a query (in Visual Studio, right-click on the DB connection -> New Query) and execute the following SQL:
ALTER TABLE tblAlpha
ADD CONSTRAINT MyConstraint FOREIGN KEY (FK_id) REFERENCES
tblGamma(GammaID)
ON UPDATE CASCADE
To verify that your foreign key was created, execute the following SQL:
SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
Credit to E Jensen (http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=532377&SiteID=1)
If you're using prefill and signed chars, be careful not to append unwanted 'F's
char out_character = 0xBE;
cout << setfill('0') << setw(2) << hex << unsigned short(out_character);
prints: ffbe
using int instead of short results in ffffffbe
To prevent the unwanted f's you can easily mask them out.
char out_character = 0xBE;
cout << setfill('0') << setw(2) << hex << unsigned short(out_character) & 0xFF;
The package directory states that xgboost is unstable for windows and is disabled:
pip installation on windows is currently disabled for further invesigation, please install from github.
In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:
$ curl https://api.twitter.com/1/help/configuration.xml | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool
Tested on Ubuntu 11.0.4/11.10.
Another issue is the desired content type. Twitter uses .xml
/.json
extension, but more idiomatic REST would require Accept
header:
$ curl -H "Accept: application/json"
Is the Config/setup.php
file actually in /test/content/home/
or is in your document root? it is best to make all references relative to your document root.
include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";
Your current code assumes that the location of setup.php
is in /text/content/home/Config/setup.php
, is this correct?
Yes:
<input required title="Enter something OR ELSE." />
The title
attribute will be used to notify the user of a problem.
You can use parameters like that
<jsp:include page='about.jsp'>
<jsp:param name="articleId" value=""/>
</jsp:include>
and
in about.jsp you can take the paramter
<%String leftAds = request.getParameter("articleId");%>
From your service method:
function serviceMethod() {
return $timeout(function() {
return {
property: 'value'
};
}, 1000);
}
And in your controller:
serviceName
.serviceMethod()
.then(function(data){
//handle the success condition here
var x = data.property
});
Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.
<maven.test.skip>false</maven.test.skip>
A similar question has been asked on the Google group: http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/e6448fc197c3c892
The zoom levels are discrete, with the scale doubling in each step. So in general you cannot fit the bounds you want exactly (unless you are very lucky with the particular map size).
Another issue is the ratio between side lengths e.g. you cannot fit the bounds exactly to a thin rectangle inside a square map.
There's no easy answer for how to fit exact bounds, because even if you are willing to change the size of the map div, you have to choose which size and corresponding zoom level you change to (roughly speaking, do you make it larger or smaller than it currently is?).
If you really need to calculate the zoom, rather than store it, this should do the trick:
The Mercator projection warps latitude, but any difference in longitude always represents the same fraction of the width of the map (the angle difference in degrees / 360). At zoom zero, the whole world map is 256x256 pixels, and zooming each level doubles both width and height. So after a little algebra we can calculate the zoom as follows, provided we know the map's width in pixels. Note that because longitude wraps around, we have to make sure the angle is positive.
var GLOBE_WIDTH = 256; // a constant in Google's map projection
var west = sw.lng();
var east = ne.lng();
var angle = east - west;
if (angle < 0) {
angle += 360;
}
var zoom = Math.round(Math.log(pixelWidth * 360 / angle / GLOBE_WIDTH) / Math.LN2);
I know this is old, but for those surfing this question, the answer by MUG4N will align all columns that use the same defaultcellstyle. I'm not using autogeneratecolumns so that is not acceptable. Instead I used:
e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
In this case e
is from:
Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
Although I'm answering it very late but it might help someone else. To inject headers to all requests when @NgModule
is used, one can do the following:
(I tested this in Angular 2.0.1)
/**
* Extending BaseRequestOptions to inject common headers to all requests.
*/
class CustomRequestOptions extends BaseRequestOptions {
constructor() {
super();
this.headers.append('Authorization', 'my-token');
this.headers.append('foo', 'bar');
}
}
Now in @NgModule
do the following:
@NgModule({
declarations: [FooComponent],
imports : [
// Angular modules
BrowserModule,
HttpModule, // This is required
/* other modules */
],
providers : [
{provide: LocationStrategy, useClass: HashLocationStrategy},
// This is the main part. We are telling Angular to provide an instance of
// CustomRequestOptions whenever someone injects RequestOptions
{provide: RequestOptions, useClass: CustomRequestOptions}
],
bootstrap : [AppComponent]
})
Add the useUnifiedTopology option and set it to true.
Set other 3 configuration of the mongoose.connect options which will deal with other remaining DeprecationWarning.
This configuration works for me!
const url = 'mongodb://localhost:27017/db_name';
mongoose.connect(
url,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
}
)
This will solve 4 DeprecationWarning.
findOneAndUpdate()
and findOneAndDelete()
without the useFindAndModify
option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-.Hope it helps.
You can check if the index of the selected value is 0 or -1 using the selectedIndex
property.
In your case 0 is also not a valid index value because its the "placeholder":
<option value="selectcard">--- Please select ---</option>
function Validate()
{
var combo = document.getElementById("cardtype");
if(combo.selectedIndex <=0)
{
alert("Please Select Valid Value");
}
}
Just follow these steps:
Always while adding a fragment,
fragmentTransaction.add(R.id.fragment_container, detail_fragment, "Fragment_tag").addToBackStack(null).commit();
Then in the main activity, override onBackPressed()
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
finish();
}
To handle the back button in your app,
Fragment f = getActivity().getSupportFragmentManager().findFragmentByTag("Fragment_tag");
if (f instanceof FragmentName) {
if (f != null)
getActivity().getSupportFragmentManager().beginTransaction().remove(f).commit()
}
That's it!
Just think of it as the keyword params
in C#, if you are coming from that background :)
If you want to add a query parameter after you have created the request, try casting the HttpRequest
to a HttpBaseRequest
. Then you can change the URI of the casted request:
HttpGet someHttpGet = new HttpGet("http://google.de");
URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
"That was easy!").build();
((HttpRequestBase) someHttpGet).setURI(uri);
Swift 3.0+
Left padding String
extension similar to padding(toLength:withPad:startingAt:)
in Foundation
extension String {
func leftPadding(toLength: Int, withPad: String = " ") -> String {
guard toLength > self.characters.count else { return self }
let padding = String(repeating: withPad, count: toLength - self.characters.count)
return padding + self
}
}
Usage:
let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"
Why not just
private double translateSlider(int sliderval) {
if(sliderval > 4 || sliderval < 0)
return 1.0d;
return (1.0d - ((double)sliderval/10.0d));
}
Or similar?
I think I got it. It's:
"SVN Client Path" /command:update / path:"My folder path"
Mac OS: You have to install ChromeDriver first:
brew cask install chromedriver
It will be copied to /usr/local/bin/chromedriver. Then you can use it in java code classes.
To select the item from the contextual menu, you have to just move your mouse positions with the use of Key down event like this:-
Actions action= new Actions(driver);
action.contextClick(productLink).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
hope this will works for you. Have a great day :)
int bigNumber = 1234567;
String formattedNumber = String.format("%,d", bigNumber);
I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2
.
You can set a default style for the entire workbook (all worksheets):
$objPHPExcel->getDefaultStyle()
->getBorders()
->getTop()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getBottom()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getLeft()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getRight()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
or
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);
And this can be used for all style properties, not just borders.
But column autosizing is structural
rather than stylistic
, and has to be set for each column on each worksheet individually.
EDIT
Note that default workbook style only applies to Excel5 Writer
Have you tried mysql_ping()?
Update: From PHP 5.5 onwards, use mysqli_ping() instead.
Pings a server connection, or tries to reconnect if the connection has gone down.
if ($mysqli->ping()) { printf ("Our connection is ok!\n"); } else { printf ("Error: %s\n", $mysqli->error); }
Alternatively, a second (less reliable) approach would be:
$link = mysql_connect('localhost','username','password');
//(...)
if($link == false){
//try to reconnect
}
Iif you want a particular <canvas id="canvasID">
to be always transparent you just have to set
#canvasID{
opacity:0.5;
}
Instead, if you want some particular elements inside the canvas area to be transparent, you have to set transparency when you draw, i.e.
context.fillStyle = "rgba(0, 0, 200, 0.5)";
To remove item you need to remove it from array and can pass bday
item to your remove function in markup. Then in controller look up the index of item and remove from array
<a class="btn" ng-click="remove(item)">Delete</a>
Then in controller:
$scope.remove = function(item) {
var index = $scope.bdays.indexOf(item);
$scope.bdays.splice(index, 1);
}
Angular will automatically detect the change to the bdays
array and do the update of ng-repeat
DEMO: http://plnkr.co/edit/ZdShIA?p=preview
EDIT: If doing live updates with server would use a service you create using $resource
to manage the array updates at same time it updates server
This is a function that takes a hex string and returns a UIColor.
(You can enter hex strings with either format: #ffffff
or ffffff
)
Usage:
var color1 = hexStringToUIColor("#d3d3d3")
Swift 5: (Swift 4+)
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
Swift 3:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
Swift 2:
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
}
if ((cString.characters.count) != 6) {
return UIColor.grayColor()
}
var rgbValue:UInt32 = 0
NSScanner(string: cString).scanHexInt(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
Source: arshad/gist:de147c42d7b3063ef7bc
Edit: Updated the code. Thanks, Hlung, jaytrixz, Ahmad F, Kegham K, and Adam Waite!
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
You can change the port while you open your XAMP control panel, follow the steps:
httpd.conf
, a text file will openlisten:80
,listen:80
replace with listen:8080
andOnce done that, you will be able to start your local server.
Might be the below GitHUb url will help you, to get the answer. Actually, Application Server like Tomcat, Weblogic denying the HTTP.DELETE call with request payload. So keeping these all things in mind, I have added example in github,please have a look into that
This error means that, while linking, compiler is not able to find the definition of main()
function anywhere.
In your makefile, the main
rule will expand to something like this.
main: producer.o consumer.o AddRemove.o
gcc -pthread -Wall -o producer.o consumer.o AddRemove.o
As per the gcc
manual page, the use of -o
switch is as below
-o file Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If
-o
is not specified, the default is to put an executable file ina.out
.
It means, gcc will put the output in the filename provided immediate next to -o
switch. So, here instead of linking all the .o
files together and creating the binary [main
, in your case], its creating the binary as producer.o
, linking the other .o
files. Please correct that.
Depends on the extension. If it's .html, you can use <?
to start and ?>
to end a comment. That's really the only alternative that I can think of. http://jsfiddle.net/SuEAW/
Following worked for me..
for a table say, 'test_update_cmd', source value column col2, target value column col1 and condition column col3: -
UPDATE test_update_cmd SET col1=col2 WHERE col3='value';
Good Luck!
Basically an index on a table works like an index in a book (that's where the name came from):
Let's say you have a book about databases and you want to find some information about, say, storage. Without an index (assuming no other aid, such as a table of contents) you'd have to go through the pages one by one, until you found the topic (that's a full table scan
).
On the other hand, an index has a list of keywords, so you'd consult the index and see that storage
is mentioned on pages 113-120,231 and 354. Then you could flip to those pages directly, without searching (that's a search with an index, somewhat faster).
Of course, how useful the index will be, depends on many things - a few examples, using the simile above:
The opposite of Raymond's solution:
sed -n '/^#/!p'
"don't print anything, except for lines that DON'T start with #"
The difference between <pluginManagement/>
and <plugins/>
is that a <plugin/>
under:
<pluginManagement/>
defines the settings for plugins that will be inherited by modules in your build. This is great for cases where you have a parent pom file.
<plugins/>
is a section for the actual invocation of the plugins. It may or may not be inherited from a <pluginManagement/>
.
You don't need to have a <pluginManagement/>
in your project, if it's not a parent POM. However, if it's a parent pom, then in the child's pom, you need to have a declaration like:
<plugins>
<plugin>
<groupId>com.foo</groupId>
<artifactId>bar-plugin</artifactId>
</plugin>
</plugins>
Notice how you aren't defining any configuration. You can inherit it from the parent, unless you need to further adjust your invocation as per the child project's needs.
For more specific information, you can check:
The Maven pom.xml reference: Plugins
The Maven pom.xml reference: Plugin Management
Use Context.getDatabasePath(databasename). The context can be obtained from your application.
If you get previous data back it can be either a) the data was stored in an unconventional location and therefore not deleted with uninstall or b) Titanium backed up the data with the app (it can do that).
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
var ar = 'foo bar spam egg'.split(/\W/);
for(var i=0; i<ar.length; i++) {
ar[i] = ar[i].substr(0,1).toUpperCase() + ar[i].substr(1,ar[i].length-1)
}
ar.join(' '); // Foo Bar Spam Egg
Here’s the modern answer (valid from 2014 and on). The accepted answer was a very fine answer in 2011. These days I recommend no one uses the Date
, DateFormat
and SimpleDateFormat
classes. It all goes more natural with the modern Java date and time API.
To get a date-time object from your millis:
ZonedDateTime dateTime = Instant.ofEpochMilli(millis)
.atZone(ZoneId.of("Australia/Sydney"));
If millis
equals 1318388699000L
, this gives you 2011-10-12T14:04:59+11:00[Australia/Sydney]
. Should the code in some strange way end up on a JVM that doesn’t know Australia/Sydney time zone, you can be sure to be notified through an exception.
If you want the date-time in your string format for presentation:
String formatted = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
Result:
12/10/2011 14:04:59
PS I don’t know what you mean by “The above doesn't work.” On my computer your code in the question too prints 12/10/2011 14:04:59
.
Just updating google-service version did not work for me.
compile
are replaced with implementation
.compile
then your project will show this error. So update all dependencies version.