code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _check_fix_Q(self, fixed_mu=False):
"""
Check the main diagonal of Q and fix it in case it does not corresond
the definition of the rate matrix. Should be run every time when creating
custom GTR model.
"""
# fix Q
self.Pi /= self.Pi.sum() # correct the Pi manu... | Check the main diagonal of Q and fix it in case it does not corresond
the definition of the rate matrix. Should be run every time when creating
custom GTR model. |
def render_cheetah_tmpl(tmplstr, context, tmplpath=None):
'''
Render a Cheetah template.
'''
from Cheetah.Template import Template
return salt.utils.data.decode(Template(tmplstr, searchList=[context])) | Render a Cheetah template. |
def getReffs(self, textId, level=1, subreference=None):
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param level: Depth for retrieval
:type level: int
:param subreference: CapitainsCtsPassage CtsReference
... | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param level: Depth for retrieval
:type level: int
:param subreference: CapitainsCtsPassage CtsReference
:type subreference: str
:return: List of references
... |
def _galaxy_tool_copy(finfo, outputs):
"""Copy information directly to pre-defined outputs from a Galaxy tool.
XXX Needs generalization
"""
tool_map = {"align": "bam", "variants": "vcf.gz"}
for galaxy_key, finfo_type in tool_map.items():
if galaxy_key in outputs and finfo.get("type") == fin... | Copy information directly to pre-defined outputs from a Galaxy tool.
XXX Needs generalization |
def invert(dict_): #TODO return a MultiDict right away
'''
Invert dict by swapping each value with its key.
Parameters
----------
dict_ : ~typing.Dict[~typing.Hashable, ~typing.Hashable]
Dict to invert.
Returns
-------
~typing.Dict[~typing.Hashable, ~typing.Set[~typing.Hashable... | Invert dict by swapping each value with its key.
Parameters
----------
dict_ : ~typing.Dict[~typing.Hashable, ~typing.Hashable]
Dict to invert.
Returns
-------
~typing.Dict[~typing.Hashable, ~typing.Set[~typing.Hashable]]
Dict with keys and values swapped.
See also
---... |
def request_vpc_peering_connection(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None,... | name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name. String type.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id. String type.
peer_vpc_id
ID of the VPC tp crete VPC peering connection wi... |
def _initialize(self):
"""Initialize collector worker thread, Log path will be checked first.
Records in DB backend will be cleared.
"""
if not os.path.exists(self._logdir):
raise CollectorError("Log directory %s not exists" % self._logdir)
self.logger.info("Collect... | Initialize collector worker thread, Log path will be checked first.
Records in DB backend will be cleared. |
def add_override(self, symbol, ind, val, dt_log=None, user=None, comment=None):
"""
Appends a single indexed-value pair, to a symbol object, to be
used during the final steps of the aggregation of the datatable.
With default settings Overrides, get applied with highest priority.
... | Appends a single indexed-value pair, to a symbol object, to be
used during the final steps of the aggregation of the datatable.
With default settings Overrides, get applied with highest priority.
Parameters
----------
symbol : Symbol or str
The Symbo... |
def AUNP_calc(classes, P, POP, AUC_dict):
"""
Calculate AUNP.
:param classes: classes
:type classes : list
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
:param AUC_dict: AUC (Area under the ROC curve) for each class
:type AUC_dict : dict
... | Calculate AUNP.
:param classes: classes
:type classes : list
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
:param AUC_dict: AUC (Area under the ROC curve) for each class
:type AUC_dict : dict
:return: AUNP as float |
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
N = len(data["symbols"])
masses = np.zeros(N, float)
counter = 0
while counter < N:
words = f.readline().split()
for word in words:
masses[counter] = float(word)*amu
... | See :meth:`PunchParser.read` |
def iperf_version(self):
"""Returns the version of the libiperf library
:rtype: string
"""
# TODO: Is there a better way to get the const char than allocating 30?
VersionType = c_char * 30
return VersionType.in_dll(self.lib, "version").value.decode('utf-8') | Returns the version of the libiperf library
:rtype: string |
def warningFailure(self, failure, swallow=True):
"""
Log a warning about a Twisted Failure. Useful as an errback handler:
d.addErrback(self.warningFailure)
@param swallow: whether to swallow the failure or not
@type swallow: bool
"""
if _canShortcutLogging(self.... | Log a warning about a Twisted Failure. Useful as an errback handler:
d.addErrback(self.warningFailure)
@param swallow: whether to swallow the failure or not
@type swallow: bool |
def generate_steady_rt_pic(process_data, para_meter, scale, steady_time):
""" generate rate steady"""
pic_path_steady = para_meter['filename'] + '_steady.png'
plt.figure(figsize=(4 * scale, 2.5 * scale))
for key in process_data.keys():
if len(process_data[key]) < steady_time:
s... | generate rate steady |
def assemble(self, blueprint, quota):
"""Assemble a quota of documents"""
# Reset the blueprint
blueprint.reset()
# Assemble the documents
documents = []
for i in range(0, int(quota)):
documents.append(blueprint.assemble())
return documents | Assemble a quota of documents |
def _get_uptime(self, app_stats):
""" Return Icinga's uptime """
if "program_start" not in app_stats.keys():
return 0
if not app_stats["program_start"].isdigit():
return 0
uptime = int(time.time()) - int(app_stats["program_start"])
if uptime < 0:
... | Return Icinga's uptime |
def blockUser(self, user_id):
"""
Blocks messages from a specifed user
:param user_id: The ID of the user that you want to block
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
data = {"fbid": user_id}
r = self._... | Blocks messages from a specifed user
:param user_id: The ID of the user that you want to block
:return: Whether the request was successful
:raises: FBchatException if request failed |
def propose(self):
"""
This method is called by step() to generate proposed values
if self.proposal_distribution is "Normal" (i.e. no proposal specified).
"""
prop_dist = self.proposal_distribution.lower()
if prop_dist == "normal":
self.stochastic.value ... | This method is called by step() to generate proposed values
if self.proposal_distribution is "Normal" (i.e. no proposal specified). |
def merge_accounts(self, request):
"""
Attach NetID account to regular django
account and then redirect user. In this situation
user dont have to fill extra fields because he filled
them when first account (request.user) was created.
Note that self.indentity must be alre... | Attach NetID account to regular django
account and then redirect user. In this situation
user dont have to fill extra fields because he filled
them when first account (request.user) was created.
Note that self.indentity must be already set in this stage by
validate_response func... |
def write_neurommsig_bel(file,
df: pd.DataFrame,
disease: str,
nift_values: Mapping[str, str],
):
"""Writes the NeuroMMSigDB excel sheet to BEL
:param file: a file or file-like that can be writen to
:param d... | Writes the NeuroMMSigDB excel sheet to BEL
:param file: a file or file-like that can be writen to
:param df:
:param disease:
:param nift_values: a dictionary of lowercased to normal names in NIFT |
def image_to_base64(self, image):
"""
:param image: One of file object, path, or URL
:return: Base64 of image
"""
if isinstance(image, file_):
return base64.b64encode(image.read())
elif isinstance(image, basestring):
if image.startswith("http"):
... | :param image: One of file object, path, or URL
:return: Base64 of image |
def _init_required_options(self, **kwargs):
"""
Initialize the required option as class members. The value will be
either None or the specified value in the kwargs or __init__. The logic
here is to make the required options accesible to edit after a class
instance has been create... | Initialize the required option as class members. The value will be
either None or the specified value in the kwargs or __init__. The logic
here is to make the required options accesible to edit after a class
instance has been created. |
def check_connection (self):
"""
Verify a list of email addresses. If one address fails,
the whole list will fail.
For each mail address the MX DNS records are found.
If no MX records are found, print a warning and try
to look for A DNS records. If no A records are found... | Verify a list of email addresses. If one address fails,
the whole list will fail.
For each mail address the MX DNS records are found.
If no MX records are found, print a warning and try
to look for A DNS records. If no A records are found either
print an error. |
def check(self, group_id, session):
'''taobao.crm.grouptask.check 查询分组任务是否完成
检查一个分组上是否有异步任务,异步任务包括
- 1.将一个分组下的所有用户添加到另外一个分组
- 2.将一个分组下的所有用户移动到另外一个分组
- 3.删除某个分组 若分组上有任务则该属性不能被操作。'''
request = TOPRequest('taobao.crm.grouptask.check')
request['group... | taobao.crm.grouptask.check 查询分组任务是否完成
检查一个分组上是否有异步任务,异步任务包括
- 1.将一个分组下的所有用户添加到另外一个分组
- 2.将一个分组下的所有用户移动到另外一个分组
- 3.删除某个分组 若分组上有任务则该属性不能被操作。 |
def _parse_multi_byte(self, s):
# type: (str) -> int
""" _parse_multi_byte parses x as a multibyte representation to get the
int value of this AbstractUVarIntField.
@param str s: the multibyte string to parse.
@return int: The parsed int value represented by this AbstractUVarI... | _parse_multi_byte parses x as a multibyte representation to get the
int value of this AbstractUVarIntField.
@param str s: the multibyte string to parse.
@return int: The parsed int value represented by this AbstractUVarIntField. # noqa: E501
@raise: AssertionError
@raise: Sca... |
def create_db(data, dbfn, id_spec=None, force=False, verbose=False,
checklines=10, merge_strategy='error', transform=None,
gtf_transcript_key='transcript_id', gtf_gene_key='gene_id',
gtf_subfeature='exon', force_gff=False,
force_dialect_check=False, from_string=Fa... | Create a database from a GFF or GTF file.
For more details on when and how to use the kwargs below, see the examples
in the online documentation (:ref:`examples`).
Parameters
----------
data : string or iterable
If a string (and `from_string` is False), then `data` is the path to
... |
def get_arguments(self):
"""
CLIs get called back so that they can process any command line arguments
that are given. This method handles the standard command line arguments for:
API Host, user, password, etc.
"""
# We call this first so that logging is enabled as soon a... | CLIs get called back so that they can process any command line arguments
that are given. This method handles the standard command line arguments for:
API Host, user, password, etc. |
def matches(self, pattern):
"""
Construct a Filter that checks regex matches against ``pattern``.
Parameters
----------
pattern : str
Regex pattern against which to compare values produced by ``self``.
Returns
-------
matches : Filter
... | Construct a Filter that checks regex matches against ``pattern``.
Parameters
----------
pattern : str
Regex pattern against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Filter returning True for all sid/date pair... |
def copy(self, resource_view):
# type: (Union[ResourceView,Dict,str]) -> None
"""Copies all fields except id, resource_id and package_id from another resource view.
Args:
resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ... | Copies all fields except id, resource_id and package_id from another resource view.
Args:
resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary
Returns:
None |
def generate(self, projectpath, parameters, serviceid, servicename,serviceurl):
"""Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance. """
#Make dictionary of parameters
parameters = sanitizeparameters(parameters)
... | Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance. |
def _bond_length_low(r, deriv):
"""Similar to bond_length, but with a relative vector"""
r = Vector3(3, deriv, r, (0, 1, 2))
d = r.norm()
return d.results() | Similar to bond_length, but with a relative vector |
def _get_part(pointlist, strokes):
"""Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts
"""
result = []
strokes = sorted(strokes)
for stroke_index in strokes:
... | Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts |
def generateProjectFiles(self, dir=os.getcwd(), args=[]):
"""
Generates IDE project files for the Unreal project in the specified directory
"""
# If the project is a pure Blueprint project, then we cannot generate project files
if os.path.exists(os.path.join(dir, 'Source')) == False:
Utility.printStderr... | Generates IDE project files for the Unreal project in the specified directory |
def validate(self, request, value):
"""
This is not for business validation
This should be only used for type validation
Hence the only input is the value of the field
:param value:
:return:
"""
if self.required and value == DEFAULT_FIELD_VALUE:
... | This is not for business validation
This should be only used for type validation
Hence the only input is the value of the field
:param value:
:return: |
def next(self):
"""Generate next of iterator"""
if self.iter_next():
if self.is_train:
data_raw_list = self.getdata()
data_shifted = []
for data_raw in data_raw_list[0]:
data_shifted.append(random_shift(data_raw.asnumpy(), 0... | Generate next of iterator |
def remove(self, payload):
"""Remove specified entries from the queue."""
succeeded = []
failed = []
for key in payload['keys']:
running = self.process_handler.is_running(key)
if not running:
removed = self.queue.remove(key)
if remo... | Remove specified entries from the queue. |
def _get_text_sequence(self, text, span, context_length):
"""Returns the subset of `text` encompassed by `span`, plus
`context_length` characters before and after.
:param text: text to extract the sequence from
:type text: `str`
:param span: start and end indices within `text`
... | Returns the subset of `text` encompassed by `span`, plus
`context_length` characters before and after.
:param text: text to extract the sequence from
:type text: `str`
:param span: start and end indices within `text`
:type span: 2-`tuple` of `int`
:param context_length: ... |
def clear_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
):
"""Remove a breakpoint"""
log.info(
'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
(filename, lineno, temporary, cond, funcname)
)
breakp... | Remove a breakpoint |
def _checkAttribs(self, strict):
"""Check initial attributes to make sure they are legal"""
if self.choice:
warning("Choice values not allowed for real-type parameter " +
self.name, strict)
self.choice = None | Check initial attributes to make sure they are legal |
def set_expire(self, y = 2999, mon = 12, d = 28, h = 23, min_ = 59,
s = 59):
"""This method is used to change the expire date of a group
- y is the year between 1 and 9999 inclusive
- mon is the month between 1 and 12
- d is a day in the given month
... | This method is used to change the expire date of a group
- y is the year between 1 and 9999 inclusive
- mon is the month between 1 and 12
- d is a day in the given month
- h is a hour between 0 and 23
- min_ is a minute between 0 and 59
- s is a s... |
def get_license_assignment_manager(service_instance):
'''
Returns the license assignment manager.
service_instance
The Service Instance Object from which to obrain the license manager.
'''
log.debug('Retrieving license assignment manager')
try:
lic_assignment_manager = \
... | Returns the license assignment manager.
service_instance
The Service Instance Object from which to obrain the license manager. |
def impulse_response(genrate, fresponse, frequencies, frange, filter_len=2 ** 14, db=True):
"""
Calculate filter kernel from attenuation vector.
Attenuation vector should represent magnitude frequency response of system
:param genrate: The generation samplerate at which the test signal was played
... | Calculate filter kernel from attenuation vector.
Attenuation vector should represent magnitude frequency response of system
:param genrate: The generation samplerate at which the test signal was played
:type genrate: int
:param fresponse: Frequency response of the system in dB, i.e. relative attenu... |
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carb... | Send the data to carbon |
def b64decode_url(istr):
""" JWT Tokens may be truncated without the usual trailing padding '='
symbols. Compensate by padding to the nearest 4 bytes.
"""
istr = encode_safe(istr)
try:
return urlsafe_b64decode(istr + '=' * (4 - (len(istr) % 4)))
except TypeError as e:
raise E... | JWT Tokens may be truncated without the usual trailing padding '='
symbols. Compensate by padding to the nearest 4 bytes. |
def close(self):
"""Close any open connections to Redis.
:raises: :exc:`tredis.exceptions.ConnectionError`
"""
if not self._connected.is_set():
raise exceptions.ConnectionError('not connected')
self._closing = True
if self._clustering:
for host i... | Close any open connections to Redis.
:raises: :exc:`tredis.exceptions.ConnectionError` |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return OptionClass(key)
if key not in OptionClass._member_map_:
extend_enum(OptionClass, key, default)
return OptionClass[key] | Backport support for original codes. |
def __buttonEvent(event):
"""
Handle an event that is generated by a person clicking a button.
"""
global boxRoot, __widgetTexts, __replyButtonText
__replyButtonText = __widgetTexts[event.widget]
boxRoot.quit() | Handle an event that is generated by a person clicking a button. |
def _internal_add_node(self,
node_name: str,
external_id: Optional[str] = None,
are_neighbors_cached: bool = False,
add_to_cache: bool = False) -> None:
"""
Adds a node with the given name t... | Adds a node with the given name to the graph without checking whether it already exists or not.
Arguments:
node_name (str): The name of the node to add.
external_id (Optional[str]): The external ID of the node.
are_neighbors_cached (bool): Whether the neighbors of the n... |
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs... | Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object |
def min(self):
"""Minimum, ignoring nans."""
if "min" not in self.attrs.keys():
def f(dataset, s):
return np.nanmin(dataset[s])
self.attrs["min"] = np.nanmin(list(self.chunkwise(f).values()))
return self.attrs["min"] | Minimum, ignoring nans. |
def as_dict(self):
""" create a dict based on class attributes """
odict = OrderedDict()
for name in self._order:
attr_value = getattr(self, name)
if isinstance(attr_value, List):
_list = []
for item in attr_value:
_list... | create a dict based on class attributes |
def _get_slave_status(self, db, above_560, nonblocking):
"""
Retrieve the slaves' statuses using:
1. The `performance_schema.threads` table. Non-blocking, requires version > 5.6.0
2. The `information_schema.processlist` table. Blocking
"""
try:
with closing(db... | Retrieve the slaves' statuses using:
1. The `performance_schema.threads` table. Non-blocking, requires version > 5.6.0
2. The `information_schema.processlist` table. Blocking |
def get_response_time(chatbot, statement='Hello'):
"""
Returns the amount of time taken for a given
chat bot to return a response.
:param chatbot: A chat bot instance.
:type chatbot: ChatBot
:returns: The response time in seconds.
:rtype: float
"""
import time
start_time = tim... | Returns the amount of time taken for a given
chat bot to return a response.
:param chatbot: A chat bot instance.
:type chatbot: ChatBot
:returns: The response time in seconds.
:rtype: float |
def maybe_key_vault(client, mount_path):
"""
Set up a client key in Vault if one does not exist already.
:param client:
The Vault API client to use.
:param mount_path:
The Vault key/value mount path to use.
:rtype: twisted.internet.defer.Deferred
"""
d = client.read_kv2('cli... | Set up a client key in Vault if one does not exist already.
:param client:
The Vault API client to use.
:param mount_path:
The Vault key/value mount path to use.
:rtype: twisted.internet.defer.Deferred |
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_nonancestors_of() with a node id is deprecated,'
' use a DAGNode instead',
Deprec... | Remove all of the non-ancestors operation nodes of node. |
def unpack_weights(self, args):
"""Unpack fused weight matrices into separate
weight matrices.
For example, say you use a module object `mod` to run a network that has an lstm cell.
In `mod.get_params()[0]`, the lstm parameters are all represented as a single big vector.
`cell.u... | Unpack fused weight matrices into separate
weight matrices.
For example, say you use a module object `mod` to run a network that has an lstm cell.
In `mod.get_params()[0]`, the lstm parameters are all represented as a single big vector.
`cell.unpack_weights(mod.get_params()[0])` will un... |
def collect(self):
"""
Collect metrics from all registered metric sets
:return:
"""
logger.debug("Collecting metrics")
for name, metricset in compat.iteritems(self._metricsets):
data = metricset.collect()
if data:
self._queue_func(... | Collect metrics from all registered metric sets
:return: |
def validate_account_id(sts_client, account_id):
"""Exit if get_caller_identity doesn't match account_id."""
resp = sts_client.get_caller_identity()
if 'Account' in resp:
if resp['Account'] == account_id:
LOGGER.info('Verified current AWS account matches required '
... | Exit if get_caller_identity doesn't match account_id. |
def equivalent_diameter(target, pore_volume='pore.volume',
pore_shape='sphere'):
r"""
Calculates the diameter of a sphere or edge-length of a cube with same
volume as the pore.
Parameters
----------
target : OpenPNM Geometry Object
The Geometry object which this ... | r"""
Calculates the diameter of a sphere or edge-length of a cube with same
volume as the pore.
Parameters
----------
target : OpenPNM Geometry Object
The Geometry object which this model is associated with. This controls
the length of the calculated array, and also provides access ... |
def find_biconnected_components_as_subgraphs(graph):
"""Finds the biconnected components and returns them as subgraphs."""
list_of_graphs = []
list_of_components = find_biconnected_components(graph)
for edge_list in list_of_components:
subgraph = get_subgraph_from_edge_list(graph, edge_list)
... | Finds the biconnected components and returns them as subgraphs. |
def query_parameters(self):
"""
A key to list of values mapping of the query parameters seen in the
request.
"""
result = getattr(self, "_query_parameters", None)
if result is None:
result = self._query_parameters = normalize_query_parameters(
... | A key to list of values mapping of the query parameters seen in the
request. |
def distort(value):
"""
Distorts a string by randomly replacing characters in it.
:param value: a string to distort.
:return: a distored string.
"""
value = value.lower()
if (RandomBoolean.chance(1, 5)):
value = value[0:1].upper() + value[1:]
... | Distorts a string by randomly replacing characters in it.
:param value: a string to distort.
:return: a distored string. |
def build_query(spec):
""" build the where clause based on a view specification
spec -- The view specification. Contains the following possible values:
future -- Boolean; whether to include entries from the future
category -- Which category to limit to
recurse -- Whether to include subc... | build the where clause based on a view specification
spec -- The view specification. Contains the following possible values:
future -- Boolean; whether to include entries from the future
category -- Which category to limit to
recurse -- Whether to include subcategories
entry_type --... |
def is_descriptor_class(desc, include_abstract=False):
r"""Check calculatable descriptor class or not.
Returns:
bool
"""
return (
isinstance(desc, type)
and issubclass(desc, Descriptor)
and (True if include_abstract else not inspect.isabstract(desc))
) | r"""Check calculatable descriptor class or not.
Returns:
bool |
def incomplete(test_func):
"""The incomplete decorator behaves much like a normal skip; however,
tests that are marked as incomplete get tracked under a different metric.
This allows for you to create a skeleton around all of your features and
specifications, and track what tests have been written and w... | The incomplete decorator behaves much like a normal skip; however,
tests that are marked as incomplete get tracked under a different metric.
This allows for you to create a skeleton around all of your features and
specifications, and track what tests have been written and what
tests are left outstanding... |
def get_property_by_hash(self, property_hash: str) -> Optional[Property]:
"""Get a property by its hash if it exists."""
return self.session.query(Property).filter(Property.sha512 == property_hash).one_or_none() | Get a property by its hash if it exists. |
def _fix_slicing_order(self, outer_fields, inner_select, order, inner_table_name):
"""
Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing.
"""
# Using ROW_NUMBER requires an ordering
if order is None:
meta = self.quer... | Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing. |
def check_siblings(self, individual_1_id, individual_2_id):
"""
Check if two family members are siblings.
Arguments:
individual_1_id (str): The id of an individual
individual_2_id (str): The id of an individual
Returns:
bool : True ... | Check if two family members are siblings.
Arguments:
individual_1_id (str): The id of an individual
individual_2_id (str): The id of an individual
Returns:
bool : True if the individuals are siblings
False if they are not sibling... |
def load(self):
"""
Load the filter from the server
"""
# Attempt to load the saved filter
payload = {
'id': self.id
}
response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload)
self.response = response
json_respo... | Load the filter from the server |
def _get_per_location_glob(tasks, outputs, regexes):
"""
Builds a glob listing existing output paths.
Esoteric reverse engineering, but worth it given that (compared to an
equivalent contiguousness guarantee by naive complete() checks)
requests to the filesystem are cut by orders of magnitude, and ... | Builds a glob listing existing output paths.
Esoteric reverse engineering, but worth it given that (compared to an
equivalent contiguousness guarantee by naive complete() checks)
requests to the filesystem are cut by orders of magnitude, and users
don't even have to retrofit existing tasks anyhow. |
def _get_stream_id(comp_name, stream_id):
"""Returns a StreamId protobuf message"""
proto_stream_id = topology_pb2.StreamId()
proto_stream_id.id = stream_id
proto_stream_id.component_name = comp_name
return proto_stream_id | Returns a StreamId protobuf message |
def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
"""Post-fork() child callback for ProcessManager.daemon_spawn()."""
java = SubprocessExecutor(self._distribution)
subproc = java.spawn(classpath=classpath,
main='com.martiansoftware.nailgun.NGServer',
... | Post-fork() child callback for ProcessManager.daemon_spawn(). |
def save_xml(self, doc, element):
'''Save this participant into an xml.dom.Element object.'''
new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'Participant')
self.target_component.save_xml(doc, new_element)
element.appendChild(new_element) | Save this participant into an xml.dom.Element object. |
def remove_entry(data, entry):
'''
Remove an entry in place.
'''
file_field = entry['fields'].get('file')
if file_field:
try:
os.remove(file_field)
except IOError:
click.echo('This entry\'s file was missing')
data.remove(entry) | Remove an entry in place. |
def _actionsFreqsAngles(self,*args,**kwargs):
"""
NAME:
actionsFreqsAngles (_actionsFreqsAngles)
PURPOSE:
evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez)
INPUT:
Either:
a) R,vR,vT,z,vz[,... | NAME:
actionsFreqsAngles (_actionsFreqsAngles)
PURPOSE:
evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez)
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
1) floats: phase-space value for single obj... |
def lv_present(name,
vgname=None,
size=None,
extents=None,
snapshot=None,
pv='',
thinvolume=False,
thinpool=False,
force=False,
**kwargs):
'''
Create a new Logical Volume
n... | Create a new Logical Volume
name
The name of the Logical Volume
vgname
The name of the Volume Group on which the Logical Volume resides
size
The initial size of the Logical Volume
extents
The number of logical extents to allocate
snapshot
The name of the ... |
def pack_balance_proof_update(
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
canonical_identifier: CanonicalIdentifier,
partner_signature: Signature,
) -> bytes:
"""Packs balance proof data to be signed for updateNonClosingBalanceProof
Packs t... | Packs balance proof data to be signed for updateNonClosingBalanceProof
Packs the given arguments in a byte array in the same configuration the
contracts expect the signed data for updateNonClosingBalanceProof to have. |
def sentences(obj: BioCCollection or BioCDocument or BioCPassage) \
-> Generator[BioCSentence, None, None]:
"""
Get all sentences in document id.
Args:
obj: BioCCollection, BioCDocument, or BioCPassage
Yields:
one sentence
"""
if isinstance(obj, BioCCollectio... | Get all sentences in document id.
Args:
obj: BioCCollection, BioCDocument, or BioCPassage
Yields:
one sentence |
def real_main(release_url=None,
tests_json_path=None,
upload_build_id=None,
upload_release_name=None):
"""Runs diff_my_images."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
data = open(FLAGS.tests_json_pat... | Runs diff_my_images. |
def do_continue(self, args):
"""Continue the interpreter
"""
self._do_print_from_last_cmd = True
self._interp.cont()
return True | Continue the interpreter |
def queue_build(self, build, project, ignore_warnings=None, check_in_ticket=None, source_build_id=None):
"""QueueBuild.
Queues a build
:param :class:`<Build> <azure.devops.v5_0.build.models.Build>` build:
:param str project: Project ID or project name
:param bool ignore_warnings:... | QueueBuild.
Queues a build
:param :class:`<Build> <azure.devops.v5_0.build.models.Build>` build:
:param str project: Project ID or project name
:param bool ignore_warnings:
:param str check_in_ticket:
:param int source_build_id:
:rtype: :class:`<Build> <azure.devo... |
def __write_divider(self, top=False, bot=False, nl=True):
"""
Write a divider line
:return none:
"""
if top:
self.noaa_txt += "\n#"
if nl:
self.noaa_txt += "\n"
self.noaa_txt += "#------------------\n"
if bot:
self.noaa_... | Write a divider line
:return none: |
def load_mask(image, allow_empty=True):
"""Load a Nifti mask volume.
Parameters
----------
image: img-like object or boyle.nifti.NeuroImage or str
Can either be:
- a file path to a Nifti image
- any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
... | Load a Nifti mask volume.
Parameters
----------
image: img-like object or boyle.nifti.NeuroImage or str
Can either be:
- a file path to a Nifti image
- any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
If niimg is a string, consider it as a path... |
def refresh(self):
'''
Refresh the contents of the ``_updates`` collection. This gets all
updates in the Windows Update system and loads them into the collection.
This is the part that is slow.
Code Example:
.. code-block:: python
import salt.utils.win_upda... | Refresh the contents of the ``_updates`` collection. This gets all
updates in the Windows Update system and loads them into the collection.
This is the part that is slow.
Code Example:
.. code-block:: python
import salt.utils.win_update
wua = salt.utils.win_upd... |
def probabilities(self, choosers, alternatives):
"""
Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households... | Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
Must have a column matching the .segmentation_col attri... |
def computeEntropy(spikeTrains):
"""
Estimates entropy in spike trains.
@param spikeTrains (array) matrix of spike trains
@return entropy (float) entropy
"""
MIN_ACTIVATION_PROB = 0.000001
activationProb = np.mean(spikeTrains, 1)
activationProb[activationProb < MIN_ACTIVATION_PROB] = MIN_ACTIVATION_P... | Estimates entropy in spike trains.
@param spikeTrains (array) matrix of spike trains
@return entropy (float) entropy |
def get_pod_by_uid(uid, podlist):
"""
Searches for a pod uid in the podlist and returns the pod if found
:param uid: pod uid
:param podlist: podlist dict object
:return: pod dict object if found, None if not found
"""
for pod in podlist.get("items", []):
try:
if pod["meta... | Searches for a pod uid in the podlist and returns the pod if found
:param uid: pod uid
:param podlist: podlist dict object
:return: pod dict object if found, None if not found |
def get_kwargs(self):
"""Return kwargs dict for text"""
kwargs = {}
if self.font_face:
kwargs["fontname"] = repr(self.font_face)
if self.font_size:
kwargs["fontsize"] = repr(self.font_size)
if self.font_style in self.style_wx2mpl:
kwargs["fon... | Return kwargs dict for text |
def warn_attribs(loc,
node,
recognised_attribs,
reqd_attribs=None):
'''
Error checking of XML input: check that the given node has certain
required attributes, and does not have any unrecognised
attributes.
Arguments:
- `loc`: a string with som... | Error checking of XML input: check that the given node has certain
required attributes, and does not have any unrecognised
attributes.
Arguments:
- `loc`: a string with some information about the location of the
error in the XML file
- `node`: the node to check
- `recognised_attribs`: a s... |
def mechanism(self, x):
"""Mechanism function."""
layers = []
layers.append(th.nn.modules.Linear(self.n_causes+1, self.nh))
layers.append(th.nn.Tanh())
layers.append(th.nn.modules.Linear(self.nh, 1))
self.layers = th.nn.Sequential(*layers)
data = x.astype('floa... | Mechanism function. |
def appendcsv(table, source=None, encoding=None, errors='strict',
write_header=False, **csvargs):
"""
Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv`
but the file is opened in append mode and the table header is not written by
default.
Note that no attempt is ma... | Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv`
but the file is opened in append mode and the table header is not written by
default.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing data, the data rows from the table are simpl... |
def setup_contracts_or_exit(
config: Dict[str, Any],
network_id: int,
) -> Dict[str, Any]:
"""Sets the contract deployment data depending on the network id and environment type
If an invalid combination of network id and environment type is provided, exits
the program with an error
"""
... | Sets the contract deployment data depending on the network id and environment type
If an invalid combination of network id and environment type is provided, exits
the program with an error |
def showEvent(self, event):
""" Reimplemented to connect signal handlers and event filter.
"""
super(CompletionWidget, self).showEvent(event)
self._text_edit.cursorPositionChanged.connect(self._update_current)
self._text_edit.installEventFilter(self) | Reimplemented to connect signal handlers and event filter. |
def format_diffindex(diff_index):
"""
Return a JSON formattable representation of a DiffIndex.
Returns a generator that returns dictionaries representing the changes.
.. code::
[
{
'type': 'A',
'path': 'path/to/added/file.txt',
},
... | Return a JSON formattable representation of a DiffIndex.
Returns a generator that returns dictionaries representing the changes.
.. code::
[
{
'type': 'A',
'path': 'path/to/added/file.txt',
},
{
'type': 'D',
... |
def get_child(self, child_number, is_prime=None, as_private=True):
"""Derive a child key.
:param child_number: The number of the child key to compute
:type child_number: int
:param is_prime: If True, the child is calculated via private
derivation. If False, then public deriv... | Derive a child key.
:param child_number: The number of the child key to compute
:type child_number: int
:param is_prime: If True, the child is calculated via private
derivation. If False, then public derivation is used. If None,
then it is figured out from the value of c... |
def _get_replica_set_members(self, selector):
"""Return set of replica set member addresses."""
# Implemented here in Topology instead of MongoClient, so it can lock.
with self._lock:
topology_type = self._description.topology_type
if topology_type not in (TOPOLOGY_TYPE.R... | Return set of replica set member addresses. |
def append(self, listname, xy_idx, var_name, element_name):
"""Append variable names to the name lists"""
self.resize()
string = '{0} {1}'
if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']:
logger.error('Wrong list name for varname.')
return
elif... | Append variable names to the name lists |
def registerStatsHandler(app, serverName, prefix='/status/'):
"""Register the stats handler with a Flask app, serving routes
with a given prefix. The prefix defaults to '/status/', which is
generally what you want."""
if prefix[-1] != '/':
prefix += '/'
handler = functools.partial(statsHandler, serverName... | Register the stats handler with a Flask app, serving routes
with a given prefix. The prefix defaults to '/status/', which is
generally what you want. |
def get_labels(self, request_data, project=None, top=None, skip=None):
"""GetLabels.
Get a collection of shallow label references.
:param :class:`<TfvcLabelRequestData> <azure.devops.v5_0.tfvc.models.TfvcLabelRequestData>` request_data: labelScope, name, owner, and itemLabelFilter
:param... | GetLabels.
Get a collection of shallow label references.
:param :class:`<TfvcLabelRequestData> <azure.devops.v5_0.tfvc.models.TfvcLabelRequestData>` request_data: labelScope, name, owner, and itemLabelFilter
:param str project: Project ID or project name
:param int top: Max number of lab... |
def _initialize(self):
'''Performs a IPC protocol handshake.'''
credentials = (self.username if self.username else '') + ':' + (self.password if self.password else '')
credentials = credentials.encode(self._encoding)
self._connection.send(credentials + b'\3\0')
response = self._c... | Performs a IPC protocol handshake. |
def set_bulk_size(size):
"""Set size limit on bulk execution.
Bulk execution bundles many operators to run together.
This can improve performance when running a lot of small
operators sequentially.
Parameters
----------
size : int
Maximum number of operators that can be bundled in ... | Set size limit on bulk execution.
Bulk execution bundles many operators to run together.
This can improve performance when running a lot of small
operators sequentially.
Parameters
----------
size : int
Maximum number of operators that can be bundled in a bulk.
Returns
-------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.