code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def one_version(self, index=0):
'''
Leaves only one version for each object.
:param index: List-like index of the version. 0 == first; -1 == last
'''
def prep(df):
start = sorted(df._start.tolist())[index]
return df[df._start == start]
return pd... | Leaves only one version for each object.
:param index: List-like index of the version. 0 == first; -1 == last |
def items(self):
"""
A generator yielding ``(key, value)`` attribute pairs, sorted by key name.
"""
for key in sorted(self.attrs):
yield key, self.attrs[key] | A generator yielding ``(key, value)`` attribute pairs, sorted by key name. |
def expandPath(self, path):
""" Follows the path and expand all nodes along the way.
Returns (item, index) tuple of the last node in the path (the leaf node). This can be
reused e.g. to select it.
"""
iiPath = self.model().findItemAndIndexPath(path)
for (item, ind... | Follows the path and expand all nodes along the way.
Returns (item, index) tuple of the last node in the path (the leaf node). This can be
reused e.g. to select it. |
def __init_object(self):
"""Create a new object for the pool."""
# Check to see if the user created a specific initalization function for this object.
if self.init_function is not None:
new_obj = self.init_function()
self.__enqueue(new_obj)
else:
raise... | Create a new object for the pool. |
def manage_subscription():
"""Shows how to interact with a parameter subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryVoltage1'
])
sleep(5)
print('Adding extra items to the existing subscription...')
subscription.add([
'/YSS/SIMUL... | Shows how to interact with a parameter subscription. |
def main():
"""Entry point for stand-alone execution."""
conf.init(), db.init(conf.DbPath)
inqueue = LineQueue(sys.stdin).queue
outqueue = type("", (), {"put": lambda self, x: print("\r%s" % x, end=" ")})()
if "--quiet" in sys.argv: outqueue = None
if conf.MouseEnabled: inqueue.put("mou... | Entry point for stand-alone execution. |
def cycle_complexity(self, cycle='V'):
"""Cycle complexity of V, W, AMLI, and F(1,1) cycle with simple relaxation.
Cycle complexity is an approximate measure of the number of
floating point operations (FLOPs) required to perform a single
multigrid cycle relative to the cost a single smo... | Cycle complexity of V, W, AMLI, and F(1,1) cycle with simple relaxation.
Cycle complexity is an approximate measure of the number of
floating point operations (FLOPs) required to perform a single
multigrid cycle relative to the cost a single smoothing operation.
Parameters
----... |
def read(self, length=-1):
"""
Read ``length`` bytes from the file. If ``length`` is negative or
omitted, read all data until EOF.
:type length: int
:param length: the number of bytes to read
:rtype: string
:return: the chunk of data read from the file
"... | Read ``length`` bytes from the file. If ``length`` is negative or
omitted, read all data until EOF.
:type length: int
:param length: the number of bytes to read
:rtype: string
:return: the chunk of data read from the file |
def get_normalization_min_max(array, norm_min, norm_max):
"""Get the minimum and maximum of the normalization of the array, which sets the lower and upper limits of the \
colormap.
If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used.
Parameters
-----... | Get the minimum and maximum of the normalization of the array, which sets the lower and upper limits of the \
colormap.
If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
Th... |
def work_request(self, worker_name, md5, subkeys=None):
""" Make a work request for an existing stored sample.
Args:
worker_name: 'strings', 'pe_features', whatever
md5: the md5 of the sample (or sample_set!)
subkeys: just get a subkey of the output: '... | Make a work request for an existing stored sample.
Args:
worker_name: 'strings', 'pe_features', whatever
md5: the md5 of the sample (or sample_set!)
subkeys: just get a subkey of the output: 'foo' or 'foo.bar' (None for all)
Returns:
... |
def find_err_pattern(self, pattern):
""" This function will read the standard error of the program and return
a matching pattern if found.
EG. prog_obj.FindErrPattern("Update of mySQL failed")
"""
if self.wdir != '':
stderr = "%s/%s"%(self.wdir, self.stderr)
else:
... | This function will read the standard error of the program and return
a matching pattern if found.
EG. prog_obj.FindErrPattern("Update of mySQL failed") |
def delete_one(self, filter, collation=None):
"""Delete a single document matching the filter.
>>> db.test.count({'x': 1})
3
>>> result = db.test.delete_one({'x': 1})
>>> result.deleted_count
1
>>> db.test.count({'x': 1})
2
:Paramet... | Delete a single document matching the filter.
>>> db.test.count({'x': 1})
3
>>> result = db.test.delete_one({'x': 1})
>>> result.deleted_count
1
>>> db.test.count({'x': 1})
2
:Parameters:
- `filter`: A query that matches the docum... |
def set_debug(self, debug):
"""
Set the debug settings for this node. This should be a modified
:class:`~Debug` instance. This will take effect immediately on
the specified node.
:param Debug debug: debug object with specified settings
:raises NodeCommandFailed: ... | Set the debug settings for this node. This should be a modified
:class:`~Debug` instance. This will take effect immediately on
the specified node.
:param Debug debug: debug object with specified settings
:raises NodeCommandFailed: fail to communicate with node
:return: N... |
async def AddToUnit(self, storages):
'''
storages : typing.Sequence[~StorageAddParams]
Returns -> typing.Sequence[~AddStorageResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Storage',
request='AddToUnit',
... | storages : typing.Sequence[~StorageAddParams]
Returns -> typing.Sequence[~AddStorageResult] |
def get_all_pattern_variables(self, patternnumber):
"""Get all variables for a given pattern at one time.
Args:
patternnumber (integer): 0-7
Returns:
A descriptive multiline string.
"""
_checkPatternNumber(patternnumber)
... | Get all variables for a given pattern at one time.
Args:
patternnumber (integer): 0-7
Returns:
A descriptive multiline string. |
def parse_code(url):
"""
Parse the code parameter from the a URL
:param str url: URL to parse
:return: code query parameter
:rtype: str
"""
result = urlparse(url)
query = parse_qs(result.query)
return query['code'] | Parse the code parameter from the a URL
:param str url: URL to parse
:return: code query parameter
:rtype: str |
def list_snapshots(connection, volume):
""" List all snapshots for the volume
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:type volume: str
:param volume: Volume ID or Volume Name
:returns: None
"""
logger.info(
'+---------------... | List all snapshots for the volume
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:type volume: str
:param volume: Volume ID or Volume Name
:returns: None |
def stream_to_packet(data):
"""
Chop a stream of data into MODBUS packets.
:param data: stream of data
:returns: a tuple of the data that is a packet with the remaining
data, or ``None``
"""
if len(data) < 6:
return None
# unpack the length
pktlen = struct.unpack(">H", ... | Chop a stream of data into MODBUS packets.
:param data: stream of data
:returns: a tuple of the data that is a packet with the remaining
data, or ``None`` |
def on_message(self, message):
""" When enaml.js sends a message """
#: Decode message
change = tornado.escape.json_decode(message)
#print change
#: Get the owner ID
ref = change.get('ref')
if not ref:
return
#: Get the server side rep... | When enaml.js sends a message |
def _function_contents(func):
"""
The signature is as follows (should be byte/chars):
< _code_contents (see above) from func.__code__ >
,( comma separated _object_contents for function argument defaults)
,( comma separated _object_contents for any closure contents )
See also: https://docs.pyth... | The signature is as follows (should be byte/chars):
< _code_contents (see above) from func.__code__ >
,( comma separated _object_contents for function argument defaults)
,( comma separated _object_contents for any closure contents )
See also: https://docs.python.org/3/reference/datamodel.html
- ... |
def getchar(self):
u'''Get next character from queue.'''
Cevent = INPUT_RECORD()
count = DWORD(0)
while 1:
status = self.ReadConsoleInputW(self.hin,
byref(Cevent), 1, byref(count))
if (status and
... | u'''Get next character from queue. |
def add_event(self, event):
"""
Adds an IEvent event to this command set.
:param event: an event instance to be added
"""
self._events.append(event)
self._events_by_name[event.get_name] = event | Adds an IEvent event to this command set.
:param event: an event instance to be added |
def calc_nearest_point(bus1, network):
"""
Function that finds the geographical nearest point in a network from a given bus.
Parameters
-----
bus1: float
id of bus
network: Pypsa network container
network including the comparable buses
Returns
------
... | Function that finds the geographical nearest point in a network from a given bus.
Parameters
-----
bus1: float
id of bus
network: Pypsa network container
network including the comparable buses
Returns
------
bus0 : float
bus_id of nearest point |
def coarsegrain(P, n):
"""
Coarse-grains transition matrix P to n sets using PCCA
Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using:
..math:
\tilde{P} = M^T P M (M^T M)^{-1}
See [2]_ for the derivation of this form from the coarse-graining method fi... | Coarse-grains transition matrix P to n sets using PCCA
Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using:
..math:
\tilde{P} = M^T P M (M^T M)^{-1}
See [2]_ for the derivation of this form from the coarse-graining method first derived in [1]_.
Reference... |
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Exampl... | Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket |
def isfinite(data: mx.nd.NDArray) -> mx.nd.NDArray:
"""Performs an element-wise check to determine if the NDArray contains an infinite element or not.
TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite()
"""
is_data_not_nan = data == data
is_data_not_i... | Performs an element-wise check to determine if the NDArray contains an infinite element or not.
TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite() |
def _socket_readlines(self, blocking=False):
"""
Generator for complete lines, received from the server
"""
try:
self.sock.setblocking(0)
except socket.error as e:
self.logger.error("socket error when setblocking(0): %s" % str(e))
raise Connect... | Generator for complete lines, received from the server |
def modify_parameters(self, modifier_function):
"""
Make modifications on the parameters of the legislation
Call this function in `apply()` if the reform asks for legislation parameter modifications.
:param modifier_function: A function that takes an object of type :any:`ParameterNode`... | Make modifications on the parameters of the legislation
Call this function in `apply()` if the reform asks for legislation parameter modifications.
:param modifier_function: A function that takes an object of type :any:`ParameterNode` and should return an object of the same type. |
def to_dict(self):
"""
A wrapper for to_dict the makes sure that all the private information
as well as extra arguments are included. This method should *not* be
used for exporting information about the key.
:return: A dictionary representation of the JSON Web key
"""
... | A wrapper for to_dict the makes sure that all the private information
as well as extra arguments are included. This method should *not* be
used for exporting information about the key.
:return: A dictionary representation of the JSON Web key |
def database_to_intermediary(database_uri, schema=None):
""" Introspect from the database (given the database_uri) to create the intermediary representation. """
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine
Base = automap_base()
engine = create_engine(databas... | Introspect from the database (given the database_uri) to create the intermediary representation. |
def atc(jobid):
'''
Print the at(1) script that will run for the passed job
id. This is mostly for debugging so the output will
just be text.
CLI Example:
.. code-block:: bash
salt '*' at.atc <jobid>
'''
# Shim to produce output similar to what __virtual__() should do
# bu... | Print the at(1) script that will run for the passed job
id. This is mostly for debugging so the output will
just be text.
CLI Example:
.. code-block:: bash
salt '*' at.atc <jobid> |
def ssh_authorized_key_exists(public_key, application_name, user=None):
"""Check if given key is in the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The u... | Check if given key is in the authorized_key file.
:param public_key: Public key.
:type public_key: str
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
:returns: Whether giv... |
def alphas(shape, alpha_value, name=None):
"""Creates a tensor with all elements set to `alpha_value`.
This operation returns a tensor of type `dtype` with shape `shape` and all
elements set to alpha.
Parameters
----------
shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of typ... | Creates a tensor with all elements set to `alpha_value`.
This operation returns a tensor of type `dtype` with shape `shape` and all
elements set to alpha.
Parameters
----------
shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type `int32`.
The shape of the desired tensor... |
def set_log_level(self):
"""
Set log level according to command-line options
@returns: logger object
"""
if self.options.debug:
self.logger.setLevel(logging.DEBUG)
elif self.options.quiet:
self.logger.setLevel(logging.ERROR)
else:
... | Set log level according to command-line options
@returns: logger object |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None
"""
if is_raster_layer(self.parent.layer):
new_step = self.parent.step_kw_band_selector
else:
... | Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None |
def dict_of_sets_add(dictionary, key, value):
# type: (DictUpperBound, Any, Any) -> None
"""Add value to a set in a dictionary by key
Args:
dictionary (DictUpperBound): Dictionary to which to add values
key (Any): Key within dictionary
value (Any): Value to add to set in dictionary
... | Add value to a set in a dictionary by key
Args:
dictionary (DictUpperBound): Dictionary to which to add values
key (Any): Key within dictionary
value (Any): Value to add to set in dictionary
Returns:
None |
def start_ray_process(command,
process_type,
env_updates=None,
cwd=None,
use_valgrind=False,
use_gdb=False,
use_valgrind_profiler=False,
use_perftools_profiler=False,... | Start one of the Ray processes.
TODO(rkn): We need to figure out how these commands interact. For example,
it may only make sense to start a process in gdb if we also start it in
tmux. Similarly, certain combinations probably don't make sense, like
simultaneously running the process in valgrind and the... |
def BHI(self, params):
"""
BHI label
Branch to the instruction at label if the C flag is set and the Z flag is not set
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# BHI label
def BHI_func():... | BHI label
Branch to the instruction at label if the C flag is set and the Z flag is not set |
def modify_environment(self, environment_id, **kwargs):
'''
modify_environment(self, environment_id, **kwargs)
Modifies an existing environment
:Parameters:
* *environment_id* (`string`) -- The environment identifier
Keywords args:
The variables to change in th... | modify_environment(self, environment_id, **kwargs)
Modifies an existing environment
:Parameters:
* *environment_id* (`string`) -- The environment identifier
Keywords args:
The variables to change in the environment
:return: id of the created environment |
def delete_external_feed_courses(self, course_id, external_feed_id):
"""
Delete an external feed.
Deletes the external feed.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course... | Delete an external feed.
Deletes the external feed. |
def static2dplot(var, time):
""" If the static option is set in tplot, and is supplied with a time, then the spectrogram plot(s) for which
it is set will have another window pop up, with y and z values plotted at the specified time. """
# Grab names of data loaded in as tplot variables.
names = list(py... | If the static option is set in tplot, and is supplied with a time, then the spectrogram plot(s) for which
it is set will have another window pop up, with y and z values plotted at the specified time. |
def optimization_at(self,
circuit: Circuit,
index: int,
op: ops.Operation
) -> Optional[PointOptimizationSummary]:
"""Describes how to change operations near the given location.
For example, this method coul... | Describes how to change operations near the given location.
For example, this method could realize that the given operation is an
X gate and that in the very next moment there is a Z gate. It would
indicate that they should be combined into a Y gate by returning
PointOptimizationSummary... |
async def send_api(container, targetname, name, params = {}):
"""
Send API and discard the result
"""
handle = object()
apiEvent = ModuleAPICall(handle, targetname, name, params = params)
await container.wait_for_send(apiEvent) | Send API and discard the result |
def output(self, filename):
"""
Output the graph in filename
Args:
filename(string)
"""
if filename == '':
filename = 'contracts.dot'
if not filename.endswith('.dot'):
filename += ".dot"
info = 'Inheritance Graph: ' ... | Output the graph in filename
Args:
filename(string) |
def add_edge_end_unused(intersection, duplicates, intersections):
"""Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end.
This is a helper for :func:`~._surface_intersection.add_intersection`.
It assumes that
* ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0``
*... | Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end.
This is a helper for :func:`~._surface_intersection.add_intersection`.
It assumes that
* ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0``
* A "misclassified" intersection in ``intersections`` that matches
`... |
def if_running(meth):
"""Decorator for service methods that must be ran only if service is in
running state."""
@wraps(meth)
def check_running(self, *args, **kwargs):
if not self.running:
return
return meth(self, *args, **kwargs)
return c... | Decorator for service methods that must be ran only if service is in
running state. |
def session_id(self):
"""
Return the session id of the current connection.
The session id is issued (through an API request) the first time it is requested, but no sooner. This is
because generating a session id puts it into the DKV on the server, which effectively locks the cluster. On... | Return the session id of the current connection.
The session id is issued (through an API request) the first time it is requested, but no sooner. This is
because generating a session id puts it into the DKV on the server, which effectively locks the cluster. Once
issued, the session id will sta... |
def get_file_path_validator(default_file_param=None):
""" Creates a namespace validator that splits out 'path' into 'directory_name' and 'file_name'.
Allows another path-type parameter to be named which can supply a default filename. """
def validator(namespace):
if not hasattr(namespace, 'path'):
... | Creates a namespace validator that splits out 'path' into 'directory_name' and 'file_name'.
Allows another path-type parameter to be named which can supply a default filename. |
def qos_map_dscp_cos_mark_dscp_in_values(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
dscp_cos = ET.SubElement(map, "dscp-cos")
... | Auto Generated Code |
def prevention():
"""The |Transition| for the prevention example from Actual Causation
Figure 5D.
"""
tpm = np.array([
[0.5, 0.5, 1],
[0.5, 0.5, 0],
[0.5, 0.5, 1],
[0.5, 0.5, 1],
[0.5, 0.5, 1],
[0.5, 0.5, 0],
[0.5, 0.5, 1],
[0.5, 0.5, 1]
... | The |Transition| for the prevention example from Actual Causation
Figure 5D. |
def ngrok_url():
"""
If ngrok is running, it exposes an API on port 4040. We can use that
to figure out what URL it has assigned, and suggest that to the user.
https://ngrok.com/docs#list-tunnels
"""
try:
ngrok_resp = requests.get("http://localhost:4040/api/tunnels")
except requests.... | If ngrok is running, it exposes an API on port 4040. We can use that
to figure out what URL it has assigned, and suggest that to the user.
https://ngrok.com/docs#list-tunnels |
def search(self, query, options):
""" Perform Bugzilla search """
query["query_format"] = "advanced"
log.debug("Search query:")
log.debug(pretty(query))
# Fetch bug info
try:
result = self.server.query(query)
except xmlrpclib.Fault as error:
... | Perform Bugzilla search |
def set_until(self, frame, lineno=None):
"""Stop on the next line number."""
self.state = Until(frame, frame.f_lineno) | Stop on the next line number. |
def set_led_brightness(self, brightness):
"""Set the LED brightness for the current group/button."""
set_cmd = self._create_set_property_msg("_led_brightness", 0x07,
brightness)
self._send_method(set_cmd, self._property_set) | Set the LED brightness for the current group/button. |
def randomToggle(self, randomize):
"""Sets the reorder function on this StimulusModel to a randomizer
or none, alternately"""
if randomize:
self._stim.setReorderFunc(order_function('random'), 'random')
else:
self._stim.reorder = None | Sets the reorder function on this StimulusModel to a randomizer
or none, alternately |
def fetch(self):
"""
Fetch a StepInstance
:returns: Fetched StepInstance
:rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params... | Fetch a StepInstance
:returns: Fetched StepInstance
:rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance |
def NewFile(self, filename, encoding, options):
"""parse an XML file from the filesystem or the network. The
parsing flags @options are a combination of
xmlParserOption. This reuses the existing @reader
xmlTextReader. """
ret = libxml2mod.xmlReaderNewFile(self._o, filename... | parse an XML file from the filesystem or the network. The
parsing flags @options are a combination of
xmlParserOption. This reuses the existing @reader
xmlTextReader. |
def intern_atom(self, name, only_if_exists = 0):
"""Intern the string name, returning its atom number. If
only_if_exists is true and the atom does not already exist, it
will not be created and X.NONE is returned."""
r = request.InternAtom(display = self.display,
... | Intern the string name, returning its atom number. If
only_if_exists is true and the atom does not already exist, it
will not be created and X.NONE is returned. |
def memo_Y(f):
"""
Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
... | Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
return inner_fib... |
def pluralize(word) :
"""Pluralize an English noun."""
rules = [
['(?i)(quiz)$' , '\\1zes'],
['^(?i)(ox)$' , '\\1en'],
['(?i)([m|l])ouse$' , '\\1ice'],
['(?i)(matr|vert|ind)ix|ex$' , '\\1ices'],
['(?i)(x|ch|ss|sh)$' , '\\1es'],
['(... | Pluralize an English noun. |
def cli(env, storage_type, size, iops, tier,
location, snapshot_size, service_offering, billing):
"""Order a file storage volume.
Valid size and iops options can be found here:
https://console.bluemix.net/docs/infrastructure/FileStorage/index.html#provisioning
"""
file_manager = SoftLayer.F... | Order a file storage volume.
Valid size and iops options can be found here:
https://console.bluemix.net/docs/infrastructure/FileStorage/index.html#provisioning |
def _parse_weights(weight_args, default_weight=0.6):
"""Parse list of weight assignments."""
weights_dict = {}
r_group_weight = default_weight
for weight_arg in weight_args:
for weight_assignment in weight_arg.split(','):
if '=' not in weight_assignment:
raise ValueEr... | Parse list of weight assignments. |
def ReadCronJobRun(self, job_id, run_id):
"""Reads a single cron job run from the db."""
for run in itervalues(self.cronjob_runs):
if run.cron_job_id == job_id and run.run_id == run_id:
return run
raise db.UnknownCronJobRunError(
"Run with job id %s and run id %s not found." % (job_id,... | Reads a single cron job run from the db. |
def search(self, **kwargs):
"""
Method to search pool's based on extends search.
:param search: Dict containing QuerySets to find pool's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:para... | Method to search pool's based on extends search.
:param search: Dict containing QuerySets to find pool's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override d... |
def is_choked_turbulent_g(x, Fgamma, xT=None, xTP=None):
r'''Calculates if a gas flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 gas valve sizing calculations.
Either xT or xTP must be provided, depending on the calculation process.
.. math::
x \ge F_\gamma x_T
.. m... | r'''Calculates if a gas flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 gas valve sizing calculations.
Either xT or xTP must be provided, depending on the calculation process.
.. math::
x \ge F_\gamma x_T
.. math::
x \ge F_\gamma x_{TP}
Parameters
-----... |
def get_template_names(self):
"""
datagrid的默认模板
"""
names = super(EasyUIDeleteView, self).get_template_names()
names.append('easyui/confirm_delete.html')
return names | datagrid的默认模板 |
def draw(self, mode='triangles', indices=None, check_error=True):
""" Draw the attribute arrays in the specified mode.
Parameters
----------
mode : str | GL_ENUM
'points', 'lines', 'line_strip', 'line_loop', 'triangles',
'triangle_strip', or 'triangle_fan'.
... | Draw the attribute arrays in the specified mode.
Parameters
----------
mode : str | GL_ENUM
'points', 'lines', 'line_strip', 'line_loop', 'triangles',
'triangle_strip', or 'triangle_fan'.
indices : array
Array of indices to draw.
check_error:
... |
def cdr(ol,**kwargs):
'''
from elist.elist import *
ol=[1,2,3,4]
id(ol)
new = cdr(ol)
new
id(new)
####
ol=[1,2,3,4]
id(ol)
rslt = cdr(ol,mode="original")
rslt
id(rslt)
'''
if('mode' in kwargs):
mode = kwa... | from elist.elist import *
ol=[1,2,3,4]
id(ol)
new = cdr(ol)
new
id(new)
####
ol=[1,2,3,4]
id(ol)
rslt = cdr(ol,mode="original")
rslt
id(rslt) |
def get_encapsulated_payload_class(self):
"""
get the class that holds the encapsulated payload of the TZSP packet
:return: class representing the payload, Raw() on error
"""
try:
return TZSP.ENCAPSULATED_PROTOCOL_CLASSES[self.encapsulated_protocol] # noqa: E501
... | get the class that holds the encapsulated payload of the TZSP packet
:return: class representing the payload, Raw() on error |
def create_wordpress(self,
service_id,
version_number,
name,
path,
comment=None):
"""Create a wordpress for the specified service and version."""
body = self._formdata({
"name": name,
"path": path,
"comment": comment,
}, FastlyWordpress.FIELDS)
content = self._fetch("/service/%s/version/%d/wo... | Create a wordpress for the specified service and version. |
def get_unique_ajps( benchmark_runs ):
"""
Determines which join parameters are unique
"""
br_ajps = {}
for br in benchmark_runs:
for ajp in br.additional_join_parameters:
if ajp not in br_ajps:
br_ajps[ajp] = set()
... | Determines which join parameters are unique |
def roundClosestValid(val, res, decimals=None):
""" round to closest resolution """
if decimals is None and "." in str(res):
decimals = len(str(res).split('.')[1])
return round(round(val / res) * res, decimals) | round to closest resolution |
def revoke_cert(
ca_name,
CN,
cacert_path=None,
ca_filename=None,
cert_path=None,
cert_filename=None,
crl_file=None,
digest='sha256',
):
'''
Revoke a certificate.
.. versionadded:: 2015.8.0
ca_name
Name of the CA.
CN
... | Revoke a certificate.
.. versionadded:: 2015.8.0
ca_name
Name of the CA.
CN
Common name matching the certificate signing request.
cacert_path
Absolute path to ca certificates root directory.
ca_filename
Alternative filename for the CA.
cert_path
Path... |
def set_save_directory(base, source):
"""Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this directory by
browser window size. """
root = os.path.join(base, source)
if not os.path.isdir(root):
os.makedirs(root)
world.screensho... | Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this directory by
browser window size. |
def getDateFields(fc):
"""
Returns a list of fields that are of type DATE
Input:
fc - feature class or table path
Output:
List of date field names as strings
"""
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
return [fie... | Returns a list of fields that are of type DATE
Input:
fc - feature class or table path
Output:
List of date field names as strings |
def natural_neighbor_point(xp, yp, variable, grid_loc, tri, neighbors, triangle_info):
r"""Generate a natural neighbor interpolation of the observations to the given point.
This uses the Liang and Hale approach [Liang2010]_. The interpolation will fail if
the grid point has no natural neighbors.
Param... | r"""Generate a natural neighbor interpolation of the observations to the given point.
This uses the Liang and Hale approach [Liang2010]_. The interpolation will fail if
the grid point has no natural neighbors.
Parameters
----------
xp: (N, ) ndarray
x-coordinates of observations
yp: (N... |
def dumps(obj, **kwargs):
''' Serialize `obj` to a JSON formatted `str`. Accepts the same arguments
as `json` module in stdlib.
:param obj: a JSON serializable Python object.
:param kwargs: all the arguments that `json.dumps <http://docs.python.org/
2/library/json.html#json.dumps>`_ ... | Serialize `obj` to a JSON formatted `str`. Accepts the same arguments
as `json` module in stdlib.
:param obj: a JSON serializable Python object.
:param kwargs: all the arguments that `json.dumps <http://docs.python.org/
2/library/json.html#json.dumps>`_ accepts.
:raises: commentjson.... |
def insert_column(self, name, data, colnum=None):
"""
Insert a new column.
parameters
----------
name: string
The column name
data:
The data to write into the new column.
colnum: int, optional
The column number for the new colu... | Insert a new column.
parameters
----------
name: string
The column name
data:
The data to write into the new column.
colnum: int, optional
The column number for the new column, zero-offset. Default
is to add the new column after t... |
def process_pem(self, data, name):
"""
PEM processing - splitting further by the type of the records
:param data:
:param name:
:return:
"""
try:
ret = []
data = to_string(data)
parts = re.split(r'-----BEGIN', data)
i... | PEM processing - splitting further by the type of the records
:param data:
:param name:
:return: |
def __substitute_replace_pairs(self):
"""
Substitutes all replace pairs in the source of the stored routine.
"""
self._set_magic_constants()
routine_source = []
i = 0
for line in self._routine_source_code_lines:
self._replace['__LINE__'] = "'%d'" % (i... | Substitutes all replace pairs in the source of the stored routine. |
def get_sorted_structure(self, key=None, reverse=False):
"""
Get a sorted copy of the structure. The parameters have the same
meaning as in list.sort. By default, sites are sorted by the
electronegativity of the species.
Args:
key: Specifies a function of one argumen... | Get a sorted copy of the structure. The parameters have the same
meaning as in list.sort. By default, sites are sorted by the
electronegativity of the species.
Args:
key: Specifies a function of one argument that is used to extract
a comparison key from each list ele... |
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the sysctl output."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(cmd, return_val)
result = rdf_protodict.AttributedDict()
# The KeyValueParser generates an ordered d... | Parse the sysctl output. |
def get_orderbook_ticker(self, **params):
"""Latest price for a symbol or symbols.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker
:param symbol:
:type symbol: str
:returns: API response
.. code-block:: py... | Latest price for a symbol or symbols.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker
:param symbol:
:type symbol: str
:returns: API response
.. code-block:: python
{
"symbol": "LTCBTC... |
def align(expnums, ccd, version='s', dry_run=False):
"""Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image.
This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs.
The scaling we are computing here is for use in planting sour... | Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image.
This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs.
The scaling we are computing here is for use in planting sources into the image at the same sky/flux locations
while ... |
def mkdummy(name, **attrs):
"""Make a placeholder object that uses its own name for its repr"""
return type(
name, (), dict(__repr__=(lambda self: "<%s>" % name), **attrs)
)() | Make a placeholder object that uses its own name for its repr |
def average(numbers, averagetype='mean'):
"""
Find the average of a list of numbers
:type numbers: list
:param numbers: The list of numbers to find the average of.
:type averagetype: string
:param averagetype: The type of average to find.
>>> average([1, 2, 3, 4, 5], 'median')
3
"... | Find the average of a list of numbers
:type numbers: list
:param numbers: The list of numbers to find the average of.
:type averagetype: string
:param averagetype: The type of average to find.
>>> average([1, 2, 3, 4, 5], 'median')
3 |
def add(self, *args):
"""Add constraints to the model."""
self._constrs.extend(self._moma._prob.add_linear_constraints(*args)) | Add constraints to the model. |
def number_of_changes(slots, events, original_schedule, X, **kwargs):
"""
A function that counts the number of changes between a given schedule
and an array (either numpy array of lp array).
"""
changes = 0
original_array = schedule_to_array(original_schedule, events=events,
... | A function that counts the number of changes between a given schedule
and an array (either numpy array of lp array). |
def set_attrs(self):
""" set our object attributes """
self.attrs.encoding = self.encoding
self.attrs.errors = self.errors | set our object attributes |
def _call_java(sc, java_obj, name, *args):
"""
Method copied from pyspark.ml.wrapper. Uses private Spark APIs.
"""
m = getattr(java_obj, name)
java_args = [_py2java(sc, arg) for arg in args]
return _java2py(sc, m(*java_args)) | Method copied from pyspark.ml.wrapper. Uses private Spark APIs. |
def get_param_doc(doc, param):
"""Get the documentation and datatype for a parameter
This function returns the documentation and the argument for a
napoleon like structured docstring `doc`
Parameters
----------
doc: str
The base docstring to use
para... | Get the documentation and datatype for a parameter
This function returns the documentation and the argument for a
napoleon like structured docstring `doc`
Parameters
----------
doc: str
The base docstring to use
param: str
The argument to use
... |
def get_vcenter_data_model(self, api, vcenter_name):
"""
:param api:
:param str vcenter_name:
:rtype: VMwarevCenterResourceModel
"""
if not vcenter_name:
raise ValueError('VMWare vCenter name is empty')
vcenter_instance = api.GetResourceDetails(vcente... | :param api:
:param str vcenter_name:
:rtype: VMwarevCenterResourceModel |
def postChunked(host, selector, fields, files):
"""
Attempt to replace postMultipart() with nearly-identical interface.
(The files tuple no longer requires the filename, and we only return
the response body.)
Uses the urllib2_file.py originally from
http://fabien.seisen.org which was also draw... | Attempt to replace postMultipart() with nearly-identical interface.
(The files tuple no longer requires the filename, and we only return
the response body.)
Uses the urllib2_file.py originally from
http://fabien.seisen.org which was also drawn heavily from
http://code.activestate.com/recipes/1463... |
def customer_discount_webhook_handler(event):
"""Handle updates to customer discount objects.
Docs: https://stripe.com/docs/api#discounts
Because there is no concept of a "Discount" model in dj-stripe (due to the
lack of a stripe id on them), this is a little different to the other
handlers.
"""
crud_type = C... | Handle updates to customer discount objects.
Docs: https://stripe.com/docs/api#discounts
Because there is no concept of a "Discount" model in dj-stripe (due to the
lack of a stripe id on them), this is a little different to the other
handlers. |
def executemany(self, command, params=None, max_attempts=5):
"""Execute multiple SQL queries without returning a result."""
attempts = 0
while attempts < max_attempts:
try:
# Execute statement
self._cursor.executemany(command, params)
s... | Execute multiple SQL queries without returning a result. |
def handle_oauth2_response(self, args):
"""Handles an oauth2 authorization response."""
client = self.make_client()
remote_args = {
'code': args.get('code'),
'client_secret': self.consumer_secret,
'redirect_uri': session.get('%s_oauthredir' % self.name)
... | Handles an oauth2 authorization response. |
def change_generated_target_suffix (type, properties, suffix):
""" Change the suffix previously registered for this type/properties
combination. If suffix is not yet specified, sets it.
"""
assert isinstance(type, basestring)
assert is_iterable_typed(properties, basestring)
assert isinstance... | Change the suffix previously registered for this type/properties
combination. If suffix is not yet specified, sets it. |
def email_message(
self,
recipient, # type: Text
subject_template, # type: Text
body_template, # type: Text
sender=None, # type: Optional[AbstractUser]
message_class=EmailMessage,
**kwargs
):
"""
Returns an invitation email message. This ca... | Returns an invitation email message. This can be easily overridden.
For instance, to send an HTML message, use the EmailMultiAlternatives message_class
and attach the additional conent. |
def framework_find(fn, executable_path=None, env=None):
"""
Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python
Python.framework
Python.framework/Versions/Current
"""
try:
return dyld_find(fn, executable_path=executable_path,... | Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python
Python.framework
Python.framework/Versions/Current |
def get_job_model(self):
"""
Returns a new JobModel instance with current loaded job data attached.
:return: JobModel
"""
if not self.job:
raise Exception('Job not loaded yet. Use load(id) first.')
return JobModel(self.job_id, self.job, self.home_config['stor... | Returns a new JobModel instance with current loaded job data attached.
:return: JobModel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.