code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_daily_rates(date_req: datetime.datetime = None, lang: str = 'rus') -> Element:
""" Getting currency for current day.
see example: http://www.cbr.ru/scripts/Root.asp?PrtId=SXML
:param date_req:
:type date_req: datetime.datetime
:param lang: language of API response ('eng' || 'rus')
:typ... | Getting currency for current day.
see example: http://www.cbr.ru/scripts/Root.asp?PrtId=SXML
:param date_req:
:type date_req: datetime.datetime
:param lang: language of API response ('eng' || 'rus')
:type lang: str
:return: :class: `Element <Element 'ValCurs'>` object
:rtype: ElementTree.... |
def load(self):
"""
Extract tabular data as |TableData| instances from a CSV file.
|load_source_desc_file|
:return:
Loaded table data.
|load_table_name_desc|
=================== ========================================
Format specifier ... | Extract tabular data as |TableData| instances from a CSV file.
|load_source_desc_file|
:return:
Loaded table data.
|load_table_name_desc|
=================== ========================================
Format specifier Value after the replacement
... |
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
... | Initialize centroids according to method by Huang [1997]. |
def dataSource(self, value):
""" sets the datasource object """
if isinstance(value, DataSource):
self._dataSource = value
else:
raise TypeError("value must be a DataSource object") | sets the datasource object |
def stripIEConditionals(contents, addHtmlIfMissing=True):
'''
stripIEConditionals - Strips Internet Explorer conditional statements.
@param contents <str> - Contents String
@param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing.... | stripIEConditionals - Strips Internet Explorer conditional statements.
@param contents <str> - Contents String
@param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing. |
def _fake_openreferenceinstancepaths(self, namespace, **params):
# pylint: disable=invalid-name
"""
Implements WBEM server responder for
:meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths`
with data from the instance repository.
"""
self._validate_namespace(... | Implements WBEM server responder for
:meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths`
with data from the instance repository. |
def nhs_number_from_text_or_none(s: str) -> Optional[int]:
"""
Returns a validated NHS number (as an integer) from a string, or ``None``
if it is not valid.
It's a 10-digit number, so note that database 32-bit INT values are
insufficient; use BIGINT. Python will handle large integers happily.
... | Returns a validated NHS number (as an integer) from a string, or ``None``
if it is not valid.
It's a 10-digit number, so note that database 32-bit INT values are
insufficient; use BIGINT. Python will handle large integers happily.
NHS number rules:
http://www.datadictionary.nhs.uk/... |
def append_row(self, index, value):
"""
Appends a row of value to the end of the data. Be very careful with this function as for sorted Series it will
not enforce sort order. Use this only for speed when needed, be careful.
:param index: index
:param value: value
:retur... | Appends a row of value to the end of the data. Be very careful with this function as for sorted Series it will
not enforce sort order. Use this only for speed when needed, be careful.
:param index: index
:param value: value
:return: nothing |
def write(self, stream):
"""Writes the topology to a stream or file."""
topology = self.createTopology()
def write_it(stream):
transportOut = TMemoryBuffer()
protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut)
topology.write(protocolOut)
by... | Writes the topology to a stream or file. |
def astuple(obj, *, tuple_factory=tuple):
"""Return the fields of a dataclass instance as a new tuple of field values.
Example usage::
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert astuple(c) == (1, 2)
If given, 'tuple_factory' will be used instead of built... | Return the fields of a dataclass instance as a new tuple of field values.
Example usage::
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert astuple(c) == (1, 2)
If given, 'tuple_factory' will be used instead of built-in tuple.
The function applies recursively t... |
def delete_many(self, filter, collation=None):
"""Delete one or more documents matching the filter.
>>> db.test.count({'x': 1})
3
>>> result = db.test.delete_many({'x': 1})
>>> result.deleted_count
3
>>> db.test.count({'x': 1})
0
:P... | Delete one or more documents matching the filter.
>>> db.test.count({'x': 1})
3
>>> result = db.test.delete_many({'x': 1})
>>> result.deleted_count
3
>>> db.test.count({'x': 1})
0
:Parameters:
- `filter`: A query that matches the ... |
def add_core(self, x, y, p):
"""Add a new core to the region tree.
Raises
------
ValueError
If the co-ordinate is not contained within this part of the tree or
the core number is out of range.
Returns
-------
bool
True if the ... | Add a new core to the region tree.
Raises
------
ValueError
If the co-ordinate is not contained within this part of the tree or
the core number is out of range.
Returns
-------
bool
True if the specified core is to be loaded to all su... |
def delete_timeline(self, scope_identifier, hub_name, plan_id, timeline_id):
"""DeleteTimeline.
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "build" for the Build server or "rm" for the Release Management server
:para... | DeleteTimeline.
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "build" for the Build server or "rm" for the Release Management server
:param str plan_id:
:param str timeline_id: |
def construct_oauth_url(self):
""" Constructs verifier OAuth URL """
response = self._requester(requests.head,
"{0}://{1}/".format(self.protocol, self.client.server),
allow_redirects=False
)
... | Constructs verifier OAuth URL |
def _extract_id(self) -> str:
"""
Get video_id needed to obtain the real_url of the video.
Raises:
VideoIdNotMatchedError: If video_id is not matched with regular expression.
"""
match = re.match(self._VALID_URL, self.url)
if match:
return match... | Get video_id needed to obtain the real_url of the video.
Raises:
VideoIdNotMatchedError: If video_id is not matched with regular expression. |
def from_date(datetime_date):
"""
construct BusinessDate instance from datetime.date instance,
raise ValueError exception if not possible
:param datetime.date datetime_date: calendar day
:return bool:
"""
return BusinessDate.from_ymd(datetime_date.year, datetime_... | construct BusinessDate instance from datetime.date instance,
raise ValueError exception if not possible
:param datetime.date datetime_date: calendar day
:return bool: |
def unset_required_for(cls, sharable_fields):
"""
Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are
required if they are declared in `sharable_fields`. Otherwise just deactivate them.
"""
if 'link_content' in cls.base_fields and 'link_content' ... | Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are
required if they are declared in `sharable_fields`. Otherwise just deactivate them. |
def transform(self, matrix):
"""Modifies the current transformation matrix (CTM)
by applying :obj:`matrix` as an additional transformation.
The new transformation of user space takes place
after any existing transformation.
:param matrix:
A transformation :class:`Mat... | Modifies the current transformation matrix (CTM)
by applying :obj:`matrix` as an additional transformation.
The new transformation of user space takes place
after any existing transformation.
:param matrix:
A transformation :class:`Matrix`
to be applied to the us... |
def uint32_to_uint8(cls, img):
"""
Cast uint32 RGB image to 4 uint8 channels.
"""
return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,))) | Cast uint32 RGB image to 4 uint8 channels. |
def findbeam_gravity(data, mask):
"""Find beam center with the "gravity" method
Inputs:
data: scattering image
mask: mask matrix
Output:
a vector of length 2 with the x (row) and y (column) coordinates
of the origin, starting from 1
"""
# for each row and column fi... | Find beam center with the "gravity" method
Inputs:
data: scattering image
mask: mask matrix
Output:
a vector of length 2 with the x (row) and y (column) coordinates
of the origin, starting from 1 |
def add_reciprocal_link(self, target, weight):
"""
Add links pointing in either direction between ``self`` and ``target``.
This creates a ``Link`` from ``self`` to ``target`` and a ``Link``
from ``target`` to ``self`` of equal weight. If ``target`` is a list
of ``Node`` 's, repe... | Add links pointing in either direction between ``self`` and ``target``.
This creates a ``Link`` from ``self`` to ``target`` and a ``Link``
from ``target`` to ``self`` of equal weight. If ``target`` is a list
of ``Node`` 's, repeat this for each one.
Args:
target (Node or li... |
def p_toc(self, toc):
'''toc : HEADERSEC opttexts TOC opttexts'''
toc[0] = TableOfContent(toc[1], toc[2], [])
self.toc = toc[0] | toc : HEADERSEC opttexts TOC opttexts |
def groupselectfirst(table, key, presorted=False, buffersize=None,
tempdir=None, cache=True):
"""Group by the `key` field then return the first row within each group.
E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... | Group by the `key` field then return the first row within each group.
E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False],
... ['C', 9, True]]
... |
def status(AuxiliaryStates_presence=0):
"""STATUS Section 9.3.27"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x3d) # 00111101
c = Cause()
d = CallState()
packet = a / b / c / d
if AuxiliaryStates_presence is 1:
e = AuxiliaryStatesHdr(ieiAS=0x24, eightBitAS=0x0)
packet = pack... | STATUS Section 9.3.27 |
def write_bytes(self, bytes, append=False):
""" Open this file and write the given bytes to it.
Default behavior is to overwrite any existing file.
Call ``p.write_bytes(bytes, append=True)`` to append instead.
"""
if append:
mode = 'ab'
else:
mode... | Open this file and write the given bytes to it.
Default behavior is to overwrite any existing file.
Call ``p.write_bytes(bytes, append=True)`` to append instead. |
def walkfolder(toppath, pred):
"""
walk folder if pred(foldername) is True
:type toppath: str
:type pred: function(str) => bool
"""
for entry in scandir.scandir(toppath):
if not entry.is_dir() or not pred(entry.name):
continue
yield entry.path
for p in walkfol... | walk folder if pred(foldername) is True
:type toppath: str
:type pred: function(str) => bool |
def make_ujson_response(obj, status_code=200):
"""Encodes the given *obj* to json and wraps it in a response.
:return:
A Flask response.
"""
json_encoded = ujson.encode(obj, ensure_ascii=False, double_precision=-1)
resp = make_response(json_encoded)
resp.mimetype = 'application/json'
... | Encodes the given *obj* to json and wraps it in a response.
:return:
A Flask response. |
def strip_ids(ids, ids_to_strip):
"""Strip ids_to_strip from the end ids."""
ids = list(ids)
while ids and ids[-1] in ids_to_strip:
ids.pop()
return ids | Strip ids_to_strip from the end ids. |
def clone(self, _, scene):
"""
Create a clone of this Frame into a new Screen.
:param _: ignored.
:param scene: The new Scene object to clone into.
"""
# Assume that the application creates a new set of Frames and so we need to match up the
# data from the old ob... | Create a clone of this Frame into a new Screen.
:param _: ignored.
:param scene: The new Scene object to clone into. |
def dendrogram(tree):
"""Plot a simple square dendrogram using Altair.
Parameters
----------
tree : `dict` returned by `scipy.cluster.hierarchy.dendrogram`
Contains, at a minimum, 'icoord', 'dcoord', and 'leaves' keys. Scipy does all the work of
determining where the lines in the tree should go... | Plot a simple square dendrogram using Altair.
Parameters
----------
tree : `dict` returned by `scipy.cluster.hierarchy.dendrogram`
Contains, at a minimum, 'icoord', 'dcoord', and 'leaves' keys. Scipy does all the work of
determining where the lines in the tree should go. All we have to do is draw t... |
def created_at(self):
"""
:return: When the document was created
:rtype: :py:class:`datetime.datetime`
"""
if self._created_at:
return self._created_at
elif not self.abstract:
return self.read_meta()._created_at
raise EmptyDocumentExceptio... | :return: When the document was created
:rtype: :py:class:`datetime.datetime` |
def set_model(self, m):
"""Set the model for the level
:param m: the model that the level should use
:type m: QtCore.QAbstractItemModel
:returns: None
:rtype: None
:raises: None
"""
self._model = m
self.new_root.emit(QtCore.QModelIndex())
... | Set the model for the level
:param m: the model that the level should use
:type m: QtCore.QAbstractItemModel
:returns: None
:rtype: None
:raises: None |
def _copy_params(self):
"""
Copy all params defined on the class to current object.
"""
cls = type(self)
src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)]
src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs))
for name, ... | Copy all params defined on the class to current object. |
def signup(self, project_name, email):
""" Signup for a new project. """
uri = 'openstack/sign-up'
data = {
"project_name": project_name,
"email": email,
}
post_body = json.dumps(data)
resp, body = self.post(uri, body=post_body)
self.expec... | Signup for a new project. |
def fval(self, instance):
"""return the raw value that this property is holding internally for instance"""
try:
val = instance.__dict__[self.instance_field_name]
except KeyError as e:
#raise AttributeError(str(e))
val = None
return val | return the raw value that this property is holding internally for instance |
def persist_config(run, session, cfg):
"""
Persist the configuration in as key-value pairs.
Args:
run: The run we attach the config to.
session: The db transaction we belong to.
cfg: The configuration we want to persist.
"""
from benchbuild.utils import schema as s
for ... | Persist the configuration in as key-value pairs.
Args:
run: The run we attach the config to.
session: The db transaction we belong to.
cfg: The configuration we want to persist. |
def check_base_required_attributes(self, dataset):
'''
Check the global required and highly recommended attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:Conventions = "CF-1.6, ACD... | Check the global required and highly recommended attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:Conventions = "CF-1.6, ACDD-1.3" ; //............................... REQUIRED - Always try to use... |
def nextpow2(value):
"""Compute the nearest power of two greater or equal to the input value"""
if value >= 1:
return 2**np.ceil(np.log2(value)).astype(int)
elif value > 0:
return 1
elif value == 0:
return 0
else:
raise ValueError('Value must be positive') | Compute the nearest power of two greater or equal to the input value |
def extract_path_ext(path, default_ext=None):
"""
Extract file extension (without dot) from `path` or return `default_ext` if
path does not contain a valid extension.
"""
ext = None
_, dotext = os.path.splitext(path)
if dotext:
ext = dotext[1:]
if not ext and default_ext:
... | Extract file extension (without dot) from `path` or return `default_ext` if
path does not contain a valid extension. |
def create_app_id(self, app_id, policies, display_name=None, mount_point='app-id', **kwargs):
"""POST /auth/<mount point>/map/app-id/<app_id>
:param app_id:
:type app_id:
:param policies:
:type policies:
:param display_name:
:type display_name:
:param mou... | POST /auth/<mount point>/map/app-id/<app_id>
:param app_id:
:type app_id:
:param policies:
:type policies:
:param display_name:
:type display_name:
:param mount_point:
:type mount_point:
:param kwargs:
:type kwargs:
:return:
... |
def add_profile(self, namespace, key, value, force=False):
""" Add profile information to this node at the DAX level
"""
try:
entry = dax.Profile(namespace, key, value)
self._dax_node.addProfile(entry)
except dax.DuplicateError:
if force:
... | Add profile information to this node at the DAX level |
def _notebook_dir_changed(self, name, old, new):
"""do a bit of validation of the notebook dir"""
if os.path.exists(new) and not os.path.isdir(new):
raise TraitError("notebook dir %r is not a directory" % new)
if not os.path.exists(new):
self.log.info("Creating notebook d... | do a bit of validation of the notebook dir |
def build_list_params(self, params, items, label):
"""
Items is a list of dictionaries or strings::
[
{
'Protocol' : 'HTTP',
'LoadBalancerPort' : '80',
'InstancePort' : '80'
},
..
... | Items is a list of dictionaries or strings::
[
{
'Protocol' : 'HTTP',
'LoadBalancerPort' : '80',
'InstancePort' : '80'
},
..
] etc.
or::
['us-east-1b',...] |
def import_context(target_zip):
"""
Overwrite old context.json, use context.json from target_zip
:param target_zip:
:return:
"""
context_path = tasks.get_context_path()
with zipfile.ZipFile(target_zip) as unzipped_data:
with open(context_path, 'w') as context:
context.wri... | Overwrite old context.json, use context.json from target_zip
:param target_zip:
:return: |
def _getdata_by_idx(data, idx):
"""Shuffle the data."""
shuffle_data = []
for k, v in data:
if (isinstance(v, h5py.Dataset) if h5py else False):
shuffle_data.append((k, v))
elif isinstance(v, CSRNDArray):
shuffle_data.append((k, sparse_array(v.asscipy()[idx], v.conte... | Shuffle the data. |
def setup_logfile_raw(self, logfile, mode='w'):
'''start logging raw bytes to the given logfile, without timestamps'''
self.logfile_raw = open(logfile, mode=mode) | start logging raw bytes to the given logfile, without timestamps |
def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
... | Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1'... |
def do_metric_name_list(mc, args):
'''List names of metrics.'''
fields = {}
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.tenant_... | List names of metrics. |
def check_response(res):
""" Check HTTP response and raise exception if response is not OK. """
try:
res.raise_for_status() # Alternative is res.ok
except Exception as exc:
# Bad response code, e.g. if adding an edge with nodes that doesn't exist
try:
err_info = res.json(... | Check HTTP response and raise exception if response is not OK. |
def get_html(self):
"""Generates if need be and returns a simpler html document with text"""
if self.__htmltree is not None:
return self.__htmltree
else:
self.__make_tree()
return self.__htmltree | Generates if need be and returns a simpler html document with text |
def get_temperature_interval(self):
"""Appoints the corresponding temperature interval to each temperature
in the temperature vector.
"""
intervals = ({
-20: 1, -19: 1, -18: 1, -17: 1, -16: 1, -15: 1, -14: 2,
-13: 2, -12: 2, -11: 2, -10: 2, -9: 3, -8: 3, -7: 3, -6... | Appoints the corresponding temperature interval to each temperature
in the temperature vector. |
def book_car(intent_request):
"""
Performs dialog management and fulfillment for booking a car.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be use... | Performs dialog management and fulfillment for booking a car.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be used to guide conversation |
def fit(self, min_ndata_factor=3, max_poly_order_factor=5, min_poly_order=2):
"""
Fit the input data to the 'numerical eos', the equation of state employed
in the quasiharmonic Debye model described in the paper:
10.1103/PhysRevB.90.174107.
credits: Cormac Toher
Args:
... | Fit the input data to the 'numerical eos', the equation of state employed
in the quasiharmonic Debye model described in the paper:
10.1103/PhysRevB.90.174107.
credits: Cormac Toher
Args:
min_ndata_factor (int): parameter that controls the minimum number
of d... |
def colRowIsOnSciencePixel(self, col, row, padding=DEFAULT_PADDING):
"""Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting pa... | Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting padding > 0 means that objects that are computed
to lie a small amount off... |
def current_user(self):
"""
.. versionadded:: 0.6.0
Requires SMC version >= 6.4
Return the currently logged on API Client user element.
:raises UnsupportedEntryPoint: Current user is only supported with SMC
version >= 6.4
:rtype: Element
... | .. versionadded:: 0.6.0
Requires SMC version >= 6.4
Return the currently logged on API Client user element.
:raises UnsupportedEntryPoint: Current user is only supported with SMC
version >= 6.4
:rtype: Element |
def open(self, name, mode='rb'):
"""
Retrieves the specified file from storage.
:param name: file name
:type name: str
:param mode: mode to open the file with
:type mode: str
:rtype: :class:`~django:django.core.files.File`
"""
return self.get_stor... | Retrieves the specified file from storage.
:param name: file name
:type name: str
:param mode: mode to open the file with
:type mode: str
:rtype: :class:`~django:django.core.files.File` |
def advth(step):
"""Theoretical advection.
This compute the theoretical profile of total advection as function of
radius.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array` and None: the theoretical ad... | Theoretical advection.
This compute the theoretical profile of total advection as function of
radius.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array` and None: the theoretical advection.
The sec... |
def current_vm(self):
"""current vm"""
try:
_, _, _, _, vm = self._callstack[-1]
return vm
except IndexError:
return None | current vm |
def process_instrs(queue, stack, body, context):
"""
Process instructions from the instruction queue.
"""
next_instr = queue.popleft
while queue:
newcontext = _process_instr(next_instr(), queue, stack, body, context)
if newcontext is not None:
context = newcontext | Process instructions from the instruction queue. |
def message_box(type, title, message, icon=None, buttons=QMessageBox.Ok, custom_buttons=None):
"""
Provides a fast GUI message box.
:param title: Current message title.
:type title: unicode
:param message: Message.
:type message: unicode
:param icon: Custom icon.
:type icon: QConstant
... | Provides a fast GUI message box.
:param title: Current message title.
:type title: unicode
:param message: Message.
:type message: unicode
:param icon: Custom icon.
:type icon: QConstant
:param buttons: Standard buttons.
:type buttons: QConstant
:param custom_buttons: Custom buttons... |
def get_palette(samples, options, return_mask=False, kmeans_iter=40):
'''Extract the palette for the set of sampled RGB values. The first
palette entry is always the background color; the rest are determined
from foreground pixels by running K-means clustering. Returns the
palette, as well as a mask corresponding ... | Extract the palette for the set of sampled RGB values. The first
palette entry is always the background color; the rest are determined
from foreground pixels by running K-means clustering. Returns the
palette, as well as a mask corresponding to the foreground pixels. |
def revoke(self):
"""Revoke the current Authorization."""
if self.access_token is None:
raise InvalidInvocation("no token available to revoke")
self._authenticator.revoke_token(self.access_token, "access_token")
self._clear_access_token() | Revoke the current Authorization. |
def __vCmdConnectCameras(self, args):
'''ToDo: Validate the argument as a valid port'''
if len(args) >= 1:
self.WirelessPort = args[0]
print ("Connecting to Cameras on %s" % self.WirelessPort)
self.__vRegisterCameras() | ToDo: Validate the argument as a valid port |
def handleEntity(self, ctxt):
"""Default handling of defined entities, when should we define
a new input stream ? When do we just handle that as a set
of chars ? OBSOLETE: to be removed at some point. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
libxm... | Default handling of defined entities, when should we define
a new input stream ? When do we just handle that as a set
of chars ? OBSOLETE: to be removed at some point. |
def glob_wildcards(pattern: str, files: Optional[List[str]] = None
) -> Dict[str, Union[List[Any], List[str]]]:
"""
Glob the values of the wildcards by matching the given pattern to the filesystem.
Returns a named tuple with a list of values for each wildcard.
"""
pattern = os.path... | Glob the values of the wildcards by matching the given pattern to the filesystem.
Returns a named tuple with a list of values for each wildcard. |
def to_xml(self, f=None):
"""Get this domain as an XML DOM Document
:param f: Optional File to dump directly to
:type f: File or Stream
:return: File object where the XML has been dumped to
:rtype: file
"""
if not f:
from tempfile import TemporaryFile... | Get this domain as an XML DOM Document
:param f: Optional File to dump directly to
:type f: File or Stream
:return: File object where the XML has been dumped to
:rtype: file |
def refresh(self):
"""Refresh widget"""
if self.isHidden():
if self.editor is not None:
self.clear_matches()
return
state = self.editor is not None
for widget in self.widgets:
widget.setEnabled(state)
if state:
... | Refresh widget |
def post_event_display_settings(self, id, **data):
"""
POST /events/:id/display_settings/
Updates the display settings for an event.
"""
return self.post("/events/{0}/display_settings/".format(id), data=data) | POST /events/:id/display_settings/
Updates the display settings for an event. |
def close(self):
" Close pipe fds. "
os.close(self._r)
os.close(self._w)
self._r = None
self._w = None | Close pipe fds. |
def _theorem6p3():
"""See Theorem 6.3 in paper.
Prunes (s,b) when (s,a) is explored, b (almost) simplicial in (s,a), and a (almost) simplicial in (s,b)
"""
pruning_set3 = set()
def _prune3(x, as_list, b):
for a in as_list:
key = (tuple(x), a, b) # (s,a,b) with (s,a) explored
... | See Theorem 6.3 in paper.
Prunes (s,b) when (s,a) is explored, b (almost) simplicial in (s,a), and a (almost) simplicial in (s,b) |
def get_event_teams_attendees(self, id, team_id, **data):
"""
GET /events/:id/teams/:team_id/attendees/
Returns :format:`attendees` for a single :format:`teams`.
"""
return self.get("/events/{0}/teams/{0}/attendees/".format(id,team_id), data=data) | GET /events/:id/teams/:team_id/attendees/
Returns :format:`attendees` for a single :format:`teams`. |
def add_secondary_linked_file(self, file_path, relpath=None, mimetype=None,
time_origin=None, assoc_with=None):
"""Add a secondary linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: M... | Add a secondary linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: Mimetype of the file, if ``None`` it tries to
guess it according to the file extension which currently only works
for wav, mpg, mpeg a... |
def get_proof(self, index):
"""
Returns the proof for a leaf at the given index as an array of merkle siblings in hex format
:param index:
:return:
"""
if not self.tree['is_ready']:
return None
current_row_index = len(self.tree['levels']) - 1
... | Returns the proof for a leaf at the given index as an array of merkle siblings in hex format
:param index:
:return: |
def _connect(self):
'''
Try to connect for the rest of time!
'''
while True:
if self._closing:
break
try:
kwargs = {}
if self.source_ip or self.source_port:
if tornado.version_info >= (4, 5):
... | Try to connect for the rest of time! |
def toplevel_packages():
""" Get package list, without sub-packages.
"""
packages = set(easy.options.setup.packages)
for pkg in list(packages):
packages -= set(p for p in packages if str(p).startswith(pkg + '.'))
return list(sorted(packages)) | Get package list, without sub-packages. |
def add_yaml_file_content_to_database(
self,
filepath,
deleteFile=False
):
"""*given a file to a yaml file, add yaml file content to database*
**Key Arguments:**
- ``filepath`` -- the path to the yaml file
- ``deleteFile`` -- delete the yaml file when... | *given a file to a yaml file, add yaml file content to database*
**Key Arguments:**
- ``filepath`` -- the path to the yaml file
- ``deleteFile`` -- delete the yaml file when its content has been added to the database. Default *False*
**Return:**
- None
**Us... |
def get_distribute_alterations_metadata(self):
"""Gets the metadata for the distribute alterations rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented fr... | Gets the metadata for the distribute alterations rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.* |
def create_server(cloud, **kwargs):
"""
Create a new instance
"""
if cloud == 'ec2':
_create_server_ec2(**kwargs)
elif cloud == 'rackspace':
_create_server_rackspace(**kwargs)
elif cloud == 'gce':
_create_server_gce(**kwargs)
else:
raise ValueError("Unknow... | Create a new instance |
def computeA(self, j, timeSeries):
""" Calculates A_j. Aj is the average value of x in the jth cycle of your data
:return: A_j
:rtype: numeric
"""
seasonLength = self.get_parameter("seasonLength")
A_j = 0
for i in range(seasonLength):
A_j += ti... | Calculates A_j. Aj is the average value of x in the jth cycle of your data
:return: A_j
:rtype: numeric |
def remove_inconsistent_edges(graph: BELGraph) -> None:
"""Remove all edges between node pairs with inconsistent edges.
This is the all-or-nothing approach. It would be better to do more careful investigation of the evidences during
curation.
"""
for u, v in get_inconsistent_edges(graph):
e... | Remove all edges between node pairs with inconsistent edges.
This is the all-or-nothing approach. It would be better to do more careful investigation of the evidences during
curation. |
def timeshift_isc(data, pairwise=False, summary_statistic='median',
n_shifts=1000, tolerate_nans=True, random_state=None):
"""Circular time-shift randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where respon... | Circular time-shift randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time series
are first circularly shifted by random intervals. If pairwise,
apply time-shift randomization to each subjects and compute pai... |
def get_capture_dimensions(capture):
"""Get the dimensions of a capture"""
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
return width, height | Get the dimensions of a capture |
def _ref_has_region_assembled_twice(nucmer_hits, ref_seq, threshold):
'''Returns true iff there is a part of the reference that is assembled
more than once (ie covered by >1 nucmer hit).
Needs a minimum proportin of the ref to be assembled more than once,
determined by threshold... | Returns true iff there is a part of the reference that is assembled
more than once (ie covered by >1 nucmer hit).
Needs a minimum proportin of the ref to be assembled more than once,
determined by threshold.
nucmer_hits = hits made by self._parse_nucmer_coords_file. |
def delete_fit(self, fit, specimen=None):
"""
removes fit from GUI results data
Parameters
----------
fit : fit to remove
specimen : specimen of fit to remove, if not provided and
set to None then the function will find the specimen itself
"""
if ... | removes fit from GUI results data
Parameters
----------
fit : fit to remove
specimen : specimen of fit to remove, if not provided and
set to None then the function will find the specimen itself |
def matchingFilePaths(targetfilename, directory, targetFileExtension=None,
selector=None):
"""Search for files in all subfolders of specified directory, return
filepaths of all matching instances.
:param targetfilename: filename to search for, only the string before the
last "... | Search for files in all subfolders of specified directory, return
filepaths of all matching instances.
:param targetfilename: filename to search for, only the string before the
last "." is used for filename matching. Ignored if a selector function
is specified.
:param directory: search dire... |
def addGraphic(self, layerName, geometry, symbol):
""" loads a geometry (ArcPy Geometry Object) into Graphic Layer"""
allowed_geomtypes = ['polygon', 'polyline', 'point', 'multipoint']
if not (geometry.type.lower() in allowed_geomtypes):
return False, layerName
geom = _unicod... | loads a geometry (ArcPy Geometry Object) into Graphic Layer |
def gmail_email(self, from_, to, msg):
"""
Send an email from your `gmail`_ account.
.. _gmail: https://mail.google.com/
msg can either be:
* A string, in which case:
* At the first newline (\\n) the string will be split into subjec... | Send an email from your `gmail`_ account.
.. _gmail: https://mail.google.com/
msg can either be:
* A string, in which case:
* At the first newline (\\n) the string will be split into subject and body
* If no newline is present, the enti... |
def get_triplet_tuple(a: BaseEntity, b: BaseEntity, c: BaseEntity) -> Tuple[str, str, str, str, str, str]:
"""Get the triple as a tuple of BEL/hashes."""
return a.as_bel(), a.sha512, b.as_bel(), b.sha512, c.as_bel(), c.sha512 | Get the triple as a tuple of BEL/hashes. |
def get_all_intervals(self):
"""Returns the true list of intervals including the empty intervals."""
ints = sorted(self.get_intervals(True))
if self.tier_type == 'IntervalTier':
if not ints:
ints.append((self.xmin, self.xmax, ''))
else:
if ... | Returns the true list of intervals including the empty intervals. |
def setEditorData(self, editor, index):
"""
Overriding method setEditorData
Model --> Editor
"""
value = self.get_value(index)
if isinstance(editor, QLineEdit):
if is_binary_string(value):
try:
value = to_text_strin... | Overriding method setEditorData
Model --> Editor |
def next_except_jump(self, start):
"""
Return the next jump that was generated by an except SomeException:
construct in a try...except...else clause or None if not found.
"""
if self.code[start] == self.opc.DUP_TOP:
except_match = self.first_instr(start, len(self.cod... | Return the next jump that was generated by an except SomeException:
construct in a try...except...else clause or None if not found. |
def run_spider(self, target_url, context_name=None, user_name=None):
"""Run spider against a URL."""
self.logger.debug('Spidering target {0}...'.format(target_url))
context_id, user_id = self._get_context_and_user_ids(context_name, user_name)
if user_id:
self.logger.debug('... | Run spider against a URL. |
def collect_cmd(self, args, ret):
"""Collect analytics info from a CLI command."""
from dvc.command.daemon import CmdDaemonAnalytics
assert isinstance(ret, int) or ret is None
if ret is not None:
self.info[self.PARAM_CMD_RETURN_CODE] = ret
if args is not None and h... | Collect analytics info from a CLI command. |
def apply_async(self, args=None, kwargs=None, **options):
""" Do not run background task if previous task is uncompleted """
if self.is_previous_task_processing(*args, **kwargs):
message = 'Background task %s was not scheduled, because its predecessor is not completed yet.' % self.name
... | Do not run background task if previous task is uncompleted |
def _password(self, password):
"""
Authenticates with the IRC server.
NOTE: Method will not raise an exception,
if the password is wrong. It will just fail..
Required arguments:
* password - Password to send.
"""
with self.lock:
self.send('PASS... | Authenticates with the IRC server.
NOTE: Method will not raise an exception,
if the password is wrong. It will just fail..
Required arguments:
* password - Password to send. |
def close(self):
"""
Close this SSHClient and its underlying `.Transport`.
.. warning::
Failure to do this may, in some situations, cause your Python
interpreter to hang at shutdown (often due to race conditions).
It's good practice to `close` your client obj... | Close this SSHClient and its underlying `.Transport`.
.. warning::
Failure to do this may, in some situations, cause your Python
interpreter to hang at shutdown (often due to race conditions).
It's good practice to `close` your client objects anytime you're
done ... |
def And(cls, *requirements):
"""
Short cut helper to construct a combinator that uses
:meth:`operator.and_` to reduce requirement results and stops
evaluating on the first False.
This is also exported at the module level as ``And``
"""
return cls(*requirements, o... | Short cut helper to construct a combinator that uses
:meth:`operator.and_` to reduce requirement results and stops
evaluating on the first False.
This is also exported at the module level as ``And`` |
def imap_connect(self):
"""
Connect to the IMAP mailbox.
"""
self.mailbox = imaplib.IMAP4_SSL(self.imap_string, self.port)
self.mailbox.login(self.uname, self.pwd)
self.mailbox.select() | Connect to the IMAP mailbox. |
def _support_diag_dump(self):
'''
Collect log info for debug
'''
# check insights config
cfg_block = []
pconn = InsightsConnection(self.config)
logger.info('Insights version: %s', get_nvr())
reg_check = registration_check(pconn)
cfg_block.append(... | Collect log info for debug |
def define_selector(by, value, el_class):
"""
:param by:
:param value:
:param el_class:
:rtype: tuple[type, str|tuple[str, str]]
:return:
"""
el = el_class
selector = by
if isinstance(value, six.string_types):
selector = (by, value)
elif value is not None:
el ... | :param by:
:param value:
:param el_class:
:rtype: tuple[type, str|tuple[str, str]]
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.