Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
20,500 | def getFiledAgainst(self, filedagainst_name, projectarea_id=None,
projectarea_name=None, archived=False):
self.log.debug("Try to get <FiledAgainst %s>", filedagainst_name)
if not isinstance(filedagainst_name,
six.string_types) or not filedagain... | Get :class:`rtcclient.models.FiledAgainst` object by its name
:param filedagainst_name: the filedagainst name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether ... |
20,501 | def prepare_encoder(inputs, hparams, attention_type="local_1d"):
x = prepare_image(inputs, hparams, name="enc_channels")
x = add_pos_signals(x, hparams, "enc_pos")
x_shape = common_layers.shape_list(x)
if attention_type == "local_1d":
x = tf.reshape(x, [x_shape[0], x_shape[1]*x_shape[2], hparams.hidde... | Prepare encoder for images. |
20,502 | def x_lower_limit(self, limit=None):
if limit is None:
if self._x_lower_limit is None:
if self.smallest_x() < 0:
if self.smallest_x() == self.largest_x():
return int(self.smallest_x() - 1)
else:
... | Returns or sets (if a value is provided) the value at which the
x-axis should start. By default this is zero (unless there are negative
values).
:param limit: If given, the chart's x_lower_limit will be set to this.
:raises ValueError: if you try to make the lower limit larger than the\... |
20,503 | def element(element, name, default=None):
element_value = element.find(name)
return element_value.text if element_value is not None else default | Returns the value of an element, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param name: The name of the element to evaluate
:type name: str
:param default: The default value to return if the element is not defined |
20,504 | def _next_regular(target):
if target <= 6:
return target
p5 = 1
while p5 < target:
p35 = p5
while p35 < target:
quotient = -(-target // p35)
try:
p2 = 2 ** ((quotient - 1).bit_length())
... | Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.
Target must be a positive integer. |
20,505 | def _get_result_paths(self, data):
assignment_fp = str(self.Parameters[].Value).strip()
if not os.path.isabs(assignment_fp):
assignment_fp = os.path.relpath(assignment_fp, self.WorkingDir)
return {: ResultPath(assignment_fp, IsWritten=True)} | Return a dict of ResultPath objects representing all possible output |
20,506 | def cutadaptit_pairs(data, sample):
LOGGER.debug("Entering cutadaptit_pairs - {}".format(sample.name))
sname = sample.name
finput_r1 = sample.files.concat[0][0]
finput_r2 = sample.files.concat[0][1]
if not data.... | Applies trim & filters to pairs, including adapter detection. If we have
barcode information then we use it to trim reversecut+bcode+adapter from
reverse read, if not then we have to apply a more general cut to make sure
we remove the barcode, this uses wildcards and so will have more false
positives... |
20,507 | def simplex_connect(self, solution_g):
component
nl = solution_g.get_node_list()
current = nl[0]
pred = solution_g.simplex_search(current, current)
separated = list(pred.keys())
for n in nl:
if solution_g.get_node(n).get_attr() != current:
... | API:
simplex_connect(self, solution_g)
Description:
At this point we assume that the solution does not have a cycle.
We check if all the nodes are connected, if not we add an arc to
solution_g that does not create a cycle and return True. Otherwise
we ... |
20,508 | def get_revisions(page, page_num=1):
revisions = page.revisions.order_by()
current = page.get_latest_revision()
if current:
revisions.exclude(id=current.id)
paginator = Paginator(revisions, 5)
try:
revisions = paginator.page(page_num)
except PageNotAnInteger:
... | Returns paginated queryset of PageRevision instances for
specified Page instance.
:param page: the page instance.
:param page_num: the pagination page number.
:rtype: django.db.models.query.QuerySet. |
20,509 | def tag_add(self, item, tag):
tags = self.item(item, "tags")
self.item(item, tags=tags + (tag,)) | Add tag to the tags of item.
:param item: item identifier
:type item: str
:param tag: tag name
:type tag: str |
20,510 | def save_params(self, fname):
arg_params, aux_params = self.get_params()
save_dict = {( % k) : v.as_in_context(cpu()) for k, v in arg_params.items()}
save_dict.update({( % k) : v.as_in_context(cpu()) for k, v in aux_params.items()})
ndarray.save(fname, save_dict) | Saves model parameters to file.
Parameters
----------
fname : str
Path to output param file.
Examples
--------
>>> # An example of saving module parameters.
>>> mod.save_params('myfile') |
20,511 | def DbGetProperty(self, argin):
self._log.debug("In DbGetProperty()")
object_name = argin[0]
return self.db.get_property(object_name, argin[1:]) | Get free object property
:param argin: Str[0] = Object name
Str[1] = Property name
Str[n] = Property name
:type: tango.DevVarStringArray
:return: Str[0] = Object name
Str[1] = Property number
Str[2] = Property name
Str[3] = Property value number (array ca... |
20,512 | def _proxy(self):
if self._context is None:
self._context = PhoneNumberContext(self._version, phone_number=self._solution[], )
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: PhoneNumberContext for this PhoneNumberInstance
:rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext |
20,513 | def _add_to_typedef(self, typedef_curr, line, lnum):
mtch = re.match(r, line)
if mtch:
field_name = mtch.group(1)
field_value = mtch.group(2).split()[0].rstrip()
if field_name == "id":
self._chk_none(typedef_curr.id, lnum)
typ... | Add new fields to the current typedef. |
20,514 | def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN,
max_len=MAX_STRLEN, **kwargs):
from syn.five import unichr
return unicode(rand_str(min_char, max_char, min_len, max_len, unichr)) | For values in the unicode range, regardless of Python version. |
20,515 | def create(cls, name, protocol_number, protocol_agent=None, comment=None):
json = {: name,
: protocol_number,
: element_resolver(protocol_agent) or None,
: comment}
return ElementCreator(cls, json) | Create the IP Service
:param str name: name of ip-service
:param int protocol_number: ip proto number for this service
:param str,ProtocolAgent protocol_agent: optional protocol agent for
this service
:param str comment: optional comment
:raises CreateElementFailed: ... |
20,516 | def errprt(op, lenout, inlist):
lenout = ctypes.c_int(lenout)
op = stypes.stringToCharP(op)
inlist = ctypes.create_string_buffer(str.encode(inlist), lenout.value)
inlistptr = ctypes.c_char_p(ctypes.addressof(inlist))
libspice.errdev_c(op, lenout, inlistptr)
return stypes.toPythonString(inli... | Retrieve or set the list of error message items to be output when an
error is detected.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errprt_c.html
:param op: The operation, "GET" or "SET".
:type op: str
:param lenout: Length of list for output.
:type lenout: int
:param inlist: S... |
20,517 | def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"):
field2 = nrefocus.refocus(field=self.field,
d=distance/self["pixel size"],
nm=self["medium index"],
res=self["wavelength"]/self... | Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: str, h5py.Group, h5py.File, or None
A path to an hdf5 data file where the... |
20,518 | def setGroupIcon( cls, groupName, icon ):
if ( cls._groupIcons is None ):
cls._groupIcons = {}
cls._groupIcons[nativestring(groupName)] = icon | Sets the group icon for the wizard plugin to the inputed icon.
:param groupName | <str>
icon | <str> |
20,519 | def multivariate_neg_logposterior(self,beta):
post = self.neg_loglik(beta)
for k in range(0,self.z_no):
if self.latent_variables.z_list[k].prior.covariance_prior is True:
post += -self.latent_variables.z_list[k].prior.logpdf(self.custom_covariance(beta))
... | Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log posterior |
20,520 | def set_owner(self):
owner = self.soup.find()
try:
self.owner_name = owner.find().string
except AttributeError:
self.owner_name = None
try:
self.owner_email = owner.find().string
except AttributeError:
self.owner_email = No... | Parses owner name and email then sets value |
20,521 | def inFocus(self):
previous_flags = self.window.flags()
self.window.setFlags(previous_flags |
QtCore.Qt.WindowStaysOnTopHint) | Set GUI on-top flag |
20,522 | def import_event_definition_elements(diagram_graph, element, event_definitions):
element_id = element.getAttribute(consts.Consts.id)
event_def_list = []
for definition_type in event_definitions:
event_def_xml = element.getElementsByTagNameNS("*", definition_type)
... | Helper function, that adds event definition elements (defines special types of events) to corresponding events.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param element: object representing a BPMN XML event element,
:param event_definitions: list of event definit... |
20,523 | def attach_to_fbo(self):
gl.glFramebufferTexture2DEXT(gl.GL_FRAMEBUFFER_EXT, self.attachment_point, self.target0, self.id, 0) | Attach the texture to a bound FBO object, for rendering to texture. |
20,524 | def prep_fastq_inputs(in_files, data):
if len(in_files) == 1 and _is_bam_input(in_files):
out = _bgzip_from_bam(in_files[0], data["dirs"], data)
elif len(in_files) == 1 and _is_cram_input(in_files):
out = _bgzip_from_cram(in_files[0], data["dirs"], data)
elif len(in_files) in [1, 2] and... | Prepare bgzipped fastq inputs |
20,525 | def _bbox(nodes):
left, bottom = np.min(nodes, axis=1)
right, top = np.max(nodes, axis=1)
return left, right, bottom, top | Get the bounding box for set of points.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): A set of points.
Returns:
Tuple[float, float, float, float]: The left, right,
bottom and top... |
20,526 | def _create_related(self, obj, related, subfield_dict):
for field, items in related.items():
subobjects = []
all_subrelated = []
Subtype, reverse_id_field, subsubdict = subfield_dict[field]
for order, item in enumerate(items):
... | create DB objects related to a base object
obj: a base object to create related
related: dict mapping field names to lists of related objects
subfield_list: where to get the next layer of subfields |
20,527 | def get_dates_file(path):
with open(path) as f:
dates = f.readlines()
return [(convert_time_string(date_string.split(" ")[0]), float(date_string.split(" ")[1]))
for date_string in dates] | parse dates file of dates and probability of choosing |
20,528 | def where_equals(self, field_name, value, exact=False):
if field_name is None:
raise ValueError("None field_name is invalid")
field_name = Query.escape_if_needed(field_name)
self._add_operator_if_needed()
token = "equals"
if self.negate:
self.ne... | To get all the document that equal to the value in the given field_name
@param str field_name: The field name in the index you want to query.
@param value: The value will be the fields value you want to query
@param bool exact: If True getting exact match of the query |
20,529 | def delete_repository(self, namespace, repository):
return self._http_call(self.REPO, delete,
namespace=namespace, repository=repository) | DELETE /v1/repositories/(namespace)/(repository)/ |
20,530 | def image_predict(self, X):
pixels = self.extract_pixels(X)
predictions = self.classifier.predict(pixels)
return predictions.reshape(X.shape[0], X.shape[1], X.shape[2]) | Predicts class label for the entire image.
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: raster classification map
:rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x] |
20,531 | def get_next_redirect_url(request, redirect_field_name="next"):
redirect_to = get_request_param(request, redirect_field_name)
if not get_adapter(request).is_safe_url(redirect_to):
redirect_to = None
return redirect_to | Returns the next URL to redirect to, if it was explicitly passed
via the request. |
20,532 | def load_servers_from_env(self, filter=[], dynamic=None):
/localhosthost.cxtcomp1.rtccomp2.rtc
if dynamic == None:
dynamic = self._dynamic
if NAMESERVERS_ENV_VAR in os.environ:
servers = [s for s in os.environ[NAMESERVERS_ENV_VAR].split() \
if s]
... | Load the name servers environment variable and parse each server in
the list.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent... |
20,533 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.entities is not None:
_dict[] = [x._to_dict() for x in self.entities]
return _dict | Return a json dictionary representing this model. |
20,534 | def diamond_search_output_basename(self, out_path):
return os.path.join(self.outdir, out_path, "%s_diamond_search" % self.basename) | Does not include the .daa part that diamond creates |
20,535 | def find():
names = (, , , )
current_dir = os.getcwd()
configconfig_file = os.path.join(current_dir, )
default_config_dir = os.path.join(current_dir, )
if os.path.isfile(configconfig_file):
logger.debug(,
configconfig_file)
... | Find the configuration file if any. |
20,536 | def _get_key_redis_key(bank, key):
opts = _get_redis_keys_opts()
return .format(
prefix=opts[],
separator=opts[],
bank=bank,
key=key
) | Return the Redis key given the bank name and the key name. |
20,537 | def general_setting(key, default=None, expected_type=None, qsettings=None):
if qsettings is None:
qsettings = QSettings()
try:
if isinstance(expected_type, type):
return qsettings.value(key, default, type=expected_type)
else:
return qsettings.value(key, defau... | Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object exp... |
20,538 | def to_html(self,
protocol=,
d3_url=None,
d3_scale_chromatic_url=None,
html_base=None):
httphttps
d3_url_struct = D3URLs(d3_url, d3_scale_chromatic_url)
ExternalJSUtilts.ensure_valid_protocol(protocol)
javascript_to_insert =... | Parameters
----------
protocol : str
'http' or 'https' for including external urls
d3_url, str
None by default. The url (or path) of
d3, to be inserted into <script src="..."/>
By default, this is `DEFAULT_D3_URL` declared in `ScatterplotStructure`.
... |
20,539 | def _compute_and_transfer_to_final_run(self, process_name, start_timeperiod, end_timeperiod, job_record):
source_collection_name = context.process_context[process_name].source
start_id = self.ds.highest_primary_key(source_collection_name, start_timeperiod, end_timeperiod)
end_id = self.... | method computes new unit_of_work and transfers the job to STATE_FINAL_RUN
it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method |
20,540 | def extract_subnetworks(
partition_file,
network_file,
output_dir,
max_cores=DEFAULT_MAX_CORES,
max_size_matrix=DEFAULT_MAX_SIZE_MATRIX,
saturation_threshold=DEFAULT_SATURATION_THRESHOLD,
):
logger.info("Loading partition...")
data_chunks = np.loadtxt(partition_file, usecols=(1,), ... | Extract bin subnetworks from the main network
Identify bins, extract subnets, draws the adjacency matrices,
saves it all in a specified output directory.
Parameters
----------
partition_file : file, str or pathlib.Path
The file containing, for each chunk, the communities it was
ass... |
20,541 | def prompt(msg, default=NO_DEFAULT, validate=None):
while True:
response = input(msg + " ").strip()
if not response:
if default is NO_DEFAULT:
continue
return default
if validate is None or validate(response):
return response | Prompt user for input |
20,542 | def _get_client_fqdn(self, client_info_contents):
yamldict = yaml.safe_load(client_info_contents)
fqdn = yamldict[][]
client_id = yamldict[].split()[1]
return client_id, fqdn | Extracts a GRR client's FQDN from its client_info.yaml file.
Args:
client_info_contents: The contents of the client_info.yaml file.
Returns:
A (str, str) tuple representing client ID and client FQDN. |
20,543 | def present(name,
object_name,
object_type,
defprivileges=None,
grant_option=None,
prepend=,
maintenance_db=None,
user=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
... | Grant the requested privilege(s) on the specified object to a role
name
Name of the role to which privileges should be granted
object_name
Name of the object on which the grant is to be performed.
'ALL' may be used for objects of type 'table' or 'sequence'.
object_type
The ob... |
20,544 | def evaluate(self, num_eval_batches=None):
num_eval_batches = num_eval_batches or self.num_eval_batches
with tf.Graph().as_default() as graph:
self.tensors = self.model.build_eval_graph(self.eval_data_paths,
self.batch_size)
self.summary = tf.su... | Run one round of evaluation, return loss and accuracy. |
20,545 | def from_dict(cls, data, intersect=False, orient=, dtype=None):
from collections import defaultdict
orient = orient.lower()
if orient == :
new_data = defaultdict(OrderedDict)
for col, df in data.items():
for item, s in df.items():
... | Construct Panel from dict of DataFrame objects.
Parameters
----------
data : dict
{field : DataFrame}
intersect : boolean
Intersect indexes of input DataFrames
orient : {'items', 'minor'}, default 'items'
The "orientation" of the data. If the ... |
20,546 | def enable_console_debug_logging():
logger = logging.getLogger("github")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler()) | This function sets up a very simple logging configuration (log everything on standard output) that is useful for troubleshooting. |
20,547 | def add_parser_arguments(parser, args, group=None, prefix=DATA_PREFIX):
if group:
parser = parser.add_argument_group(group)
for arg, kwargs in iteritems(args):
arg_name = kwargs.pop(, arg.replace(, ))
if not in kwargs:
kwargs[] = arg.upper()
if in kwargs:
... | Helper method that populates parser arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The keys will be used as keys in returned
data. Their values will be passed as kwargs ... |
20,548 | def get_compiler(compiler, **compiler_attrs):
if compiler is None or isinstance(compiler, str):
cc = ccompiler.new_compiler(compiler=compiler, verbose=0)
customize_compiler(cc)
if cc.compiler_type == :
customize_mingw(cc)
else:
cc = compiler
customize_gcc... | get and customize a compiler |
20,549 | def _getPattern(self, ipattern, done=None):
if ipattern is None:
return None
if ipattern is True:
if done is not None:
return ([(None, None, done)], {})
return ([(0, False)], {})
def _getReverse(pm):
return pm... | Parses sort pattern.
:ipattern: A pattern to parse.
:done: If :ipattern: refers to done|undone,
use this to indicate proper state.
:returns: A pattern suitable for Model.modify. |
20,550 | def _find_listeners():
for i in range(31):
try:
if gpib.listener(BOARD, i) and gpib.ask(BOARD, 1) != i:
yield i
except gpib.GpibError as e:
logger.debug("GPIB error in _find_listeners(): %s", repr(e)) | Find GPIB listeners. |
20,551 | def depth(args):
import seaborn as sns
p = OptionParser(depth.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="14x14")
if len(args) != 1:
sys.exit(not p.print_help())
tsvfile, = args
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2,
... | %prog depth DP.tsv
Plot read depths across all TREDs. |
20,552 | def RFC3156_micalg_from_algo(hash_algo):
algo = gpg.core.hash_algo_name(hash_algo)
if algo is None:
raise GPGProblem(.format(algo),
code=GPGCode.INVALID_HASH_ALGORITHM)
return + algo.lower() | Converts a GPGME hash algorithm name to one conforming to RFC3156.
GPGME returns hash algorithm names such as "SHA256", but RFC3156 says that
programs need to use names such as "pgp-sha256" instead.
:param str hash_algo: GPGME hash_algo
:returns: the lowercase name of of the algorithm with "pgp-" prep... |
20,553 | def erase_up (self):
self.erase_start_of_line ()
self.fill_region (self.cur_r-1, 1, 1, self.cols) | Erases the screen from the current line up to the top of the
screen. |
20,554 | def rest(self, method, uri, data=None, status_codes=None, parse=True, **kwargs):
r = self.pool.request_encode_body(method, uri, fields=data, encode_multipart=False)
if not r.status in (status_codes if status_codes else (200,201)):
print cl( % (uri, method), )
print cl(data, )
print r.head... | Rest helpers |
20,555 | def __update_action(self, revision):
patch = revision.get("patch")
if patch.get("_id"):
del patch["_id"]
update_response = yield self.collection.patch(revision.get("master_id"), self.__make_storeable_patch_patchable(patch))
if update_response.get("n") == 0:
... | Update a master document and revision history document
:param dict revision: The revision dictionary |
20,556 | def spline_fit_magseries(times, mags, errs, period,
knotfraction=0.01,
maxknots=30,
sigclip=30.0,
plotfit=False,
ignoreinitfail=False,
magsarefluxes=False,
... | This fits a univariate cubic spline to the phased light curve.
This fit may be better than the Fourier fit for sharply variable objects,
like EBs, so can be used to distinguish them from other types of variables.
Parameters
----------
times,mags,errs : np.array
The input mag/flux time-ser... |
20,557 | def cublasDspr2(handle, uplo, n, alpha, x, incx, y, incy, AP):
status = _libcublas.cublasDspr2_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(ctypes.c_double(alpha)),
int(x), incx, int(... | Rank-2 operation on real symmetric-packed matrix. |
20,558 | def get_object(self, queryset=None):
assert queryset is None, "Passing a queryset is disabled"
queryset = self.filter_queryset(self.get_queryset())
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
lookup = self.kwargs.get(lookup_url_kwarg, None)
... | Return the object the view is displaying.
Same as rest_framework.generics.GenericAPIView, but:
- Failed assertions instead of deprecations |
20,559 | def dateint_to_datetime(dateint):
if len(str(dateint)) != 8:
raise ValueError(
)
year, month, day = decompose_dateint(dateint)
return datetime(year=year, month=month, day=day) | Converts the given dateint to a datetime object, in local timezone.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
datetime.datetime
A timezone-unaware datetime object representing the start of the given
... |
20,560 | def master_ref(self):
return ReferencesDataFrame(self._engine_dataframe.getMaster(),
self._session, self._implicits)
return self.ref() | Filters the current DataFrame to only contain those rows whose reference is master.
>>> master_df = refs_df.master_ref
:rtype: ReferencesDataFrame |
20,561 | def _upgrade_schema(engine):
inspector = reflection.Inspector.from_engine(engine)
with engine.connect() as conn:
if not in [x[] for x in inspector.get_columns()]:
logger.warning()
conn.execute()
conn.execute()
if in engine.dialect.na... | Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database. |
20,562 | def all_pairs_normalized_distances_reference(X):
n_samples, n_cols = X.shape
D = np.ones((n_samples, n_samples), dtype="float32") * np.inf
for i in range(n_samples):
diffs = X - X[i, :].reshape((1, n_cols))
missing_diffs = np.isnan(diffs)
missing_counts_per_row = missing_di... | Reference implementation of normalized all-pairs distance, used
for testing the more efficient implementation above for equivalence. |
20,563 | def do_lmfit(data, params, B=None, errs=None, dojac=True):
params = copy.deepcopy(params)
data = np.array(data)
mask = np.where(np.isfinite(data))
def residual(params, **kwargs):
f = ntwodgaussian_lmfit(params)
model = f(*mask)
if B is None:
... | Fit the model to the data
data may contain 'flagged' or 'masked' data with the value of np.NaN
Parameters
----------
data : 2d-array
Image data
params : lmfit.Parameters
Initial model guess.
B : 2d-array
B matrix to be used in residual calculations.
Default = N... |
20,564 | def _get_containing_contigs(self, hits_dict):
containing = {}
for qry_name in hits_dict:
d = self._containing_contigs(hits_dict[qry_name])
if len(d):
containing[qry_name] = d
return containing | Given dictionary of nucmer hits (made by self._load_nucmer_hits()), returns a dictionary.
key=contig name. Value = set of contigs that contain the key. |
20,565 | def print_attrs(data_file, node_name=, which=, compress=False):
node = data_file.get_node(node_name)
print ( % node)
for attr in node._v_attrs._f_list():
print ( % attr)
attr_content = repr(node._v_attrs[attr])
if compress:
attr_content = attr_content.split()[0]
... | Print the HDF5 attributes for `node_name`.
Parameters:
data_file (pytables HDF5 file object): the data file to print
node_name (string): name of the path inside the file to be printed.
Can be either a group or a leaf-node. Default: '/', the root node.
which (string): Valid value... |
20,566 | def EMAIL_REQUIRED(self):
from allauth.account import app_settings as account_settings
return self._setting("EMAIL_REQUIRED", account_settings.EMAIL_REQUIRED) | The user is required to hand over an e-mail address when signing up |
20,567 | def plugins(self):
if not self._plugins:
self._plugins = [
(plugin_name,
plugin_cfg[],
plugin_cfg) for plugin_name, plugin_cfg in self.validated.items() if (
plugin_name not in self.base_schema.keys()) and plugin_cfg[]]
... | :returns: [(plugin_name, plugin_package, plugin_config), ...]
:rtype: list of tuple |
20,568 | def send_UDP_message(self, message):
x = 0
if self.tracking_enabled:
try:
proc = udp_messenger(self.domain_name, self.UDP_IP, self.UDP_PORT, self.sock_timeout, message)
self.procs.append(proc)
except Exception as e:
logger.... | Send UDP message. |
20,569 | def render(self, dt):
for frame in self._frozen:
for body in frame:
self.draw_body(body)
for body in self.world.bodies:
self.draw_body(body)
if hasattr(self.world, ):
window.glColor4f(0.9, 0.1, 0.1, 0.9)
windo... | Draw all bodies in the world. |
20,570 | def find_table_links(self):
html = urlopen(self.model_url).read()
doc = lh.fromstring(html)
href_list = [area.attrib[] for area in doc.cssselect()]
tables = self._inception_table_links(href_list)
return tables | When given a url, this function will find all the available table names
for that EPA dataset. |
20,571 | def ref(self, tickers, flds, ovrds=None):
ovrds = [] if not ovrds else ovrds
logger = _get_logger(self.debug)
if type(tickers) is not list:
tickers = [tickers]
if type(flds) is not list:
flds = [flds]
request = self._create_req(, tickers, flds,
... | Make a reference data request, get tickers and fields, return long
pandas DataFrame with columns [ticker, field, value]
Parameters
----------
tickers: {list, string}
String or list of strings corresponding to tickers
flds: {list, string}
String or list of... |
20,572 | def ot_validate(nexson, **kwargs):
codes_to_skip = [NexsonWarningCodes.UNVALIDATED_ANNOTATION]
v_log, adaptor = validate_nexson(nexson, codes_to_skip, **kwargs)
annotation = v_log.prepare_annotation(author_name=,
description=)
return annotation, v_lo... | Returns three objects:
an annotation dict (NexSON formmatted),
the validation_log object created when NexSON validation was performed, and
the object of class NexSON which was created from nexson. This object may
alias parts of the nexson dict that is passed in as an argument.
C... |
20,573 | def save_file(self, filename, text):
_defaultdir = self.DEFAULTDIR
try:
if not filename.endswith():
filename +=
try:
self.DEFAULTDIR = (
+ hydpy.pub.timegrids.sim.lastdate.to_string())
except AttributeErro... | Save the given text under the given condition filename and the
current path.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation end date. If
such an directory does not exist, it is created immediately. |
20,574 | def close(self):
if self._dev is not None:
usb.util.dispose_resources(self._dev)
self._dev = None | Close and release the current usb device.
:return: None |
20,575 | def save(self, savefile):
with open(str(savefile), ) as f:
self.write_to_fp(f)
log.debug("Saved to %s", savefile) | Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request. |
20,576 | def get(self, path_or_index, default=None):
err, value = self._resolve(path_or_index)
value = default if err else value
return err, value | Get details about a given result
:param path_or_index: The path (or index) of the result to fetch.
:param default: If the given result does not exist, return this value
instead
:return: A tuple of `(error, value)`. If the entry does not exist
then `(err, default)` is ret... |
20,577 | def analyze(fqdn, result, argl, argd):
package = fqdn.split()[0]
if package not in _methods:
_load_methods(package)
if _methods[package] is not None and fqdn in _methods[package]:
return _methods[package][fqdn](fqdn, result, *argl, **argd) | Analyzes the result from calling the method with the specified FQDN.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to the method call.
argd (dict): keyword arguments pa... |
20,578 | def expand_hostdef(self, hostdef):
try:
hosts_todo = [hostdef]
hosts_done = []
while hosts_todo:
host = hosts_todo.pop(0)
if not in host:
hosts_done.append(host)... | Expand a host definition (e.g. "foo[001:010].bar.com") into seperate
hostnames. Supports zero-padding, numbered ranges and alphabetical
ranges. Multiple patterns in a host defnition are also supported.
Returns a list of the fully expanded hostnames. Ports are also removed
from hostnames ... |
20,579 | def norm(self, order=2):
return (sum(val**order for val in abs(self).values()))**(1/order) | Find the vector norm, with the given order, of the values |
20,580 | def add_pool(arg, opts, shell_opts):
p = Pool()
p.name = opts.get()
p.description = opts.get()
p.default_type = opts.get()
p.ipv4_default_prefix_length = opts.get()
p.ipv6_default_prefix_length = opts.get()
if in opts:
tags = list(csv.reader([opts.get(, )], escapechar=))[0]
... | Add a pool. |
20,581 | def cmd_center(self, args):
if len(args) < 3:
print("map center LAT LON")
return
lat = float(args[1])
lon = float(args[2])
self.map.set_center(lat, lon) | control center of view |
20,582 | def search(connect_spec, base, scope=, filterstr=,
attrlist=None, attrsonly=0):
subtreebaseonelevels immediate children.
:param filterstr:
String representation of the filter to apply in the search.
:param attrlist:
Limit the returned attributes to those in the specified list.
... | Search an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param base:
Distinguished name of the entry at which to start the search.
:param scope:
One of the following:
* ``'subtree'``
... |
20,583 | def get_active_sessions(self):
for last_timestamp, i, events in self.recently_active:
yield Session(events[-1].user, unpack_events(events)) | Retrieves the active, unexpired sessions.
:Returns:
A generator of :class:`~mwsessions.Session` |
20,584 | def make_dict(name, words, *args, **kwargs):
info = CzechHashBuilder(words, *args, **kwargs)
doc = % (__name__, make_dict.__name__, name)
return create_dict_subclass(name, info.hash_function, info.words, doc) | make_dict(name, words, *args, **kwargs) -> mapping subclass
Takes a sequence of words (or a pre-built Czech HashInfo) and returns a
mapping subclass called `name` (used a dict) that employs the use of the
minimal perfect hash.
This mapping subclass has guaranteed O(1) worst-case lookups, additions,
... |
20,585 | def parse_date(date, default=None):
if date == "":
if default is not None:
return default
else:
raise Exception("Unknown format for " + date)
for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M",... | Parse a valid date |
20,586 | def find_by_id(self, attachment, params={}, **options):
path = "/attachments/%s" % (attachment)
return self.client.get(path, params, **options) | Returns the full record for a single attachment.
Parameters
----------
attachment : {Id} Globally unique identifier for the attachment.
[params] : {Object} Parameters for the request |
20,587 | def random_matrix(rows, cols, mean=0, std=1, sparsity=0, radius=0, diagonal=0, rng=None):
if rng is None or isinstance(rng, int):
rng = np.random.RandomState(rng)
arr = mean + std * rng.randn(rows, cols)
if 1 > sparsity > 0:
k = min(rows, cols)
mask = rng.binomial(n=1, p=1 - spa... | Create a matrix of randomly-initialized weights.
Parameters
----------
rows : int
Number of rows of the weight matrix -- equivalently, the number of
"input" units that the weight matrix connects.
cols : int
Number of columns of the weight matrix -- equivalently, the number
... |
20,588 | def open_config(self,type="shared"):
try:
output = self.dev.rpc("<open-configuration><{0}/></open-configuration>".format(type))
except Exception as err:
print err | Opens the configuration of the currently connected device
Args:
:type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default mode is **shared**.
Examples:
.. code-... |
20,589 | def check_hash(self, checker, filename, tfp):
checker.report(
self.debug,
"Validating %%s checksum for %s" % filename)
if not checker.is_valid():
tfp.close()
os.unlink(filename)
raise DistutilsError(
"%s validation fail... | checker is a ContentChecker |
20,590 | def param_extract(args, short_form, long_form, default=None):
val = default
for i, a in enumerate(args):
elems = a.split("=", 1)
if elems[0] in [short_form, long_form]:
if len(elems) == 1:
if i + 1 < len(args) and not args[i + 1].st... | Quick extraction of a parameter from the command line argument list.
In some cases we need to parse a few arguments before the official
arg-parser starts.
Returns parameter value, or None if not present. |
20,591 | def extern_store_tuple(self, context_handle, vals_ptr, vals_len):
c = self._ffi.from_handle(context_handle)
return c.to_value(tuple(c.from_value(val[0]) for val in self._ffi.unpack(vals_ptr, vals_len))) | Given storage and an array of Handles, return a new Handle to represent the list. |
20,592 | def followers(self):
if self._followers is None:
self.assert_bind_client()
if self.follower_count > 0:
self._followers = self.bind_client.get_athlete_followers(self.id)
else:
self._followers = []
return self._f... | :return: Iterator of :class:`stravalib.model.Athlete` followers objects for this athlete. |
20,593 | def toDict(self):
if six.PY3:
result = super().toDict()
else:
result = AARead.toDict(self)
result.update({
: self.start,
: self.stop,
: self.openLeft,
: self.openRight,
})
return result | Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self. |
20,594 | def SetAndLoadTagFile(self, tagging_file_path):
tag_file = tagging_file.TaggingFile(tagging_file_path)
self._tagging_rules = tag_file.GetEventTaggingRules() | Sets the tag file to be used by the plugin.
Args:
tagging_file_path (str): path of the tagging file. |
20,595 | def create_address(kwargs=None, call=None):
if call != :
raise SaltCloudSystemExit(
)
if not kwargs or not in kwargs:
log.error(
)
return False
if not in kwargs:
log.error(
)
return False
name... | Create a static address in a region.
CLI Example:
.. code-block:: bash
salt-cloud -f create_address gce name=my-ip region=us-central1 address=IP |
20,596 | def draw_if_interactive():
fig = Gcf.get_active().canvas.figure
if not hasattr(fig, ):
fig.show = lambda *a: send_figure(fig)
if not matplotlib.is_interactive():
return
try:
... | Is called after every pylab drawing command |
20,597 | def get_order(self, order_id):
resp = self.get(.format(order_id))
return Order(resp) | Get an order |
20,598 | def raw(self, raw):
if raw is None:
raise ValueError("Invalid value for `raw`, must not be `None`")
if raw is not None and not re.search(r, raw):
raise ValueError(r"Invalid value for `raw`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\... | Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object. # noqa: E501
:param raw: The raw of this RuntimeRawExtension. # noqa: E501
:type: str |
20,599 | def get_system_data() -> typing.Union[None, dict]:
site_packages = get_site_packages()
path_prefixes = [(, p) for p in site_packages]
path_prefixes.append((, sys.exec_prefix))
packages = [
module_to_package_data(name, entry, path_prefixes)
for name, entry in list(sys.modules.items... | Returns information about the system in which Cauldron is running.
If the information cannot be found, None is returned instead.
:return:
Dictionary containing information about the Cauldron system, whic
includes:
* name
* location
* version |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.