Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,100 | def _registrant_publication(reg_pub, rules):
for rule in rules:
if rule.min <= reg_pub <= rule.max:
reg_len = rule.registrant_length
break
else:
raise Exception(
)
registrant, publication = reg_pub[:reg_... | Separate the registration from the publication in a given
string.
:param reg_pub: A string of digits representing a registration
and publication.
:param rules: A list of RegistrantRules which designate where
to separate the values in the string.
:returns: A (regis... |
368,101 | def Pack(self):
return struct.pack(self.format, self.command, self.arg0, self.arg1,
len(self.data), self.checksum, self.magic) | Returns this message in an over-the-wire format. |
368,102 | def use_isolated_vault_view(self):
self._vault_view = ISOLATED
for session in self._get_provider_sessions():
try:
session.use_isolated_vault_view()
except AttributeError:
pass | Pass through to provider AuthorizationLookupSession.use_isolated_vault_view |
368,103 | def parse_data_line(self, line):
it = self._generate(line)
reader = csv.DictReader(it, fieldnames=self.headers)
values = reader.next()
values[] =
values[] = re.sub(r, , values[].strip())
values[] = values[].strip()
values[... | Parses the data line into a dictionary for the importer |
368,104 | def apply_changes(self, other, with_buffer=False):
self.rs.update(other.buffer)
if with_buffer:
self.buffer = other.buffer.copy() | Applies updates from the buffer of another filter.
Params:
other (MeanStdFilter): Other filter to apply info from
with_buffer (bool): Flag for specifying if the buffer should be
copied from other.
Examples:
>>> a = MeanStdFilter(())
>>> a... |
368,105 | def push_results(self, kill_event):
logger.debug("[RESULT_PUSH_THREAD] Starting thread")
push_poll_period = max(10, self.poll_period) / 1000
logger.debug("[RESULT_PUSH_THREAD] push poll period: {}".format(push_poll_period))
last_beat = time.time()
items = []
... | Listens on the pending_result_queue and sends out results via 0mq
Parameters:
-----------
kill_event : threading.Event
Event to let the thread know when it is time to die. |
368,106 | def setup_icons(self, ):
folder_icon = get_icon(, asicon=True)
self.asset_open_path_tb.setIcon(folder_icon)
self.shot_open_path_tb.setIcon(folder_icon)
current_icon = get_icon(, asicon=True)
self.current_pb.setIcon(current_icon)
refresh_icon = get_icon(, asicon... | Set all icons on buttons
:returns: None
:rtype: None
:raises: None |
368,107 | def key_value(minion_id,
pillar,
pillar_key=):
key_type = __salt__[](minion_id)
if key_type == :
return {pillar_key: __salt__[](minion_id)}
elif key_type == :
return {pillar_key: __salt__[](minion_id)}
elif key_type == :
list_size = __salt_... | Looks for key in redis matching minion_id, returns a structure based on the
data type of the redis key. String for string type, dict for hash type and
lists for lists, sets and sorted sets.
pillar_key
Pillar key to return data into |
368,108 | def iter_chunks(chunk_size, iterator):
"Yield from an iterator in chunks of chunk_size."
iterator = iter(iterator)
while True:
next_chunk = _take_n(chunk_size, iterator)
if next_chunk:
yield next_chunk
else:
break | Yield from an iterator in chunks of chunk_size. |
368,109 | def get_pid_from_tid(self, dwThreadId):
try:
try:
hThread = win32.OpenThread(
win32.THREAD_QUERY_LIMITED_INFORMATION, False, dwThreadId)
except WindowsError:
e = sys.exc_in... | Retrieves the global ID of the process that owns the thread.
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@rtype: int
@return: Process global ID.
@raise KeyError: The thread does not exist. |
368,110 | def create_session(user):
def cb():
if user:
if __options__.get("require_email_verification") and not user.email_verified:
raise exceptions.VerifyEmailError()
if flask_login.login_user(user):
user.update(last_login_at=utc_now())
r... | Create the login session
:param user: UserModel
:return: |
368,111 | def AddEvent(self, event):
self._RaiseIfNotWritable()
event_data_identifier = event.GetEventDataIdentifier()
if event_data_identifier:
if not isinstance(event_data_identifier, identifiers.SQLTableIdentifier):
raise IOError(.format(
type(event_data_identifier)))
... | Adds an event.
Args:
event (EventObject): event.
Raises:
IOError: when the storage file is closed or read-only or
if the event data identifier type is not supported.
OSError: when the storage file is closed or read-only or
if the event data identifier type is not supporte... |
368,112 | def catFiles(filesToCat, catFile):
if len(filesToCat) == 0:
open(catFile, ).close()
return
maxCat = 25
system("cat %s > %s" % (" ".join(filesToCat[:maxCat]), catFile))
filesToCat = filesToCat[maxCat:]
while len(filesToCat) > 0:
system("cat %s >> %s" % (" ".join(filesToC... | Cats a bunch of files into one file. Ensures a no more than maxCat files
are concatenated at each step. |
368,113 | def qos_map_cos_mutation_name(self, **kwargs):
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
cos_mutation = ET.SubElement(map, "cos-mutation")
name = ET.SubElement(cos_mutation, ... | Auto Generated Code |
368,114 | def InterpretWaveform(raw, integersOnly=False, headersOnly=False, noTimeArray=False):
MissingData = False
from struct import unpack
if raw[0:1] != b:
cmd = raw.split(b)[0]
wave = raw[len(cmd)+1:]
else:
wave = raw
... | Take the raw binary from a file saved from the LeCroy, read from a file using
the 2 lines:
with open(filename, "rb") as file:
raw = file.read()
And extracts various properties of the saved time trace.
Parameters
----------
raw : bytes
Bytes o... |
368,115 | def speed(self):
self._speed, value = self.get_attr_int(self._speed, )
return value | Returns the current motor speed in tacho counts per second. Note, this is
not necessarily degrees (although it is for LEGO motors). Use the `count_per_rot`
attribute to convert this value to RPM or deg/sec. |
368,116 | def copy_config_input_source_config_source_candidate_candidate(self, **kwargs):
config = ET.Element("config")
copy_config = ET.Element("copy_config")
config = copy_config
input = ET.SubElement(copy_config, "input")
source = ET.SubElement(input, "source")
config_s... | Auto Generated Code |
368,117 | def turn_physical_on(self,ro=None,vo=None):
self._roSet= True
self._voSet= True
if not ro is None:
if _APY_LOADED and isinstance(ro,units.Quantity):
ro= ro.to(units.kpc).value
self._ro= ro
if not vo is None:
if _APY_LOADED and ... | NAME:
turn_physical_on
PURPOSE:
turn on automatic returning of outputs in physical units
INPUT:
ro= reference distance (kpc; can be Quantity)
vo= reference velocity (km/s; can be Quantity)
OUTPUT:
(none)
HISTORY:
... |
368,118 | def list_blobs(
self,
max_results=None,
page_token=None,
prefix=None,
delimiter=None,
versions=None,
projection="noAcl",
fields=None,
client=None,
):
extra_params = {"projection": projection}
if prefix is not None:
... | Return an iterator used to find blobs in the bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type max_results: int
:param max_results:
(Optional) The maximum number of blobs in each page of results
from this request. Non-positive values a... |
368,119 | def _get_rows(self, options):
if options["oldsortslice"]:
rows = copy.deepcopy(self._rows[options["start"]:options["end"]])
else:
rows = copy.deepcopy(self._rows)
if options["sortby"]:
sortindex = self._field_names.index(options["sortby"])
... | Return only those data rows that should be printed, based on slicing and sorting.
Arguments:
options - dictionary of option settings. |
368,120 | def salt_extend(extension, name, description, salt_dir, merge):
import salt.utils.extend
salt.utils.extend.run(extension=extension,
name=name,
description=description,
salt_dir=salt_dir,
merge=merge) | Quickstart for developing on the saltstack installation
.. versionadded:: 2016.11.0 |
368,121 | def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None,
**kwargs):
if allow_label_click is None:
allow_label_click = capybara.automatic_label_click
@self.synchronize(wait=BaseQuery.normalize_wait(wait)... | Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element should be checked.
locator (str, optional): Which element to check.
allow_label_click (bool, optional): Attempt to click the label to toggle st... |
368,122 | def _escape(s):
assert isinstance(s, str), \
"expected %s but got %s; value=%s" % (type(str), type(s), s)
s = s.replace("\\", "\\\\")
s = s.replace("\n", "\\n")
s = s.replace("\t", "\\t")
s = s.replace(",", "\t")
return s | Escape commas, tabs, newlines and dashes in a string
Commas are encoded as tabs |
368,123 | def get_queryset(self, request):
qs = super(TenantGroupAdmin, self).get_queryset(request)
if not request.user.is_superuser:
qs = qs.filter(tenantrole__user=request.user,
tenantrole__role=TenantRole.ROLE_GROUP_MANAGER)
return qs | Limit to TenantGroups that this user can access. |
368,124 | def _tarjan(self, function, order, stack, data):
try:
func_data = data[function.id]
return order
except KeyError:
func_data = self._TarjanData(order)
data[function.id] = func_data
order += 1
pos = len(stack)
stack.append(f... | Tarjan's strongly connected components algorithm.
See also:
- http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm |
368,125 | def reverted(name, snapshot=None, cleanup=False):
ret = {: name, : {}, : False, : }
try:
domains = fnmatch.filter(__salt__[](), name)
if not domains:
ret[] = .format(name)
else:
ignored_domains = list()
if len(domains) > 1:
ret[... | .. deprecated:: 2016.3.0
Reverts to the particular snapshot.
.. versionadded:: 2016.3.0
.. code-block:: yaml
domain_name:
virt.reverted:
- cleanup: True
domain_name_1:
virt.reverted:
- snapshot: snapshot_name
- cleanup: False |
368,126 | def _get_sortgo(self):
if in self.datobj.kws:
return self.datobj.kws[]
return self.datobj.grprdflt.gosubdag.prt_attr[] + "\n" | Get function for sorting GO terms in a list of namedtuples. |
368,127 | async def reply(self, *args, **kwargs):
kwargs[] = self.id
return await self._client.send_message(
await self.get_input_chat(), *args, **kwargs) | Replies to the message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with both ``entity`` and ``reply_to`` already set. |
368,128 | def extract_flash(prihdr, scihdu):
flshfile = prihdr.get(, )
flashsta = prihdr.get(, )
flashdur = prihdr.get(, 0.0)
if flshfile == or flashdur <= 0:
return None
if flashsta != :
warnings.warn(.format(flashsta),
AstropyUserWarning)
flshfile = from_ir... | Extract postflash data from ``FLSHFILE``.
Parameters
----------
prihdr : obj
FITS primary header HDU.
scihdu : obj
Extension HDU of the science image.
This is only used to extract subarray data.
Returns
-------
flash : ndarray or `None`
Postflash, if any. S... |
368,129 | def validate(self, validator, preserve_errors=False, copy=False,
section=None):
if section is None:
if self.configspec is None:
raise ValueError()
if preserve_errors:
from .validate import VdtMiss... | Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(validator)
(Normally having previously passed in the configspec when the ConfigObj
was created - you... |
368,130 | def prepare_metadata_for_build_wheel(metadata_directory, config_settings):
backend = _build_backend()
try:
hook = backend.prepare_metadata_for_build_wheel
except AttributeError:
return _get_wheel_metadata_from_wheel(backend, metadata_directory,
... | Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined. |
368,131 | def gen_min(cachedir, extra_mods=, overwrite=False, so_mods=,
python2_bin=, python3_bin=):
mindir = os.path.join(cachedir, )
if not os.path.isdir(mindir):
os.makedirs(mindir)
mintar = os.path.join(mindir, )
minver = os.path.join(mindir, )
pyminver = os.path.join(mindir, )
... | Generate the salt-min tarball and print the location of the tarball
Optional additional mods to include (e.g. mako) can be supplied as a comma
delimited string. Permits forcing an overwrite of the output file as well.
CLI Example:
.. code-block:: bash
salt-run min.generate
salt-run m... |
368,132 | def get_remote_peer_list(self):
params = {
: 0,
: DEFAULT_V,
: 2
}
res = self._get(, params=params)
return res[] | listPeer 返回列表
{
"rtn":0,
"peerList": [{
"category": "",
"status": 0,
"name": "GUNNER_HOME",
"vodPort": 43566,
"company": "XUNLEI_MIPS_BE_MIPS32",
"pid": "8498352EB4F5208X0001",
... |
368,133 | def get_grade_entries(self):
if self.retrieved:
raise errors.IllegalState()
self.retrieved = True
return objects.GradeEntryList(self._results, runtime=self._runtime) | Gets the package list resulting from the search.
return: (osid.grading.GradeEntryList) - the grade entry list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.* |
368,134 | def _set_child_joined_alias_using_join_map(child, join_map, alias_map):
for lhs, table, join_cols in join_map:
if lhs is None:
continue
if lhs == child.alias:
relevant_alias = child.related_alias
elif lhs == child.related_alias:
... | Set the joined alias on the child, for Django <= 1.7.x.
:param child:
:param join_map:
:param alias_map: |
368,135 | def expire_token(self, token):
r = requests.post(self._login_uri("/oauth/token/expire"),
data={
"client_id": self.client_id,
"client_secret": self.client_secret,
"token": token,
})
if r.status_code != 200:
rais... | Given a token, makes a request to the authentication server to expire
it immediately. This is considered a responsible way to log out a
user. If you simply remove the session your application has for the
user without expiring their token, the user is not _really_ logged out.
:param to... |
368,136 | def process_text(self, text, format=):
if self.eidos_reader is None:
self.initialize_reader()
default_arg = lambda x: autoclass()(x)
today = datetime.date.today().strftime("%Y-%m-%d")
fname =
annot_doc = self.eidos_reader.extractFromText(
text,
... | Return a mentions JSON object given text.
Parameters
----------
text : str
Text to be processed.
format : str
The format of the output to produce, one of "json" or "json_ld".
Default: "json"
Returns
-------
json_dict : dict
... |
368,137 | def print_details(self):
print("Title:", self.title)
print("Category:", self.category)
print("Page: ", self.page)
print("Size: ", self.size)
print("Files: ", self.files)
print("Age: ", self.age)
print("Seeds:", self.seeders)
print("Leechers: ", self.leechers)
print("Magnet: ", self.magnet)
print(... | Print torrent details |
368,138 | def integrate(self, coord, datetime_unit=None):
if not isinstance(coord, (list, tuple)):
coord = (coord, )
result = self
for c in coord:
result = result._integrate_one(c, datetime_unit=datetime_unit)
return result | integrate the array with the trapezoidal rule.
.. note::
This feature is limited to simple cartesian geometry, i.e. coord
must be one dimensional.
Parameters
----------
dim: str, or a sequence of str
Coordinate(s) used for the integration.
da... |
368,139 | def d2Ibr_dV2(Ybr, V, lam):
nb = len(V)
diaginvVm = spdiag(div(matrix(1.0, (nb, 1)), abs(V)))
Haa = spdiag(mul(-(Ybr.T * lam), V))
Hva = -1j * Haa * diaginvVm
Hav = Hva
Hvv = spmatrix([], [], [], (nb, nb))
return Haa, Hav, Hva, Hvv | Computes 2nd derivatives of complex branch current w.r.t. voltage. |
368,140 | def piece_size(model_file=None, model_proto=None, name=None):
return _gen_sentencepiece_processor_op.sentencepiece_get_piece_size(
model_file=model_file, model_proto=model_proto, name=name) | Returns the piece size (vocabulary size).
Args:
model_file: The sentencepiece model file path.
model_proto: The sentencepiece model serialized proto.
Either `model_file` or `model_proto` must be set.
name: The name argument that is passed to the op function.
Returns:
A scalar repre... |
368,141 | def clear_thumbnails(self):
state = self.state
for l in state.layers:
keys = state.layers[l].keys()[:]
for key in keys:
if (isinstance(state.layers[l][key], SlipThumbnail)
and not isinstance(state.layers[l][key], SlipIcon)):
... | clear all thumbnails from the map |
368,142 | def patText(s0):
arr = np.zeros((s0,s0), dtype=np.uint8)
s = int(round(s0/100.))
p1 = 0
pp1 = int(round(s0/10.))
for pos0 in np.linspace(0,s0,10):
cv2.putText(arr, , (p1,int(round(pos0))),
cv2.FONT_HERSHEY_COMPLEX_SMALL, fontScale=s,
col... | make text pattern |
368,143 | def render(template, context, partials={}, state=None):
state = state or State()
if isinstance(context, Context):
state.context = context
else:
state.context = Context(context)
if partials:
state.partials.push(partials)
return __render(make_unicode... | Renders a given mustache template, with sane defaults. |
368,144 | def is_not_none(self, a, message=None):
"Check if a value is not None"
if a is None:
self.log_error("{} is None".format(str(a)), message)
return False
return True | Check if a value is not None |
368,145 | def sync_one(self, aws_syncr, amazon, bucket):
if bucket.permission.statements:
permission_document = bucket.permission.document
else:
permission_document = ""
bucket_info = amazon.s3.bucket_info(bucket.name)
if not bucket_info.creation_date:
... | Make sure this bucket exists and has only attributes we want it to have |
368,146 | def apply_network(network, x, chunksize=None):
network_is_cuda = next(network.parameters()).is_cuda
x = torch.from_numpy(x)
with torch.no_grad():
if network_is_cuda:
x = x.cuda()
if chunksize is None:
return from_var(network(x))
return np.concatenate(... | Apply a pytorch network, potentially in chunks |
368,147 | def get_assessment_part_item_design_session(self, *args, **kwargs):
if not self.supports_assessment_part_lookup():
raise errors.Unimplemented()
if self._proxy_in_args(*args, **kwargs):
raise errors.InvalidArgument()
return sessions.AssessmentPartItemDe... | Gets the ``OsidSession`` associated with the assessment part item design service.
return: (osid.assessment.authoring.AssessmentPartItemDesignSession)
- an ``AssessmentPartItemDesignSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_... |
368,148 | def UrlGet(url, timeout=10, retries=0):
socket.setdefaulttimeout(timeout)
attempts = 0
content = None
while not content:
try:
content = urllib2.urlopen(url).read()
except urllib2.URLError:
attempts = attempts + 1
if attempts > retries:
raise IOError... | Retrieve content from the given URL. |
368,149 | def load_filter_plugins(entrypoint_group: str) -> Iterable[Filter]:
global loaded_filter_plugins
enabled_plugins: List[str] = []
config = BandersnatchConfig().config
try:
config_blacklist_plugins = config["blacklist"]["plugins"]
split_plugins = config_blacklist_plugins.split("\n")
... | Load all blacklist plugins that are registered with pkg_resources
Parameters
==========
entrypoint_group: str
The entrypoint group name to load plugins from
Returns
=======
List of Blacklist:
A list of objects derived from the Blacklist class |
368,150 | def get_withdrawal_quotas(self, currency):
data = {
: currency
}
return self._get(, True, data=data) | Get withdrawal quotas for a currency
https://docs.kucoin.com/#get-withdrawal-quotas
:param currency: Name of currency
:type currency: string
.. code:: python
quotas = client.get_withdrawal_quotas('ETH')
:returns: ApiResponse
.. code:: python
... |
368,151 | def token(self, i, restrict=None):
tokens_len = len(self.tokens)
if i == tokens_len:
tokens_len += self.scan(restrict)
if i < tokens_len:
if restrict and self.restrictions[i] and restrict > self.restrictions[i]:
raise NotImplementedError(
... | Get the i'th token, and if i is one past the end, then scan
for another token; restrict is a list of tokens that
are allowed, or 0 for any token. |
368,152 | def save_object(collection, obj):
if not in obj:
obj.id = uuid()
id = obj.id
path = object_path(collection, id)
temp_path = % path
with open(temp_path, ) as f:
data = _serialize(obj)
f.write(data)
shutil.move(temp_path, path)
if id in _db[collection].cache:
... | Save an object ``obj`` to the given ``collection``.
``obj.id`` must be unique across all other existing objects in
the given collection. If ``id`` is not present in the object, a
*UUID* is assigned as the object's ``id``.
Indexes already defined on the ``collection`` are updated after
the object ... |
368,153 | def set_uri(self, uri):
publicObj = self.get_public()
if publicObj is not None:
publicObj.set_uri(uri)
else:
publicObj = Cpublic()
publicObj.set_uri(uri)
self.set_public(publicObj) | Sets the uri to the public object
@param uri: a uri
@type uri: string |
368,154 | def t_NUMBER(self, t):
r
if t.value.find(".") != -1:
t.value = float(t.value)
else:
t.value = int(t.value)
return t | r'\d+\.?\d* |
368,155 | def enable_category(self, category: str) -> None:
for cmd_name in list(self.disabled_commands):
func = self.disabled_commands[cmd_name].command_function
if hasattr(func, HELP_CATEGORY) and getattr(func, HELP_CATEGORY) == category:
self.enable_command(cmd_name) | Enable an entire category of commands
:param category: the category to enable |
368,156 | def meanApprox(self, timeout, confidence=0.95):
jrdd = self.map(float)._to_java_object_rdd()
jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())
r = jdrdd.meanApprox(timeout, confidence).getFinalValue()
return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high()) | .. note:: Experimental
Approximate operation to return the mean within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000)) / 1000.0
>>> abs(rdd.meanApprox(1000) - r) / r < 0.05
True |
368,157 | def add_get(self, *args, **kwargs):
return self.add_route(hdrs.METH_GET, *args, **kwargs) | Shortcut for add_route with method GET |
368,158 | def save_csv(self, csv_location):
with open(csv_location, ) as csv_handle:
writer = csv.writer(csv_handle)
for row in self.csv_data:
writer.writerow(row) | Save the csv to a file |
368,159 | def remove_ticks(ax, x=False, y=False):
if x:
ax.xaxis.set_ticks_position("none")
if y:
ax.yaxis.set_ticks_position("none")
return ax | Remove ticks from axis.
Parameters:
ax: axes to work on
x: if True, remove xticks. Default False.
y: if True, remove yticks. Default False.
Examples:
removeticks(ax, x=True)
removeticks(ax, x=True, y=True) |
368,160 | def neighbor_graph(X, metric=, k=None, epsilon=None,
weighting=, precomputed=False):
precomputedbinarynonebinary
if k is None and epsilon is None:
raise ValueError()
if weighting not in (, ):
raise ValueError( % weighting)
precomputed = precomputed or (metric == )
binar... | Build a neighbor graph from pairwise distance information.
X : two-dimensional array-like
Shape must either be (num_pts, num_dims) or (num_pts, num_pts).
k : int, maximum number of nearest neighbors
epsilon : float, maximum distance to a neighbor
metric : str, type of distance metric (see sklearn.m... |
368,161 | def update_profiles(self):
for path in [get_ipython_dir(), os.getcwdu()]:
for profile in list_profiles_in(path):
pd = self.get_profile_dir(profile, path)
if profile not in self.profiles:
self.log.debug("Adding cluster profile " % profile)
... | List all profiles in the ipython_dir and cwd. |
368,162 | def gps2_raw_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age, force_mavlink1=False):
return self.send(self.gps2_raw_encode(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age), force... | Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS
frame).
time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t)
fix_type : See the GPS_FIX_TYPE enum. (uint8_t)
l... |
368,163 | def build_js():
print("Building BokehJS... ", end="")
sys.stdout.flush()
os.chdir()
cmd = ["node", "make", , ]
t0 = time.time()
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as e:
print(BUILD_EXEC_FAIL_MSG % (cmd, e))
... | Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source
subdirectory.
Also prints a table of statistics about the generated assets (file sizes,
etc.) or any error messages if the build fails.
Note this function only builds BokehJS assets, it does not install them
into the python source tre... |
368,164 | def get_playcount(self):
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "playcount")) | Returns the user's playcount so far. |
368,165 | def _read_file(self, filename):
result = []
with open(filename, ) as f:
lines = f.read().split()
for line in lines:
nocomment = line.strip().split()[0].strip()
if nocomment:
result.append(nocomment)
return resul... | Return the lines from the given file, ignoring lines that start with
comments |
368,166 | def initialize(self, request):
if request.method == :
self.query = request.META.get(, )
elif request.method == :
self.query = request.body.decode()
self.ipaddress = request.META.get(, ) | Store the data we'll need to make the postback from the request object. |
368,167 | def capture_insert(self, *, exclude_fields=()):
return self.capture_insert_from_model(self.table_name, self.record_id,
exclude_fields=exclude_fields) | Apply :meth:`.TriggerLogAbstract.capture_insert_from_model` for this log. |
368,168 | def _progress(bytes_received, bytes_total, worker):
worker.sig_download_progress.emit(
worker.url, worker.path, bytes_received, bytes_total) | Return download progress. |
368,169 | def save(self, to_save, manipulate=True, check_keys=True, **kwargs):
warnings.warn("save is deprecated. Use insert_one or replace_one "
"instead", DeprecationWarning, stacklevel=2)
common.validate_is_document_type("to_save", to_save)
write_concern = None
c... | Save a document in this collection.
**DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead.
.. versionchanged:: 3.0
Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
operations. |
368,170 | def urlfetch_async(self, url, method=, headers=None,
payload=None, deadline=None, callback=None,
follow_redirects=False):
headers = {} if headers is None else dict(headers)
headers.update(self.user_agent)
try:
self.token = yield self.get_token_async()
... | Make an async urlfetch() call.
This is an async wrapper around urlfetch(). It adds an authentication
header.
Args:
url: the url to fetch.
method: the method in which to fetch.
headers: the http headers.
payload: the data to submit in the fetch.
deadline: the deadline in which... |
368,171 | def select_peer(peer_addrs, service, routing_id, method):
if any(p is None for p in peer_addrs):
return None
return random.choice(peer_addrs) | Choose a target from the available peers for a singular message
:param peer_addrs:
the ``(host, port)``s of the peers eligible to handle the RPC, and
possibly a ``None`` entry if this hub can handle it locally
:type peer_addrs: list
:param service: the service of the message
:type servi... |
368,172 | def find_minimum_spanning_forest(graph):
msf = []
if graph.num_nodes() == 0:
return msf
if graph.num_edges() == 0:
return msf
connected_components = get_connected_components_as_subgraphs(graph)
for subgraph in connected_components:
edge_list = kruskal_mst(subgraph)
... | Calculates the minimum spanning forest of a disconnected graph.
Returns a list of lists, each containing the edges that define that tree.
Returns an empty list for an empty graph. |
368,173 | def list_models(self, limit=-1, offset=-1):
return self.list_objects(limit=limit, offset=offset) | List models in the database. Takes optional parameters limit and
offset for pagination.
Parameters
----------
limit : int
Limit number of models in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
... |
368,174 | def unwrap_arguments(xml_response):
xml_response = xml_response.encode()
try:
tree... | Extract arguments and their values from a SOAP response.
Args:
xml_response (str): SOAP/xml response text (unicode,
not utf-8).
Returns:
dict: a dict of ``{argument_name: value}`` items. |
368,175 | def delete_handle_value(self, handle, key):
LOGGER.debug()
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg =
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_jso... | Delete a key-value pair from a handle record. If the key exists more
than once, all key-value pairs with this key are deleted.
:param handle: Handle from whose record the entry should be deleted.
:param key: Key to be deleted. Also accepts a list of keys.
:raises: :exc:`~b2handle.handle... |
368,176 | async def api_call(self, endpoint):
data = None
if self.session is None:
self.session = aiohttp.ClientSession()
try:
async with async_timeout.timeout(5, loop=self.loop):
response = await self.session.get(endpoint, headers=HEADERS)
... | Call the API. |
368,177 | def growSynapses(self, segments, activeInputsBySource, initialPermanence):
for source, connections in self.connectionsBySource.iteritems():
connections.growSynapses(segments, activeInputsBySource[source],
initialPermanence) | Grow synapses to each of the specified inputs on each specified segment.
@param segments (numpy array)
The segments that should add synapses
@param activeInputsBySource (dict)
The active cells in each source. Example:
{"customInputName1": np.array([42, 69])}
@param initialPermanence (float) |
368,178 | def place(vertices_resources, nets, machine, constraints, breadth_first=True):
return sequential_place(vertices_resources, nets,
machine, constraints,
(None if not breadth_first else
breadth_first_vertex_order(vertices_resourc... | Places vertices in breadth-first order along a hilbert-curve path
through the chips in the machine.
This is a thin wrapper around the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placement algorithm which
optionally uses the :py:func:`breadth_first_vertex_order` vertex ordering
... |
368,179 | def render(self):
release_notes = []
for parser in self.parsers:
parser_content = parser.render()
if parser_content is not None:
release_notes.append(parser_content)
return u"\r\n\r\n".join(release_notes) | Returns the rendered release notes from all parsers as a string |
368,180 | def parameter_names_flat(self, include_fixed=False):
name_list = []
for p in self.flattened_parameters:
name = p.hierarchy_name()
if p.size > 1:
name_list.extend(["{}[{!s}]".format(name, i) for i in p._indices()])
else:
name_li... | Return the flattened parameter names for all subsequent parameters
of this parameter. We do not include the name for self here!
If you want the names for fixed parameters as well in this list,
set include_fixed to True.
if not hasattr(obj, 'cache'):
obj.cache = Funct... |
368,181 | def route(self, path=None, method=, callback=None, name=None,
apply=None, skip=None, **config):
if callable(path): path, callback = None, path
plugins = makelist(apply)
skiplist = makelist(skip)
def decorator(callback):
if isinstance(callba... | A decorator to bind a function to a request URL. Example::
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
The ``:name`` part is a wildcard. See :class:`Router` for syntax
details.
:param path: Request path o... |
368,182 | def get_consistent_edges(graph: BELGraph) -> Iterable[Tuple[BaseEntity, BaseEntity]]:
for u, v in graph.edges():
if pair_is_consistent(graph, u, v):
yield u, v | Yield pairs of (source node, target node) for which all of their edges have the same type of relation.
:return: An iterator over (source, target) node pairs corresponding to edges with many inconsistent relations |
368,183 | def get_cumulative_data(self):
sets = map(itemgetter(), self.data)
if not sets:
return
sum = sets.pop(0)
yield sum
while sets:
sum = map(add, sets.pop(0))
yield sum | Get the data as it will be charted. The first set will be
the actual first data set. The second will be the sum of the
first and the second, etc. |
368,184 | def _findRedundantProteins(protToPeps, pepToProts, proteins=None):
if proteins is None:
proteins = viewkeys(protToPeps)
pepFrequency = _getValueCounts(pepToProts)
protPepCounts = _getValueCounts(protToPeps)
getCount = operator.itemgetter(1)
getProt = operator.itemgetter(0)
... | Returns a set of proteins with redundant peptide evidence.
After removing the redundant proteins from the "protToPeps" and "pepToProts"
mapping, all remaining proteins have at least one unique peptide. The
remaining proteins are a "minimal" set of proteins that are able to explain
all peptides. However... |
368,185 | def _mb_model(self, beta, mini_batch):
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(beta.shape[0])])
rand_int = np.random.randint(low=0, high=self.data_length-mini_batch+1)
sample = np.arange(start=rand_int, stop=rand_int+mini_batc... | Creates the structure of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
mini_batch : int
Mini batch size for the data sampling
Returns
----------
lambda : np.array
... |
368,186 | def enable_zones(self, zones):
if isinstance(zones, str) or isinstance(zones, unicode):
zones = [zones]
new_zones = self.connection.enable_availability_zones(self.name, zones)
self.availability_zones = new_zones | Enable availability zones to this Access Point.
All zones must be in the same region as the Access Point.
:type zones: string or List of strings
:param zones: The name of the zone(s) to add. |
368,187 | def _psi(self, x, y, q, s):
return np.sqrt(q**2 * (s**2 + x**2) + y**2) | expression after equation (8) in Keeton&Kochanek 1998
:param x:
:param y:
:param q:
:param s:
:return: |
368,188 | def modflow_read_hydmod_file(hydmod_file, hydmod_outfile=None):
try:
import flopy.utils as fu
except Exception as e:
print(.format(hydmod_file, e))
return
obs = fu.HydmodObs(hydmod_file)
hyd_df = obs.get_dataframe()
hyd_df.columns = [i[2:] if i.lower() != else i f... | read in a binary hydmod file and return a dataframe of the results
Parameters
----------
hydmod_file : str
modflow hydmod binary file
hydmod_outfile : str
output file to write. If None, use <hydmod_file>.dat.
Default is None
Returns
-------
df : pandas.DataFrame
... |
368,189 | def makeSubDir(dirName):
if not os.path.exists(dirName):
os.mkdir(dirName)
os.chmod(dirName, 0777)
return dirName | Makes a given subdirectory if it doesn't already exist, making sure it us public. |
368,190 | def integrate_auto_switch(odes, kw, x, y0, params=(), **kwargs):
x_arr = np.asarray(x)
if x_arr.shape[-1] > 2:
raise NotImplementedError("Only adaptive support return_on_error for now")
multimode = False if x_arr.ndim < 2 else x_arr.shape[0]
nfo_keys = (, , , )
next_autonomous = getatt... | Auto-switching between formulations of ODE system.
In case one has a formulation of a system of ODEs which is preferential in
the beginning of the integration, this function allows the user to run the
integration with this system where it takes a user-specified maximum number
of steps before switching ... |
368,191 | def _initialize(self, *args, **kwargs):
self.items = None
self.keys = None
self.values = None
if args:
if len(args) != 2:
raise TypeError("expected exactly two positional arguments, "
"got %s" % len(args))
... | Initiaize the mapping matcher with constructor arguments. |
368,192 | def get_stack_frame(self, max_size = None):
sp, fp = self.get_stack_frame_range()
size = fp - sp
if max_size and size > max_size:
size = max_size
return self.get_process().peek(sp, size) | Reads the contents of the current stack frame.
Only works for functions with standard prologue and epilogue.
@type max_size: int
@param max_size: (Optional) Maximum amount of bytes to read.
@rtype: str
@return: Stack frame data.
May not be accurate, depending on t... |
368,193 | def initialize_memory(basic_block):
global MEMORY
MEMORY = basic_block.mem
get_labels(MEMORY, basic_block)
basic_block.mem = MEMORY | Initializes global memory array with the given one |
368,194 | def create_where():
conjunction = Forward().setResultsName("conjunction")
nested = Group(Suppress("(") + conjunction + Suppress(")")).setResultsName(
"conjunction"
)
maybe_nested = nested | constraint
inverted = Group(not_ + maybe_nested).setResultsName("not")
full_constraint = may... | Create a grammar for the 'where' clause used by 'select' |
368,195 | async def jsk_vc_youtube_dl(self, ctx: commands.Context, *, url: str):
if not youtube_dl:
return await ctx.send("youtube_dl is not installed.")
voice = ctx.guild.voice_client
if voice.is_playing():
voice.stop()
url = url.lstrip("<").rstrip(">... | Plays audio from youtube_dl-compatible sources. |
368,196 | def show_updates(self):
dists = Distributions()
if self.project_name:
pkg_list = [self.project_name]
else:
pkg_list = get_pkglist()
found = None
for pkg in pkg_list:
for (dist, active) in dists.get_distributio... | Check installed packages for available updates on PyPI
@param project_name: optional package name to check; checks every
installed pacakge if none specified
@type project_name: string
@returns: None |
368,197 | async def set_volume(self, volume: int, *, device: Optional[SomeDevice] = None):
await self._user.http.set_playback_volume(volume, device_id=str(device)) | Set the volume for the user’s current playback device.
Parameters
----------
volume : int
The volume to set. Must be a value from 0 to 100 inclusive.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
... |
368,198 | def save_feature(self, cat, img, feature, data):
filename = self.path(cat, img, feature)
mkdir(filename)
savemat(filename, {:data}) | Saves a new feature. |
368,199 | def cmd_cammsg(self, args):
print("Sent DIGICAM_CONTROL CMD_LONG")
self.master.mav.command_long_send(
self.settings.target_system,
0,
mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL,
0,
10,
20,
30,
... | cammsg |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.