Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,400 | def set(self, val):
msg = ExtendedSend(
address=self._address,
commandtuple=COMMAND_THERMOSTAT_SET_COOL_SETPOINT_0X6C_NONE,
cmd2=int(val * 2),
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self._set_cool_point_ack) | Set the cool set point. |
345,401 | def emit(self, signal, message, analysis_id):
log.debug(
.format(analysis_id, signal, message))
self.zmq_publish.send(json.dumps({
: analysis_id,
: {: signal, : message},
}, default=json_encoder_default).encode()) | Emit signal to main.
Args:
signal: Name of the signal to be emitted.
message: Message to be sent.
analysis_id: Identifies the instance of this analysis. |
345,402 | def id(self):
m = re.match(r,
self.message)
return m.group(1) | Bug ID number that caused this error |
345,403 | def add_transaction(self, tx, origin=None, force_broadcast=False):
self.consensus_manager.log(
, blk=self.chain.head_candidate, lock=self.proposal_lock)
log.debug(, lock=self.proposal_lock)
block = self.proposal_lock.block
self.proposal_lock.acquire()
self.co... | Warning:
Locking proposal_lock may block incoming events which are necessary to unlock!
I.e. votes / blocks!
Take care! |
345,404 | def validate(self, graph=None):
graph = graph if graph is not None else self.graph
if len(self.ind_nodes(graph)) == 0:
return (False, )
try:
self.topological_sort(graph)
except ValueError:
return (False, )
return (True, ) | Returns (Boolean, message) of whether DAG is valid. |
345,405 | def run_example(example_cls: Example, args=None):
values = parse_args(args)
window_cls = get_window_cls(values.window)
window = window_cls(
title=example_cls.title,
size=example_cls.window_size,
fullscreen=values.fullscreen,
resizable=example_cls.resizable,
... | Run an example entering a blocking main loop
Args:
example_cls: The exmaple class to render
args: Override sys.args |
345,406 | def _rank_1_J_update(self, direction, values):
vals_to_sub = np.dot(direction, self.J)
delta_vals = values - vals_to_sub
for a in range(direction.size):
self.J[a] += direction[a] * delta_vals | Does J += np.outer(direction, new_values - old_values) without
using lots of memory |
345,407 | def parse_args(arguments, wrapper_kwargs={}):
args = {}
positional = [
,
,
]
for key in positional:
args[key] = arguments[ + key + ]
port = arguments[]
args[] = port if port == else int(port)
interval = arguments[]
args[] = int(interva... | MMI Runner |
345,408 | def _run_popen(command, print_output=False):
output =
po = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
fcntl.fcntl(
po.stdout.fileno(),
fcntl.F_SETFL,
fcntl.fcntl(po.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,
... | subprocess has the most terrible interface ever.
Envoy is an option but too heavyweight for this.
This is a convenience wrapper around subprocess.Popen.
Also, this merges STDOUT and STDERR together, since
there isn't a good way of interleaving them without
threads. |
345,409 | def _get_relationship_data(self):
relationship_field = request.path.split()[-1].replace(, )
if relationship_field not in get_relationships(self.schema):
raise RelationNotFound("{} has no attribute {}".format(self.schema.__name__, relationship_field))
related_type_ = self.s... | Get useful data for relationship management |
345,410 | def intermediates(self):
if self._context_handle_pointer is None:
self._raise_closed()
if self._certificate is None:
self._read_certificates()
return self._intermediates | A list of asn1crypto.x509.Certificate objects that were presented as
intermediates by the server |
345,411 | def should_ignore_rule(self, rule):
return rule.id in self.config.ignore or rule.name in self.config.ignore | Determines whether a rule should be ignored based on the general list of commits to ignore |
345,412 | def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
params = values.of({: page_token, : page_number, : page_size, })
response = self._version.page(
,
self._uri,
params=params,
)
return Sync... | Retrieve a single page of SyncListInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to... |
345,413 | def ensure_token(self, auth, name, username=None):
if username is None:
username = self.authenticated_user(auth).username
tokens = [token for token in self.get_tokens(auth, username) if token.name == name]
if len(tokens) > 0:
return tokens[0]
return self.... | Ensures the existence of a token with the specified name for the
specified user. Creates a new token if none exists. If no user is
specified, uses user authenticated by ``auth``.
:param auth.Authentication auth: authentication for user to retrieve.
Must ... |
345,414 | def as_xml(self,parent):
n=parent.newChild(None,"GEO",None)
n.newTextChild(None,"LAT",to_utf8(self.lat))
n.newTextChild(None,"LON",to_utf8(self.lon))
return n | Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode` |
345,415 | def assign_remote_machine(self, machine, console):
if not isinstance(machine, IMachine):
raise TypeError("machine can only be an instance of type IMachine")
if not isinstance(console, IConsole):
raise TypeError("console can only be an instance of type IConsole")
... | Assigns the machine and the (remote) console object associated with
this remote-type session.
in machine of type :class:`IMachine`
in console of type :class:`IConsole`
raises :class:`VBoxErrorInvalidVmState`
Session state prevents operation. |
345,416 | def create_for_wrong_result_type(parser: _BaseParserDeclarationForRegistries, desired_type: Type[T],
obj: PersistedObject, result: T, options: Dict[str, Dict[str, Any]]):
msg = "Error while parsing {obj} as a {typ} with parser {p} using options=({opts}) - parser ret... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parser:
:param desired_type:
:param obj:
:param result:
:param options:
:return: |
345,417 | def iterateEM(self, count):
for iter in range(count):
countef = {}
totalf = {}
for word in self.en_words:
if(word not in self.probs):
continue
word_probs = self.probs[word]
count = d... | Iterate through all transmissions of english to
foreign words. keep count of repeated occurences
do until convergence
set count(e|f) to 0 for all e,f
set total(f) to 0 for all f
for all sentence pairs (e_s,f_s)
set total_s(e) = 0 for all e
for ... |
345,418 | def for_instances(cls, data, multi=None):
if multi is None:
return Capabilities(javabridge.static_call(
"weka/core/Capabilities", "forInstances",
"(Lweka/core/Instances;)Lweka/core/Capabilities;", data.jobject))
else:
return Capabilities(j... | returns a Capabilities object specific for this data. The minimum number of instances is not set, the check
for multi-instance data is optional.
:param data: the data to generate the capabilities for
:type data: Instances
:param multi: whether to check the structure, too
:type m... |
345,419 | def GetClosestPoint(x, a, b):
assert(x.IsUnitLength())
assert(a.IsUnitLength())
assert(b.IsUnitLength())
a_cross_b = a.RobustCrossProd(b)
p = x.Minus(
a_cross_b.Times(
x.DotProd(a_cross_b) / a_cross_b.Norm2()))
if SimpleCCW(a_cross_b, a, p) and SimpleCCW(p, b, a_cross_b):
return p... | Returns the point on the great circle segment ab closest to x. |
345,420 | def board_links_to_ids(self):
resp = self.stats.session.open(
"{0}/members/{1}/boards?{2}".format(
self.stats.url, self.username, urllib.urlencode({
"key": self.key,
"token": self.token,
"fields": "shortLink"})))
... | Convert board links to ids |
345,421 | def overlaps(self, other, permissive=False):
if isinstance(other, AtomicInterval):
for interval in self._intervals:
if interval.overlaps(other, permissive=permissive):
return True
return False
elif isinstance(other, Interval):
... | Test if intervals have any overlapping value.
If 'permissive' is set to True (default is False), then intervals that are contiguous
are considered as overlapping intervals as well (e.g. [1, 2) and [2, 3],
but not [1, 2) and (2, 3] because 2 is not part of their union).
:param other:... |
345,422 | def overwrite(char_list: List[str], regexp: str, quality: str, offset: int = 0) -> List[str]:
long_matcher = re.compile(regexp)
line = "".join(char_list)
long_positions = long_matcher.finditer(line)
for match in long_positions:
(start, end) = match.span()
char_list[start + offset]... | Given a list of characters and spaces, a matching regular expression, and a quality or
character, replace the matching character with a space, overwriting with an offset and
a multiplier if provided.
:param char_list:
:param regexp:
:param quality:
:param offset:
:return:
>>> overwrite... |
345,423 | def urls(self):
from django.conf.urls import url
urls = [
url(r, self.documentation),
url(r, self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r.format(
resource_name), self.handle... | Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls |
345,424 | def _linearInterpolationTransformMatrix(matrix1, matrix2, value):
return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1))) | Linear, 'oldstyle' interpolation of the transform matrix. |
345,425 | def plot_ratio(cid, ax, plotman, title, alpha, vmin, vmax,
xmin, xmax, zmin, zmax, xunit, cbtiks, elecs):
cblabel =
zlabel = + xunit +
xlabel = + xunit +
cm =
xmin, xmax, zmin, zmax, vmin, vmax = check_minmax(
plotman,
cid,
xmin... | Plot ratio of two conductivity directions. |
345,426 | def release(ctx, deploy=False, test=False, version=):
if test:
run("python setup.py check")
run("python setup.py register sdist upload --dry-run")
if deploy:
run("python setup.py check")
if version:
run("git checkout master")
run("git tag -a v{ver} -... | Tag release, run Travis-CI, and deploy to PyPI |
345,427 | def normalize_time(timestamp):
offset = timestamp.utcoffset()
if offset is None:
return timestamp
return timestamp.replace(tzinfo=None) - offset | Normalize time in arbitrary timezone to UTC naive object. |
345,428 | def cli(env):
account = env.client[]
nas_accounts = account.getNasNetworkStorage(
mask=)
table = formatting.Table([, , , ])
for nas_account in nas_accounts:
table.add_row([
nas_account[],
utils.lookup(nas_account,
,
... | List NAS accounts. |
345,429 | def xi_eq(x, kappa, chi_eff, q):
return x**3*(x**2-3*kappa*x+2*chi_eff*kappa*math.sqrt(kappa*x))-3*q*(x**2-2*kappa*x+(chi_eff*kappa)**2) | The roots of this equation determine the orbital radius
at the onset of NS tidal disruption in a nonprecessing
NS-BH binary [(7) in Foucart PRD 86, 124007 (2012)]
Parameters
-----------
x: float
orbital separation in units of the NS radius
kappa: float
the BH mass divided by the... |
345,430 | def get_answers(self):
inst2ans = {}
with io.open(self.test_ans, ) as fin:
for line in fin:
line, _, lemma = line.strip().rpartition()
lemma, pos = lemma[6:].split()
textid, _, line = line.partition()
instid, _, line =... | Returns a {(key,value), ...} dictionary of {(instance_id,Answer),...)}
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> inst2ans = coarse_wsd.get_answers()
>>> for inst in inst2ans:
... print inst, inst2ans[inst
... break |
345,431 | def add_tuning(instrument, description, tuning):
t = StringTuning(instrument, description, tuning)
if _known.has_key(str.upper(instrument)):
_known[str.upper(instrument)][1][str.upper(description)] = t
else:
_known[str.upper(instrument)] = (instrument,
{str.upper(descrip... | Add a new tuning to the index.
The instrument and description parameters should be strings; tuning
should be a list of strings or a list of lists to denote courses.
Example:
>>> std_strings = ['E-2', 'A-2', 'D-3', 'G-3', 'B-3', 'E-4']
>>> tuning.add_tuning('Guitar', 'standard', std_strings)
>>... |
345,432 | async def contains_tracks(self, *tracks: Sequence[Union[str, Track]]) -> List[bool]:
_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]
return await self.user.http.is_saved_track(_tracks) | Check if one or more tracks is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
tracks : Union[Track, str]
A sequence of track objects or spotify IDs |
345,433 | def _retrieve(self, namespace, stream, start_id, end_time, order, limit,
configuration):
start_id_event = Event(start_id)
end_id_event = Event(uuid_from_kronos_time(end_time,
_type=UUIDType.HIGHEST))
stream_events = self.db[namespace][strea... | Yield events from stream starting after the event with id `start_id` until
and including events with timestamp `end_time`. |
345,434 | def releaseLicense(self, username):
url = self._url + "/licenses/releaseLicense"
params = {
"username" : username,
"f" : "json"
}
return self._post(url=url,
param_dict=params,
proxy_url=self._proxy_url,
... | If a user checks out an ArcGIS Pro license for offline or
disconnected use, this operation releases the license for the
specified account. A license can only be used with a single device
running ArcGIS Pro. To check in the license, a valid access token
and refresh token is required. If t... |
345,435 | def prepend(self, key, val, time=0, min_compress_len=0):
s value.
Only stores in memcache if key already exists.
Also see L{append}.
@return: Nonzero on success.
@rtype: int
'
return self._set("prepend", key, val, time, min_compress_len) | Prepend the value to the beginning of the existing key's value.
Only stores in memcache if key already exists.
Also see L{append}.
@return: Nonzero on success.
@rtype: int |
345,436 | def _reindex_output(self, result):
groupings = self.grouper.groupings
if groupings is None:
return result
elif len(groupings) == 1:
return result
elif self.observed:
return result
elif no... | If we have categorical groupers, then we want to make sure that
we have a fully reindex-output to the levels. These may have not
participated in the groupings (e.g. may have all been
nan groups);
This can re-expand the output space |
345,437 | def solve(self, t0, y0, h=1.0, T=None, g=None, tol=None,
integrator=, step=False, relax=False, **kwargs):
r
self._initialize_integrator(t0, y0, integrator, **kwargs)
if (g is not None) and (tol is not None):
soln = self._integrate_variable_trajectory(h, g, tol, step, r... | r"""
Solve the IVP by integrating the ODE given some initial condition.
Parameters
----------
t0 : float
Initial condition for the independent variable.
y0 : array_like (float, shape=(n,))
Initial condition for the dependent variables.
h : float, ... |
345,438 | def wrapinstance(ptr, base=None):
if ptr is None:
return None
ptr = long(ptr)
from wishlib.qt import active, QtCore, QtGui
if active == "PySide":
import shiboken
if base is None:
qObj = shiboken.wrapInstance(ptr, QtCore.QObject)
metaObj = qObj.metaO... | convert a pointer to a Qt class instance (PySide/PyQt compatible) |
345,439 | def delete_snapshot(snapshots_ids=None, config="root"):
***
if not snapshots_ids:
raise CommandExecutionError()
try:
current_snapshots_ids = [x[] for x in list_snapshots(config)]
if not isinstance(snapshots_ids, list):
snapshots_ids = [snapshots_ids]
if not set(sn... | Deletes an snapshot
config
Configuration name. (Default: root)
snapshots_ids
List of the snapshots IDs to be deleted.
CLI example:
.. code-block:: bash
salt '*' snapper.delete_snapshot 54
salt '*' snapper.delete_snapshot config=root 54
salt '*' snapper.delete... |
345,440 | def copy_w_id_suffix(elem, suffix="_copy"):
mycopy = deepcopy(elem)
for id_elem in mycopy.xpath():
id_elem.set(, id_elem.get() + suffix)
return mycopy | Make a deep copy of the provided tree, altering ids. |
345,441 | def get_last_updated(self, node_id=None):
if not node_id:
node_id = self.conn.id
dt = self.conn.client.hget(self.nodelist_key, node_id)
return int(dt) if dt else None | Returns the time a particular node has been last refreshed.
:param string node_id: optional, the connection id of the node to retrieve
:rtype: int
:returns: Returns a unix timestamp if it exists, otherwise None |
345,442 | def set_runtime_value_float(self, ihcid: int, value: float) -> bool:
if self.client.set_runtime_value_float(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_float(ihcid, value) | Set float runtime value with re-authenticate if needed |
345,443 | def dynamic_content_item_variant_delete(self, item_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/dynamic_content
api_path = "/api/v2/dynamic_content/items/{item_id}/variants/{id}.json"
api_path = api_path.format(item_id=item_id, id=id)
return self.call(api_path, me... | https://developer.zendesk.com/rest_api/docs/core/dynamic_content#delete-variant |
345,444 | def get_output_column_widths(table, spans):
widths = []
for column in table[0]:
widths.append(3)
for row in range(len(table)):
for column in range(len(table[row])):
span = get_span(spans, row, column)
column_count = get_span_column_count(span)
if co... | Gets the widths of the columns of the output table
Parameters
----------
table : list of lists of str
The table of rows of text
spans : list of lists of int
The [row, column] pairs of combined cells
Returns
-------
widths : list of int
The widths of each column in t... |
345,445 | def build_vocab(self, *args, **kwargs):
counter = Counter()
sources = []
for arg in args:
if isinstance(arg, Dataset):
sources += [getattr(arg, name) for name, field in
arg.fields.items() if field is self]
else:
... | Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the set of possible values for this field. If
... |
345,446 | def _check_spot_bid(spot_bid, spot_history):
average = mean([datum.price for datum in spot_history])
if spot_bid > average * 2:
logger.warn("Your bid $ %f is more than double this instance type's average "
"spot price ($ %f) over the last week", spot_bid, average) | Prevents users from potentially over-paying for instances
Note: this checks over the whole region, not a particular zone
:param spot_bid: float
:type spot_history: list[SpotPriceHistory]
:raises UserError: if bid is > 2X the spot price's average
>>> from collections import namedtuple
>>> Fa... |
345,447 | def send_keys(self, value, **kwargs):
self.debug_log("Sending keys")
highlight = kwargs.get(
,
BROME_CONFIG[][]
)
if highlight:
self.highlight(
style=BROME_CONFIG[][]
)
clear = kwargs.get(, False)
... | wait_until_clickable = kwargs.get(
'wait_until_clickable',
BROME_CONFIG['proxy_element']['wait_until_clickable']
)
if wait_until_clickable:
# TODO manage the raise exception better
self.pdriver.wait_until_clickable(
self.selector._selector... |
345,448 | def parse_table_name(bigquery_table):
id_name = bigquery_table.split()
if len(id_name) != 2:
raise ValueError(
% bigquery_table)
return id_name[1] | Giving a string a:b.c, returns b.c.
Args:
bigquery_table: full table name project_id:dataset:table
Returns:
dataset:table
Raises:
ValueError: if a, b, or c contain the character ':'. |
345,449 | def address_to_native_contract_class(self, address):
"returns class._on_msg_unsafe, use x.im_self to get class"
assert isinstance(address, bytes) and len(address) == 20
assert self.is_instance_address(address)
nca = self.native_contract_address_prefix + address[-4:]
return self.n... | returns class._on_msg_unsafe, use x.im_self to get class |
345,450 | def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool:
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
if test_overlap:
test =... | Do any of the intervals overlap?
Args:
test_overlap: if ``True``, test for overlapping intervals; if
``False``, test for contiguous intervals. |
345,451 | def rename(self, mapping=None, inplace=False, append=False,
check_duplicates=True, **kwargs):
mapping = mapping or {}
duplicate = set(mapping).intersection(kwargs)
if duplicate:
msg = .format(duplicate)
raise ValueError(msg)
mappin... | Rename and aggregate column entries using `groupby.sum()` on values.
When renaming models or scenarios, the uniqueness of the index must be
maintained, and the function will raise an error otherwise.
Renaming is only applied to any data where a filter matches for all
columns given in `m... |
345,452 | def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]):
if (self.dtype != str):
raise TypeError("Only SArray of string type is supported for counting bag of words")
if (not all([len(delim) == 1 for delim in delimiters])):
raise ValueError... | This returns an SArray with, for each input string, a dict from the unique,
delimited substrings to their number of occurrences within the original
string.
The SArray must be of type string.
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi... |
345,453 | def read(self, size):
data = self.serial_h.read(size)
self.logger.debug( + str(len(data)) + + binascii.b2a_hex(data).decode())
self.serial_h.write(ACK)
if sys.version_info[0] == 2:
data = bytearray(data)
return data | Read raw data from the serial connection. This function is not
meant to be called directly.
:param int size: The number of bytes to read from the serial connection. |
345,454 | def node_to_point_geometry(node):
assert "pointGeometry" in node.tag
for subnode in node.nodes:
if "Point" in subnode.tag:
lon, lat = map(float, subnode.nodes[0].text.split())
point = Point(lon, lat)
elif "upperSeismoDepth" in subnode.tag:
up... | Reads the node and returns the point geometry, upper depth and lower depth |
345,455 | def write_mongo(document, database_name,
collection_name, update=False):
l = []
response_dict = {}
try:
mongodb_client_url = getattr(settings, ,
)
mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
db = mc[str(databa... | Write a document to the collection. Return a response_dict containing
the written record. Method functions as both insert or update based on update
parameter |
345,456 | def get_meshes(path=, cutoff=None):
bodies = collections.deque()
for file_name in os.listdir(path):
try:
mesh = trimesh.load(os.path.join(path, file_name))
split = mesh.split()
bodies.extend(split)
if len(split) > 1:
bodies.... | Get a list of single- body meshes to test identifiers on.
Parameters
------------
path: str, location of models
cutoff: int, number of meshes to stop loading at
Returns
------------
meshes: (n,) list of Trimesh objects |
345,457 | def scaling(self, x, y):
self.drawer.append(pgmagick.DrawableScaling(float(x), float(y))) | Scaling Draw Object
:param x: 0.0 ~ 1.0
:param y: 0.0 ~ 1.0 |
345,458 | def angle( x, y ):
dot = np.dot( x, y )
x_mod = np.linalg.norm( x )
y_mod = np.linalg.norm( y )
cos_angle = dot / ( x_mod * y_mod )
return np.degrees( np.arccos( cos_angle ) ) | Calculate the angle between two vectors, in degrees.
Args:
x (np.array): one vector.
y (np.array): the other vector.
Returns:
(float): the angle between x and y in degrees. |
345,459 | def format(self, template):
return template.format(**dict(zip(self._fields, self))) | Format the message according to the given template.
The template format is the one of the format method :
cf. http://docs.python.org/2/library/string.html#formatstrings |
345,460 | def group_by_witness(self):
if self._matches.empty:
self._matches = pd.DataFrame(
{}, columns=[constants.WORK_FIELDNAME,
constants.SIGLUM_FIELDNAME,
constants.LABEL_FIELDNAME,
... | Groups results by witness, providing a single summary field giving
the n-grams found in it, a count of their number, and the count of
their combined occurrences. |
345,461 | def between(self, time_):
hour = int(time_[0:2])
minute = int(time_[3:5])
return not (
hour < self.h1 or hour > self.h2 or
(hour == self.h1 and minute < self.m1) or
(hour == self.h2 and minute > self.m2)
) | Compare if the parameter HH:MM is in the time range. |
345,462 | def from_dict(d):
query_params_match = d.get()
sources = [Source.from_dict(source) for source in d.get(, [])]
fields = Person.fields_from_dict(d)
return Person(fields=fields, sources=sources,
query_params_match=query_params_match) | Transform the dict to a person object and return the person. |
345,463 | def config_delete(args):
r = fapi.delete_workspace_config(args.project, args.workspace,
args.namespace, args.config)
fapi._check_response_code(r, [200,204])
return r.text if r.text else None | Remove a method config from a workspace |
345,464 | def es_query_template(path):
if not is_text(path):
Log.error("expecting path to be a string")
if path != ".":
f0 = {}
f1 = {}
output = wrap({
"query": es_and([
f0,
{"nested": {
"path": path,
... | RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE
:param path: THE NESTED PATH (NOT INCLUDING TABLE NAME)
:return: (es_query, es_filters) TUPLE |
345,465 | def on_selection_changed(self, sel):
m, self.editing_iter = sel.get_selected()
if self.editing_iter:
self.editing_model = m[self.editing_iter][0]
self.show_curr_model_view(self.editing_model, False)
else: self.view.remove_currency_view()
... | The user changed selection |
345,466 | def prepare_bam(bam_in, precursors):
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(precursors)
c = a.intersect(b, u=True)
out_file = utils.splitext_plus(op.basename(bam_in))[0] + "_clean.bam"
c.saveas(out_file)
return op.abspath(out_file) | Clean BAM file to keep only position inside the bigger cluster |
345,467 | def __cleanup_module(self, event):
pid = event.get_pid()
process = event.get_process()
module = event.get_module()
for tid in process.iter_thread_ids():
thread = process.get_thread(tid)
if tid in self.__runningBP:
... | Auxiliary method for L{_notify_unload_dll}. |
345,468 | def list_terreinobjecten_by_huisnummer(self, huisnummer):
try:
id = huisnummer.id
except AttributeError:
id = huisnummer
def creator():
res = crab_gateway_request(
self.client, , id
)
try:
retur... | List all `terreinobjecten` for a :class:`Huisnummer`
:param huisnummer: The :class:`Huisnummer` for which the \
`terreinobjecten` are wanted.
:rtype: A :class:`list` of :class:`Terreinobject` |
345,469 | def gffselect(args):
from jcvi.formats.bed import intersectBed_wao
p = OptionParser(gffselect.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
gmapped, expected, idsfile, tag = args
data = get_tags(idsfile)
completeness = dict((a.replac... | %prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag
Try to match up the expected location and gmap locations for particular
genes. translated.ids was generated by fasta.translate --ids. tag must be
one of "complete|pseudogene|partial". |
345,470 | def strip_between(self, string, start, end):
regex = start + r + end + r
res = re.sub(regex, , string,
flags=re.DOTALL|re.IGNORECASE|re.MULTILINE)
return res | Deletes everything between regexes start and end from string |
345,471 | def update(self):
old_focus_position = self.todolist.focus
id_length = max_id_length(self.view.todolist.count())
del self.todolist[:]
for group, todos in self.view.groups.items():
if len(self.view.groups) > 1:
grouplabel = ", ".join(group)
... | Updates the todo list according to the todos in the view associated
with this list. |
345,472 | def animation_add(sequence_number, animation_id, name):
return MessageWriter().string("animation.add").uint64(sequence_number).uint32(animation_id).string(name).get() | Create a animation.add message |
345,473 | def prokka_table(self):
headers = OrderedDict()
headers[] = {
: ,
: ,
}
headers[] = {
: ,
: ,
: ,
}
headers[] = {
: ,
: ,
: ,... | Make basic table of the annotation stats |
345,474 | def evaluate_wavefunc(self, kpoint, band, r, spin=0):
r
v = self.Gpoints[kpoint] + self.kpoints[kpoint]
u = np.dot(np.dot(v, self.b), r)
c = self.coeffs[spin][kpoint][band] if self.spin == 2 else \
self.coeffs[kpoint][band]
return np.sum(np.dot(c, np.exp(1j * u, dtype... | r"""
Evaluates the wavefunction for a given position, r.
The wavefunction is given by the k-point and band. It is evaluated
at the given position by summing over the components. Formally,
\psi_n^k (r) = \sum_{i=1}^N c_i^{n,k} \exp (i (k + G_i^{n,k}) \cdot r)
where \psi_n^k is ... |
345,475 | def get_networks(context, limit=None, sorts=[], marker=None,
page_reverse=False, filters=None, fields=None):
LOG.info("get_networks for tenant %s with filters %s, fields %s" %
(context.tenant_id, filters, fields))
filters = filters or {}
nets = db_api.network_find(context,... | Retrieve a list of networks.
The contents of the list depends on the identity of the user
making the request (as indicated by the context) as well as any
filters.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid keys for
a network as listed... |
345,476 | def redraw_label(self):
sx,sy = self.size
x,y = self.pos
self._label.anchor_x = "left"
self._label.x = x+sx/2.+sx
self._label.y = y+sy/2.+sy*.15
self._label._update() | Re-calculates the position of the Label. |
345,477 | def build_graph(self):
self.global_step = tf.Variable(0, trainable=False)
self._build_model()
if self.mode == "train":
self._build_train_op()
else:
self.variables = ray.experimental.tf_utils.TensorFlowVariables(
self.cost)
... | Build a whole graph for the model. |
345,478 | def deferAssignment(self, callable):
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) | Schedule an assignment handler to be called just after deferred
function handlers. |
345,479 | def _execute_insert(self, conn, keys, data_iter):
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(), data) | Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted |
345,480 | def remove(cls, name: sym.Symbol) -> Optional["Namespace"]:
while True:
oldval: lmap.Map = cls._NAMESPACES.deref()
ns: Optional[Namespace] = oldval.entry(name, None)
newval = oldval
if ns is not None:
newval = oldval.dissoc(name)
... | Remove the namespace bound to the symbol `name` in the global
namespace cache and return that namespace.
Return None if the namespace did not exist in the cache. |
345,481 | def scompressed2ibytes(stream):
def more():
try:
while True:
bytes_ = stream.read(4096)
if not bytes_:
return
yield bytes_
except Exception as e:
Log.error("Problem iterating through stream", cause=e)
... | :param stream: SOMETHING WITH read() METHOD TO GET MORE BYTES
:return: GENERATOR OF UNCOMPRESSED BYTES |
345,482 | def endpoint(url, method="GET", expected_status=200):
def dec(obj):
obj.ENDPOINT = url
obj.METHOD = method
obj.EXPECTED_STATUS = expected_status
return obj
return dec | endpoint - decorator to manipulate the REST-service endpoint.
The endpoint decorator sets the endpoint and the method for the class
to access the REST-service. |
345,483 | def _validate_callback(callback):
cb_name = callback.__name__ if hasattr(callback, "__name__") else callback
if not callable(callback):
msg = "The specified callback is not callable.".format(cb_name)
raise client_err.SlackClientError(msg)
callback_params = insp... | Checks if the specified callback is callable and accepts a kwargs param.
Args:
callback (obj): Any object or a list of objects that can be called.
e.g. <function say_hello at 0x101234567>
Raises:
SlackClientError: The specified callback is not callable.
... |
345,484 | def default(self, meth):
if self._default is not NOTHING:
raise DefaultAlreadySetError()
self._default = Factory(meth, takes_self=True)
return meth | Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0 |
345,485 | def remove_nodes(network, rm_nodes):
rm_nodes = set(rm_nodes)
ndf = network.nodes_df
edf = network.edges_df
nodes_to_keep = ~ndf.index.isin(rm_nodes)
edges_to_keep = ~(edf[].isin(rm_nodes) | edf[].isin(rm_nodes))
return ndf.loc[nodes_to_keep], edf.loc[edges_to_keep] | Create DataFrames of nodes and edges that do not include specified nodes.
Parameters
----------
network : pandana.Network
rm_nodes : array_like
A list, array, Index, or Series of node IDs that should *not*
be saved as part of the Network.
Returns
-------
nodes, edges : pand... |
345,486 | def b64decode(foo, *args):
if isinstance(foo, str):
foo = foo.encode()
return base64.b64decode(foo, *args) | Only here for consistency with the above. |
345,487 | def WriteSymlink(self, src_arcname, dst_arcname):
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to write to a ZIP archive that was already closed.")
src_arcname = SmartStr(src_arcname)
dst_arcname = SmartStr(dst_arcname)
zinfo = zipfile.ZipInfo(dst_a... | Writes a symlink into the archive. |
345,488 | def loadDeviceDefinitions(self, urlOfXMLDefinition, timeout=3):
proxies = {}
if self.__httpsProxy:
proxies = {"https": self.__httpsProxy}
if self.__httpProxy:
proxies = {"http": self.__httpProxy}
headers = {"User-Agent": "Mozilla/5.0;... | Loads the device definitions from a given URL which points to the root XML in the device.
This loads the device definitions which is needed in case you like to:
* get additional information's about the device like manufacture, device type, etc
* get all support service types of this device
... |
345,489 | def get_returns_cached(filepath, update_func, latest_dt, **kwargs):
update_cache = False
try:
mtime = getmtime(filepath)
except OSError as e:
if e.errno != errno.ENOENT:
raise
update_cache = True
else:
file_dt = pd.Timestamp(mtime, unit=)
if l... | Get returns from a cached file if the cache is recent enough,
otherwise, try to retrieve via a provided update function and
update the cache file.
Parameters
----------
filepath : str
Path to cached csv file
update_func : function
Function to call in case cache is not up-to-date.... |
345,490 | def p_retry(p):
if len(p) == 5:
p[0] = Retry(p[3])
elif len(p) == 8:
p[0] = Retry(p[6], **p[3])
else:
raise RuntimeError("Invalid product rules for ") | retry : RETRY OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET
| RETRY OPEN_BRACKET retry_option_list CLOSE_BRACKET OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET |
345,491 | def validate(self, value, redis):
if type(value) == str:
value = value.strip()
value = self.value_or_default(value)
self.validate_required(value)
if self.regex and not re.match(self.regex, value, flags=re.ASCII):
raise InvalidFieldErr... | Validates data obtained from a request and returns it in the apropiate
format |
345,492 | def get_logs(self):
folder = os.path.dirname(self.pcfg[])
for path, dir, files in os.walk(folder):
for file in files:
if os.path.splitext(file)[-1] == :
yield os.path.join(path, file) | returns logs from disk, requires .log extenstion |
345,493 | def getDesc(self, entry):
if len(self._descDict) == 0:
self.getStats()
return self._descDict.get(entry) | Returns description for stat entry.
@param entry: Entry name.
@return: Description for entry. |
345,494 | def set_status(self, on, switch=1):
if isinstance(switch, int):
switch = str(switch)
payload = self.generate_payload(SET, {switch:on})
data = self._send_receive(payload)
log.debug(, data)
return data | Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set |
345,495 | def get_starred_repos(self):
starred_url = self.api_url + "/starred"
keep_finding = True
current_page = 1
repos_list = []
while keep_finding:
api_url = starred_url + "?page=" + str(
current_page)
api_driver = GithubRawApi(
... | Gets repos starred by user
:return: List of starred repositories |
345,496 | def _main_loop(self):
self.logger.debug("Running main loop")
old_time = 0
while True:
for plugin_key in self.plugins_dict:
obj = self.plugins_dict[plugin_key]
self._process_plugin(obj)
if self.settings[] != 0:
new_... | The internal while true main loop for the redis monitor |
345,497 | def nvme_nqn():
grains = {}
grains[] = False
if salt.utils.platform.is_linux():
grains[] = _linux_nqn()
return grains | Return NVMe NQN |
345,498 | def _paired_load_script(work_bams, names, chrom, pairmode, items):
paired = vcfutils.get_paired_bams(work_bams, items)
bed_file = _get_regional_bed_file(items[0])
if bed_file:
return _paired_prep_targeted.format(case_file=paired.tumor_bam, case_name=paired.tumor_name,
... | Prepare BAMs for assessing CNVs in a paired tumor/normal setup. |
345,499 | def IndexedDB_requestDatabaseNames(self, securityOrigin):
assert isinstance(securityOrigin, (str,)
), "Argument must be of type str. Received type: " % type(
securityOrigin)
subdom_funcs = self.synchronous_command(,
securityOrigin=securityOrigin)
return subdom_funcs | Function path: IndexedDB.requestDatabaseNames
Domain: IndexedDB
Method name: requestDatabaseNames
Parameters:
Required arguments:
'securityOrigin' (type: string) -> Security origin.
Returns:
'databaseNames' (type: array) -> Database names for origin.
Description: Requests database name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.