Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
339,400 | def register(cls, name):
def decorate(klazz):
if name in cls._events:
raise GerritError("Duplicate event: %s" % name)
cls._events[name] = [klazz.__module__, klazz.__name__]
klazz.name = name
return klazz
return decora... | Decorator to register the event identified by `name`.
Return the decorated class.
Raise GerritError if the event is already registered. |
339,401 | def uri(self):
return url_for(
.format(self.pid.pid_type),
pid_value=self.pid.pid_value,
filename=self.file.key) | Get file download link.
.. note::
The URI generation assumes that you can download the file using the
view ``invenio_records_ui.<pid_type>_files``. |
339,402 | def success_response(field=None, data=None, request_type=""):
data_out = {}
data_out["status"] = "success"
if field:
data_out[field] = data
print("{} request successful.".format(request_type))
js = dumps(data_out, default=date_handler)
return Response(js, status=200, mimetype=) | Return a generic success response. |
339,403 | def set_sample_type_default_stickers(portal):
stickers = getStickerTemplates()
sticker_ids = []
for sticker in stickers:
sticker_ids.append(sticker.get())
def_small_template = portal.bika_setup.getSmallStickerTemplate()
def_large_template = portal.bika_setup.getLargeStickerTemplate... | Fills the admitted stickers and their default stickers to every sample
type. |
339,404 | def get_job_definitions(self, identifier):
result = []
env = self.get_job_definition_by_arn(identifier)
if env is not None:
result.append(env)
else:
for value in self._job_definitions.values():
if value.name == identifier:
... | Get job defintiion by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Job definition or None
:rtype: list of JobDefinition |
339,405 | def is_type_I_branch(u, v, dfs_data):
if u != a(v, dfs_data):
return False
if u == L2(v, dfs_data):
return True
return False | Determines whether a branch uv is a type I branch. |
339,406 | def add_music_cue(self, track, comp_cue, song_cue, duration=6.0,
padding_before=12.0, padding_after=12.0):
self.tracks.add(track)
pre_fade = 3
post_fade = 3
if padding_before + pre_fade > song_cue:
padding_before = song_cue - ... | Add a music cue to the composition. This doesn't do any audio
analysis, it just aligns a specified point in the track
(presumably music) with a location in the composition. See
UnderScore_ for a visualization of what this is doing to the
music track.
.. _UnderScore: http://vis.b... |
339,407 | def plot_ell(fignum, pars, col, lower, plot):
plt.figure(num=fignum)
rad = old_div(np.pi, 180.)
Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc = pars[0], pars[
1], pars[2], pars[3], pars[4], pars[5], pars[6], pars[7]
if beta > 90. or gamma > 90:
beta = 180. - beta
gamma = 1... | function to calcualte/plot points on an ellipse about Pdec,Pdip with angle beta,gamma
Parameters
_________
fignum : matplotlib figure number
pars : list of [Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc ]
where P is direction, Bdec,Binc are beta direction, and Gdec,Ginc are gamma direction
... |
339,408 | def handle(self, sock, address, internal=False):
try:
sock = StatsSocket(sock)
rfile = sock.makefile(, 4096)
first = rfile.readline().strip("\r\n")
words = first.split()
if not (2 <= len(words) <= 3):
... | Handles an incoming HTTP connection. |
339,409 | def kunc_k_num(v, v0, k0, k0p, order=5, precision=1.e-5):
return -1. * v * kunc_dPdV(v, v0, k0, k0p, order=order,
precision=precision) | calculate bulk modulus numerically from volume, not pressure
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus a... |
339,410 | def setBusStop(self, vehID, stopID, duration=2**31 - 1, until=-1, flags=tc.STOP_DEFAULT):
self.setStop(vehID, stopID, duration=duration,
until=until, flags=flags | tc.STOP_BUS_STOP) | setBusStop(string, string, integer, integer, integer) -> None
Adds or modifies a bus stop with the given parameters. The duration and the until attribute are
in milliseconds. |
339,411 | def clone(self):
logger.debug("Attempting to clone {0}".format(self.book_repo_name))
if self.path_exists():
return False, "Error: Local clone of {0} already exists".format(self.book_repo_name)
try:
self.local_repo = git.Repo.clone_from(self.get_clone_url_ssh(),... | clones a book from GITenberg's repo into the library
assumes you are authenticated to git clone from repo?
returns True/False, message |
339,412 | async def get_json(self, encoding=):
return (await self.get(encoding=encoding, decoder=json.loads)) | Shortcut to get JSON messages. |
339,413 | def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
name = field.getName()
otherName = "%s_other" % name
value = form.get(otherName, empty_marker)
regex = field.widget.field_regex
if value and not re... | A typed in value takes precedence over a selected value. |
339,414 | def treble(self):
response = self.renderingControl.GetTreble([
(, 0),
(, ),
])
treble = response[]
return int(treble) | int: The speaker's treble EQ.
An integer between -10 and 10. |
339,415 | def has_fired(self, my_task):
dt = my_task.workflow.script_engine.evaluate(my_task, self.dateTime)
if dt is None:
return False
if dt.tzinfo:
tz = dt.tzinfo
now = tz.fromutc(datetime.datetime.utcnow().replace(tzinfo=tz))
else:
now =... | The Timer is considered to have fired if the evaluated dateTime
expression is before datetime.datetime.now() |
339,416 | def to_dot(self) -> str:
txt = ""
txt += "digraph S%d {\n" % id(self)
if self.label is not None:
txt += % (self.label + ).replace(, )
txt += "\trankdir=LR;\n"
txt +=
txt += "\tesep=1;\n"
txt +=
txt += "\tnode [shape = circl... | Provide a '.dot' representation of all State in the register. |
339,417 | def generate_thumbnail_download_link_vimeo(video_id_from_shortcode):
video_metadata = urlopen("https://vimeo.com/api/v2/video/" + str(video_id_from_shortcode) + ".json").read()
return video_thumbnail_large_location | Thumbnail URL generator for Vimeo videos. |
339,418 | def save(self, basepath):
out.info(u"Get image URL %s" % self.url, level=1)
self.connect()
filename = "%s%s" % (self.filename, self.ext)
comicDir = os.path.join(basepath, self.dirname)
if not os.path.isdir(comicDir):
os.makedirs(comicDir)
fn = os.path... | Save comic URL to filename on disk. |
339,419 | def shell(self):
click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!")
self.zappa.shell()
return | Spawn a debug shell. |
339,420 | def _retrieve_binary(self, file_name):
with open(file_name, ) as f:
return self.session.retrbinary( + file_name, f.write) | Retrieve a file in binary transfer mode. |
339,421 | def CompileReport(self, mediator):
lines_of_text = []
if self._output_format == :
lines_of_text.append(
yaml.safe_dump_all(self._service_collection.services))
else:
lines_of_text.append()
for service in self._service_collection.services:
lines_of_text.append(sel... | Compiles an analysis report.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
Returns:
AnalysisReport: report. |
339,422 | def get_work_commits(repo_addr, ascending = True, tz = , correct_times = True):
repo = git.Repo(repo_addr)
commits = list(repo.iter_commits())
logs = [(c.authored_datetime, c.message.strip(), str(c)) for c in repo.iter_commits()]
work = pd.DataFrame.from_records(logs, columns = [, , ])
work... | Retrives work commits from repo |
339,423 | def validateOneNamespace(self, ctxt, elem, prefix, ns, value):
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if elem is None: elem__o = None
else: elem__o = elem._o
if ns is None: ns__o = None
else: ns__o = ns._o
ret = libxml2mod.xmlValidateOneN... | Try to validate a single namespace declaration for an
element basically it does the following checks as described
by the XML-1.0 recommendation: - [ VC: Attribute Value Type
] - [ VC: Fixed Attribute Default ] - [ VC: Entity Name ] -
[ VC: Name Token ] - [ VC: ID ] - [ VC: IDREF ... |
339,424 | def _writeloop(self, consumer):
while True:
bytes = self._inputFile.read(self._readSize)
if not bytes:
self._inputFile.close()
break
consumer.write(bytes)
yield None | Return an iterator which reads one chunk of bytes from the input file
and writes them to the consumer for each time it is iterated. |
339,425 | def Click(cls):
element= cls._element()
action = ActionChains(Web.driver)
action.click(element)
action.perform() | 左键 点击 1次 |
339,426 | def _hid_enumerate(vendor_id=0, product_id=0):
start = hidapi.hid_enumerate(vendor_id, product_id)
result = []
cur = ffi.new("struct hid_device_info*");
cur = start
while cur != ffi.NULL:
result.append(HIDDevice(cur))
cur = cur.next
hidapi.hid_free_enumeration(st... | Enumerates all the hid devices for VID:PID. Returns a list of `HIDDevice`
objects. If vid is 0, then match any vendor id. Similarly, if pid is 0,
match any product id. If both are zero, enumerate all HID devices. |
339,427 | def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components,
skip_num_points=0):
X_embedded = params.reshape(n_samples, n_components)
X_embedded[i] - X_embedded)
grad = grad.ravel()
c = 2.0 * (degrees_of_freedom + 1.0) / degrees_of_freedom... | t-SNE objective function: gradient of the KL divergence
of p_ijs and q_ijs and the absolute error.
Parameters
----------
params : array, shape (n_params,)
Unraveled embedding.
P : array, shape (n_samples * (n_samples-1) / 2,)
Condensed joint probability matrix.
degrees_of_free... |
339,428 | def auth_request(self, url, headers, body):
return self.req.post(url, headers, body=body) | Perform auth request for token. |
339,429 | def add_login_attempt_task(user_agent, ip_address, username,
http_accept, path_info, login_valid):
store_login_attempt(user_agent, ip_address, username,
http_accept, path_info, login_valid) | Create a record for the login attempt |
339,430 | def ranges_to_coverage(rngs,threads=1):
def do_chr(rngs):
start_events = [x.start for x in rngs]
end_events = [x.end+1 for x in rngs]
indexed_events = {}
for e in start_events:
if e not in indexed_events: indexed_events[e] = {:0,:0}
indexed_events[e][]+=1
for e i... | take a list of ranges as an input
output a list of ranges and the coverage at each range
:param rngs: bed ranges on a single chromosome. not certain about that single chromosome requirement
:type rngs: GenomicRange[] or Bed[]
:param threads: Not currently being used
:type threads: int
:return: out is the n... |
339,431 | def setup_once(initfn):
def wrap(method):
finit = initfn.__name__
fnname = method.__name__
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
@functools.wraps(method)
def aftersetup(*a, **kw):
return method(self, *a, **kw)
... | call class instance method for initial setup ::
class B(object):
def init(self, a):
print 'init call:', a
@setup_once(init)
def mycall(self, a):
print 'real call:', a
b = B()
b.mycall(222)
b.mycall(333)
:param f... |
339,432 | def get_webhook_url(deployment_name,
space=,
data_source=,
token_manager=None,
app_url=defaults.APP_URL,
**fields):
import_url = data_engine.get_import_data_url(deployment_name,
... | return the webhook URL for posting webhook data to |
339,433 | def verb_chain_texts(self):
if not self.is_tagged(VERB_CHAINS):
self.tag_verb_chains()
return self.texts(VERB_CHAINS) | The list of texts of ``verb_chains`` layer elements. |
339,434 | def paths(obj, dirs=True, leaves=True, path=[], skip=False):
if isinstance(obj, MutableMapping):
if PY3:
iteritems = obj.items()
string_class = str
else:
iteritems = obj.iteritems()
string_class = basestring
for (k, v) in iterit... | Yield all paths of the object.
Arguments:
obj -- An object to get paths from.
Keyword Arguments:
dirs -- Yield intermediate paths.
leaves -- Yield the paths with leaf objects.
path -- A list of keys representing the path.
skip -- Skip special keys beginning with '+'. |
339,435 | def do_initial_operations(self):
if not self.request_hc_path_corresponds():
return
self.set_coap_uri()
self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port)) | Setup the client for interact with remote server |
339,436 | def index(request):
"Displays a list of all services and their current status."
service_list = Service.objects.all()
event_list = list(Event.objects\
.filter(Q(status__gt=0) | Q(date_updated__gte=datetime.datetime.now()-datetime.timedelta(days=1)))\
... | Displays a list of all services and their current status. |
339,437 | def unpack(regex):
if is_packed(regex) and not regex.startswith():
return re.sub(r, r, regex)
else:
return regex | Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]' |
339,438 | def create(domain_name, years, **kwargs):
my-minion
idn_codes = (, , , , , , , , , , , , , ,
, , , , , , , , , , , , , ,
, , , , , , , , , , , , , ,
, , , , , , , , , , , , , ,
, , , , , , , , , , , , , ,
, , , , , , , , , , , ... | Try to register the specified domain name
domain_name
The domain name to be registered
years
Number of years to register
Returns the following information:
- Whether or not the domain was renewed successfully
- Whether or not WhoisGuard is enabled
- Whether or not registratio... |
339,439 | async def stat(self, path):
path = pathlib.PurePosixPath(path)
try:
code, info = await self.command("MLST " + str(path), "2xx")
name, info = self.parse_mlsx_line(info[1].lstrip())
return info
except errors.StatusCodeError as e:
if not e.re... | :py:func:`asyncio.coroutine`
Getting path stats.
:param path: path for getting info
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:return: path info
:rtype: :py:class:`dict` |
339,440 | def get_abbr_impl(env):
impl = env.python_implementation
if impl == "PyPy":
return "pp"
elif impl == "Jython":
return "jy"
elif impl == "IronPython":
return "ip"
elif impl == "CPython":
return "cp"
raise LookupError("Unknown Python implementation: " + impl) | Return abbreviated implementation name. |
339,441 | def mean_se(series, mult=1):
m = np.mean(series)
se = mult * np.sqrt(np.var(series) / len(series))
return pd.DataFrame({: [m],
: m-se,
: m+se}) | Calculate mean and standard errors on either side |
339,442 | def add_edu(self, edu):
edu_id = self.get_element_id(edu)
edu_attribs = self.element_attribs_to_dict(edu)
self.add_node(edu_id, layers={self.ns, self.ns+}, attr_dict=edu_attribs)
edu_token_ids = []
for word in edu.iterdescendants():
word_id = self.get_eleme... | Parameters
----------
edu : etree.Element
etree representation of a <edu> element
(annotates an EDU)
Note: the arg1 EDU has a discRel child, the arg2 doesn't
Example
-------
<edu xml:id="edu_55_21_1">
<discRel relation="Explanation-Ca... |
339,443 | def validate_wrap(self, value):
try:
self.computed_type.validate_wrap(value)
except BadValueException as bve:
self._fail_validation(value, , cause=bve) | Check that ``value`` is valid for unwrapping with ``ComputedField.computed_type`` |
339,444 | def get_jobs(self, recursive=True):
if recursive:
ret_dict = self.jobs.copy()
return ret_dict
return self.jobs | Return a dictionary with all the jobs
For sub-classes, if recursive is True this will include jobs
from any internal `Link` |
339,445 | def get_port_at_point(self, vpos, distance=10, exclude=None, exclude_port_fun=None):
v2i = self.get_matrix_v2i
vx, vy = vpos
max_dist = distance
port = None
glue_pos = None
item = None
rect = (vx - distance, vy - distance, distance * 2... | Find item with port closest to specified position.
List of items to be ignored can be specified with `exclude`
parameter.
Tuple is returned
- found item
- closest, connectable port
- closest point on found port (in view coordinates)
:Parameters:
vpos
... |
339,446 | def _clone(self):
cloned_self = self.__class__(
*self.flat_path, project=self.project, namespace=self.namespace
)
cloned_self._parent = self._parent
return cloned_self | Duplicates the Key.
Most attributes are simple types, so don't require copying. Other
attributes like ``parent`` are long-lived and so we re-use them.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: A new ``Key`` instance with the same data as the current one. |
339,447 | def normal_surface_single_list(obj, param_list, normalize):
ret_vector = []
for param in param_list:
temp = normal_surface_single(obj, param, normalize)
ret_vector.append(temp)
return tuple(ret_vector) | Evaluates the surface normal vectors at the given list of parameter values.
:param obj: input surface
:type obj: abstract.Surface
:param param_list: parameter list
:type param_list: list or tuple
:param normalize: if True, the returned vector is converted to a unit vector
:type normalize: bool
... |
339,448 | def get_attribute(self, code, default=None):
try:
return self.get(code=code).value
except models.ObjectDoesNotExist:
return default | Get attribute for user |
339,449 | def cmp(self, other_service):
if not isinstance(other_service, HttpService):
return None
for att in dir(self):
if att == or att.startswith():
continue
if not hasattr(other_service, att):
return None
if getattr(self... | Compare with an instance of this object. Returns None if the object
is not comparable, False is relevant attributes don't match and True
if they do. |
339,450 | def get_version():
release = get_release()
split_version = release.split(".")
if len(split_version) == 3:
return ".".join(split_version[:2])
return release | Reads the version (MAJOR.MINOR) from this module. |
339,451 | def FilePrinter(filename, mode=, closing=True):
path = os.path.abspath(os.path.expanduser(filename))
f = open(path, mode)
return Printer(f, closing) | Opens the given file and returns a printer to it. |
339,452 | def addRow(self, *value):
if len(value) == 1 and isinstance(value[0], (tuple, list)):
value = value[0]
assert len(value) == self.getNumCols()
self._impl.addRow(Tuple(value)._impl) | Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments with the values for
each column. |
339,453 | def _compute_mean(self, C, mag, rjb):
mean = (C[] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, rjb))
return mean | Compute mean value according to equation 3, page 46. |
339,454 | def from_values(cls, location, direct_normal_irradiance,
diffuse_horizontal_irradiance, timestep=1, is_leap_year=False):
err_message = \
if len(direct_normal_irradiance) % cls.hour_count(is_leap_year) == 0:
err_message = err_message + ... | Create wea from a list of irradiance values.
This method converts input lists to data collection. |
339,455 | def plot_inducing(self, visible_dims=None, projection=, label=, legend=True, **plot_kwargs):
canvas, kwargs = pl().new_canvas(projection=projection, **plot_kwargs)
plots = _plot_inducing(self, canvas, visible_dims, projection, label, **kwargs)
return pl().add_to_canvas(canvas, plots, legend=legend) | Plot the inducing inputs of a sparse gp model
:param array-like visible_dims: an array specifying the input dimensions to plot (maximum two)
:param kwargs plot_kwargs: keyword arguments for the plotting library |
339,456 | def _generate_art(self, image, width, height):
image = image.resize((width, height), Image.ANTIALIAS).convert("RGB")
pixels = list(image.getdata())
for y in range(0, height - 1, 2):
for x in range(width):
i = y * width + x
bg = rgb2short(*(pi... | Return an iterator that produces the ascii art. |
339,457 | def downloaded(name, artifact, target_dir=, target_file=None):
t exist, then
it will be downloaded. If it already exists then the checksum of existing file is checked
against checksum in nexus. If it is different then the step will fail.
artifact
Details of the artifact to be downloaded from ne... | Ensures that the artifact from nexus exists at given location. If it doesn't exist, then
it will be downloaded. If it already exists then the checksum of existing file is checked
against checksum in nexus. If it is different then the step will fail.
artifact
Details of the artifact to be downloaded... |
339,458 | def _BuildKeyHierarchy(self, subkeys, values):
if subkeys:
for registry_key in subkeys:
name = registry_key.name.upper()
if name in self._subkeys:
continue
self._subkeys[name] = registry_key
registry_key._key_path = key_paths.JoinKeyPath([
s... | Builds the Windows Registry key hierarchy.
Args:
subkeys (list[FakeWinRegistryKey]): list of subkeys.
values (list[FakeWinRegistryValue]): list of values. |
339,459 | def evaluate(ref_intervals, ref_pitches, est_intervals, est_pitches, **kwargs):
scores = collections.OrderedDict()
kwargs.setdefault(, 0.2)
orig_offset_ratio = kwargs[]
if kwargs[] is not None:
(scores[],
scores[],
scores[],
scores[]) = util.filter_kwar... | Compute all metrics for the given reference and estimated annotations.
Examples
--------
>>> ref_intervals, ref_pitches = mir_eval.io.load_valued_intervals(
... 'reference.txt')
>>> est_intervals, est_pitches = mir_eval.io.load_valued_intervals(
... 'estimate.txt')
>>> scores = mir_ev... |
339,460 | def optionally_with_plugs(phase, **subplugs):
if isinstance(phase, PhaseGroup):
return phase.with_plugs(**subplugs)
if isinstance(phase, collections.Iterable):
return [optionally_with_plugs(p, **subplugs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_des... | Apply only the with_plugs that the phase knows.
This will determine the subset of plug overrides for only plugs the phase
actually has.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply the
plug chan... |
339,461 | def loadcache(json_file):
f = open(json_file, )
data = f.read()
f.close()
try:
apicache = json.loads(data)
except ValueError as e:
print("Error processing json:", json_file, e)
return {}
return apicache | Loads json file as dictionary, feeds it to monkeycache and spits result |
339,462 | def write(self, filename=None):
file_data = list(self.__data__)
for structure in self.__structures__:
struct_data = list(structure.__pack__())
offset = structure.get_file_offset()
file_data[offset:offset+len(struct_data)] = ... | Write the PE file.
This function will process all headers and components
of the PE file and include all changes made (by just
assigning to attributes in the PE objects) and write
the changes back to a file whose name is provided as
an argument. The filename is optional, ... |
339,463 | def ToJson(self, auto_hex=True):
jsn = {}
jsn[] = str(ContractParameterType(self.Type))
if self.Type == ContractParameterType.Signature:
jsn[] = self.Value.hex()
elif self.Type == ContractParameterType.ByteArray:
if auto_hex:
jsn[] = sel... | Converts a ContractParameter instance to a json representation
Returns:
dict: a dictionary representation of the contract parameter |
339,464 | def pixbuf_to_cairo_png(pixbuf):
buffer_pointer = ffi.new()
buffer_size = ffi.new()
error = ffi.new()
handle_g_error(error, pixbuf.save_to_buffer(
buffer_pointer, buffer_size, ffi.new(, b), error,
ffi.new(, b), ffi.new(, b),
ffi.NULL))
png_bytes = ffi.buffer(buffer_point... | Convert from PixBuf to ImageSurface, by going through the PNG format.
This method is 10~30x slower than GDK but always works. |
339,465 | def get_extr_license_ident(self, extr_lic):
identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace[], None)))
if not identifier_tripples:
self.error = True
msg =
self.logger.log(msg)
return
if len(identifier_trippl... | Return an a license identifier from an ExtractedLicense or None. |
339,466 | def reader(self):
from ambry.orm.exc import NotFoundError
from fs.errors import ResourceNotFoundError
try:
return self.datafile.reader
except ResourceNotFoundError:
raise NotFoundError("Failed to find partition file, "
.f... | The reader for the datafile |
339,467 | def colstack(self, new, mode=):
if isinstance(new,list):
return tab_colstack([self] + new,mode)
else:
return tab_colstack([self, new], mode) | Horizontal stacking for tabarrays.
Stack tabarray(s) in `new` to the right of `self`.
**See also**
:func:`tabular.tabarray.tab_colstack`,
:func:`tabular.spreadsheet.colstack` |
339,468 | def load_rsa_private_key_file(rsakeyfile, passphrase):
keypath = os.path.expandvars(os.path.expanduser(rsakeyfile))
with open(keypath, ) as keyfile:
return cryptography.hazmat.primitives.serialization.\
load_pem_private_key(
keyfile.read(),
pass... | Load an RSA Private key PEM file with passphrase if specified
:param str rsakeyfile: RSA private key PEM file to load
:param str passphrase: optional passphrase
:rtype: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey
:return: RSAPrivateKey |
339,469 | def set_title(self, title):
assert isinstance(title, six.text_type)
self._winapi(windll.kernel32.SetConsoleTitleW, title) | Set terminal title. |
339,470 | def wrap_handler(self, api_types, methods, endpoints):
def wrapper(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return fn(*args, **kwargs)
for api_type in api_types:
for method in methods:
for endpoint in endpoin... | Allow for a handler to be wrapped in a chain.
:param api_types: Types to wrap handlers for
:param methods: Methods to wrap handlers for
:param endpoints: Endpoints to wrap handlers for |
339,471 | async def async_send_to_pipe_channel(channel_name,
label,
value):
pcn = _form_pipe_channel_name(channel_name)
channel_layer = get_channel_layer()
await channel_layer.group_send(pcn,
{"type":"pi... | Send message asynchronously through pipe to client component |
339,472 | def to_localized_time(self, date, **kw):
if date is None:
return ""
options = {
"long_format": True,
"time_only": False,
"context": api.get_portal(),
"request": api.get_request(),
"domain": "senaite.core",
... | Converts the given date to a localized time string |
339,473 | def handle_publishable_m2m_changed(
sender, instance, action, reverse, model, pk_set, **kwargs):
if not issubclass(model, PublishingModel):
return
if reverse:
for rel_obj in instance._meta.get_all_related_many_to_many_objects():
if rel_obj.field.rel.throug... | Cache related published objects in `pre_clear` so they can be restored in
`post_clear`. |
339,474 | def reverse(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
):
params = {}
params[] = self.api_key
point = self._coerce_point_to_string(query, "%(lon)s,%(lat)s")
quoted_query = quote(point.encode())
url = "?"... | Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latitude)s, %(longitude)s"``.
:pa... |
339,475 | def get_args():
parser = build_parser()
args = vars(parser.parse_args())
if args[] and args[] is None:
args[] = args[]
args.pop(, None)
return {key: val for key, val in args.items() if val is not None} | Load settings from the command line. |
339,476 | def put_httpsconf(self, name, certid, forceHttps):
req = {}
req.update({"certid": certid})
req.update({"forceHttps": forceHttps})
body = json.dumps(req)
url = .format(self.server, name)
return self.__put(url, body) | 修改证书,文档 https://developer.qiniu.com/fusion/api/4246/the-domain-name#11
Args:
domains: 域名name
CertID: 证书id,从上传或者获取证书列表里拿到证书id
ForceHttps: 是否强制https跳转
Returns:
{} |
339,477 | def uuid_object(title="Reference", description="Select an object", default=None, display=True):
uuid = {
:
,
: ,
: title,
: description,
}
if not display:
uuid[] = {
: "false"
}
if default is not ... | Generates a regular expression controlled UUID field |
339,478 | def encryption_details(self):
event_type = self.findtext("event_type")
if event_type != "encryption":
raise AttributeError(
" details".format(event_type)
)
parsed_encryption_event_detail = self.parsed_event_detail
encrypti... | Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption. |
339,479 | def init_package(package_path, package_name, docstring):
module_names = get_module_names(package_path)
modules = get_modules(package_name, module_names)
dunder_all = dunder_all_concat(modules)
for module in modules:
append_summary_to_module_docstring(module)
pairs = list(zip(module_names, modules))
k... | Package initialization, to be called only by ``__init__.py``.
- Find all module names;
- Import all modules (so they're already cached on sys.modules), in
the sorting order (this might make difference on cyclic imports);
- Update all module docstrings (with the summary of its contents);
- Build a module su... |
339,480 | def _fetch_features(self):
if self.next_page_url is None:
return
response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers)
self.features.extend(response[])
self.next_page_url = response[][]
self.layer_size = r... | Retrieves a new page of features from Geopedia |
339,481 | def subscribe(self, callback, filter_):
sub_id = "subscriber_{uuid}".format(uuid=uuid.uuid4())
sub = pd.DataFrame({sub_id: filter_}).T
sub[] = callback
self.subscribers = self.subscribers.append(sub)
this_subscriber_metrics = self.__filter(self.metrics... | Create and register metric subscriber,
find metrics for this subscriber (using filter_) and subscribe
Args:
callback (object method): subscriber's callback
filter_ (dict): filter dict
filter sample:
{'type': 'metrics', 'source': 'gun'} |
339,482 | def register_parser(self, parser: Parser):
check_var(parser, var_types=Parser, var_name=)
if (not parser.supports_multifile()) and (not parser.supports_singlefile()):
raise _InvalidParserException.create(parser)
res = parser.is_able_to_parse_detailed(d... | Utility method to register any parser. Parsers that support any type will be stored in the "generic"
list, and the others will be stored in front of the types they support
:return: |
339,483 | def _visibility_to_text(self, distance):
if not isinstance(distance, (int, long)):
raise ValueError("Distance must be an integer not", type(distance))
if distance < 0:
raise ValueError("Distance out of bounds, should be 0 or greater")
if 0 <= distance < 1000:
... | Convert observed visibility in metres to text used in forecast |
339,484 | def longest_common_subsequence(x, y):
n = len(x)
m = len(y)
A = [[0 for j in range(m + 1)] for i in range(n + 1)]
for i in range(n):
for j in range(m):
if x[i] == y[j]:
A[i + 1][j + 1] = A[i][j] + 1
else:
A[i + 1][j + 1] = max(A[i... | Longest common subsequence
Dynamic programming
:param x:
:param y: x, y are lists or strings
:returns: longest common subsequence in form of a string
:complexity: `O(|x|*|y|)` |
339,485 | def name_is_valid(name):
if len(name) > MAX_NAME_LENGTH:
return False
return bool(NAME_VALID_CHARS_REGEX.match(name)) | Return True if the dataset name is valid.
The name can only be 80 characters long.
Valid characters: Alpha numeric characters [0-9a-zA-Z]
Valid special characters: - _ . |
339,486 | def color_selection(show_palette=False, opacity_control=False, title="",
width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, timeout=None):
dialog = ZColorSelection(show_palette, opacity_control, title, width, height, timeout)
dialog.run()
return dialog.response | Display a color selection dialog
:param show_palette: hide/show the palette with preselected colors
:type show_palette: bool
:param opacity_control: allow to control opacity
:type opacity_control: bool
:param title: title of the window
:type title: str
:param width: window width
:type w... |
339,487 | def calc_bias_abc(second_order_influence):
num_obs = second_order_influence.shape[0]
constant = 2.0 * num_obs**2
bias = second_order_influence.sum(axis=0) / constant
return bias | Calculates the approximate bias of the MLE estimates for use in calculating
the approximate bootstrap confidence (ABC) intervals.
Parameters
----------
second_order_influence : 2D ndarray.
Should have one row for each observation. Should have one column for
each parameter in the paramet... |
339,488 | def _request(self, url, method="GET", params=None, api_call=None):
method = method.lower()
params = params or {}
func = getattr(requests, method)
requests_args = {}
if method == "get" or method == "delete":
requests_args["params"] = params
else:
... | Internal request method |
339,489 | def save_with_exif_info(img, *args, **kwargs):
if in kwargs:
exif = kwargs.pop()
else:
exif = img.info.get()
img.save(*args, exif=exif, **kwargs) | Saves an image using PIL, preserving the exif information.
Args:
img (PIL.Image.Image):
*args: The arguments for the `save` method of the Image class.
**kwargs: The keywords for the `save` method of the Image class. |
339,490 | def connect_child(self, sprite, event, *args, **kwargs):
handler = sprite.connect(event, *args, **kwargs)
self._child_handlers[sprite].append(handler)
return handler | connect to a child event so that will disconnect if the child is
removed from this sprite. this is the recommended way to connect to
child events. syntax is same as for the .connect itself, just you
prepend the child sprite as the first element |
339,491 | def validate(self):
for name, field in self:
try:
field.validate_for_object(self)
except ValidationError as error:
raise ValidationError(
"Error for field .".format(name=name),
error,
) | Explicitly validate all the fields. |
339,492 | def validate_keys(self):
url =
keys_present = self.consumer_key and self.consumer_secret and \
self.access_token and self.access_token_secret
if keys_present:
try:
self.connect()
self... | Validate the keys provided are authentic credentials. |
339,493 | def __collapse_stranded(s, proc_strands, names=False, verbose=False):
def get_first_matching_index(s, proc_strands):
for i in range(0, len(s)):
if s[i].strand in proc_strands:
return i
return None
if proc_strands not in [set("+"), set("-"), set(["+", "-"])]:
raise GenomicIntervalError(... | Get the union of a set of genomic intervals.
given a list of genomic intervals with chromosome, start, end and strand
fields, collapse those intervals with strand in the set <proc_strands>
into a set of non-overlapping intervals. Other intervals are ignored.
Intervals must be sorted by chromosome and then star... |
339,494 | def get_argument_values(self, model, prefix_args):
spec = inspect.getfullargspec(model)
if spec.varargs:
logger.warning("ABI: A vararg model must be a unary function.")
nargs = len(spec.args) - len(prefix_args)
if inspect.ismethod(model):
narg... | Extract arguments for model from the environment and return as a tuple that
is ready to be passed to the model.
:param callable model: Python model of the function
:param tuple prefix_args: Parameters to pass to model before actual ones
:return: Arguments to be passed to the model
... |
339,495 | def transform_grid_to_reference_frame(self, grid):
transformed = np.subtract(grid, self.centre)
return transformed.view(TransformedGrid) | Transform a grid of (y,x) coordinates to the reference frame of the profile, including a translation to \
its centre.
Parameters
----------
grid : ndarray
The (y, x) coordinates in the original reference frame of the grid. |
339,496 | def space(self):
arg_spaces = [o.space for o in self.matrix.ravel()
if hasattr(o, )]
if len(arg_spaces) == 0:
return TrivialSpace
else:
return ProductSpace.create(*arg_spaces) | Combined Hilbert space of all matrix elements. |
339,497 | def get(cls, keyval, key=, user_id=None):
if keyval is None:
return None
if (key in cls.__table__.columns
and cls.__table__.columns[key].primary_key):
return cls.query.get(keyval)
else:
result = cls.query.filt... | Fetches a single instance which has value `keyval`
for the attribute `key`.
Args:
keyval: The value of the attribute.
key (str, optional): The attribute to search by. By default,
it is 'id'.
Returns:
A model instance if found. Else None.
... |
339,498 | def is_transport_reaction_annotations(rxn):
reactants = set([(k, tuple(v)) for met in rxn.reactants
for k, v in iteritems(met.annotation)
if met.id != "H"
and k is not None and k != and v is not None])
products = set([(k, tuple(v)) for met in ... | Return boolean if a reaction is a transport reaction (from annotations).
Parameters
----------
rxn: cobra.Reaction
The metabolic reaction under investigation. |
339,499 | def create(gandi, name, vm, size, snapshotprofile, datacenter, source,
background):
try:
gandi.datacenter.is_opened(datacenter, )
except DatacenterLimited as exc:
gandi.echo(
%
(datacenter, exc.date))
if vm:
vm_dc = gandi.iaas.i... | Create a new disk. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.