anchor stringlengths 16 95 | positive stringlengths 87 6.25k | negative stringlengths 87 6.4k |
|---|---|---|
python determine whether windows or linux | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | def on_windows ():
""" Returns true if running on windows, whether in cygwin or not.
"""
if bjam.variable("NT"):
return True
elif bjam.variable("UNIX"):
uname = bjam.variable("JAMUNAME")
if uname and uname[0].startswith("CYGWIN"):
return True
return False |
python determine whether windows or linux | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | def is_unix_style(flags):
"""Check if we should use Unix style."""
return (util.platform() != "windows" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN |
python determine whether windows or linux | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | def _get_wow64():
"""
Determines if the current process is running in Windows-On-Windows 64 bits.
@rtype: bool
@return: C{True} of the current process is a 32 bit program running in a
64 bit version of Windows, C{False} if it's either a 32 bit program
in a 32 bit Windows or a 64 bit pr... |
python determine whether windows or linux | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | def check64bit(current_system="python"):
"""checks if you are on a 64 bit platform"""
if current_system == "python":
return sys.maxsize > 2147483647
elif current_system == "os":
import platform
pm = platform.machine()
if pm != ".." and pm.endswith('64'): # recent Python (not... |
python determine whether windows or linux | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | def _is_osx_107():
"""
:return:
A bool if the current machine is running OS X 10.7
"""
if sys.platform != 'darwin':
return False
version = platform.mac_ver()[0]
return tuple(map(int, version.split('.')))[0:2] == (10, 7) |
python dict remove items by keys | def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys} | def rm_keys_from_dict(d, keys):
"""
Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata
"""
# Loop for each key given
for key in keys:
# Is the key in the ... |
python dict remove items by keys | def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys} | def _remove_dict_keys_with_value(dict_, val):
"""Removes `dict` keys which have have `self` as value."""
return {k: v for k, v in dict_.items() if v is not val} |
python dict remove items by keys | def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys} | def __delitem__ (self, key):
"""Remove key from dict."""
self._keys.remove(key)
super(ListDict, self).__delitem__(key) |
python dict remove items by keys | def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys} | def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys} |
python dict remove items by keys | def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys} | def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists.
"""
for d in dict_list:
d.pop(key, None) |
check all attributes in an object python | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | def get_all_attributes(klass_or_instance):
"""Get all attribute members (attribute, property style method).
"""
pairs = list()
for attr, value in inspect.getmembers(
klass_or_instance, lambda x: not inspect.isroutine(x)):
if not (attr.startswith("__") or attr.endswith("__")):
... |
check all attributes in an object python | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | def get_methods(*objs):
""" Return the names of all callable attributes of an object"""
return set(
attr
for obj in objs
for attr in dir(obj)
if not attr.startswith('_') and callable(getattr(obj, attr))
) |
check all attributes in an object python | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | def get_object_attrs(obj):
"""
Get the attributes of an object using dir.
This filters protected attributes
"""
attrs = [k for k in dir(obj) if not k.startswith('__')]
if not attrs:
attrs = dir(obj)
return attrs |
check all attributes in an object python | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | def instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods."""
return item in (member for _, member in inspect.getmembers(container)) |
check all attributes in an object python | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | def check_attribute_exists(instance):
""" Additional check for the dimension model, to ensure that attributes
given as the key and label attribute on the dimension exist. """
attributes = instance.get('attributes', {}).keys()
if instance.get('key_attribute') not in attributes:
return False
l... |
check equality between arrays python | def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and... | def indexes_equal(a: Index, b: Index) -> bool:
"""
Are two indexes equal? Checks by comparing ``str()`` versions of them.
(AM UNSURE IF THIS IS ENOUGH.)
"""
return str(a) == str(b) |
check equality between arrays python | def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and... | def equal(obj1, obj2):
"""Calculate equality between two (Comparable) objects."""
Comparable.log(obj1, obj2, '==')
equality = obj1.equality(obj2)
Comparable.log(obj1, obj2, '==', result=equality)
return equality |
check equality between arrays python | def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and... | def all_equal(arg1,arg2):
"""
Return a single boolean for arg1==arg2, even for numpy arrays
using element-wise comparison.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
If both objects have an '_infinitely_iterable' attribute, they are
not be zipped together and are compared di... |
check equality between arrays python | def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and... | def _eq(self, other):
"""Compare two nodes for equality."""
return (self.type, self.value) == (other.type, other.value) |
check equality between arrays python | def numpy_aware_eq(a, b):
"""Return whether two objects are equal via recursion, using
:func:`numpy.array_equal` for comparing numpy arays.
"""
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
return np.array_equal(a, b)
if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and... | def hard_equals(a, b):
"""Implements the '===' operator."""
if type(a) != type(b):
return False
return a == b |
check if an element is present in python and webdriver | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... | def is_element_present(self, strategy, locator):
"""Checks whether an element is present.
:param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.
:param locator: Location of target element.
:typ... |
check if an element is present in python and webdriver | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... | def assert_visible(self, locator, msg=None):
"""
Hard assert for whether and element is present and visible in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference
"""
e = driver.find_ele... |
check if an element is present in python and webdriver | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... | def elXpath(self, xpath, dom=None):
"""check if element is present by css"""
if dom is None:
dom = self.browser
return expect(dom.is_element_present_by_xpath, args=[xpath]) |
check if an element is present in python and webdriver | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... | def is_webdriver_ios(webdriver):
"""
Check if a web driver if mobile.
Args:
webdriver (WebDriver): Selenium webdriver.
"""
browser = webdriver.capabilities['browserName']
if (browser == u('iPhone') or
browser == u('iPad')):
return T... |
check if an element is present in python and webdriver | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... | def _interface_exists(self, interface):
"""Check whether interface exists."""
ios_cfg = self._get_running_config()
parse = HTParser(ios_cfg)
itfcs_raw = parse.find_lines("^interface " + interface)
return len(itfcs_raw) > 0 |
check if arg is function python | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) | def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object)) |
check if arg is function python | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) | def isfunc(x):
"""
Returns `True` if the given value is a function or method object.
Arguments:
x (mixed): value to check.
Returns:
bool
"""
return any([
inspect.isfunction(x) and not asyncio.iscoroutinefunction(x),
inspect.ismethod(x) and not asyncio.iscoroutin... |
check if arg is function python | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) | def is_function(self):
"""return True if callback is a vanilla plain jane function"""
if self.is_instance() or self.is_class(): return False
return isinstance(self.callback, (Callable, classmethod)) |
check if arg is function python | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) | def is_parameter(self):
"""Whether this is a function parameter."""
return (isinstance(self.scope, CodeFunction)
and self in self.scope.parameters) |
check if arg is function python | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) | def callable_validator(v: Any) -> AnyCallable:
"""
Perform a simple check if the value is callable.
Note: complete matching of argument type hints and return types is not performed
"""
if callable(v):
return v
raise errors.CallableError(value=v) |
python disconnect shared connection | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | def disconnect(self):
"""Gracefully close connection to stomp server."""
if self._connected:
self._connected = False
self._conn.disconnect() |
python disconnect shared connection | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | def disconnect(self):
"""
Closes the connection.
"""
self.logger.debug('Close connection...')
self.auto_reconnect = False
if self.websocket is not None:
self.websocket.close() |
python disconnect shared connection | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | def do_stc_disconnectall(self, s):
"""Remove connections to all chassis (test ports) in this session."""
if self._not_joined():
return
try:
self._stc.disconnectall()
except resthttp.RestHttpError as e:
print(e)
return
print('OK') |
python disconnect shared connection | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | def delete_connection():
"""
Stop and destroy Bloomberg connection
"""
if _CON_SYM_ in globals():
con = globals().pop(_CON_SYM_)
if not getattr(con, '_session').start(): con.stop() |
python disconnect shared connection | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None | def exit(self):
"""
Closes the connection
"""
self.pubsub.unsubscribe()
self.client.connection_pool.disconnect()
logger.info("Connection to Redis closed") |
check if column is object in python | def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
r... | def is_not_null(df: DataFrame, col_name: str) -> bool:
"""
Return ``True`` if the given DataFrame has a column of the given
name (string), and there exists at least one non-NaN value in that
column; return ``False`` otherwise.
"""
if (
isinstance(df, pd.DataFrame)
and col_name in... |
check if column is object in python | def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
r... | def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Numeric) |
check if column is object in python | def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
r... | def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type an integer type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Integer) |
check if column is object in python | def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
r... | def columns_equal(a: Column, b: Column) -> bool:
"""
Are two SQLAlchemy columns are equal? Checks based on:
- column ``name``
- column ``type`` (see :func:`column_types_equal`)
- ``nullable``
"""
return (
a.name == b.name and
column_types_equal(a.type, b.type) and
a.... |
check if column is object in python | def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
r... | def _raise_error_if_column_exists(dataset, column_name = 'dataset',
dataset_variable_name = 'dataset',
column_name_error_message_name = 'column_name'):
"""
Check if a column exists in an SFrame with error message.
"""
err_msg = 'The SFrame {0} must... |
check if datetime python | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) | def is_timestamp(obj):
"""
Yaml either have automatically converted it to a datetime object
or it is a string that will be validated later.
"""
return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj) |
check if datetime python | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) | def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False |
check if datetime python | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) | def is_timestamp(instance):
"""Validates data is a timestamp"""
if not isinstance(instance, (int, str)):
return True
return datetime.fromtimestamp(int(instance)) |
check if datetime python | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date... |
check if datetime python | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) | def is_date_type(cls):
"""Return True if the class is a date type."""
if not isinstance(cls, type):
return False
return issubclass(cls, date) and not issubclass(cls, datetime) |
python disctionary from json string | def serialize_json_string(self, value):
"""
Tries to load an encoded json string back into an object
:param json_string:
:return:
"""
# Check if the value might be a json string
if not isinstance(value, six.string_types):
return value
# Make ... | def json_decode(data):
"""
Decodes the given JSON as primitives
"""
if isinstance(data, six.binary_type):
data = data.decode('utf-8')
return json.loads(data) |
python disctionary from json string | def serialize_json_string(self, value):
"""
Tries to load an encoded json string back into an object
:param json_string:
:return:
"""
# Check if the value might be a json string
if not isinstance(value, six.string_types):
return value
# Make ... | def from_json(cls, json_doc):
"""Parse a JSON string and build an entity."""
try:
d = json.load(json_doc)
except AttributeError: # catch the read() error
d = json.loads(json_doc)
return cls.from_dict(d) |
python disctionary from json string | def serialize_json_string(self, value):
"""
Tries to load an encoded json string back into an object
:param json_string:
:return:
"""
# Check if the value might be a json string
if not isinstance(value, six.string_types):
return value
# Make ... | def from_json(cls, s):
"""
Restores the object from the given JSON.
:param s: the JSON string to parse
:type s: str
:return: the
"""
d = json.loads(s)
return get_dict_handler(d["type"])(d) |
python disctionary from json string | def serialize_json_string(self, value):
"""
Tries to load an encoded json string back into an object
:param json_string:
:return:
"""
# Check if the value might be a json string
if not isinstance(value, six.string_types):
return value
# Make ... | def from_json(cls, json_str):
"""Deserialize the object from a JSON string."""
d = json.loads(json_str)
return cls.from_dict(d) |
python disctionary from json string | def serialize_json_string(self, value):
"""
Tries to load an encoded json string back into an object
:param json_string:
:return:
"""
# Check if the value might be a json string
if not isinstance(value, six.string_types):
return value
# Make ... | def process_result_value(self, value, dialect):
"""convert value from json to a python object"""
if value is not None:
value = simplejson.loads(value)
return value |
check if function is defined python | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) | def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object)) |
check if function is defined python | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) | def isfunc(x):
"""
Returns `True` if the given value is a function or method object.
Arguments:
x (mixed): value to check.
Returns:
bool
"""
return any([
inspect.isfunction(x) and not asyncio.iscoroutinefunction(x),
inspect.ismethod(x) and not asyncio.iscoroutin... |
check if function is defined python | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) |
check if function is defined python | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) | def is_function(self):
"""return True if callback is a vanilla plain jane function"""
if self.is_instance() or self.is_class(): return False
return isinstance(self.callback, (Callable, classmethod)) |
check if function is defined python | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) | def is_parameter(self):
"""Whether this is a function parameter."""
return (isinstance(self.scope, CodeFunction)
and self in self.scope.parameters) |
python django delete all rows in table | def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().dele... | def wipe_table(self, table: str) -> int:
"""Delete all records from a table. Use caution!"""
sql = "DELETE FROM " + self.delimit(table)
return self.db_exec(sql) |
python django delete all rows in table | def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().dele... | def clear_table(dbconn, table_name):
"""
Delete all rows from a table
:param dbconn: data base connection
:param table_name: name of the table
:return:
"""
cur = dbconn.cursor()
cur.execute("DELETE FROM '{name}'".format(name=table_name))
dbconn.commit() |
python django delete all rows in table | def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().dele... | def drop_all_tables(self):
"""Drop all tables in the database"""
for table_name in self.table_names():
self.execute_sql("DROP TABLE %s" % table_name)
self.connection.commit() |
python django delete all rows in table | def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().dele... | def destroy(self):
""" Destroy the SQLStepQueue tables in the database """
with self._db_conn() as conn:
for table_name in self._tables:
conn.execute('DROP TABLE IF EXISTS %s' % table_name)
return self |
python django delete all rows in table | def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().dele... | def remove_non_magic_cols(self):
"""
Remove all non-MagIC columns from all tables.
"""
for table_name in self.tables:
table = self.tables[table_name]
table.remove_non_magic_cols_from_table() |
check if number is complex python | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) | def complex_check(*args, func=None):
"""Check if arguments are complex numbers."""
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, numbers.Complex):
name = type(var).__name__
raise ComplexError(
f'Function {func} expected complex n... |
check if number is complex python | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) | def __complex__(self):
"""Called to implement the built-in function complex()."""
if self._t != 99 or self.key != ['re', 'im']:
return complex(float(self))
return complex(float(self.re), float(self.im)) |
check if number is complex python | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) | def part(z, s):
r"""Get the real or imaginary part of a complex number."""
if sage_included:
if s == 1: return np.real(z)
elif s == -1: return np.imag(z)
elif s == 0:
return z
else:
if s == 1: return z.real
elif s == -1: return z.imag
elif s == 0: ... |
check if number is complex python | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) | def is_finite(value: Any) -> bool:
"""Return true if a value is a finite number."""
return isinstance(value, int) or (isinstance(value, float) and isfinite(value)) |
check if number is complex python | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) | def isreal(obj):
"""
Test if the argument is a real number (float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float))
) |
check is string is date in python | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date... | def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False |
check is string is date in python | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date... | def _validate_date_str(str_):
"""Validate str as a date and return string version of date"""
if not str_:
return None
# Convert to datetime so we can validate it's a real date that exists then
# convert it back to the string.
try:
date = datetime.strptime(str_, DATE_FMT)
except... |
check is string is date in python | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date... | def is_date_type(cls):
"""Return True if the class is a date type."""
if not isinstance(cls, type):
return False
return issubclass(cls, date) and not issubclass(cls, datetime) |
check is string is date in python | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date... | def string_to_date(value):
"""
Return a Python date that corresponds to the specified string
representation.
@param value: string representation of a date.
@return: an instance ``datetime.datetime`` represented by the string.
"""
if isinstance(value, datetime.date):
return value
... |
check is string is date in python | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date... | def is_timestamp(obj):
"""
Yaml either have automatically converted it to a datetime object
or it is a string that will be validated later.
"""
return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj) |
python draw a box at random coordinates | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) |
python draw a box at random coordinates | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | def point8_to_box(points):
"""
Args:
points: (nx4)x2
Returns:
nx4 boxes (x1y1x2y2)
"""
p = points.reshape((-1, 4, 2))
minxy = p.min(axis=1) # nx2
maxxy = p.max(axis=1) # nx2
return np.concatenate((minxy, maxxy), axis=1) |
python draw a box at random coordinates | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | def paint_cube(self, x, y):
"""
Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube.
"""
... |
python draw a box at random coordinates | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | def _draw_lines_internal(self, coords, colour, bg):
"""Helper to draw lines connecting a set of nodes that are scaled for the Screen."""
for i, (x, y) in enumerate(coords):
if i == 0:
self._screen.move(x, y)
else:
self._screen.draw(x, y, colour=col... |
python draw a box at random coordinates | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | def polyline(self, arr):
"""Draw a set of lines"""
for i in range(0, len(arr) - 1):
self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]) |
check my python path | def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | def isPackage(file_path):
"""
Determine whether or not a given path is a (sub)package or not.
"""
return (os.path.isdir(file_path) and
os.path.isfile(os.path.join(file_path, '__init__.py'))) |
check my python path | def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip')) |
check my python path | def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | def _is_already_configured(configuration_details):
"""Returns `True` when alias already in shell config."""
path = Path(configuration_details.path).expanduser()
with path.open('r') as shell_config:
return configuration_details.content in shell_config.read() |
check my python path | def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | def executable_exists(executable):
"""Test if an executable is available on the system."""
for directory in os.getenv("PATH").split(":"):
if os.path.exists(os.path.join(directory, executable)):
return True
return False |
check my python path | def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | def isdir(path, **kwargs):
"""Check if *path* is a directory"""
import os.path
return os.path.isdir(path, **kwargs) |
python draw a line | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | def _draw_lines_internal(self, coords, colour, bg):
"""Helper to draw lines connecting a set of nodes that are scaled for the Screen."""
for i, (x, y) in enumerate(coords):
if i == 0:
self._screen.move(x, y)
else:
self._screen.draw(x, y, colour=col... |
python draw a line | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | def polyline(self, arr):
"""Draw a set of lines"""
for i in range(0, len(arr) - 1):
self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]) |
python draw a line | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | def vline(self, x, y, height, color):
"""Draw a vertical line up to a given length."""
self.rect(x, y, 1, height, color, fill=True) |
python draw a line | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | def _add_line_segment(self, x, y):
"""Add a |_LineSegment| operation to the drawing sequence."""
self._drawing_operations.append(_LineSegment.new(self, x, y)) |
python draw a line | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) | def straight_line_show(title, length=100, linestyle="=", pad=0):
"""Print a formatted straight line.
"""
print(StrTemplate.straight_line(
title=title, length=length, linestyle=linestyle, pad=pad)) |
check set covers other set python | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | def issubset(self, other):
"""Report whether another set contains this RangeSet."""
self._binary_sanity_check(other)
return set.issubset(self, other) |
check set covers other set python | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | def issubset(self, other):
"""
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5... |
check set covers other set python | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | def sets_are_rooted_compat(one_set, other):
"""treats the 2 sets are sets of taxon IDs on the same (unstated)
universe of taxon ids.
Returns True clades implied by each are compatible and False otherwise
"""
if one_set.issubset(other) or other.issubset(one_set):
return True
return not in... |
check set covers other set python | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | def issuperset(self, items):
"""Return whether this collection contains all items.
>>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])
True
"""
return all(_compat.map(self._seen.__contains__, items)) |
check set covers other set python | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | def __isub__(self, other):
"""Remove all elements of another set from this RangeSet."""
self._binary_sanity_check(other)
set.difference_update(self, other)
return self |
python elasticsearch bulk index | def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = mode... | def bulk_load_docs(es, docs):
"""Bulk load docs
Args:
es: elasticsearch handle
docs: Iterator of doc objects - includes index_name
"""
chunk_size = 200
try:
results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)
log.debug(f"Elasticsearch documents lo... |
python elasticsearch bulk index | def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = mode... | def index(obj, index=INDEX_NAME, doc_type=DOC_TYPE):
"""
Index the given document.
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.index
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html
"""
doc = to_dict(obj)
if doc is ... |
python elasticsearch bulk index | def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = mode... | def can_elasticsearch(record):
"""Check if a given record is indexed.
:param record: A record object.
:returns: If the record is indexed returns `True`, otherwise `False`.
"""
search = request._methodview.search_class()
search = search.get_record(str(record.id))
return search.count() == 1 |
python elasticsearch bulk index | def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = mode... | def clear_es():
"""Clear all indexes in the es core"""
# TODO: should receive a catalog slug.
ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])
LOGGER.debug('Elasticsearch: Index cleared') |
python elasticsearch bulk index | def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = mode... | def all_documents(index=INDEX_NAME):
"""
Get all documents from the given index.
Returns full Elasticsearch objects so you can get metadata too.
"""
query = {
'query': {
'match_all': {}
}
}
for result in raw_query(query, index=index):
yield result |
checking types of elements inside of an 2d array python | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | def contains_all(self, array):
"""Test if `array` is an array of real numbers."""
dtype = getattr(array, 'dtype', None)
if dtype is None:
dtype = np.result_type(*array)
return is_real_dtype(dtype) |
checking types of elements inside of an 2d array python | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | def is_vector(inp):
""" Returns true if the input can be interpreted as a 'true' vector
Note
----
Does only check dimensions, not if type is numeric
Parameters
----------
inp : numpy.ndarray or something that can be converted into ndarray
Returns
-------
Boolean
True f... |
checking types of elements inside of an 2d array python | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | def is_int_vector(l):
r"""Checks if l is a numpy array of integers
"""
if isinstance(l, np.ndarray):
if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):
return True
return False |
checking types of elements inside of an 2d array python | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | def _check_2d_shape(X):
"""Check shape of array or sparse matrix.
Assure that X is always 2D: Unlike numpy we always deal with 2D arrays.
"""
if X.dtype.names is None and len(X.shape) != 2:
raise ValueError('X needs to be 2-dimensional, not '
'{}-dimensional.'.format(le... |
checking types of elements inside of an 2d array python | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) | def isarray(array, test, dim=2):
"""Returns True if test is True for all array elements.
Otherwise, returns False.
"""
if dim > 1:
return all(isarray(array[i], test, dim - 1)
for i in range(len(array)))
return all(test(i) for i in array) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.