anchor stringlengths 16 95 | positive stringlengths 87 6.25k | negative stringlengths 89 3.19k |
|---|---|---|
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def data_from_techshop_ws(tws_url):
"""Scrapes data from techshop.ws."""
r = requests.get(tws_url)
if r.status_code == 200:
data = BeautifulSoup(r.text, "lxml")
else:
data = "There was an error while accessing data on techshop.ws."
return data |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def matrix_to_gl(matrix):
"""
Convert a numpy row- major homogenous transformation matrix
to a flat column- major GLfloat transformation.
Parameters
-------------
matrix : (4,4) float
Row- major homogenous transform
Returns
-------------
glmatrix : (16,) gl.GLfloat
Transform in pyglet format
"""
matrix = np.asanyarray(matrix, dtype=np.float64)
if matrix.shape != (4, 4):
raise ValueError('matrix must be (4,4)!')
# switch to column major and flatten to (16,)
column = matrix.T.flatten()
# convert to GLfloat
glmatrix = (gl.GLfloat * 16)(*column)
return glmatrix |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def matrix_to_gl(matrix):
"""
Convert a numpy row- major homogenous transformation matrix
to a flat column- major GLfloat transformation.
Parameters
-------------
matrix : (4,4) float
Row- major homogenous transform
Returns
-------------
glmatrix : (16,) gl.GLfloat
Transform in pyglet format
"""
matrix = np.asanyarray(matrix, dtype=np.float64)
if matrix.shape != (4, 4):
raise ValueError('matrix must be (4,4)!')
# switch to column major and flatten to (16,)
column = matrix.T.flatten()
# convert to GLfloat
glmatrix = (gl.GLfloat * 16)(*column)
return glmatrix |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def get_column_definition(self, table, column):
"""Retrieve the column definition statement for a column from a table."""
# Parse column definitions for match
for col in self.get_column_definition_all(table):
if col.strip('`').startswith(column):
return col.strip(',') |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def matrix_at_check(self, original, loc, tokens):
"""Check for Python 3.5 matrix multiplication."""
return self.check_py("35", "matrix multiplication", original, loc, tokens) |
are python strings hashable | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | def dedupe(items):
"""Remove duplicates from a sequence (of hashable items) while maintaining
order. NOTE: This only works if items in the list are hashable types.
Taken from the Python Cookbook, 3rd ed. Such a great book!
"""
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item) |
are python strings hashable | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | def dedupe(items):
"""Remove duplicates from a sequence (of hashable items) while maintaining
order. NOTE: This only works if items in the list are hashable types.
Taken from the Python Cookbook, 3rd ed. Such a great book!
"""
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item) |
are python strings hashable | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | def dedupe(items):
"""Remove duplicates from a sequence (of hashable items) while maintaining
order. NOTE: This only works if items in the list are hashable types.
Taken from the Python Cookbook, 3rd ed. Such a great book!
"""
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item) |
are python strings hashable | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | def _split_python(python):
"""Split Python source into chunks.
Chunks are separated by at least two return lines. The break must not
be followed by a space. Also, long Python strings spanning several lines
are not splitted.
"""
python = _preprocess(python)
if not python:
return []
lexer = PythonSplitLexer()
lexer.read(python)
return lexer.chunks |
are python strings hashable | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | def urlencoded(body, charset='ascii', **kwargs):
"""Converts query strings into native Python objects"""
return parse_query_string(text(body, charset=charset), False) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def from_pydatetime(cls, pydatetime):
"""
Creates sql datetime2 object from Python datetime object
ignoring timezone
@param pydatetime: Python datetime object
@return: sql datetime2 object
"""
return cls(date=Date.from_pydate(pydatetime.date),
time=Time.from_pytime(pydatetime.time)) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def from_pydatetime(cls, pydatetime):
"""
Creates sql datetime2 object from Python datetime object
ignoring timezone
@param pydatetime: Python datetime object
@return: sql datetime2 object
"""
return cls(date=Date.from_pydate(pydatetime.date),
time=Time.from_pytime(pydatetime.time)) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def from_pydatetime(cls, pydatetime):
"""
Creates sql datetime2 object from Python datetime object
ignoring timezone
@param pydatetime: Python datetime object
@return: sql datetime2 object
"""
return cls(date=Date.from_pydate(pydatetime.date),
time=Time.from_pytime(pydatetime.time)) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def from_pydatetime(cls, pydatetime):
"""
Creates sql datetime2 object from Python datetime object
ignoring timezone
@param pydatetime: Python datetime object
@return: sql datetime2 object
"""
return cls(date=Date.from_pydate(pydatetime.date),
time=Time.from_pytime(pydatetime.time)) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def from_pydatetime(cls, pydatetime):
"""
Creates sql datetime2 object from Python datetime object
ignoring timezone
@param pydatetime: Python datetime object
@return: sql datetime2 object
"""
return cls(date=Date.from_pydate(pydatetime.date),
time=Time.from_pytime(pydatetime.time)) |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def stepBy(self, steps):
"""steps value up/down by a single step. Single step is defined in singleStep().
Args:
steps (int): positiv int steps up, negativ steps down
"""
self.setValue(self.value() + steps*self.singleStep()) |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def string_to_genomic_range(rstring):
""" Convert a string to a genomic range
:param rstring: string representing a genomic range chr1:801-900
:type rstring:
:returns: object representing the string
:rtype: GenomicRange
"""
m = re.match('([^:]+):(\d+)-(\d+)',rstring)
if not m:
sys.stderr.write("ERROR: problem with range string "+rstring+"\n")
return GenomicRange(m.group(1),int(m.group(2)),int(m.group(3))) |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def empty(self, start=None, stop=None):
"""Empty the range from start to stop.
Like delete, but no Error is raised if the entire range isn't mapped.
"""
self.set(NOT_SET, start=start, stop=stop) |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def empty(self, start=None, stop=None):
"""Empty the range from start to stop.
Like delete, but no Error is raised if the entire range isn't mapped.
"""
self.set(NOT_SET, start=start, stop=stop) |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def empty(self, start=None, stop=None):
"""Empty the range from start to stop.
Like delete, but no Error is raised if the entire range isn't mapped.
"""
self.set(NOT_SET, start=start, stop=stop) |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def listunion(ListOfLists):
"""
Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is like::
a.extend(b)
**Parameters**
**ListOfLists** : Python list
Python list of Python lists.
**Returns**
**u** : Python list
Python list created by taking the union of the
lists in `ListOfLists`.
"""
u = []
for s in ListOfLists:
if s != None:
u.extend(s)
return u |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def listunion(ListOfLists):
"""
Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is like::
a.extend(b)
**Parameters**
**ListOfLists** : Python list
Python list of Python lists.
**Returns**
**u** : Python list
Python list created by taking the union of the
lists in `ListOfLists`.
"""
u = []
for s in ListOfLists:
if s != None:
u.extend(s)
return u |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def listunion(ListOfLists):
"""
Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is like::
a.extend(b)
**Parameters**
**ListOfLists** : Python list
Python list of Python lists.
**Returns**
**u** : Python list
Python list created by taking the union of the
lists in `ListOfLists`.
"""
u = []
for s in ListOfLists:
if s != None:
u.extend(s)
return u |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def listunion(ListOfLists):
"""
Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is like::
a.extend(b)
**Parameters**
**ListOfLists** : Python list
Python list of Python lists.
**Returns**
**u** : Python list
Python list created by taking the union of the
lists in `ListOfLists`.
"""
u = []
for s in ListOfLists:
if s != None:
u.extend(s)
return u |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def listunion(ListOfLists):
"""
Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is like::
a.extend(b)
**Parameters**
**ListOfLists** : Python list
Python list of Python lists.
**Returns**
**u** : Python list
Python list created by taking the union of the
lists in `ListOfLists`.
"""
u = []
for s in ListOfLists:
if s != None:
u.extend(s)
return u |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def load(cls, fname):
""" Loads the dictionary from json file
:param fname: file to load from
:return: loaded dictionary
"""
with open(fname) as f:
return Config(**json.load(f)) |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer') |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cint32_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):
return np.fromiter(cptr, dtype=np.int32, count=length)
else:
raise RuntimeError('Expected int pointer') |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cint8_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer') |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer') |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cint32_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):
return np.fromiter(cptr, dtype=np.int32, count=length)
else:
raise RuntimeError('Expected int pointer') |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def from_file(cls, file_path, validate=True):
""" Creates a Python object from a XML file
:param file_path: Path to the XML file
:param validate: XML should be validated against the embedded XSD definition
:type validate: Boolean
:returns: the Python object
"""
return xmlmap.load_xmlobject_from_file(file_path, xmlclass=cls, validate=validate) |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def _rescale_array(self, array, scale, zero):
"""
Scale the input array
"""
if scale != 1.0:
sval = numpy.array(scale, dtype=array.dtype)
array *= sval
if zero != 0.0:
zval = numpy.array(zero, dtype=array.dtype)
array += zval |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def getEdges(npArr):
"""get np array of bin edges"""
edges = np.concatenate(([0], npArr[:,0] + npArr[:,2]))
return np.array([Decimal(str(i)) for i in edges]) |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def _create_empty_array(self, frames, always_2d, dtype):
"""Create an empty array with appropriate shape."""
import numpy as np
if always_2d or self.channels > 1:
shape = frames, self.channels
else:
shape = frames,
return np.empty(shape, dtype, order='C') |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def _create_empty_array(self, frames, always_2d, dtype):
"""Create an empty array with appropriate shape."""
import numpy as np
if always_2d or self.channels > 1:
shape = frames, self.channels
else:
shape = frames,
return np.empty(shape, dtype, order='C') |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def _create_empty_array(self, frames, always_2d, dtype):
"""Create an empty array with appropriate shape."""
import numpy as np
if always_2d or self.channels > 1:
shape = frames, self.channels
else:
shape = frames,
return np.empty(shape, dtype, order='C') |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotateImage(image, angle):
"""
rotates a 2d array to a multiple of 90 deg.
0 = default
1 = 90 deg. cw
2 = 180 deg.
3 = 90 deg. ccw
"""
image = [list(row) for row in image]
for n in range(angle % 4):
image = list(zip(*image[::-1]))
return image |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotateImage(image, angle):
"""
rotates a 2d array to a multiple of 90 deg.
0 = default
1 = 90 deg. cw
2 = 180 deg.
3 = 90 deg. ccw
"""
image = [list(row) for row in image]
for n in range(angle % 4):
image = list(zip(*image[::-1]))
return image |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotateImage(image, angle):
"""
rotates a 2d array to a multiple of 90 deg.
0 = default
1 = 90 deg. cw
2 = 180 deg.
3 = 90 deg. ccw
"""
image = [list(row) for row in image]
for n in range(angle % 4):
image = list(zip(*image[::-1]))
return image |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotateImage(image, angle):
"""
rotates a 2d array to a multiple of 90 deg.
0 = default
1 = 90 deg. cw
2 = 180 deg.
3 = 90 deg. ccw
"""
image = [list(row) for row in image]
for n in range(angle % 4):
image = list(zip(*image[::-1]))
return image |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotateImage(image, angle):
"""
rotates a 2d array to a multiple of 90 deg.
0 = default
1 = 90 deg. cw
2 = 180 deg.
3 = 90 deg. ccw
"""
image = [list(row) for row in image]
for n in range(angle % 4):
image = list(zip(*image[::-1]))
return image |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def manhattan_distance_numpy(object1, object2):
"""!
@brief Calculate Manhattan distance between two objects using numpy.
@param[in] object1 (array_like): The first array_like object.
@param[in] object2 (array_like): The second array_like object.
@return (double) Manhattan distance between two objects.
"""
return numpy.sum(numpy.absolute(object1 - object2), axis=1).T |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def manhattan_distance_numpy(object1, object2):
"""!
@brief Calculate Manhattan distance between two objects using numpy.
@param[in] object1 (array_like): The first array_like object.
@param[in] object2 (array_like): The second array_like object.
@return (double) Manhattan distance between two objects.
"""
return numpy.sum(numpy.absolute(object1 - object2), axis=1).T |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def hamming(s, t):
"""
Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.
:param s: string 1
:type s: str
:param t: string 2
:type s: str
:return: Hamming distance
:rtype: float
"""
if len(s) != len(t):
raise ValueError('Hamming distance needs strings of equal length.')
return sum(s_ != t_ for s_, t_ in zip(s, t)) |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def hamming(s, t):
"""
Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.
:param s: string 1
:type s: str
:param t: string 2
:type s: str
:return: Hamming distance
:rtype: float
"""
if len(s) != len(t):
raise ValueError('Hamming distance needs strings of equal length.')
return sum(s_ != t_ for s_, t_ in zip(s, t)) |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def hamming(s, t):
"""
Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.
:param s: string 1
:type s: str
:param t: string 2
:type s: str
:return: Hamming distance
:rtype: float
"""
if len(s) != len(t):
raise ValueError('Hamming distance needs strings of equal length.')
return sum(s_ != t_ for s_, t_ in zip(s, t)) |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def build_parser():
"""Build argument parsers."""
parser = argparse.ArgumentParser("Release packages to pypi")
parser.add_argument('--check', '-c', action="store_true", help="Do a dry run without uploading")
parser.add_argument('component', help="The component to release as component-version")
return parser |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def build_parser():
"""Build argument parsers."""
parser = argparse.ArgumentParser("Release packages to pypi")
parser.add_argument('--check', '-c', action="store_true", help="Do a dry run without uploading")
parser.add_argument('component', help="The component to release as component-version")
return parser |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def build_parser():
"""Build argument parsers."""
parser = argparse.ArgumentParser("Release packages to pypi")
parser.add_argument('--check', '-c', action="store_true", help="Do a dry run without uploading")
parser.add_argument('component', help="The component to release as component-version")
return parser |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime
"""
chunks = list(map(int, date.split('T')[0].split('-')))
return datetime.datetime(chunks[0], chunks[1], chunks[2]) |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime
"""
chunks = list(map(int, date.split('T')[0].split('-')))
return datetime.datetime(chunks[0], chunks[1], chunks[2]) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def WriteManyToPath(objs, filepath):
"""Serializes and writes given Python objects to a multi-document YAML file.
Args:
objs: An iterable of Python objects to serialize.
filepath: A path to the file into which the object is to be written.
"""
with io.open(filepath, mode="w", encoding="utf-8") as filedesc:
WriteManyToFile(objs, filedesc) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def __cmp__(self, other):
"""Comparsion not implemented."""
# Stops python 2 from allowing comparsion of arbitrary objects
raise TypeError('unorderable types: {}, {}'
''.format(self.__class__.__name__, type(other))) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def _format_title_string(self, title_string):
""" format mpv's title """
return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix)) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def _format_title_string(self, title_string):
""" format mpv's title """
return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix)) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def _format_title_string(self, title_string):
""" format mpv's title """
return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix)) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def validate_django_compatible_with_python():
"""
Verify Django 1.11 is present if Python 2.7 is active
Installation of pinax-cli requires the correct version of Django for
the active Python version. If the developer subsequently changes
the Python version the installed Django may no longer be compatible.
"""
python_version = sys.version[:5]
django_version = django.get_version()
if sys.version_info == (2, 7) and django_version >= "2":
click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version)) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def validate_django_compatible_with_python():
"""
Verify Django 1.11 is present if Python 2.7 is active
Installation of pinax-cli requires the correct version of Django for
the active Python version. If the developer subsequently changes
the Python version the installed Django may no longer be compatible.
"""
python_version = sys.version[:5]
django_version = django.get_version()
if sys.version_info == (2, 7) and django_version >= "2":
click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version)) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def validate_django_compatible_with_python():
"""
Verify Django 1.11 is present if Python 2.7 is active
Installation of pinax-cli requires the correct version of Django for
the active Python version. If the developer subsequently changes
the Python version the installed Django may no longer be compatible.
"""
python_version = sys.version[:5]
django_version = django.get_version()
if sys.version_info == (2, 7) and django_version >= "2":
click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version)) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def __init__(self, form_post_data=None, *args, **kwargs):
"""
Overriding init so we can set the post vars like a normal form and generate
the form the same way Django does.
"""
kwargs.update({'form_post_data': form_post_data})
super(MongoModelForm, self).__init__(*args, **kwargs) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def get_language():
"""
Wrapper around Django's `get_language` utility.
For Django >= 1.8, `get_language` returns None in case no translation is activate.
Here we patch this behavior e.g. for back-end functionality requiring access to translated fields
"""
from parler import appsettings
language = dj_get_language()
if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:
return appsettings.PARLER_DEFAULT_LANGUAGE_CODE
else:
return language |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def _system_parameters(**kwargs):
"""
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments.
"""
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def zeros(self, name, **kwargs):
"""Create an array. Keyword arguments as per
:func:`zarr.creation.zeros`."""
return self._write_op(self._zeros_nosync, name, **kwargs) |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def zeros(self, name, **kwargs):
"""Create an array. Keyword arguments as per
:func:`zarr.creation.zeros`."""
return self._write_op(self._zeros_nosync, name, **kwargs) |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def zeros(self, name, **kwargs):
"""Create an array. Keyword arguments as per
:func:`zarr.creation.zeros`."""
return self._write_op(self._zeros_nosync, name, **kwargs) |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def zeros(self, name, **kwargs):
"""Create an array. Keyword arguments as per
:func:`zarr.creation.zeros`."""
return self._write_op(self._zeros_nosync, name, **kwargs) |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 11