positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def parse_nate_sims(path):
'''
parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return:
'''
... | parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return: |
def order_book(self, symbol, parameters=None):
"""
curl "https://api.bitfinex.com/v1/book/btcusd"
{"bids":[{"price":"561.1101","amount":"0.985","timestamp":"1395557729.0"}],"asks":[{"price":"562.9999","amount":"0.985","timestamp":"1395557711.0"}]}
The 'bids' and 'asks' arrays will have... | curl "https://api.bitfinex.com/v1/book/btcusd"
{"bids":[{"price":"561.1101","amount":"0.985","timestamp":"1395557729.0"}],"asks":[{"price":"562.9999","amount":"0.985","timestamp":"1395557711.0"}]}
The 'bids' and 'asks' arrays will have multiple bid and ask dicts.
Optional parameters
... |
def _cast_boolean(value):
"""
Helper to convert config values to boolean as ConfigParser do.
"""
_BOOLEANS = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False, '': False}
value = str(value)
if value.lower() not in _BOOLEANS:... | Helper to convert config values to boolean as ConfigParser do. |
def _set_vcenter(self, v, load=False):
"""
Setter method for vcenter, mapped from YANG variable /vcenter (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_vcenter is considered as a private
method. Backends looking to populate this variable should
do so via ... | Setter method for vcenter, mapped from YANG variable /vcenter (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_vcenter is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_vcenter() directly.
YANG ... |
def _to_dict_fixed_width_arrays(self, var_len_str=True):
"""A dict of arrays that stores data and annotation.
It is sufficient for reconstructing the object.
"""
self.strings_to_categoricals()
obs_rec, uns_obs = df_to_records_fixed_width(self._obs, var_len_str)
var_rec, ... | A dict of arrays that stores data and annotation.
It is sufficient for reconstructing the object. |
def _check_regr(self, regr, new_reg):
"""
Check that a registration response contains the registration we were
expecting.
"""
body = getattr(new_reg, 'body', new_reg)
for k, v in body.items():
if k == 'resource' or not v:
continue
i... | Check that a registration response contains the registration we were
expecting. |
def save_to_folders(self, parameter_space, folder_name, runs):
"""
Save results to a folder structure.
"""
self.space_to_folders(self.db.get_results(), {}, parameter_space, runs,
folder_name) | Save results to a folder structure. |
def step_context(self):
"""
Access the step_context
:returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList
:rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList
"""
if self._step_context is None:
self._step... | Access the step_context
:returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList
:rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList |
def sign(self,
consumer_secret,
access_token_secret,
method,
url,
oauth_params,
req_kwargs):
'''Sign request parameters.
:param consumer_secret: RSA private key.
:type consumer_secret: str or RSA._RSAobj
:para... | Sign request parameters.
:param consumer_secret: RSA private key.
:type consumer_secret: str or RSA._RSAobj
:param access_token_secret: Unused.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param url: The ... |
def get_central_wave(wavl, resp):
"""Calculate the central wavelength or the central wavenumber,
depending on what is input
"""
return np.trapz(resp * wavl, wavl) / np.trapz(resp, wavl) | Calculate the central wavelength or the central wavenumber,
depending on what is input |
def apply_subfield_projection(field, value, deep=False):
"""Apply projection from request context.
The passed dictionary may be mutated.
:param field: An instance of `Field` or `Serializer`
:type field: `Field` or `Serializer`
:param value: Dictionary to apply the projection to
:type value: di... | Apply projection from request context.
The passed dictionary may be mutated.
:param field: An instance of `Field` or `Serializer`
:type field: `Field` or `Serializer`
:param value: Dictionary to apply the projection to
:type value: dict
:param deep: Also process all deep projections
:type ... |
def GetLinkedFileEntry(self):
"""Retrieves the linked file entry, e.g. for a symbolic link.
Returns:
TSKFileEntry: linked file entry or None.
"""
link = self._GetLink()
if not link:
return None
# TODO: is there a way to determine the link inode number here?
link_inode = None
... | Retrieves the linked file entry, e.g. for a symbolic link.
Returns:
TSKFileEntry: linked file entry or None. |
def _forney(self, omega, X):
'''Computes the error magnitudes. Works also with erasures and errors+erasures beyond the (n-k)//2 bound, here the bound is 2*e+v <= (n-k-1) with e the number of errors and v the number of erasures.'''
# XXX Is floor division okay here? Should this be ceiling?
Y = [... | Computes the error magnitudes. Works also with erasures and errors+erasures beyond the (n-k)//2 bound, here the bound is 2*e+v <= (n-k-1) with e the number of errors and v the number of erasures. |
def __convertIp6PrefixStringToIp6Address(self, strIp6Prefix):
"""convert IPv6 prefix string to IPv6 dotted-quad format
for example:
2001000000000000 -> 2001::
Args:
strIp6Prefix: IPv6 address string
Returns:
IPv6 address dotted-quad format
... | convert IPv6 prefix string to IPv6 dotted-quad format
for example:
2001000000000000 -> 2001::
Args:
strIp6Prefix: IPv6 address string
Returns:
IPv6 address dotted-quad format |
def find(self, id, **kwargs):
"""
Finds a record by its id in the model's table in the replica database.
:returns: an instance of the model.
"""
return self.find_by(values={self.primary_key: id}, **kwargs) | Finds a record by its id in the model's table in the replica database.
:returns: an instance of the model. |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`Payment`.
"""
asset = self.asset.to_xdr_object()
destination = account_xdr_object(self.destination)
amount = Operation.to_xdr_amount(self.amount)
payment_op = Xdr.types.Pay... | Creates an XDR Operation object that represents this
:class:`Payment`. |
def shell(self, command, *args, environment=None):
"""
Runs a shell command
"""
command += ' ' + ' '.join(args)
command = command.strip()
self.debug(self.yellow_style('$ %s' % command))
env = self.env.copy()
env.update(environment or {})
return sub... | Runs a shell command |
def log_source(self, loglevel='INFO'):
"""Logs and returns the entire html source of the current page or frame.
The `loglevel` argument defines the used log level. Valid log levels are
`WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging).
"""
ll = loglevel.up... | Logs and returns the entire html source of the current page or frame.
The `loglevel` argument defines the used log level. Valid log levels are
`WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging). |
def angle(vec1, vec2):
"""Calculate the angle between two Vector2's"""
dotp = Vector2.dot(vec1, vec2)
mag1 = vec1.length()
mag2 = vec2.length()
result = dotp / (mag1 * mag2)
return math.acos(result) | Calculate the angle between two Vector2's |
def _get_additional_options(runtime, debug_options):
"""
Return additional Docker container options. Used by container debug mode to enable certain container
security options.
:param DebugContext debug_options: DebugContext for the runtime of the container.
:return dict: Dictiona... | Return additional Docker container options. Used by container debug mode to enable certain container
security options.
:param DebugContext debug_options: DebugContext for the runtime of the container.
:return dict: Dictionary containing additional arguments to be passed to container creation. |
def get_embedded_object(self, signature_id):
''' Retrieves a embedded signing object
Retrieves an embedded object containing a signature url that can be opened in an iFrame.
Args:
signature_id (str): The id of the signature to get a signature url for
Returns:
... | Retrieves a embedded signing object
Retrieves an embedded object containing a signature url that can be opened in an iFrame.
Args:
signature_id (str): The id of the signature to get a signature url for
Returns:
An Embedded object |
def read_file(self):
'''load config from local file'''
if os.path.exists(self.experiment_file):
try:
with open(self.experiment_file, 'r') as file:
return json.load(file)
except ValueError:
return {}
return {} | load config from local file |
def to_rst(cls) -> str:
"""Output the registry as reStructuredText, for documentation."""
sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n'
blank_line = '|' + 78 * ' ' + '|\n'
table = ''
for group in cls.groups:
table += sep_line
table += blank_line
... | Output the registry as reStructuredText, for documentation. |
def can_use_cache(self, target: Target) -> bool:
"""Return True if should attempt to load `target` from cache.
Return False if `target` has to be built, regardless of its cache
status (because cache is disabled, or dependencies are dirty).
"""
# if caching is disabled for t... | Return True if should attempt to load `target` from cache.
Return False if `target` has to be built, regardless of its cache
status (because cache is disabled, or dependencies are dirty). |
def cli(ctx, list, dir, files, project_dir, sayno):
"""Manage verilog examples.\n
Install with `apio install examples`"""
exit_code = 0
if list:
exit_code = Examples().list_examples()
elif dir:
exit_code = Examples().copy_example_dir(dir, project_dir, sayno)
elif files:
... | Manage verilog examples.\n
Install with `apio install examples` |
def follower_num(self):
"""获取问题关注人数.
:return: 问题关注人数
:rtype: int
"""
follower_num_block = self.soup.find('div', class_='zg-gray-normal')
# 无人关注时 找不到对应block,直接返回0 (感谢知乎用户 段晓晨 提出此问题)
if follower_num_block is None or follower_num_block.strong is None:
re... | 获取问题关注人数.
:return: 问题关注人数
:rtype: int |
def IntegerMax(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Finds the maximum between two vertices
:param left: one of the vertices to find the maximum of
:param right: one of the vertices to find the maximum of
"""
r... | Finds the maximum between two vertices
:param left: one of the vertices to find the maximum of
:param right: one of the vertices to find the maximum of |
def _xpath_to_dict(self, element, property_map, namespace_map):
"""
property_map = {
u'name' : { u'xpath' : u't:Mailbox/t:Name'},
u'email' : { u'xpath' : u't:Mailbox/t:EmailAddress'},
u'response' : { u'xpath' : u't:ResponseType'},
u'last_response': { u'xpath' : u't:Las... | property_map = {
u'name' : { u'xpath' : u't:Mailbox/t:Name'},
u'email' : { u'xpath' : u't:Mailbox/t:EmailAddress'},
u'response' : { u'xpath' : u't:ResponseType'},
u'last_response': { u'xpath' : u't:LastResponseTime', u'cast': u'datetime'},
}
This runs the given xpath ... |
def emit(self, record):
"""
Function inserts log messages to list_view
"""
msg = record.getMessage()
list_store = self.list_view.get_model()
Gdk.threads_enter()
if msg:
# Underline URLs in the record message
msg = replace_markup_chars(recor... | Function inserts log messages to list_view |
def _get_parameter(self, name, tp, timeout=1.0, max_retries=2):
""" Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to chec... | Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to check. It is always the command to
set it but without the value.
... |
def list(self, request, *args, **kwargs):
"""
To get a list of alerts, run **GET** against */api/alerts/* as authenticated user.
Alert severity field can take one of this values: "Error", "Warning", "Info", "Debug".
Field scope will contain link to object that cause alert.
Conte... | To get a list of alerts, run **GET** against */api/alerts/* as authenticated user.
Alert severity field can take one of this values: "Error", "Warning", "Info", "Debug".
Field scope will contain link to object that cause alert.
Context - dictionary that contains information about all related to... |
def dipole(src, rec, depth, res, freqtime, signal=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='fht', htarg=None, ft='sin', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the electromagnetic field due to a dipole source.
C... | r"""Return the electromagnetic field due to a dipole source.
Calculate the electromagnetic frequency- or time-domain field due to
infinitesimal small electric or magnetic dipole source(s), measured by
infinitesimal small electric or magnetic dipole receiver(s); sources and
receivers are directed along ... |
def get(self, key, default=None):
"""Gets config from dynaconf variables
if variables does not exists in dynaconf try getting from
`app.config` to support runtime settings."""
return self._settings.get(key, Config.get(self, key, default)) | Gets config from dynaconf variables
if variables does not exists in dynaconf try getting from
`app.config` to support runtime settings. |
def drag(self, NewPt):
# //Mouse drag, calculate rotation (Point2fT Quat4fT)
""" drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec
"""
X = 0
Y = 1
Z = 2
W = 3
self.m_EnVec = self._mapToSphere(NewPt)
# //Compute the vector perpendicular t... | drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec |
def delete(self, request, *args, **kwargs):
"""
Calls the delete() method on the fetched object and then
redirects to the success URL.
"""
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
if self.request.is_ajax():... | Calls the delete() method on the fetched object and then
redirects to the success URL. |
def get_default_config_help(self):
"""
Return help text for collector configuration
"""
config_help = super(ConnTrackCollector, self).get_default_config_help()
config_help.update({
"dir": "Directories with files of interest, comma seperated",
"files":... | Return help text for collector configuration |
def get_payment_token_by_id(cls, payment_token_id, **kwargs):
"""Find PaymentToken
Return single instance of PaymentToken by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_payment... | Find PaymentToken
Return single instance of PaymentToken by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_payment_token_by_id(payment_token_id, async=True)
>>> result = thread.ge... |
def _get_meta(model):
"""Return metadata of a model.
Model could be a real model or evaluated metadata."""
if isinstance(model, Model):
w = model.meta
else:
w = model # Already metadata
return w | Return metadata of a model.
Model could be a real model or evaluated metadata. |
def parse_dmidecode(dmidecode_content, pythonic_keys=False):
"""
Returns a dictionary of dmidecode information parsed from a dmidecode list
(i.e. from context.content)
This method will attempt to handle leading spaces rather than tabs.
"""
if len(dmidecode_content) < 3:
return {}
s... | Returns a dictionary of dmidecode information parsed from a dmidecode list
(i.e. from context.content)
This method will attempt to handle leading spaces rather than tabs. |
def graph_impl(self, run, tag, is_conceptual, limit_attr_size=None, large_attrs_key=None):
"""Result of the form `(body, mime_type)`, or `None` if no graph exists."""
if is_conceptual:
tensor_events = self._multiplexer.Tensors(run, tag)
# Take the first event if there are multiple events written fro... | Result of the form `(body, mime_type)`, or `None` if no graph exists. |
def PopEvent(self):
"""Pops an event from the heap.
Returns:
tuple: containing:
str: identifier of the event MACB group or None if the event cannot
be grouped.
str: identifier of the event content.
EventObject: event.
"""
try:
macb_group_identifier, cont... | Pops an event from the heap.
Returns:
tuple: containing:
str: identifier of the event MACB group or None if the event cannot
be grouped.
str: identifier of the event content.
EventObject: event. |
def notes(self):
"""*list of the notes assoicated with this object*
**Usage:**
The document, project and task objects can all contain notes.
.. code-block:: python
docNotes = doc.notes
projectNotes = aProject.notes
taskNotes = a... | *list of the notes assoicated with this object*
**Usage:**
The document, project and task objects can all contain notes.
.. code-block:: python
docNotes = doc.notes
projectNotes = aProject.notes
taskNotes = aTask.notes |
def get(self, name):
""" Looks for a name in the path.
:param name: file name
:return: path to the file
"""
for d in self.paths:
if os.path.exists(d) and name in os.listdir(d):
return os.path.join(d, name)
logger.debug('File not found {}'.for... | Looks for a name in the path.
:param name: file name
:return: path to the file |
def mangle(tree, toplevel=False):
"""Mangle names.
Args:
toplevel: defaults to False. Defines if global
scope should be mangled or not.
"""
sym_table = SymbolTable()
visitor = ScopeTreeVisitor(sym_table)
visitor.visit(tree)
fill_scope_references(tree)
mangle_scope_tree(... | Mangle names.
Args:
toplevel: defaults to False. Defines if global
scope should be mangled or not. |
def to_representation(self, obj):
""" convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe type... | convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact.
NB: The argument is whole o... |
def get_rate_limit(self):
"""
Rate limit status for different resources (core/search/graphql).
:calls: `GET /rate_limit <http://developer.github.com/v3/rate_limit>`_
:rtype: :class:`github.RateLimit.RateLimit`
"""
headers, data = self.__requester.requestJsonAndCheck(
... | Rate limit status for different resources (core/search/graphql).
:calls: `GET /rate_limit <http://developer.github.com/v3/rate_limit>`_
:rtype: :class:`github.RateLimit.RateLimit` |
def getList(self, dummy = 56184, orgresource = '/', type = 1, dept = 0, sort = 'name', order = 'asc', startnum = 0, pagingrow = 1000):
"""GetList
Args:
dummy: ???
orgresource: Directory path to get the file list
ex) /Picture/
type: 1 => only director... | GetList
Args:
dummy: ???
orgresource: Directory path to get the file list
ex) /Picture/
type: 1 => only directories with idxfolder property
2 => only files
3 => directories and files with thumbnail info
... |
def has_no_narrow_start(neuron, frac=0.9):
'''Check if neurites have a narrow start
Arguments:
neuron(Neuron): The neuron object to test
frac(float): Ratio that the second point must be smaller than the first
Returns:
CheckResult with a list of all first segments of neurites with a... | Check if neurites have a narrow start
Arguments:
neuron(Neuron): The neuron object to test
frac(float): Ratio that the second point must be smaller than the first
Returns:
CheckResult with a list of all first segments of neurites with a narrow start |
def get_config_from_file(conf_properties_files):
"""Reads properties files and saves them to a config object
:param conf_properties_files: comma-separated list of properties files
:returns: config object
"""
# Initialize the config object
config = ExtendedConfigParser()
... | Reads properties files and saves them to a config object
:param conf_properties_files: comma-separated list of properties files
:returns: config object |
def decode_from_file(estimator,
filename,
hparams,
decode_hp,
decode_to_file=None,
checkpoint_path=None):
"""Compute predictions on entries in filename and write them out."""
if not decode_hp.batch_size:
dec... | Compute predictions on entries in filename and write them out. |
def _set_receive(self, v, load=False):
"""
Setter method for receive, mapped from YANG variable /routing_system/ipv6/receive (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_receive is considered as a private
method. Backends looking to populate this varia... | Setter method for receive, mapped from YANG variable /routing_system/ipv6/receive (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_receive is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_recei... |
async def clean_up_clients_async(self):
"""
Resets the pump swallows all exceptions.
"""
if self.partition_receiver:
if self.eh_client:
await self.eh_client.stop_async()
self.partition_receiver = None
self.partition_receive_hand... | Resets the pump swallows all exceptions. |
def get_labels(self):
"""
Returns a list of strings representing the values about
which the discretization method calculates the probabilty
masses.
Default value is the points -
[low, low+step, low+2*step, ......... , high-step]
unless the method is overridden by... | Returns a list of strings representing the values about
which the discretization method calculates the probabilty
masses.
Default value is the points -
[low, low+step, low+2*step, ......... , high-step]
unless the method is overridden by a subclass.
Examples
---... |
def _bsd_bradd(br):
'''
Internal, creates the bridge
'''
kernel = __grains__['kernel']
ifconfig = _tool_path('ifconfig')
if not br:
return False
if __salt__['cmd.retcode']('{0} {1} create up'.format(ifconfig, br),
python_shell=False) != 0:
ret... | Internal, creates the bridge |
def grant_privilege(self, privilege, database, username):
"""Grant a privilege on a database to a user.
:param privilege: the privilege to grant, one of 'read', 'write'
or 'all'. The string is case-insensitive
:type privilege: str
:param database: the database to grant the p... | Grant a privilege on a database to a user.
:param privilege: the privilege to grant, one of 'read', 'write'
or 'all'. The string is case-insensitive
:type privilege: str
:param database: the database to grant the privilege on
:type database: str
:param username: the ... |
def main():
"""Core function for the script"""
commands = ['update', 'list', 'get', 'info', 'count', 'search', 'download']
parser = argparse.ArgumentParser(description="Command line access to software repositories for TI calculators, primarily ticalc.org and Cemetech")
parser.add_argument("action", metavar="ACTION"... | Core function for the script |
def _tls_aead_auth_decrypt(alg, c, read_seq_num):
"""
Provided with a TLSCiphertext instance c, the function applies AEAD
cipher alg auth_decrypt function to c.data (and additional data)
in order to authenticate the data and decrypt c.data. When those
steps succeed, the result is a newly created TLS... | Provided with a TLSCiphertext instance c, the function applies AEAD
cipher alg auth_decrypt function to c.data (and additional data)
in order to authenticate the data and decrypt c.data. When those
steps succeed, the result is a newly created TLSCompressed instance.
On error, None is returned. Note that... |
def smoothed(mesh, angle):
"""
Return a non- watertight version of the mesh which will
render nicely with smooth shading by disconnecting faces
at sharp angles to each other.
Parameters
---------
mesh : trimesh.Trimesh
Source geometry
angle : float
Angle in radians, adjacent... | Return a non- watertight version of the mesh which will
render nicely with smooth shading by disconnecting faces
at sharp angles to each other.
Parameters
---------
mesh : trimesh.Trimesh
Source geometry
angle : float
Angle in radians, adjacent faces which have normals
below t... |
def where_entry_visible(query, date=None):
""" Generate a where clause for currently-visible entries
Arguments:
date -- The date to generate it relative to (defaults to right now)
"""
return orm.select(
e for e in query
if e.status == model.PublishStatus.PUBLISHED.value or
... | Generate a where clause for currently-visible entries
Arguments:
date -- The date to generate it relative to (defaults to right now) |
def __create_log_props(cls, log_props, _getdict, _setdict): # @NoSelf
"""Creates all the logical property.
The list of names of properties to be created is passed
with frozenset log_props. The getter/setter information is
taken from _{get,set}dict.
This method resolves also wi... | Creates all the logical property.
The list of names of properties to be created is passed
with frozenset log_props. The getter/setter information is
taken from _{get,set}dict.
This method resolves also wildcards in names, and performs
all checks to ensure correctness.
... |
def finish(self):
""" Resets the progress bar and clears it from the terminal """
pct = floor(round(self.progress/self.size, 2)*100)
pr = floor(pct*.33)
bar = "".join([" " for x in range(pr-1)] + ["↦"])
subprogress = self.format_parent_bar() if self.parent_bar else ""
fin... | Resets the progress bar and clears it from the terminal |
def build_path(operation, ns):
"""
Build a path URI for an operation.
"""
try:
return ns.url_for(operation, _external=False)
except BuildError as error:
# we are missing some URI path parameters
uri_templates = {
argument: "{{{}}}".format(argument)
fo... | Build a path URI for an operation. |
def hierarchy_cycles(rdf, fix=False):
"""Check if the graph contains skos:broader cycles and optionally break these.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing any skos:broader that overlaps
with skos:broaderTransitive.
"""
top_concepts = so... | Check if the graph contains skos:broader cycles and optionally break these.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing any skos:broader that overlaps
with skos:broaderTransitive. |
def confusion_matrix(y_true, y_pred, target_names=None, normalize=False,
cmap=None, ax=None):
"""
Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_pred : array-like, shape = [n_samples]
... | Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_pred : array-like, shape = [n_samples]
Target predicted classes (estimator predictions).
target_names : list
List containing the names of the target... |
def get_json_from_remote_server(func, **kwargs):
"""
Safely manage calls to the remote server by encapsulating JSON creation
from Piwik data.
"""
rawjson = func(**kwargs)
if rawjson is None:
# If the request failed we already logged in in PiwikRequest;
# no need to get into the e... | Safely manage calls to the remote server by encapsulating JSON creation
from Piwik data. |
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--vmname', '-n', required=True, action='store', help='Name')
arg_parser.add_argument('--rgname', '-g', required=True, action='store',
help='R... | Main routine. |
def get_table_description(self, cursor, table_name, identity_check=True):
"""Returns a description of the table, with DB-API cursor.description interface.
The 'auto_check' parameter has been added to the function argspec.
If set to True, the function will check each of the table's fields for th... | Returns a description of the table, with DB-API cursor.description interface.
The 'auto_check' parameter has been added to the function argspec.
If set to True, the function will check each of the table's fields for the
IDENTITY property (the IDENTITY property is the MSSQL equivalent to an Auto... |
def _autocomplete(client, url_part, input_text, session_token=None,
offset=None, location=None, radius=None, language=None,
types=None, components=None, strict_bounds=False):
"""
Internal handler for ``autocomplete`` and ``autocomplete_query``.
See each method's docs for ... | Internal handler for ``autocomplete`` and ``autocomplete_query``.
See each method's docs for arg details. |
def _send_byte(self,value):
"""
Convert a numerical value into an integer, then to a byte object. Check
bounds for byte.
"""
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_value = i... | Convert a numerical value into an integer, then to a byte object. Check
bounds for byte. |
def __update(self, sym, item, metadata=None, combine_method=None, chunk_range=None, audit=None):
'''
helper method used by update and append since they very closely
resemble eachother. Really differ only by the combine method.
append will combine existing date with new data (within a chu... | helper method used by update and append since they very closely
resemble eachother. Really differ only by the combine method.
append will combine existing date with new data (within a chunk),
whereas update will replace existing data with new data (within a
chunk). |
def vlan_classifier_group_rule_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan")
classifier = ET.SubElement(vlan, "classifier")
group = ET.SubElement(classifier, "... | Auto Generated Code |
def parse(data, eventer):
"""Parse the XML data, firing events from the eventer"""
parser = etree.XMLParser(target=ODMTargetParser(eventer))
return etree.XML(data, parser) | Parse the XML data, firing events from the eventer |
def _drawContents(self, currentRti=None):
""" Draws the attributes of the currentRTI
"""
#logger.debug("_drawContents: {}".format(currentRti))
table = self.table
table.setUpdatesEnabled(False)
try:
table.clearContents()
verticalHeader = table.verti... | Draws the attributes of the currentRTI |
def tile(ctx, point, zoom):
"""Print Tile containing POINT.."""
tile = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile_from_xy(*point, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
click.echo('%s %s %s' % tile.id)
... | Print Tile containing POINT.. |
def directp(node0, node1, node2, node3, hypocenter, reference, pp):
"""
Get the Direct Point and the corresponding E-path as described in
Spudich et al. (2013). This method also provides a logical variable
stating if the DPP calculation must consider the neighbouring patch.
To define the intersectio... | Get the Direct Point and the corresponding E-path as described in
Spudich et al. (2013). This method also provides a logical variable
stating if the DPP calculation must consider the neighbouring patch.
To define the intersection point(Pd) of PpPh line segment and fault plane,
we obtain the intersection... |
def accumulate(iterable):
" Return series of accumulated sums. "
iterator = iter(iterable)
sum_data = next(iterator)
yield sum_data
for el in iterator:
sum_data += el
yield sum_data | Return series of accumulated sums. |
def _generate_solution(self):
"""Return a single random solution."""
return common.random_real_solution(
self._solution_size, self._lower_bounds, self._upper_bounds) | Return a single random solution. |
def register_target(self, target: Target):
"""Register a `target` instance in this build context.
A registered target is saved in the `targets` map and in the
`targets_by_module` map, but is not added to the target graph until
target extraction is completed (thread safety considerations... | Register a `target` instance in this build context.
A registered target is saved in the `targets` map and in the
`targets_by_module` map, but is not added to the target graph until
target extraction is completed (thread safety considerations). |
def multi_raw(query, params, models, model_to_fields):
"""Scoop multiple model instances out of the DB at once, given a query that
returns all fields of each.
Return an iterable of sequences of model instances parallel to the
``models`` sequence of classes. For example::
[(<User such-and-such>... | Scoop multiple model instances out of the DB at once, given a query that
returns all fields of each.
Return an iterable of sequences of model instances parallel to the
``models`` sequence of classes. For example::
[(<User such-and-such>, <Watch such-and-such>), ...] |
def process_resource(self, req, resp, resource, uri_kwargs=None):
"""Process resource after routing to it.
This is basic falcon middleware handler.
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
resource (object): resource... | Process resource after routing to it.
This is basic falcon middleware handler.
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
resource (object): resource object matched by falcon router
uri_kwargs (dict): additional ke... |
def create_backends_from_settings(self):
"""
Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point
to a dictionary of backend engine configurations.
Example::
EVENT_TRACKING_BACKENDS = {
'default': {
'ENGINE': 'some... | Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point
to a dictionary of backend engine configurations.
Example::
EVENT_TRACKING_BACKENDS = {
'default': {
'ENGINE': 'some.arbitrary.Backend',
'OPTIONS': {
... |
def write(gmt, out_path):
""" Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None
"""
with open(out_path, 'w') as f:
for _, each_dict in enumerate(gmt):
f.write(each_dict[SET_IDENTIFIER_FIELD] +... | Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None |
def tnr(y_true, y_pred, round=True):
"""True negative rate `tn / (tn + fp)`
"""
y_true, y_pred = _mask_value_nan(y_true, y_pred)
if round:
y_true = np.round(y_true)
y_pred = np.round(y_pred)
c = skm.confusion_matrix(y_true, y_pred)
return c[0, 0] / c[0].sum() | True negative rate `tn / (tn + fp)` |
def initialTrendSmoothingFactors(self, timeSeries):
""" Calculate the initial Trend smoothing Factor b0.
Explanation:
http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing
:return: Returns the initial trend smoothing factor b0
"""
result... | Calculate the initial Trend smoothing Factor b0.
Explanation:
http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing
:return: Returns the initial trend smoothing factor b0 |
def getSaveFileName(self, *args, **kwargs):
"""
analogue to QtWidgets.QFileDialog.getSaveFileNameAndFilter
but returns the filename + chosen file ending even if not typed in gui
"""
if 'directory' not in kwargs:
if self.opts['save']:
if self.opts['save... | analogue to QtWidgets.QFileDialog.getSaveFileNameAndFilter
but returns the filename + chosen file ending even if not typed in gui |
def jsonp_wrap(callback_key='callback'):
"""
Format response to jsonp and add a callback to JSON data - a jsonp request
"""
def decorator_fn(f):
@wraps(f)
def jsonp_output_decorator(*args, **kwargs):
task_data = _get_data_from_args(args)
data = task_data.get_dat... | Format response to jsonp and add a callback to JSON data - a jsonp request |
def plot(self):
"""
Sets the internal databox to the supplied value and plots it.
If databox=None, this will plot the internal databox.
"""
# if we're disabled or have no data columns, clear everything!
if not self.button_enabled.is_checked() or len(self) == 0:
... | Sets the internal databox to the supplied value and plots it.
If databox=None, this will plot the internal databox. |
def resample(input_data, ratio, converter_type='sinc_best', verbose=False):
"""Resample the signal in `input_data` at once.
Parameters
----------
input_data : ndarray
Input data. A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is repre... | Resample the signal in `input_data` at once.
Parameters
----------
input_data : ndarray
Input data. A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is represented as a 2D array of shape
(`num_frames`, `num_channels`). For use with ... |
def _setupTable_hhea_or_vhea(self, tag):
"""
Make the hhea table or the vhea table. This assume the hmtx or
the vmtx were respectively made first.
"""
if tag not in self.tables:
return
if tag == "hhea":
isHhea = True
else:
isHh... | Make the hhea table or the vhea table. This assume the hmtx or
the vmtx were respectively made first. |
def get(url):
"""
USE json.net CONVENTIONS TO LINK TO INLINE OTHER JSON
"""
url = text_type(url)
if url.find("://") == -1:
Log.error("{{url}} must have a prototcol (eg http://) declared", url=url)
base = URL("")
if url.startswith("file://") and url[7] != "/":
if os.sep=="\\"... | USE json.net CONVENTIONS TO LINK TO INLINE OTHER JSON |
def filter_by_IDs(self, ids, ID=None):
"""
Keep only Measurements with given IDs.
"""
fil = lambda x: x in ids
return self.filter_by_attr('ID', fil, ID) | Keep only Measurements with given IDs. |
def observable(operator, rho, unfolding, complex=False):
r"""Return an observable ammount.
INPUT:
- ``operator`` - An square matrix representing a hermitian operator \
in thesame basis as the density matrix.
- ``rho`` - A density matrix in unfolded format, or a list of such \
density matrice... | r"""Return an observable ammount.
INPUT:
- ``operator`` - An square matrix representing a hermitian operator \
in thesame basis as the density matrix.
- ``rho`` - A density matrix in unfolded format, or a list of such \
density matrices.
- ``unfolding`` - A mapping from matrix element indic... |
def on_get(self, req, resp):
"""
Send a GET request to get the list of all available network interfaces
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# connect to docker
try:
d_client = docker.from_env()
except Except... | Send a GET request to get the list of all available network interfaces |
def setup_hds(self):
""" setup modflow head save file observations for given kper (zero-based
stress period index) and k (zero-based layer index) pairs using the
kperk argument.
Note
----
this can setup a shit-ton of observations
this is useful for dataw... | setup modflow head save file observations for given kper (zero-based
stress period index) and k (zero-based layer index) pairs using the
kperk argument.
Note
----
this can setup a shit-ton of observations
this is useful for dataworth analyses or for monitoring
... |
def build_marshmallow_field(self, **kwargs):
"""
:return: The Marshmallow Field instanciated and configured
"""
field_kwargs = None
for param in self.params:
field_kwargs = param.apply(field_kwargs)
field_kwargs.update(kwargs)
return self.marshmallow_f... | :return: The Marshmallow Field instanciated and configured |
def serialize(self, buffer=bytearray(), index=Index(), **options):
""" Serializes the `Field` to the byte *buffer* starting at the begin
of the *buffer* or with the given *index* by packing the :attr:`value`
of the `Field` to the byte *buffer* in accordance with the encoding
*byte order*... | Serializes the `Field` to the byte *buffer* starting at the begin
of the *buffer* or with the given *index* by packing the :attr:`value`
of the `Field` to the byte *buffer* in accordance with the encoding
*byte order* for the serialization and the encoding :attr:`byte_order`
of the `Fiel... |
def list_(bank, cachedir):
'''
Return an iterable object containing all entries stored in the specified bank.
'''
base = os.path.join(cachedir, os.path.normpath(bank))
if not os.path.isdir(base):
return []
try:
items = os.listdir(base)
except OSError as exc:
raise Sal... | Return an iterable object containing all entries stored in the specified bank. |
def mag_roll(RAW_IMU, inclination, declination):
'''estimate roll from mag'''
m = mag_rotation(RAW_IMU, inclination, declination)
(r, p, y) = m.to_euler()
return degrees(r) | estimate roll from mag |
def load_dockercfg(self):
"""
:return:
"""
if self.ssl_cert_path:
self._validate_ssl_certs()
if self.auth_type == 'registry_rubber':
self.user, self.passwd = self._registry_rubber_uonce('add')
self._config_path = self._create_dockercfg(
... | :return: |
def main():
""" Main function"""
parser = argparse.ArgumentParser(description='JSON Web Key (JWK) Generator')
parser.add_argument('--kty',
dest='kty',
metavar='type',
help='Key type',
required=True)
parser.a... | Main function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.