code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
async def start(self):
"""
Start discarding media.
"""
for track, task in self.__tracks.items():
if task is None:
self.__tracks[track] = asyncio.ensure_future(blackhole_consume(track)) | Start discarding media. |
def per_section(it, is_delimiter=lambda x: x.isspace()):
"""
From http://stackoverflow.com/a/25226944/610569
"""
ret = []
for line in it:
if is_delimiter(line):
if ret:
yield ret # OR ''.join(ret)
ret = []
else:
ret.append(lin... | From http://stackoverflow.com/a/25226944/610569 |
def abfGroupFiles(groups,folder):
"""
when given a dictionary where every key contains a list of IDs, replace
the keys with the list of files matching those IDs. This is how you get a
list of files belonging to each child for each parent.
"""
assert os.path.exists(folder)
files=os.listdir(fo... | when given a dictionary where every key contains a list of IDs, replace
the keys with the list of files matching those IDs. This is how you get a
list of files belonging to each child for each parent. |
def inc(self, name, value=1):
""" Increment value """
clone = self._clone()
clone._qsl = [(q, v) if q != name else (q, int(v) + value)
for (q, v) in self._qsl]
if name not in dict(clone._qsl).keys():
clone._qsl.append((name, value))
return clone | Increment value |
def start_fitting(self):
"""
Launches the fitting routine on another thread
"""
self.queue = queue.Queue()
self.peak_vals = []
self.fit_thread = QThread() #must be assigned as an instance variable, not local, as otherwise thread is garbage
... | Launches the fitting routine on another thread |
def set_transfer_spec(self):
''' run the function to set the transfer spec on error set associated exception '''
_ret = False
try:
self._args.transfer_spec_func(self._args)
_ret = True
except Exception as ex:
self.notify_exception(AsperaTransferSpecErr... | run the function to set the transfer spec on error set associated exception |
def save_script_file_for_state_and_source_path(state, state_path_full, as_copy=False):
"""Saves the script file for a state to the directory of the state.
The script name will be set to the SCRIPT_FILE constant.
:param state: The state of which the script file should be saved
:param str state_path_ful... | Saves the script file for a state to the directory of the state.
The script name will be set to the SCRIPT_FILE constant.
:param state: The state of which the script file should be saved
:param str state_path_full: The path to the file system storage location of the state
:param bool as_copy: Temporar... |
def quarantineWorker(self, *args, **kwargs):
"""
Quarantine a worker
Quarantine a worker
This method takes input: ``v1/quarantine-worker-request.json#``
This method gives output: ``v1/worker-response.json#``
This method is ``experimental``
"""
return ... | Quarantine a worker
Quarantine a worker
This method takes input: ``v1/quarantine-worker-request.json#``
This method gives output: ``v1/worker-response.json#``
This method is ``experimental`` |
def get(self, key, default=None, reraise=False):
"""
Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param defau... | Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param default: the value to return if the key does not exist in cache
:p... |
def onSave(self, grid):#, age_data_type='site'):
"""
Save grid data in the data object
"""
# deselect column, including remove 'EDIT ALL' label
if self.drop_down_menu:
self.drop_down_menu.clean_up()
# save all changes to er_magic data object
self.grid... | Save grid data in the data object |
def upload_path(instance, filename):
'''
Sanitize the user-provided file name, add timestamp for uniqness.
'''
filename = filename.replace(" ", "_")
filename = unicodedata.normalize('NFKD', filename).lower()
return os.path.join(str(timezone.now().date().isoformat()), filename) | Sanitize the user-provided file name, add timestamp for uniqness. |
def filter_dict(self, query, **kwargs):
''' Filter for :func:`~ommongo.fields.mapping.DictField`.
**Examples**: ``query.filter_dict({"User.Fullname": "Oji"})``
'''
for name, value in query.items():
field = name.split(".")[0]
try:
getattr(self.... | Filter for :func:`~ommongo.fields.mapping.DictField`.
**Examples**: ``query.filter_dict({"User.Fullname": "Oji"})`` |
def project_remove_folder(object_id, input_params={}, always_retry=False, **kwargs):
"""
Invokes the /project-xxxx/removeFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FremoveFolder
"""
return DXHTTPRequest... | Invokes the /project-xxxx/removeFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FremoveFolder |
def positionIf(pred, seq):
"""
>>> positionIf(lambda x: x > 3, range(10))
4
"""
for i,e in enumerate(seq):
if pred(e):
return i
return -1 | >>> positionIf(lambda x: x > 3, range(10))
4 |
def filter_by_domain(self, domain):
"""
Apply the given domain to a copy of this query
"""
query = self._copy()
query.domain = domain
return query | Apply the given domain to a copy of this query |
def vmach2cas(M, h):
""" Mach to CAS conversion """
tas = vmach2tas(M, h)
cas = vtas2cas(tas, h)
return cas | Mach to CAS conversion |
def _theorem6p4():
"""See Theorem 6.4 in paper.
Let E(x) denote the edges added when eliminating x. (edges_x below).
Prunes (s,b) when (s,a) is explored and E(a) is a subset of E(b).
For this theorem we only record E(a) rather than (s,E(a))
because we only need to check for pruning in the same s con... | See Theorem 6.4 in paper.
Let E(x) denote the edges added when eliminating x. (edges_x below).
Prunes (s,b) when (s,a) is explored and E(a) is a subset of E(b).
For this theorem we only record E(a) rather than (s,E(a))
because we only need to check for pruning in the same s context
(i.e the same lev... |
def hide_me(tb, g=globals()):
"""Hide stack traceback of given stack"""
base_tb = tb
try:
while tb and tb.tb_frame.f_globals is not g:
tb = tb.tb_next
while tb and tb.tb_frame.f_globals is g:
tb = tb.tb_next
except Exception as e:
logging.exception(e)
... | Hide stack traceback of given stack |
async def purgeRequests(self, *args, **kwargs):
"""
Open Purge Requests for a provisionerId/workerType pair
List of caches that need to be purged if they are from before
a certain time. This is safe to be used in automation from
workers.
This method gives output: ``v1/p... | Open Purge Requests for a provisionerId/workerType pair
List of caches that need to be purged if they are from before
a certain time. This is safe to be used in automation from
workers.
This method gives output: ``v1/purge-cache-request-list.json#``
This method is ``stable`` |
def write(self, vals):
"""
Overrides orm write method.
@param self: The object pointer
@param vals: dictionary of fields value.
Update Hotel Room Reservation line history"""
reservation_line_obj = self.env['hotel.room.reservation.line']
room_obj = self.env['hotel.... | Overrides orm write method.
@param self: The object pointer
@param vals: dictionary of fields value.
Update Hotel Room Reservation line history |
def get_policy_configurations(self, project, repository_id=None, ref_name=None, policy_type=None, top=None, continuation_token=None):
"""GetPolicyConfigurations.
[Preview API] Retrieve a list of policy configurations by a given set of scope/filtering criteria.
:param str project: Project ID or p... | GetPolicyConfigurations.
[Preview API] Retrieve a list of policy configurations by a given set of scope/filtering criteria.
:param str project: Project ID or project name
:param str repository_id: The repository id.
:param str ref_name: The fully-qualified Git ref name (e.g. refs/heads/m... |
def unicode_key(key):
"""
CONVERT PROPERTY VALUE TO QUOTED NAME OF SAME
"""
if not isinstance(key, (text_type, binary_type)):
from mo_logs import Log
Log.error("{{key|quote}} is not a valid key", key=key)
return quote(text_type(key)) | CONVERT PROPERTY VALUE TO QUOTED NAME OF SAME |
def process_python(self, path):
"""Process a python file."""
(pylint_stdout, pylint_stderr) = epylint.py_run(
' '.join([str(path)] + self.pylint_opts), return_std=True)
emap = {}
print(pylint_stderr.read())
for line in pylint_stdout:
sys.stderr.write(line)... | Process a python file. |
def scan(self, table, scan_filter=None,
attributes_to_get=None, request_limit=None, max_results=None,
count=False, exclusive_start_key=None, item_class=Item):
"""
Perform a scan of DynamoDB.
:type table: :class:`boto.dynamodb.table.Table`
:param table: The Tabl... | Perform a scan of DynamoDB.
:type table: :class:`boto.dynamodb.table.Table`
:param table: The Table object that is being scanned.
:type scan_filter: A list of tuples
:param scan_filter: A list of tuples where each tuple consists
of an attribute name, a comparison operator, ... |
def fillPelicanHole(site, username, password, tstat_name, start_time, end_time):
"""Fill a hole in a Pelican thermostat's data stream.
Arguments:
site -- The thermostat's Pelican site name
username -- The Pelican username for the site
password -- The Pelican password for the site
... | Fill a hole in a Pelican thermostat's data stream.
Arguments:
site -- The thermostat's Pelican site name
username -- The Pelican username for the site
password -- The Pelican password for the site
tstat_name -- The name of the thermostat, as identified by Pelican
start_time ... |
def ndarray_to_list_in_structure(item, squeeze=True):
""" Change ndarray in structure of lists and dicts into lists.
"""
tp = type(item)
if tp == np.ndarray:
if squeeze:
item = item.squeeze()
item = item.tolist()
elif tp == list:
for i in range(len(item)):
... | Change ndarray in structure of lists and dicts into lists. |
def discard(self, key):
"""
Remove an element. Do not raise an exception if absent.
The MutableSet mixin uses this to implement the .remove() method, which
*does* raise an error when asked to remove a non-existent item.
"""
if key in self:
i = self.map[key]
... | Remove an element. Do not raise an exception if absent.
The MutableSet mixin uses this to implement the .remove() method, which
*does* raise an error when asked to remove a non-existent item. |
def BFS_Tree(G, start):
"""
Return an oriented tree constructed from bfs starting at 'start'.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
pred = BFS(G, start)
T = digraph.DiGraph()
queue = Queue()
queue.put(start)
wh... | Return an oriented tree constructed from bfs starting at 'start'. |
def get_protocols(self, device):
"""Returns a list of available protocols for the specified device."""
return self._reg.device_builder(device, self._rv).protocols | Returns a list of available protocols for the specified device. |
def by_player(self):
""":class:`bool`: Whether the kill involves other characters."""
return any([k.player and self.name != k.name for k in self.killers]) | :class:`bool`: Whether the kill involves other characters. |
def download_metadata_cli(master_token, output_csv, verbose=False,
debug=False):
"""
Command line function for downloading metadata.
For more information visit
:func:`download_metadata<ohapi.command_line.download_metadata>`.
"""
return download_metadata(master_token, ou... | Command line function for downloading metadata.
For more information visit
:func:`download_metadata<ohapi.command_line.download_metadata>`. |
def guess_service_info_from_path(spec_path):
"""Guess Python Autorest options based on the spec path.
Expected path:
specification/compute/resource-manager/readme.md
"""
spec_path = spec_path.lower()
spec_path = spec_path[spec_path.index("specification"):] # Might raise and it's ok
split_sp... | Guess Python Autorest options based on the spec path.
Expected path:
specification/compute/resource-manager/readme.md |
def get_bounds(tune_params):
""" create a bounds array from the tunable parameters """
bounds = []
for values in tune_params.values():
sorted_values = numpy.sort(values)
bounds.append((sorted_values[0], sorted_values[-1]))
return bounds | create a bounds array from the tunable parameters |
def itemat(iterable, index):
"""Try to get the item at index position in iterable after iterate on
iterable items.
:param iterable: object which provides the method __getitem__ or __iter__.
:param int index: item position to get.
"""
result = None
handleindex = True
if isinstance(ite... | Try to get the item at index position in iterable after iterate on
iterable items.
:param iterable: object which provides the method __getitem__ or __iter__.
:param int index: item position to get. |
def get_mode(path, follow_symlinks=True):
'''
Return the mode of a file
path
file or directory of which to get the mode
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
.. versionchange... | Return the mode of a file
path
file or directory of which to get the mode
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
.. versionchanged:: 2014.1.0
``follow_symlinks`` option added |
def get_node_type(self, node, parent=None):
"""If node is a document, the type is page.
If node is a binder with no parent, the type is book.
If node is a translucent binder, the type is either chapters (only
contain pages) or unit (contains at least one translucent binder).
"""
... | If node is a document, the type is page.
If node is a binder with no parent, the type is book.
If node is a translucent binder, the type is either chapters (only
contain pages) or unit (contains at least one translucent binder). |
def _post_filter(search, urlkwargs, definitions):
"""Ingest post filter in query."""
filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions)
for filter_ in filters:
search = search.post_filter(filter_)
return (search, urlkwargs) | Ingest post filter in query. |
def as_dict(self):
""" Return the URI object as a dictionary"""
d = {k:v for (k,v) in self.__dict__.items()}
return d | Return the URI object as a dictionary |
def get_random_mass(numPoints, massRangeParams):
"""
This function will generate a large set of points within the chosen mass
and spin space, and with the desired minimum remnant disk mass (this applies
to NS-BH systems only). It will also return the corresponding PN spin
coefficients for ease of us... | This function will generate a large set of points within the chosen mass
and spin space, and with the desired minimum remnant disk mass (this applies
to NS-BH systems only). It will also return the corresponding PN spin
coefficients for ease of use later (though these may be removed at some
future point... |
def log_pdf(self, y, mu, weights=None):
"""
computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights ... | computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights : array-like shape (n,) or None, default: None
s... |
def is_finalized(self):
"""Return True if the bundle is installed."""
return self.state == self.STATES.FINALIZED or self.state == self.STATES.INSTALLED | Return True if the bundle is installed. |
def stream_command_dicts(commands, parallel=False):
"""
Takes a list of dictionaries with keys corresponding to ``stream_command``
arguments, and runs all concurrently.
:param commands: A list of dictionaries, the keys of which should line up
with the arguments to ``stream_command`... | Takes a list of dictionaries with keys corresponding to ``stream_command``
arguments, and runs all concurrently.
:param commands: A list of dictionaries, the keys of which should line up
with the arguments to ``stream_command`` function.
:type commands: ``list`` of ``dict``
:param ... |
def _machine_actions(self, action):
"""
Actions for the machine (e.g. stop, start etc)
:param action: Can be "reboot", "start", "stop", "destroy"
:returns: An updated list of the added machines
"""
payload = {
'action': action
}
data = json.du... | Actions for the machine (e.g. stop, start etc)
:param action: Can be "reboot", "start", "stop", "destroy"
:returns: An updated list of the added machines |
def set_options(self, **kwargs):
"""
Set options.
@param kwargs: keyword arguments.
@see: L{Options}
"""
p = Unskin(self.options)
p.update(kwargs) | Set options.
@param kwargs: keyword arguments.
@see: L{Options} |
def set_public_transport_route(self, public_transport_route):
"""
Set the public transport route.
:param public_transport_route: TransportRoute
"""
self._query_params += str(QueryParam.ROUTE_ID) + str(public_transport_route) | Set the public transport route.
:param public_transport_route: TransportRoute |
def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request object
:return: namespace, config
"""
app = None
if getattr(request, 'current_page', None) and request.current_page.application_urls:
app = apph... | Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request object
:return: namespace, config |
def process_increase_expression_amount(self):
"""Looks for Positive_Regulation events with a specified Cause
and a Gene_Expression theme, and processes them into INDRA statements.
"""
statements = []
pwcs = self.find_event_parent_with_event_child(
'Positive_regul... | Looks for Positive_Regulation events with a specified Cause
and a Gene_Expression theme, and processes them into INDRA statements. |
def id_pools_vsn_ranges(self):
"""
Gets the IdPoolsRanges API Client for VSN Ranges.
Returns:
IdPoolsRanges:
"""
if not self.__id_pools_vsn_ranges:
self.__id_pools_vsn_ranges = IdPoolsRanges('vsn', self.__connection)
return self.__id_pools_vsn_ran... | Gets the IdPoolsRanges API Client for VSN Ranges.
Returns:
IdPoolsRanges: |
def plot_pdf(self, names=None, Nbest=5, lw=2):
"""Plots Probability density functions of the distributions
:param str,list names: names can be a single distribution name, or a list
of distribution names, or kept as None, in which case, the first Nbest
distribution will be taken ... | Plots Probability density functions of the distributions
:param str,list names: names can be a single distribution name, or a list
of distribution names, or kept as None, in which case, the first Nbest
distribution will be taken (default to best 5) |
def update(self, dtrain, iteration, fobj=None):
"""
Update for one iteration, with objective function calculated internally.
Parameters
----------
dtrain : DMatrix
Training data.
iteration : int
Current iteration number.
fobj : function
... | Update for one iteration, with objective function calculated internally.
Parameters
----------
dtrain : DMatrix
Training data.
iteration : int
Current iteration number.
fobj : function
Customized objective function. |
def get_gene_count_tab(infile,
bc_getter=None):
''' Yields the counts per umi for each gene
bc_getter: method to get umi (plus optionally, cell barcode) from
read, e.g get_umi_read_id or get_umi_tag
TODO: ADD FOLLOWING OPTION
skip_regex: skip genes matching this regex. Us... | Yields the counts per umi for each gene
bc_getter: method to get umi (plus optionally, cell barcode) from
read, e.g get_umi_read_id or get_umi_tag
TODO: ADD FOLLOWING OPTION
skip_regex: skip genes matching this regex. Useful to ignore
unassigned reads (as per get_bundles class above) |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the UsernamePasswordCredential struct to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usua... | Write the data encoding the UsernamePasswordCredential struct to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enum... |
def _stage_input_files(self, file_mapping, dry_run=True):
"""Stage the input files to the scratch area and adjust the arguments accordingly"""
# print ("Staging input ", file_mapping)
if self._file_stage is None:
return
self._file_stage.copy_to_scratch(file_mapping, dry_run) | Stage the input files to the scratch area and adjust the arguments accordingly |
def geometricmean(inlist):
"""
Calculates the geometric mean of the values in the passed list.
That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list.
Usage: lgeometricmean(inlist)
"""
mult = 1.0
one_over_n = 1.0 / len(inlist)
for item in inlist:
mult = mult * pow(item, one_over_n)... | Calculates the geometric mean of the values in the passed list.
That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list.
Usage: lgeometricmean(inlist) |
def validate_id(request):
"""Validate request id."""
if 'id' in request:
correct_id = isinstance(
request['id'],
(string_types, int, None),
)
error = 'Incorrect identifier'
assert correct_id, error | Validate request id. |
def tagExplicitly(self, superTag):
"""Return explicitly tagged *TagSet*
Create a new *TagSet* representing callee *TagSet* explicitly tagged
with passed tag(s). With explicit tagging mode, new tags are appended
to existing tag(s).
Parameters
----------
superTag:... | Return explicitly tagged *TagSet*
Create a new *TagSet* representing callee *TagSet* explicitly tagged
with passed tag(s). With explicit tagging mode, new tags are appended
to existing tag(s).
Parameters
----------
superTag: :class:`~pyasn1.type.tag.Tag`
*Ta... |
def open_las(source, closefd=True):
""" Opens and reads the header of the las content in the source
>>> with open_las('pylastests/simple.las') as f:
... print(f.header.point_format_id)
3
>>> f = open('pylastests/simple.las', mode='rb')
>>> with open_las(f, closefd=Fals... | Opens and reads the header of the las content in the source
>>> with open_las('pylastests/simple.las') as f:
... print(f.header.point_format_id)
3
>>> f = open('pylastests/simple.las', mode='rb')
>>> with open_las(f, closefd=False) as flas:
... print(flas.heade... |
def SingleModeCombine(pupils,modeDiameter=None):
"""
Return the instantaneous coherent fluxes and photometric fluxes for a
multiway single-mode fibre combiner
"""
if modeDiameter is None:
modeDiameter=0.9*pupils.shape[-1]
amplitudes=FibreCouple(pupils,modeDiameter)
cc=np.conj(amplitu... | Return the instantaneous coherent fluxes and photometric fluxes for a
multiway single-mode fibre combiner |
def p_paramlist(self, p):
'paramlist : DELAY LPAREN params RPAREN'
p[0] = Paramlist(params=p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | paramlist : DELAY LPAREN params RPAREN |
def get_value_of_splits_for_account(self, account_id: str) -> Decimal:
""" Returns the sum of values for all splits for the given account """
splits = self.get_split_for_account(account_id)
result = Decimal(0)
for split in splits:
result += split.value
return result | Returns the sum of values for all splits for the given account |
def viewbox_mouse_event(self, event):
"""
The viewbox received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event.
"""
if event.handled or not self.interactive:
return
Pe... | The viewbox received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event. |
def derelativise_url(url):
'''
Normalizes URLs, gets rid of .. and .
'''
parsed = six.moves.urllib.parse.urlparse(url)
newpath=[]
for chunk in parsed.path[1:].split('/'):
if chunk == '.':
continue
elif chunk == '..':
# parent dir.
newpath=newpa... | Normalizes URLs, gets rid of .. and . |
def read_actions():
"""Yields actions for pressed keys."""
while True:
key = get_key()
# Handle arrows, j/k (qwerty), and n/e (colemak)
if key in (const.KEY_UP, const.KEY_CTRL_N, 'k', 'e'):
yield const.ACTION_PREVIOUS
elif key in (const.KEY_DOWN, const.KEY_CTRL_P, 'j... | Yields actions for pressed keys. |
def get_branches(self, project=None, include_parent=None, include_children=None, include_deleted=None, include_links=None):
"""GetBranches.
Get a collection of branch roots -- first-level children, branches with no parents.
:param str project: Project ID or project name
:param bool inclu... | GetBranches.
Get a collection of branch roots -- first-level children, branches with no parents.
:param str project: Project ID or project name
:param bool include_parent: Return the parent branch, if there is one. Default: False
:param bool include_children: Return the child branches fo... |
def get_last_block(working_dir):
"""
Get the last block processed
Return the integer on success
Return None on error
"""
# make this usable even if we haven't explicitly configured virtualchain
impl = sys.modules[__name__]
return BlockstackDB.get_lastblock(impl, working_dir) | Get the last block processed
Return the integer on success
Return None on error |
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
bucket,
key=None,
keyid=None,
verify_ssl=True,
location=None,
multiple_env=False,
environment='base',
prefix='',
... | Execute a command and read the output as YAML |
def map(self, mapper):
"""
Map categories using input correspondence (dict, Series, or function).
Parameters
----------
mapper : dict, Series, callable
The correspondence from old values to new.
Returns
-------
SparseArray
The out... | Map categories using input correspondence (dict, Series, or function).
Parameters
----------
mapper : dict, Series, callable
The correspondence from old values to new.
Returns
-------
SparseArray
The output array will have the same density as the... |
def listDF(option='mostactive', token='', version=''):
'''Returns an array of quotes for the top 10 symbols in a specified list.
https://iexcloud.io/docs/api/#list
Updated intraday
Args:
option (string); Option to query
token (string); Access token
version (string); API versio... | Returns an array of quotes for the top 10 symbols in a specified list.
https://iexcloud.io/docs/api/#list
Updated intraday
Args:
option (string); Option to query
token (string); Access token
version (string); API version
Returns:
DataFrame: result |
def build_effects_to_residuals_matrix(num_seasons, dtype):
"""Build change-of-basis matrices for constrained seasonal effects.
This method builds the matrix that transforms seasonal effects into
effect residuals (differences from the mean effect), and additionally
projects these residuals onto the subspace whe... | Build change-of-basis matrices for constrained seasonal effects.
This method builds the matrix that transforms seasonal effects into
effect residuals (differences from the mean effect), and additionally
projects these residuals onto the subspace where the mean effect is zero.
See `ConstrainedSeasonalStateSpac... |
def remove_filtered_edges(graph, edge_predicates=None):
"""Remove edges passing the given edge predicates.
:param pybel.BELGraph graph: A BEL graph
:param edge_predicates: A predicate or list of predicates
:type edge_predicates: None or ((pybel.BELGraph, tuple, tuple, int) -> bool) or iter[(pybel.BELGr... | Remove edges passing the given edge predicates.
:param pybel.BELGraph graph: A BEL graph
:param edge_predicates: A predicate or list of predicates
:type edge_predicates: None or ((pybel.BELGraph, tuple, tuple, int) -> bool) or iter[(pybel.BELGraph, tuple, tuple, int) -> bool]]
:return: |
def _check_timeouts(self):
"""Check if any operations in progress need to be timed out
Adds the corresponding finish action that fails the request due to a
timeout.
"""
for conn_id, data in self._connections.items():
if 'timeout' in data and data['timeout'].expired:... | Check if any operations in progress need to be timed out
Adds the corresponding finish action that fails the request due to a
timeout. |
def EnumerateClasses(self, namespace=None, ClassName=None,
DeepInheritance=None, LocalOnly=None,
IncludeQualifiers=None, IncludeClassOrigin=None,
**extra):
# pylint: disable=invalid-name,line-too-long
"""
Enumerate the su... | Enumerate the subclasses of a class, or the top-level classes in a
namespace.
This method performs the EnumerateClasses operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method retur... |
def make_timing_logger(logger, precision=3, level=logging.DEBUG):
""" Return a timing logger.
Usage::
>>> logger = logging.getLogger('foobar')
>>> log_time = make_timing_logger(
... logger, level=logging.INFO, precision=2)
>>>
>>> with log_time("hello %s", "world"):... | Return a timing logger.
Usage::
>>> logger = logging.getLogger('foobar')
>>> log_time = make_timing_logger(
... logger, level=logging.INFO, precision=2)
>>>
>>> with log_time("hello %s", "world"):
... time.sleep(1)
INFO:foobar:hello world in 1.00s |
def p_scope(self, p):
'scope : identifier DOT'
scope = () if p[1].scope is None else p[1].scope.labellist
p[0] = IdentifierScope(
scope + (IdentifierScopeLabel(p[1].name, lineno=p.lineno(1)),), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | scope : identifier DOT |
def _unlock_temporarily(self):
"""
Allow tokens to modify the world for the duration of a with-block.
It's important that tokens only modify the world at appropriate times,
otherwise the changes they make may not be communicated across the
network to other clients. To help ca... | Allow tokens to modify the world for the duration of a with-block.
It's important that tokens only modify the world at appropriate times,
otherwise the changes they make may not be communicated across the
network to other clients. To help catch and prevent these kinds of
errors, the... |
def _catch_nonjson_streamresponse(rawresponse):
"""
Validate a streamed response is JSON. Return a Python dictionary either way.
**Parameters:**
- **rawresponse:** Streamed Response from Requests.
**Returns:** Dictionary
"""
# attempt to load response for re... | Validate a streamed response is JSON. Return a Python dictionary either way.
**Parameters:**
- **rawresponse:** Streamed Response from Requests.
**Returns:** Dictionary |
def rename(self, from_name, to_name):
"""Renames an existing database."""
log.info('renaming database from %s to %s' % (from_name, to_name))
self._run_stmt('alter database %s rename to %s' % (from_name, to_name)) | Renames an existing database. |
def _edit_name(name, code, add_code=None, delete_end=False):
"""
Helping function for creating file names in .SAFE format
:param name: initial string
:type name: str
:param code:
:type code: str
:param add_code:
:type add_code: str or None
:param delete_end:
:type delete_end: bo... | Helping function for creating file names in .SAFE format
:param name: initial string
:type name: str
:param code:
:type code: str
:param add_code:
:type add_code: str or None
:param delete_end:
:type delete_end: bool
:return: edited string
:rtype: str |
def filter(self, all_records=False, **filters):
"""
Applies given query filters. If wanted result is more than specified size,
exception is raised about using all() method instead of filter.
Args:
all_records (bool):
**filters: Query filters as keyword arguments.... | Applies given query filters. If wanted result is more than specified size,
exception is raised about using all() method instead of filter.
Args:
all_records (bool):
**filters: Query filters as keyword arguments.
Returns:
Self. Queryset object.
Examp... |
def create_certificate_id(vault, name, version=None):
"""
:param vault: The vault uri.
:type vault: str
:param name: The certificate name.
:type name: str
:param version: The certificate version.
:type version: str
:rtype: KeyVaultId
"""
re... | :param vault: The vault uri.
:type vault: str
:param name: The certificate name.
:type name: str
:param version: The certificate version.
:type version: str
:rtype: KeyVaultId |
def get_qseq_dir(fc_dir):
"""Retrieve the qseq directory within Solexa flowcell output.
"""
machine_bc = os.path.join(fc_dir, "Data", "Intensities", "BaseCalls")
if os.path.exists(machine_bc):
return machine_bc
# otherwise assume we are in the qseq directory
# XXX What other cases can we... | Retrieve the qseq directory within Solexa flowcell output. |
def spectrogram_from_file(filename, step=10, window=20, max_freq=None,
eps=1e-14, overwrite=False, save_feature_as_csvfile=False):
""" Calculate the log of linear spectrogram from FFT energy
Params:
filename (str): Path to the audio file
step (int): Step size in millise... | Calculate the log of linear spectrogram from FFT energy
Params:
filename (str): Path to the audio file
step (int): Step size in milliseconds between windows
window (int): FFT window size in milliseconds
max_freq (int): Only FFT bins corresponding to frequencies between
[0... |
def parse_repeating_time_interval_to_str(date_str):
"""Devuelve descripción humana de un intervalo de repetición.
TODO: Por ahora sólo interpreta una lista fija de intervalos. Debería poder
parsear cualquier caso.
"""
with open(os.path.join(ABSOLUTE_SCHEMA_DIR,
"accrualP... | Devuelve descripción humana de un intervalo de repetición.
TODO: Por ahora sólo interpreta una lista fija de intervalos. Debería poder
parsear cualquier caso. |
def get_instance(self):
"""Get the Streams instance that owns this view.
Returns:
Instance: Streams instance owning this view.
"""
return Instance(self.rest_client.make_request(self.instance), self.rest_client) | Get the Streams instance that owns this view.
Returns:
Instance: Streams instance owning this view. |
def ldap_server_definitions(self):
"""
:class:`~zhmcclient.LdapServerDefinitionManager`: Access to the
:term:`LDAP Server Definitions <LDAP Server Definition>` in this
Console.
"""
# We do here some lazy loading.
if not self._ldap_server_definitions:
s... | :class:`~zhmcclient.LdapServerDefinitionManager`: Access to the
:term:`LDAP Server Definitions <LDAP Server Definition>` in this
Console. |
def forms(self, req, tag):
"""
Make and return some forms, using L{self.parameter.getInitialLiveForms}.
@return: some subforms.
@rtype: C{list} of L{LiveForm}
"""
liveForms = self.parameter.getInitialLiveForms()
for liveForm in liveForms:
liveForm.set... | Make and return some forms, using L{self.parameter.getInitialLiveForms}.
@return: some subforms.
@rtype: C{list} of L{LiveForm} |
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None, # noqa: E501
parse_results=False):
"""Send packets at layer 2 using tcpreplay for performance
pps: packets per second
mpbs: MBits per second
realtime: use packet's timestamp, bend... | Send packets at layer 2 using tcpreplay for performance
pps: packets per second
mpbs: MBits per second
realtime: use packet's timestamp, bending time with real-time value
loop: number of times to process the packet list
file_cache: cache packets in RAM instead of reading from disk at each iteration... |
def train(self, training_set, iterations=500):
"""Trains itself using the sequence data."""
if len(training_set) > 2:
self.__X = np.matrix([example[0] for example in training_set])
if self.__num_labels == 1:
self.__y = np.matrix([example[1] for example in training... | Trains itself using the sequence data. |
def add_source(source, key=None):
"""Add a package source to this system.
@param source: a URL with a rpm package
@param key: A key to be added to the system's keyring and used
to verify the signatures on packages. Ideally, this should be an
ASCII format GPG public key including the block headers.... | Add a package source to this system.
@param source: a URL with a rpm package
@param key: A key to be added to the system's keyring and used
to verify the signatures on packages. Ideally, this should be an
ASCII format GPG public key including the block headers. A GPG key
id may also be used, but b... |
def p_scalar__folded(self, p):
"""
scalar : B_FOLD_START scalar_group B_FOLD_END
"""
scalar_group = ''.join(p[2])
folded_scalar = fold(dedent(scalar_group)).rstrip()
p[0] = ScalarDispatch('%s\n' % folded_scalar, cast='str') | scalar : B_FOLD_START scalar_group B_FOLD_END |
def _from_float(cls, xmin, xmax, ymin, ymax):
"""
Return the smallest bounding box that fully contains a given
rectangle defined by float coordinate values.
Following the pixel index convention, an integer index
corresponds to the center of a pixel and the pixel edges span
... | Return the smallest bounding box that fully contains a given
rectangle defined by float coordinate values.
Following the pixel index convention, an integer index
corresponds to the center of a pixel and the pixel edges span
from (index - 0.5) to (index + 0.5). For example, the pixel
... |
def find_referenced_subfiles(self, directory):
"""
Return list of files below specified `directory` in job inputs. Could
use more sophisticated logic (match quotes to handle spaces, handle
subdirectories, etc...).
**Parameters**
directory : str
Full path to ... | Return list of files below specified `directory` in job inputs. Could
use more sophisticated logic (match quotes to handle spaces, handle
subdirectories, etc...).
**Parameters**
directory : str
Full path to directory to search. |
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(
OID=self.oid,
Active=bool_to_true_false(self.active),
BypassDuringMigration=bool_to_true_false(self.bypass_during_migration),
NeedsRetesting=bool_to_true_false(self.needs_rete... | Build XML by appending to builder |
def federation(self):
"""returns the class that controls federation"""
url = self._url + "/federation"
return _Federation(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._p... | returns the class that controls federation |
def get_submission_ids(self, tournament=1):
"""Get dict with username->submission_id mapping.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
dict: username->submission_id mapping, string->string
Example:
>>> NumerAPI... | Get dict with username->submission_id mapping.
Args:
tournament (int): ID of the tournament (optional, defaults to 1)
Returns:
dict: username->submission_id mapping, string->string
Example:
>>> NumerAPI().get_submission_ids()
{'1337ai': '93c4685... |
def inv(self):
"""The inverse transformation"""
result = Complete(self.r.transpose(), np.dot(self.r.transpose(), -self.t))
result._cache_inv = self
return result | The inverse transformation |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
FakeFileEntry: a file entry or None if not available.
"""
path_spec = fake_path_spec.FakePathSpec(location=self.LOCATION_ROOT)
return self.GetFileEntryByPathSpec(path_spec) | Retrieves the root file entry.
Returns:
FakeFileEntry: a file entry or None if not available. |
def update_index(self, project_name, logstore_name, index_detail):
""" update index for a logstore
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_na... | update index for a logstore
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type index_detail: IndexConfig
:param... |
def run_bang(alt_args=None):
"""
Runs bang with optional list of strings as command line options.
If ``alt_args`` is not specified, defaults to parsing ``sys.argv`` for
command line options.
"""
parser = get_parser()
args = parser.parse_args(alt_args)
source = args.config_specs or get_... | Runs bang with optional list of strings as command line options.
If ``alt_args`` is not specified, defaults to parsing ``sys.argv`` for
command line options. |
def OnTableChanged(self, event):
"""Table changed event handler"""
if hasattr(event, 'table'):
self.SetValue(event.table)
wx.TextCtrl.SetInsertionPoint(self, self.cursor_pos)
event.Skip() | Table changed event handler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.