Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,200 | def parse_command_line(self, argv=None):
argv = sys.argv[1:] if argv is None else argv
self.argv = [py3compat.cast_unicode(arg) for arg in argv]
ProviderClass = getattr(providers, self.provider_type)
self.classes.append(ProviderClass)
if any(x in self.argv for... | Parse the jhubctl command line arguments.
This overwrites traitlets' default `parse_command_line` method
and tailors it to jhubctl's needs. |
368,201 | def length_of_overlap(first_start, first_end, second_start, second_end):
if first_end <= second_start or first_start >= second_end:
return 0.0
if first_start < second_start:
if first_end < second_end:
return abs(first_end - second_start)
else:
return abs(sec... | Find the length of the overlapping part of two segments.
Args:
first_start (float): Start of the first segment.
first_end (float): End of the first segment.
second_start (float): Start of the second segment.
second_end (float): End of the second segment.
Return:
float: ... |
368,202 | def _createAssociateRequest(self, endpoint, assoc_type, session_type):
session_type_class = self.session_types[session_type]
assoc_session = session_type_class()
args = {
: ,
: assoc_type,
}
if not endpoint.compatibilityMode():
a... | Create an association request for the given assoc_type and
session_type.
@param endpoint: The endpoint whose server_url will be
queried. The important bit about the endpoint is whether
it's in compatiblity mode (OpenID 1.1)
@param assoc_type: The association type that t... |
368,203 | def install_new_pipeline():
def new_create_pipeline(context, *args, **kwargs):
result = old_create_pipeline(context, *args, **kwargs)
result.insert(1, DAAPObjectTransformer(context))
return result
old_create_pipeline = Pipeline.create_pipeline
Pipeline.create_pipeline = new_c... | Install above transformer into the existing pipeline creator. |
368,204 | def cms_identify(self, url, timeout=15, headers={}):
self.out.debug("cms_identify")
if isinstance(self.regular_file_url, str):
rfu = [self.regular_file_url]
else:
rfu = self.regular_file_url
is_cms = False
for regular_file_url in rfu:
... | Function called when attempting to determine if a URL is identified
as being this particular CMS.
@param url: the URL to attempt to identify.
@param timeout: number of seconds before a timeout occurs on a http
connection.
@param headers: custom HTTP headers as expected by req... |
368,205 | def double_percent_options_to_metadata(options):
matches = _PERCENT_CELL.findall( + options)
if not matches:
return {: options.strip()}
matches = matches[0]
if matches[4]:
metadata = json_options_to_metadata(matches[4], add_brackets=False)
else:
metadat... | Parse double percent options |
368,206 | def com_google_fonts_check_name_typographicsubfamilyname(ttFont, style_with_spaces):
from fontbakery.utils import name_entry_id
failed = False
if style_with_spaces in [,
,
,
]:
for name in ttFont[].names:
if name.nameID... | Check name table: TYPOGRAPHIC_SUBFAMILY_NAME entries. |
368,207 | def convertToBool():
if not OPTIONS.strictBool.value:
return []
REQUIRES.add()
result = []
result.append()
result.append()
result.append()
return result | Convert a byte value to boolean (0 or 1) if
the global flag strictBool is True |
368,208 | def string(self, writesize=None):
if not self.finished:
self.finished = True
return self.content
return | Looks like a file handle |
368,209 | def getCollectorPath(self):
if self.host is None:
return self.path.split()[2]
offset = self.path.index(self.host)
offset += len(self.host) + 1
endoffset = self.path.index(, offset)
return self.path[offset:endoffset] | Returns collector path
servers.host.cpu.total.idle
return "cpu" |
368,210 | def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True):
template_name = template_name or [u % site_name, u]
site_available = u % site_name
upload_template(template_name, site_available, context=context, use_sudo=True)
if enable:
enable_site(site_name) | Upload Nginx site configuration from a template. |
368,211 | def ingest(event):
set_service_status(Service.INGEST, ServiceStatus.BUSY)
notify.notify()
recording_state(event.uid, )
update_event_status(event, Status.UPLOADING)
service = config()
service = service[randrange(0, len(service))]
logger.info( + service)
... | Ingest a finished recording to the Opencast server. |
368,212 | def load_transform(fname):
if fname is None:
return np.eye(4)
if fname.endswith():
return np.loadtxt(fname)
elif fname.endswith():
with open(fname, ) as fobj:
for line in fobj:
if line.startswith(b):
break
lines = fobj... | Load affine transform from file
Parameters
----------
fname : str or None
Filename of an LTA or FSL-style MAT transform file.
If ``None``, return an identity transform
Returns
-------
affine : (4, 4) numpy.ndarray |
368,213 | def select_month(self, month):
def _select_month(month):
return self.data.loc[month, slice(None)]
try:
return self.new(_select_month(month), self.type, self.if_fq)
except:
raise ValueError(.format(month)) | 选择月份
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复 |
368,214 | def make_df_from_batch(batch_name, batch_col="b01", reader=None, reader_label=None):
batch_name = batch_name
batch_col = batch_col
logger.debug(f"batch_name, batch_col: {batch_name}, {batch_col}")
if reader is None:
reader_obj = get_db_reader(reader_label)
reader = reader_obj()
... | Create a pandas DataFrame with the info needed for ``cellpy`` to load
the runs.
Args:
batch_name (str): Name of the batch.
batch_col (str): The column where the batch name is in the db.
reader (method): the db-loader method.
reader_label (str): the label for the db-loader (if db... |
368,215 | def color(string, name, style=, when=):
if name not in colors:
from .text import oxford_comma
raise ValueError("unknown color .\nknown colors are: {}".format(
name, oxford_comma(["".format(x) for x in sorted(colors)])))
if style not in styles:
from .text import oxford_c... | Change the color of the given string. |
368,216 | def first_solar_spectral_loss(self, pw, airmass_absolute):
if in \
self.module_parameters.keys():
coefficients = \
self.module_parameters[]
module_type = None
else:
module_type = self._infer_cell_type()
coeffi... | Use the :py:func:`first_solar_spectral_correction` function to
calculate the spectral loss modifier. The model coefficients are
specific to the module's cell type, and are determined by searching
for one of the following keys in self.module_parameters (in order):
'first_solar_spectra... |
368,217 | def putParamset(self, paramset, data={}):
try:
if paramset in self._PARAMSETS and data:
self._proxy.putParamset(self._ADDRESS, paramset, data)
self.updateParamsets()
return True
el... | Some devices act upon changes to paramsets.
A "putted" paramset must not contain all keys available in the specified paramset,
just the ones which are writable and should be changed. |
368,218 | def motif3struct_bin(A):
from scipy import io
import os
fname = os.path.join(os.path.dirname(__file__), motiflib)
mot = io.loadmat(fname)
m3n = mot[]
id3 = mot[].squeeze()
n = len(A)
f = np.zeros((13,))
F = np.zeros((13, n))
A = binarize(A, copy=True)
As = np.l... | Structural motifs are patterns of local connectivity. Motif frequency
is the frequency of occurrence of motifs around a node.
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
F : 13xN np.ndarray
motif frequency matrix
f : 13x1 n... |
368,219 | def on_push(self, device):
src = device.src.lower()
if last_execution[src] + self.settings.get(, DEFAULT_DELAY) > time.time():
return
last_execution[src] = time.time()
self.execute(device) | Press button. Check DEFAULT_DELAY.
:param scapy.packet.Packet device: Scapy packet
:return: None |
368,220 | def present(name=None, start_addr=None, end_addr=None, data=None, **api_opts):
129.97.150.160129.97.150.170always_update_dnsauthoritycommentrange of IP addresses used for salt.. was used for ghost images deploymentddns_generate_hostnamedeny_all_clientsdeny_bootpdisableemail_listenable_ddnsenable_dhcp_thresholdsenab... | Ensure range record is present.
infoblox_range.present:
start_addr: '129.97.150.160',
end_addr: '129.97.150.170',
Verbose state example:
.. code-block:: yaml
infoblox_range.present:
data: {
'always_update_dns': False,
'authority': False... |
368,221 | def parse_hostname(hostname, default_port):
try:
host, sep, port = hostname.strip().rpartition()
if not port:
return None
if not host:
host = port
port = default_port
if host.count() == 1:
host, sep, por... | Parse hostname string and return a tuple of (host, port)
If port missing in hostname string then use default_port
If anything is not a valid then return None
hostname should contain a host and an option space delimited port
host port
As an attempt to prevent foolish mistakes the parser also tries ... |
368,222 | def find(*_, **kwargs):
click.echo(green())
click.echo(green( * 40))
with get_app().app_context():
user = find_user(kwargs)
if not user:
click.echo(red())
return
click.echo(str(user) + )
return | Find user by id/email |
368,223 | def create_entity(self,
workspace_id,
entity,
description=None,
metadata=None,
fuzzy_match=None,
values=None,
**kwargs):
if workspace_id is None:
... | Create entity.
Create a new entity, or enable a system entity.
This operation is limited to 1000 requests per 30 minutes. For more information,
see **Rate limiting**.
:param str workspace_id: Unique identifier of the workspace.
:param str entity: The name of the entity. This st... |
368,224 | def winning_name(self):
if self.winner == HOME:
if not in str(self._home_name):
return str(self._home_name)
return self._home_name.text()
if not in str(self._away_name):
return str(self._away_name)
return self._away_name.text() | Returns a ``string`` of the winning team's name, such as 'Purdue
Boilermakers'. |
368,225 | def dumps():
d = {}
for k, v in FILTERS.items():
d[dr.get_name(k)] = list(v)
return _dumps(d) | Returns a string representation of the FILTERS dictionary. |
368,226 | def _enum_from_direction(direction):
if isinstance(direction, int):
return direction
if direction == Query.ASCENDING:
return enums.StructuredQuery.Direction.ASCENDING
elif direction == Query.DESCENDING:
return enums.StructuredQuery.Direction.DESCENDING
else:
msg = _... | Convert a string representation of a direction to an enum.
Args:
direction (str): A direction to order by. Must be one of
:attr:`~.firestore.Query.ASCENDING` or
:attr:`~.firestore.Query.DESCENDING`.
Returns:
int: The enum corresponding to ``direction``.
Raises:
... |
368,227 | def parseFilename(filename):
_indx = filename.find()
if _indx > 0:
_fname = filename[:_indx]
extn = filename[_indx+1:-1]
if repr(extn).find() > 1:
_extns = extn.split()
_extn = [_extns[0],int(_extns[1])]
... | Parse out filename from any specified extensions.
Returns rootname and string version of extension name.
Modified from 'pydrizzle.fileutil' to allow this
module to be independent of PyDrizzle/MultiDrizzle. |
368,228 | def _parse_common_paths_file(project_path):
common_paths_file = os.path.join(project_path, )
tree = etree.parse(common_paths_file)
paths = {}
path_vars = [, , , , ,
]
for path_var in path_vars:
specific_path = tree.find(.format(path_var)... | Parses a common_paths.xml file and returns a dictionary of paths,
a dictionary of annotation level descriptions and the filename
of the style file.
Parameters
----------
project_path : str
path to the root directory of the MMAX project
Returns
------... |
368,229 | def put(self, resource):
endpoint = self.endpoint
if resource.id:
endpoint = self._build_url(endpoint, resource.id)
response = self.api.execute("PUT", endpoint, json=resource.as_dict())
if not response.ok:
raise Error.parse(response.json())
r... | Edits an existing resource
Args:
resource - gophish.models.Model - The resource instance |
368,230 | def get_module_names(p):
mods = list()
mods = [f.split()[0] for f in listdir(p)
if isfile(join(p, f)) and not f.endswith() and not f.startswith()]
print len(mods)
return mods | Accepts a path to search for modules. The method will filter on files
that end in .pyc or files that start with __.
Arguments:
p (string): The path to search
Returns:
list of file names |
368,231 | def parse_at_element(
self,
element,
state
):
xml_value = self._processor.parse_at_element(element, state)
return _hooks_apply_after_parse(self._hooks, state, xml_value) | Parse the given element. |
368,232 | def delete_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs)
else:
(data) = s... | Delete certificate issuer configuration. # noqa: E501
Delete the configured certificate issuer configuration. You can only delete the configurations of custom certificates. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass... |
368,233 | def _start_monitoring(self):
before = self._file_timestamp_info(self.path)
while True:
gevent.sleep(1)
after = self._file_timestamp_info(self.path)
added = [fname for fname in after.keys() if fname not in before.keys()]
removed... | Internal method that monitors the directory for changes |
368,234 | def check_constraints(self, instance):
recalc_fields = []
for constraint in self.constraints:
try:
constraint(self.model, instance)
except constraints.InvalidConstraint as e:
recalc_fields.extend(e.fields)
return recalc_fields | Return fieldnames which need recalculation. |
368,235 | def survey(self, pk=None, **kwargs):
job_template = self.get(pk=pk, **kwargs)
if settings.format == :
settings.format =
return client.get(self._survey_endpoint(job_template[])).json() | Get the survey_spec for the job template.
To write a survey, use the modify command with the --survey-spec parameter.
=====API DOCS=====
Get the survey specification of a resource object.
:param pk: Primary key of the resource to retrieve survey from. Tower CLI will only attempt to
... |
368,236 | def maybe(func):
name = object_name(func)
@wraps(func)
def maybe_wrapped(*args, **kwargs):
fails = [
(name, k, v)
for k, v in chain(enumerate(args), kwargs.items())
if isinstance(v, Fail)]
if fails:
return Fail(func, fails=fail... | Calls `f` in a try/except block, returning a `Fail` object if
the call fails in any way. If any of the arguments to the call are Fail
objects, the call is not attempted. |
368,237 | def user(self, message):
if Settings.UserLogs:
self._write_log(Settings.UserLogPrefix, Settings.UserLogTime, message) | Creates a user log (if user logging is turned on)
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
Note: Does *not* use Java string formatting like Sikuli.
Format your message with Python ``basestring.format()`` instead. |
368,238 | def num_tasks(self, work_spec_name):
return self.num_finished(work_spec_name) + \
self.num_failed(work_spec_name) + \
self.registry.len(WORK_UNITS_ + work_spec_name) | Get the total number of work units for some work spec. |
368,239 | def _data(self):
if self.is_caching:
return self.cache
with open(self.path, "r") as f:
return json.load(f) | A simpler version of data to avoid infinite recursion in some cases.
Don't use this. |
368,240 | def sorted_proposals(proposals, scopepref=None, typepref=None):
sorter = _ProposalSorter(proposals, scopepref, typepref)
return sorter.get_sorted_proposal_list() | Sort a list of proposals
Return a sorted list of the given `CodeAssistProposal`\s.
`scopepref` can be a list of proposal scopes. Defaults to
``['parameter_keyword', 'local', 'global', 'imported',
'attribute', 'builtin', 'keyword']``.
`typepref` can be a list of proposal types. Defaults to
`... |
368,241 | def set_storage_controller_bootable(self, name, bootable):
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
if not isinstance(bootable, bool):
raise TypeError("bootable can only be an instance of type bool")
... | Sets the bootable flag of the storage controller with the given name.
in name of type str
in bootable of type bool
raises :class:`VBoxErrorObjectNotFound`
A storage controller with given name doesn't exist.
raises :class:`VBoxErrorObjectInUse`
Another ... |
368,242 | def assortativity_wei(CIJ, flag=0):
if flag == 0:
str = strengths_und(CIJ)
i, j = np.where(np.triu(CIJ, 1) > 0)
K = len(i)
stri = str[i]
strj = str[j]
else:
ist, ost = strengths_dir(CIJ)
i, j = np.where(CIJ > 0)
K = len(i)
if flag... | The assortativity coefficient is a correlation coefficient between the
strengths (weighted degrees) of all nodes on two opposite ends of a link.
A positive assortativity coefficient indicates that nodes tend to link to
other nodes with the same or similar strength.
Parameters
----------
CIJ : N... |
368,243 | def append(self, other):
self.data.extend(other.data)
self.height = self.height + other.height
return self | Append a Printable Image at the end of the current instance.
:param other: another PrintableImage
:return: PrintableImage containing data from both self and other |
368,244 | def wgs84_to_utm(lng, lat, utm_crs=None):
if utm_crs is None:
utm_crs = get_utm_crs(lng, lat)
return transform_point((lng, lat), CRS.WGS84, utm_crs) | Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically.
:param lng: longitude in WGS84 system
:type lng: float
:param lat: latitude in WGS84 system
:type lat: float
:param utm_crs: UTM coordinate reference system enum constants
:type utm_crs: constants.CRS o... |
368,245 | def get_consumed_read_units_percent(
table_name, gsi_name, lookback_window_start=15, lookback_period=5):
try:
metrics = __get_aws_metric(
table_name,
gsi_name,
lookback_window_start,
lookback_period,
)
except BotoServerError:
... | Returns the number of consumed read units in percent
:type table_name: str
:param table_name: Name of the DynamoDB table
:type gsi_name: str
:param gsi_name: Name of the GSI
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lo... |
368,246 | def get_queryset(self):
kwargs = {: self.model, : self._db}
if hasattr(self, ):
kwargs[] = self._hints
return self._queryset_class(**kwargs).filter(is_removed=False) | Return queryset limited to not removed entries. |
368,247 | def update_name( self, name ):
checklistitem_json = self.fetch_json(
uri_path = self.base_uri + ,
http_method = ,
query_params = {: name}
)
return self.create_checklist_item(self.idCard, self.idChecklist, checklistitem_json) | Rename the current checklist item. Returns a new ChecklistItem object. |
368,248 | def remove_child(self, *sprites):
scene = self.get_scene()
if scene:
child_sprites = list(self.all_child_sprites())
if scene._focus_sprite in child_sprites:
scene._focus_sprite = None
for sprite in sprites:
if sprite in se... | Remove one or several :class:`Sprite` sprites from scene |
368,249 | def slice(self, start_time, end_time, strict=False):
sliced_array = AnnotationArray()
for ann in self:
sliced_array.append(ann.slice(start_time, end_time, strict=strict))
return sliced_array | Slice every annotation contained in the annotation array using
`Annotation.slice`
and return as a new AnnotationArray
See `Annotation.slice` for details about slicing. This function does
not modify the annotations in the original annotation array.
Parameters
----------
... |
368,250 | def evaluate(x, amplitude, mean, stddev):
return 1.0 - Gaussian1D.evaluate(x, amplitude, mean, stddev) | GaussianAbsorption1D model function. |
368,251 | def load_deploy_config(deploy_filename, config=None):
if not config:
config = Config()
if not deploy_filename:
return
if path.exists(deploy_filename):
extract_file_config(deploy_filename, config)
return config | Loads any local config overrides in the deploy file. |
368,252 | def removed(name, ruby=None, user=None, gem_bin=None):
ret = {: name, : None, : , : {}}
if name not in __salt__[](name, ruby, gem_bin=gem_bin, runas=user):
ret[] = True
ret[] =
return ret
if __opts__[]:
ret[] = .format(name)
return ret
if __salt__[](name, ... | Make sure that a gem is not installed.
name
The name of the gem to uninstall
gem_bin : None
Full path to ``gem`` binary to use.
ruby : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.
user: None
The u... |
368,253 | def sb_filter(fastq, bc, cores, nedit):
barcodes = set(sb.strip() for sb in bc)
if nedit == 0:
filter_sb = partial(exact_sample_filter2, barcodes=barcodes)
else:
barcodehash = MutationHash(barcodes, nedit)
filter_sb = partial(correcting_sample_filter2, barcodehash=barcodehash)
... | Filters reads with non-matching sample barcodes
Expects formatted fastq files. |
368,254 | def paramnames(co):
flags = co.co_flags
varnames = co.co_varnames
argcount, kwonlyargcount = co.co_argcount, co.co_kwonlyargcount
total = argcount + kwonlyargcount
args = varnames[:argcount]
kwonlyargs = varnames[argcount:total]
varargs, varkwargs = None, None
if flags & Flag.CO_V... | Get the parameter names from a pycode object.
Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs).
varargs and varkwargs will be None if the function doesn't take *args or
**kwargs, respectively. |
368,255 | def set_manip(self, manip, ovs_sm=None, ovs_lg=None, name=):
o3d_manip_id = self.create_o3d_asset(manip,
small_ov_set=ovs_sm,
large_ov_set=ovs_lg,
display_name=name)
... | stub |
368,256 | def cluster(points, radius):
if isinstance(points, vtk.vtkActor):
poly = points.GetMapper().GetInput()
else:
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(points))
src.Update()
vpts = src.GetOutput().GetPoints()
for i, p in enumerate(points):
... | Clustering of points in space.
`radius` is the radius of local search.
Individual subsets can be accessed through ``actor.clusters``.
.. hint:: |clustering| |clustering.py|_ |
368,257 | def multipublish(self, topic, messages, block=True, timeout=None,
raise_error=True):
result = AsyncResult()
conn = self._get_connection(block=block, timeout=timeout)
try:
self._response_queues[conn].append(result)
conn.multipublish(topic, me... | Publish an iterable of messages to the given topic.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
a... |
368,258 | def execute_cross_join(op, left, right, **kwargs):
key = "cross_join_{}".format(ibis.util.guid())
join_key = {key: True}
new_left = left.assign(**join_key)
new_right = right.assign(**join_key)
on=key,
copy=False,
suffixes=constants.JOIN_SUFFIXES,
)
d... | Execute a cross join in pandas.
Notes
-----
We create a dummy column of all :data:`True` instances and use that as the
join key. This results in the desired Cartesian product behavior guaranteed
by cross join. |
368,259 | def diff(local_path, remote_path):
with hide():
if isinstance(local_path, basestring):
with open(local_path) as stream:
local_content = stream.read()
else:
pos = local_path.tell()
local_content = local_path.read()
local_path.seek(p... | Return true if local and remote paths differ in contents |
368,260 | def _le_from_lt(self, other):
op_result = self.__lt__(other)
return op_result or self == other | Return a <= b. Computed by @total_ordering from (a < b) or (a == b). |
368,261 | def polish(commit_indexes=None, urls=None):
def decorator(f):
if commit_indexes:
f.polish_commit_indexes = commit_indexes
if urls:
f.polish_urls = urls
@wraps(f)
def wrappee(*args, **kwargs):
return f(*args, **kwargs)
return wrappee
... | Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots
For example, if you have 10 commits in a row where static file links were broken, you could re-write the html
in memory as it is interpreted.
Keyword arguments:
commit_indexes -- A list of indexes to a... |
368,262 | def subclass_exception(name, parents, module, attached_to=None):
class_dict = {: module}
if attached_to is not None:
def __reduce__(self):
return (unpickle_inner_exception, (attached_to, name), self.args)
def __setstate__(self, args):
self.... | Create exception subclass.
If 'attached_to' is supplied, the exception will be created in a way that
allows it to be pickled, assuming the returned exception class will be added
as an attribute to the 'attached_to' class. |
368,263 | def set_monitor(self, monitor):
if type(monitor) != bool:
raise InvalidInput("Monitor value must be bool")
self._roast[] = bool2int(monitor)
self._q.put(self._config)
if self._roast[]:
self._roast_start = now_time(str=True)
self._roast[] = se... | Set the monitor config.
This module assumes that users will connect to the roaster and get
reading information _before_ they want to begin collecting roast
details. This method is critical to enabling the collection of roast
information and ensuring it gets saved in memory.
:pa... |
368,264 | def has_src_builder(self):
try:
scb = self.sbuilder
except AttributeError:
scb = self.sbuilder = self.find_src_builder()
return scb is not None | Return whether this Node has a source builder or not.
If this Node doesn't have an explicit source code builder, this
is where we figure out, on the fly, if there's a transparent
source code builder for it.
Note that if we found a source builder, we also set the
self.builder at... |
368,265 | def _WorkerCommand_launcher(self):
return [
self.workersArguments.pythonExecutable,
,
,
str(self.workerAmount),
str(self.workersArguments.verbose),
] | Return list commands to start the bootstrap process |
368,266 | def compute(self, x, yerr=0.0, **kwargs):
self._x = self.parse_samples(x)
self._x = np.ascontiguousarray(self._x, dtype=np.float64)
try:
self._yerr2 = float(yerr)**2 * np.ones(len(x))
except TypeError:
self._yerr2 = self._check_dimensions(yerr) *... | Pre-compute the covariance matrix and factorize it for a set of times
and uncertainties.
:param x: ``(nsamples,)`` or ``(nsamples, ndim)``
The independent coordinates of the data points.
:param yerr: (optional) ``(nsamples,)`` or scalar
The Gaussian uncertainties on the... |
368,267 | def write_electrodes(self, filename):
fid = open(filename, )
for i in self.Electrodes:
fid.write(.format(self.Points[i][0], self.Points[i][1]))
fid.close() | Write X Y coordinates of electrodes |
368,268 | def _ensure_initialized(cls, instance=None, gateway=None, conf=None):
with SparkContext._lock:
if not SparkContext._gateway:
SparkContext._gateway = gateway or launch_gateway(conf)
SparkContext._jvm = SparkContext._gateway.jvm
if instance:
... | Checks whether a SparkContext is initialized or not.
Throws error if a SparkContext is already running. |
368,269 | def tag_add(self, *tags):
return View({**self.spec, : list(set(self.tags) | set(tags))}) | Return a view with the specified tags added |
368,270 | def list_upgrades(refresh=True, backtrack=3, **kwargs):
*
if salt.utils.data.is_true(refresh):
refresh_db()
return _get_upgradable(backtrack) | List all available package upgrades.
refresh
Whether or not to sync the portage tree before checking for upgrades.
backtrack
Specifies an integer number of times to backtrack if dependency
calculation fails due to a conflict or an unsatisfied dependency
(default: ´3´).
... |
368,271 | def load_card(self, code, cache=True):
card = self.card_cache.get(code, None)
if card is None:
code = code if isinstance(code, str) else str(code)
with sqlite3.connect(self.dbname) as carddb:
result = carddb.execute(
"SELECT * FROM CAR... | Load a card with the given code from the database. This calls each
save event hook on the save string before commiting it to the database.
Will cache each resulting card for faster future lookups with this
method while respecting the libraries cache limit. However only if the
cache argu... |
368,272 | def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol=):
s API.
This is data on blockcypher
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key or not private,
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
... | Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain. |
368,273 | def sort_seeds(uhandle, usort):
cmd = ["sort", "-k", "2", uhandle, "-o", usort]
proc = sps.Popen(cmd, close_fds=True)
proc.communicate() | sort seeds from cluster results |
368,274 | def get_dependency_graph(self):
from rez.vendor.pygraph.classes.digraph import digraph
nodes = {}
edges = set()
for variant in self._resolved_packages:
nodes[variant.name] = variant.qualified_package_name
for request in variant.get_requires():
... | Generate the dependency graph.
The dependency graph is a simpler subset of the resolve graph. It
contains package name nodes connected directly to their dependencies.
Weak references and conflict requests are not included in the graph.
The dependency graph does not show conflicts.
... |
368,275 | def do_cleanup(self, subcmd, opts, *args):
print " opts: %s" % (subcmd, opts)
print " args: %s" % (subcmd, args) | Recursively clean up the working copy, removing locks, resuming
unfinished operations, etc.
usage:
cleanup [PATH...]
${cmd_option_list} |
368,276 | def getEffort(self, vehID, time, edgeID):
self._connection._beginMessage(tc.CMD_GET_VEHICLE_VARIABLE,
tc.VAR_EDGE_EFFORT, vehID, 1 + 4 + 1 + 4 + 1 + 4 + len(edgeID))
self._connection._string += struct.pack(
"!BiBi", tc.TYPE_COMPOUND, 2, tc.TYPE... | getEffort(string, double, string) -> double
. |
368,277 | def register_command(self, name: str, f: Callable):
self._commands.append((name, f)) | Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to defi... |
368,278 | def clear(self):
if self._cache is not None:
with self._cache as c, self._out as out:
self.in_flush_all = True
c.clear()
out.clear()
self.in_flush_all = False | Clears this instance's cache. |
368,279 | def get_element_attribute(elem_to_parse, attrib_name, default_value=u):
element = get_element(elem_to_parse)
if element is None:
return default_value
return element.attrib.get(attrib_name, default_value) | :return: an attribute from the parsed element if it has the attribute,
otherwise the default value |
368,280 | def _build_basic_context(self):
topclasses = self.ontospy_graph.toplayer_classes[:]
if len(topclasses) < 3:
for topclass in self.ontospy_graph.toplayer_classes:
for child in topclass.children():
if child not in topclasses: topclasses.ap... | Return a standard dict used in django as a template context |
368,281 | def realpath(self, spec, key):
if key not in spec:
return
if not spec[key]:
logger.warning(
"cannot resolve realpath of as it is not defined", key)
return
check = realpath(join(spec.get(WORKING_DIR, ), spec[key]))
... | Resolve and update the path key in the spec with its realpath,
based on the working directory. |
368,282 | def unpackVersion(ver):
major = (ver >> 20 * 2) & mask20
minor = (ver >> 20) & mask20
patch = ver & mask20
return major, minor, patch | Unpack a system normalized integer representing a softare version into its component parts.
Args:
ver (int): System normalized integer value to unpack into a tuple.
Returns:
(int, int, int): A tuple containing the major, minor and patch values shifted out of the integer. |
368,283 | def getRecommendedRenderTargetSize(self):
fn = self.function_table.getRecommendedRenderTargetSize
pnWidth = c_uint32()
pnHeight = c_uint32()
fn(byref(pnWidth), byref(pnHeight))
return pnWidth.value, pnHeight.value | Suggested size for the intermediate render target that the distortion pulls from. |
368,284 | def _init_metadata(self):
super(PDFPreviewFormRecord, self)._init_metadata()
self._preview_metadata = {
: Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
),
: ,
: ,
... | stub |
368,285 | def filename_add_custom_url_params(filename, request):
if hasattr(request, ) and request.custom_url_params is not None:
for param, value in sorted(request.custom_url_params.items(),
key=lambda parameter_item: parameter_item[0].value):
f... | Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url p... |
368,286 | def last_blank(src):
if not src: return False
ll = src.splitlines()[-1]
return (ll == ) or ll.isspace() | Determine if the input source ends in a blank.
A blank is either a newline or a line consisting of whitespace.
Parameters
----------
src : string
A single or multiline string. |
368,287 | def mkdirs(remote_dir, use_sudo=False):
func = use_sudo and sudo or run
result = func(.join([,remote_dir])).split()
return result | Wrapper around mkdir -pv
Returns a list of directories created |
368,288 | def render_binary(self, context, result):
context.response.app_iter = iter((result, ))
return True | Return binary responses unmodified. |
368,289 | def map_pixel(point_x, point_y, cellx, celly, xmin, ymax):
point_x = np.asarray(point_x)
point_y = np.asarray(point_y)
col = np.floor((point_x - xmin) / cellx).astype(int)
row = np.floor((point_y - ymax) / celly).astype(int)
return row, col | Usage:
map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax)
where:
xmin is leftmost X coordinate in system
ymax is topmost Y coordinate in system
Example:
raster = HMISea.tif
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(raster)
... |
368,290 | def element_to_object(elem_to_parse, element_path=None):
if isinstance(elem_to_parse, STRING_TYPES) or hasattr(elem_to_parse, ):
elem_to_parse = strip_namespaces(elem_to_parse)
if element_path is not None:
elem_to_parse = get_element(elem_to_parse, element_path)
element_tree... | :return: the root key, and a dict with all the XML data, but without preserving structure, for instance:
<elem val="attribute"><val>nested text</val><val prop="attr">nested dict text</val>nested dict tail</elem>
{'elem': {
'val': [
u'nested text',
{'prop': u'attr', 'value': [u'n... |
368,291 | def open_state_machine(path=None, recent_opened_notification=False):
start_time = time.time()
if path is None:
if interface.open_folder_func is None:
logger.error("No function defined for opening a folder")
return
load_path = interface.open_folder_func("Please choose... | Open a state machine from respective file system path
:param str path: file system path to the state machine
:param bool recent_opened_notification: flags that indicates that this call also should update recently open
:rtype rafcon.core.state_machine.StateMachine
:return: opened state machine |
368,292 | def validate_cookies(session, class_name):
if not do_we_have_enough_cookies(session.cookies, class_name):
return False
url = CLASS_URL.format(class_name=class_name) +
r = session.head(url, allow_redirects=False)
if r.status_code == 200:
return True
else:
logging.debug... | Checks whether we have all the required cookies
to authenticate on class.coursera.org. Also check for and remove
stale session. |
368,293 | def create_lbaas_member(self, lbaas_pool, body=None):
return self.post(self.lbaas_members_path % lbaas_pool, body=body) | Creates a lbaas_member. |
368,294 | def process_presence(self, stanza):
stanza_type = stanza.stanza_type
return self.__try_handlers(self._presence_handlers, stanza, stanza_type) | Process presence stanza.
Pass it to a handler of the stanza's type and payload namespace.
:Parameters:
- `stanza`: presence stanza to be handled |
368,295 | def call_status(*args, **kwargs):
***
res = dict()
devices = _get_lights()
for dev_id in not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
dev_id = six.text_type(dev_id)
res[dev_id] = {
: devices[dev_id][][],
: devices[dev_id][][]
}
r... | Return the status of the lamps.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.status
salt '*' hue.status id=1
salt '*' hue.status id=1,2,3 |
368,296 | def get_arg_parse_arguments(self):
ret = dict()
if self._required:
if self.value is not None:
ret["default"] = self.value
else:
ret["required"] = True
ret["dest"] = self._name
if not self.e_type_exclude:
if sel... | During the element declaration, all configuration file requirements
and all cli requirements have been described once.
This method will build a dict containing all argparse options.
It can be used to feed argparse.ArgumentParser.
You does not need to have multiple declarations. |
368,297 | def techport(Id):
base_url =
if not isinstance(Id, str):
raise ValueError("The Id arg you provided is not the type of str")
else:
base_url += Id
return dispatch_http_get(base_url) | In order to use this capability, queries can be issued to the system with the following URI
format:
GET /xml-api/id_parameter
Parameter Required? Value Description
id_parameter Yes Type: String
Default: None
The id value of the TechPort record.
TechPort values range from 0-20000.
Not all... |
368,298 | def validate(self, generator, axesToMove=None, **kwargs):
iterations = 10
for k, default in self._block.configure.defaults.items():
if k not in kwargs:
kwargs[k] = default
params = ConfigureParams(generator, axesToMove, **kwargs)
... | Validate configuration parameters and return validated parameters.
Doesn't take device state into account so can be run in any state |
368,299 | def _watchdog_queue(self):
while not self.quit:
k = self.queue.get()
if k == self.keys[]:
self.quit = True
self.switch_queue.put()
elif k == self.keys[]:
self.data.bye()
self.player.start_queue(self)
... | 从queue里取出字符执行命令 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.