code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def has_table(self, table):
"""
Determine if the given table exists.
:param table: The table
:type table: str
:rtype: bool
"""
sql = self._grammar.compile_table_exists()
table = self._connection.get_table_prefix() + table
return len(self._conne... | Determine if the given table exists.
:param table: The table
:type table: str
:rtype: bool |
def stop(self, check=True):
"""return a dictionary with the termination status.
With ``check==False``, the termination conditions are not checked
and the status might not reflect the current situation.
"""
if (check and self.countiter > 0 and self.opts['termination_callback'] an... | return a dictionary with the termination status.
With ``check==False``, the termination conditions are not checked
and the status might not reflect the current situation. |
def _getEventsByWeek(self, request, year, month):
"""Return my child events for the given month grouped by week."""
return getAllEventsByWeek(request, year, month, home=self) | Return my child events for the given month grouped by week. |
def identity(requestContext, name, step=60):
"""
Identity function:
Returns datapoints where the value equals the timestamp of the datapoint.
Useful when you have another series where the value is a timestamp, and
you want to compare it to the time of the datapoint, to render an age
Example::
... | Identity function:
Returns datapoints where the value equals the timestamp of the datapoint.
Useful when you have another series where the value is a timestamp, and
you want to compare it to the time of the datapoint, to render an age
Example::
&target=identity("The.time.series")
This wou... |
def is_partly_within_image(self, image):
"""
Estimate whether the bounding box is at least partially inside the image area.
Parameters
----------
image : (H,W,...) ndarray or tuple of int
Image dimensions to use.
If an ndarray, its shape will be used.
... | Estimate whether the bounding box is at least partially inside the image area.
Parameters
----------
image : (H,W,...) ndarray or tuple of int
Image dimensions to use.
If an ndarray, its shape will be used.
If a tuple, it is assumed to represent the image sha... |
def get_rendered_transform_path(self):
"""
Generates a rendered transform path
that is calculated from all parents.
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not None:
path = "{0}/{1}".format(parent.transform... | Generates a rendered transform path
that is calculated from all parents.
:return: |
def _delete_collection(self, **kwargs):
"""wrapped with delete_collection, override that in a sublcass to customize """
error_message = "The request must include \"requests_params\": {\"params\": \"options=<glob pattern>\"} as kwarg"
try:
if kwargs['requests_params']['params'].split(... | wrapped with delete_collection, override that in a sublcass to customize |
def get_key():
"""Get a key from the keyboard as a string
A 'key' will be a single char, or the name of an extended key
"""
character_name = chr
codes = _get_keycodes()
if len(codes) == 1:
code = codes[0]
if code >= 32:
return character_name(code)
return cont... | Get a key from the keyboard as a string
A 'key' will be a single char, or the name of an extended key |
def remote_daemon(conf_file):
"""
Run the external control daemon.
:param conf_file: Name of the configuration file.
"""
eventlet.monkey_patch()
conf = config.Config(conf_file=conf_file)
daemon = remote.RemoteControlDaemon(None, conf)
daemon.serve() | Run the external control daemon.
:param conf_file: Name of the configuration file. |
def add_actions(self, actions_list, scheduler_instance_id):
"""Add a list of actions to the satellite queues
:param actions_list: Actions list to add
:type actions_list: list
:param scheduler_instance_id: sheduler link to assign the actions to
:type scheduler_instance_id: Schedu... | Add a list of actions to the satellite queues
:param actions_list: Actions list to add
:type actions_list: list
:param scheduler_instance_id: sheduler link to assign the actions to
:type scheduler_instance_id: SchedulerLink
:return: None |
def fetch_as_element(self, **kw):
"""
Fetch the blacklist and return as an instance of Element.
:return: generator returning element instances
:rtype: BlacklistEntry
"""
clone = self.copy()
# Replace all filters with a combined filter
bldata = Tex... | Fetch the blacklist and return as an instance of Element.
:return: generator returning element instances
:rtype: BlacklistEntry |
def fastaRead(fileHandleOrFile):
"""iteratively yields a sequence for each '>' it encounters, ignores '#' lines
"""
fileHandle = _getFileHandle(fileHandleOrFile)
line = fileHandle.readline()
chars_to_remove = "\n "
valid_chars = {x for x in string.ascii_letters + "-"}
while line != '':
... | iteratively yields a sequence for each '>' it encounters, ignores '#' lines |
def _GenerateSection(self, problem_type):
"""Generate a listing of the given type of problems.
Args:
problem_type: The type of problem. This is one of the problem type
constants from transitfeed.
Returns:
The generated HTML as a string.
"""
if problem_type == transi... | Generate a listing of the given type of problems.
Args:
problem_type: The type of problem. This is one of the problem type
constants from transitfeed.
Returns:
The generated HTML as a string. |
def cleanup_datastore(self):
"""Cleans up datastore and deletes all information about current round."""
print_header('CLEANING UP ENTIRE DATASTORE')
kinds_to_delete = [u'Submission', u'SubmissionType',
u'DatasetImage', u'DatasetBatch',
u'AdversarialImage', u'Adv... | Cleans up datastore and deletes all information about current round. |
def trunc_str(s: str) -> str:
"""Truncate strings to maximum length."""
if len(s) > max_str_size:
i = max(0, (max_str_size - 3) // 2)
j = max(0, max_str_size - 3 - i)
s = s[:i] + "..." + s[-j:]
return s | Truncate strings to maximum length. |
def check_pre_requirements(pre_requirements):
"""Check all necessary system requirements to exist.
:param pre_requirements:
Sequence of pre-requirements to check by running
``where <pre_requirement>`` on Windows and ``which ...`` elsewhere.
"""
pre_requirements = set(pre_requirements or... | Check all necessary system requirements to exist.
:param pre_requirements:
Sequence of pre-requirements to check by running
``where <pre_requirement>`` on Windows and ``which ...`` elsewhere. |
def check_auth(args, role=None):
"""Check the user authentication."""
users = boto3.resource("dynamodb").Table(os.environ['people'])
if not (args.get('email', None) and args.get('api_key', None)):
mesg = "Invalid request: `email` and `api_key` are required"
return {'success': False, 'message... | Check the user authentication. |
def import_agent(self,
parent,
agent_uri=None,
agent_content=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
... | Imports the specified agent from a ZIP file.
Uploads new intents and entity types without deleting the existing ones.
Intents and entity types with the same name are replaced with the new
versions from ImportAgentRequest.
Operation <response: ``google.protobuf.Empty``,
metadata... |
def send_with_data_passthrough(self, event):
"""Identical to :meth:`send`, except that in situations where
:meth:`send` returns a single :term:`bytes-like object`, this instead
returns a list of them -- and when sending a :class:`Data` event, this
list is guaranteed to contain the exact ... | Identical to :meth:`send`, except that in situations where
:meth:`send` returns a single :term:`bytes-like object`, this instead
returns a list of them -- and when sending a :class:`Data` event, this
list is guaranteed to contain the exact object you passed in as
:attr:`Data.data`. See :... |
def sep(s):
"""Find the path separator used in this string, or os.sep if none."""
sep_match = re.search(r"[\\/]", s)
if sep_match:
the_sep = sep_match.group(0)
else:
the_sep = os.sep
return the_sep | Find the path separator used in this string, or os.sep if none. |
def env_timestamp(name, required=False, default=empty):
"""Pulls an environment variable out of the environment and parses it to a
``datetime.datetime`` object. The environment variable is expected to be a
timestamp in the form of a float.
If the name is not present in the environment and no default is... | Pulls an environment variable out of the environment and parses it to a
``datetime.datetime`` object. The environment variable is expected to be a
timestamp in the form of a float.
If the name is not present in the environment and no default is specified
then a ``ValueError`` will be raised.
:para... |
def _normalize_dates(self, context):
'''
Build a timeline from given (or not) start and end dates
'''
if 'start' in context:
if isinstance(context['start'], dt.date):
context['start'] = dt.date.strftime(
context['start'], format='%Y-%m-%d')... | Build a timeline from given (or not) start and end dates |
def betting_market_create(
self, payout_condition, description, group_id="0.0.0", account=None, **kwargs
):
""" Create an event group. This needs to be **proposed**.
:param list payout_condition: Internationalized names, e.g.
``[['de', 'Foo'], ['en', 'bar']]``
... | Create an event group. This needs to be **proposed**.
:param list payout_condition: Internationalized names, e.g.
``[['de', 'Foo'], ['en', 'bar']]``
:param list description: Internationalized descriptions, e.g.
``[['de', 'Foo'], ['en', 'bar']]``
:para... |
def is_import_exception(mod):
"""Check module name to see if import has been whitelisted.
Import based rules should not run on any whitelisted module
"""
return (mod in IMPORT_EXCEPTIONS or
any(mod.startswith(m + '.') for m in IMPORT_EXCEPTIONS)) | Check module name to see if import has been whitelisted.
Import based rules should not run on any whitelisted module |
def bend(self, n_bends, start_times, end_times, cents, frame_rate=25,
oversample_rate=16):
'''Changes pitch by specified amounts at specified times.
The pitch-bending algorithm utilises the Discrete Fourier Transform
(DFT) at a particular frame rate and over-sampling rate.
... | Changes pitch by specified amounts at specified times.
The pitch-bending algorithm utilises the Discrete Fourier Transform
(DFT) at a particular frame rate and over-sampling rate.
Parameters
----------
n_bends : int
The number of intervals to pitch shift
star... |
def single_valued(self, e):
"""
Returns True whether `e` is a concrete value or is a value set with
only 1 possible value. This differs from `unique` in that this *does*
not query the constraint solver.
"""
if self.state.mode == 'static':
if type(e) in (int, b... | Returns True whether `e` is a concrete value or is a value set with
only 1 possible value. This differs from `unique` in that this *does*
not query the constraint solver. |
def send_notice(self, text):
"""Send a notice (from bot) message to the room."""
return self.client.api.send_notice(self.room_id, text) | Send a notice (from bot) message to the room. |
def validate(self, attrs):
""" checks if login credentials are correct """
user = authenticate(**self.user_credentials(attrs))
if user:
if user.is_active:
self.instance = user
else:
raise serializers.ValidationError(_("This account is curr... | checks if login credentials are correct |
def extract_url_query_parameter(url, parameter):
"""Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for the given query name in the gi... | Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for the given query name in the given URL or
an empty string if the query is not i... |
def view(self, shape=None, chunks=None, dtype=None,
fill_value=None, filters=None, read_only=None,
synchronizer=None):
"""Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or ... | Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape.
dtype : string or dtype, optional
NumPy dtype.
fill_value : object
... |
def getRootDirectory(cls):
"""
Get the root directory that contains files added through
C{SparkContext.addFile()}.
"""
if cls._is_running_on_worker:
return cls._root_directory
else:
# This will have to change if we support multiple SparkContexts:
... | Get the root directory that contains files added through
C{SparkContext.addFile()}. |
def get_item(self, item_index, force_download=False):
""" Retrieve the metadata for a specific item in this ItemGroup
:type item_index: int
:param item_index: the index of the item
:type force_download: Boolean
:param force_download: True to download from the server
... | Retrieve the metadata for a specific item in this ItemGroup
:type item_index: int
:param item_index: the index of the item
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: Item
:... |
def from_env(key: str, default: T = None) -> Union[str, Optional[T]]:
"""Shortcut for safely reading environment variable.
:param key: Environment var key.
:param default:
Return default value if environment var not found by given key. By
default: ``None``
"""
return os.getenv(key, ... | Shortcut for safely reading environment variable.
:param key: Environment var key.
:param default:
Return default value if environment var not found by given key. By
default: ``None`` |
def sharpe_ratio(self, rf=0.02, ddof=0):
"""Return over `rf` per unit of total risk.
The average return in excess of the risk-free rate divided
by the standard deviation of return; a measure of the average
excess return earned per unit of standard deviation of return.
[Source: C... | Return over `rf` per unit of total risk.
The average return in excess of the risk-free rate divided
by the standard deviation of return; a measure of the average
excess return earned per unit of standard deviation of return.
[Source: CFA Institute]
Parameters
----------... |
def isNumber(s):
"""
Determines if a unicode string (that may include commas) is a number.
:param s: Any unicode string.
:return: True if s represents a number, False otherwise.
"""
s = s.replace(',', '')
try:
float(s)
return True
except ValueError:
pass
try:... | Determines if a unicode string (that may include commas) is a number.
:param s: Any unicode string.
:return: True if s represents a number, False otherwise. |
def available_backups(self):
"""
The backups response contains what backups are available to be restored.
"""
if not hasattr(self, '_avail_backups'):
result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self)
if not 'automatic' in result:
... | The backups response contains what backups are available to be restored. |
def points(ys, width=None):
'''Usage:
import scipy.stats
def walk(steps, position=0):
for step in steps:
position += step
yield position
positions = list(walk(scipy.stats.norm.rvs(size=1000)))
points(positions)
'''
if width is None:
width = terminal.wi... | Usage:
import scipy.stats
def walk(steps, position=0):
for step in steps:
position += step
yield position
positions = list(walk(scipy.stats.norm.rvs(size=1000)))
points(positions) |
def raw_print_err(*args, **kw):
"""Raw print to sys.__stderr__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stderr__)
sys.__stderr__.flush() | Raw print to sys.__stderr__, otherwise identical interface to print(). |
def active_db():
"""Returns the active :class:`TaskDB` for the current project and task.
"""
global dbs
# The task database is encapsulated in a class for easier serialization to
# JSON. Get the DB for the (project, task) combination.
dbkey = (project, task)
if dbkey in dbs:
taskdb =... | Returns the active :class:`TaskDB` for the current project and task. |
def convert_btc_to_cur(self, coins, currency):
"""
Convert X bit coins to valid currency amount
"""
if isinstance(coins, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.js... | Convert X bit coins to valid currency amount |
def get(cls, transferwise_quote_id, transferwise_transfer_id,
custom_headers=None):
"""
:type api_context: context.ApiContext
:type user_id: int
:type transferwise_quote_id: int
:type transferwise_transfer_id: int
:type custom_headers: dict[str, str]|None
... | :type api_context: context.ApiContext
:type user_id: int
:type transferwise_quote_id: int
:type transferwise_transfer_id: int
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseTransferwiseTransfer |
def get_node_by_dsl(self, node_dict: BaseEntity) -> Optional[Node]:
"""Look up a node by its data dictionary by hashing it then using :func:`get_node_by_hash`."""
return self.get_node_by_hash(node_dict.as_sha512()) | Look up a node by its data dictionary by hashing it then using :func:`get_node_by_hash`. |
def _get_encrypted_manifest(self):
"""
Returns contents of the manifest where environment variables
that are secret will be encrypted without modifying the existing
state in memory which will remain unencrypted.
"""
key = predix.config.get_crypt_key(self.manifest_key)
... | Returns contents of the manifest where environment variables
that are secret will be encrypted without modifying the existing
state in memory which will remain unencrypted. |
def add_fields(self, *args):
"""
This method only works for extensible fields. It allows to add values without precising their fields' names
or indexes.
Parameters
----------
args: field values
"""
if not self.is_extensible():
raise TypeError(... | This method only works for extensible fields. It allows to add values without precising their fields' names
or indexes.
Parameters
----------
args: field values |
def request_args(self):
"""Use args_schema to parse request query arguments."""
args = flask.request.args
data_raw = {}
for field_name, field in self.args_schema.fields.items():
alternate_field_name = field.load_from if MA2 else field.data_key
if alternate_field... | Use args_schema to parse request query arguments. |
def experiments_predictions_update_state_success(self, experiment_id, run_id, result_file):
"""Update state of given prediction to success. Create a function data
resource for the given result file and associate it with the model run.
Parameters
----------
experiment_id : string... | Update state of given prediction to success. Create a function data
resource for the given result file and associate it with the model run.
Parameters
----------
experiment_id : string
Unique experiment identifier
run_id : string
Unique model run identifi... |
def random_string(length):
"""
Generates a random alphanumeric string
"""
# avoid things that could be mistaken ex: 'I' and '1'
letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
return "".join([random.choice(letters) for _ in range(length)]) | Generates a random alphanumeric string |
def fetchThreadList(
self, offset=None, limit=20, thread_location=ThreadLocation.INBOX, before=None
):
"""Get thread list of your facebook account
:param offset: Deprecated. Do not use!
:param limit: Max. number of threads to retrieve. Capped at 20
:param thread_location: mo... | Get thread list of your facebook account
:param offset: Deprecated. Do not use!
:param limit: Max. number of threads to retrieve. Capped at 20
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: A timestamp (in milliseconds), indicating from w... |
def analyze_reply_code(self, xml_response_dict):
"""
Checks the RETS Response Code and handles non-zero answers.
:param xml_response_dict:
:return: None
"""
if 'RETS-STATUS' in xml_response_dict:
attributes = self.get_attributes(xml_response_dict['RETS-STATUS'... | Checks the RETS Response Code and handles non-zero answers.
:param xml_response_dict:
:return: None |
def organization_deidentify_template_path(cls, organization, deidentify_template):
"""Return a fully-qualified organization_deidentify_template string."""
return google.api_core.path_template.expand(
"organizations/{organization}/deidentifyTemplates/{deidentify_template}",
organi... | Return a fully-qualified organization_deidentify_template string. |
def from_pickle(path: Union[str, BinaryIO], check_version: bool = True) -> BELGraph:
"""Read a graph from a pickle file.
:param path: File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
:param bool check_version: Checks if the graph was produced by this version of PyBEL
"""
... | Read a graph from a pickle file.
:param path: File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
:param bool check_version: Checks if the graph was produced by this version of PyBEL |
def drop_modifiers(sentence_str):
"""Given a string, drop the modifiers and return a string
without them"""
tdoc = textacy.Doc(sentence_str, lang='en_core_web_lg')
new_sent = tdoc.text
unusual_char = '形'
for tag in tdoc:
if tag.dep_.endswith('mod'):
# Replace the tag
... | Given a string, drop the modifiers and return a string
without them |
def QA_fetch_financial_report(code, report_date, ltype='EN', db=DATABASE):
"""获取专业财务报表
Arguments:
code {[type]} -- [description]
report_date {[type]} -- [description]
Keyword Arguments:
ltype {str} -- [description] (default: {'EN'})
db {[type]} -- [description] (default: {DAT... | 获取专业财务报表
Arguments:
code {[type]} -- [description]
report_date {[type]} -- [description]
Keyword Arguments:
ltype {str} -- [description] (default: {'EN'})
db {[type]} -- [description] (default: {DATABASE})
Raises:
e -- [description]
Returns:
pd.DataFrame -... |
def set_training(train_mode): #pylint: disable=redefined-outer-name
"""Set status to training/predicting. This affects ctx.is_train in operator
running context. For example, Dropout will drop inputs randomly when
train_mode=True while simply passing through if train_mode=False.
Parameters
---------... | Set status to training/predicting. This affects ctx.is_train in operator
running context. For example, Dropout will drop inputs randomly when
train_mode=True while simply passing through if train_mode=False.
Parameters
----------
train_mode: bool
Returns
-------
previous state before t... |
def openSession(self, slot, flags=0):
"""
C_OpenSession
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param flags: 0 (default), `CKF_RW_SESSION` for RW session
:type flags: integer
:return: a :class:`Session` object
"""
... | C_OpenSession
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param flags: 0 (default), `CKF_RW_SESSION` for RW session
:type flags: integer
:return: a :class:`Session` object |
def join(self, channel):
"""Add this user to the channel's user list and add the channel to this
user's list of joined channels.
"""
if channel not in self.channels:
channel.users.add(self.nick)
self.channels.append(channel) | Add this user to the channel's user list and add the channel to this
user's list of joined channels. |
def get_client_from_cli_profile(client_class, **kwargs):
"""Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
Parameters p... | Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
Parameters provided in kwargs will override CLI parameters and be passed dir... |
def trace_modules(self, modules, pattern=r".*", flags=re.IGNORECASE):
"""
Traces given modules using given filter pattern.
:param modules: Modules to trace.
:type modules: list
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex ... | Traces given modules using given filter pattern.
:param modules: Modules to trace.
:type modules: list
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Method success.
:rtype: bool |
def conform_query(cls, query):
"""Converts the query string from a target uri, uses
cls.allowed_kwargs, and cls.filter_kwargs to drive logic.
:param query: Unparsed query string
:type query: urllib.parse.unsplit(uri).query
:returns: Dictionary of parsed values, everything in cls... | Converts the query string from a target uri, uses
cls.allowed_kwargs, and cls.filter_kwargs to drive logic.
:param query: Unparsed query string
:type query: urllib.parse.unsplit(uri).query
:returns: Dictionary of parsed values, everything in cls.allowed_kwargs
with values se... |
def set_validation(self, batch_size, X_val, Y_val, trigger, val_method=None):
"""
Configure validation settings.
:param batch_size: validation batch size
:param X_val: features of validation dataset
:param Y_val: label of validation dataset
:param trigger: validation int... | Configure validation settings.
:param batch_size: validation batch size
:param X_val: features of validation dataset
:param Y_val: label of validation dataset
:param trigger: validation interval
:param val_method: the ValidationMethod to use,e.g. "Top1Accuracy", "Top5Accuracy", ... |
def try_adiabatic_elimination(slh, k=None, fock_trunc=6, sub_P0=True):
"""Attempt to automatically do adiabatic elimination on an SLH object
This will project the `Y` operator onto a truncated basis with dimension
specified by `fock_trunc`. `sub_P0` controls whether an attempt is made to
replace the k... | Attempt to automatically do adiabatic elimination on an SLH object
This will project the `Y` operator onto a truncated basis with dimension
specified by `fock_trunc`. `sub_P0` controls whether an attempt is made to
replace the kernel projector P0 by an :class:`.IdentityOperator`. |
def wait( self, timeout = -1 ):
"""Wait for all pending results to be finished. If timeout is set,
return after this many seconds regardless.
:param timeout: timeout period in seconds (defaults to forever)
:returns: True if all the results completed"""
# we can't use ipyparalle... | Wait for all pending results to be finished. If timeout is set,
return after this many seconds regardless.
:param timeout: timeout period in seconds (defaults to forever)
:returns: True if all the results completed |
def get(self, instance_name):
"""Get an ObjectRocket instance by name.
:param str instance_name: The name of the instance to retrieve.
:returns: A subclass of :py:class:`bases.BaseInstance`, or None if instance does not exist.
:rtype: :py:class:`bases.BaseInstance`
"""
u... | Get an ObjectRocket instance by name.
:param str instance_name: The name of the instance to retrieve.
:returns: A subclass of :py:class:`bases.BaseInstance`, or None if instance does not exist.
:rtype: :py:class:`bases.BaseInstance` |
def _survivor_merge(call_vcf, truth_vcf, stats, work_dir, data):
"""Perform a merge of two callsets using SURVIVOR,
"""
out_file = os.path.join(work_dir, "eval-merge.vcf")
if not utils.file_uptodate(out_file, call_vcf):
in_call_vcf = call_vcf.replace(".vcf.gz", ".vcf")
if not utils.file_... | Perform a merge of two callsets using SURVIVOR, |
def create_user(self, user_id,
roles=None, netmask=None,
secret=None, pubkey=None):
u"""Create user for the Merchant given in the X-Mcash-Merchant header.
Arguments:
user_id:
Identifier for the user
roles:
R... | u"""Create user for the Merchant given in the X-Mcash-Merchant header.
Arguments:
user_id:
Identifier for the user
roles:
Role
netmask:
Limit user connections by netmask, for example 192.168.1.0/24
secret:
... |
def set_status(self, instance, status):
"""Sets the field status for up to 5 minutes."""
status_key = self.get_status_key(instance)
cache.set(status_key, status, timeout=300) | Sets the field status for up to 5 minutes. |
def fit(self, X, y=None):
"""Fit the grid
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data points
Returns
-------
self
"""
X = array2d(X)
self.n_features = X.shape[1]
self.n_bins = self.n_bins... | Fit the grid
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data points
Returns
-------
self |
def get_dists_to_ignore(installed):
"""
Returns a collection of package names to ignore when performing pip-sync,
based on the currently installed environment. For example, when pip-tools
is installed in the local environment, it should be ignored, including all
of its dependencies (e.g. click). W... | Returns a collection of package names to ignore when performing pip-sync,
based on the currently installed environment. For example, when pip-tools
is installed in the local environment, it should be ignored, including all
of its dependencies (e.g. click). When pip-tools is not installed
locally, clic... |
def s3_connect(bucket_name, s3_access_key_id, s3_secret_key):
""" Returns a Boto connection to the provided S3 bucket. """
conn = connect_s3(s3_access_key_id, s3_secret_key)
try:
return conn.get_bucket(bucket_name)
except S3ResponseError as e:
if e.status == 403:
raise Except... | Returns a Boto connection to the provided S3 bucket. |
def indent(self, indent_count):
'''
add whitespace to the beginning of each line of val
link -- http://code.activestate.com/recipes/66055-changing-the-indentation-of-a-multi-line-string/
val -- string
indent -- integer -- how much whitespace we want in front of each line of val... | add whitespace to the beginning of each line of val
link -- http://code.activestate.com/recipes/66055-changing-the-indentation-of-a-multi-line-string/
val -- string
indent -- integer -- how much whitespace we want in front of each line of val
return -- string -- val with more whitespa... |
def get_embedded(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the embedded object for link_relation. The returned object can be
treated as a result object in its own right.
'result_object' a JSON object returned by a previous API call.
The ... | Given a result_object (returned by a previous API call), return
the embedded object for link_relation. The returned object can be
treated as a result object in its own right.
'result_object' a JSON object returned by a previous API call.
The link relation of teh embedded object must have been specifie... |
def _crc32(self, ch, crc):
"""Compute the CRC32 primitive on one byte."""
return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] | Compute the CRC32 primitive on one byte. |
def _init_browser(self):
"""
Ovveride this method with the appropriate way to prepare a logged in
browser.
"""
self.browser = mechanize.Browser()
self.browser.set_handle_robots(False)
self.browser.open(self.server_url + "/youraccount/login")
self.browser.s... | Ovveride this method with the appropriate way to prepare a logged in
browser. |
def get_modules():
'''
Get a list of the PowerShell modules which are potentially available to be
imported. The intent is to mimic the functionality of ``Get-Module
-ListAvailable | Select-Object -Expand Name``, without the delay of loading
PowerShell to do so.
Returns:
list: A list of ... | Get a list of the PowerShell modules which are potentially available to be
imported. The intent is to mimic the functionality of ``Get-Module
-ListAvailable | Select-Object -Expand Name``, without the delay of loading
PowerShell to do so.
Returns:
list: A list of modules available to Powershell... |
def set_el(cls, el, value):
"""
Set given `el` tag element to `value`.
Automatically choose proper method to set the `value` based on the type
of the `el`.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
v... | Set given `el` tag element to `value`.
Automatically choose proper method to set the `value` based on the type
of the `el`.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
value (list): List of dicts with two keys: ``sour... |
def from_dict(cls, d):
"""
Create an instance from a dictionary.
"""
instance = super(SimulationGroup, cls).from_dict(d)
# instance.simulations is a list of dictionaries; convert each dictionary to a Simulation instance
instance.simulations = [Simulation.from_dict(x) for... | Create an instance from a dictionary. |
def createZMQSocket(self, sock_type):
"""Create a socket of the given sock_type and deactivate message dropping"""
sock = self.ZMQcontext.socket(sock_type)
sock.setsockopt(zmq.LINGER, LINGER_TIME)
sock.setsockopt(zmq.IPV4ONLY, 0)
# Remove message dropping
sock.setsockopt... | Create a socket of the given sock_type and deactivate message dropping |
def convert_key_to_attr_names(cls, original):
""" convert key names to their corresponding attribute names """
attrs = fields(cls)
updated = {}
keys_pulled = set()
for a in attrs:
key_name = a.metadata.get('key') or a.name
if key_name in original:
updated[a.name] = origi... | convert key names to their corresponding attribute names |
def tco_return_handle(tokens):
"""Process tail-call-optimizable return statements."""
internal_assert(len(tokens) == 2, "invalid tail-call-optimizable return statement tokens", tokens)
if tokens[1].startswith("()"):
return "return _coconut_tail_call(" + tokens[0] + ")" + tokens[1][2:] # tokens[1] c... | Process tail-call-optimizable return statements. |
def delete(self, user, name):
"""
Removes a feed
:param user: feed username
:param name: feed name
:return: true/false
"""
uri = self.client.remote + '/users/{}/feeds/{}'.format(user, name)
resp = self.client.session.delete(uri)
return resp.stat... | Removes a feed
:param user: feed username
:param name: feed name
:return: true/false |
def graphviz(self, highlight=None, maximal_label=None, topdown=None,
filename=None, directory=None, render=False, view=False):
"""Return the system lattice visualization as graphviz source."""
return visualize.featuresystem(self, highlight, maximal_label,
topdown, filename, direc... | Return the system lattice visualization as graphviz source. |
def tanh_warp(x, n, l1, l2, lw, x0):
r"""Implements a tanh warping function and its derivative.
.. math::
l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w}
Parameters
----------
x : float or array of float
Locations to evaluate the function at.
n ... | r"""Implements a tanh warping function and its derivative.
.. math::
l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w}
Parameters
----------
x : float or array of float
Locations to evaluate the function at.
n : int
Derivative order to take. U... |
def _handle_tag_jpegtables(self):
"""Handle the JPEGTables tag."""
obj = _make_object("JPEGTables")
assert self._src.read(2) == b'\xFF\xD8' # SOI marker
eoimark1 = eoimark2 = None
allbytes = [b'\xFF\xD8']
while not (eoimark1 == b'\xFF' and eoimark2 == b'\xD9'):
... | Handle the JPEGTables tag. |
def join(self, right_table, on=None, right_prefix='R.', outer=False):
"""
Inner-joins another DataTable to this one using `on` (iterable of join
keys). If two tables share columns other than the join keys, appends
right_prefix to the right table's column name. If `on` is not
prov... | Inner-joins another DataTable to this one using `on` (iterable of join
keys). If two tables share columns other than the join keys, appends
right_prefix to the right table's column name. If `on` is not
provided, performs a 'natural join' using all columns of the same name. |
def findAll(haystack, needle) :
"""returns a list of all occurances of needle in haystack"""
h = haystack
res = []
f = haystack.find(needle)
offset = 0
while (f >= 0) :
#print h, needle, f, offset
res.append(f+offset)
offset += f+len(needle)
h = h[f+len(needle):]
f = h.find(needle)
return res | returns a list of all occurances of needle in haystack |
def get_format_modules(lang=None, reverse=False):
"""
Returns a list of the format modules found
"""
if lang is None:
lang = get_language()
modules = _format_modules_cache.setdefault(lang, list(
iter_format_modules(lang)))
if reverse:
return list(reversed(modules))
r... | Returns a list of the format modules found |
def strip_tsft(self, idx):
"""strip(8 byte) radiotap.mactime
:idx: int
:return: int
idx
:return: int
mactime
"""
idx = Radiotap.align(idx, 8)
mactime, = struct.unpack_from('<Q', self._rtap, idx)
return idx + 8, mactime | strip(8 byte) radiotap.mactime
:idx: int
:return: int
idx
:return: int
mactime |
def add(self, interface_id, virtual_mapping=None,
virtual_resource_name=None, zone_ref=None, comment=None):
"""
Add single physical interface with interface_id. Use other methods
to fully add an interface configuration based on engine type.
Virtual mapping and resource are on... | Add single physical interface with interface_id. Use other methods
to fully add an interface configuration based on engine type.
Virtual mapping and resource are only used in Virtual Engines.
:param str,int interface_id: interface identifier
:param int virtual_mapping: virtual firewall ... |
def default(self):
"""Default the NTP source entry from the node.
Returns:
True if the operation succeeds, otherwise False.
"""
cmd = self.command_builder('ntp source', default=True)
return self.configure(cmd) | Default the NTP source entry from the node.
Returns:
True if the operation succeeds, otherwise False. |
def collapse(self, remove=False):
"""
Move all ``sequence_ids`` in the subtree below this node to this node.
If ``remove`` is True, nodes below this one are deleted from the
taxonomy.
"""
descendants = iter(self)
# Skip this node
assert next(descendants) ... | Move all ``sequence_ids`` in the subtree below this node to this node.
If ``remove`` is True, nodes below this one are deleted from the
taxonomy. |
def to_json(self):
"""Serialize an object to JSON based on its "properties" class
attribute.
:rtype: string"""
j = {}
for p in self.properties:
try:
v = getattr(self, p)
except AttributeError:
continue
if v is ... | Serialize an object to JSON based on its "properties" class
attribute.
:rtype: string |
def invokeSmapiApi(rh):
"""
Invoke a SMAPI API.
Input:
Request Handle with the following properties:
function - 'SMAPI'
subfunction - 'API'
userid - 'HYPERVISOR'
parms['apiName'] - Name of API as defined by SMCLI
parms['operands'] - List (... | Invoke a SMAPI API.
Input:
Request Handle with the following properties:
function - 'SMAPI'
subfunction - 'API'
userid - 'HYPERVISOR'
parms['apiName'] - Name of API as defined by SMCLI
parms['operands'] - List (array) of operands to send or
... |
def parse(self, method, endpoint, body):
''' calls parse on list or detail '''
if isinstance(body, dict): # request body was already parsed
return body
if endpoint == 'list':
return self.parse_list(body)
return self.parse_detail(body) | calls parse on list or detail |
def storages(self):
"""
Gathers relevant storage results.
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
Dataframe containing all storages installed in the MV grid and
LV grids. Index of the dataframe are the storage representatives,
c... | Gathers relevant storage results.
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
Dataframe containing all storages installed in the MV grid and
LV grids. Index of the dataframe are the storage representatives,
columns are the following:
n... |
def update_handler(args):
"""usage: {program} update [<path>]
Update out of date anchors in the current repository.
"""
repo = _open_repo(args)
for anchor_id, anchor in repo.items():
try:
anchor = update(anchor)
except AlignmentError as e:
print('Unable to u... | usage: {program} update [<path>]
Update out of date anchors in the current repository. |
def get_provider():
'''Get the current provider from config'''
name = get_config('provider')
available = entrypoints.get_all('udata.avatars')
if name not in available:
raise ValueError('Unknown avatar provider: {0}'.format(name))
return available[name] | Get the current provider from config |
def base64_bytes(x):
"""Turn base64 into bytes"""
if six.PY2:
return base64.decodestring(x)
return base64.decodebytes(bytes_encode(x)) | Turn base64 into bytes |
def analyzeAP(Y,dY,I,rate,verbose=False):
"""
given a sweep and a time point, return the AP array for that AP.
APs will be centered in time by their maximum upslope.
"""
Ims = int(rate/1000) #Is per MS
IsToLook=5*Ims #TODO: clarify this, ms until downslope is over
upslope=np.max(dY[I:I+IsToL... | given a sweep and a time point, return the AP array for that AP.
APs will be centered in time by their maximum upslope. |
def calculate_size(name, expected, updated):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
data_size += LONG_SIZE_IN_BYTES
return data_size | Calculates the request payload size |
def _dump_arg_defaults(kwargs):
"""Inject default arguments for dump functions."""
if current_app:
kwargs.setdefault('cls', current_app.json_encoder)
if not current_app.config['JSON_AS_ASCII']:
kwargs.setdefault('ensure_ascii', False)
kwargs.setdefault('sort_keys', current_ap... | Inject default arguments for dump functions. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.