code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def set_command(value, parameter):
"""
Executor for `globus config set`
"""
conf = get_config_obj()
section = "cli"
if "." in parameter:
section, parameter = parameter.split(".", 1)
# ensure that the section exists
if section not in conf:
conf[section] = {}
# set th... | Executor for `globus config set` |
def splitAt(iterable, indices):
r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4],... | r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]] |
def send(self):
"""
Sends all the key-value pairs to the graphics card.
These uniform variables will be available in the currently-bound shader.
"""
for name, array in iteritems(self):
shader_id = c_int(0)
gl.glGetIntegerv(gl.GL_CURRENT_PROGRAM, byref(sh... | Sends all the key-value pairs to the graphics card.
These uniform variables will be available in the currently-bound shader. |
def split(url):
"""Split URL into scheme, netloc, path, query and fragment.
>>> split('http://www.example.com/abc?x=1&y=2#foo')
SplitResult(scheme='http', netloc='www.example.com', path='/abc', query='x=1&y=2', fragment='foo')
"""
scheme = netloc = path = query = fragment = ''
ip6_start = url.f... | Split URL into scheme, netloc, path, query and fragment.
>>> split('http://www.example.com/abc?x=1&y=2#foo')
SplitResult(scheme='http', netloc='www.example.com', path='/abc', query='x=1&y=2', fragment='foo') |
def parse(self, element):
"""Parses the contents of the specified XML element using template info.
:arg element: the XML element from the input file being converted.
"""
result = []
if element.text is not None and element.tag == self.identifier:
l, k = (0, 0)
... | Parses the contents of the specified XML element using template info.
:arg element: the XML element from the input file being converted. |
def rotate_vector(evecs, old_vector, rescale_factor, index):
"""
Function to find the position of the system(s) in one of the xi_i or mu_i
directions.
Parameters
-----------
evecs : numpy.matrix
Matrix of the eigenvectors of the metric in lambda_i coordinates. Used
to rotate to ... | Function to find the position of the system(s) in one of the xi_i or mu_i
directions.
Parameters
-----------
evecs : numpy.matrix
Matrix of the eigenvectors of the metric in lambda_i coordinates. Used
to rotate to a Cartesian coordinate system.
old_vector : list of floats or numpy.a... |
def init(self):
"""Init the connection to the CouchDB server."""
if not self.export_enable:
return None
if self.user is None:
server_uri = 'http://{}:{}/'.format(self.host,
self.port)
else:
server_uri = ... | Init the connection to the CouchDB server. |
def run_git(self, args, git_env=None):
'''
Runs the git executable with the arguments given and returns a list of
lines produced on its standard output.
'''
popen_kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
}
if git_e... | Runs the git executable with the arguments given and returns a list of
lines produced on its standard output. |
def download_sample(job, ids, input_args, sample):
"""
Defines variables unique to a sample that are used in the rest of the pipelines
ids: dict Dictionary of fileStore IDS
input_args: dict Dictionary of input arguments
sample: tuple Contains uuid and sample_url
"""
if le... | Defines variables unique to a sample that are used in the rest of the pipelines
ids: dict Dictionary of fileStore IDS
input_args: dict Dictionary of input arguments
sample: tuple Contains uuid and sample_url |
def _z2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_z2deriv
PURPOSE:
evaluate the second vertical derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t- time
OUTP... | NAME:
_z2deriv
PURPOSE:
evaluate the second vertical derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t- time
OUTPUT:
the second vertical derivative
HI... |
def _println(self, *args):
'''Convenience function for the print function.'''
string = ' '.join([str(arg) for arg in args])
print(string, file=self._stream) | Convenience function for the print function. |
def close(self):
"""
Ensure that all spans from the queue are submitted.
Returns Future that will be completed once the queue is empty.
"""
with self.stop_lock:
self.stopped = True
return ioloop_util.submit(self._flush, io_loop=self.io_loop) | Ensure that all spans from the queue are submitted.
Returns Future that will be completed once the queue is empty. |
def exchange_declare(self, exchange, type, passive=False, durable=False,
auto_delete=True, internal=False, nowait=False,
arguments=None, ticket=None):
"""
declare exchange, create if needed
This method creates an exchange if it does not already exist,
and if the exchange... | declare exchange, create if needed
This method creates an exchange if it does not already exist,
and if the exchange exists, verifies that it is of the correct
and expected class.
RULE:
The server SHOULD support a minimum of 16 exchanges per
virtual host and id... |
def checksum_identity_card_number(characters):
"""
Calculates and returns a control digit for given list of characters basing on Identity Card Number standards.
"""
weights_for_check_digit = [7, 3, 1, 0, 7, 3, 1, 7, 3]
check_digit = 0
for i in range(3):
check_digit += weights_for_check_... | Calculates and returns a control digit for given list of characters basing on Identity Card Number standards. |
def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj... | Set an object permission for the given user sid |
def add_filter(self, filter):
"""
Add filter to property
:param filter: object, extending from AbstractFilter
:return: None
"""
if not isinstance(filter, AbstractFilter):
err = 'Filters must be of type {}'.format(AbstractFilter)
raise InvalidFilter... | Add filter to property
:param filter: object, extending from AbstractFilter
:return: None |
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:... | Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the... |
def connect_table(self, table, chunk, markup):
""" Creates a link from the table to paragraph and vice versa.
Finds the first heading above the table in the markup.
This is the title of the paragraph the table belongs to.
"""
k = markup.find(chunk)
i =... | Creates a link from the table to paragraph and vice versa.
Finds the first heading above the table in the markup.
This is the title of the paragraph the table belongs to. |
def validate_votes(self, validators_H, validators_prevH):
"set of validators may change between heights"
assert self.sender
def check(lockset, validators):
if not lockset.num_eligible_votes == len(validators):
raise InvalidProposalError('lockset num_eligible_votes mi... | set of validators may change between heights |
def raise_for_status(self, r):
"""Given a response, raise for bad status for certain actions
Some redcap api methods don't return error messages
that the user could test for or otherwise use. Therefore, we
need to do the testing ourself
Raising for everything wouldn't let the u... | Given a response, raise for bad status for certain actions
Some redcap api methods don't return error messages
that the user could test for or otherwise use. Therefore, we
need to do the testing ourself
Raising for everything wouldn't let the user see the
(hopefully helpful) er... |
def continuityGrouping(values, limit):
""" #TODO docstring
:param values: ``numpy.array`` containg ``int`` or ``float``, must be sorted
:param limit: the maximal difference between two values, if this number is
exceeded a new group is generated
:returns: a list containing array start and end p... | #TODO docstring
:param values: ``numpy.array`` containg ``int`` or ``float``, must be sorted
:param limit: the maximal difference between two values, if this number is
exceeded a new group is generated
:returns: a list containing array start and end positions of continuous
groups |
def map_values(
cr, source_column, target_column, mapping,
model=None, table=None, write='sql'):
"""
Map old values to new values within the same model or table. Old values
presumably come from a legacy column.
You will typically want to use it in post-migration scripts.
:param cr: ... | Map old values to new values within the same model or table. Old values
presumably come from a legacy column.
You will typically want to use it in post-migration scripts.
:param cr: The database cursor
:param source_column: the database column that contains old values to be \
mapped
:param targ... |
def render_table(output_dir, packages, jenv=JENV):
"""
Render and output dispatch table
"""
destination_filename = output_dir + "/com/swiftnav/sbp/client/MessageTable.java"
with open(destination_filename, 'w+') as f:
print(destination_filename)
f.write(jenv.get_template(TEMPLATE_TABLE_NAME).render... | Render and output dispatch table |
def auto_sort(parser, token):
"usage: {% auto_sort queryset %}"
try:
tag_name, queryset = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("{0} tag requires a single argument".format(token.contents.split()[0]))
return SortedQuerysetNode(queryset) | usage: {% auto_sort queryset %} |
def _get_tls_object(self, ssl_params):
"""
Return a TLS object to establish a secure connection to a server
"""
if ssl_params is None:
return None
if not ssl_params["verify"] and ssl_params["ca_certs"]:
self.warning(
"Incorrect configurati... | Return a TLS object to establish a secure connection to a server |
def insert(self, context):
"""
Create resource.
:param resort.engine.execution.Context context:
Current execution context.
"""
status_code, msg = self.__endpoint.post(
"/resources/custom-resource",
data={
"id": self.__name,
"restype": self.__restype,
"factoryclass": self.__factc... | Create resource.
:param resort.engine.execution.Context context:
Current execution context. |
def evaluate(contents, jsonnet_library_paths=None):
'''
Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths.
'''
if not jsonnet_library_paths:
jsonnet_library_paths = __salt__['config.option'](
... | Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths. |
def image_plot(shap_values, x, labels=None, show=True, width=20, aspect=0.2, hspace=0.2, labelpad=None):
""" Plots SHAP values for image inputs.
"""
multi_output = True
if type(shap_values) != list:
multi_output = False
shap_values = [shap_values]
# make sure labels
if labels i... | Plots SHAP values for image inputs. |
def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types:... | Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwar... |
def _populate_sgc_payoff_arrays(payoff_arrays):
"""
Populate the ndarrays in `payoff_arrays` with the payoff values of
the SGC game.
Parameters
----------
payoff_arrays : tuple(ndarray(float, ndim=2))
Tuple of 2 ndarrays of shape (4*k-1, 4*k-1). Modified in place.
"""
n = payof... | Populate the ndarrays in `payoff_arrays` with the payoff values of
the SGC game.
Parameters
----------
payoff_arrays : tuple(ndarray(float, ndim=2))
Tuple of 2 ndarrays of shape (4*k-1, 4*k-1). Modified in place. |
def connection_made(self, transport):
"""Start the Hub connection process.
Called when asyncio.Protocol establishes the network connection.
"""
_LOGGER.info('Connection established to Hub')
_LOGGER.debug('Transport: %s', transport)
self.transport = transport
sel... | Start the Hub connection process.
Called when asyncio.Protocol establishes the network connection. |
def get_obsolete_user_ids(self, db_read=None):
"""
Returns obsolete users IDs to unaward.
"""
db_read = db_read or self.db_read
already_awarded_ids = self.get_already_awarded_user_ids(db_read=db_read, show_log=False)
current_ids = self.get_current_user_ids(db_read=db_rea... | Returns obsolete users IDs to unaward. |
def zdivide(a, b, null=0):
'''
zdivide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
or a/b syntax, zdivide will thread over the earliest dimension possible; thus if a.shape is
(4,2) and b.shape is 4, zdivide(a,b) is a equivalent to [ai*zinv(bi) for (ai,bi)... | zdivide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
or a/b syntax, zdivide will thread over the earliest dimension possible; thus if a.shape is
(4,2) and b.shape is 4, zdivide(a,b) is a equivalent to [ai*zinv(bi) for (ai,bi) in zip(a,b)].
The optional argume... |
def _assert_lt(self, cost):
"""
The method enforces an upper bound on the cost of the MaxSAT
solution. This is done by encoding the sum of all soft clause
selectors with the use the iterative totalizer encoding, i.e.
:class:`.ITotalizer`. Note that the sum is crea... | The method enforces an upper bound on the cost of the MaxSAT
solution. This is done by encoding the sum of all soft clause
selectors with the use the iterative totalizer encoding, i.e.
:class:`.ITotalizer`. Note that the sum is created once, at the
beginning. Each of the ... |
def json_data(self):
"""The json representation of a transmissions."""
return {
"vector_id": self.vector_id,
"origin_id": self.origin_id,
"destination_id": self.destination_id,
"info_id": self.info_id,
"network_id": self.network_id,
... | The json representation of a transmissions. |
def _parse_docstring(fh):
"""Parse the docstrings of a script to find marked dependencies."""
find_fades = re.compile(r'\b(fades)\b:').search
for line in fh:
if line.startswith("'"):
quote = "'"
break
if line.startswith('"'):
quote = '"'
break... | Parse the docstrings of a script to find marked dependencies. |
def change_default(config):
"""
Change the default configuration.
"""
config_file, cf = read_latoolscfg()
if config not in cf.sections():
raise ValueError("\n'{:s}' is not a defined configuration.".format(config))
if config == 'REPRODUCE':
pstr = ('Are you SURE you want to set ... | Change the default configuration. |
def dict_to_qs(dct):
"""
Takes a dictionary and uses it to create a query string.
"""
itms = ["%s=%s" % (key, val) for key, val in list(dct.items())
if val is not None]
return "&".join(itms) | Takes a dictionary and uses it to create a query string. |
def peddy_het_check_plot(self):
"""plot the het_check scatter plot"""
# empty dictionary to add sample names, and dictionary of values
data = {}
# for each sample, and list in self.peddy_data
for s_name, d in self.peddy_data.items():
# check the sample contains the r... | plot the het_check scatter plot |
def get_payload(self):
"""Return Payload."""
return bytes(
[self.major_version >> 8 & 255, self.major_version & 255,
self.minor_version >> 8 & 255, self.minor_version & 255]) | Return Payload. |
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
"""
Updates references to the old logical id of a resource to the new (generated) logical id.
Example:
{"Ref": "MyLayer"} => {"Ref": "MyLayerABC123"}
:param dict input_dict: Dictionary representing ... | Updates references to the old logical id of a resource to the new (generated) logical id.
Example:
{"Ref": "MyLayer"} => {"Ref": "MyLayerABC123"}
:param dict input_dict: Dictionary representing the Ref function to be resolved.
:param dict supported_resource_id_refs: Dictionary that... |
def toimages(self):
"""
Convert blocks to images.
"""
from thunder.images.images import Images
if self.mode == 'spark':
values = self.values.values_to_keys((0,)).unchunk()
if self.mode == 'local':
values = self.values.unchunk()
return Im... | Convert blocks to images. |
def process(self, data):
"""
Update the state based on the incoming data
This function updates the state of the DeviceSpec object, giving values for each
axis [x,y,z,roll,pitch,yaw] in range [-1.0, 1.0]
The state tuple is only set when all 6 DoF have been read correctly.... | Update the state based on the incoming data
This function updates the state of the DeviceSpec object, giving values for each
axis [x,y,z,roll,pitch,yaw] in range [-1.0, 1.0]
The state tuple is only set when all 6 DoF have been read correctly.
The timestamp (in fractiona... |
def fit(self, X, y):
"""
Extract the information, which of the features are relevent using the given target.
For more information, please see the :func:`~tsfresh.festure_selection.festure_selector.check_fs_sig_bh`
function. All columns in the input data sample are treated as feature. Th... | Extract the information, which of the features are relevent using the given target.
For more information, please see the :func:`~tsfresh.festure_selection.festure_selector.check_fs_sig_bh`
function. All columns in the input data sample are treated as feature. The index of all
rows in X must be ... |
def _control_longitude(self):
''' Control on longitude values '''
if self.lonm < 0.0:
self.lonm = 360.0 + self.lonm
if self.lonM < 0.0:
self.lonM = 360.0 + self.lonM
if self.lonm > 360.0:
self.lonm = self.lonm - 360.0
if self.lonM > 360.0:
... | Control on longitude values |
def delete(self, request, uri):
"""
Delete versioned uri and return empty text response on success.
"""
uri = self.decode_uri(uri)
uris = cio.delete(uri)
if uri not in uris:
raise Http404
return self.render_to_response() | Delete versioned uri and return empty text response on success. |
def solve_linear_diop(total: int, *coeffs: int) -> Iterator[Tuple[int, ...]]:
r"""Yield non-negative integer solutions of a linear Diophantine equation of the format
:math:`c_1 x_1 + \dots + c_n x_n = total`.
If there are at most two coefficients, :func:`base_solution_linear()` is used to find the solution... | r"""Yield non-negative integer solutions of a linear Diophantine equation of the format
:math:`c_1 x_1 + \dots + c_n x_n = total`.
If there are at most two coefficients, :func:`base_solution_linear()` is used to find the solutions.
Otherwise, the solutions are found recursively, by reducing the number of v... |
def _project_perturbation(perturbation, epsilon, input_image, clip_min=None,
clip_max=None):
"""Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable.
"""
... | Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable. |
def start(self, contract_names, target):
'''
loads the contracts -- starts their event listeners
:param contract_names:
:return:
'''
if isinstance(contract_names, str):
contract_names = [contract_names]
if not isinstance(contract_names, list):
... | loads the contracts -- starts their event listeners
:param contract_names:
:return: |
def _strip_marker_elem(elem_name, elements):
"""Remove the supplied element from the marker.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The element's operand is always
associated with an "and" operator. This means that we can simply rem... | Remove the supplied element from the marker.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The element's operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associate... |
def proximal_huber(space, gamma):
"""Proximal factory of the Huber norm.
Parameters
----------
space : `TensorSpace`
The domain of the functional
gamma : float
The smoothing parameter of the Huber norm functional.
Returns
-------
prox_factory : function
Factory ... | Proximal factory of the Huber norm.
Parameters
----------
space : `TensorSpace`
The domain of the functional
gamma : float
The smoothing parameter of the Huber norm functional.
Returns
-------
prox_factory : function
Factory for the proximal operator to be initializ... |
def _onNextBookmark(self):
"""Previous Bookmark action triggered. Move cursor
"""
for block in qutepart.iterateBlocksFrom(self._qpart.textCursor().block().next()):
if self.isBlockMarked(block):
self._qpart.setTextCursor(QTextCursor(block))
return | Previous Bookmark action triggered. Move cursor |
def _get_coords(self, obj):
"""
Get the coordinates of the 2D aggregate, maintaining the correct
sorting order.
"""
xdim, ydim = obj.dimensions(label=True)[:2]
xcoords = obj.dimension_values(xdim, False)
ycoords = obj.dimension_values(ydim, False)
# Deter... | Get the coordinates of the 2D aggregate, maintaining the correct
sorting order. |
def _get_ipmitool_path(self, cmd='ipmitool'):
"""Get full path to the ipmitool command using the unix
`which` command
"""
p = subprocess.Popen(["which", cmd],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return o... | Get full path to the ipmitool command using the unix
`which` command |
def get_param(self, number):
"""Reads an internal Client object parameter.
"""
logger.debug("retreiving param number %s" % number)
type_ = param_types[number]
value = type_()
code = self.library.Cli_GetParam(self.pointer, c_int(number),
... | Reads an internal Client object parameter. |
def create_archive(
source: Path,
target: Path,
interpreter: str,
main: str,
compressed: bool = True
) -> None:
"""Create an application archive from SOURCE.
A slightly modified version of stdlib's
`zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archi... | Create an application archive from SOURCE.
A slightly modified version of stdlib's
`zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_ |
def get_default_qubit_mapping(program):
"""
Takes a program which contains qubit placeholders and provides a mapping to the integers
0 through N-1.
The output of this function is suitable for input to :py:func:`address_qubits`.
:param program: A program containing qubit placeholders
:return: A... | Takes a program which contains qubit placeholders and provides a mapping to the integers
0 through N-1.
The output of this function is suitable for input to :py:func:`address_qubits`.
:param program: A program containing qubit placeholders
:return: A dictionary mapping qubit placeholder to an addresse... |
def create_multispan_plots(tag_ids):
"""Create detail plots (first row) and total block(second row) of experiments.
Args:
tag_ids: list of tag-dictionaries, where the dictionaries must have fields 'name' (used for naming)
and 'id' (used for numbering axis_dict)
Re... | Create detail plots (first row) and total block(second row) of experiments.
Args:
tag_ids: list of tag-dictionaries, where the dictionaries must have fields 'name' (used for naming)
and 'id' (used for numbering axis_dict)
Returns:
Figure element fig, ax_di... |
def map_df(self, df):
"""
Map df
"""
if len(df) == 0:
return
aesthetics = set(self.aesthetics) & set(df.columns)
for ae in aesthetics:
df[ae] = self.map(df[ae])
return df | Map df |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ModelBuildContext for this ModelBuildInstance
:rtype: twilio.rest.autopilot.v1.assistant.model_bu... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ModelBuildContext for this ModelBuildInstance
:rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext |
def add_item(self, text, font=("default", 12, "bold"), backgroundcolor="yellow", textcolor="black",
highlightcolor="blue"):
"""
Add a new item on the Canvas.
:param text: text to display
:type text: str
:param font: font of the text
:type font: t... | Add a new item on the Canvas.
:param text: text to display
:type text: str
:param font: font of the text
:type font: tuple or :class:`~tkinter.font.Font`
:param backgroundcolor: background color
:type backgroundcolor: str
:param textcolor: text color
... |
def _delete_wals_before(self, segment_info):
"""
Delete all WAL files before segment_info.
Doesn't delete any base-backup data.
"""
wal_key_depth = self.layout.wal_directory().count('/') + 1
for key in self._backup_list(prefix=self.layout.wal_directory()):
ke... | Delete all WAL files before segment_info.
Doesn't delete any base-backup data. |
def has_approx_support(m, m_hat, prob=0.01):
"""Returns 1 if model selection error is less than or equal to prob rate,
0 else.
NOTE: why does np.nonzero/np.flatnonzero create so much problems?
"""
m_nz = np.flatnonzero(np.triu(m, 1))
m_hat_nz = np.flatnonzero(np.triu(m_hat, 1))
upper_diago... | Returns 1 if model selection error is less than or equal to prob rate,
0 else.
NOTE: why does np.nonzero/np.flatnonzero create so much problems? |
def tabs_or_spaces(physical_line, indent_char):
r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively. When
invoki... | r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively. When
invoking the Python command line interpreter with the -t o... |
def vincenty(lon0, lat0, a1, s):
"""
Returns the coordinates of a new point that is a given angular distance s away from a starting point (lon0, lat0) at bearing (angle from north) a1), to within a given precision
Note that this calculation is a simplified version of the full vincenty problem, which solves for t... | Returns the coordinates of a new point that is a given angular distance s away from a starting point (lon0, lat0) at bearing (angle from north) a1), to within a given precision
Note that this calculation is a simplified version of the full vincenty problem, which solves for the coordinates on the surface on an arbit... |
def getVolumeInformation(
self,
volumeNameBuffer,
volumeNameSize,
volumeSerialNumber,
maximumComponentLength,
fileSystemFlags,
fileSystemNameBuffer,
fileSystemNameSize,
dokanFileInfo,
):
"""Get information about the volume.
:pa... | Get information about the volume.
:param volumeNameBuffer: buffer for volume name
:type volumeNameBuffer: ctypes.c_void_p
:param volumeNameSize: volume name buffer size
:type volumeNameSize: ctypes.c_ulong
:param volumeSerialNumber: buffer for volume serial number
:type ... |
def call_async(self, fn, *args, **kwargs):
"""
Arrange for `fn(*args, **kwargs)` to be invoked on the context's main
thread.
:param fn:
A free function in module scope or a class method of a class
directly reachable from module scope:
.. code-block::... | Arrange for `fn(*args, **kwargs)` to be invoked on the context's main
thread.
:param fn:
A free function in module scope or a class method of a class
directly reachable from module scope:
.. code-block:: python
# mymodule.py
def my_... |
def handle_one_request(self):
"""Handle a single HTTP request."""
self.raw_requestline = self.rfile.readline()
if not self.raw_requestline:
self.close_connection = 1
elif self.parse_request():
return self.run_wsgi() | Handle a single HTTP request. |
def get_responses(self, assessment_taken_id):
"""Gets the submitted responses.
arg: assessment_taken_id (osid.id.Id): ``Id`` of the
``AssessmentTaken``
return: (osid.assessment.ResponseList) - the submitted answers
raise: NotFound - ``assessment_taken_id`` is not fou... | Gets the submitted responses.
arg: assessment_taken_id (osid.id.Id): ``Id`` of the
``AssessmentTaken``
return: (osid.assessment.ResponseList) - the submitted answers
raise: NotFound - ``assessment_taken_id`` is not found
raise: NullArgument - ``assessment_taken_id``... |
def spec_var(model, ph):
"""Compute variance of ``p`` from Fourier coefficients ``ph``.
Parameters
----------
model : pyqg.Model instance
The model object from which `ph` originates
ph : complex array
The field on which to compute the variance
Returns
-------
var_dens :... | Compute variance of ``p`` from Fourier coefficients ``ph``.
Parameters
----------
model : pyqg.Model instance
The model object from which `ph` originates
ph : complex array
The field on which to compute the variance
Returns
-------
var_dens : float
The variance of `... |
def to_array(self):
"""
Serializes this ForceReply to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ForceReply, self).to_array()
array['force_reply'] = bool(self.force_reply) # type bool
if self.selective... | Serializes this ForceReply to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
def normal_case(name):
"""Converts "CamelCaseHere" to "camel case here"."""
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name)
return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower() | Converts "CamelCaseHere" to "camel case here". |
def init(redis_address=None,
num_cpus=None,
num_gpus=None,
resources=None,
object_store_memory=None,
redis_max_memory=None,
log_to_driver=True,
node_ip_address=None,
object_id_seed=None,
local_mode=False,
redirect_worker_output=No... | Connect to an existing Ray cluster or start one and connect to it.
This method handles two cases. Either a Ray cluster already exists and we
just attach this driver to it, or we start all of the processes associated
with a Ray cluster and attach to the newly started cluster.
To start Ray and all of th... |
def Cylinder(center=(0.,0.,0.), direction=(1.,0.,0.), radius=0.5, height=1.0,
resolution=100, **kwargs):
"""
Create the surface of a cylinder.
Parameters
----------
center : list or np.ndarray
Location of the centroid in [x, y, z]
direction : list or np.ndarray
Di... | Create the surface of a cylinder.
Parameters
----------
center : list or np.ndarray
Location of the centroid in [x, y, z]
direction : list or np.ndarray
Direction cylinder points to in [x, y, z]
radius : float
Radius of the cylinder.
height : float
Height of ... |
def set_standard(self):
"""Set the charger to standard range for daily commute."""
if self.__maxrange_state:
data = self._controller.command(self._id, 'charge_standard',
wake_if_asleep=True)
if data and data['response']['result']:
... | Set the charger to standard range for daily commute. |
def title(words_quantity=4):
"""Return a random sentence to be used as e.g. an e-mail subject."""
result = words(quantity=words_quantity)
result += random.choice('?.!')
return result.capitalize() | Return a random sentence to be used as e.g. an e-mail subject. |
def init(name, languages, run):
"""Initializes your CONFIG_FILE for the current submission"""
contents = [file_name for file_name in glob.glob("*.*") if file_name != "brains.yaml"]
with open(CONFIG_FILE, "w") as output:
output.write(yaml.safe_dump({
"run": run,
"name": name,... | Initializes your CONFIG_FILE for the current submission |
def get_initial_status_brok(self, extra=None):
"""
Create an initial status brok
:param extra: some extra information to be added in the brok data
:type extra: dict
:return: Brok object
:rtype: alignak.Brok
"""
data = {'uuid': self.uuid}
self.fill... | Create an initial status brok
:param extra: some extra information to be added in the brok data
:type extra: dict
:return: Brok object
:rtype: alignak.Brok |
def update_file(self, path):
'''
Updates the file watcher and calls the appropriate method for results
@return: False if we need to keep trying the connection
'''
try:
# grab the file
result, stat = self.zoo_client.get(path, watch=self.watch_file)
... | Updates the file watcher and calls the appropriate method for results
@return: False if we need to keep trying the connection |
def dump_addresses(self, network, filename=None):
"""Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network`
"""
addrs = [addr.data for a in self.accounts.values() if a.network == network
... | Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network` |
def propagate(self, assumptions=[], phase_saving=0):
"""
The method takes a list of assumption literals and does unit
propagation of each of these literals consecutively. A Boolean
status is returned followed by a list of assigned (assumed and also
propagated) lit... | The method takes a list of assumption literals and does unit
propagation of each of these literals consecutively. A Boolean
status is returned followed by a list of assigned (assumed and also
propagated) literals. The status is ``True`` if no conflict arised
during propag... |
def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num):
"""
This is called when the coordinator node determines that a read or
write operation cannot be successful because the number of live
replicas are too low to meet the requested :class:`.Consisten... | This is called when the coordinator node determines that a read or
write operation cannot be successful because the number of live
replicas are too low to meet the requested :class:`.ConsistencyLevel`.
This means that the read or write operation was never forwarded to
any replicas.
... |
def _get_modules(path):
"""Finds modules in folder recursively
:param path: directory
:return: list of modules
"""
lst = []
folder_contents = os.listdir(path)
is_python_module = "__init__.py" in folder_contents
if is_python_module:
for file in folder_contents:
full_... | Finds modules in folder recursively
:param path: directory
:return: list of modules |
def import_from_xml(xml, edx_video_id, resource_fs, static_dir, external_transcripts=dict(), course_id=None):
"""
Imports data from a video_asset element about the given video_id.
If the edx_video_id already exists, then no changes are made. If an unknown
profile is referenced by an encoded video, that... | Imports data from a video_asset element about the given video_id.
If the edx_video_id already exists, then no changes are made. If an unknown
profile is referenced by an encoded video, that encoding will be ignored.
Arguments:
xml (Element): An lxml video_asset element containing import data
... |
def delete_many(self, keys, noreply=None):
"""
A convenience function to delete multiple keys.
Args:
keys: list(str), the list of keys to delete.
noreply: optional bool, True to not wait for the reply (defaults to
self.default_noreply).
Returns:
... | A convenience function to delete multiple keys.
Args:
keys: list(str), the list of keys to delete.
noreply: optional bool, True to not wait for the reply (defaults to
self.default_noreply).
Returns:
True. If an exception is raised then all, some or none... |
def validate_satisfied_by(self, obj):
"""Return `obj` if the object satisfies this type constraint, or raise.
:raises: `TypeConstraintError` if `obj` does not satisfy the constraint.
"""
if self.satisfied_by(obj):
return obj
raise self.make_type_constraint_error(obj, self) | Return `obj` if the object satisfies this type constraint, or raise.
:raises: `TypeConstraintError` if `obj` does not satisfy the constraint. |
def get_function_signature(func):
"""
Return the signature string of the specified function.
>>> def foo(name): pass
>>> get_function_signature(foo)
'foo(name)'
>>> something = 'Hello'
>>> get_function_signature(something)
Traceback (most recent call last):
...
TypeError: Th... | Return the signature string of the specified function.
>>> def foo(name): pass
>>> get_function_signature(foo)
'foo(name)'
>>> something = 'Hello'
>>> get_function_signature(something)
Traceback (most recent call last):
...
TypeError: The argument must be a function object: None typ... |
def get_reporters(self):
"""
Converts the report_generators list to a dictionary, and caches the result.
:return: A dictionary with such references.
"""
if not hasattr(self, '_report_generators_by_key'):
self._report_generators_by_key = {r.key: r for r in self.report... | Converts the report_generators list to a dictionary, and caches the result.
:return: A dictionary with such references. |
def get_relname_and_parent(self, treepos):
"""Return the (relation name, parent ID) tuple that a node is in.
Return None if this node is not in a relation.
"""
node = self.dgtree[treepos]
node_type = get_node_type(node)
assert node_type in (TreeNodeTypes.relation_node, Tr... | Return the (relation name, parent ID) tuple that a node is in.
Return None if this node is not in a relation. |
def build_attachment2():
"""Build attachment mock."""
attachment = Attachment()
attachment.content = "BwdW"
attachment.type = "image/png"
attachment.filename = "banner.png"
attachment.disposition = "inline"
attachment.content_id = "Banner"
return attachment | Build attachment mock. |
def _check_steps(a, b):
"""Check that the steps of ``a`` and ``b`` are both 1.
Parameters
----------
a : range
The first range to check.
b : range
The second range to check.
Raises
------
ValueError
Raised when either step is not 1.
"""
if a.step != 1:
... | Check that the steps of ``a`` and ``b`` are both 1.
Parameters
----------
a : range
The first range to check.
b : range
The second range to check.
Raises
------
ValueError
Raised when either step is not 1. |
def euler_scheme(traj, diff_func):
"""Simulation function for Euler integration.
:param traj:
Container for parameters and results
:param diff_func:
The differential equation we want to integrate
"""
steps = traj.steps
initial_conditions = traj.initial_conditions
dimens... | Simulation function for Euler integration.
:param traj:
Container for parameters and results
:param diff_func:
The differential equation we want to integrate |
def program_checks(job, input_args):
"""
Checks that dependency programs are installed.
input_args: dict Dictionary of input arguments (from main())
"""
# Program checks
for program in ['curl', 'docker', 'unzip', 'samtools']:
assert which(program), 'Program "{}" must be installed... | Checks that dependency programs are installed.
input_args: dict Dictionary of input arguments (from main()) |
def run(self):
"""Custom execution for chapel module directive. This class is instantiated by
the directive implementation and then this method is called. It parses
the options on the module directive, updates the environment according,
and creates an index entry for the module.
... | Custom execution for chapel module directive. This class is instantiated by
the directive implementation and then this method is called. It parses
the options on the module directive, updates the environment according,
and creates an index entry for the module.
Based on the python domai... |
def check(codeString, filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the Python source given by codeString for unfrosted flakes."""
if not settings_path and filename:
settings_path = os.path.dirname(os.path.abspath(filename))
settings_path = settings_path... | Check the Python source given by codeString for unfrosted flakes. |
def do_cd(self, arglist):
"""Change directory.
Usage:
cd <new_dir>
"""
# Expect 1 argument, the directory to change to
if not arglist or len(arglist) != 1:
self.perror("cd requires exactly 1 argument:", traceback_war=False)
self.do_help('cd')
... | Change directory.
Usage:
cd <new_dir> |
def build_index_name(app, *parts):
"""Build an index name from parts.
:param parts: Parts that should be combined to make an index name.
"""
base_index = os.path.splitext(
'-'.join([part for part in parts if part])
)[0]
return prefix_index(app=app, index=base_index) | Build an index name from parts.
:param parts: Parts that should be combined to make an index name. |
def has_target(alias, target):
'''
Return true if the alias/target is set
CLI Example:
.. code-block:: bash
salt '*' aliases.has_target alias target
'''
if target == '':
raise SaltInvocationError('target can not be an empty string')
aliases = list_aliases()
if alias no... | Return true if the alias/target is set
CLI Example:
.. code-block:: bash
salt '*' aliases.has_target alias target |
def semanticSimilarity(self, text1, text2, distanceMeasure = "cosine"):
"""
determine the semantic similarity of the two provided documents
@param text1: first document to analyze
@param text2: second document to analyze
@param distanceMeasure: distance measure to use for compari... | determine the semantic similarity of the two provided documents
@param text1: first document to analyze
@param text2: second document to analyze
@param distanceMeasure: distance measure to use for comparing two documents. Possible values are "cosine" (default) or "jaccard"
@returns: dict |
def _generate(self, size=None):
"Generates a new word"
corpus_letters = list(self.vectors.keys())
current_letter = random.choice(corpus_letters)
if size is None:
size = int(random.normalvariate(self.avg, self.std_dev))
letters = [current_letter]
for _ in ran... | Generates a new word |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.