text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def genPrime():
"""
Generate 2 large primes `p_prime` and `q_prime` and use them
to generate another 2 primes `p` and `q` of 1024 bits
"""
prime = cmod.randomPrime(LARGE_PRIME)
i = 0
while not cmod.isPrime(2 * prime + 1):
prime = cmod.randomPrime(LARGE_PRIME)
i += 1
retur... | 0.003058 |
def calculate_width_widget_int(width, border = False, margin = None, margin_left = None, margin_right = None):
"""
Calculate actual widget content width based on given margins and paddings.
"""
if margin_left is None:
margin_left = margin
if margin_right is None:
... | 0.020513 |
def run_cell(self, cell, store_history=True):
"""Run a complete IPython cell.
Parameters
----------
cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell will be stored ... | 0.003531 |
def add_done_callback(self, fn):
"""Adds a callback to be completed once future is done
:parm fn: A callable that takes no arguments. Note that is different
than concurrent.futures.Future.add_done_callback that requires
a single argument for the future.
"""
# The... | 0.003026 |
def from_object(self, obj):
"""Updates the values from the given object. An object can be of one
of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually e... | 0.001718 |
def probably_geojson(input):
'''A quick check to see if this input looks like GeoJSON. If not a dict
JSON-like object, attempt to parse input as JSON. If the resulting object
has a type property that looks like GeoJSON, return that object or None'''
valid = False
if not isinstance(input, dict):
... | 0.001391 |
def save_token(self, token, request, *args, **kwargs):
"""Persist the token with a token type specific method.
Currently, only save_bearer_token is supported.
:param token: A (Bearer) token dict.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"... | 0.005089 |
def migrate_thrift_obj(self, obj):
"""Helper function that can be called when serializing/deserializing thrift objects whose definitions
have changed, we need to make sure we initialize the new attributes to their default value"""
if not hasattr(obj, "thrift_spec"):
return
o... | 0.007924 |
def stream_template(template_name, **context):
'''
Some templates can be huge, this function returns an streaming response,
sending the content in chunks and preventing from timeout.
:param template_name: template
:param **context: parameters for templates.
:yields: HTML strings
'''
app... | 0.002004 |
def is_img_id_exists(img_id):
"""
Checks if img_id has real file on filesystem.
"""
main_rel_path = get_relative_path_from_img_id(img_id)
main_path = media_path(main_rel_path)
return os.path.isfile(main_path) | 0.00431 |
def put(self, key):
"""Insert the key
:return: Key name
"""
self.client.put_object(
Body=json.dumps(key),
Bucket=self.db_path,
Key=key['name'])
return key['name'] | 0.008403 |
def display_variogram_model(self):
"""Displays variogram model with the actual binned data."""
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(self.lags, self.semivariance, 'r*')
ax.plot(self.lags,
self.variogram_function(self.variogram_model_parameters... | 0.005 |
def _convert_list2str(self, fields):
"""
:param fields: ('bdate', 'domain')
:return: 'bdate,domain'
"""
if isinstance(fields, tuple) or isinstance(fields, list):
return ','.join(fields)
return fields | 0.007722 |
def refresh_image(self):
"""Get the most recent camera image."""
url = str.replace(CONST.TIMELINE_IMAGES_ID_URL,
'$DEVID$', self.device_id)
response = self._abode.send_request("get", url)
_LOGGER.debug("Get image response: %s", response.text)
return se... | 0.005391 |
def _parse_property(cls, name, value):
"""Parse a property received from the API into an internal object.
Args:
name (str): Name of the property on the object.
value (mixed): The unparsed API value.
Raises:
HelpScoutValidationException: In the event that the... | 0.001787 |
def run_docstring_examples(f, globs, verbose=False, name="NoName",
compileflags=None, optionflags=0):
"""
Test examples in the given object's docstring (`f`), using `globs`
as globals. Optional argument `name` is used in failure messages.
If the optional argument `verbose` is... | 0.000949 |
def get_address(self, address):
"""Retrieve an address from the wallet.
:param str address: address in the wallet to look up
:return: an instance of :class:`Address` class
"""
params = self.build_basic_request()
params['address'] = address
respo... | 0.00684 |
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
"""
Resolve resource references within a GetAtt dict.
Example:
{ "Fn::GetAtt": ["LogicalId", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]}
Theoretically, only the first element of the... | 0.005299 |
def _ensure_index_cache(self, db_uri, db_name, collection_name):
"""Adds a collections index entries to the cache if not present"""
if not self._check_indexes or db_uri is None:
return {'indexes': None}
if db_name not in self.get_cache():
self._internal_map[db_name] = {}
... | 0.004088 |
def rooms_favorite(self, room_id=None, room_name=None, favorite=True):
"""Favorite or unfavorite room."""
if room_id is not None:
return self.__call_api_post('rooms.favorite', roomId=room_id, favorite=favorite)
elif room_name is not None:
return self.__call_api_post('room... | 0.008658 |
def convert_datetime(obj):
"""Returns a DATETIME or TIMESTAMP column value as a datetime object:
>>> datetime_or_None('2007-02-25 23:06:20')
datetime.datetime(2007, 2, 25, 23, 6, 20)
>>> datetime_or_None('2007-02-25T23:06:20')
datetime.datetime(2007, 2, 25, 23, 6, 20)
Illegal values ar... | 0.004315 |
def line_iterator(readable_file, size=None):
# type: (IO[bytes], Optional[int]) -> Iterator[bytes]
"""Iterate over the lines of a file.
Implementation reads each char individually, which is not very
efficient.
Yields:
str: a single line in the file.
"""
read = readable_file.read
... | 0.001271 |
def return_action(self, text, loc, ret):
"""Code executed after recognising a return statement"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("RETURN:",ret)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
if not self.symtab.same_typ... | 0.011547 |
def decode_cpu_id(self, cpuid):
"""Decode the CPU id into a string"""
ret = ()
for i in cpuid.split(':'):
ret += (eval('0x' + i),)
return ret | 0.010753 |
def on_open_output_tool_clicked(self):
"""Autoconnect slot activated when open output tool button is clicked.
"""
output_path = self.output_path.text()
if not output_path:
output_path = os.path.expanduser('~')
# noinspection PyCallByClass,PyTypeChecker
filenam... | 0.003992 |
def declalltypes(self):
"""generator on all declaration of type"""
for f in self.body:
if (hasattr(f, '_ctype')
and f._ctype._storage == Storages.TYPEDEF):
yield f | 0.008811 |
def create_request(query):
"""
Creates a GET request to Yarr! server
:param query: Free-text search query
:returns: Requests object
"""
yarr_url = app.config.get('YARR_URL', False)
if not yarr_url:
raise('No URL to Yarr! server specified in config.')
api_token = app.config.get... | 0.001894 |
def quit(self):
"""Restore previous stdout/stderr and destroy the window."""
sys.stdout = self._oldstdout
sys.stderr = self._oldstderr
self.destroy() | 0.01105 |
def _evaluate_hodograph(s, nodes):
r"""Evaluate the Hodograph curve at a point :math:`s`.
The Hodograph (first derivative) of a B |eacute| zier curve
degree :math:`d = n - 1` and is given by
.. math::
B'(s) = n \sum_{j = 0}^{d} \binom{d}{j} s^j
(1 - s)^{d - j} \cdot \Delta v_j
wher... | 0.000992 |
def googlenet_resize(im, targ, min_area_frac, min_aspect_ratio, max_aspect_ratio, flip_hw_p, interpolation=cv2.INTER_AREA):
""" Randomly crop an image with an aspect ratio and returns a squared resized image of size targ
References:
1. https://arxiv.org/pdf/1409.4842.pdf
2. https://arxiv.org/pdf/18... | 0.0055 |
def COOKIES(self):
""" Cookie information parsed into a dictionary.
Secure cookies are NOT decoded automatically. See
Request.get_cookie() for details.
"""
if self._COOKIES is None:
raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
self.... | 0.00641 |
def gc(self):
'''Find the frequency of G and C in the current sequence.'''
gc = len([base for base in self.seq if base == 'C' or base == 'G'])
return float(gc) / len(self) | 0.010256 |
def cov_from_scales(self, scales):
"""Return a covariance matrix built from a dictionary of scales.
`scales` is a dictionary keyed by stochastic instances, and the
values refer are the variance of the jump distribution for each
stochastic. If a stochastic is a sequence, the variance mus... | 0.002436 |
def nested_option(default=False):
""" Attaches the option ``nested`` with its *default* value to the
keyword arguments when the option does not exist. All positional
arguments and keyword arguments are forwarded unchanged.
"""
def decorator(method):
@wraps(method)
def wrapper(*args,... | 0.001908 |
def getImage(path, dockerfile, tag):
'''Check if an image with a given tag exists. If not, build an image from
using a given dockerfile in a given path, tagging it with a given tag.
No extra side effects. Handles and reraises BuildError, TypeError, and
APIError exceptions.
'''
image = getImageBy... | 0.001082 |
def sample_logits(embedding, bias, labels, inputs, sampler):
"""
embedding: an nn.Embedding layer
bias: [n_vocab]
labels: [b1, b2]
inputs: [b1, b2, n_emb]
sampler: you may use a LogUniformSampler
Return
logits: [b1, b2, 1 + n_sample]
"""
true_log_probs, sa... | 0.002646 |
def batchcancel_order(self, order_ids: list):
"""
批量撤销订单
:param order_id:
:return:
"""
assert isinstance(order_ids, list)
params = {'order-ids': order_ids}
path = f'/v1/order/orders/batchcancel'
def _wrapper(_func):
@wraps(_func)
... | 0.004525 |
def format_duration(secs):
"""
Format a duration in seconds as minutes and seconds.
"""
secs = int(secs)
if abs(secs) > 60:
mins = abs(secs) / 60
secs = abs(secs) - (mins * 60)
return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs)
return '%is' % secs | 0.003247 |
def p_factor(self, tok):
"""factor : IPV4
| IPV6
| DATETIME
| TIMEDELTA
| INTEGER
| FLOAT
| VARIABLE
| CONSTANT
| FUNCTION RPAREN
| FUNCTION expressio... | 0.002766 |
def spare_disk(self, disk_xml=None):
""" Number of spare disk per type.
For example: storage.ontap.filer201.disk.SATA
"""
spare_disk = {}
disk_types = set()
for filer_disk in disk_xml:
disk_types.add(filer_disk.find('effective-disk-type').text)
... | 0.002356 |
def verify(self):
"""
Running all conditions in the instance variable valid_list
Return:
True: pass all conditions
False: fail at more than one condition
"""
if self not in self._queue:
return False
valid = True
for check in sel... | 0.005128 |
def add_to_manifest(self, manifest):
"""
Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry... | 0.003132 |
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
... | 0.000788 |
def validate(self, value):
"""
Validates that the input is in self.choices.
"""
super(ChoicesField, self).validate(value)
if value and not self.valid_value(value):
self._on_invalid_value(value) | 0.008163 |
def parse(cls, json):
# type: (dict) -> Any
"""Parse a json dict and return the correct subclass of :class:`ValidatorEffect`.
It uses the 'effect' key to determine which :class:`ValidatorEffect` to instantiate.
Please refer to :class:`enums.ValidatorEffectTypes` for the supported effect... | 0.007394 |
def expected_param_keys(self):
"""returns a list of params that this ConfigTemplate expects to receive"""
expected_keys = []
r = re.compile('%\(([^\)]+)\)s')
for block in self.keys():
for key in self[block].keys():
s = self[block][key]
i... | 0.011958 |
def _add_response(self, response, weight=1):
"""
Add a new trigger
:param response: The Response object
:type response: Response or Condition
:param weight: The weight of the response
:type weight: int
"""
# If no response with this priority level has b... | 0.004732 |
def write_meta_info(self, byte1, byte2, data):
"Worker method for writing meta info"
write_varlen(self.data, 0) # tick
write_byte(self.data, byte1)
write_byte(self.data, byte2)
write_varlen(self.data, len(data))
write_chars(self.data, data) | 0.00692 |
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate() | 0.003731 |
def CMOVNS(cpu, dest, src):
"""
Conditional move - Not sign (non-negative).
Tests the status flags in the EFLAGS register and moves the source operand
(second operand) to the destination operand (first operand) if the given
test condition is true.
:param cpu: current CP... | 0.011976 |
def _run_cnvkit_shared(inputs, backgrounds):
"""Shared functionality to run CNVkit, parallelizing over multiple BAM files.
Handles new style cases where we have pre-normalized inputs and
old cases where we run CNVkit individually.
"""
if tz.get_in(["depth", "bins", "normalized"], inputs[0]):
... | 0.005388 |
def get_feature_sequence(self, feature_id, organism=None, sequence=None):
"""
[CURRENTLY BROKEN] Get the sequence of a feature
:type feature_id: str
:param feature_id: Feature UUID
:type organism: str
:param organism: Organism Common Name
:type sequence: str
... | 0.003442 |
def interp_value(self, lat, lon, indexed=False):
""" Lookup a pixel value in the raster data, performing linear interpolation
if necessary. Indexed ==> nearest neighbor (*fast*). """
(px, py) = self.grid_coordinates.projection_to_raster_coords(lat, lon)
if indexed:
return sel... | 0.010417 |
def filterData(self, key):
"""
Returns the filter data for the given key.
:param key | <str>
:return <str>
"""
if key == 'text':
default = nativestring(self.text())
else:
default = ''
return self._filt... | 0.011628 |
async def read_data_frame(self, max_size: int) -> Optional[Frame]:
"""
Read a single data frame from the connection.
Process control frames received before the next data frame.
Return ``None`` if a close frame is encountered before any data frame.
"""
# 6.2. Receiving ... | 0.0017 |
def blob(self, nodeid, tag, start=0, end=0xFFFFFFFF):
"""
Blobs are stored in sequential nodes
with increasing index values.
most blobs, like scripts start at index
0, long names start at a specified
offset.
"""
startkey = self.makekey(nodeid, ... | 0.00354 |
def fill_dcnm_net_info(self, tenant_id, direc, vlan_id=0,
segmentation_id=0):
"""Fill DCNM network parameters.
Function that fills the network parameters for a tenant required by
DCNM.
"""
serv_obj = self.get_service_obj(tenant_id)
fw_dict = se... | 0.001993 |
def on_start(self, host, port, channel, nickname, password):
"""
A WebSocket session has started - create a greenlet to host
the IRC client, and start it.
"""
self.client = WebSocketIRCClient(host, port, channel, nickname,
password, self)
... | 0.005602 |
def is_rectilinear(self):
"""True if the transform is rectilinear, i.e., whether a shape would
remain axis-aligned, within rounding limits, after applying the
transform.
"""
a, b, c, d, e, f, g, h, i = self
return (abs(a) < EPSILON and abs(e) < EPSILON) or (
a... | 0.005464 |
async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
"""
Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found.
"""
respo... | 0.007984 |
def make_input_stream():
"""Creates a :py:class:`Queue` object and a co-routine yielding from that
queue. The queue should be populated with 2-tuples of the form `(command,
message)`, where `command` is one of [`msg`, `end`].
When the `end` command is recieved, the co-routine returns, ending the
st... | 0.001206 |
def parse_content(self, text):
"""parse section to formal format
raw_content: {title: section(with title)}. For `help` access.
formal_content: {title: section} but the section has been dedented
without title. For parse instance"""
raw_content = self.raw_content
... | 0.000832 |
def getBestDiscount(sender,**kwargs):
'''
When a customer registers for events, discounts may need to be
automatically applied. A given shopping cart may, in fact,
be eligible for multiple different types of discounts (e.g. hours-based
discounts for increasing numbers of class hours), but typically... | 0.007721 |
def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
... | 0.004115 |
def _edge_mapping(G):
"""Assigns a variable for each edge in G.
(u, v) and (v, u) map to the same variable.
"""
edge_mapping = {edge: idx for idx, edge in enumerate(G.edges)}
edge_mapping.update({(e1, e0): idx for (e0, e1), idx in edge_mapping.items()})
return edge_mapping | 0.006734 |
def _interfaces_removed(self, object_path, interfaces):
"""Internal method."""
old_state = copy(self._objects[object_path])
for interface in interfaces:
del self._objects[object_path][interface]
new_state = self._objects[object_path]
if Interface['Drive'] in interfac... | 0.001612 |
def log_head(path, log_file, log_time):
"""
write headers to log file
"""
with open(path + log_file, "w") as log:
log.write("#" * 79 + "\n\n")
log.write("File : " + log_file + "\n")
log.write("Path : " + path + "\n")
log.write("Date : " + time.strftime("%d/%m/%Y") + "\n")... | 0.002347 |
def _fun_names_iter(self, functyp, val):
"""Iterate over the names of the functions in ``val``,
adding them to ``funcstore`` if they are missing;
or if the items in ``val`` are already the names of functions
in ``funcstore``, iterate over those.
"""
funcstore = getattr(s... | 0.002642 |
def curve_to(self, x1, y1, x2, y2, x3, y3):
"""Adds a cubic Bézier spline to the path
from the current point
to position ``(x3, y3)`` in user-space coordinates,
using ``(x1, y1)`` and ``(x2, y2)`` as the control points.
After this call the current point will be ``(x3, y3)``.
... | 0.001784 |
def clean(ctx, state, dry_run=False, bare=False, user=False):
"""Uninstalls all packages not specified in Pipfile.lock."""
from ..core import do_clean
do_clean(ctx=ctx, three=state.three, python=state.python, dry_run=dry_run,
system=state.system) | 0.00369 |
def parse_aioredis_url(url: str) -> DictStrAny:
"""
Convert Redis URL string to dict suitable to pass to
``aioredis.create_redis(...)`` call.
**Usage**::
async def connect_redis(url=None):
url = url or 'redis://localhost:6379/0'
return await create_redis(**get_aioredis_... | 0.001506 |
def delete(self):
"""Delete this file from the device
.. note::
After deleting the file, this object will no longer contain valid information
and further calls to delete or get_data will return :class:`~.ErrorInfo` objects
"""
target = DeviceTarget(self.device_id)
... | 0.010152 |
def import_training_data(self,
positive_corpus_file=os.path.join(os.path.dirname(__file__),
"positive.txt"),
negative_corpus_file=os.path.join(os.path.dirname(__file__),
"negative.txt")
):
"""
This method imports the positive and negati... | 0.012037 |
def copy_to_clipboard(self, copy=True):
"""
Copies the selected items to the clipboard
:param copy: True to copy, False to cut.
"""
urls = self.selected_urls()
if not urls:
return
mime = self._UrlListMimeData(copy)
mime.set_list(urls)
c... | 0.004988 |
def duration(self):
"""Returns the integer value of the interval, the value is in milliseconds.
If the interval has not had stop called yet,
it will report the number of milliseconds in the interval up to the current point in time.
"""
if self._stop_instant is None:
... | 0.009597 |
def cancelTickByTickData(self, contract: Contract, tickType: str):
"""
Unsubscribe from tick-by-tick data
Args:
contract: The exact contract object that was used to
subscribe with.
"""
ticker = self.ticker(contract)
reqId = self.wrapper.endTic... | 0.003766 |
def setEnable(self, status, wanInterfaceId=1, timeout=1):
"""Set enable status for a WAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait... | 0.006107 |
def remove_client(self, client):
# type: (object) -> None
"""Remove the client from the users of the socket.
If there are no more clients for the socket, it
will close automatically.
"""
try:
self._clients.remove(id(client))
except ValueError:
... | 0.007673 |
def canonical_dataset_to_grib(dataset, path, mode='wb', no_warn=False, grib_keys={}, **kwargs):
# type: (xr.Dataset, str, str, bool, T.Dict[str, T.Any] T.Any) -> None
"""
Write a ``xr.Dataset`` in *canonical* form to a GRIB file.
"""
if not no_warn:
warnings.warn("GRIB write support is exper... | 0.005959 |
def autodiscover(self, autoregister=True):
"""This function will send out an autodiscover broadcast to find a
Neteria server. Any servers that respond with an "OHAI CLIENT"
packet are servers that we can connect to. Servers that respond are
stored in the "discovered_servers" list.
... | 0.003425 |
def initialize(self):
"""
Initialize the internal objects.
"""
if self._pooler is None:
params = {
"inputWidth": self.inputWidth,
"lateralInputWidths": [self.cellCount] * self.numOtherCorticalColumns,
"cellCount": self.cellCount,
"sdrSize": self.sdrSize,
"on... | 0.002216 |
def _get_access_token(self, verifier=None):
"""
Fetch an access token from `self.access_token_url`.
"""
response, content = self.client(verifier).request(
self.access_token_url, "POST")
content = smart_unicode(content)
if not response['statu... | 0.015759 |
def get_data(self, file_id):
"""
Acquires the data from the table identified by the id.
The file is read only once, consecutive calls to this method will
return the sale collection.
:param file_id: identifier for the table
:return: all the values from the table
... | 0.003559 |
def Tphi(self,**kwargs): #pragma: no cover
"""
NAME:
Tphi
PURPOSE:
Calculate the azimuthal period
INPUT:
+scipy.integrate.quadrature keywords
OUTPUT:
T_phi(R,vT,vT)/ro/vc + estimate of the error
HISTORY:
2010-12-01 - ... | 0.021994 |
def construct_task_instance(self, session=None, lock_for_update=False):
"""
Construct a TaskInstance from the database based on the primary key
:param session: DB session.
:param lock_for_update: if True, indicates that the database should
lock the TaskInstance (issuing a FO... | 0.002681 |
def get_logger(
name, file_name=None, stream=None, template=None, propagate=False):
"""Get a logger by name
if file_name is specified, and the dirname() of the file_name exists, it will
write to that file. If the dirname dies not exist, it will silently ignre it. """
logger = logging.getLogger... | 0.002602 |
def image_to_file(self, path, get_image=True):
"""Write the image to a file."""
if not self.image_url or get_image:
if not self.refresh_image():
return False
response = requests.get(self.image_url, stream=True)
if response.status_code != 200:
_LO... | 0.00311 |
def new_histogram(name, reservoir=None):
"""
Build a new histogram metric with a given reservoir object
If the reservoir is not provided, a uniform reservoir with the default size is used
"""
if reservoir is None:
reservoir = histogram.UniformReservoir(histogram.DEFAULT_UNIFORM_RESERVOIR_SI... | 0.007813 |
def me(cls):
"""
Returns information about the currently authenticated user.
:return:
:rtype: User
"""
return fields.ObjectField(name=cls.ENDPOINT, init_class=cls).decode(
cls.element_from_string(
cls._get_request(endpoint=cls.ENDPOINT + '/me'... | 0.005714 |
def relayIndextoCoord(self, i):
"""
Map 1D cell index to a 2D coordinate
:param i: integer 1D cell index
:return: (x, y), a 2D coordinate
"""
x = i % self.relayWidth
y = i / self.relayWidth
return x, y | 0.004255 |
def compile(self, session=None):
"""
Before calling the standard compile function, check to see if the size
of the data has changed and add variational parameters appropriately.
This is necessary because the shape of the parameters depends on the
shape of the data.
"""
... | 0.005666 |
def rerun(store, mail, current_user, institute_id, case_name, sender, recipient):
"""Request a rerun by email."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
user_obj = store.user(current_user.email)
link = url_for('cases.case', institute_id=institute_id, case_name=case_... | 0.003656 |
def remove_vrf(self, auth, spec):
""" Remove a VRF.
* `auth` [BaseAuth]
AAA options.
* `spec` [vrf_spec]
A VRF specification.
Remove VRF matching the `spec` argument.
This is the documentation of the internal backend function. It... | 0.005379 |
def na_value_for_dtype(dtype, compat=True):
"""
Return a dtype compat na value
Parameters
----------
dtype : string / dtype
compat : boolean, default True
Returns
-------
np.dtype or a pandas dtype
Examples
--------
>>> na_value_for_dtype(np.dtype('int64'))
0
>... | 0.000958 |
def get_recipients(self, ar):
"""Return the AR recipients in the same format like the AR Report
expects in the records field `Recipients`
"""
plone_utils = api.get_tool("plone_utils")
def is_email(email):
if not plone_utils.validateSingleEmailAddress(email):
... | 0.001425 |
def ftdetect(filename):
"""Determine if filename is markdown or notebook,
based on the file extension.
"""
_, extension = os.path.splitext(filename)
md_exts = ['.md', '.markdown', '.mkd', '.mdown', '.mkdn', '.Rmd']
nb_exts = ['.ipynb']
if extension in md_exts:
return 'markdown'
e... | 0.002494 |
def add(self, process, name=None):
"""Add a new process to the registry.
:param process: A callable (either plain function or object
implementing __calll).
:param name: The name of the executable to match. If not given
it must be provided as 'name' attribute of the given... | 0.004073 |
def passthrough(args):
"""
%prog passthrough chrY.vcf chrY.new.vcf
Pass through Y and MT vcf.
"""
p = OptionParser(passthrough.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
vcffile, newvcffile = args
fp = open(vcffile)
fw = op... | 0.002532 |
def create(self, server):
"""Create the tasks on the server"""
for chunk in self.__cut_to_size():
server.post(
'tasks_admin',
chunk.as_payload(),
replacements={
'slug': chunk.challenge.slug}) | 0.006969 |
def save_matpower(self, fd):
""" Serialize the case as a MATPOWER data file.
"""
from pylon.io import MATPOWERWriter
MATPOWERWriter(self).write(fd) | 0.011173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.