Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
20,100 | def head_object(Bucket=None, IfMatch=None, IfModifiedSince=None, IfNoneMatch=None, IfUnmodifiedSince=None, Key=None, Range=None, VersionId=None, SSECustomerAlgorithm=None, SSECustomerKey=None, SSECustomerKeyMD5=None, RequestPayer=None, PartNumber=None):
pass | The HEAD operation retrieves metadata from an object without returning the object itself. This operation is useful if you're only interested in an object's metadata. To use HEAD, you must have READ access to the object.
See also: AWS API Documentation
:example: response = client.head_object(
B... |
20,101 | def _display(self, sent, now, chunk, mbps):
if self.parent is not None:
self.parent._display(self.parent.offset + sent, now, chunk, mbps)
return
elapsed = now - self.startTime
if sent > 0 and self.total is not None and sent <= self.total:
eta = (sel... | Display intermediate progress. |
20,102 | def format(self, sql, params):
if isinstance(sql, unicode):
string_type = unicode
elif isinstance(sql, bytes):
string_type = bytes
sql = sql.decode(_BYTES_ENCODING)
else:
raise TypeError("sql:{!r} is not a unicode or byte string.".format(sql))
if self.named == :
if isinstance(params, collecti... | Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
simply a |sequence| of values mapped by index.
Returns a 2-|tuple|... |
20,103 | def splitPrefix(name):
if isinstance(name, basestring) \
and in name:
return tuple(name.split(, 1))
else:
return (None, name) | Split the name into a tuple (I{prefix}, I{name}). The first element in
the tuple is I{None} when the name does't have a prefix.
@param name: A node name containing an optional prefix.
@type name: basestring
@return: A tuple containing the (2) parts of I{name}
@rtype: (I{prefix}, I{name}) |
20,104 | def dropSpans(spans, text):
spans.sort()
res =
offset = 0
for s, e in spans:
if offset <= s:
if offset < s:
res += text[offset:s]
offset = e
res += text[offset:]
return res | Drop from text the blocks identified in :param spans:, possibly nested. |
20,105 | def add_page(self, page=None):
if page is None:
self.page = PDFPage(self.orientation_default, self.layout_default, self.margins)
else:
self.page = page
self.page._set_index(len(self.pages))
self.pages.append(self.page)
currentfont = self.f... | May generate and add a PDFPage separately, or use this to generate
a default page. |
20,106 | def netconf_config_change_datastore(self, **kwargs):
config = ET.Element("config")
netconf_config_change = ET.SubElement(config, "netconf-config-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
datastore = ET.SubElement(netconf_config_change, "datastore")
... | Auto Generated Code |
20,107 | def full_value(self):
s = self.name_value()
s += self.path_value()
s += "\n\n"
return s | Returns the full value with the path also (ie, name = value (path))
:returns: String |
20,108 | def array_controller_by_model(self, model):
for member in self.get_members():
if member.model == model:
return member | Returns array controller instance by model
:returns Instance of array controller |
20,109 | def tile_read(source, bounds, tilesize, **kwargs):
if isinstance(source, DatasetReader):
return _tile_read(source, bounds, tilesize, **kwargs)
else:
with rasterio.open(source) as src_dst:
return _tile_read(src_dst, bounds, tilesize, **kwargs) | Read data and mask.
Attributes
----------
source : str or rasterio.io.DatasetReader
input file path or rasterio.io.DatasetReader object
bounds : list
Mercator tile bounds (left, bottom, right, top)
tilesize : int
Output image size
kwargs: dict, optional
These wil... |
20,110 | def _is_monotonic(coord, axis=0):
if coord.shape[axis] < 3:
return True
else:
n = coord.shape[axis]
delta_pos = (coord.take(np.arange(1, n), axis=axis) >=
coord.take(np.arange(0, n - 1), axis=axis))
delta_neg = (coord.take(np.arange(1, n), axis=axis) <=
... | >>> _is_monotonic(np.array([0, 1, 2]))
True
>>> _is_monotonic(np.array([2, 1, 0]))
True
>>> _is_monotonic(np.array([0, 2, 1]))
False |
20,111 | def set_env(self):
if self.cov_source is None:
os.environ[] =
else:
os.environ[] = UNIQUE_SEP.join(self.cov_source)
os.environ[] = self.cov_data_file
os.environ[] = self.cov_config | Put info about coverage into the env so that subprocesses can activate coverage. |
20,112 | def to_regex(regex, flags=0):
if regex is None:
raise TypeError()
if hasattr(regex, ):
return regex
return re.compile(regex, flags) | Given a string, this function returns a new re.RegexObject.
Given a re.RegexObject, this function just returns the same object.
:type regex: string|re.RegexObject
:param regex: A regex or a re.RegexObject
:type flags: int
:param flags: See Python's re.compile().
:rtype: re.RegexObject
:r... |
20,113 | def _get_dst_resolution(self, dst_res=None):
if dst_res is None:
dst_res = min(self._res_indices.keys())
return dst_res | Get default resolution, i.e. the highest resolution or smallest cell size. |
20,114 | def reply(self, user, msg, errors_as_replies=True):
return self._brain.reply(user, msg, errors_as_replies) | Fetch a reply from the RiveScript brain.
Arguments:
user (str): A unique user ID for the person requesting a reply.
This could be e.g. a screen name or nickname. It's used internally
to store user variables (including topic and history), so if your
bo... |
20,115 | def make_attrstring(attr):
attrstring = .join([ % (k, v) for k, v in attr.items()])
return % ( if attrstring != else , attrstring) | Returns an attribute string in the form key="val" |
20,116 | def at_depth(self, depth):
for child in list(self.children):
if depth == 0:
yield child
else:
for grandchild in child.at_depth(depth - 1):
yield grandchild | Returns a generator yielding all nodes in the tree at a specific depth
:param depth:
An integer >= 0 of the depth of nodes to yield
:return:
A generator yielding PolicyTreeNode objects |
20,117 | def status(self):
if self.provider:
status = self.provider.status(self.engines)
else:
status = []
return status | Returns the status of the executor via probing the execution providers. |
20,118 | def apply(self, func, skills):
def run_item(skill):
try:
func(skill)
return True
except MsmException as e:
LOG.error(.format(
func.__name__, skill.name, repr(e)
))
return False
... | Run a function on all skills in parallel |
20,119 | def complete_url(self, url):
if self.base_url:
return urlparse.urljoin(self.base_url, url)
else:
return url | Completes a given URL with this instance's URL base. |
20,120 | def expire_leaderboard_at_for(self, leaderboard_name, timestamp):
pipeline = self.redis_connection.pipeline()
pipeline.expireat(leaderboard_name, timestamp)
pipeline.expireat(
self._ties_leaderboard_key(leaderboard_name), timestamp)
pipeline.expireat(self._member_dat... | Expire the given leaderboard at a specific UNIX timestamp. Do not use this with
leaderboards that utilize member data as there is no facility to cascade the
expiration out to the keys for the member data.
@param leaderboard_name [String] Name of the leaderboard.
@param timestamp [int] U... |
20,121 | def request_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests
api_path = "/api/v2/requests/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/requests#show-request |
20,122 | def pick_peaks(nc, L=16, offset_denom=0.1):
offset = nc.mean() * float(offset_denom)
th = filters.median_filter(nc, size=L) + offset
peaks = []
for i in range(1, nc.shape[0] - 1):
if nc[i - 1] < nc[i] and nc[i] > nc[i + 1]:
if ... | Obtain peaks from a novelty curve using an adaptive threshold. |
20,123 | def at(*args, **kwargs):
timespec**/sbin/reboot*3:05am +3 daysbin/myscript
if len(args) < 2:
return {: []}
if in kwargs:
stdin = .format(kwargs[], .join(args[1:]))
else:
stdin = .join(args[1:])
cmd_kwargs = {: stdin, : False}
if in kwargs:
cmd_kwa... | Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' tag=reboot
salt '*' at.at '3:05am +3 days' 'bin/myscri... |
20,124 | def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):
datetime_object = cls.CopyToDatetime(
timestamp, timezone, raise_error=raise_error)
return datetime_object.isoformat() | Copies the timestamp to an ISO 8601 formatted string.
Args:
timestamp: The timestamp which is an integer containing the number
of micro seconds since January 1, 1970, 00:00:00 UTC.
timezone: Optional timezone (instance of pytz.timezone).
raise_error: Boolean that if set to True w... |
20,125 | def API520_B(Pset, Pback, overpressure=0.1):
r
gauge_backpressure = (Pback-atm)/(Pset-atm)*100
if overpressure not in [0.1, 0.16, 0.21]:
raise Exception()
if (overpressure == 0.1 and gauge_backpressure < 30) or (
overpressure == 0.16 and gauge_backpressure < 38) or (
overpressur... | r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in vapor service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is per... |
20,126 | def compute_logarithmic_scale(min_, max_, min_scale, max_scale):
if max_ <= 0 or min_ <= 0:
return []
min_order = int(floor(log10(min_)))
max_order = int(ceil(log10(max_)))
positions = []
amplitude = max_order - min_order
if amplitude <= 1:
return []
detail = 10.
whi... | Compute an optimal scale for logarithmic |
20,127 | def from_location(cls, location):
if not location:
return cls()
try:
if hasattr(location, ):
return location
elif hasattr(location, ):
return cls(city=location)
return cls(cit... | Try to create a Ladybug location from a location string.
Args:
locationString: Location string
Usage:
l = Location.from_location(locationString) |
20,128 | async def join_voice_channel(self, guild_id, channel_id):
voice_ws = self.get_voice_ws(guild_id)
await voice_ws.voice_state(guild_id, channel_id) | Alternative way to join a voice channel if node is known. |
20,129 | def results(context, history_log):
if context.obj is None:
context.obj = {}
context.obj[] = history_log
if context.invoked_subcommand is None:
context.invoke(show, item=1) | Process provided history log and results files. |
20,130 | def show_bounds(self, mesh=None, bounds=None, show_xaxis=True,
show_yaxis=True, show_zaxis=True, show_xlabels=True,
show_ylabels=True, show_zlabels=True, italic=False,
bold=True, shadow=False, font_size=None,
font_family=Non... | Adds bounds axes. Shows the bounds of the most recent input
mesh unless mesh is specified.
Parameters
----------
mesh : vtkPolydata or unstructured grid, optional
Input mesh to draw bounds axes around
bounds : list or tuple, optional
Bounds to override ... |
20,131 | def _bnd(self, xloc, dist, cache):
return numpy.log(evaluation.evaluate_bound(
dist, numpy.e**xloc, cache=cache)) | Distribution bounds. |
20,132 | def macro_body(self, node, frame):
frame = frame.inner()
frame.symbols.analyze_node(node)
macro_ref = MacroRef(node)
explicit_caller = None
skip_special_params = set()
args = []
for idx, arg in enumerate(node.args):
if arg.name == :
... | Dump the function def of a macro or call block. |
20,133 | def get_mapping(self, doc_type=None, indices=None, raw=False):
if doc_type is None and indices is None:
path = make_path("_mapping")
is_mapping = False
else:
indices = self.conn._validate_indices(indices)
if doc_type:
path = make_p... | Register specific mapping definition for a specific type against one or more indices.
(See :ref:`es-guide-reference-api-admin-indices-get-mapping`) |
20,134 | def link(self, camera):
cam1, cam2 = self, camera
while cam1 in cam2._linked_cameras:
cam2._linked_cameras.remove(cam1)
while cam2 in cam1._linked_cameras:
cam1._linked_cameras.remove(cam2)
cam1._linked_cameras.append(cam2)
cam2.... | Link this camera with another camera of the same type
Linked camera's keep each-others' state in sync.
Parameters
----------
camera : instance of Camera
The other camera to link. |
20,135 | def thumbnail_preview(src_path):
try:
assert(exists(src_path))
width =
dest_dir = mkdtemp(prefix=)
cmd = [QLMANAGE, , , width, src_path, , dest_dir]
assert(check_call(cmd) == 0)
src_filename = basename(src_path)
dest_list = glob(join(dest_dir, % (src_filename)))
assert(dest_lis... | Returns the path to small thumbnail preview. |
20,136 | def _update(self, rect, delta_y, force_update_margins=False):
helper = TextHelper(self.editor)
if not self:
return
for zones_id, zone in self._panels.items():
if zones_id == Panel.Position.TOP or \
zones_id == Panel.Position.BOTTOM:
... | Updates panels |
20,137 | def low_mem_sq(m, step=100000):
if not m.flags.c_contiguous:
raise ValueError()
mmt = np.zeros([m.shape[0], m.shape[0]])
for a in range(0, m.shape[0], step):
mx = min(a+step, m.shape[1])
... | np.dot(m, m.T) with low mem usage, by doing it in small steps |
20,138 | def init_app(self, app, minters_entry_point_group=None,
fetchers_entry_point_group=None):
self.init_config(app)
app.cli.add_command(cmd)
app.config.setdefault(, app.debug)
if app.config[]:
for handler in app.logger.handlers:
... | Flask application initialization.
Initialize:
* The CLI commands.
* Initialize the logger (Default: `app.debug`).
* Initialize the default admin object link endpoint.
(Default: `{"rec": "recordmetadata.details_view"}` if
`invenio-records` is installed, otherwi... |
20,139 | def createpath(path, mode, exists_ok=True):
try:
os.makedirs(path, mode)
except OSError, e:
if e.errno != errno.EEXIST or not exists_ok:
raise e | Create directories in the indicated path.
:param path:
:param mode:
:param exists_ok:
:return: |
20,140 | def find_locales(self) -> Dict[str, gettext.GNUTranslations]:
translations = {}
for name in os.listdir(self.path):
if not os.path.isdir(os.path.join(self.path, name)):
continue
mo_path = os.path.join(self.path, name, , self.domain + )
if os.... | Load all compiled locales from path
:return: dict with locales |
20,141 | def batch_split_words(self, sentences: List[str]) -> List[List[Token]]:
return [self.split_words(sentence) for sentence in sentences] | Spacy needs to do batch processing, or it can be really slow. This method lets you take
advantage of that if you want. Default implementation is to just iterate of the sentences
and call ``split_words``, but the ``SpacyWordSplitter`` will actually do batched
processing. |
20,142 | def navigation_info(request):
if request.GET.get() == "1":
nav_class = "wafer-invisible"
else:
nav_class = "wafer-visible"
context = {
: nav_class,
}
return context | Expose whether to display the navigation header and footer |
20,143 | def get_precision_regex():
expr = re.escape(PRECISION_FORMULA)
expr += r
return re.compile(expr) | Build regular expression used to extract precision
metric from command output |
20,144 | def _col_name(index):
for exp in itertools.count(1):
limit = 26 ** exp
if index < limit:
return .join(chr(ord() + index // (26 ** i) % 26) for i in range(exp-1, -1, -1))
index -= limit | Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA' |
20,145 | def mqc_load_userconfig(paths=()):
mqc_load_config(os.path.join( os.path.dirname(MULTIQC_DIR), ))
mqc_load_config(os.path.expanduser())
if os.environ.get() is not None:
mqc_load_config( os.environ.get() )
mqc_load_config()
for p in paths:
mqc_load_c... | Overwrite config defaults with user config files |
20,146 | def middleware(self, *args, **kwargs):
kwargs.setdefault(, 5)
kwargs.setdefault(, None)
kwargs.setdefault(, None)
kwargs.setdefault(, False)
if len(args) == 1 and callable(args[0]):
middle_f = args[0]
self._middlewares.append(
Futu... | Decorate and register middleware
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments passed in
:type kwargs: dict(Any)
:return: The middleware function to use as the decorator
:rtype: fn |
20,147 | def get_paths(self):
paths = []
for key, child in six.iteritems(self):
if isinstance(child, TreeMap) and child:
for path in child.get_paths():
path.insert(0, key)
paths.append(path)
else:
... | Get all paths from the root to the leaves.
For example, given a chain like `{'a':{'b':{'c':None}}}`,
this method would return `[['a', 'b', 'c']]`.
Returns:
A list of lists of paths. |
20,148 | def f_store(self, recursive=True, store_data=pypetconstants.STORE_DATA,
max_depth=None):
traj = self._nn_interface._root_instance
storage_service = traj.v_storage_service
storage_service.store(pypetconstants.GROUP, self,
trajectory_name=tra... | Stores a group node to disk
:param recursive:
Whether recursively all children should be stored too. Default is ``True``.
:param store_data:
For how to choose 'store_data' see :ref:`more-on-storing`.
:param max_depth:
In case `recursive` is `True`, you c... |
20,149 | def _get_data(self) -> BaseFrameManager:
def iloc(partition, row_internal_indices, col_internal_indices):
return partition.iloc[row_internal_indices, col_internal_indices]
masked_data = self.parent_data.apply_func_to_indices_both_axis(
func=iloc,
row_indice... | Perform the map step
Returns:
A BaseFrameManager object. |
20,150 | def _fmt_structured(d):
timeEntry = datetime.datetime.utcnow().strftime(
"time=%Y-%m-%dT%H:%M:%S.%f-00")
pidEntry = "pid=" + str(os.getpid())
rest = sorted(.join([str(k), str(v)])
for (k, v) in list(d.items()))
return .join([timeEntry, pidEntr... | Formats '{k1:v1, k2:v2}' => 'time=... pid=... k1=v1 k2=v2'
Output is lexically sorted, *except* the time and pid always
come first, to assist with human scanning of the data. |
20,151 | def arg(*args, **kwargs):
metadata = {: (args, kwargs)}
return attrib(default=arg_default(*args, **kwargs), metadata=metadata) | Return an attrib() that can be fed as a command-line argument.
This function is a wrapper for an attr.attrib to create a corresponding
command line argument for it. Use it with the same arguments as argparse's
add_argument().
Example:
>>> @attrs
... class MyFeature(Feature):
... my_nu... |
20,152 | def decimal_format(value, TWOPLACES=Decimal(100) ** -2):
if not isinstance(value, Decimal):
value = Decimal(str(value))
return value.quantize(TWOPLACES) | Format a decimal.Decimal like to 2 decimal places. |
20,153 | def maybe_inspect_zip(models):
r
if not(is_zip_file(models)):
return models
if len(models) > 1:
return models
if len(models) < 1:
raise AssertionError()
return zipfile.ZipFile(models[0]).namelist() | r'''
Detect if models is a list of protocolbuffer files or a ZIP file.
If the latter, then unzip it and return the list of protocolbuffer files
that were inside. |
20,154 | def create_session(self, session_request, protocol):
route_values = {}
if protocol is not None:
route_values[] = self._serialize.url(, protocol, )
content = self._serialize.body(session_request, )
response = self._send(http_method=,
loca... | CreateSession.
[Preview API] Creates a session, a wrapper around a feed that can store additional metadata on the packages published to it.
:param :class:`<SessionRequest> <azure.devops.v5_0.provenance.models.SessionRequest>` session_request: The feed and metadata for the session
:param str prot... |
20,155 | def generate_cutV_genomic_CDR3_segs(self):
max_palindrome = self.max_delV_palindrome
self.cutV_genomic_CDR3_segs = []
for CDR3_V_seg in [x[1] for x in self.genV]:
if len(CDR3_V_seg) < max_palindrome:
self.cutV_genomic_CDR3_segs += [cutR_seq(CDR3_V_seg, ... | Add palindromic inserted nucleotides to germline V sequences.
The maximum number of palindromic insertions are appended to the
germline V segments so that delV can index directly for number of
nucleotides to delete from a segment.
Sets the attribute cutV_genomic_CDR3_se... |
20,156 | def get_container_service(access_token, subscription_id, resource_group, service_name):
endpoint = .join([get_rm_endpoint(),
, subscription_id,
, resource_group,
, service_name,
, ACS_API])
return do_get(endpoin... | Get details about an Azure Container Server
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
service_name (str): Name of container service.
Returns:
HTTP response... |
20,157 | def hook_drop(self):
widget = self.widget
widget.setAcceptDrops(True)
widget.dragEnterEvent = self.dragEnterEvent
widget.dragMoveEvent = self.dragMoveEvent
widget.dragLeaveEvent = self.dragLeaveEvent
widget.dropEvent = self.dropEvent | Install hooks for drop operations. |
20,158 | def send(self, stanza):
if self.uplink:
self.uplink.send(stanza)
else:
raise NoRouteError("No route for stanza") | Send a stanza somwhere.
The default implementation sends it via the `uplink` if it is defined
or raises the `NoRouteError`.
:Parameters:
- `stanza`: the stanza to send.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza` |
20,159 | def update_user_password(new_pwd_user_id, new_password,**kwargs):
try:
user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(str(new_password).encode(), bcrypt.gensalt())
return user_i
except NoResultFound:
raise Resour... | Update a user's password |
20,160 | def read_samples(self, sr=None, offset=0, duration=None):
with self.container.open_if_needed(mode=) as cnt:
samples, native_sr = cnt.get(self.key)
start_sample_index = int(offset * native_sr)
if duration is None:
end_sample_index = samples.shape[0]
... | Return the samples from the track in the container.
Uses librosa for resampling, if needed.
Args:
sr (int): If ``None``, uses the sampling rate given by the file,
otherwise resamples to the given sampling rate.
offset (float): The time in seconds, from wher... |
20,161 | def bootstrap_repl(which_ns: str) -> types.ModuleType:
repl_ns = runtime.Namespace.get_or_create(sym.symbol("basilisp.repl"))
ns = runtime.Namespace.get_or_create(sym.symbol(which_ns))
repl_module = importlib.import_module("basilisp.repl")
ns.add_alias(sym.symbol("basilisp.repl"), repl_ns)
ns.r... | Bootstrap the REPL with a few useful vars and returned the
bootstrapped module so it's functions can be used by the REPL
command. |
20,162 | def loads(s: str, **kwargs) -> JsonObj:
if isinstance(s, (bytes, bytearray)):
s = s.decode(json.detect_encoding(s), )
return json.loads(s, object_hook=lambda pairs: JsonObj(**pairs), **kwargs) | Convert a json_str into a JsonObj
:param s: a str instance containing a JSON document
:param kwargs: arguments see: json.load for details
:return: JsonObj representing the json string |
20,163 | def load_profiles_from_file(self, fqfn):
if self.args.verbose:
print(.format(c.Style.BRIGHT, c.Fore.MAGENTA, fqfn))
with open(fqfn, ) as fh:
data = json.load(fh)
for profile in data:
self.profile_update(profile)
... | Load profiles from file.
Args:
fqfn (str): Fully qualified file name. |
20,164 | def on_train_begin(self, **kwargs):
"Call watch method to log model topology, gradients & weights"
super().on_train_begin()
if not WandbCallback.watch_called:
WandbCallback.watch_called = True
wandb.watch(self.learn.model, log=self.log) | Call watch method to log model topology, gradients & weights |
20,165 | def scoped_session_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with sessions_scope(session):
logger.debug("Running worker %s in scoped DB session", func.__name__)
return func(*args, **kwargs)
return wr... | Manage contexts and add debugging to db sessions. |
20,166 | def copy(self):
return type(self)(self.chr,
self.start+self._start_offset,
self.end,
self.payload,
self.dir) | Create a new copy of selfe. does not do a deep copy for payload
:return: copied range
:rtype: GenomicRange |
20,167 | def webapi_request(url, method=, caller=None, session=None, params=None):
if method not in (, ):
raise NotImplemented("HTTP method: %s" % repr(self.method))
if params is None:
params = {}
onetime = {}
for param in DEFAULT_PARAMS:
params[param] = onetime[param] = params.get(... | Low level function for calling Steam's WebAPI
.. versionchanged:: 0.8.3
:param url: request url (e.g. ``https://api.steampowered.com/A/B/v001/``)
:type url: :class:`str`
:param method: HTTP method (GET or POST)
:type method: :class:`str`
:param caller: caller reference, caller.last_response is... |
20,168 | def calculate_incorrect_name_dict(graph: BELGraph) -> Mapping[str, List[str]]:
missing = defaultdict(list)
for namespace, name in _iterate_namespace_name(graph):
missing[namespace].append(name)
return dict(missing) | Get missing names grouped by namespace. |
20,169 | def state_name(self):
if self.state == 1:
return
elif self.state == 2:
return
elif self.state == 3:
return
elif self.state == 4:
return
elif self.state == 5:
return
elif self.state == 6:
... | Get a human-readable value of the state
Returns:
str: Name of the current state |
20,170 | def _validate_target(self, y):
if y is None:
return
y_type = type_of_target(y)
if y_type not in ("binary", "multiclass"):
raise YellowbrickValueError((
" target type not supported, only binary and multiclass"
).format(y_type)... | Raises a value error if the target is not a classification target. |
20,171 | def origin(self, origin):
ox, oy, oz = origin[0], origin[1], origin[2]
self.SetOrigin(ox, oy, oz)
self.Modified() | Set the origin. Pass a length three tuple of floats |
20,172 | def migrator(self):
migrator = Migrator(self.database)
for name in self.done:
self.run_one(name, migrator)
return migrator | Create migrator and setup it with fake migrations. |
20,173 | def getResponsible(self):
managers = {}
for department in self.getDepartments():
manager = department.getManager()
if manager is None:
continue
manager_id = manager.getId()
if manager_id not in managers:
managers[ma... | Return all manager info of responsible departments |
20,174 | def create_selection():
operation = Forward()
nested = Group(Suppress("(") + operation + Suppress(")")).setResultsName("nested")
select_expr = Forward()
functions = select_functions(select_expr)
maybe_nested = functions | nested | Group(var_val)
operation <<= maybe_nested + OneOrMore(oneOf(... | Create a selection expression |
20,175 | def get_class_field(cls, field_name):
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_fi... | Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model. |
20,176 | def decode(self, encoding=None, errors=):
return self.__class__(super(ColorStr, self).decode(encoding, errors), keep_tags=True) | Decode using the codec registered for encoding. encoding defaults to the default encoding.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other nam... |
20,177 | def _get_chain_by_sid(sid):
try:
return d1_gmn.app.models.Chain.objects.get(sid__did=sid)
except d1_gmn.app.models.Chain.DoesNotExist:
pass | Return None if not found. |
20,178 | def main(host):
client = capnp.TwoPartyClient(host)
calculator = client.bootstrap().cast_as(calculator_capnp.Calculator)
s interesting here is that evaluate() returns a "Value", which is
another interface and therefore points back to an object living on the
server. We then have to call ... | Make a request that just evaluates the literal value 123.
What's interesting here is that evaluate() returns a "Value", which is
another interface and therefore points back to an object living on the
server. We then have to call read() on that object to read it.
However, even though we are making two ... |
20,179 | def _histplot_bins(column, bins=100):
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | Helper to get bins for histplot. |
20,180 | def topological_order_dfs(graph):
n = len(graph)
order = []
times_seen = [-1] * n
for start in range(n):
if times_seen[start] == -1:
times_seen[start] = 0
to_visit = [start]
while to_visit:
node = to_visit[-1]
children = gr... | Topological sorting by depth first search
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of vertices in order
:complexity: `O(|V|+|E|)` |
20,181 | def required_items(element, children, attributes):
required_elements(element, *children)
required_attributes(element, *attributes) | Check an xml element to include given attributes and children.
:param element: ElementTree element
:param children: list of XPaths to check
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
:raises NotValidXmlException: if some child is m... |
20,182 | def _recover_network_failure(self):
if self.auto_reconnect and not self._is_closing:
connected = False
while not connected:
log_msg = "* ATTEMPTING RECONNECT"
if self._retry_new_version:
log_msg = "* RETRYING DIFFERENT DDP VERS... | Recover from a network failure |
20,183 | def set_user_jobs(session, job_ids):
jobs_data = {
: job_ids
}
response = make_put_request(session, , json_data=jobs_data)
json_data = response.json()
if response.status_code == 200:
return json_data[]
else:
raise UserJobsNotSetException(
message=json_dat... | Replace the currently authenticated user's list of jobs with a new list of
jobs |
20,184 | def is_negated(self):
return all(
clause.presence == QueryPresence.PROHIBITED for clause in self.clauses
) | A negated query is one in which every clause has a presence of
prohibited. These queries require some special processing to return
the expected results. |
20,185 | def find_node(self, attribute):
for model in GraphModel._GraphModel__models_instances.itervalues():
for node in foundations.walkers.nodes_walker(model.root_node):
if attribute in node.get_attributes():
return node | Returns the Node with given attribute.
:param attribute: Attribute.
:type attribute: GraphModelAttribute
:return: Node.
:rtype: GraphModelNode |
20,186 | def associations(self, subject, object=None):
if object is None:
if self.associations_by_subj is not None:
return self.associations_by_subj[subject]
else:
return []
else:
if self.associations_by_subj_obj is not None:
... | Given a subject-object pair (e.g. gene id to ontology class id), return all association
objects that match. |
20,187 | def create_ingest_point(self, privateStreamName, publicStreamName):
return self.protocol.execute(,
privateStreamName=privateStreamName,
publicStreamName=publicStreamName) | Creates an RTMP ingest point, which mandates that streams pushed into
the EMS have a target stream name which matches one Ingest Point
privateStreamName.
:param privateStreamName: The name that RTMP Target Stream Names must
match.
:type privateStreamName: str
:param... |
20,188 | def update_rec(self, rec, name, value):
if name == "def":
name = "defn"
if hasattr(rec, name):
if name not in self.attrs_scalar:
if name not in self.attrs_nested:
getattr(rec, name).add(value)
... | Update current GOTerm with optional record. |
20,189 | def write(self, output_filepath):
with open(output_filepath, ) as out_file:
out_file.write(self.__str__()) | serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created |
20,190 | def extended_fade_in(self, segment, duration):
dur = int(duration * segment.track.samplerate)
if segment.start - dur >= 0:
segment.start -= dur
else:
raise Exception(
"Cannot create fade-in that extends "
"past the tracks beginning... | Add a fade-in to a segment that extends the beginning of the
segment.
:param segment: Segment to fade in
:type segment: :py:class:`radiotool.composer.Segment`
:param duration: Duration of fade-in (in seconds)
:returns: The fade that has been added to the composition
:rty... |
20,191 | def _schedule_dependencies(dag):
in_degrees = dict(dag.get_indegrees())
independent_vertices = collections.deque([vertex for vertex in dag if dag.get_indegree(vertex) == 0])
topological_order = []
while independent_vertices:
v_vertex = independent_vertices.po... | Computes an ordering < of tasks so that for any two tasks t and t' we have that if t depends on t' then
t' < t. In words, all dependencies of a task precede the task in this ordering.
:param dag: A directed acyclic graph representing dependencies between tasks.
:type dag: DirectedGraph
... |
20,192 | def stringfy(expr, sym_const=None, sym_states=None, sym_algebs=None):
if not sym_const:
sym_const = []
if not sym_states:
sym_states = []
if not sym_algebs:
sym_algebs = []
expr_str = []
if type(expr) in (int, float):
return expr
if expr.is_Atom:
if e... | Convert the right-hand-side of an equation into CVXOPT matrix operations |
20,193 | def deployment_absent(name, namespace=, **kwargs):
ret = {: name,
: {},
: False,
: }
deployment = __salt__[](name, namespace, **kwargs)
if deployment is None:
ret[] = True if not __opts__[] else None
ret[] =
return ret
if __opts__[]:
... | Ensures that the named deployment is absent from the given namespace.
name
The name of the deployment
namespace
The name of the namespace |
20,194 | def parse_gradient_rgb_args(args):
arglen = len(args)
if arglen < 1 or arglen > 2:
raise InvalidArg(arglen, label=-G\)
start_rgb = try_rgb(args[0]) if args else None
stop_rgb = try_rgb(args[1]) if arglen > 1 else None
return start_rgb, stop_rgb | Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were given. |
20,195 | def compensate_system_time_change(self, difference):
super(Alignak, self).compensate_system_time_change(difference)
self.program_start = max(0, self.program_start + difference)
if not hasattr(self.sched, "conf"):
return
... | Compensate a system time change of difference for all hosts/services/checks/notifs
:param difference: difference in seconds
:type difference: int
:return: None |
20,196 | def repair_central_directory(zipFile, is_file_instance):
f = zipFile if is_file_instance else open(zipFile, )
data = f.read()
pos = data.find(CENTRAL_DIRECTORY_SIGNATURE)
if (pos > 0):
sio = BytesIO(data)
sio.seek(pos + 22)
sio.truncate()
sio.seek(0)
ret... | trims trailing data from the central directory
code taken from http://stackoverflow.com/a/7457686/570216, courtesy of Uri Cohen |
20,197 | def PC_varExplained(Y,standardized=True):
if standardized:
Y-=Y.mean(0)
Y/=Y.std(0)
covY = sp.cov(Y)
S,U = linalg.eigh(covY+1e-6*sp.eye(covY.shape[0]))
S = S[::-1]
rv = np.array([S[0:i].sum() for i in range(1,S.shape[0])])
rv/= S.sum()
return rv | Run PCA and calculate the cumulative fraction of variance
Args:
Y: phenotype values
standardize: if True, phenotypes are standardized
Returns:
var: cumulative distribution of variance explained |
20,198 | def export_content_groups(self, group_id, export_type, skip_notifications=None):
path = {}
data = {}
params = {}
path["group_id"] = group_id
self._validate_enum(export_type, ["common_cartridge", "qti", "zip"])
data... | Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export... |
20,199 | def get_cluster_name(self):
return self._get(
url=self.url + ,
headers=self.headers,
auth=self.auth
) | Name identifying this RabbitMQ cluster. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.