code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def namedb_get_num_names( cur, current_block, include_expired=False ):
"""
Get the number of names that exist at the current block
"""
unexpired_query = ""
unexpired_args = ()
if not include_expired:
# count all names, including expired ones
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
unexpired_query = 'WHERE {}'.format(unexpired_query)
query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + ";"
args = unexpired_args
num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
return num_rows | Get the number of names that exist at the current block | Below is the the instruction that describes the task:
### Input:
Get the number of names that exist at the current block
### Response:
def namedb_get_num_names( cur, current_block, include_expired=False ):
"""
Get the number of names that exist at the current block
"""
unexpired_query = ""
unexpired_args = ()
if not include_expired:
# count all names, including expired ones
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
unexpired_query = 'WHERE {}'.format(unexpired_query)
query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + ";"
args = unexpired_args
num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
return num_rows |
def hse_output(pdb_file, file_type):
"""
The solvent exposure of an amino acid residue is important for analyzing,
understanding and predicting aspects of protein structure and function [73].
A residue's solvent exposure can be classified as four categories: exposed, partly exposed,
buried and deeply buried residues. Hamelryck et al. [73] established a new 2D measure that provides a
different view of solvent exposure, i.e. half-sphere exposure (HSE). By conceptually dividing the sphere
of a residue into two halves- HSE-up and HSE-down, HSE provides a more detailed description of an amino
acid residue's spatial neighborhood. HSE is calculated by the hsexpo module implemented in the BioPython
package [74] from a PDB file.
http://onlinelibrary.wiley.com/doi/10.1002/prot.20379/abstract
Args:
pdb_file:
Returns:
"""
# Get the first model
my_structure = StructureIO(pdb_file)
model = my_structure.first_model
# Calculate HSEalpha
exp_ca = HSExposureCA(model)
# Calculate HSEbeta
exp_cb = HSExposureCB(model)
# Calculate classical coordination number
exp_fs = ExposureCN(model)
return | The solvent exposure of an amino acid residue is important for analyzing,
understanding and predicting aspects of protein structure and function [73].
A residue's solvent exposure can be classified as four categories: exposed, partly exposed,
buried and deeply buried residues. Hamelryck et al. [73] established a new 2D measure that provides a
different view of solvent exposure, i.e. half-sphere exposure (HSE). By conceptually dividing the sphere
of a residue into two halves- HSE-up and HSE-down, HSE provides a more detailed description of an amino
acid residue's spatial neighborhood. HSE is calculated by the hsexpo module implemented in the BioPython
package [74] from a PDB file.
http://onlinelibrary.wiley.com/doi/10.1002/prot.20379/abstract
Args:
pdb_file:
Returns: | Below is the the instruction that describes the task:
### Input:
The solvent exposure of an amino acid residue is important for analyzing,
understanding and predicting aspects of protein structure and function [73].
A residue's solvent exposure can be classified as four categories: exposed, partly exposed,
buried and deeply buried residues. Hamelryck et al. [73] established a new 2D measure that provides a
different view of solvent exposure, i.e. half-sphere exposure (HSE). By conceptually dividing the sphere
of a residue into two halves- HSE-up and HSE-down, HSE provides a more detailed description of an amino
acid residue's spatial neighborhood. HSE is calculated by the hsexpo module implemented in the BioPython
package [74] from a PDB file.
http://onlinelibrary.wiley.com/doi/10.1002/prot.20379/abstract
Args:
pdb_file:
Returns:
### Response:
def hse_output(pdb_file, file_type):
"""
The solvent exposure of an amino acid residue is important for analyzing,
understanding and predicting aspects of protein structure and function [73].
A residue's solvent exposure can be classified as four categories: exposed, partly exposed,
buried and deeply buried residues. Hamelryck et al. [73] established a new 2D measure that provides a
different view of solvent exposure, i.e. half-sphere exposure (HSE). By conceptually dividing the sphere
of a residue into two halves- HSE-up and HSE-down, HSE provides a more detailed description of an amino
acid residue's spatial neighborhood. HSE is calculated by the hsexpo module implemented in the BioPython
package [74] from a PDB file.
http://onlinelibrary.wiley.com/doi/10.1002/prot.20379/abstract
Args:
pdb_file:
Returns:
"""
# Get the first model
my_structure = StructureIO(pdb_file)
model = my_structure.first_model
# Calculate HSEalpha
exp_ca = HSExposureCA(model)
# Calculate HSEbeta
exp_cb = HSExposureCB(model)
# Calculate classical coordination number
exp_fs = ExposureCN(model)
return |
def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False, validating=True):
"""Return UIDs of the selected services
"""
service_uids = form.get("uids", [])
return service_uids, {} | Return UIDs of the selected services | Below is the the instruction that describes the task:
### Input:
Return UIDs of the selected services
### Response:
def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False, validating=True):
"""Return UIDs of the selected services
"""
service_uids = form.get("uids", [])
return service_uids, {} |
def update(self, dt):
"""
Responsabilities:
Updates game engine each tick
Copies new stats into labels
"""
for key, value in self.labels.iteritems():
str_val = str(int(self.stats[key]))
self.msgs[key][0].element.text = self.labels[key] + str_val
self.msgs[key][1].element.text = self.labels[key] + str_val | Responsabilities:
Updates game engine each tick
Copies new stats into labels | Below is the the instruction that describes the task:
### Input:
Responsabilities:
Updates game engine each tick
Copies new stats into labels
### Response:
def update(self, dt):
"""
Responsabilities:
Updates game engine each tick
Copies new stats into labels
"""
for key, value in self.labels.iteritems():
str_val = str(int(self.stats[key]))
self.msgs[key][0].element.text = self.labels[key] + str_val
self.msgs[key][1].element.text = self.labels[key] + str_val |
def lmax(self):
r"""Largest eigenvalue of the graph Laplacian.
Can be exactly computed by :func:`compute_fourier_basis` or
approximated by :func:`estimate_lmax`.
"""
if self._lmax is None:
self.logger.warning('The largest eigenvalue G.lmax is not '
'available, we need to estimate it. '
'Explicitly call G.estimate_lmax() or '
'G.compute_fourier_basis() '
'once beforehand to suppress the warning.')
self.estimate_lmax()
return self._lmax | r"""Largest eigenvalue of the graph Laplacian.
Can be exactly computed by :func:`compute_fourier_basis` or
approximated by :func:`estimate_lmax`. | Below is the the instruction that describes the task:
### Input:
r"""Largest eigenvalue of the graph Laplacian.
Can be exactly computed by :func:`compute_fourier_basis` or
approximated by :func:`estimate_lmax`.
### Response:
def lmax(self):
r"""Largest eigenvalue of the graph Laplacian.
Can be exactly computed by :func:`compute_fourier_basis` or
approximated by :func:`estimate_lmax`.
"""
if self._lmax is None:
self.logger.warning('The largest eigenvalue G.lmax is not '
'available, we need to estimate it. '
'Explicitly call G.estimate_lmax() or '
'G.compute_fourier_basis() '
'once beforehand to suppress the warning.')
self.estimate_lmax()
return self._lmax |
def _get_range_dimension_key(self,
base_key: Key,
start_time: datetime,
end_time: datetime,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a DIMENSION key.
"""
raise NotImplementedError() | Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a DIMENSION key. | Below is the the instruction that describes the task:
### Input:
Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a DIMENSION key.
### Response:
def _get_range_dimension_key(self,
base_key: Key,
start_time: datetime,
end_time: datetime,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a DIMENSION key.
"""
raise NotImplementedError() |
def ToMicroseconds(self):
"""Converts a Duration to microseconds."""
micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)
return self.seconds * _MICROS_PER_SECOND + micros | Converts a Duration to microseconds. | Below is the the instruction that describes the task:
### Input:
Converts a Duration to microseconds.
### Response:
def ToMicroseconds(self):
"""Converts a Duration to microseconds."""
micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)
return self.seconds * _MICROS_PER_SECOND + micros |
def remove_node(self, node):
"""
Removes node from circle and rebuild it.
"""
try:
self._nodes.remove(node)
del self._weights[node]
except (KeyError, ValueError):
pass
self._hashring = dict()
self._sorted_keys = []
self._build_circle() | Removes node from circle and rebuild it. | Below is the the instruction that describes the task:
### Input:
Removes node from circle and rebuild it.
### Response:
def remove_node(self, node):
"""
Removes node from circle and rebuild it.
"""
try:
self._nodes.remove(node)
del self._weights[node]
except (KeyError, ValueError):
pass
self._hashring = dict()
self._sorted_keys = []
self._build_circle() |
def _read_marcxml(xml):
"""
Read MARC XML or OAI file, convert, add namespace and return XML in
required format with all necessities.
Args:
xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
Returns:
obj: Required XML parsed with ``lxml.etree``.
"""
# read file, if `xml` is valid file path
marc_xml = _read_content_or_path(xml)
# process input file - convert it from possible OAI to MARC XML and add
# required XML namespaces
marc_xml = _oai_to_xml(marc_xml)
marc_xml = _add_namespace(marc_xml)
file_obj = StringIO.StringIO(marc_xml)
return ET.parse(file_obj) | Read MARC XML or OAI file, convert, add namespace and return XML in
required format with all necessities.
Args:
xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
Returns:
obj: Required XML parsed with ``lxml.etree``. | Below is the the instruction that describes the task:
### Input:
Read MARC XML or OAI file, convert, add namespace and return XML in
required format with all necessities.
Args:
xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
Returns:
obj: Required XML parsed with ``lxml.etree``.
### Response:
def _read_marcxml(xml):
"""
Read MARC XML or OAI file, convert, add namespace and return XML in
required format with all necessities.
Args:
xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
Returns:
obj: Required XML parsed with ``lxml.etree``.
"""
# read file, if `xml` is valid file path
marc_xml = _read_content_or_path(xml)
# process input file - convert it from possible OAI to MARC XML and add
# required XML namespaces
marc_xml = _oai_to_xml(marc_xml)
marc_xml = _add_namespace(marc_xml)
file_obj = StringIO.StringIO(marc_xml)
return ET.parse(file_obj) |
def weakref_proxy(obj):
"""returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself."""
if type(obj) in weakref.ProxyTypes:
return obj
else:
return weakref.proxy(obj) | returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself. | Below is the the instruction that describes the task:
### Input:
returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself.
### Response:
def weakref_proxy(obj):
"""returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself."""
if type(obj) in weakref.ProxyTypes:
return obj
else:
return weakref.proxy(obj) |
def fetch(opts):
"""
Create a local mirror of one or more resources.
"""
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name))
if opts.verbose:
backend.VERBOSE = True
_fetch(resources, opts.resource_names, opts.mirror_url, opts.force, reporthook)
return verify(opts) | Create a local mirror of one or more resources. | Below is the the instruction that describes the task:
### Input:
Create a local mirror of one or more resources.
### Response:
def fetch(opts):
"""
Create a local mirror of one or more resources.
"""
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name))
if opts.verbose:
backend.VERBOSE = True
_fetch(resources, opts.resource_names, opts.mirror_url, opts.force, reporthook)
return verify(opts) |
def call_purge_doc(cls, kb_app, sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docname: str):
""" On env-purge-doc, do callbacks """
for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD):
callback(kb_app, sphinx_app, sphinx_env, docname) | On env-purge-doc, do callbacks | Below is the the instruction that describes the task:
### Input:
On env-purge-doc, do callbacks
### Response:
def call_purge_doc(cls, kb_app, sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docname: str):
""" On env-purge-doc, do callbacks """
for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD):
callback(kb_app, sphinx_app, sphinx_env, docname) |
def status_charge():
'''
Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge
'''
data = status()
if 'BCHARGE' in data:
charge = data['BCHARGE'].split()
if charge[1].lower() == 'percent':
return float(charge[0])
return {'Error': 'Load not available.'} | Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge | Below is the the instruction that describes the task:
### Input:
Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge
### Response:
def status_charge():
'''
Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge
'''
data = status()
if 'BCHARGE' in data:
charge = data['BCHARGE'].split()
if charge[1].lower() == 'percent':
return float(charge[0])
return {'Error': 'Load not available.'} |
def __normalize_grades(self):
"""
Adjust the grades list.
If a grade has been set, set All to false
"""
if 'grades' in self and self['grades']['All'] is True:
for grade in self['grades']:
if grade != 'All' and self['grades'][grade] is True:
self['grades']['All'] = False
break | Adjust the grades list.
If a grade has been set, set All to false | Below is the the instruction that describes the task:
### Input:
Adjust the grades list.
If a grade has been set, set All to false
### Response:
def __normalize_grades(self):
"""
Adjust the grades list.
If a grade has been set, set All to false
"""
if 'grades' in self and self['grades']['All'] is True:
for grade in self['grades']:
if grade != 'All' and self['grades'][grade] is True:
self['grades']['All'] = False
break |
def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
global _my_windows
if no_window:
if _my_windows.NumOpenWindows:
root = tk.Toplevel()
else:
root = tk.Tk()
try:
root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint'
except:
pass
folder_name = tk.filedialog.askdirectory() # show the 'get folder' dialog box
root.destroy()
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[Button('Ok', size=(5, 1), bind_return_key=True), Button('Cancel', size=(5, 1))]]
window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.LayoutAndRead(layout)
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path | Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled | Below is the the instruction that describes the task:
### Input:
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
### Response:
def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
"""
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
:param keep_on_top:
:param location:
:return: Contents of text field. None if closed using X or cancelled
"""
global _my_windows
if no_window:
if _my_windows.NumOpenWindows:
root = tk.Toplevel()
else:
root = tk.Tk()
try:
root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint'
except:
pass
folder_name = tk.filedialog.askdirectory() # show the 'get folder' dialog box
root.destroy()
return folder_name
layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)],
[InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)],
[Button('Ok', size=(5, 1), bind_return_key=True), Button('Cancel', size=(5, 1))]]
window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color,
background_color=background_color,
font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top,
location=location)
(button, input_values) = window.LayoutAndRead(layout)
window.Close()
if button != 'Ok':
return None
else:
path = input_values[0]
return path |
def needs_ssh(hostname, _socket=None):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:
return False
_socket = _socket or socket
fqdn = _socket.getfqdn()
if hostname == fqdn:
return False
local_hostname = _socket.gethostname()
local_short_hostname = local_hostname.split('.')[0]
if local_hostname == hostname or local_short_hostname == hostname:
return False
return True | Obtains remote hostname of the socket and cuts off the domain part
of its FQDN. | Below is the the instruction that describes the task:
### Input:
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
### Response:
def needs_ssh(hostname, _socket=None):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:
return False
_socket = _socket or socket
fqdn = _socket.getfqdn()
if hostname == fqdn:
return False
local_hostname = _socket.gethostname()
local_short_hostname = local_hostname.split('.')[0]
if local_hostname == hostname or local_short_hostname == hostname:
return False
return True |
def _convert_fancy(self, field):
"""Convert to a list (sep != None) and convert list elements."""
if self.sep is False:
x = self._convert_singlet(field)
else:
x = tuple([self._convert_singlet(s) for s in field.split(self.sep)])
if len(x) == 0:
x = ''
elif len(x) == 1:
x = x[0]
#print "%r --> %r" % (field, x)
return x | Convert to a list (sep != None) and convert list elements. | Below is the the instruction that describes the task:
### Input:
Convert to a list (sep != None) and convert list elements.
### Response:
def _convert_fancy(self, field):
"""Convert to a list (sep != None) and convert list elements."""
if self.sep is False:
x = self._convert_singlet(field)
else:
x = tuple([self._convert_singlet(s) for s in field.split(self.sep)])
if len(x) == 0:
x = ''
elif len(x) == 1:
x = x[0]
#print "%r --> %r" % (field, x)
return x |
def parse_script(output_script):
"""
Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes
"""
script_iterator = output_script.raw_iter()
try:
first_opcode, _, _ = next(script_iterator, (None, None, None))
_, data, _ = next(script_iterator, (None, None, None))
remainder = next(script_iterator, None)
except bitcoin.core.script.CScriptTruncatedPushDataError:
return None
except bitcoin.core.script.CScriptInvalidError:
return None
if first_opcode == bitcoin.core.script.OP_RETURN and data is not None and remainder is None:
return data
else:
return None | Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes
### Response:
def parse_script(output_script):
"""
Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes
"""
script_iterator = output_script.raw_iter()
try:
first_opcode, _, _ = next(script_iterator, (None, None, None))
_, data, _ = next(script_iterator, (None, None, None))
remainder = next(script_iterator, None)
except bitcoin.core.script.CScriptTruncatedPushDataError:
return None
except bitcoin.core.script.CScriptInvalidError:
return None
if first_opcode == bitcoin.core.script.OP_RETURN and data is not None and remainder is None:
return data
else:
return None |
def get_comment_object(self):
"""
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``).
"""
if not self.is_valid():
raise ValueError("get_comment_object may only be called on valid forms")
CommentModel = self.get_comment_model()
new = CommentModel(**self.get_comment_create_data())
new = self.check_for_duplicate_comment(new)
return new | Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``). | Below is the the instruction that describes the task:
### Input:
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``).
### Response:
def get_comment_object(self):
"""
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``).
"""
if not self.is_valid():
raise ValueError("get_comment_object may only be called on valid forms")
CommentModel = self.get_comment_model()
new = CommentModel(**self.get_comment_create_data())
new = self.check_for_duplicate_comment(new)
return new |
def output_touch(self):
"""ensure the ./swhlab/ folder exists."""
if not os.path.exists(self.outFolder):
self.log.debug("creating %s",self.outFolder)
os.mkdir(self.outFolder) | ensure the ./swhlab/ folder exists. | Below is the the instruction that describes the task:
### Input:
ensure the ./swhlab/ folder exists.
### Response:
def output_touch(self):
"""ensure the ./swhlab/ folder exists."""
if not os.path.exists(self.outFolder):
self.log.debug("creating %s",self.outFolder)
os.mkdir(self.outFolder) |
def upgrade():
"""Upgrade database."""
op.create_table(
'pidstore_pid',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pid_type', sa.String(length=6), nullable=False),
sa.Column('pid_value', sa.String(length=255), nullable=False),
sa.Column('pid_provider', sa.String(length=8), nullable=True),
sa.Column('status', sa.CHAR(1), nullable=False),
sa.Column('object_type', sa.String(length=3), nullable=True),
sa.Column(
'object_uuid',
sqlalchemy_utils.types.uuid.UUIDType(),
nullable=True
),
sa.PrimaryKeyConstraint('id')
)
op.create_index(
'idx_object', 'pidstore_pid', ['object_type', 'object_uuid'],
unique=False
)
op.create_index('idx_status', 'pidstore_pid', ['status'], unique=False)
op.create_index(
'uidx_type_pid', 'pidstore_pid', ['pid_type', 'pid_value'],
unique=True
)
op.create_table(
'pidstore_recid',
sa.Column('recid', sa.BigInteger(), nullable=False),
sa.PrimaryKeyConstraint('recid')
)
op.create_table(
'pidstore_redirect',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column(
'id',
sqlalchemy_utils.types.uuid.UUIDType(),
nullable=False
),
sa.Column('pid_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
['pid_id'],
[u'pidstore_pid.id'],
onupdate='CASCADE',
ondelete='RESTRICT'
),
sa.PrimaryKeyConstraint('id')
) | Upgrade database. | Below is the the instruction that describes the task:
### Input:
Upgrade database.
### Response:
def upgrade():
"""Upgrade database."""
op.create_table(
'pidstore_pid',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pid_type', sa.String(length=6), nullable=False),
sa.Column('pid_value', sa.String(length=255), nullable=False),
sa.Column('pid_provider', sa.String(length=8), nullable=True),
sa.Column('status', sa.CHAR(1), nullable=False),
sa.Column('object_type', sa.String(length=3), nullable=True),
sa.Column(
'object_uuid',
sqlalchemy_utils.types.uuid.UUIDType(),
nullable=True
),
sa.PrimaryKeyConstraint('id')
)
op.create_index(
'idx_object', 'pidstore_pid', ['object_type', 'object_uuid'],
unique=False
)
op.create_index('idx_status', 'pidstore_pid', ['status'], unique=False)
op.create_index(
'uidx_type_pid', 'pidstore_pid', ['pid_type', 'pid_value'],
unique=True
)
op.create_table(
'pidstore_recid',
sa.Column('recid', sa.BigInteger(), nullable=False),
sa.PrimaryKeyConstraint('recid')
)
op.create_table(
'pidstore_redirect',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column(
'id',
sqlalchemy_utils.types.uuid.UUIDType(),
nullable=False
),
sa.Column('pid_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
['pid_id'],
[u'pidstore_pid.id'],
onupdate='CASCADE',
ondelete='RESTRICT'
),
sa.PrimaryKeyConstraint('id')
) |
def _xy2hash(x, y, dim):
"""Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int y value of point [0, dim) in dim x dim coord system
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
int: hashcode ∈ [0, dim**2)
"""
d = 0
lvl = dim >> 1
while (lvl > 0):
rx = int((x & lvl) > 0)
ry = int((y & lvl) > 0)
d += lvl * lvl * ((3 * rx) ^ ry)
x, y = _rotate(lvl, x, y, rx, ry)
lvl >>= 1
return d | Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int y value of point [0, dim) in dim x dim coord system
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
int: hashcode ∈ [0, dim**2) | Below is the the instruction that describes the task:
### Input:
Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int y value of point [0, dim) in dim x dim coord system
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
int: hashcode ∈ [0, dim**2)
### Response:
def _xy2hash(x, y, dim):
"""Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int y value of point [0, dim) in dim x dim coord system
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
int: hashcode ∈ [0, dim**2)
"""
d = 0
lvl = dim >> 1
while (lvl > 0):
rx = int((x & lvl) > 0)
ry = int((y & lvl) > 0)
d += lvl * lvl * ((3 * rx) ^ ry)
x, y = _rotate(lvl, x, y, rx, ry)
lvl >>= 1
return d |
def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None,
other=None):
"""
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will usually be an estimate of sigma^2. Scale is assumed to be
a scalar.
Parameters
----------
r_matrix : array-like
Can be 1d, or 2d. Can be used alone or with other.
column : array-like, optional
Must be used on its own. Can be 0d or 1d see below.
scale : float, optional
Can be specified or not. Default is None, which means that
the scale argument is taken from the model.
other : array-like, optional
Can be used when r_matrix is specified.
Returns
-------
cov : ndarray
covariance matrix of the parameter estimates or of linear
combination of parameter estimates. See Notes.
Notes
-----
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model
``(scale)*(X.T X)^(-1)``
If contrast is specified it pre and post-multiplies as follows
``(scale) * r_matrix (X.T X)^(-1) r_matrix.T``
If contrast and other are specified returns
``(scale) * r_matrix (X.T X)^(-1) other.T``
If column is specified returns
``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d
OR
``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d
"""
if (hasattr(self, 'mle_settings') and
self.mle_settings['optimizer'] in ['l1', 'l1_cvxopt_cp']):
dot_fun = nan_dot
else:
dot_fun = np.dot
if (cov_p is None and self.normalized_cov_params is None and
not hasattr(self, 'cov_params_default')):
raise ValueError('need covariance of parameters for computing '
'(unnormalized) covariances')
if column is not None and (r_matrix is not None or other is not None):
raise ValueError('Column should be specified without other '
'arguments.')
if other is not None and r_matrix is None:
raise ValueError('other can only be specified with r_matrix')
if cov_p is None:
if hasattr(self, 'cov_params_default'):
cov_p = self.cov_params_default
else:
if scale is None:
scale = self.scale
cov_p = self.normalized_cov_params * scale
if column is not None:
column = np.asarray(column)
if column.shape == ():
return cov_p[column, column]
else:
# return cov_p[column][:, column]
return cov_p[column[:, None], column]
elif r_matrix is not None:
r_matrix = np.asarray(r_matrix)
if r_matrix.shape == ():
raise ValueError("r_matrix should be 1d or 2d")
if other is None:
other = r_matrix
else:
other = np.asarray(other)
tmp = dot_fun(r_matrix, dot_fun(cov_p, np.transpose(other)))
return tmp
else: # if r_matrix is None and column is None:
return cov_p | Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will usually be an estimate of sigma^2. Scale is assumed to be
a scalar.
Parameters
----------
r_matrix : array-like
Can be 1d, or 2d. Can be used alone or with other.
column : array-like, optional
Must be used on its own. Can be 0d or 1d see below.
scale : float, optional
Can be specified or not. Default is None, which means that
the scale argument is taken from the model.
other : array-like, optional
Can be used when r_matrix is specified.
Returns
-------
cov : ndarray
covariance matrix of the parameter estimates or of linear
combination of parameter estimates. See Notes.
Notes
-----
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model
``(scale)*(X.T X)^(-1)``
If contrast is specified it pre and post-multiplies as follows
``(scale) * r_matrix (X.T X)^(-1) r_matrix.T``
If contrast and other are specified returns
``(scale) * r_matrix (X.T X)^(-1) other.T``
If column is specified returns
``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d
OR
``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d | Below is the the instruction that describes the task:
### Input:
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will usually be an estimate of sigma^2. Scale is assumed to be
a scalar.
Parameters
----------
r_matrix : array-like
Can be 1d, or 2d. Can be used alone or with other.
column : array-like, optional
Must be used on its own. Can be 0d or 1d see below.
scale : float, optional
Can be specified or not. Default is None, which means that
the scale argument is taken from the model.
other : array-like, optional
Can be used when r_matrix is specified.
Returns
-------
cov : ndarray
covariance matrix of the parameter estimates or of linear
combination of parameter estimates. See Notes.
Notes
-----
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model
``(scale)*(X.T X)^(-1)``
If contrast is specified it pre and post-multiplies as follows
``(scale) * r_matrix (X.T X)^(-1) r_matrix.T``
If contrast and other are specified returns
``(scale) * r_matrix (X.T X)^(-1) other.T``
If column is specified returns
``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d
OR
``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d
### Response:
def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None,
other=None):
"""
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will usually be an estimate of sigma^2. Scale is assumed to be
a scalar.
Parameters
----------
r_matrix : array-like
Can be 1d, or 2d. Can be used alone or with other.
column : array-like, optional
Must be used on its own. Can be 0d or 1d see below.
scale : float, optional
Can be specified or not. Default is None, which means that
the scale argument is taken from the model.
other : array-like, optional
Can be used when r_matrix is specified.
Returns
-------
cov : ndarray
covariance matrix of the parameter estimates or of linear
combination of parameter estimates. See Notes.
Notes
-----
(The below are assumed to be in matrix notation.)
If no argument is specified returns the covariance matrix of a model
``(scale)*(X.T X)^(-1)``
If contrast is specified it pre and post-multiplies as follows
``(scale) * r_matrix (X.T X)^(-1) r_matrix.T``
If contrast and other are specified returns
``(scale) * r_matrix (X.T X)^(-1) other.T``
If column is specified returns
``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d
OR
``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d
"""
if (hasattr(self, 'mle_settings') and
self.mle_settings['optimizer'] in ['l1', 'l1_cvxopt_cp']):
dot_fun = nan_dot
else:
dot_fun = np.dot
if (cov_p is None and self.normalized_cov_params is None and
not hasattr(self, 'cov_params_default')):
raise ValueError('need covariance of parameters for computing '
'(unnormalized) covariances')
if column is not None and (r_matrix is not None or other is not None):
raise ValueError('Column should be specified without other '
'arguments.')
if other is not None and r_matrix is None:
raise ValueError('other can only be specified with r_matrix')
if cov_p is None:
if hasattr(self, 'cov_params_default'):
cov_p = self.cov_params_default
else:
if scale is None:
scale = self.scale
cov_p = self.normalized_cov_params * scale
if column is not None:
column = np.asarray(column)
if column.shape == ():
return cov_p[column, column]
else:
# return cov_p[column][:, column]
return cov_p[column[:, None], column]
elif r_matrix is not None:
r_matrix = np.asarray(r_matrix)
if r_matrix.shape == ():
raise ValueError("r_matrix should be 1d or 2d")
if other is None:
other = r_matrix
else:
other = np.asarray(other)
tmp = dot_fun(r_matrix, dot_fun(cov_p, np.transpose(other)))
return tmp
else: # if r_matrix is None and column is None:
return cov_p |
def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs):
"""
Convert a textual representation of \*MRS from one the src_fmt
representation to the tgt_fmt representation. By default, only
read and convert a single \*MRS object (e.g. for `mrx` this
starts at <mrs> and not <mrs-list>), but changing the `mode`
argument to `corpus` (alternatively: `list`) reads and converts
multiple \*MRSs.
Args:
txt: A string of semantic data.
src_fmt: The original representation format of txt.
tgt_fmt: The representation format to convert to.
single: If True, assume txt represents a single \*MRS, otherwise
read it as a corpus (or list) of \*MRSs.
kwargs: Any other keyword arguments to pass to the serializer
of the target format. See Notes.
Returns:
A string in the target format.
Notes:
src_fmt and tgt_fmt may be one of the following:
| format | description |
| --------- | ---------------------------- |
| simplemrs | The popular SimpleMRS format |
| mrx | The XML format of MRS |
| dmrx | The XML format of DMRS |
Additional keyword arguments for the serializer may include:
| option | description |
| ------------ | ----------------------------------- |
| pretty_print | print with newlines and indentation |
| color | print with syntax highlighting |
"""
from importlib import import_module
reader = import_module('{}.{}'.format('delphin.mrs', src_fmt.lower()))
writer = import_module('{}.{}'.format('delphin.mrs', tgt_fmt.lower()))
return writer.dumps(
reader.loads(txt, single=single),
single=single,
**kwargs
) | Convert a textual representation of \*MRS from one the src_fmt
representation to the tgt_fmt representation. By default, only
read and convert a single \*MRS object (e.g. for `mrx` this
starts at <mrs> and not <mrs-list>), but changing the `mode`
argument to `corpus` (alternatively: `list`) reads and converts
multiple \*MRSs.
Args:
txt: A string of semantic data.
src_fmt: The original representation format of txt.
tgt_fmt: The representation format to convert to.
single: If True, assume txt represents a single \*MRS, otherwise
read it as a corpus (or list) of \*MRSs.
kwargs: Any other keyword arguments to pass to the serializer
of the target format. See Notes.
Returns:
A string in the target format.
Notes:
src_fmt and tgt_fmt may be one of the following:
| format | description |
| --------- | ---------------------------- |
| simplemrs | The popular SimpleMRS format |
| mrx | The XML format of MRS |
| dmrx | The XML format of DMRS |
Additional keyword arguments for the serializer may include:
| option | description |
| ------------ | ----------------------------------- |
| pretty_print | print with newlines and indentation |
| color | print with syntax highlighting | | Below is the the instruction that describes the task:
### Input:
Convert a textual representation of \*MRS from one the src_fmt
representation to the tgt_fmt representation. By default, only
read and convert a single \*MRS object (e.g. for `mrx` this
starts at <mrs> and not <mrs-list>), but changing the `mode`
argument to `corpus` (alternatively: `list`) reads and converts
multiple \*MRSs.
Args:
txt: A string of semantic data.
src_fmt: The original representation format of txt.
tgt_fmt: The representation format to convert to.
single: If True, assume txt represents a single \*MRS, otherwise
read it as a corpus (or list) of \*MRSs.
kwargs: Any other keyword arguments to pass to the serializer
of the target format. See Notes.
Returns:
A string in the target format.
Notes:
src_fmt and tgt_fmt may be one of the following:
| format | description |
| --------- | ---------------------------- |
| simplemrs | The popular SimpleMRS format |
| mrx | The XML format of MRS |
| dmrx | The XML format of DMRS |
Additional keyword arguments for the serializer may include:
| option | description |
| ------------ | ----------------------------------- |
| pretty_print | print with newlines and indentation |
| color | print with syntax highlighting |
### Response:
def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs):
"""
Convert a textual representation of \*MRS from one the src_fmt
representation to the tgt_fmt representation. By default, only
read and convert a single \*MRS object (e.g. for `mrx` this
starts at <mrs> and not <mrs-list>), but changing the `mode`
argument to `corpus` (alternatively: `list`) reads and converts
multiple \*MRSs.
Args:
txt: A string of semantic data.
src_fmt: The original representation format of txt.
tgt_fmt: The representation format to convert to.
single: If True, assume txt represents a single \*MRS, otherwise
read it as a corpus (or list) of \*MRSs.
kwargs: Any other keyword arguments to pass to the serializer
of the target format. See Notes.
Returns:
A string in the target format.
Notes:
src_fmt and tgt_fmt may be one of the following:
| format | description |
| --------- | ---------------------------- |
| simplemrs | The popular SimpleMRS format |
| mrx | The XML format of MRS |
| dmrx | The XML format of DMRS |
Additional keyword arguments for the serializer may include:
| option | description |
| ------------ | ----------------------------------- |
| pretty_print | print with newlines and indentation |
| color | print with syntax highlighting |
"""
from importlib import import_module
reader = import_module('{}.{}'.format('delphin.mrs', src_fmt.lower()))
writer = import_module('{}.{}'.format('delphin.mrs', tgt_fmt.lower()))
return writer.dumps(
reader.loads(txt, single=single),
single=single,
**kwargs
) |
def table(self, table):
"""
Modify a table on the schema.
:param table: The table
"""
try:
blueprint = self._create_blueprint(table)
yield blueprint
except Exception as e:
raise
try:
self._build(blueprint)
except Exception:
raise | Modify a table on the schema.
:param table: The table | Below is the the instruction that describes the task:
### Input:
Modify a table on the schema.
:param table: The table
### Response:
def table(self, table):
"""
Modify a table on the schema.
:param table: The table
"""
try:
blueprint = self._create_blueprint(table)
yield blueprint
except Exception as e:
raise
try:
self._build(blueprint)
except Exception:
raise |
def frets_to_NoteContainer(self, fingering):
"""Convert a list such as returned by find_fret to a NoteContainer."""
res = []
for (string, fret) in enumerate(fingering):
if fret is not None:
res.append(self.get_Note(string, fret))
return NoteContainer(res) | Convert a list such as returned by find_fret to a NoteContainer. | Below is the the instruction that describes the task:
### Input:
Convert a list such as returned by find_fret to a NoteContainer.
### Response:
def frets_to_NoteContainer(self, fingering):
"""Convert a list such as returned by find_fret to a NoteContainer."""
res = []
for (string, fret) in enumerate(fingering):
if fret is not None:
res.append(self.get_Note(string, fret))
return NoteContainer(res) |
def _deriv_logaddexp2(x1, x2):
"""The derivative of f(x, y) = log2(2^x + 2^y)"""
y1 = np.exp2(x1)
y2 = np.exp2(x2)
df_dx1 = y1 / (y1 + y2)
df_dx2 = y2 / (y1 + y2)
return np.vstack([df_dx1, df_dx2]).T | The derivative of f(x, y) = log2(2^x + 2^y) | Below is the the instruction that describes the task:
### Input:
The derivative of f(x, y) = log2(2^x + 2^y)
### Response:
def _deriv_logaddexp2(x1, x2):
"""The derivative of f(x, y) = log2(2^x + 2^y)"""
y1 = np.exp2(x1)
y2 = np.exp2(x2)
df_dx1 = y1 / (y1 + y2)
df_dx2 = y2 / (y1 + y2)
return np.vstack([df_dx1, df_dx2]).T |
def get_viz(self, force=False):
"""Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz
"""
slice_params = json.loads(self.params)
slice_params['slice_id'] = self.id
slice_params['json'] = 'false'
slice_params['slice_name'] = self.slice_name
slice_params['viz_type'] = self.viz_type if self.viz_type else 'table'
return viz_types[slice_params.get('viz_type')](
self.datasource,
form_data=slice_params,
force=force,
) | Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz | Below is the the instruction that describes the task:
### Input:
Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz
### Response:
def get_viz(self, force=False):
"""Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz
"""
slice_params = json.loads(self.params)
slice_params['slice_id'] = self.id
slice_params['json'] = 'false'
slice_params['slice_name'] = self.slice_name
slice_params['viz_type'] = self.viz_type if self.viz_type else 'table'
return viz_types[slice_params.get('viz_type')](
self.datasource,
form_data=slice_params,
force=force,
) |
def get_font_files():
"""Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['NotoSans-Bold'].endswith('/NotoSans-Bold.ttf')
True
"""
roots = [
'/usr/share/fonts/truetype', # where ubuntu puts fonts
'/usr/share/fonts', # where fedora puts fonts
os.path.expanduser('~/.fonts'), # custom user fonts
os.path.abspath(os.path.join(os.path.dirname(__file__), 'fonts')),
]
result = {}
for root in roots:
for path, dirs, names in os.walk(root):
for name in names:
if name.endswith(('.ttf', '.otf')):
result[name[:-4]] = os.path.join(path, name)
return result | Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['NotoSans-Bold'].endswith('/NotoSans-Bold.ttf')
True | Below is the the instruction that describes the task:
### Input:
Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['NotoSans-Bold'].endswith('/NotoSans-Bold.ttf')
True
### Response:
def get_font_files():
"""Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['NotoSans-Bold'].endswith('/NotoSans-Bold.ttf')
True
"""
roots = [
'/usr/share/fonts/truetype', # where ubuntu puts fonts
'/usr/share/fonts', # where fedora puts fonts
os.path.expanduser('~/.fonts'), # custom user fonts
os.path.abspath(os.path.join(os.path.dirname(__file__), 'fonts')),
]
result = {}
for root in roots:
for path, dirs, names in os.walk(root):
for name in names:
if name.endswith(('.ttf', '.otf')):
result[name[:-4]] = os.path.join(path, name)
return result |
def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]:
"""Eliminate dead code from function bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.FunctionDef)
return ast.copy_location(
ast.FunctionDef(
name=new_node.name,
args=new_node.args,
body=_filter_dead_code(new_node.body),
decorator_list=new_node.decorator_list,
returns=new_node.returns,
),
new_node,
) | Eliminate dead code from function bodies. | Below is the the instruction that describes the task:
### Input:
Eliminate dead code from function bodies.
### Response:
def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]:
"""Eliminate dead code from function bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.FunctionDef)
return ast.copy_location(
ast.FunctionDef(
name=new_node.name,
args=new_node.args,
body=_filter_dead_code(new_node.body),
decorator_list=new_node.decorator_list,
returns=new_node.returns,
),
new_node,
) |
def configure_logging(level=logging.DEBUG):
'''Configures the root logger for command line applications.
A stream handler will be added to the logger that directs
messages to the standard error stream.
By default, *no* messages will be filtered out: set a higher
level on derived/child loggers to achieve filtering.
Warning
-------
Logging should only be configured once at the main entry point of the
application!
'''
fmt = '%(asctime)s | %(levelname)-8s | %(name)-40s | %(message)s'
datefmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
logger = logging.getLogger() # returns the root logger
stderr_handler = logging.StreamHandler(stream=sys.stderr)
stderr_handler.name = 'err'
stderr_handler.setLevel(level)
stderr_handler.setFormatter(formatter)
logger.addHandler(stderr_handler) | Configures the root logger for command line applications.
A stream handler will be added to the logger that directs
messages to the standard error stream.
By default, *no* messages will be filtered out: set a higher
level on derived/child loggers to achieve filtering.
Warning
-------
Logging should only be configured once at the main entry point of the
application! | Below is the the instruction that describes the task:
### Input:
Configures the root logger for command line applications.
A stream handler will be added to the logger that directs
messages to the standard error stream.
By default, *no* messages will be filtered out: set a higher
level on derived/child loggers to achieve filtering.
Warning
-------
Logging should only be configured once at the main entry point of the
application!
### Response:
def configure_logging(level=logging.DEBUG):
'''Configures the root logger for command line applications.
A stream handler will be added to the logger that directs
messages to the standard error stream.
By default, *no* messages will be filtered out: set a higher
level on derived/child loggers to achieve filtering.
Warning
-------
Logging should only be configured once at the main entry point of the
application!
'''
fmt = '%(asctime)s | %(levelname)-8s | %(name)-40s | %(message)s'
datefmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
logger = logging.getLogger() # returns the root logger
stderr_handler = logging.StreamHandler(stream=sys.stderr)
stderr_handler.name = 'err'
stderr_handler.setLevel(level)
stderr_handler.setFormatter(formatter)
logger.addHandler(stderr_handler) |
def remove_user(self, name):
"""Remove a user from kubeconfig.
"""
user = self.get_user(name)
users = self.get_users()
users.remove(user) | Remove a user from kubeconfig. | Below is the the instruction that describes the task:
### Input:
Remove a user from kubeconfig.
### Response:
def remove_user(self, name):
"""Remove a user from kubeconfig.
"""
user = self.get_user(name)
users = self.get_users()
users.remove(user) |
def get_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint
"""
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} | Returns Dockerfile values for CMD and Entrypoint | Below is the the instruction that describes the task:
### Input:
Returns Dockerfile values for CMD and Entrypoint
### Response:
def get_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint
"""
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} |
def _get_kernel_data(self, nmr_samples, thinning, return_output):
"""Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of iterations to sample
* iteration_offset: the current sample index, that is, the offset to the given number of iterations
* rng_state: the random number generator state
* current_chain_position: the current position of the sampled chain
* current_log_likelihood: the log likelihood of the current position on the chain
* current_log_prior: the log prior of the current position on the chain
Additionally, if ``return_output`` is True, we add to that the arrays:
* samples: for the samples
* log_likelihoods: for storing the log likelihoods
* log_priors: for storing the priors
Args:
nmr_samples (int): the number of samples we will draw
thinning (int): the thinning factor we want to use
return_output (boolean): if the kernel should return output
Returns:
dict[str: mot.lib.utils.KernelData]: the kernel input data
"""
kernel_data = {
'data': self._data,
'method_data': self._get_mcmc_method_kernel_data(),
'nmr_iterations': Scalar(nmr_samples * thinning, ctype='ulong'),
'iteration_offset': Scalar(self._sampling_index, ctype='ulong'),
'rng_state': Array(self._rng_state, 'uint', mode='rw', ensure_zero_copy=True),
'current_chain_position': Array(self._current_chain_position, 'mot_float_type',
mode='rw', ensure_zero_copy=True),
'current_log_likelihood': Array(self._current_log_likelihood, 'mot_float_type',
mode='rw', ensure_zero_copy=True),
'current_log_prior': Array(self._current_log_prior, 'mot_float_type',
mode='rw', ensure_zero_copy=True),
}
if return_output:
kernel_data.update({
'samples': Zeros((self._nmr_problems, self._nmr_params, nmr_samples), ctype='mot_float_type'),
'log_likelihoods': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'),
'log_priors': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'),
})
return kernel_data | Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of iterations to sample
* iteration_offset: the current sample index, that is, the offset to the given number of iterations
* rng_state: the random number generator state
* current_chain_position: the current position of the sampled chain
* current_log_likelihood: the log likelihood of the current position on the chain
* current_log_prior: the log prior of the current position on the chain
Additionally, if ``return_output`` is True, we add to that the arrays:
* samples: for the samples
* log_likelihoods: for storing the log likelihoods
* log_priors: for storing the priors
Args:
nmr_samples (int): the number of samples we will draw
thinning (int): the thinning factor we want to use
return_output (boolean): if the kernel should return output
Returns:
dict[str: mot.lib.utils.KernelData]: the kernel input data | Below is the the instruction that describes the task:
### Input:
Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of iterations to sample
* iteration_offset: the current sample index, that is, the offset to the given number of iterations
* rng_state: the random number generator state
* current_chain_position: the current position of the sampled chain
* current_log_likelihood: the log likelihood of the current position on the chain
* current_log_prior: the log prior of the current position on the chain
Additionally, if ``return_output`` is True, we add to that the arrays:
* samples: for the samples
* log_likelihoods: for storing the log likelihoods
* log_priors: for storing the priors
Args:
nmr_samples (int): the number of samples we will draw
thinning (int): the thinning factor we want to use
return_output (boolean): if the kernel should return output
Returns:
dict[str: mot.lib.utils.KernelData]: the kernel input data
### Response:
def _get_kernel_data(self, nmr_samples, thinning, return_output):
"""Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of iterations to sample
* iteration_offset: the current sample index, that is, the offset to the given number of iterations
* rng_state: the random number generator state
* current_chain_position: the current position of the sampled chain
* current_log_likelihood: the log likelihood of the current position on the chain
* current_log_prior: the log prior of the current position on the chain
Additionally, if ``return_output`` is True, we add to that the arrays:
* samples: for the samples
* log_likelihoods: for storing the log likelihoods
* log_priors: for storing the priors
Args:
nmr_samples (int): the number of samples we will draw
thinning (int): the thinning factor we want to use
return_output (boolean): if the kernel should return output
Returns:
dict[str: mot.lib.utils.KernelData]: the kernel input data
"""
kernel_data = {
'data': self._data,
'method_data': self._get_mcmc_method_kernel_data(),
'nmr_iterations': Scalar(nmr_samples * thinning, ctype='ulong'),
'iteration_offset': Scalar(self._sampling_index, ctype='ulong'),
'rng_state': Array(self._rng_state, 'uint', mode='rw', ensure_zero_copy=True),
'current_chain_position': Array(self._current_chain_position, 'mot_float_type',
mode='rw', ensure_zero_copy=True),
'current_log_likelihood': Array(self._current_log_likelihood, 'mot_float_type',
mode='rw', ensure_zero_copy=True),
'current_log_prior': Array(self._current_log_prior, 'mot_float_type',
mode='rw', ensure_zero_copy=True),
}
if return_output:
kernel_data.update({
'samples': Zeros((self._nmr_problems, self._nmr_params, nmr_samples), ctype='mot_float_type'),
'log_likelihoods': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'),
'log_priors': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'),
})
return kernel_data |
def queue_raw_jobs(queue, params_list, **kwargs):
""" Queue some jobs on a raw queue """
from .queue import Queue
queue_obj = Queue(queue)
queue_obj.enqueue_raw_jobs(params_list, **kwargs) | Queue some jobs on a raw queue | Below is the the instruction that describes the task:
### Input:
Queue some jobs on a raw queue
### Response:
def queue_raw_jobs(queue, params_list, **kwargs):
""" Queue some jobs on a raw queue """
from .queue import Queue
queue_obj = Queue(queue)
queue_obj.enqueue_raw_jobs(params_list, **kwargs) |
def _transition_loop(self):
"""Execute all queued transitions step by step."""
while self._transitions:
start = time.time()
for transition in self._transitions:
transition.step()
if transition.finished:
self._transitions.remove(transition)
time_delta = time.time() - start
sleep_time = max(0, self.MIN_STEP_TIME - time_delta)
time.sleep(sleep_time) | Execute all queued transitions step by step. | Below is the the instruction that describes the task:
### Input:
Execute all queued transitions step by step.
### Response:
def _transition_loop(self):
"""Execute all queued transitions step by step."""
while self._transitions:
start = time.time()
for transition in self._transitions:
transition.step()
if transition.finished:
self._transitions.remove(transition)
time_delta = time.time() - start
sleep_time = max(0, self.MIN_STEP_TIME - time_delta)
time.sleep(sleep_time) |
def blue(self, memo=None):
"""
Constructs a BlueDispatcher out of the current object.
:param memo:
A dictionary to cache Blueprints.
:type memo: dict[T,schedula.utils.blue.Blueprint]
:return:
A BlueDispatcher of the current object.
:rtype: schedula.utils.blue.BlueDispatcher
"""
memo = {} if memo is None else memo
if self in memo:
return memo[self]
from .utils.dsp import map_list
from .utils.blue import BlueDispatcher, _parent_blue
memo[self] = blue = BlueDispatcher(
executor=self.executor, name=self.name, raises=self.raises,
description=self.__doc__
)
dfl = self.default_values
key_map_data = ['data_id', {'value': 'default_value'}]
pred, succ = self.dmap.pred, self.dmap.succ
def _set_weight(n, r, d):
d = {i: j['weight'] for i, j in d.items() if 'weight' in j}
if d:
r[n] = d
for k, v in sorted(self.nodes.items(), key=lambda x: x[1]['index']):
v = v.copy()
t = v.pop('type')
del v['index']
if t == 'data':
method = 'add_data'
combine_dicts(map_list(key_map_data, k, dfl.get(k, {})), base=v)
elif t in ('function', 'dispatcher'):
method = 'add_%s' % t
if t == 'dispatcher':
t = 'dsp'
v['%s_id' % t] = k
del v['wait_inputs']
_set_weight('inp_weight', v, pred[k])
_set_weight('out_weight', v, succ[k])
if 'function' in v:
v[t] = _parent_blue(v.pop('function'), memo)
blue.deferred.append((method, v))
return blue | Constructs a BlueDispatcher out of the current object.
:param memo:
A dictionary to cache Blueprints.
:type memo: dict[T,schedula.utils.blue.Blueprint]
:return:
A BlueDispatcher of the current object.
:rtype: schedula.utils.blue.BlueDispatcher | Below is the the instruction that describes the task:
### Input:
Constructs a BlueDispatcher out of the current object.
:param memo:
A dictionary to cache Blueprints.
:type memo: dict[T,schedula.utils.blue.Blueprint]
:return:
A BlueDispatcher of the current object.
:rtype: schedula.utils.blue.BlueDispatcher
### Response:
def blue(self, memo=None):
"""
Constructs a BlueDispatcher out of the current object.
:param memo:
A dictionary to cache Blueprints.
:type memo: dict[T,schedula.utils.blue.Blueprint]
:return:
A BlueDispatcher of the current object.
:rtype: schedula.utils.blue.BlueDispatcher
"""
memo = {} if memo is None else memo
if self in memo:
return memo[self]
from .utils.dsp import map_list
from .utils.blue import BlueDispatcher, _parent_blue
memo[self] = blue = BlueDispatcher(
executor=self.executor, name=self.name, raises=self.raises,
description=self.__doc__
)
dfl = self.default_values
key_map_data = ['data_id', {'value': 'default_value'}]
pred, succ = self.dmap.pred, self.dmap.succ
def _set_weight(n, r, d):
d = {i: j['weight'] for i, j in d.items() if 'weight' in j}
if d:
r[n] = d
for k, v in sorted(self.nodes.items(), key=lambda x: x[1]['index']):
v = v.copy()
t = v.pop('type')
del v['index']
if t == 'data':
method = 'add_data'
combine_dicts(map_list(key_map_data, k, dfl.get(k, {})), base=v)
elif t in ('function', 'dispatcher'):
method = 'add_%s' % t
if t == 'dispatcher':
t = 'dsp'
v['%s_id' % t] = k
del v['wait_inputs']
_set_weight('inp_weight', v, pred[k])
_set_weight('out_weight', v, succ[k])
if 'function' in v:
v[t] = _parent_blue(v.pop('function'), memo)
blue.deferred.append((method, v))
return blue |
def mimic_user_input(
args: List[str],
source_challenge_response: List[Tuple[SubprocSource,
str,
Union[str, SubprocCommand]]],
line_terminators: List[str] = None,
print_stdout: bool = False,
print_stderr: bool = False,
print_stdin: bool = False,
stdin_encoding: str = None,
stdout_encoding: str = None,
suppress_decoding_errors: bool = True,
sleep_time_s: float = 0.1) -> None:
r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(challsrc,
challenge, response)``; see below
line_terminators: valid line terminators
print_stdout:
print_stderr:
print_stdin:
stdin_encoding:
stdout_encoding:
suppress_decoding_errors: trap any ``UnicodeDecodeError``?
sleep_time_s:
The ``(challsrc, challenge, response)`` tuples have this meaning:
- ``challsrc``: where is the challenge coming from? Must be one of the
objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`;
- ``challenge``: text of challenge
- ``response``: text of response (send to the subcommand's ``stdin``).
Example (modified from :class:`CorruptedZipReader`):
.. code-block:: python
from cardinal_pythonlib.subproc import *
SOURCE_FILENAME = "corrupt.zip"
TMP_DIR = "/tmp"
OUTPUT_FILENAME = "rescued.zip"
cmdargs = [
"zip", # Linux zip tool
"-FF", # or "--fixfix": "fix very broken things"
SOURCE_FILENAME, # input file
"--temp-path", TMP_DIR, # temporary storage path
"--out", OUTPUT_FILENAME # output file
]
# We would like to be able to say "y" automatically to
# "Is this a single-disk archive? (y/n):"
# The source code (api.c, zip.c, zipfile.c), from
# ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q"
# should do this (internally "-q" sets "noisy = 0") - but in
# practice it doesn't work. This is a critical switch.
# Therefore we will do something very ugly, and send raw text via
# stdin.
ZIP_PROMPTS_RESPONSES = [
(SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"),
(SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"),
(SOURCE_STDERR,
"zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) "
"&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && "
"prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) "
"== 0)' failed.", TERMINATE_SUBPROCESS),
]
ZIP_STDOUT_TERMINATORS = ["\n", "): "]
mimic_user_input(cmdargs,
source_challenge_response=ZIP_PROMPTS_RESPONSES,
line_terminators=ZIP_STDOUT_TERMINATORS,
print_stdout=show_zip_output,
print_stdin=show_zip_output)
""" # noqa
line_terminators = line_terminators or ["\n"] # type: List[str]
stdin_encoding = stdin_encoding or sys.getdefaultencoding()
stdout_encoding = stdout_encoding or sys.getdefaultencoding()
# Launch the command
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0)
# Launch the asynchronous readers of stdout and stderr
stdout_queue = Queue()
# noinspection PyTypeChecker
stdout_reader = AsynchronousFileReader(
fd=p.stdout,
queue=stdout_queue,
encoding=stdout_encoding,
line_terminators=line_terminators,
cmdargs=args,
suppress_decoding_errors=suppress_decoding_errors
)
stdout_reader.start()
stderr_queue = Queue()
# noinspection PyTypeChecker
stderr_reader = AsynchronousFileReader(
fd=p.stderr,
queue=stderr_queue,
encoding=stdout_encoding, # same as stdout
line_terminators=line_terminators,
cmdargs=args,
suppress_decoding_errors=suppress_decoding_errors
)
stderr_reader.start()
while not stdout_reader.eof() or not stderr_reader.eof():
lines_with_source = [] # type: List[Tuple[SubprocSource, str]]
while not stdout_queue.empty():
lines_with_source.append((SOURCE_STDOUT, stdout_queue.get()))
while not stderr_queue.empty():
lines_with_source.append((SOURCE_STDERR, stderr_queue.get()))
for src, line in lines_with_source:
if src is SOURCE_STDOUT and print_stdout:
print(line, end="") # terminator already in line
if src is SOURCE_STDERR and print_stderr:
print(line, end="") # terminator already in line
for challsrc, challenge, response in source_challenge_response:
# log.critical("challsrc={!r}", challsrc)
# log.critical("challenge={!r}", challenge)
# log.critical("line={!r}", line)
# log.critical("response={!r}", response)
if challsrc != src:
continue
if challenge in line:
if response is TERMINATE_SUBPROCESS:
log.warning("Terminating subprocess {!r} because input "
"{!r} received", args, challenge)
p.kill()
return
else:
p.stdin.write(response.encode(stdin_encoding))
p.stdin.flush()
if print_stdin:
print(response, end="")
# Sleep a bit before asking the readers again.
sleep(sleep_time_s)
stdout_reader.join()
stderr_reader.join()
p.stdout.close()
p.stderr.close() | r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(challsrc,
challenge, response)``; see below
line_terminators: valid line terminators
print_stdout:
print_stderr:
print_stdin:
stdin_encoding:
stdout_encoding:
suppress_decoding_errors: trap any ``UnicodeDecodeError``?
sleep_time_s:
The ``(challsrc, challenge, response)`` tuples have this meaning:
- ``challsrc``: where is the challenge coming from? Must be one of the
objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`;
- ``challenge``: text of challenge
- ``response``: text of response (send to the subcommand's ``stdin``).
Example (modified from :class:`CorruptedZipReader`):
.. code-block:: python
from cardinal_pythonlib.subproc import *
SOURCE_FILENAME = "corrupt.zip"
TMP_DIR = "/tmp"
OUTPUT_FILENAME = "rescued.zip"
cmdargs = [
"zip", # Linux zip tool
"-FF", # or "--fixfix": "fix very broken things"
SOURCE_FILENAME, # input file
"--temp-path", TMP_DIR, # temporary storage path
"--out", OUTPUT_FILENAME # output file
]
# We would like to be able to say "y" automatically to
# "Is this a single-disk archive? (y/n):"
# The source code (api.c, zip.c, zipfile.c), from
# ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q"
# should do this (internally "-q" sets "noisy = 0") - but in
# practice it doesn't work. This is a critical switch.
# Therefore we will do something very ugly, and send raw text via
# stdin.
ZIP_PROMPTS_RESPONSES = [
(SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"),
(SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"),
(SOURCE_STDERR,
"zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) "
"&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && "
"prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) "
"== 0)' failed.", TERMINATE_SUBPROCESS),
]
ZIP_STDOUT_TERMINATORS = ["\n", "): "]
mimic_user_input(cmdargs,
source_challenge_response=ZIP_PROMPTS_RESPONSES,
line_terminators=ZIP_STDOUT_TERMINATORS,
print_stdout=show_zip_output,
print_stdin=show_zip_output) | Below is the the instruction that describes the task:
### Input:
r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(challsrc,
challenge, response)``; see below
line_terminators: valid line terminators
print_stdout:
print_stderr:
print_stdin:
stdin_encoding:
stdout_encoding:
suppress_decoding_errors: trap any ``UnicodeDecodeError``?
sleep_time_s:
The ``(challsrc, challenge, response)`` tuples have this meaning:
- ``challsrc``: where is the challenge coming from? Must be one of the
objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`;
- ``challenge``: text of challenge
- ``response``: text of response (send to the subcommand's ``stdin``).
Example (modified from :class:`CorruptedZipReader`):
.. code-block:: python
from cardinal_pythonlib.subproc import *
SOURCE_FILENAME = "corrupt.zip"
TMP_DIR = "/tmp"
OUTPUT_FILENAME = "rescued.zip"
cmdargs = [
"zip", # Linux zip tool
"-FF", # or "--fixfix": "fix very broken things"
SOURCE_FILENAME, # input file
"--temp-path", TMP_DIR, # temporary storage path
"--out", OUTPUT_FILENAME # output file
]
# We would like to be able to say "y" automatically to
# "Is this a single-disk archive? (y/n):"
# The source code (api.c, zip.c, zipfile.c), from
# ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q"
# should do this (internally "-q" sets "noisy = 0") - but in
# practice it doesn't work. This is a critical switch.
# Therefore we will do something very ugly, and send raw text via
# stdin.
ZIP_PROMPTS_RESPONSES = [
(SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"),
(SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"),
(SOURCE_STDERR,
"zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) "
"&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && "
"prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) "
"== 0)' failed.", TERMINATE_SUBPROCESS),
]
ZIP_STDOUT_TERMINATORS = ["\n", "): "]
mimic_user_input(cmdargs,
source_challenge_response=ZIP_PROMPTS_RESPONSES,
line_terminators=ZIP_STDOUT_TERMINATORS,
print_stdout=show_zip_output,
print_stdin=show_zip_output)
### Response:
def mimic_user_input(
args: List[str],
source_challenge_response: List[Tuple[SubprocSource,
str,
Union[str, SubprocCommand]]],
line_terminators: List[str] = None,
print_stdout: bool = False,
print_stderr: bool = False,
print_stdin: bool = False,
stdin_encoding: str = None,
stdout_encoding: str = None,
suppress_decoding_errors: bool = True,
sleep_time_s: float = 0.1) -> None:
r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(challsrc,
challenge, response)``; see below
line_terminators: valid line terminators
print_stdout:
print_stderr:
print_stdin:
stdin_encoding:
stdout_encoding:
suppress_decoding_errors: trap any ``UnicodeDecodeError``?
sleep_time_s:
The ``(challsrc, challenge, response)`` tuples have this meaning:
- ``challsrc``: where is the challenge coming from? Must be one of the
objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`;
- ``challenge``: text of challenge
- ``response``: text of response (send to the subcommand's ``stdin``).
Example (modified from :class:`CorruptedZipReader`):
.. code-block:: python
from cardinal_pythonlib.subproc import *
SOURCE_FILENAME = "corrupt.zip"
TMP_DIR = "/tmp"
OUTPUT_FILENAME = "rescued.zip"
cmdargs = [
"zip", # Linux zip tool
"-FF", # or "--fixfix": "fix very broken things"
SOURCE_FILENAME, # input file
"--temp-path", TMP_DIR, # temporary storage path
"--out", OUTPUT_FILENAME # output file
]
# We would like to be able to say "y" automatically to
# "Is this a single-disk archive? (y/n):"
# The source code (api.c, zip.c, zipfile.c), from
# ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q"
# should do this (internally "-q" sets "noisy = 0") - but in
# practice it doesn't work. This is a critical switch.
# Therefore we will do something very ugly, and send raw text via
# stdin.
ZIP_PROMPTS_RESPONSES = [
(SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"),
(SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"),
(SOURCE_STDERR,
"zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) "
"&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && "
"prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) "
"== 0)' failed.", TERMINATE_SUBPROCESS),
]
ZIP_STDOUT_TERMINATORS = ["\n", "): "]
mimic_user_input(cmdargs,
source_challenge_response=ZIP_PROMPTS_RESPONSES,
line_terminators=ZIP_STDOUT_TERMINATORS,
print_stdout=show_zip_output,
print_stdin=show_zip_output)
""" # noqa
line_terminators = line_terminators or ["\n"] # type: List[str]
stdin_encoding = stdin_encoding or sys.getdefaultencoding()
stdout_encoding = stdout_encoding or sys.getdefaultencoding()
# Launch the command
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0)
# Launch the asynchronous readers of stdout and stderr
stdout_queue = Queue()
# noinspection PyTypeChecker
stdout_reader = AsynchronousFileReader(
fd=p.stdout,
queue=stdout_queue,
encoding=stdout_encoding,
line_terminators=line_terminators,
cmdargs=args,
suppress_decoding_errors=suppress_decoding_errors
)
stdout_reader.start()
stderr_queue = Queue()
# noinspection PyTypeChecker
stderr_reader = AsynchronousFileReader(
fd=p.stderr,
queue=stderr_queue,
encoding=stdout_encoding, # same as stdout
line_terminators=line_terminators,
cmdargs=args,
suppress_decoding_errors=suppress_decoding_errors
)
stderr_reader.start()
while not stdout_reader.eof() or not stderr_reader.eof():
lines_with_source = [] # type: List[Tuple[SubprocSource, str]]
while not stdout_queue.empty():
lines_with_source.append((SOURCE_STDOUT, stdout_queue.get()))
while not stderr_queue.empty():
lines_with_source.append((SOURCE_STDERR, stderr_queue.get()))
for src, line in lines_with_source:
if src is SOURCE_STDOUT and print_stdout:
print(line, end="") # terminator already in line
if src is SOURCE_STDERR and print_stderr:
print(line, end="") # terminator already in line
for challsrc, challenge, response in source_challenge_response:
# log.critical("challsrc={!r}", challsrc)
# log.critical("challenge={!r}", challenge)
# log.critical("line={!r}", line)
# log.critical("response={!r}", response)
if challsrc != src:
continue
if challenge in line:
if response is TERMINATE_SUBPROCESS:
log.warning("Terminating subprocess {!r} because input "
"{!r} received", args, challenge)
p.kill()
return
else:
p.stdin.write(response.encode(stdin_encoding))
p.stdin.flush()
if print_stdin:
print(response, end="")
# Sleep a bit before asking the readers again.
sleep(sleep_time_s)
stdout_reader.join()
stderr_reader.join()
p.stdout.close()
p.stderr.close() |
def leaveoneout(self):
"""Train & Test using leave one out"""
traintestfile = self.fileprefix + '.train'
options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out"
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
self.api = timblapi.TimblAPI(options, "")
if self.debug:
print("Enabling debug for timblapi",file=stderr)
self.api.enableDebug()
print("Calling Timbl API : " + options,file=stderr)
if sys.version < '3':
self.api.learn(b(traintestfile))
self.api.test(b(traintestfile), b(self.fileprefix + '.out'),b'')
else:
self.api.learn(u(traintestfile))
self.api.test(u(traintestfile), u(self.fileprefix + '.out'),'')
return self.api.getAccuracy() | Train & Test using leave one out | Below is the the instruction that describes the task:
### Input:
Train & Test using leave one out
### Response:
def leaveoneout(self):
"""Train & Test using leave one out"""
traintestfile = self.fileprefix + '.train'
options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out"
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
self.api = timblapi.TimblAPI(options, "")
if self.debug:
print("Enabling debug for timblapi",file=stderr)
self.api.enableDebug()
print("Calling Timbl API : " + options,file=stderr)
if sys.version < '3':
self.api.learn(b(traintestfile))
self.api.test(b(traintestfile), b(self.fileprefix + '.out'),b'')
else:
self.api.learn(u(traintestfile))
self.api.test(u(traintestfile), u(self.fileprefix + '.out'),'')
return self.api.getAccuracy() |
def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
redisent = self.redises[self._getnodenamefor(key) + '_slave']
return getattr(redisent, 'object')(infotype, key) | Return the encoding, idletime, or refcount about the key | Below is the the instruction that describes the task:
### Input:
Return the encoding, idletime, or refcount about the key
### Response:
def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
redisent = self.redises[self._getnodenamefor(key) + '_slave']
return getattr(redisent, 'object')(infotype, key) |
def set_uploaded(self, files_uploaded):
""" set_uploaded: records progress after uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None
"""
self.files_uploaded = files_uploaded
self.__record_progress(Status.UPLOAD_CHANNEL) | set_uploaded: records progress after uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None | Below is the the instruction that describes the task:
### Input:
set_uploaded: records progress after uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None
### Response:
def set_uploaded(self, files_uploaded):
""" set_uploaded: records progress after uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None
"""
self.files_uploaded = files_uploaded
self.__record_progress(Status.UPLOAD_CHANNEL) |
def json_2_cluster(json_obj):
"""
transform json from Ariane server to local object
:param json_obj: json from Ariane Server
:return: transformed cluster
"""
LOGGER.debug("Cluster.json_2_cluster")
return Cluster(
cid=json_obj['clusterID'],
name=json_obj['clusterName'],
containers_id=json_obj['clusterContainersID'],
ignore_sync=True
) | transform json from Ariane server to local object
:param json_obj: json from Ariane Server
:return: transformed cluster | Below is the the instruction that describes the task:
### Input:
transform json from Ariane server to local object
:param json_obj: json from Ariane Server
:return: transformed cluster
### Response:
def json_2_cluster(json_obj):
"""
transform json from Ariane server to local object
:param json_obj: json from Ariane Server
:return: transformed cluster
"""
LOGGER.debug("Cluster.json_2_cluster")
return Cluster(
cid=json_obj['clusterID'],
name=json_obj['clusterName'],
containers_id=json_obj['clusterContainersID'],
ignore_sync=True
) |
def checkValidCell(self, index):
"""Asks the model if the value at *index* is valid
See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>`
"""
col = index.column()
row = index.row()
return self.model.isFieldValid(row, self._headers[index.column()]) | Asks the model if the value at *index* is valid
See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>` | Below is the the instruction that describes the task:
### Input:
Asks the model if the value at *index* is valid
See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>`
### Response:
def checkValidCell(self, index):
"""Asks the model if the value at *index* is valid
See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>`
"""
col = index.column()
row = index.row()
return self.model.isFieldValid(row, self._headers[index.column()]) |
def load_v4_tools():
""" Load Gromacs 4.x tools automatically using some heuristic.
Tries to load tools (1) in configured tool groups (2) and fails back to
automatic detection from ``GMXBIN`` (3) then to a prefilled list.
Also load any extra tool configured in ``~/.gromacswrapper.cfg``
:return: dict mapping tool names to GromacsCommand classes
"""
logger.debug("Loading v4 tools...")
names = config.get_tool_names()
if len(names) == 0 and 'GMXBIN' in os.environ:
names = find_executables(os.environ['GMXBIN'])
if len(names) == 0 or len(names) > len(V4TOOLS) * 4:
names = list(V4TOOLS)
names.extend(config.get_extra_tool_names())
tools = {}
for name in names:
fancy = make_valid_identifier(name)
tools[fancy] = tool_factory(fancy, name, None)
if not tools:
errmsg = "Failed to load v4 tools"
logger.debug(errmsg)
raise GromacsToolLoadingError(errmsg)
logger.debug("Loaded {0} v4 tools successfully!".format(len(tools)))
return tools | Load Gromacs 4.x tools automatically using some heuristic.
Tries to load tools (1) in configured tool groups (2) and fails back to
automatic detection from ``GMXBIN`` (3) then to a prefilled list.
Also load any extra tool configured in ``~/.gromacswrapper.cfg``
:return: dict mapping tool names to GromacsCommand classes | Below is the the instruction that describes the task:
### Input:
Load Gromacs 4.x tools automatically using some heuristic.
Tries to load tools (1) in configured tool groups (2) and fails back to
automatic detection from ``GMXBIN`` (3) then to a prefilled list.
Also load any extra tool configured in ``~/.gromacswrapper.cfg``
:return: dict mapping tool names to GromacsCommand classes
### Response:
def load_v4_tools():
""" Load Gromacs 4.x tools automatically using some heuristic.
Tries to load tools (1) in configured tool groups (2) and fails back to
automatic detection from ``GMXBIN`` (3) then to a prefilled list.
Also load any extra tool configured in ``~/.gromacswrapper.cfg``
:return: dict mapping tool names to GromacsCommand classes
"""
logger.debug("Loading v4 tools...")
names = config.get_tool_names()
if len(names) == 0 and 'GMXBIN' in os.environ:
names = find_executables(os.environ['GMXBIN'])
if len(names) == 0 or len(names) > len(V4TOOLS) * 4:
names = list(V4TOOLS)
names.extend(config.get_extra_tool_names())
tools = {}
for name in names:
fancy = make_valid_identifier(name)
tools[fancy] = tool_factory(fancy, name, None)
if not tools:
errmsg = "Failed to load v4 tools"
logger.debug(errmsg)
raise GromacsToolLoadingError(errmsg)
logger.debug("Loaded {0} v4 tools successfully!".format(len(tools)))
return tools |
def add_args_kwargs(func):
"""Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper
"""
@wraps(func)
def wrapper(*args, **kwargs):
props = argspec(func)
# if 'args' not in props:
if isinstance(props[1], type(None)):
args = args[:len(props[0])]
if ((not isinstance(props[2], type(None))) or
(not isinstance(props[3], type(None)))):
return func(*args, **kwargs)
else:
return func(*args)
return wrapper | Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper | Below is the the instruction that describes the task:
### Input:
Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper
### Response:
def add_args_kwargs(func):
"""Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper
"""
@wraps(func)
def wrapper(*args, **kwargs):
props = argspec(func)
# if 'args' not in props:
if isinstance(props[1], type(None)):
args = args[:len(props[0])]
if ((not isinstance(props[2], type(None))) or
(not isinstance(props[3], type(None)))):
return func(*args, **kwargs)
else:
return func(*args)
return wrapper |
def handle(self, *args, **options):
"""Run do_index_command on each specified index and log the output."""
for index in options.pop("indexes"):
data = {}
try:
data = self.do_index_command(index, **options)
except TransportError as ex:
logger.warning("ElasticSearch threw an error: %s", ex)
data = {"index": index, "status": ex.status_code, "reason": ex.error}
finally:
logger.info(data) | Run do_index_command on each specified index and log the output. | Below is the the instruction that describes the task:
### Input:
Run do_index_command on each specified index and log the output.
### Response:
def handle(self, *args, **options):
"""Run do_index_command on each specified index and log the output."""
for index in options.pop("indexes"):
data = {}
try:
data = self.do_index_command(index, **options)
except TransportError as ex:
logger.warning("ElasticSearch threw an error: %s", ex)
data = {"index": index, "status": ex.status_code, "reason": ex.error}
finally:
logger.info(data) |
def make_interactive_tree(matrix=None,labels=None):
'''make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
'''
from scipy.cluster.hierarchy import (
dendrogram,
linkage,
to_tree
)
d3 = None
from scipy.cluster.hierarchy import cophenet
from scipy.spatial.distance import pdist
if isinstance(matrix,pandas.DataFrame):
Z = linkage(matrix, 'ward') # clusters
T = to_tree(Z, rd=False)
if labels == None:
labels = matrix.index.tolist()
lookup = dict(zip(range(len(labels)), labels))
# Create a dendrogram object without plotting
dend = dendrogram(Z,no_plot=True,
orientation="right",
leaf_rotation=90., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
labels=labels)
d3 = dict(children=[], name="root")
add_node(T, d3)
label_tree(d3["children"][0],lookup)
else:
bot.warning('Please provide data as pandas Data Frame.')
return d3 | make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out. | Below is the the instruction that describes the task:
### Input:
make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
### Response:
def make_interactive_tree(matrix=None,labels=None):
'''make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
'''
from scipy.cluster.hierarchy import (
dendrogram,
linkage,
to_tree
)
d3 = None
from scipy.cluster.hierarchy import cophenet
from scipy.spatial.distance import pdist
if isinstance(matrix,pandas.DataFrame):
Z = linkage(matrix, 'ward') # clusters
T = to_tree(Z, rd=False)
if labels == None:
labels = matrix.index.tolist()
lookup = dict(zip(range(len(labels)), labels))
# Create a dendrogram object without plotting
dend = dendrogram(Z,no_plot=True,
orientation="right",
leaf_rotation=90., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
labels=labels)
d3 = dict(children=[], name="root")
add_node(T, d3)
label_tree(d3["children"][0],lookup)
else:
bot.warning('Please provide data as pandas Data Frame.')
return d3 |
def seqs_from_file(filename, exit_on_err=False, return_qual=False):
"""Extract sequences from a file
Name:
seqs_from_file
Author(s):
Martin C F Thomsen
Date:
18 Jul 2013
Description:
Iterator which extract sequence data from the input file
Args:
filename: string which contain a path to the input file
Supported Formats:
fasta, fastq
USAGE:
>>> import os, sys
>>> # Create fasta test file
>>> file_content = ('>head1 desc1\nthis_is_seq_1\n>head2 desc2\n'
'this_is_seq_2\n>head3 desc3\nthis_is_seq_3\n')
>>> with open_('test.fsa', 'w') as f: f.write(file_content)
>>> # Parse and print the fasta file
>>> for seq, name, desc in SeqsFromFile('test.fsa'):
... print ">%s %s\n%s"%(name, desc, seq)
...
>head1 desc1
this_is_seq_1
>head2 desc2
this_is_seq_2
>head3 desc3
this_is_seq_3
"""
# VALIDATE INPUT
if not isinstance(filename, str):
msg = 'Filename has to be a string.'
if exit_on_err:
sys.stderr.write('Error: %s\n'%msg)
sys.exit(1)
else: raise IOError(msg)
if not os.path.exists(filename):
msg = 'File "%s" does not exist.'%filename
if exit_on_err:
sys.stderr.write('Error: %s\n'%msg)
sys.exit(1)
else: raise IOError(msg)
# EXTRACT DATA
with open_(filename,"rt") as f:
query_seq_segments = []
seq, name, desc, qual = '', '', '', ''
add_segment = query_seq_segments.append
for l in f:
if len(l.strip()) == 0: continue
#sys.stderr.write("%s\n"%line)
fields=l.strip().split()
if l.startswith(">"):
# FASTA HEADER FOUND
if query_seq_segments != []:
# YIELD SEQUENCE AND RESET
seq = ''.join(query_seq_segments)
yield (seq, name, desc)
seq, name, desc = '', '', ''
del query_seq_segments[:]
name = fields[0][1:]
desc = ' '.join(fields[1:])
elif l.startswith("@"):
# FASTQ HEADER FOUND
name = fields[0][1:]
desc = ' '.join(fields[1:])
try:
# EXTRACT FASTQ SEQUENCE
seq = next(f).strip().split()[0]
# SKIP SECOND HEADER LINE AND QUALITY SCORES
l = next(f)
qual = next(f).strip() # Qualities
except:
break
else:
# YIELD SEQUENCE AND RESET
if return_qual:
yield (seq, qual, name, desc)
else:
yield (seq, name, desc)
seq, name, desc, qual = '', '', '', ''
elif len(fields[0])>0:
# EXTRACT FASTA SEQUENCE
add_segment(fields[0])
# CHECK FOR LAST FASTA SEQUENCE
if query_seq_segments != []:
# YIELD SEQUENCE
seq = ''.join(query_seq_segments)
yield (seq, name, desc) | Extract sequences from a file
Name:
seqs_from_file
Author(s):
Martin C F Thomsen
Date:
18 Jul 2013
Description:
Iterator which extract sequence data from the input file
Args:
filename: string which contain a path to the input file
Supported Formats:
fasta, fastq
USAGE:
>>> import os, sys
>>> # Create fasta test file
>>> file_content = ('>head1 desc1\nthis_is_seq_1\n>head2 desc2\n'
'this_is_seq_2\n>head3 desc3\nthis_is_seq_3\n')
>>> with open_('test.fsa', 'w') as f: f.write(file_content)
>>> # Parse and print the fasta file
>>> for seq, name, desc in SeqsFromFile('test.fsa'):
... print ">%s %s\n%s"%(name, desc, seq)
...
>head1 desc1
this_is_seq_1
>head2 desc2
this_is_seq_2
>head3 desc3
this_is_seq_3 | Below is the the instruction that describes the task:
### Input:
Extract sequences from a file
Name:
seqs_from_file
Author(s):
Martin C F Thomsen
Date:
18 Jul 2013
Description:
Iterator which extract sequence data from the input file
Args:
filename: string which contain a path to the input file
Supported Formats:
fasta, fastq
USAGE:
>>> import os, sys
>>> # Create fasta test file
>>> file_content = ('>head1 desc1\nthis_is_seq_1\n>head2 desc2\n'
'this_is_seq_2\n>head3 desc3\nthis_is_seq_3\n')
>>> with open_('test.fsa', 'w') as f: f.write(file_content)
>>> # Parse and print the fasta file
>>> for seq, name, desc in SeqsFromFile('test.fsa'):
... print ">%s %s\n%s"%(name, desc, seq)
...
>head1 desc1
this_is_seq_1
>head2 desc2
this_is_seq_2
>head3 desc3
this_is_seq_3
### Response:
def seqs_from_file(filename, exit_on_err=False, return_qual=False):
"""Extract sequences from a file
Name:
seqs_from_file
Author(s):
Martin C F Thomsen
Date:
18 Jul 2013
Description:
Iterator which extract sequence data from the input file
Args:
filename: string which contain a path to the input file
Supported Formats:
fasta, fastq
USAGE:
>>> import os, sys
>>> # Create fasta test file
>>> file_content = ('>head1 desc1\nthis_is_seq_1\n>head2 desc2\n'
'this_is_seq_2\n>head3 desc3\nthis_is_seq_3\n')
>>> with open_('test.fsa', 'w') as f: f.write(file_content)
>>> # Parse and print the fasta file
>>> for seq, name, desc in SeqsFromFile('test.fsa'):
... print ">%s %s\n%s"%(name, desc, seq)
...
>head1 desc1
this_is_seq_1
>head2 desc2
this_is_seq_2
>head3 desc3
this_is_seq_3
"""
# VALIDATE INPUT
if not isinstance(filename, str):
msg = 'Filename has to be a string.'
if exit_on_err:
sys.stderr.write('Error: %s\n'%msg)
sys.exit(1)
else: raise IOError(msg)
if not os.path.exists(filename):
msg = 'File "%s" does not exist.'%filename
if exit_on_err:
sys.stderr.write('Error: %s\n'%msg)
sys.exit(1)
else: raise IOError(msg)
# EXTRACT DATA
with open_(filename,"rt") as f:
query_seq_segments = []
seq, name, desc, qual = '', '', '', ''
add_segment = query_seq_segments.append
for l in f:
if len(l.strip()) == 0: continue
#sys.stderr.write("%s\n"%line)
fields=l.strip().split()
if l.startswith(">"):
# FASTA HEADER FOUND
if query_seq_segments != []:
# YIELD SEQUENCE AND RESET
seq = ''.join(query_seq_segments)
yield (seq, name, desc)
seq, name, desc = '', '', ''
del query_seq_segments[:]
name = fields[0][1:]
desc = ' '.join(fields[1:])
elif l.startswith("@"):
# FASTQ HEADER FOUND
name = fields[0][1:]
desc = ' '.join(fields[1:])
try:
# EXTRACT FASTQ SEQUENCE
seq = next(f).strip().split()[0]
# SKIP SECOND HEADER LINE AND QUALITY SCORES
l = next(f)
qual = next(f).strip() # Qualities
except:
break
else:
# YIELD SEQUENCE AND RESET
if return_qual:
yield (seq, qual, name, desc)
else:
yield (seq, name, desc)
seq, name, desc, qual = '', '', '', ''
elif len(fields[0])>0:
# EXTRACT FASTA SEQUENCE
add_segment(fields[0])
# CHECK FOR LAST FASTA SEQUENCE
if query_seq_segments != []:
# YIELD SEQUENCE
seq = ''.join(query_seq_segments)
yield (seq, name, desc) |
def all(self, timeout=None, max_concurrency=64, auto_batch=True):
"""Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Example::
with cluster.all() as client:
client.flushdb()
"""
return self.fanout('all', timeout=timeout,
max_concurrency=max_concurrency,
auto_batch=auto_batch) | Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Example::
with cluster.all() as client:
client.flushdb() | Below is the the instruction that describes the task:
### Input:
Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Example::
with cluster.all() as client:
client.flushdb()
### Response:
def all(self, timeout=None, max_concurrency=64, auto_batch=True):
"""Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Example::
with cluster.all() as client:
client.flushdb()
"""
return self.fanout('all', timeout=timeout,
max_concurrency=max_concurrency,
auto_batch=auto_batch) |
def user_data(self, access_token, *args, **kwargs):
"""Load user data from OAuth Profile Google App Engine App"""
url = GOOGLE_APPENGINE_PROFILE_V1
auth = self.oauth_auth(access_token)
return self.get_json(url,
auth=auth, params=auth
) | Load user data from OAuth Profile Google App Engine App | Below is the the instruction that describes the task:
### Input:
Load user data from OAuth Profile Google App Engine App
### Response:
def user_data(self, access_token, *args, **kwargs):
"""Load user data from OAuth Profile Google App Engine App"""
url = GOOGLE_APPENGINE_PROFILE_V1
auth = self.oauth_auth(access_token)
return self.get_json(url,
auth=auth, params=auth
) |
def submit_status_external_cmd(cmd_file, status_file):
''' Submits the status lines in the status_file to Nagios' external cmd file.
'''
try:
with open(cmd_file, 'a') as cmd_file:
cmd_file.write(status_file.read())
except IOError:
exit("Fatal error: Unable to write to Nagios external command file '%s'.\n"
"Make sure that the file exists and is writable." % (cmd_file,)) | Submits the status lines in the status_file to Nagios' external cmd file. | Below is the the instruction that describes the task:
### Input:
Submits the status lines in the status_file to Nagios' external cmd file.
### Response:
def submit_status_external_cmd(cmd_file, status_file):
''' Submits the status lines in the status_file to Nagios' external cmd file.
'''
try:
with open(cmd_file, 'a') as cmd_file:
cmd_file.write(status_file.read())
except IOError:
exit("Fatal error: Unable to write to Nagios external command file '%s'.\n"
"Make sure that the file exists and is writable." % (cmd_file,)) |
def getMetadata(L):
"""
Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only)
"""
_l = {}
try:
# Create a copy. Do not affect the original data.
_l = copy.deepcopy(L)
# Remove values fields
_l = rm_values_fields(_l)
except Exception as e:
# Input likely not formatted correctly, though other problems can occur.
print("Error: Unable to get data. Please check that input is LiPD data: {}".format(e))
return _l | Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only) | Below is the the instruction that describes the task:
### Input:
Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only)
### Response:
def getMetadata(L):
"""
Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only)
"""
_l = {}
try:
# Create a copy. Do not affect the original data.
_l = copy.deepcopy(L)
# Remove values fields
_l = rm_values_fields(_l)
except Exception as e:
# Input likely not formatted correctly, though other problems can occur.
print("Error: Unable to get data. Please check that input is LiPD data: {}".format(e))
return _l |
def add_extension(self, extension):
"""
Specify a broadway extension to initialise
.. code-block:: python
factory = Factory()
factory.add_extension('broadway_sqlalchemy')
:param extension: import path to extension
:type extension: str
"""
instance = werkzeug.utils.import_string(extension)
if hasattr(instance, 'register'):
instance.register(self)
self._extensions.append(instance) | Specify a broadway extension to initialise
.. code-block:: python
factory = Factory()
factory.add_extension('broadway_sqlalchemy')
:param extension: import path to extension
:type extension: str | Below is the the instruction that describes the task:
### Input:
Specify a broadway extension to initialise
.. code-block:: python
factory = Factory()
factory.add_extension('broadway_sqlalchemy')
:param extension: import path to extension
:type extension: str
### Response:
def add_extension(self, extension):
"""
Specify a broadway extension to initialise
.. code-block:: python
factory = Factory()
factory.add_extension('broadway_sqlalchemy')
:param extension: import path to extension
:type extension: str
"""
instance = werkzeug.utils.import_string(extension)
if hasattr(instance, 'register'):
instance.register(self)
self._extensions.append(instance) |
def fill_cache(self):
"""Fill the cache with new data from the sensor."""
_LOGGER.debug('Filling cache with new sensor data.')
try:
firmware_version = self.firmware_version()
except BluetoothBackendException:
# If a sensor doesn't work, wait 5 minutes before retrying
self._last_read = datetime.now() - self._cache_timeout + \
timedelta(seconds=300)
raise
with self._bt_interface.connect(self._mac) as connection:
if firmware_version >= "2.6.6":
# for the newer models a magic number must be written before we can read the current data
try:
connection.write_handle(_HANDLE_WRITE_MODE_CHANGE, _DATA_MODE_CHANGE) # pylint: disable=no-member
# If a sensor doesn't work, wait 5 minutes before retrying
except BluetoothBackendException:
self._last_read = datetime.now() - self._cache_timeout + \
timedelta(seconds=300)
return
self._cache = connection.read_handle(_HANDLE_READ_SENSOR_DATA) # pylint: disable=no-member
_LOGGER.debug('Received result for handle %s: %s',
_HANDLE_READ_SENSOR_DATA, self._format_bytes(self._cache))
self._check_data()
if self.cache_available():
self._last_read = datetime.now()
else:
# If a sensor doesn't work, wait 5 minutes before retrying
self._last_read = datetime.now() - self._cache_timeout + \
timedelta(seconds=300) | Fill the cache with new data from the sensor. | Below is the the instruction that describes the task:
### Input:
Fill the cache with new data from the sensor.
### Response:
def fill_cache(self):
"""Fill the cache with new data from the sensor."""
_LOGGER.debug('Filling cache with new sensor data.')
try:
firmware_version = self.firmware_version()
except BluetoothBackendException:
# If a sensor doesn't work, wait 5 minutes before retrying
self._last_read = datetime.now() - self._cache_timeout + \
timedelta(seconds=300)
raise
with self._bt_interface.connect(self._mac) as connection:
if firmware_version >= "2.6.6":
# for the newer models a magic number must be written before we can read the current data
try:
connection.write_handle(_HANDLE_WRITE_MODE_CHANGE, _DATA_MODE_CHANGE) # pylint: disable=no-member
# If a sensor doesn't work, wait 5 minutes before retrying
except BluetoothBackendException:
self._last_read = datetime.now() - self._cache_timeout + \
timedelta(seconds=300)
return
self._cache = connection.read_handle(_HANDLE_READ_SENSOR_DATA) # pylint: disable=no-member
_LOGGER.debug('Received result for handle %s: %s',
_HANDLE_READ_SENSOR_DATA, self._format_bytes(self._cache))
self._check_data()
if self.cache_available():
self._last_read = datetime.now()
else:
# If a sensor doesn't work, wait 5 minutes before retrying
self._last_read = datetime.now() - self._cache_timeout + \
timedelta(seconds=300) |
def bootstrap(nside, rand, nbar, *data):
""" This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
nside : number of healpix pixels per side to use
*data : a list of data -- will be binned on the same regions.
small regions (incomplete pixels) are combined such that the total
area is about the same (a healpix pixel) in each returned boot strap sample
Yields: area, random, *data
rand and *data are in (RA, DEC)
Example:
>>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2):
>>> # Do stuff
>>> pass
"""
def split(data, indices, axis):
""" This function splits array. It fixes the bug
in numpy that zero length array are improperly handled.
In the future this will be fixed.
"""
s = []
s.append(slice(0, indices[0]))
for i in range(len(indices) - 1):
s.append(slice(indices[i], indices[i+1]))
s.append(slice(indices[-1], None))
rt = []
for ss in s:
ind = [slice(None, None, None) for i in range(len(data.shape))]
ind[axis] = ss
ind = tuple(ind)
rt.append(data[ind])
return rt
def hpsplit(nside, data):
# data is (RA, DEC)
RA, DEC = data
pix = radec2pix(nside, RA, DEC)
n = numpy.bincount(pix)
a = numpy.argsort(pix)
data = numpy.array(data)[:, a]
rt = split(data, n.cumsum(), axis=-1)
return rt
# mean area of sky.
Abar = 41252.96 / nside2npix(nside)
rand = hpsplit(nside, rand)
if len(data) > 0:
data = [list(i) for i in zip(*[hpsplit(nside, d1) for d1 in data])]
else:
data = [[] for i in range(len(rand))]
heap = []
j = 0
for r, d in zip(rand, data):
if len(r[0]) == 0: continue
a = 1.0 * len(r[0]) / nbar
j = j + 1
if len(heap) == 0:
heapq.heappush(heap, (a, j, r, d))
else:
a0, j0, r0, d0 = heapq.heappop(heap)
if a0 + a < Abar:
a0 += a
d0 = [
numpy.concatenate((d0[i], d[i]), axis=-1)
for i in range(len(d))
]
r0 = numpy.concatenate((r0, r), axis=-1)
else:
heapq.heappush(heap, (a, j, r, d))
heapq.heappush(heap, (a0, j0, r0, d0))
for i in range(len(heap)):
area, j, r, d = heapq.heappop(heap)
rt = [area, r] + d
yield rt | This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
nside : number of healpix pixels per side to use
*data : a list of data -- will be binned on the same regions.
small regions (incomplete pixels) are combined such that the total
area is about the same (a healpix pixel) in each returned boot strap sample
Yields: area, random, *data
rand and *data are in (RA, DEC)
Example:
>>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2):
>>> # Do stuff
>>> pass | Below is the the instruction that describes the task:
### Input:
This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
nside : number of healpix pixels per side to use
*data : a list of data -- will be binned on the same regions.
small regions (incomplete pixels) are combined such that the total
area is about the same (a healpix pixel) in each returned boot strap sample
Yields: area, random, *data
rand and *data are in (RA, DEC)
Example:
>>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2):
>>> # Do stuff
>>> pass
### Response:
def bootstrap(nside, rand, nbar, *data):
""" This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
nside : number of healpix pixels per side to use
*data : a list of data -- will be binned on the same regions.
small regions (incomplete pixels) are combined such that the total
area is about the same (a healpix pixel) in each returned boot strap sample
Yields: area, random, *data
rand and *data are in (RA, DEC)
Example:
>>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2):
>>> # Do stuff
>>> pass
"""
def split(data, indices, axis):
""" This function splits array. It fixes the bug
in numpy that zero length array are improperly handled.
In the future this will be fixed.
"""
s = []
s.append(slice(0, indices[0]))
for i in range(len(indices) - 1):
s.append(slice(indices[i], indices[i+1]))
s.append(slice(indices[-1], None))
rt = []
for ss in s:
ind = [slice(None, None, None) for i in range(len(data.shape))]
ind[axis] = ss
ind = tuple(ind)
rt.append(data[ind])
return rt
def hpsplit(nside, data):
# data is (RA, DEC)
RA, DEC = data
pix = radec2pix(nside, RA, DEC)
n = numpy.bincount(pix)
a = numpy.argsort(pix)
data = numpy.array(data)[:, a]
rt = split(data, n.cumsum(), axis=-1)
return rt
# mean area of sky.
Abar = 41252.96 / nside2npix(nside)
rand = hpsplit(nside, rand)
if len(data) > 0:
data = [list(i) for i in zip(*[hpsplit(nside, d1) for d1 in data])]
else:
data = [[] for i in range(len(rand))]
heap = []
j = 0
for r, d in zip(rand, data):
if len(r[0]) == 0: continue
a = 1.0 * len(r[0]) / nbar
j = j + 1
if len(heap) == 0:
heapq.heappush(heap, (a, j, r, d))
else:
a0, j0, r0, d0 = heapq.heappop(heap)
if a0 + a < Abar:
a0 += a
d0 = [
numpy.concatenate((d0[i], d[i]), axis=-1)
for i in range(len(d))
]
r0 = numpy.concatenate((r0, r), axis=-1)
else:
heapq.heappush(heap, (a, j, r, d))
heapq.heappush(heap, (a0, j0, r0, d0))
for i in range(len(heap)):
area, j, r, d = heapq.heappop(heap)
rt = [area, r] + d
yield rt |
def DeleteOldCronJobRuns(self, cutoff_timestamp):
"""Deletes cron job runs for a given job id."""
deleted = 0
for run in list(itervalues(self.cronjob_runs)):
if run.timestamp < cutoff_timestamp:
del self.cronjob_runs[(run.cron_job_id, run.run_id)]
deleted += 1
return deleted | Deletes cron job runs for a given job id. | Below is the the instruction that describes the task:
### Input:
Deletes cron job runs for a given job id.
### Response:
def DeleteOldCronJobRuns(self, cutoff_timestamp):
"""Deletes cron job runs for a given job id."""
deleted = 0
for run in list(itervalues(self.cronjob_runs)):
if run.timestamp < cutoff_timestamp:
del self.cronjob_runs[(run.cron_job_id, run.run_id)]
deleted += 1
return deleted |
def get_file(self, hash_list):
"""
Returns the path of the file - but verifies that the hash is actually present.
"""
assert len(hash_list) == 1
self._check_hashes(hash_list)
return self.object_path(hash_list[0]) | Returns the path of the file - but verifies that the hash is actually present. | Below is the the instruction that describes the task:
### Input:
Returns the path of the file - but verifies that the hash is actually present.
### Response:
def get_file(self, hash_list):
"""
Returns the path of the file - but verifies that the hash is actually present.
"""
assert len(hash_list) == 1
self._check_hashes(hash_list)
return self.object_path(hash_list[0]) |
def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`"""
status_pos = 0
for line in response.split("\n"):
if line.startswith('JOBID'):
try:
status_pos = line.find('STAT')
except ValueError:
return None
else:
status = line[status_pos:].split()[0]
if status in self.status_mapping:
return self.status_mapping[status]
return None | Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status` | Below is the the instruction that describes the task:
### Input:
Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`
### Response:
def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`"""
status_pos = 0
for line in response.split("\n"):
if line.startswith('JOBID'):
try:
status_pos = line.find('STAT')
except ValueError:
return None
else:
status = line[status_pos:].split()[0]
if status in self.status_mapping:
return self.status_mapping[status]
return None |
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None,
maxifds=None):
"""Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
"""
if offsetsize == 4:
offsetformat = byteorder+'I'
tagnosize = 2
tagnoformat = byteorder+'H'
tagsize = 12
tagformat1 = byteorder+'HH'
tagformat2 = byteorder+'I4s'
elif offsetsize == 8:
offsetformat = byteorder+'Q'
tagnosize = 8
tagnoformat = byteorder+'Q'
tagsize = 20
tagformat1 = byteorder+'HH'
tagformat2 = byteorder+'Q8s'
else:
raise ValueError('invalid offset size')
if customtags is None:
customtags = {}
if maxifds is None:
maxifds = 2**32
result = []
unpack = struct.unpack
offset = fh.tell()
while len(result) < maxifds:
# loop over IFDs
try:
tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
if tagno > 4096:
raise TiffFileError('suspicious number of tags')
except Exception:
log.warning('read_tags: corrupted tag list at offset %i', offset)
break
tags = {}
data = fh.read(tagsize * tagno)
pos = fh.tell()
index = 0
for _ in range(tagno):
code, type_ = unpack(tagformat1, data[index:index+4])
count, value = unpack(tagformat2, data[index+4:index+tagsize])
index += tagsize
name = tagnames.get(code, str(code))
try:
dtype = TIFF.DATA_FORMATS[type_]
except KeyError:
raise TiffFileError('unknown tag data type %i' % type_)
fmt = '%s%i%s' % (byteorder, count * int(dtype[0]), dtype[1])
size = struct.calcsize(fmt)
if size > offsetsize or code in customtags:
offset = unpack(offsetformat, value)[0]
if offset < 8 or offset > fh.size - size:
raise TiffFileError('invalid tag value offset %i' % offset)
fh.seek(offset)
if code in customtags:
readfunc = customtags[code][1]
value = readfunc(fh, byteorder, dtype, count, offsetsize)
elif type_ == 7 or (count > 1 and dtype[-1] == 'B'):
value = read_bytes(fh, byteorder, dtype, count, offsetsize)
elif code in tagnames or dtype[-1] == 's':
value = unpack(fmt, fh.read(size))
else:
value = read_numpy(fh, byteorder, dtype, count, offsetsize)
elif dtype[-1] == 'B' or type_ == 7:
value = value[:size]
else:
value = unpack(fmt, value[:size])
if code not in customtags and code not in TIFF.TAG_TUPLE:
if len(value) == 1:
value = value[0]
if type_ != 7 and dtype[-1] == 's' and isinstance(value, bytes):
# TIFF ASCII fields can contain multiple strings,
# each terminated with a NUL
try:
value = bytes2str(stripascii(value).strip())
except UnicodeDecodeError:
log.warning(
'read_tags: coercing invalid ASCII to bytes (tag %i)',
code)
tags[name] = value
result.append(tags)
# read offset to next page
fh.seek(pos)
offset = unpack(offsetformat, fh.read(offsetsize))[0]
if offset == 0:
break
if offset >= fh.size:
log.warning('read_tags: invalid page offset (%i)', offset)
break
fh.seek(offset)
if result and maxifds == 1:
result = result[0]
return result | Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header. | Below is the the instruction that describes the task:
### Input:
Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
### Response:
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None,
maxifds=None):
"""Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
"""
if offsetsize == 4:
offsetformat = byteorder+'I'
tagnosize = 2
tagnoformat = byteorder+'H'
tagsize = 12
tagformat1 = byteorder+'HH'
tagformat2 = byteorder+'I4s'
elif offsetsize == 8:
offsetformat = byteorder+'Q'
tagnosize = 8
tagnoformat = byteorder+'Q'
tagsize = 20
tagformat1 = byteorder+'HH'
tagformat2 = byteorder+'Q8s'
else:
raise ValueError('invalid offset size')
if customtags is None:
customtags = {}
if maxifds is None:
maxifds = 2**32
result = []
unpack = struct.unpack
offset = fh.tell()
while len(result) < maxifds:
# loop over IFDs
try:
tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
if tagno > 4096:
raise TiffFileError('suspicious number of tags')
except Exception:
log.warning('read_tags: corrupted tag list at offset %i', offset)
break
tags = {}
data = fh.read(tagsize * tagno)
pos = fh.tell()
index = 0
for _ in range(tagno):
code, type_ = unpack(tagformat1, data[index:index+4])
count, value = unpack(tagformat2, data[index+4:index+tagsize])
index += tagsize
name = tagnames.get(code, str(code))
try:
dtype = TIFF.DATA_FORMATS[type_]
except KeyError:
raise TiffFileError('unknown tag data type %i' % type_)
fmt = '%s%i%s' % (byteorder, count * int(dtype[0]), dtype[1])
size = struct.calcsize(fmt)
if size > offsetsize or code in customtags:
offset = unpack(offsetformat, value)[0]
if offset < 8 or offset > fh.size - size:
raise TiffFileError('invalid tag value offset %i' % offset)
fh.seek(offset)
if code in customtags:
readfunc = customtags[code][1]
value = readfunc(fh, byteorder, dtype, count, offsetsize)
elif type_ == 7 or (count > 1 and dtype[-1] == 'B'):
value = read_bytes(fh, byteorder, dtype, count, offsetsize)
elif code in tagnames or dtype[-1] == 's':
value = unpack(fmt, fh.read(size))
else:
value = read_numpy(fh, byteorder, dtype, count, offsetsize)
elif dtype[-1] == 'B' or type_ == 7:
value = value[:size]
else:
value = unpack(fmt, value[:size])
if code not in customtags and code not in TIFF.TAG_TUPLE:
if len(value) == 1:
value = value[0]
if type_ != 7 and dtype[-1] == 's' and isinstance(value, bytes):
# TIFF ASCII fields can contain multiple strings,
# each terminated with a NUL
try:
value = bytes2str(stripascii(value).strip())
except UnicodeDecodeError:
log.warning(
'read_tags: coercing invalid ASCII to bytes (tag %i)',
code)
tags[name] = value
result.append(tags)
# read offset to next page
fh.seek(pos)
offset = unpack(offsetformat, fh.read(offsetsize))[0]
if offset == 0:
break
if offset >= fh.size:
log.warning('read_tags: invalid page offset (%i)', offset)
break
fh.seek(offset)
if result and maxifds == 1:
result = result[0]
return result |
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
"""
The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
identical spans.
"""
merged_clusters: List[Set[Tuple[int, int]]] = []
for cluster in clusters.values():
cluster_with_overlapping_mention = None
for mention in cluster:
# Look at clusters we have already processed to
# see if they contain a mention in the current
# cluster for comparison.
for cluster2 in merged_clusters:
if mention in cluster2:
# first cluster in merged clusters
# which contains this mention.
cluster_with_overlapping_mention = cluster2
break
# Already encountered overlap - no need to keep looking.
if cluster_with_overlapping_mention is not None:
break
if cluster_with_overlapping_mention is not None:
# Merge cluster we are currently processing into
# the cluster in the processed list.
cluster_with_overlapping_mention.update(cluster)
else:
merged_clusters.append(set(cluster))
return [list(c) for c in merged_clusters] | The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
identical spans. | Below is the the instruction that describes the task:
### Input:
The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
identical spans.
### Response:
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
"""
The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
identical spans.
"""
merged_clusters: List[Set[Tuple[int, int]]] = []
for cluster in clusters.values():
cluster_with_overlapping_mention = None
for mention in cluster:
# Look at clusters we have already processed to
# see if they contain a mention in the current
# cluster for comparison.
for cluster2 in merged_clusters:
if mention in cluster2:
# first cluster in merged clusters
# which contains this mention.
cluster_with_overlapping_mention = cluster2
break
# Already encountered overlap - no need to keep looking.
if cluster_with_overlapping_mention is not None:
break
if cluster_with_overlapping_mention is not None:
# Merge cluster we are currently processing into
# the cluster in the processed list.
cluster_with_overlapping_mention.update(cluster)
else:
merged_clusters.append(set(cluster))
return [list(c) for c in merged_clusters] |
def Field(
dagster_type,
default_value=FIELD_NO_DEFAULT_PROVIDED,
is_optional=INFER_OPTIONAL_COMPOSITE_FIELD,
is_secret=False,
description=None,
):
'''
The schema for configuration data that describes the type, optionality, defaults, and description.
Args:
dagster_type (DagsterType):
A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})`
default_value (Any):
A default value to use that respects the schema provided via dagster_type
is_optional (bool): Whether the presence of this field is optional
despcription (str):
'''
config_type = resolve_to_config_type(dagster_type)
if not config_type:
raise DagsterInvalidDefinitionError(
(
'Attempted to pass {value_repr} to a Field that expects a valid '
'dagster type usable in config (e.g. Dict, NamedDict, Int, String et al).'
).format(value_repr=repr(dagster_type))
)
return FieldImpl(
config_type=resolve_to_config_type(dagster_type),
default_value=default_value,
is_optional=is_optional,
is_secret=is_secret,
description=description,
) | The schema for configuration data that describes the type, optionality, defaults, and description.
Args:
dagster_type (DagsterType):
A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})`
default_value (Any):
A default value to use that respects the schema provided via dagster_type
is_optional (bool): Whether the presence of this field is optional
despcription (str): | Below is the the instruction that describes the task:
### Input:
The schema for configuration data that describes the type, optionality, defaults, and description.
Args:
dagster_type (DagsterType):
A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})`
default_value (Any):
A default value to use that respects the schema provided via dagster_type
is_optional (bool): Whether the presence of this field is optional
despcription (str):
### Response:
def Field(
dagster_type,
default_value=FIELD_NO_DEFAULT_PROVIDED,
is_optional=INFER_OPTIONAL_COMPOSITE_FIELD,
is_secret=False,
description=None,
):
'''
The schema for configuration data that describes the type, optionality, defaults, and description.
Args:
dagster_type (DagsterType):
A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})`
default_value (Any):
A default value to use that respects the schema provided via dagster_type
is_optional (bool): Whether the presence of this field is optional
despcription (str):
'''
config_type = resolve_to_config_type(dagster_type)
if not config_type:
raise DagsterInvalidDefinitionError(
(
'Attempted to pass {value_repr} to a Field that expects a valid '
'dagster type usable in config (e.g. Dict, NamedDict, Int, String et al).'
).format(value_repr=repr(dagster_type))
)
return FieldImpl(
config_type=resolve_to_config_type(dagster_type),
default_value=default_value,
is_optional=is_optional,
is_secret=is_secret,
description=description,
) |
def get(self, *keys: str, default: Any = NOT_SET) -> Any:
""" Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "two")
1
>>> settings.get("two", "one")
2
>>> settings.get("three", "one")
1
>>> settings.get("three", default=3)
3
>>> settings.get("three")
Traceback (most recent call last):
...
KeyError:
:param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key
that has a value is returned.
:param default: If none of the ``options`` aren't set, return this value.
:return: A value from the settings or the default.
:raise ValueError: If no keys are provided.
:raise KeyError: If none of the keys are set and no default is provided.
"""
if not len(keys):
raise ValueError("At least one key must be provided.")
for option in keys:
key = f"{self.PREFIX}_{option.upper()}"
if key in self._data:
return self._data[key]
if default is NOT_SET:
raise KeyError("None of the following key is present in settings and no default is set: {}".format(
", ".join(keys)
))
return default | Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "two")
1
>>> settings.get("two", "one")
2
>>> settings.get("three", "one")
1
>>> settings.get("three", default=3)
3
>>> settings.get("three")
Traceback (most recent call last):
...
KeyError:
:param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key
that has a value is returned.
:param default: If none of the ``options`` aren't set, return this value.
:return: A value from the settings or the default.
:raise ValueError: If no keys are provided.
:raise KeyError: If none of the keys are set and no default is provided. | Below is the the instruction that describes the task:
### Input:
Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "two")
1
>>> settings.get("two", "one")
2
>>> settings.get("three", "one")
1
>>> settings.get("three", default=3)
3
>>> settings.get("three")
Traceback (most recent call last):
...
KeyError:
:param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key
that has a value is returned.
:param default: If none of the ``options`` aren't set, return this value.
:return: A value from the settings or the default.
:raise ValueError: If no keys are provided.
:raise KeyError: If none of the keys are set and no default is provided.
### Response:
def get(self, *keys: str, default: Any = NOT_SET) -> Any:
""" Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "two")
1
>>> settings.get("two", "one")
2
>>> settings.get("three", "one")
1
>>> settings.get("three", default=3)
3
>>> settings.get("three")
Traceback (most recent call last):
...
KeyError:
:param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key
that has a value is returned.
:param default: If none of the ``options`` aren't set, return this value.
:return: A value from the settings or the default.
:raise ValueError: If no keys are provided.
:raise KeyError: If none of the keys are set and no default is provided.
"""
if not len(keys):
raise ValueError("At least one key must be provided.")
for option in keys:
key = f"{self.PREFIX}_{option.upper()}"
if key in self._data:
return self._data[key]
if default is NOT_SET:
raise KeyError("None of the following key is present in settings and no default is set: {}".format(
", ".join(keys)
))
return default |
def index(self, val, start=None, stop=None):
"""
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices.
"""
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(val))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(val))
_maxes = self._maxes
key = self._key(val)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(val))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(val))
if _lists[pos][idx] == val:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(val))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(val)) | Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices. | Below is the the instruction that describes the task:
### Input:
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices.
### Response:
def index(self, val, start=None, stop=None):
"""
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices.
"""
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(val))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(val))
_maxes = self._maxes
key = self._key(val)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(val))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(val))
if _lists[pos][idx] == val:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(val))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(val)) |
def handle_line(self, line):
"""Handle incoming string data one line at a time."""
if not self.gateway.can_log:
_LOGGER.debug('Receiving %s', line)
self.gateway.add_job(self.gateway.logic, line) | Handle incoming string data one line at a time. | Below is the the instruction that describes the task:
### Input:
Handle incoming string data one line at a time.
### Response:
def handle_line(self, line):
"""Handle incoming string data one line at a time."""
if not self.gateway.can_log:
_LOGGER.debug('Receiving %s', line)
self.gateway.add_job(self.gateway.logic, line) |
def register(self, x, graph=False):
"""Register a function as being part of an API, then returns the original function."""
if graph:
# This function must comply to the "graph" API interface, meaning it can bahave like bonobo.run.
from inspect import signature
parameters = list(signature(x).parameters)
required_parameters = {"plugins", "services", "strategy"}
assert (
len(parameters) > 0 and parameters[0] == "graph"
), 'First parameter of a graph api function must be "graph".'
assert (
required_parameters.intersection(parameters) == required_parameters
), "Graph api functions must define the following parameters: " + ", ".join(sorted(required_parameters))
self.__all__.append(get_name(x))
return x | Register a function as being part of an API, then returns the original function. | Below is the the instruction that describes the task:
### Input:
Register a function as being part of an API, then returns the original function.
### Response:
def register(self, x, graph=False):
"""Register a function as being part of an API, then returns the original function."""
if graph:
# This function must comply to the "graph" API interface, meaning it can bahave like bonobo.run.
from inspect import signature
parameters = list(signature(x).parameters)
required_parameters = {"plugins", "services", "strategy"}
assert (
len(parameters) > 0 and parameters[0] == "graph"
), 'First parameter of a graph api function must be "graph".'
assert (
required_parameters.intersection(parameters) == required_parameters
), "Graph api functions must define the following parameters: " + ", ".join(sorted(required_parameters))
self.__all__.append(get_name(x))
return x |
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), )) | Writes the given output to the log file, appending unless `truncate` is True. | Below is the the instruction that describes the task:
### Input:
Writes the given output to the log file, appending unless `truncate` is True.
### Response:
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), )) |
def convert(model, input_features, output_features):
"""Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Set the interface params.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# feature name in and out are the same here
spec = set_transform_interface_params(spec, input_features, output_features)
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Imputer)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'statistics_'))
if model.axis != 0:
raise ValueError("Imputation is only supported along axis = 0.")
# The imputer in our framework only works on single columns, so
# we need to translate that over. The easiest way to do that is to
# put it in a nested pipeline with a feature extractor and a
tr_spec = spec.imputer
for v in model.statistics_:
tr_spec.imputedDoubleArray.vector.append(v)
try:
tr_spec.replaceDoubleValue = float(model.missing_values)
except ValueError:
raise ValueError("Only scalar values or NAN as missing_values "
"in _imputer are supported.")
return _MLModel(spec) | Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model | Below is the the instruction that describes the task:
### Input:
Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
### Response:
def convert(model, input_features, output_features):
"""Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Set the interface params.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# feature name in and out are the same here
spec = set_transform_interface_params(spec, input_features, output_features)
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Imputer)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'statistics_'))
if model.axis != 0:
raise ValueError("Imputation is only supported along axis = 0.")
# The imputer in our framework only works on single columns, so
# we need to translate that over. The easiest way to do that is to
# put it in a nested pipeline with a feature extractor and a
tr_spec = spec.imputer
for v in model.statistics_:
tr_spec.imputedDoubleArray.vector.append(v)
try:
tr_spec.replaceDoubleValue = float(model.missing_values)
except ValueError:
raise ValueError("Only scalar values or NAN as missing_values "
"in _imputer are supported.")
return _MLModel(spec) |
def prepare_for_build(self):
'''Prepare the build.
'''
assert(self.target is not None)
if hasattr(self.target, '_build_prepared'):
return
self.info('Preparing build')
self.info('Check requirements for {0}'.format(self.targetname))
self.target.check_requirements()
self.info('Install platform')
self.target.install_platform()
self.info('Check application requirements')
self.check_application_requirements()
self.info('Check garden requirements')
self.check_garden_requirements()
self.info('Compile platform')
self.target.compile_platform()
# flag to prevent multiple build
self.target._build_prepared = True | Prepare the build. | Below is the the instruction that describes the task:
### Input:
Prepare the build.
### Response:
def prepare_for_build(self):
'''Prepare the build.
'''
assert(self.target is not None)
if hasattr(self.target, '_build_prepared'):
return
self.info('Preparing build')
self.info('Check requirements for {0}'.format(self.targetname))
self.target.check_requirements()
self.info('Install platform')
self.target.install_platform()
self.info('Check application requirements')
self.check_application_requirements()
self.info('Check garden requirements')
self.check_garden_requirements()
self.info('Compile platform')
self.target.compile_platform()
# flag to prevent multiple build
self.target._build_prepared = True |
def map_across_full_axis(self, axis, map_func):
"""Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - columns).
map_func: The function to apply.
Returns:
A new BaseFrameManager object, the type of object that called this.
"""
# Since we are already splitting the DataFrame back up after an
# operation, we will just use this time to compute the number of
# partitions as best we can right now.
num_splits = self._compute_num_partitions()
preprocessed_map_func = self.preprocess_func(map_func)
partitions = self.column_partitions if not axis else self.row_partitions
# For mapping across the entire axis, we don't maintain partitioning because we
# may want to line to partitioning up with another BlockPartitions object. Since
# we don't need to maintain the partitioning, this gives us the opportunity to
# load-balance the data as well.
result_blocks = np.array(
[
part.apply(preprocessed_map_func, num_splits=num_splits)
for part in partitions
]
)
# If we are mapping over columns, they are returned to use the same as
# rows, so we need to transpose the returned 2D numpy array to return
# the structure to the correct order.
return (
self.__constructor__(result_blocks.T)
if not axis
else self.__constructor__(result_blocks)
) | Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - columns).
map_func: The function to apply.
Returns:
A new BaseFrameManager object, the type of object that called this. | Below is the the instruction that describes the task:
### Input:
Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - columns).
map_func: The function to apply.
Returns:
A new BaseFrameManager object, the type of object that called this.
### Response:
def map_across_full_axis(self, axis, map_func):
"""Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - columns).
map_func: The function to apply.
Returns:
A new BaseFrameManager object, the type of object that called this.
"""
# Since we are already splitting the DataFrame back up after an
# operation, we will just use this time to compute the number of
# partitions as best we can right now.
num_splits = self._compute_num_partitions()
preprocessed_map_func = self.preprocess_func(map_func)
partitions = self.column_partitions if not axis else self.row_partitions
# For mapping across the entire axis, we don't maintain partitioning because we
# may want to line to partitioning up with another BlockPartitions object. Since
# we don't need to maintain the partitioning, this gives us the opportunity to
# load-balance the data as well.
result_blocks = np.array(
[
part.apply(preprocessed_map_func, num_splits=num_splits)
for part in partitions
]
)
# If we are mapping over columns, they are returned to use the same as
# rows, so we need to transpose the returned 2D numpy array to return
# the structure to the correct order.
return (
self.__constructor__(result_blocks.T)
if not axis
else self.__constructor__(result_blocks)
) |
def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family
"""
return ss.expon.logpdf(x=y, scale=1/mean) | Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family | Below is the the instruction that describes the task:
### Input:
Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family
### Response:
def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
shape : float
tail thickness parameter for the Exponential distribution
skewness : float
skewness parameter for the Exponential distribution
Returns
----------
- Markov blanket of the Exponential family
"""
return ss.expon.logpdf(x=y, scale=1/mean) |
def check_recovery(working_dir):
"""
Do we need to recover on start-up?
"""
recovery_start_block, recovery_end_block = get_recovery_range(working_dir)
if recovery_start_block is not None and recovery_end_block is not None:
local_current_block = virtualchain_hooks.get_last_block(working_dir)
if local_current_block <= recovery_end_block:
return True
# otherwise, we're outside the recovery range and we can clear it
log.debug('Chain state is at block {}, and is outside the recovery window {}-{}'.format(local_current_block, recovery_start_block, recovery_end_block))
clear_recovery_range(working_dir)
return False
else:
# not recovering
return False | Do we need to recover on start-up? | Below is the the instruction that describes the task:
### Input:
Do we need to recover on start-up?
### Response:
def check_recovery(working_dir):
"""
Do we need to recover on start-up?
"""
recovery_start_block, recovery_end_block = get_recovery_range(working_dir)
if recovery_start_block is not None and recovery_end_block is not None:
local_current_block = virtualchain_hooks.get_last_block(working_dir)
if local_current_block <= recovery_end_block:
return True
# otherwise, we're outside the recovery range and we can clear it
log.debug('Chain state is at block {}, and is outside the recovery window {}-{}'.format(local_current_block, recovery_start_block, recovery_end_block))
clear_recovery_range(working_dir)
return False
else:
# not recovering
return False |
def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs):
"""
index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs
"""
fit = np.empty((len(boot_collection), dimensions))
if ISPY3:
query_trees = [PhyloTree(tree.encode(), rooted) for tree in boot_collection.trees]
ref_trees = [PhyloTree(tree.encode(), rooted) for tree in ref_collection.trees]
else:
query_trees = [PhyloTree(tree, rooted) for tree in boot_collection.trees]
ref_trees = [PhyloTree(tree, rooted) for tree in ref_collection.trees]
for i, tree in enumerate(query_trees):
distvec = np.array([task(tree, ref_tree, False) for ref_tree in ref_trees])
oos = OutOfSampleMDS(ref_distance_matrix)
fit[i] = oos.fit(index, distvec, dimensions=dimensions, **kwargs)
return fit | index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs | Below is the the instruction that describes the task:
### Input:
index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs
### Response:
def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs):
"""
index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs
"""
fit = np.empty((len(boot_collection), dimensions))
if ISPY3:
query_trees = [PhyloTree(tree.encode(), rooted) for tree in boot_collection.trees]
ref_trees = [PhyloTree(tree.encode(), rooted) for tree in ref_collection.trees]
else:
query_trees = [PhyloTree(tree, rooted) for tree in boot_collection.trees]
ref_trees = [PhyloTree(tree, rooted) for tree in ref_collection.trees]
for i, tree in enumerate(query_trees):
distvec = np.array([task(tree, ref_tree, False) for ref_tree in ref_trees])
oos = OutOfSampleMDS(ref_distance_matrix)
fit[i] = oos.fit(index, distvec, dimensions=dimensions, **kwargs)
return fit |
def set_patient_medhx_flag(self, patient_id,
medhx_status):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param patient_id
:param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and
errors out if included.
U=Unknown
G=Granted
D=Declined
:return: JSON response
"""
magic = self._magic_json(
action=TouchWorksMagicConstants.ACTION_SET_PATIENT_MEDHX_FLAG,
patient_id=patient_id,
parameter1=medhx_status
)
response = self._http_request(TouchWorksEndPoints.MAGIC_JSON, data=magic)
result = self._get_results_or_raise_if_magic_invalid(
magic,
response,
TouchWorksMagicConstants.RESULT_SET_PATIENT_MEDHX_FLAG)
return result | invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param patient_id
:param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and
errors out if included.
U=Unknown
G=Granted
D=Declined
:return: JSON response | Below is the the instruction that describes the task:
### Input:
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param patient_id
:param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and
errors out if included.
U=Unknown
G=Granted
D=Declined
:return: JSON response
### Response:
def set_patient_medhx_flag(self, patient_id,
medhx_status):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param patient_id
:param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and
errors out if included.
U=Unknown
G=Granted
D=Declined
:return: JSON response
"""
magic = self._magic_json(
action=TouchWorksMagicConstants.ACTION_SET_PATIENT_MEDHX_FLAG,
patient_id=patient_id,
parameter1=medhx_status
)
response = self._http_request(TouchWorksEndPoints.MAGIC_JSON, data=magic)
result = self._get_results_or_raise_if_magic_invalid(
magic,
response,
TouchWorksMagicConstants.RESULT_SET_PATIENT_MEDHX_FLAG)
return result |
def alias_assessment_taken(self, assessment_taken_id, alias_id):
"""Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility.
The primary ``Id`` of the ``AssessmentTaken`` is determined by
the provider. The new ``Id`` is an alias to the primary ``Id``.
If the alias is a pointer to another assessment taken, it is
reassigned to the given assessment taken ``Id``.
arg: assessment_taken_id (osid.id.Id): the ``Id`` of an
``AssessmentTaken``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is in use as a primary
``Id``
raise: NotFound - ``assessment_taken_id`` not found
raise: NullArgument - ``assessment_taken_id`` or ``alias_id``
is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure occurred
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.alias_resources_template
self._alias_id(primary_id=assessment_taken_id, equivalent_id=alias_id) | Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility.
The primary ``Id`` of the ``AssessmentTaken`` is determined by
the provider. The new ``Id`` is an alias to the primary ``Id``.
If the alias is a pointer to another assessment taken, it is
reassigned to the given assessment taken ``Id``.
arg: assessment_taken_id (osid.id.Id): the ``Id`` of an
``AssessmentTaken``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is in use as a primary
``Id``
raise: NotFound - ``assessment_taken_id`` not found
raise: NullArgument - ``assessment_taken_id`` or ``alias_id``
is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure occurred
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility.
The primary ``Id`` of the ``AssessmentTaken`` is determined by
the provider. The new ``Id`` is an alias to the primary ``Id``.
If the alias is a pointer to another assessment taken, it is
reassigned to the given assessment taken ``Id``.
arg: assessment_taken_id (osid.id.Id): the ``Id`` of an
``AssessmentTaken``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is in use as a primary
``Id``
raise: NotFound - ``assessment_taken_id`` not found
raise: NullArgument - ``assessment_taken_id`` or ``alias_id``
is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure occurred
*compliance: mandatory -- This method must be implemented.*
### Response:
def alias_assessment_taken(self, assessment_taken_id, alias_id):
"""Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility.
The primary ``Id`` of the ``AssessmentTaken`` is determined by
the provider. The new ``Id`` is an alias to the primary ``Id``.
If the alias is a pointer to another assessment taken, it is
reassigned to the given assessment taken ``Id``.
arg: assessment_taken_id (osid.id.Id): the ``Id`` of an
``AssessmentTaken``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is in use as a primary
``Id``
raise: NotFound - ``assessment_taken_id`` not found
raise: NullArgument - ``assessment_taken_id`` or ``alias_id``
is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure occurred
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.alias_resources_template
self._alias_id(primary_id=assessment_taken_id, equivalent_id=alias_id) |
def check_state(self, state):
"""
Check if the specific function is reached with certain arguments
:param angr.SimState state: The state to check
:return: True if the function is reached with certain arguments, False otherwise.
:rtype: bool
"""
if state.addr == self.function.addr:
arch = state.arch
if self._check_arguments(arch, state):
return True
return False | Check if the specific function is reached with certain arguments
:param angr.SimState state: The state to check
:return: True if the function is reached with certain arguments, False otherwise.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if the specific function is reached with certain arguments
:param angr.SimState state: The state to check
:return: True if the function is reached with certain arguments, False otherwise.
:rtype: bool
### Response:
def check_state(self, state):
"""
Check if the specific function is reached with certain arguments
:param angr.SimState state: The state to check
:return: True if the function is reached with certain arguments, False otherwise.
:rtype: bool
"""
if state.addr == self.function.addr:
arch = state.arch
if self._check_arguments(arch, state):
return True
return False |
def CBO_Gamma(self, **kwargs):
'''
Returns the strain-shifted Gamma-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally.
'''
return (self.unstrained.CBO_Gamma(**kwargs) +
self.CBO_strain_shift(**kwargs)) | Returns the strain-shifted Gamma-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally. | Below is the the instruction that describes the task:
### Input:
Returns the strain-shifted Gamma-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally.
### Response:
def CBO_Gamma(self, **kwargs):
'''
Returns the strain-shifted Gamma-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally.
'''
return (self.unstrained.CBO_Gamma(**kwargs) +
self.CBO_strain_shift(**kwargs)) |
def get_fieldsets(self, *args, **kwargs):
"""Re-order fields"""
result = super(EventAdmin, self).get_fieldsets(*args, **kwargs)
result = list(result)
fields = list(result[0][1]['fields'])
for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \
'external_link', 'calendars'):
fields.remove(name)
fields.append(name)
result[0][1]['fields'] = tuple(fields)
return tuple(result) | Re-order fields | Below is the the instruction that describes the task:
### Input:
Re-order fields
### Response:
def get_fieldsets(self, *args, **kwargs):
"""Re-order fields"""
result = super(EventAdmin, self).get_fieldsets(*args, **kwargs)
result = list(result)
fields = list(result[0][1]['fields'])
for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \
'external_link', 'calendars'):
fields.remove(name)
fields.append(name)
result[0][1]['fields'] = tuple(fields)
return tuple(result) |
def UploadAccount(self, hash_algorithm, hash_key, accounts):
"""Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response of the API.
"""
param = {
'hashAlgorithm': hash_algorithm,
'signerKey': hash_key,
'users': accounts
}
# pylint does not recognize the return type of simplejson.loads
# pylint: disable=maybe-no-member
return self._InvokeGitkitApi('uploadAccount', param) | Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response of the API. | Below is the the instruction that describes the task:
### Input:
Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response of the API.
### Response:
def UploadAccount(self, hash_algorithm, hash_key, accounts):
"""Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response of the API.
"""
param = {
'hashAlgorithm': hash_algorithm,
'signerKey': hash_key,
'users': accounts
}
# pylint does not recognize the return type of simplejson.loads
# pylint: disable=maybe-no-member
return self._InvokeGitkitApi('uploadAccount', param) |
def from_Composition(composition, width=80):
"""Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
attribute.
"""
# Collect tunings
instr_tunings = []
for track in composition:
tun = track.get_tuning()
if tun:
instr_tunings.append(tun)
else:
instr_tunings.append(default_tuning)
result = add_headers(
width,
composition.title,
composition.subtitle,
composition.author,
composition.email,
composition.description,
instr_tunings,
)
# Some variables
w = _get_width(width)
barindex = 0
bars = width / w
lastlen = 0
maxlen = max([len(x) for x in composition.tracks])
while barindex < maxlen:
notfirst = False
for tracks in composition:
tuning = tracks.get_tuning()
ascii = []
for x in xrange(bars):
if barindex + x < len(tracks):
bar = tracks[barindex + x]
r = from_Bar(bar, w, tuning, collapse=False)
barstart = r[1].find('||') + 2
# Add extra '||' to quarter note marks to connect tracks.
if notfirst:
r[0] = (r[0])[:barstart - 2] + '||' + (r[0])[barstart:]
# Add bar to ascii
if ascii != []:
for i in range(1, len(r) + 1):
item = r[len(r) - i]
ascii[-i] += item[barstart:]
else:
ascii += r
# Add extra '||' to connect tracks
if notfirst and ascii != []:
pad = ascii[-1].find('||')
result += [' ' * pad + '||', ' ' * pad + '||']
else:
notfirst = True
# Finally, add ascii to result
result += ascii
result += ['', '', '']
barindex += bars
return os.linesep.join(result) | Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
attribute. | Below is the the instruction that describes the task:
### Input:
Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
attribute.
### Response:
def from_Composition(composition, width=80):
"""Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
attribute.
"""
# Collect tunings
instr_tunings = []
for track in composition:
tun = track.get_tuning()
if tun:
instr_tunings.append(tun)
else:
instr_tunings.append(default_tuning)
result = add_headers(
width,
composition.title,
composition.subtitle,
composition.author,
composition.email,
composition.description,
instr_tunings,
)
# Some variables
w = _get_width(width)
barindex = 0
bars = width / w
lastlen = 0
maxlen = max([len(x) for x in composition.tracks])
while barindex < maxlen:
notfirst = False
for tracks in composition:
tuning = tracks.get_tuning()
ascii = []
for x in xrange(bars):
if barindex + x < len(tracks):
bar = tracks[barindex + x]
r = from_Bar(bar, w, tuning, collapse=False)
barstart = r[1].find('||') + 2
# Add extra '||' to quarter note marks to connect tracks.
if notfirst:
r[0] = (r[0])[:barstart - 2] + '||' + (r[0])[barstart:]
# Add bar to ascii
if ascii != []:
for i in range(1, len(r) + 1):
item = r[len(r) - i]
ascii[-i] += item[barstart:]
else:
ascii += r
# Add extra '||' to connect tracks
if notfirst and ascii != []:
pad = ascii[-1].find('||')
result += [' ' * pad + '||', ' ' * pad + '||']
else:
notfirst = True
# Finally, add ascii to result
result += ascii
result += ['', '', '']
barindex += bars
return os.linesep.join(result) |
def enumeration(values, converter=str, default=''):
"""Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
>>> enumeration(('text', 3))
'text and 3'
>>> enumeration(('text',))
'text'
>>> enumeration(())
''
All given objects are converted to strings by function |str|, as shown
by the first two examples. This behaviour can be changed by another
function expecting a single argument and returning a string:
>>> from hydpy.core.objecttools import classname
>>> enumeration(('text', 3, []), converter=classname)
'str, int, and list'
Furthermore, you can define a default string that is returned
in case an empty iterable is given:
>>> enumeration((), default='nothing')
'nothing'
"""
values = tuple(converter(value) for value in values)
if not values:
return default
if len(values) == 1:
return values[0]
if len(values) == 2:
return ' and '.join(values)
return ', and '.join((', '.join(values[:-1]), values[-1])) | Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
>>> enumeration(('text', 3))
'text and 3'
>>> enumeration(('text',))
'text'
>>> enumeration(())
''
All given objects are converted to strings by function |str|, as shown
by the first two examples. This behaviour can be changed by another
function expecting a single argument and returning a string:
>>> from hydpy.core.objecttools import classname
>>> enumeration(('text', 3, []), converter=classname)
'str, int, and list'
Furthermore, you can define a default string that is returned
in case an empty iterable is given:
>>> enumeration((), default='nothing')
'nothing' | Below is the the instruction that describes the task:
### Input:
Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
>>> enumeration(('text', 3))
'text and 3'
>>> enumeration(('text',))
'text'
>>> enumeration(())
''
All given objects are converted to strings by function |str|, as shown
by the first two examples. This behaviour can be changed by another
function expecting a single argument and returning a string:
>>> from hydpy.core.objecttools import classname
>>> enumeration(('text', 3, []), converter=classname)
'str, int, and list'
Furthermore, you can define a default string that is returned
in case an empty iterable is given:
>>> enumeration((), default='nothing')
'nothing'
### Response:
def enumeration(values, converter=str, default=''):
"""Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
>>> enumeration(('text', 3))
'text and 3'
>>> enumeration(('text',))
'text'
>>> enumeration(())
''
All given objects are converted to strings by function |str|, as shown
by the first two examples. This behaviour can be changed by another
function expecting a single argument and returning a string:
>>> from hydpy.core.objecttools import classname
>>> enumeration(('text', 3, []), converter=classname)
'str, int, and list'
Furthermore, you can define a default string that is returned
in case an empty iterable is given:
>>> enumeration((), default='nothing')
'nothing'
"""
values = tuple(converter(value) for value in values)
if not values:
return default
if len(values) == 1:
return values[0]
if len(values) == 2:
return ' and '.join(values)
return ', and '.join((', '.join(values[:-1]), values[-1])) |
def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
self._valid_set = map(func, self._valid_set)
if self._test_set:
self._test_set = map(func, self._test_set) | Process all data with given function.
The scheme of function should be x,y -> x,y. | Below is the the instruction that describes the task:
### Input:
Process all data with given function.
The scheme of function should be x,y -> x,y.
### Response:
def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
self._valid_set = map(func, self._valid_set)
if self._test_set:
self._test_set = map(func, self._test_set) |
def populate_unique_identifiers(self, metamodel):
'''
Populate a *metamodel* with class unique identifiers previously
encountered from input.
'''
for stmt in self.statements:
if isinstance(stmt, CreateUniqueStmt):
metamodel.define_unique_identifier(stmt.kind, stmt.name,
*stmt.attributes) | Populate a *metamodel* with class unique identifiers previously
encountered from input. | Below is the the instruction that describes the task:
### Input:
Populate a *metamodel* with class unique identifiers previously
encountered from input.
### Response:
def populate_unique_identifiers(self, metamodel):
'''
Populate a *metamodel* with class unique identifiers previously
encountered from input.
'''
for stmt in self.statements:
if isinstance(stmt, CreateUniqueStmt):
metamodel.define_unique_identifier(stmt.kind, stmt.name,
*stmt.attributes) |
def notify_user(
self,
msg,
level="error",
rate_limit=None,
module_name="",
icon=None,
title="py3status",
):
"""
Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
NOTE: Message should end with a '.' for consistency.
"""
dbus = self.config.get("dbus_notify")
if dbus:
# force msg, icon, title to be a string
title = u"{}".format(title)
msg = u"{}".format(msg)
if icon:
icon = u"{}".format(icon)
else:
msg = u"py3status: {}".format(msg)
if level != "info" and module_name == "":
fix_msg = u"{} Please try to fix this and reload i3wm (Mod+Shift+R)"
msg = fix_msg.format(msg)
# Rate limiting. If rate limiting then we need to calculate the time
# period for which the message should not be repeated. We just use
# A simple chunked time model where a message cannot be repeated in a
# given time period. Messages can be repeated more frequently but must
# be in different time periods.
limit_key = ""
if rate_limit:
try:
limit_key = time.time() // rate_limit
except TypeError:
pass
# We use a hash to see if the message is being repeated. This is crude
# and imperfect but should work for our needs.
msg_hash = hash(u"{}#{}#{}#{}".format(module_name, limit_key, msg, title))
if msg_hash in self.notified_messages:
return
elif module_name:
log_msg = 'Module `%s` sent a notification. "%s: %s"' % (
module_name,
title,
msg,
)
self.log(log_msg, level)
else:
self.log(msg, level)
self.notified_messages.add(msg_hash)
try:
if dbus:
# fix any html entities
msg = msg.replace("&", "&")
msg = msg.replace("<", "<")
msg = msg.replace(">", ">")
cmd = ["notify-send"]
if icon:
cmd += ["-i", icon]
cmd += ["-u", DBUS_LEVELS.get(level, "normal"), "-t", "10000"]
cmd += [title, msg]
else:
py3_config = self.config.get("py3_config", {})
nagbar_font = py3_config.get("py3status", {}).get("nagbar_font")
wm_nag = self.config["wm"]["nag"]
cmd = [wm_nag, "-m", msg, "-t", level]
if nagbar_font:
cmd += ["-f", nagbar_font]
Popen(cmd, stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
except Exception as err:
self.log("notify_user error: %s" % err) | Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
NOTE: Message should end with a '.' for consistency. | Below is the the instruction that describes the task:
### Input:
Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
NOTE: Message should end with a '.' for consistency.
### Response:
def notify_user(
self,
msg,
level="error",
rate_limit=None,
module_name="",
icon=None,
title="py3status",
):
"""
Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
NOTE: Message should end with a '.' for consistency.
"""
dbus = self.config.get("dbus_notify")
if dbus:
# force msg, icon, title to be a string
title = u"{}".format(title)
msg = u"{}".format(msg)
if icon:
icon = u"{}".format(icon)
else:
msg = u"py3status: {}".format(msg)
if level != "info" and module_name == "":
fix_msg = u"{} Please try to fix this and reload i3wm (Mod+Shift+R)"
msg = fix_msg.format(msg)
# Rate limiting. If rate limiting then we need to calculate the time
# period for which the message should not be repeated. We just use
# A simple chunked time model where a message cannot be repeated in a
# given time period. Messages can be repeated more frequently but must
# be in different time periods.
limit_key = ""
if rate_limit:
try:
limit_key = time.time() // rate_limit
except TypeError:
pass
# We use a hash to see if the message is being repeated. This is crude
# and imperfect but should work for our needs.
msg_hash = hash(u"{}#{}#{}#{}".format(module_name, limit_key, msg, title))
if msg_hash in self.notified_messages:
return
elif module_name:
log_msg = 'Module `%s` sent a notification. "%s: %s"' % (
module_name,
title,
msg,
)
self.log(log_msg, level)
else:
self.log(msg, level)
self.notified_messages.add(msg_hash)
try:
if dbus:
# fix any html entities
msg = msg.replace("&", "&")
msg = msg.replace("<", "<")
msg = msg.replace(">", ">")
cmd = ["notify-send"]
if icon:
cmd += ["-i", icon]
cmd += ["-u", DBUS_LEVELS.get(level, "normal"), "-t", "10000"]
cmd += [title, msg]
else:
py3_config = self.config.get("py3_config", {})
nagbar_font = py3_config.get("py3status", {}).get("nagbar_font")
wm_nag = self.config["wm"]["nag"]
cmd = [wm_nag, "-m", msg, "-t", level]
if nagbar_font:
cmd += ["-f", nagbar_font]
Popen(cmd, stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
except Exception as err:
self.log("notify_user error: %s" % err) |
def adjustMinimumWidth( self ):
"""
Updates the minimum width for this menu based on the font metrics \
for its title (if its shown). This method is called automatically \
when the menu is shown.
"""
if not self.showTitle():
return
metrics = QFontMetrics(self.font())
width = metrics.width(self.title()) + 20
if self.minimumWidth() < width:
self.setMinimumWidth(width) | Updates the minimum width for this menu based on the font metrics \
for its title (if its shown). This method is called automatically \
when the menu is shown. | Below is the the instruction that describes the task:
### Input:
Updates the minimum width for this menu based on the font metrics \
for its title (if its shown). This method is called automatically \
when the menu is shown.
### Response:
def adjustMinimumWidth( self ):
"""
Updates the minimum width for this menu based on the font metrics \
for its title (if its shown). This method is called automatically \
when the menu is shown.
"""
if not self.showTitle():
return
metrics = QFontMetrics(self.font())
width = metrics.width(self.title()) + 20
if self.minimumWidth() < width:
self.setMinimumWidth(width) |
def fetch_all_images(self, type=None, private=None):
# pylint: disable=redefined-builtin
r"""
Returns a generator that yields all of the images available to the
account
:param type: the type of images to fetch: ``"distribution"``,
``"application"``, or all (`None`); default: `None`
:type type: string or None
:param bool private: whether to only return the user's private images;
default: return all images
:rtype: generator of `Image`\ s
:raises DOAPIError: if the API endpoint replies with an error
"""
params = {}
if type is not None:
params["type"] = type
if private is not None:
params["private"] = 'true' if private else 'false'
return map(self._image, self.paginate('/v2/images', 'images',
params=params)) | r"""
Returns a generator that yields all of the images available to the
account
:param type: the type of images to fetch: ``"distribution"``,
``"application"``, or all (`None`); default: `None`
:type type: string or None
:param bool private: whether to only return the user's private images;
default: return all images
:rtype: generator of `Image`\ s
:raises DOAPIError: if the API endpoint replies with an error | Below is the the instruction that describes the task:
### Input:
r"""
Returns a generator that yields all of the images available to the
account
:param type: the type of images to fetch: ``"distribution"``,
``"application"``, or all (`None`); default: `None`
:type type: string or None
:param bool private: whether to only return the user's private images;
default: return all images
:rtype: generator of `Image`\ s
:raises DOAPIError: if the API endpoint replies with an error
### Response:
def fetch_all_images(self, type=None, private=None):
# pylint: disable=redefined-builtin
r"""
Returns a generator that yields all of the images available to the
account
:param type: the type of images to fetch: ``"distribution"``,
``"application"``, or all (`None`); default: `None`
:type type: string or None
:param bool private: whether to only return the user's private images;
default: return all images
:rtype: generator of `Image`\ s
:raises DOAPIError: if the API endpoint replies with an error
"""
params = {}
if type is not None:
params["type"] = type
if private is not None:
params["private"] = 'true' if private else 'false'
return map(self._image, self.paginate('/v2/images', 'images',
params=params)) |
def status(name, sig=None):
'''
Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name>
'''
cmd = 's6-svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd)
try:
pid = re.search(r'up \(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid | Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name> | Below is the the instruction that describes the task:
### Input:
Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name>
### Response:
def status(name, sig=None):
'''
Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name>
'''
cmd = 's6-svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd)
try:
pid = re.search(r'up \(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid |
def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1,
dest_coord=None):
"""Private method to handle generic mouse button clicking.
Parameters: coord (x, y) to click, mouseButton (e.g.,
kCGMouseButtonLeft), modFlags set (int)
Optional: clickCount (default 1; set to 2 for double-click; 3 for
triple-click on host)
Returns: None
"""
# For now allow only left and right mouse buttons:
mouseButtons = {
Quartz.kCGMouseButtonLeft: 'LeftMouse',
Quartz.kCGMouseButtonRight: 'RightMouse',
}
if mouseButton not in mouseButtons:
raise ValueError('Mouse button given not recognized')
eventButtonDown = getattr(Quartz,
'kCGEvent%sDown' % mouseButtons[mouseButton])
eventButtonUp = getattr(Quartz,
'kCGEvent%sUp' % mouseButtons[mouseButton])
eventButtonDragged = getattr(Quartz,
'kCGEvent%sDragged' % mouseButtons[
mouseButton])
# Press the button
buttonDown = Quartz.CGEventCreateMouseEvent(None,
eventButtonDown,
coord,
mouseButton)
# Set modflags (default None) on button down:
Quartz.CGEventSetFlags(buttonDown, modFlags)
# Set the click count on button down:
Quartz.CGEventSetIntegerValueField(buttonDown,
Quartz.kCGMouseEventClickState,
int(clickCount))
if dest_coord:
# Drag and release the button
buttonDragged = Quartz.CGEventCreateMouseEvent(None,
eventButtonDragged,
dest_coord,
mouseButton)
# Set modflags on the button dragged:
Quartz.CGEventSetFlags(buttonDragged, modFlags)
buttonUp = Quartz.CGEventCreateMouseEvent(None,
eventButtonUp,
dest_coord,
mouseButton)
else:
# Release the button
buttonUp = Quartz.CGEventCreateMouseEvent(None,
eventButtonUp,
coord,
mouseButton)
# Set modflags on the button up:
Quartz.CGEventSetFlags(buttonUp, modFlags)
# Set the click count on button up:
Quartz.CGEventSetIntegerValueField(buttonUp,
Quartz.kCGMouseEventClickState,
int(clickCount))
# Queue the events
self._queueEvent(Quartz.CGEventPost,
(Quartz.kCGSessionEventTap, buttonDown))
if dest_coord:
self._queueEvent(Quartz.CGEventPost,
(Quartz.kCGHIDEventTap, buttonDragged))
self._queueEvent(Quartz.CGEventPost,
(Quartz.kCGSessionEventTap, buttonUp)) | Private method to handle generic mouse button clicking.
Parameters: coord (x, y) to click, mouseButton (e.g.,
kCGMouseButtonLeft), modFlags set (int)
Optional: clickCount (default 1; set to 2 for double-click; 3 for
triple-click on host)
Returns: None | Below is the the instruction that describes the task:
### Input:
Private method to handle generic mouse button clicking.
Parameters: coord (x, y) to click, mouseButton (e.g.,
kCGMouseButtonLeft), modFlags set (int)
Optional: clickCount (default 1; set to 2 for double-click; 3 for
triple-click on host)
Returns: None
### Response:
def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1,
dest_coord=None):
"""Private method to handle generic mouse button clicking.
Parameters: coord (x, y) to click, mouseButton (e.g.,
kCGMouseButtonLeft), modFlags set (int)
Optional: clickCount (default 1; set to 2 for double-click; 3 for
triple-click on host)
Returns: None
"""
# For now allow only left and right mouse buttons:
mouseButtons = {
Quartz.kCGMouseButtonLeft: 'LeftMouse',
Quartz.kCGMouseButtonRight: 'RightMouse',
}
if mouseButton not in mouseButtons:
raise ValueError('Mouse button given not recognized')
eventButtonDown = getattr(Quartz,
'kCGEvent%sDown' % mouseButtons[mouseButton])
eventButtonUp = getattr(Quartz,
'kCGEvent%sUp' % mouseButtons[mouseButton])
eventButtonDragged = getattr(Quartz,
'kCGEvent%sDragged' % mouseButtons[
mouseButton])
# Press the button
buttonDown = Quartz.CGEventCreateMouseEvent(None,
eventButtonDown,
coord,
mouseButton)
# Set modflags (default None) on button down:
Quartz.CGEventSetFlags(buttonDown, modFlags)
# Set the click count on button down:
Quartz.CGEventSetIntegerValueField(buttonDown,
Quartz.kCGMouseEventClickState,
int(clickCount))
if dest_coord:
# Drag and release the button
buttonDragged = Quartz.CGEventCreateMouseEvent(None,
eventButtonDragged,
dest_coord,
mouseButton)
# Set modflags on the button dragged:
Quartz.CGEventSetFlags(buttonDragged, modFlags)
buttonUp = Quartz.CGEventCreateMouseEvent(None,
eventButtonUp,
dest_coord,
mouseButton)
else:
# Release the button
buttonUp = Quartz.CGEventCreateMouseEvent(None,
eventButtonUp,
coord,
mouseButton)
# Set modflags on the button up:
Quartz.CGEventSetFlags(buttonUp, modFlags)
# Set the click count on button up:
Quartz.CGEventSetIntegerValueField(buttonUp,
Quartz.kCGMouseEventClickState,
int(clickCount))
# Queue the events
self._queueEvent(Quartz.CGEventPost,
(Quartz.kCGSessionEventTap, buttonDown))
if dest_coord:
self._queueEvent(Quartz.CGEventPost,
(Quartz.kCGHIDEventTap, buttonDragged))
self._queueEvent(Quartz.CGEventPost,
(Quartz.kCGSessionEventTap, buttonUp)) |
def stableSlugId():
"""Returns a closure which can be used to generate stable slugIds.
Stable slugIds can be used in a graph to specify task IDs in multiple
places without regenerating them, e.g. taskId, requires, etc.
"""
_cache = {}
def closure(name):
if name not in _cache:
_cache[name] = slugId()
return _cache[name]
return closure | Returns a closure which can be used to generate stable slugIds.
Stable slugIds can be used in a graph to specify task IDs in multiple
places without regenerating them, e.g. taskId, requires, etc. | Below is the the instruction that describes the task:
### Input:
Returns a closure which can be used to generate stable slugIds.
Stable slugIds can be used in a graph to specify task IDs in multiple
places without regenerating them, e.g. taskId, requires, etc.
### Response:
def stableSlugId():
"""Returns a closure which can be used to generate stable slugIds.
Stable slugIds can be used in a graph to specify task IDs in multiple
places without regenerating them, e.g. taskId, requires, etc.
"""
_cache = {}
def closure(name):
if name not in _cache:
_cache[name] = slugId()
return _cache[name]
return closure |
def calc_support(self, items):
"""
Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']).
"""
# Empty items is supported by all transactions.
if not items:
return 1.0
# Empty transactions supports no items.
if not self.num_transaction:
return 0.0
# Create the transaction index intersection.
sum_indexes = None
for item in items:
indexes = self.__transaction_index_map.get(item)
if indexes is None:
# No support for any set that contains a not existing item.
return 0.0
if sum_indexes is None:
# Assign the indexes on the first time.
sum_indexes = indexes
else:
# Calculate the intersection on not the first time.
sum_indexes = sum_indexes.intersection(indexes)
# Calculate and return the support.
return float(len(sum_indexes)) / self.__num_transaction | Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']). | Below is the the instruction that describes the task:
### Input:
Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']).
### Response:
def calc_support(self, items):
"""
Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']).
"""
# Empty items is supported by all transactions.
if not items:
return 1.0
# Empty transactions supports no items.
if not self.num_transaction:
return 0.0
# Create the transaction index intersection.
sum_indexes = None
for item in items:
indexes = self.__transaction_index_map.get(item)
if indexes is None:
# No support for any set that contains a not existing item.
return 0.0
if sum_indexes is None:
# Assign the indexes on the first time.
sum_indexes = indexes
else:
# Calculate the intersection on not the first time.
sum_indexes = sum_indexes.intersection(indexes)
# Calculate and return the support.
return float(len(sum_indexes)) / self.__num_transaction |
def delete_collection_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_stateful_set # noqa: E501
delete collection of StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501
else:
(data) = self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501
return data | delete_collection_namespaced_stateful_set # noqa: E501
delete collection of StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread. | Below is the the instruction that describes the task:
### Input:
delete_collection_namespaced_stateful_set # noqa: E501
delete collection of StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
### Response:
def delete_collection_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_stateful_set # noqa: E501
delete collection of StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501
else:
(data) = self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501
return data |
def to_8bit(self):
"""
Convert to 8-bit color
:return: Color8Bit instance
"""
h, s, v = colorsys.rgb_to_hsv(*self.scale(1))
# Check if the color is a shade of grey
if s * v < 0.3:
if v < 0.3:
return Color8Bit(Color8Bit.BLACK, False)
elif v < 0.66:
return Color8Bit(Color8Bit.BLACK, True)
elif v < 0.91:
return Color8Bit(Color8Bit.WHITE, False)
else:
return Color8Bit(Color8Bit.WHITE, True)
# not grey? What color is it then?
if h < 0.041 or h > 0.92:
res = Color8Bit.RED
elif h < 0.11:
# orange = dark yellow
return Color8Bit(Color8Bit.YELLOW, False)
elif h < 0.2:
res = Color8Bit.YELLOW
elif h < 0.45:
res = Color8Bit.GREEN
elif h < 0.6:
res = Color8Bit.CYAN
elif h < 0.74:
res = Color8Bit.BLUE
else:
res = Color8Bit.MAGENTA
return Color8Bit(res, v > 0.6) | Convert to 8-bit color
:return: Color8Bit instance | Below is the the instruction that describes the task:
### Input:
Convert to 8-bit color
:return: Color8Bit instance
### Response:
def to_8bit(self):
"""
Convert to 8-bit color
:return: Color8Bit instance
"""
h, s, v = colorsys.rgb_to_hsv(*self.scale(1))
# Check if the color is a shade of grey
if s * v < 0.3:
if v < 0.3:
return Color8Bit(Color8Bit.BLACK, False)
elif v < 0.66:
return Color8Bit(Color8Bit.BLACK, True)
elif v < 0.91:
return Color8Bit(Color8Bit.WHITE, False)
else:
return Color8Bit(Color8Bit.WHITE, True)
# not grey? What color is it then?
if h < 0.041 or h > 0.92:
res = Color8Bit.RED
elif h < 0.11:
# orange = dark yellow
return Color8Bit(Color8Bit.YELLOW, False)
elif h < 0.2:
res = Color8Bit.YELLOW
elif h < 0.45:
res = Color8Bit.GREEN
elif h < 0.6:
res = Color8Bit.CYAN
elif h < 0.74:
res = Color8Bit.BLUE
else:
res = Color8Bit.MAGENTA
return Color8Bit(res, v > 0.6) |
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None):
"""Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with check_key. Example: "CNAME"
Returns:
json: Found Record. Returns None if no record found
"""
client = boto3.Session(profile_name=env).client('route53')
pager = client.get_paginator('list_resource_record_sets')
existingrecord = None
for rset in pager.paginate(HostedZoneId=zone_id):
for record in rset['ResourceRecordSets']:
if check_key:
if record['Name'].rstrip('.') == dns_name and record.get(check_key) == check_value:
LOG.info("Found existing record: %s", record)
existingrecord = record
break
return existingrecord | Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with check_key. Example: "CNAME"
Returns:
json: Found Record. Returns None if no record found | Below is the the instruction that describes the task:
### Input:
Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with check_key. Example: "CNAME"
Returns:
json: Found Record. Returns None if no record found
### Response:
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None):
"""Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with check_key. Example: "CNAME"
Returns:
json: Found Record. Returns None if no record found
"""
client = boto3.Session(profile_name=env).client('route53')
pager = client.get_paginator('list_resource_record_sets')
existingrecord = None
for rset in pager.paginate(HostedZoneId=zone_id):
for record in rset['ResourceRecordSets']:
if check_key:
if record['Name'].rstrip('.') == dns_name and record.get(check_key) == check_value:
LOG.info("Found existing record: %s", record)
existingrecord = record
break
return existingrecord |
def add_section(self, ino, sector_count, load_seg, media_name, system_type,
efi, bootable):
# type: (inode.Inode, int, int, str, int, bool, bool) -> None
'''
A method to add an section header and entry to this Boot Catalog.
Parameters:
ino - The Inode object to associate with the new Entry.
sector_count - The number of sectors to assign to the new Entry.
load_seg - The load segment address of the boot image.
media_name - The name of the media type, one of 'noemul', 'floppy', or 'hdemul'.
system_type - The type of partition this entry should be.
efi - Whether this section is an EFI section.
bootable - Whether this entry should be bootable.
Returns:
Nothing.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError('El Torito Boot Catalog not yet initialized')
# The Eltorito Boot Catalog can only be 2048 bytes (1 extent). By
# default, the first 64 bytes are used by the Validation Entry and the
# Initial Entry, which leaves 1984 bytes. Each section takes up 32
# bytes for the Section Header and 32 bytes for the Section Entry, for
# a total of 64 bytes, so we can have a maximum of 1984/64 = 31
# sections.
if len(self.sections) == 31:
raise pycdlibexception.PyCdlibInvalidInput('Too many Eltorito sections')
sec = EltoritoSectionHeader()
platform_id = self.validation_entry.platform_id
if efi:
platform_id = 0xef
sec.new(b'\x00' * 28, platform_id)
secentry = EltoritoEntry()
secentry.new(sector_count, load_seg, media_name, system_type, bootable)
secentry.set_inode(ino)
ino.linked_records.append(secentry)
sec.add_new_entry(secentry)
if self.sections:
self.sections[-1].set_record_not_last()
self.sections.append(sec) | A method to add an section header and entry to this Boot Catalog.
Parameters:
ino - The Inode object to associate with the new Entry.
sector_count - The number of sectors to assign to the new Entry.
load_seg - The load segment address of the boot image.
media_name - The name of the media type, one of 'noemul', 'floppy', or 'hdemul'.
system_type - The type of partition this entry should be.
efi - Whether this section is an EFI section.
bootable - Whether this entry should be bootable.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
A method to add an section header and entry to this Boot Catalog.
Parameters:
ino - The Inode object to associate with the new Entry.
sector_count - The number of sectors to assign to the new Entry.
load_seg - The load segment address of the boot image.
media_name - The name of the media type, one of 'noemul', 'floppy', or 'hdemul'.
system_type - The type of partition this entry should be.
efi - Whether this section is an EFI section.
bootable - Whether this entry should be bootable.
Returns:
Nothing.
### Response:
def add_section(self, ino, sector_count, load_seg, media_name, system_type,
efi, bootable):
# type: (inode.Inode, int, int, str, int, bool, bool) -> None
'''
A method to add an section header and entry to this Boot Catalog.
Parameters:
ino - The Inode object to associate with the new Entry.
sector_count - The number of sectors to assign to the new Entry.
load_seg - The load segment address of the boot image.
media_name - The name of the media type, one of 'noemul', 'floppy', or 'hdemul'.
system_type - The type of partition this entry should be.
efi - Whether this section is an EFI section.
bootable - Whether this entry should be bootable.
Returns:
Nothing.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError('El Torito Boot Catalog not yet initialized')
# The Eltorito Boot Catalog can only be 2048 bytes (1 extent). By
# default, the first 64 bytes are used by the Validation Entry and the
# Initial Entry, which leaves 1984 bytes. Each section takes up 32
# bytes for the Section Header and 32 bytes for the Section Entry, for
# a total of 64 bytes, so we can have a maximum of 1984/64 = 31
# sections.
if len(self.sections) == 31:
raise pycdlibexception.PyCdlibInvalidInput('Too many Eltorito sections')
sec = EltoritoSectionHeader()
platform_id = self.validation_entry.platform_id
if efi:
platform_id = 0xef
sec.new(b'\x00' * 28, platform_id)
secentry = EltoritoEntry()
secentry.new(sector_count, load_seg, media_name, system_type, bootable)
secentry.set_inode(ino)
ino.linked_records.append(secentry)
sec.add_new_entry(secentry)
if self.sections:
self.sections[-1].set_record_not_last()
self.sections.append(sec) |
def rel_humid_from_db_wb(db_temp, wet_bulb, b_press=101325):
"""Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa).
"""
# Calculate saturation pressure.
p_ws = saturated_vapor_pressure(db_temp + 273.15)
p_ws_wb = saturated_vapor_pressure(wet_bulb + 273.15)
# calculate partial vapor pressure
p_w = p_ws_wb - (b_press * 0.000662 * (db_temp - wet_bulb))
# Calculate the relative humidity.
rel_humid = (p_w / p_ws) * 100
return rel_humid | Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa). | Below is the the instruction that describes the task:
### Input:
Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa).
### Response:
def rel_humid_from_db_wb(db_temp, wet_bulb, b_press=101325):
"""Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa).
"""
# Calculate saturation pressure.
p_ws = saturated_vapor_pressure(db_temp + 273.15)
p_ws_wb = saturated_vapor_pressure(wet_bulb + 273.15)
# calculate partial vapor pressure
p_w = p_ws_wb - (b_press * 0.000662 * (db_temp - wet_bulb))
# Calculate the relative humidity.
rel_humid = (p_w / p_ws) * 100
return rel_humid |
def a_alpha_and_derivatives(self, T, full=True, quick=True):
r'''Method to calculate `a_alpha` and its first and second
derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
`d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more
documentation. Uses the set values of `Tc`, `omega`, and `a`.
Because of its similarity for the TWUPR EOS, this has been moved to an
external `TWU_a_alpha_common` function. See it for further
documentation.
'''
return TWU_a_alpha_common(T, self.Tc, self.omega, self.a, full=full, quick=quick, method='SRK') | r'''Method to calculate `a_alpha` and its first and second
derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
`d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more
documentation. Uses the set values of `Tc`, `omega`, and `a`.
Because of its similarity for the TWUPR EOS, this has been moved to an
external `TWU_a_alpha_common` function. See it for further
documentation. | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate `a_alpha` and its first and second
derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
`d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more
documentation. Uses the set values of `Tc`, `omega`, and `a`.
Because of its similarity for the TWUPR EOS, this has been moved to an
external `TWU_a_alpha_common` function. See it for further
documentation.
### Response:
def a_alpha_and_derivatives(self, T, full=True, quick=True):
r'''Method to calculate `a_alpha` and its first and second
derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
`d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more
documentation. Uses the set values of `Tc`, `omega`, and `a`.
Because of its similarity for the TWUPR EOS, this has been moved to an
external `TWU_a_alpha_common` function. See it for further
documentation.
'''
return TWU_a_alpha_common(T, self.Tc, self.omega, self.a, full=full, quick=quick, method='SRK') |
def showinfo(self):
''' 總覽顯示 '''
print 'money:',self.money
print 'store:',self.store
print 'avgprice:',self.avgprice | 總覽顯示 | Below is the the instruction that describes the task:
### Input:
總覽顯示
### Response:
def showinfo(self):
''' 總覽顯示 '''
print 'money:',self.money
print 'store:',self.store
print 'avgprice:',self.avgprice |
def open_process(cls, cmd, **kwargs):
"""Opens a process object via subprocess.Popen().
:param string|list cmd: A list or string representing the command to run.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A `subprocess.Popen` object.
:raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
"""
assert len(cmd) > 0, 'cannot execute an empty command!'
try:
return subprocess.Popen(cmd, **kwargs)
except (IOError, OSError) as e:
if e.errno == errno.ENOENT:
raise cls.ExecutableNotFound(cmd, e)
else:
raise cls.ExecutionError(repr(e), cmd, e) | Opens a process object via subprocess.Popen().
:param string|list cmd: A list or string representing the command to run.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A `subprocess.Popen` object.
:raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist. | Below is the the instruction that describes the task:
### Input:
Opens a process object via subprocess.Popen().
:param string|list cmd: A list or string representing the command to run.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A `subprocess.Popen` object.
:raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
### Response:
def open_process(cls, cmd, **kwargs):
"""Opens a process object via subprocess.Popen().
:param string|list cmd: A list or string representing the command to run.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A `subprocess.Popen` object.
:raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
"""
assert len(cmd) > 0, 'cannot execute an empty command!'
try:
return subprocess.Popen(cmd, **kwargs)
except (IOError, OSError) as e:
if e.errno == errno.ENOENT:
raise cls.ExecutableNotFound(cmd, e)
else:
raise cls.ExecutionError(repr(e), cmd, e) |
def checkpath(path_, verbose=VERYVERBOSE, n=None, info=VERYVERBOSE):
r""" verbose wrapper around ``os.path.exists``
Returns:
true if ``path_`` exists on the filesystem show only the
top `n` directories
Args:
path_ (str): path string
verbose (bool): verbosity flag(default = False)
n (int): (default = None)
info (bool): (default = False)
CommandLine:
python -m utool.util_path --test-checkpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__
>>> verbose = True
>>> n = None
>>> info = False
>>> result = checkpath(path_, verbose, n, info)
>>> print(result)
True
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__ + 'foobar'
>>> verbose = True
>>> result = checkpath(path_, verbose, n=None, info=True)
>>> print(result)
False
"""
assert isinstance(path_, six.string_types), (
'path_=%r is not a string. type(path_) = %r' % (path_, type(path_)))
path_ = normpath(path_)
if sys.platform.startswith('win32'):
# convert back to windows style path if using unix style
if path_.startswith('\\'):
dirs = path_.split('\\')
if len(dirs) > 1 and len(dirs[0]) == 0 and len(dirs[1]) == 1:
dirs[1] = dirs[1].upper() + ':'
path_ = '\\'.join(dirs[1:])
does_exist = exists(path_)
if verbose:
#print_('[utool] checkpath(%r)' % (path_))
pretty_path = path_ndir_split(path_, n)
caller_name = util_dbg.get_caller_name(allow_genexpr=False)
print('[%s] checkpath(%r)' % (caller_name, pretty_path))
if does_exist:
path_type = get_path_type(path_)
#path_type = 'file' if isfile(path_) else 'directory'
print('[%s] ...(%s) exists' % (caller_name, path_type,))
else:
print('[%s] ... does not exist' % (caller_name))
if not does_exist and info:
#print('[util_path] ! Does not exist')
_longest_path = longest_existing_path(path_)
_longest_path_type = get_path_type(_longest_path)
print('[util_path] ... The longest existing path is: %r' % _longest_path)
print('[util_path] ... and has type %r' % (_longest_path_type,))
return does_exist | r""" verbose wrapper around ``os.path.exists``
Returns:
true if ``path_`` exists on the filesystem show only the
top `n` directories
Args:
path_ (str): path string
verbose (bool): verbosity flag(default = False)
n (int): (default = None)
info (bool): (default = False)
CommandLine:
python -m utool.util_path --test-checkpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__
>>> verbose = True
>>> n = None
>>> info = False
>>> result = checkpath(path_, verbose, n, info)
>>> print(result)
True
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__ + 'foobar'
>>> verbose = True
>>> result = checkpath(path_, verbose, n=None, info=True)
>>> print(result)
False | Below is the the instruction that describes the task:
### Input:
r""" verbose wrapper around ``os.path.exists``
Returns:
true if ``path_`` exists on the filesystem show only the
top `n` directories
Args:
path_ (str): path string
verbose (bool): verbosity flag(default = False)
n (int): (default = None)
info (bool): (default = False)
CommandLine:
python -m utool.util_path --test-checkpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__
>>> verbose = True
>>> n = None
>>> info = False
>>> result = checkpath(path_, verbose, n, info)
>>> print(result)
True
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__ + 'foobar'
>>> verbose = True
>>> result = checkpath(path_, verbose, n=None, info=True)
>>> print(result)
False
### Response:
def checkpath(path_, verbose=VERYVERBOSE, n=None, info=VERYVERBOSE):
r""" verbose wrapper around ``os.path.exists``
Returns:
true if ``path_`` exists on the filesystem show only the
top `n` directories
Args:
path_ (str): path string
verbose (bool): verbosity flag(default = False)
n (int): (default = None)
info (bool): (default = False)
CommandLine:
python -m utool.util_path --test-checkpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__
>>> verbose = True
>>> n = None
>>> info = False
>>> result = checkpath(path_, verbose, n, info)
>>> print(result)
True
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> path_ = ut.__file__ + 'foobar'
>>> verbose = True
>>> result = checkpath(path_, verbose, n=None, info=True)
>>> print(result)
False
"""
assert isinstance(path_, six.string_types), (
'path_=%r is not a string. type(path_) = %r' % (path_, type(path_)))
path_ = normpath(path_)
if sys.platform.startswith('win32'):
# convert back to windows style path if using unix style
if path_.startswith('\\'):
dirs = path_.split('\\')
if len(dirs) > 1 and len(dirs[0]) == 0 and len(dirs[1]) == 1:
dirs[1] = dirs[1].upper() + ':'
path_ = '\\'.join(dirs[1:])
does_exist = exists(path_)
if verbose:
#print_('[utool] checkpath(%r)' % (path_))
pretty_path = path_ndir_split(path_, n)
caller_name = util_dbg.get_caller_name(allow_genexpr=False)
print('[%s] checkpath(%r)' % (caller_name, pretty_path))
if does_exist:
path_type = get_path_type(path_)
#path_type = 'file' if isfile(path_) else 'directory'
print('[%s] ...(%s) exists' % (caller_name, path_type,))
else:
print('[%s] ... does not exist' % (caller_name))
if not does_exist and info:
#print('[util_path] ! Does not exist')
_longest_path = longest_existing_path(path_)
_longest_path_type = get_path_type(_longest_path)
print('[util_path] ... The longest existing path is: %r' % _longest_path)
print('[util_path] ... and has type %r' % (_longest_path_type,))
return does_exist |
def dropna(df, nonnull_rows=100, nonnull_cols=50, nanstrs=('nan', 'NaN', ''), nullstr=''):
"""Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns: []
Index: []
>>> dropna(df, nonnull_cols=0, nonnull_rows=0)
0 1 2
0 NaN str
1 0.1 and
2 2 NaN
"""
if 0 < nonnull_rows < 1:
nonnull_rows = int(nonnull_rows * len(df))
if 0 < nonnull_cols < 1:
nonnull_cols = int(nonnull_cols * len(df.columns))
for label in df.columns:
series = df[label].copy()
if series.dtype in (np.dtype('O'), np.dtype('U'), np.dtype('S')):
for nanstr in nanstrs:
series[series == nanstr] = np.nan
df[label] = series
# in iPython Notebook, try dropping with lower thresholds, checking column and row count each time
print('The raw table shape is {}'.format(df.shape))
df = df.dropna(axis=1, thresh=nonnull_rows)
print('After dropping columns with fewer than {} nonnull values, the table shape is {}'.format(nonnull_rows, df.shape))
df = df.dropna(axis=0, thresh=nonnull_cols)
print('After dropping rows with fewer than {} nonnull values, the table shape is {}'.format(nonnull_cols, df.shape))
for label in df.columns:
series = df[label].copy()
if series.dtype == np.dtype('O'):
nonnull_dtype = series.dropna(inplace=False).values.dtype
if nonnull_dtype == np.dtype('O'):
series[series.isnull()] = nullstr
df[label] = series
else:
df[label] = series.astype(nonnull_dtype)
return df | Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns: []
Index: []
>>> dropna(df, nonnull_cols=0, nonnull_rows=0)
0 1 2
0 NaN str
1 0.1 and
2 2 NaN | Below is the the instruction that describes the task:
### Input:
Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns: []
Index: []
>>> dropna(df, nonnull_cols=0, nonnull_rows=0)
0 1 2
0 NaN str
1 0.1 and
2 2 NaN
### Response:
def dropna(df, nonnull_rows=100, nonnull_cols=50, nanstrs=('nan', 'NaN', ''), nullstr=''):
"""Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns: []
Index: []
>>> dropna(df, nonnull_cols=0, nonnull_rows=0)
0 1 2
0 NaN str
1 0.1 and
2 2 NaN
"""
if 0 < nonnull_rows < 1:
nonnull_rows = int(nonnull_rows * len(df))
if 0 < nonnull_cols < 1:
nonnull_cols = int(nonnull_cols * len(df.columns))
for label in df.columns:
series = df[label].copy()
if series.dtype in (np.dtype('O'), np.dtype('U'), np.dtype('S')):
for nanstr in nanstrs:
series[series == nanstr] = np.nan
df[label] = series
# in iPython Notebook, try dropping with lower thresholds, checking column and row count each time
print('The raw table shape is {}'.format(df.shape))
df = df.dropna(axis=1, thresh=nonnull_rows)
print('After dropping columns with fewer than {} nonnull values, the table shape is {}'.format(nonnull_rows, df.shape))
df = df.dropna(axis=0, thresh=nonnull_cols)
print('After dropping rows with fewer than {} nonnull values, the table shape is {}'.format(nonnull_cols, df.shape))
for label in df.columns:
series = df[label].copy()
if series.dtype == np.dtype('O'):
nonnull_dtype = series.dropna(inplace=False).values.dtype
if nonnull_dtype == np.dtype('O'):
series[series.isnull()] = nullstr
df[label] = series
else:
df[label] = series.astype(nonnull_dtype)
return df |
def add_text(orig, dc, img, text=None):
"""Add text to an image using the pydecorate package.
All the features of pydecorate's ``add_text`` are available.
See documentation of :doc:`pydecorate:index` for more info.
"""
LOG.info("Add text to image.")
dc.add_text(**text)
arr = da.from_array(np.array(img) / 255.0, chunks=CHUNK_SIZE)
new_data = xr.DataArray(arr, dims=['y', 'x', 'bands'],
coords={'y': orig.data.coords['y'],
'x': orig.data.coords['x'],
'bands': list(img.mode)},
attrs=orig.data.attrs)
return XRImage(new_data) | Add text to an image using the pydecorate package.
All the features of pydecorate's ``add_text`` are available.
See documentation of :doc:`pydecorate:index` for more info. | Below is the the instruction that describes the task:
### Input:
Add text to an image using the pydecorate package.
All the features of pydecorate's ``add_text`` are available.
See documentation of :doc:`pydecorate:index` for more info.
### Response:
def add_text(orig, dc, img, text=None):
"""Add text to an image using the pydecorate package.
All the features of pydecorate's ``add_text`` are available.
See documentation of :doc:`pydecorate:index` for more info.
"""
LOG.info("Add text to image.")
dc.add_text(**text)
arr = da.from_array(np.array(img) / 255.0, chunks=CHUNK_SIZE)
new_data = xr.DataArray(arr, dims=['y', 'x', 'bands'],
coords={'y': orig.data.coords['y'],
'x': orig.data.coords['x'],
'bands': list(img.mode)},
attrs=orig.data.attrs)
return XRImage(new_data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.