Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
352,700 | def iterstraight(self, raw):
rb_1 = self.row_bytes + 1
a = bytearray()
filt = Filter(self.bitdepth * self.planes)
for some in raw:
a.extend(some)
offset = 0
while len(a) >= rb_1 + offset:
filter_type = a[offset]
... | Iterator that undoes the effect of filtering
Yields each row in serialised format (as a sequence of bytes).
Assumes input is straightlaced. `raw` should be an iterable
that yields the raw bytes in chunks of arbitrary size. |
352,701 | def clear(self):
for node in self.dli():
node.empty = True
node.key = None
node.value = None
self.head = _dlnode()
self.head.next = self.head
self.head.prev = self.head
self.listSize = 1
self.table.clear()
self.hit_cnt = 0
self.miss_cnt = 0
self.remove_cnt = 0 | claar all the cache, and release memory |
352,702 | def _analyses_data(self, ws):
ans = ws.getAnalyses()
layout = ws.getLayout()
pos_count = 0
prev_pos = 0
ars = {}
uid_to_pos_mapping = dict(
map(lambda row: (row["analysis_uid"], row["position"]), layout))
for an in ans:
... | Returns a list of dicts. Each dict represents an analysis
assigned to the worksheet |
352,703 | def add_document(self, doc_id, nosave=False, score=1.0, payload=None,
replace=False, partial=False, language=None, **fields):
return self._add_document(doc_id, conn=None, nosave=nosave, score=score,
payload=payload, replace=replace,
... | Add a single document to the index.
### Parameters
- **doc_id**: the id of the saved document.
- **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.
- **score**: the document ranking, between 0.0 and 1.0
... |
352,704 | def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
source = None
if loader is not None and hasattr(loader, "get_source"):
try:
source = loader.get_source(module_name)
except ImportError:
pass
... | Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context). |
352,705 | def plot_zed(ZED, datablock, angle, s, units):
for fignum in list(ZED.keys()):
fig = plt.figure(num=ZED[fignum])
plt.clf()
if not isServer:
plt.figtext(.02, .01, version_num)
DIbad, DIgood = [], []
for rec in datablock:
if cb.is_null(rec[1],zero_as_null=False... | function to make equal area plot and zijderveld plot
Parameters
_________
ZED : dictionary with keys for plots
eqarea : figure number for equal area projection
zijd : figure number for zijderveld plot
demag : figure number for magnetization against demag step
datablock :... |
352,706 | def evolve(inst, **changes):
cls = inst.__class__
attrs = fields(cls)
for a in attrs:
if not a.init:
continue
attr_name = a.name
init_name = attr_name if attr_name[0] != "_" else attr_name[1:]
if init_name not in changes:
changes[init_name] = ge... | Create a new instance, based on *inst* with *changes* applied.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise TypeError: If *attr_name* couldn't be found in the class
``__... |
352,707 | def query(self, w, ed=1):
assert ed <= self._ed
if ed == 0:
return [w] if w in self._L else []
w = str(w)
n = len(w)
prefix, suffix = w[:n // 2], w[n // 2:][::-1]
options_w_prefix = self._L.keys(prefix)
options_w_suffix = [x[::-1] for x in s... | Finds the fuzzy matches (within edit distance 1) of w from words |
352,708 | def submit_tasks(self, wait=False):
for task in self:
task.start()
if wait:
for task in self: task.wait() | Submits the task in self and wait.
TODO: change name. |
352,709 | def _check_registers(self, report=True):
for r in self.state.arch.uc_regs.keys():
v = getattr(self.state.regs, r)
processed_v = self._process_value(v, )
if processed_v is None or processed_v.symbolic:
if report:
se... | check if this state might be used in unicorn (has no concrete register) |
352,710 | def setup_project(self, directory):
self.emptywidget.hide()
self.treewidget.show()
self.set_project_dir(directory) | Setup project |
352,711 | def get_macs_for_vlan(self, ip, vlan, display_progress=0, snmpobj=None, system_name=None, ifname_vbtbl=None):
ret_macs = []
if (snmpobj == None):
snmpobj = natlas_snmp(ip)
if (snmpobj.get_cred(self.config.snmp_creds) == 0):
return None
if (ifname... | Return array of MAC addresses for a single VLAN from a single node at an IP |
352,712 | def runner(self):
logging.info(.format(self.analysistype))
if not self.pipeline:
except AttributeError:
objects = Objectprep(self)
objects.objectprep()
self.runmetadata = objects.samples
... | Run the necessary methods in the correct order |
352,713 | def vrelg(v1, v2, ndim):
v1 = stypes.toDoubleVector(v1)
v2 = stypes.toDoubleVector(v2)
ndim = ctypes.c_int(ndim)
return libspice.vrelg_c(v1, v2, ndim) | Return the relative difference between two vectors of general dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrelg_c.html
:param v1: First vector
:type v1: Array of floats
:param v2: Second vector
:type v2: Array of floats
:param ndim: Dimension of v1 and v2.
:type nd... |
352,714 | def get_languages(self, repo, temp_repo):
try:
self.languages[repo.language] += 1
except KeyError:
count = self.languages[repo.language] = 1
for repo_languages in repo.iter_languages():
self.languages_json[repo.name][repo_languages[0]] = repo_language... | Retrieves the languages used in the repo and increments the respective
counts of those languages. Only increments languages that have names.
Anything else is not incremented (i.e. numbers). |
352,715 | def generate_payload(self, config, context):
request = current_request()
payload = {
: request.build_absolute_uri(),
: request.resolver_match.app_name,
: request.resolver_match.func.__name__,
: {},
: {},
: dict(request.MET... | Generate payload by checking Django request object.
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload. |
352,716 | def next(self):
if self._records_iter >= len(self._records):
raise StopIteration
self._records_iter += 1
return self._records[self._records_iter - 1] | Return one of record in this batch in out-of-order.
:raises: `StopIteration` when no more record is in this batch |
352,717 | def fwdl_status_output_fwdl_entries_message(self, **kwargs):
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_entries = ET.SubElement(output, "fwdl-entries")
message = ET... | Auto Generated Code |
352,718 | def unify_partitions(self):
partitions = self.collect_segment_partitions()
with self.progress.start(, 0, message=) as ps:
for name, segments in iteritems(partitions):
ps.add(item_type=, item_count=len(segments),
message=.f... | For all of the segments for a partition, create the parent partition, combine the
children into the parent, and delete the children. |
352,719 | def get_time_inqueue(self):
if self.submission is None: return None
if self.start is None:
delta = datetime.datetime.now() - self.submission
else:
delta = self.start - self.submission
if delta.total_seconds() < 0: delta = datetime.timede... | :class:`timedelta` with the time spent in the Queue, None if the Task is not running
.. note:
This value is always greater than the real value computed by the resource manager
as we start to count only when check_status sets the `Task` status to S_RUN. |
352,720 | def remove_total_size(apps, schema_editor):
Data = apps.get_model(, )
for data in Data.objects.all():
for field_schema, fields in iterate_fields(data.output, data.process.output_schema):
name = field_schema[]
value = fields[name]
if in field_schema:
... | Remove ``total_size`` field from all file/dir-type outputs. |
352,721 | def server_url_for_websocket_url(url):
if url.startswith("ws:"):
reprotocoled = "http" + url[2:]
elif url.startswith("wss:"):
reprotocoled = "https" + url[3:]
else:
raise ValueError("URL has non-websocket protocol " + url)
if not reprotocoled.endswith("/ws"):
raise V... | Convert an ``ws(s)`` URL for a Bokeh server into the appropriate
``http(s)`` URL for the websocket endpoint.
Args:
url (str):
An ``ws(s)`` URL ending in ``/ws``
Returns:
str:
The corresponding ``http(s)`` URL.
Raises:
ValueError:
If the inpu... |
352,722 | def _post_run_hook(self, runtime):
self._anat_file = self.inputs.in_files[0]
outputs = self.aggregate_outputs(runtime=runtime)
self._mask_file = outputs.tissue_class_map
self._seg_files = outputs.tissue_class_files[1:]
self._masked = False
NIWO... | generates a report showing nine slices, three per axis, of an
arbitrary volume of `in_files`, with the resulting segmentation
overlaid |
352,723 | def get(cls, object_id):
return fields.ObjectField(name=cls.ENDPOINT, init_class=cls).decode(
cls.element_from_string(
cls._get_request(endpoint=cls.ENDPOINT + + str(object_id)).text
)
) | Retrieves a single model
:param object_id: the primary id of the model
:type object_id: integer
:return: the object of the parsed xml object
:rtype: object |
352,724 | def request_from_context(context):
new_context = copy.deepcopy(context)
assert new_context.method in ALLOWED_METHODS
new_context.url_path = generate_url_path(
new_context.url_path,
prefix=new_context.prefix_url_path,
format_suffix=new_context.url_path_format,
**new_cont... | Do http requests from context.
:param context: request context. |
352,725 | def _get_pgroup(name, array):
pgroup = None
for temp in array.list_pgroups():
if temp[] == name:
pgroup = temp
break
return pgroup | Private function to check protection group |
352,726 | def VOICE(input_shape,
conv_layers,
dense_layers,
output_layer=[1, ],
padding=,
optimizer=,
loss=):
inputs = Input(shape=input_shape)
for i, c in enumerate(conv_layers):
if i == 0:
conv = Conv1D(c[0][0], c[0][1], p... | Conv1D CNN used primarily for voice data.
Args:
input_shape (tuple): The shape of the input layer
targets (int): Number of targets
conv_layers (list): Conv layer descriptor [[(filter, kernel), (pool_size, stride), leak, drop], ... []]
dense_layers (TYPE): Dense layer descriptor ... |
352,727 | def reset(self):
if not any(state in self.states for state in ("ready", "finished")):
return self.error.emit("Not ready")
self.initialising.emit()
util.timer("resetting..")
stats = {"requestCount": self.host.stats()["totalRequestCount"]}
self.dat... | Request that host re-discovers plug-ins and re-processes selectors
A reset completely flushes the state of the GUI and reverts
back to how it was when it first got launched.
Pipeline:
______________ ____________ ______________
| | | ... |
352,728 | def create_profiles(self, prefix, weeks, ip_user=False):
record_counter = {}
for year, week in weeks:
file = self.storage.get(prefix, year, week)
self.count_records(record_counter, file)
print("Records read all: {}".format(se... | Create the user profiles for the given weeks. |
352,729 | def get_file_id(credentials, gfile, write_access=False):
http = credentials.authorize(Http())
service = discovery.build(, , http=http, cache_discovery=False)
file_id = service.files().get(fileId=, fields=).execute().get()
pathway = gfile.strip().split()
for idx, name in enumerate(p... | Get file ID by provided path. If file does not exist and
`write_access` is true, it will create whole path for you.
:param credentials: provide own credentials
:param gfile: path to Google Spreadsheet
:param write_access: allows to create full path if file does not exist
:type c... |
352,730 | def prepareImages(self, fileName, logType):
import subprocess
if self.imageType == "png":
self.imagePixmap.save(fileName + ".png", "PNG", -1)
if logType == "Physics":
makePostScript = "convert " + fileName + ".png " + fileName + ".ps"
... | Convert supplied QPixmap object to image file. |
352,731 | def set_more_headers(self, req, extra_headers=None):
oss_url = url.URL(req.url)
req.headers.update(extra_headers or {})
content_type = req.headers.get("content-type")
if content_type is None:
content_type, __ = mimetypes.guess_type(oss_url.path)
req... | Set content-type, content-md5, date to the request
Returns a new `PreparedRequest`
:param req: the origin unsigned request
:param extra_headers: extra headers you want to set, pass as dict |
352,732 | def post(self, path=, **params):
url = ensure_trailing_slash(self.url + path.lstrip())
return self._json_request(, url, data=json.dumps(params),
headers={: }) | Make a POST request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the POST.
POST requests are requests that cause a change on the server,
especially those that ask to create and return an object o... |
352,733 | def _run_aggregation_cmd(self, session, explicit_session):
read_preference = self._target._read_preference_for(session)
client = self._database.client
def _cmd(session, server, sock_info, slave_ok):
pipeline = self._full_pipeline()
cmd = SON([("aggregate", self.... | Run the full aggregation pipeline for this ChangeStream and return
the corresponding CommandCursor. |
352,734 | def changes(self, **kwargs):
path = self._get_id_path()
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the changes for a specific movie id.
Changes are grouped by key, and ordered by date in descending order.
By default, only the last 24 hours of changes are returned. The
maximum number of days that can be returned in a single request is 14.
The language is present on fields that are... |
352,735 | def multiple_extend_request_args(self, args, key, parameters, item_types,
orig=False):
_state = self.get_state(key)
for typ in item_types:
try:
_item = Message(**_state[typ])
except KeyError:
continue
... | Go through a set of items (by their type) and add the attribute-value
that match the list of parameters to the arguments
If the same parameter occurs in 2 different items then the value in
the later one will be the one used.
:param args: Initial set of arguments
:param key: Key ... |
352,736 | def get_ca_signed_key(ca_name,
CN=,
as_text=False,
cacert_path=None,
key_filename=None):
*
set_ca_path(cacert_path)
if not key_filename:
key_filename = CN
keyp = .format(
cert_base_path(),
ca... | Get the certificate path or content
ca_name
name of the CA
CN
common name of the certificate
as_text
if true, return the certificate content instead of the path
cacert_path
absolute path to certificates root directory
key_filename
alternative filename for the... |
352,737 | def _set_load_balance(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 6}, u: {: 2}, u: {... | Setter method for load_balance, mapped from YANG variable /interface/port_channel/load_balance (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_load_balance is considered as a private
method. Backends looking to populate this variable should
do so via callin... |
352,738 | def save_configuration_to_hdf5(register, configuration_file, name=):
def save_conf():
logging.info("Saving configuration: %s" % h5_file.filename)
register.configuration_file = h5_file.filename
try:
configuration_group = h5_file.create_group(h5_file.root, "configuration... | Saving configuration to HDF5 file from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
name : string
Additional identifier (subgroup). Useful when storing mo... |
352,739 | def handle(cls, vm, args):
docker = Iaas.info(vm)
if not docker:
raise Exception( % vm)
if docker[] != :
Iaas.start(vm)
remote_addr = docker[][0][][0][]
port = unixpipe.setup(remote_addr, , )
os.environ[] = % port
cls... | Setup forwarding connection to given VM and pipe docker cmds over SSH. |
352,740 | def _send_mail(subject_or_message: Optional[Union[str, Message]] = None,
to: Optional[Union[str, List[str]]] = None,
template: Optional[str] = None,
**kwargs):
subject_or_message = subject_or_message or kwargs.pop()
to = to or kwargs.pop(, [])
msg = make_mes... | The default function used for sending emails.
:param subject_or_message: A subject string, or for backwards compatibility with
stock Flask-Mail, a :class:`~flask_mail.Message` instance
:param to: An email address, or a list of email addresses
:param template: Which template t... |
352,741 | def verify_message(data_to_verify, signature, verify_cert):
cms_content = cms.ContentInfo.load(signature)
digest_alg = None
if cms_content[].native == :
for signer in cms_content[][]:
signed_attributes = signer[].copy()
digest_alg = signer[][].native
if d... | Function parses an ASN.1 encrypted message and extracts/decrypts
the original message.
:param data_to_verify:
A byte string of the data to be verified against the signature.
:param signature: A CMS ASN.1 byte string containing the signature.
:param verify_cert: The certificate ... |
352,742 | def clean(self):
EmailConfirmation.objects.filter(content_type=self.content_type, object_id=self.object_id, email_field_name=self.email_field_name).delete() | delete all confirmations for the same content_object and the same field |
352,743 | def urlstate(self, encryption_key):
lzma = LZMACompressor()
urlstate_data = json.dumps(self._state_dict)
urlstate_data = lzma.compress(urlstate_data.encode("UTF-8"))
urlstate_data += lzma.flush()
urlstate_data = _AESCipher(encryption_key).encrypt(urlstate_data)
l... | Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state. |
352,744 | def _add_hgnc_symbols(self, variant_obj):
hgnc_symbols = set()
if variant_obj.transcripts:
for transcript in variant_obj.transcripts:
if transcript.hgnc_symbol:
hgnc_symbols.add(transcript.hgnc_symbol)
else:
chrom = variant_obj... | Add hgnc symbols to the variant
If there are transcripts use the symbols found here,
otherwise use phizz to get the gene ids. |
352,745 | def load_dxf(file_obj, **kwargs):
def info(e):
get = {: }
renamed = {get[k]: util.make_sequence(v)[0] for k,
v in e.items() if k in get}
return renamed
def convert_line(e):
entities.append(... | Load a DXF file to a dictionary containing vertices and
entities.
Parameters
----------
file_obj: file or file- like object (has object.read method)
Returns
----------
result: dict, keys are entities, vertices and metadata |
352,746 | def history_search_forward(self, e):
u
self.l_buffer=self._history.history_search_forward(self.l_buffer) | u'''Search forward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search. By default, this command is unbound. |
352,747 | def parseDateText(self, dateString):
yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime()
currentMth = mth
currentDy = dy
s = dateString.lower()
m = self.ptc.CRE_DATE3.search(s)
mth = m.group()
mth = self.ptc.MonthOffsets[mth]
... | Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@return: calculated C{struct_time} value of dateString |
352,748 | def dump(self):
return {
: self.title,
: self.issue_id,
: self.reporter,
: self.assignee,
: self.status,
: self.product,
: self.component,
: self.created_at,
: self.updated_at,
: sel... | Return the object itself. |
352,749 | def dimension_values(self, dimension, expanded=True, flat=True):
index = self.get_dimension_index(dimension)
if index == 0:
return np.array([self.data if np.isscalar(self.data) else self.data[index]])
elif index == 1:
return [] if np.isscalar(self.data) else np.a... | Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten array
Returns:
NumPy array of values along the requested di... |
352,750 | def m2i(self, pkt, s):
if len(s) == 0:
raise ASN1_Error("ASN1F_CHOICE: got empty string")
_, s = BER_tagging_dec(s, hidden_tag=self.ASN1_tag,
explicit_tag=self.explicit_tag)
tag, _ = BER_id_dec(s)
if tag not in self.choices:
... | First we have to retrieve the appropriate choice.
Then we extract the field/packet, according to this choice. |
352,751 | def mock_input_submit(self, *args, **kwargs):
self.robot.load_page(self.base[])
if kwargs.get():
self.force_window_topper()
if self.base.get():
self.mock_popovers()
if self.base.get():
self.robot.mock_click(self.base[])
... | 模拟输入参数, 然后提交 |
352,752 | def DeviceGet(self, device_id):
if self.__SenseApiCall__(.format(device_id), ):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Obtain details of a single device
@param device_id (int) - Device for which to obtain details |
352,753 | def get_b(self):
start_point, end_point = self._get_bottom_line_coordinates()
width = self._get_bottom_line_width()
color = self._get_bottom_line_color()
return CellBorder(start_point, end_point, width, color) | Returns the bottom border of the cell |
352,754 | def absent(name=None, ipv4addr=None, **api_opts):
ret = {: name, : False, : , : {}}
obj = __salt__[](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts)
if not obj:
ret[] = True
ret[] =
return ret
if __opts__[]:
ret[] = None
ret[] = {: obj, : }
... | Ensure infoblox A record is removed.
State example:
.. code-block:: yaml
infoblox_a.absent:
- name: example-ha-0.domain.com
infoblox_a.absent:
- name:
- ipv4addr: 127.0.23.23 |
352,755 | def needs_gcloud(self):
gcloud_default_path = [, ]
if platform.system() != "Windows":
gcloud_default_path = os.path.join(os.path.expanduser(),
*gcloud_default_path)
else:
gcloud_default_path = os.path.join(os.environ... | Returns true if gcloud is unavailable and needed for
authentication. |
352,756 | def _updateWidgets(self):
row = 0
model = self.tree.model()
nodePath = if self.rti is None else self.rti.nodePath
pathItem = QtGui.QStandardItem(nodePath)
pathItem.setToolTip(nodePath)
pathItem.setEditable(False)
if self.rti is not None:
... | Updates the combo and spin boxes given the new rti or axes.
Emits the sigContentsChanged signal. |
352,757 | def request_status(r, detailed=False):
base_string = "HTTP {r.request.method} {r.request.url}: {r.status_code}"
if r.status_code in range(200,99):
string = base_string
if detailed is True:
string += " - {r.json()}"
else:
string += " - 👍"
return string.format(r=r)
else:
string = base_string
r... | Returns a formatted string about the status, useful for logging.
args:
r - takes requests.models.Response |
352,758 | def generate_mail(self):
msg = "Script info : \r\n"
msg = msg + "%-9s: %s" % (, SOURCEDIR) + "\r\n"
msg = msg + "%-9s: %s" % (, USER) + "\r\n"
msg = msg + "%-9s: %s" % (, HOST) + "\r\n"
msg = msg + "%-9s: %s" % (, PID) + "\r\n"
msg = msg + "\r... | Generate the email as MIMEText |
352,759 | def _get_altair_html_(self, chart_obj, slug):
try:
json_data = chart_obj.to_json(indent=0)
except Exception as e:
self.err(e)
html = + slug +
html +=
html += + json_data.replace("\n", "") + ";"
html +=
html += "const el_" + sl... | Get html for an Altair chart |
352,760 | def get_source(self, path_or_url):
if path_or_url.startswith((, )):
try:
return urlopen(path_or_url)
except IOError:
return None
fullpath = path_or_url
if not os.path.isabs(path_or_url):
fullpath = os.path.join(self.ba... | Returns the source image file descriptor.
path_or_url:
Path to the source image as an absolute path, a path relative
to `self.base_path` or a URL beginning with `http[s]` |
352,761 | def machine(self, machine_id, credentials=False):
if isinstance(machine_id, dict):
machine_id = machine_id[]
elif isinstance(machine_id, Machine):
machine_id = machine_id.id
return Machine(datacenter=self, machine_id=machine_id,
credentials=crede... | ::
GET /:login/machines/:id
:param machine_id: unique identifier for a machine to be found in the
datacenter
:type machine_id: :py:class:`basestring`
:rtype: :py:class:`smartdc.machine.Machine` |
352,762 | def _branch_flow_dc(self, branches, Bf, Pfinj, base_mva):
il = array([i for i,l in enumerate(branches) if 0.0 < l.rate_a < 1e10])
lpf = -Inf * ones(len(il))
rate_a = array([l.rate_a / base_mva for l in branches])
upf = rate_a[il] - Pfinj[il]
upt = rate_a[il] + P... | Returns the branch flow limit constraint. The real power flows
at the from end the lines are related to the bus voltage angles by
Pf = Bf * Va + Pfinj. |
352,763 | def is_namedtuple(type_: Type[Any]) -> bool:
return _issubclass(type_, tuple) and hasattr(type_, ) and hasattr(type_, ) | Generated with typing.NamedTuple |
352,764 | def format_args_in_redis_protocol(*args):
buf = WriteBuffer()
l = "*%d\r\n" % len(args)
if six.PY2:
buf.append(l)
else:
buf.append(l.encode())
for arg in args:
if isinstance(arg, six.text_type):
arg = arg.encode()
elif isinstance(arg,... | Formats arguments into redis protocol...
This function makes and returns a string/buffer corresponding to
given arguments formated with the redis protocol.
integer, text, string or binary types are automatically converted
(using utf8 if necessary).
More informations about the protocol: http://red... |
352,765 | def align(self, input_path, output_path, directions, pipeline,
filter_minimum):
with tempfile.NamedTemporaryFile(prefix=, suffix=) as fwd_fh:
fwd_conv_file = fwd_fh.name
with tempfile.NamedTemporaryFile(prefix=, suffix=) as rev_fh:
rev_co... | align - Takes input path to fasta of unaligned reads, aligns them to
a HMM, and returns the aligned reads in the output path
Parameters
----------
input_path : str
output_path : str
reverse_direction : dict
A dictionary of read names, with the entries being t... |
352,766 | def define(
self,
name: str,
default: Any = None,
type: type = None,
help: str = None,
metavar: str = None,
multiple: bool = False,
group: str = None,
callback: Callable[[Any], None] = None,
) -> None:
normalized = self._normal... | Defines a new command line option.
``type`` can be any of `str`, `int`, `float`, `bool`,
`~datetime.datetime`, or `~datetime.timedelta`. If no ``type``
is given but a ``default`` is, ``type`` is the type of
``default``. Otherwise, ``type`` defaults to `str`.
If ``multiple`` is ... |
352,767 | def add_neighbours(self):
ipix = self._best_res_pixels()
hp = HEALPix(nside=(1 << self.max_order), order=)
extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix)
neigh_ipix = np.setdiff1d(extend_ipix, ipix)
shift = 2... | Extends the MOC instance so that it includes the HEALPix cells touching its border.
The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance.
Returns
-------
moc : `~mocpy.moc.MOC`
self extended by one degree of neighbours. |
352,768 | def is_subdomain(self, other):
(nr, o, nl) = self.fullcompare(other)
if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL:
return True
return False | Is self a subdomain of other?
The notion of subdomain includes equality.
@rtype: bool |
352,769 | def destroy(self, sshkeyid, params=None):
params = update_params(params, {: sshkeyid})
return self.request(, params, ) | /v1/sshkey/destroy
POST - account
Remove a SSH key. Note that this will not remove
the key from any machines that already have it.
Link: https://www.vultr.com/api/#sshkey_destroy |
352,770 | def circle2circle(line):
words = re.split(, line)
ra = words[1]
dec = words[2]
radius = words[3][:-1]
if ":" in ra:
ra = Angle(ra, unit=u.hour)
else:
ra = Angle(ra, unit=u.degree)
dec = Angle(dec, unit=u.degree)
radius = Angle(radius, unit=u.arcsecond)
return [... | Parse a string that describes a circle in ds9 format.
Parameters
----------
line : str
A string containing a DS9 region command for a circle.
Returns
-------
circle : [ra, dec, radius]
The center and radius of the circle. |
352,771 | def create_key_bindings(history, python_input, history_mapping):
bindings = KeyBindings()
handle = bindings.add
@handle(, filter=has_focus(history.history_buffer))
def _(event):
b = event.current_buffer
line_no = b.document.cursor_position_row
if not history_mappi... | Key bindings. |
352,772 | def parse_map_file(mapFNH):
m = OrderedDict()
map_header = None
with file_handle(mapFNH) as mapF:
for line in mapF:
if line.startswith("
map_header = line.strip().split("\t")
if line.startswith("
continue
line = line.strip... | Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID
(default) or a user-supplied one. The only required fields are SampleID,
BarcodeSequence, LinkerPrimerSequence (in that order), and Description
(which must be the final field).
:type mapFNH: str
:param mapFNH: Eith... |
352,773 | def insert(self, task, args=[], kwargs={}, delay_seconds=0):
body = {
"payload": task.payload(),
"queueName": self._queue_name,
"groupByTag": True,
"tag": task.__class__.__name__
}
def cloud_insertion():
self._api.insert(body, delay_seconds)
self._pool.spawn(cloud_in... | Insert a task into an existing queue. |
352,774 | def set_color(self, rgb):
target = .join([str(c) for c in rgb])
self.set_service_value(
self.color_service,
,
,
target)
rgbi = self.get_color_index([, , ])
if rgbi is None:
return
target = ( +
... | Set dimmer color. |
352,775 | def fetch_sqlite_master(self):
sqlite_master_record_list = []
result = self.__cur.execute(
"SELECT {:s} FROM sqlite_master".format(", ".join(self._SQLITE_MASTER_ATTR_NAME_LIST))
)
for record in result.fetchall():
sqlite_master_record_list.append(
... | Get sqlite_master table information as a list of dictionaries.
:return: sqlite_master table information.
:rtype: list
:Sample Code:
.. code:: python
from sqliteschema import SQLiteSchemaExtractor
print(json.dumps(SQLiteSchemaExtractor("sample.sqlit... |
352,776 | def parse_parameter(self, node):
if self.current_component_type == None:
self.raise_error( +
)
try:
name = node.lattrib[]
except:
self.raise_error()
try:
dimension = node.lattrib[]
except:
... | Parses <Parameter>
@param node: Node containing the <Parameter> element
@type node: xml.etree.Element
@raise ParseError: Raised when the parameter does not have a name.
@raise ParseError: Raised when the parameter does not have a
dimension. |
352,777 | def calc_autocorrelation(Signal, FFT=False, PyCUDA=False):
if FFT==True:
Signal_padded = scipy.fftpack.ifftshift((Signal-_np.average(Signal))/_np.std(Signal))
n, = Signal_padded.shape
Signal_padded = _np.r_[Signal_padded[:n//2], _np.zeros_like(Signal_padded), Signal_padded[n//2:]]
... | Calculates the autocorrelation from a given Signal via using
Parameters
----------
Signal : array-like
Array containing the signal to have the autocorrelation calculated for
FFT : optional, bool
Uses FFT to accelerate autocorrelation calculation, but assumes certain
certain... |
352,778 | def get_accounts(self, **kwargs):
return PaginatedList(
Account,
self.__requester,
,
,
_kwargs=combine_kwargs(**kwargs)
) | List accounts that the current user can view or manage.
Typically, students and teachers will get an empty list in
response. Only account admins can view the accounts that they
are in.
:calls: `GET /api/v1/accounts \
<https://canvas.instructure.com/doc/api/accounts.html#method.... |
352,779 | async def _playnow(self, ctx, *, query: str):
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue and not player.is_playing:
return await ctx.invoke(self._play, query=query)
query = query.strip()
if not url_rx.match(query):
... | Plays immediately a song. |
352,780 | async def _do_tp(self, pip, mount) -> top_types.Point:
pip.update_instrument_offset(top_types.Point())
hotspots = robot_configs.calculate_tip_probe_hotspots(
pip.current_tip_length, self._config.tip_probe)
new_pos: Dict[Axis, List[float]] = {
ax... | Execute the work of tip probe.
This is a separate function so that it can be encapsulated in
a context manager that ensures the state of the pipette tip tracking
is reset properly. It should not be called outside of
:py:meth:`locate_tip_probe_center`.
:param pip: The pipette to... |
352,781 | def terminate_all(self):
logger.info(.format(self.name))
for task in self.tasks.itervalues():
if task.started_at and not task.completed_at:
task.terminate() | Terminate all currently running tasks. |
352,782 | async def estimate_pruned_members(self, *, days):
if not isinstance(days, int):
raise InvalidArgument(.format(days))
data = await self._state.http.estimate_pruned_members(self.id, days)
return data[] | |coro|
Similar to :meth:`prune_members` except instead of actually
pruning members, it returns how many members it would prune
from the guild had it been called.
Parameters
-----------
days: :class:`int`
The number of days before counting as inactive.
... |
352,783 | def is_subpath(path, parent):
try:
relpath = os.path.relpath(path, parent)
except ValueError:
return False
return relpath == os.curdir or not relpath.startswith(os.pardir) | Returns True if *path* points to the same or a subpath of *parent*. |
352,784 | def _output_work(self, work, root):
output_filename = os.path.join(self._output_dir, work)
tree = etree.ElementTree(root)
tree.write(output_filename, encoding=, pretty_print=True) | Saves the TEI XML document `root` at the path `work`. |
352,785 | def model_counts_spectrum(self, name, logemin, logemax, weighted=False):
return cs[imin:imax] | Return the model counts spectrum of a source.
Parameters
----------
name : str
Source name. |
352,786 | def set_plot_CC_T_rho_new(self,fig=,linestyle=[],burn_limit=0.997,color=[],marker=[],markevery=500):
if len(linestyle)==0:
linestyle=200*[]
plt.figure(fig)
for i in range(len(self.runs_H5_surf)):
sefiles=se(self.runs_H5_out[i])
t1_model=-1
mi... | Plots
end_model - array, control how far in models a run is plottet, if -1 till end
symbs_1 - set symbols of runs |
352,787 | def get_namespace_cost( db, namespace_id ):
lastblock = db.lastblock
namespace_units = get_epoch_namespace_price_units(lastblock)
namespace_fee = price_namespace( namespace_id, lastblock, namespace_units )
namespace = db.get_namespace( namespace_id )
namespace_fee = int(math.ceil(name... | Get the cost of a namespace.
Returns {'amount': ..., 'units': ..., 'namespace': ...} |
352,788 | def get_period_LS(self, date, mag, n_threads, min_period):
oversampling = 3.
hifac = int((max(date) - min(date)) / len(date) / min_period * 2.)
if hifac < 100:
hifac = 100
fx, fy, nout, jmax, prob = pLS.fasper(date, mag, oversampling, hi... | Period finding using the Lomb-Scargle algorithm.
Finding two periods. The second period is estimated after whitening
the first period. Calculating various other features as well
using derived periods.
Parameters
----------
date : array_like
An array of obser... |
352,789 | def create_absolute_values_structure(layer, fields):
summaries = {}
for field in source_fields:
if field in absolute_fields:
field_name = source_fields[field]
index = layer.fields().lookupField(field_name)
flat_table = FlatTable(*fields)
summarie... | Helper function to create the structure for absolute values.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields: List of name field on which we want to aggregate.
:type fields: list
:return: The data structure.
:rtype: dict |
352,790 | def index_genome_alignment_by_locus(fh, out_fh, verbose=False):
bound_iter = functools.partial(genome_alignment_iterator,
reference_species="hg19", index_friendly=True)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
idx = IndexedFile(fh, bound_iter, hash_func)
idx.writ... | Build an index for a genome alig. using coords in ref genome as keys. |
352,791 | def add_callback(self, name, callback, echo_old=False, priority=0):
if self.is_callback_property(name):
prop = getattr(type(self), name)
prop.add_callback(self, callback, echo_old=echo_old, priority=priority)
else:
raise TypeError("attribute is not a callbac... | Add a callback that gets triggered when a callback property of the
class changes.
Parameters
----------
name : str
The instance to add the callback to.
callback : func
The callback function to add
echo_old : bool, optional
If `True`, t... |
352,792 | def __push_params(self, tid, params):
stack = self.__paramStack.get( tid, [] )
stack.append(params)
self.__paramStack[tid] = stack | Remembers the arguments tuple for the last call to the hooked function
from this thread.
@type tid: int
@param tid: Thread global ID.
@type params: tuple( arg, arg, arg... )
@param params: Tuple of arguments. |
352,793 | def get_conv_name(conv, truncate=False, show_unread=False):
num_unread = len([conv_event for conv_event in conv.unread_events if
isinstance(conv_event, hangups.ChatMessageEvent) and
not conv.get_user(conv_event.user_id).is_self])
if show_unread and num_unread > 0... | Return a readable name for a conversation.
If the conversation has a custom name, use the custom name. Otherwise, for
one-to-one conversations, the name is the full name of the other user. For
group conversations, the name is a comma-separated list of first names. If
the group conversation is empty, th... |
352,794 | def complete_ls(self, text, *_):
return [t + " " for t in self.engine.cached_descriptions if t.startswith(text)] | Autocomplete for ls |
352,795 | def _keep_cursor_in_buffer(self):
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved | Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved. |
352,796 | def away_shift_summ(self):
if not self.__wrapped_away:
self.__wrapped_away = self.__wrap(self._away.by_player)
return self.__wrapped_away | :returns: :py:class:`.ShiftSummary` by player for the away team
:rtype: dict ``{ player_num: shift_summary_obj }`` |
352,797 | def author_line(soup):
author_line = None
authors_json_data = authors_json(soup)
author_names = extract_author_line_names(authors_json_data)
if len(author_names) > 0:
author_line = format_author_line(author_names)
return author_line | take preferred names from authors json and format them into an author line |
352,798 | def _min(self):
return (
self.range[0] if (self.range and self.range[0] is not None) else
(min(self._values) if self._values else None)
) | Getter for the minimum series value |
352,799 | def listify(func=None, wrapper=list):
def _listify_return(func):
@functools.wraps(func)
def _listify_helper(*args, **kw):
return wrapper(func(*args, **kw))
return _listify_helper
if func is None:
return _listify_return
return _listify_return(func) | A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
... for i in iterable:
... yield... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.