Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
5,800 | def __parse_names():
filename = get_file()
with io.open(filename, , encoding=) as textfile:
next(textfile)
for line in textfile:
tokens = line.strip().split()
chebi_id = int(tokens[1])
if chebi_id not in __ALL_NAMES:
__ALL_NAMES[chebi_i... | Gets and parses file |
5,801 | def _get_libvirt_enum_string(prefix, value):
attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)]
prefixes = [_compute_subprefix(p) for p in attributes]
counts = {p: prefixes.count(p) for p in prefixes}
sub_prefixes = [p for p, count in counts.items() if c... | Convert the libvirt enum integer value into a human readable string.
:param prefix: start of the libvirt attribute to look for.
:param value: integer to convert to string |
5,802 | def delay(self, secs):
secs = int(secs)
for i in reversed(range(secs)):
sys.stdout.write()
sys.stdout.write("sleep %ds, left %2ds" % (secs, i+1))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\n")
return self | Delay some seconds
Args:
secs: float seconds
Returns:
self |
5,803 | def _create_validate_config(vrn_file, rm_file, rm_interval_file, base_dir, data):
ref_call = {"file": str(rm_file), "name": "ref", "type": "grading-ref",
"fix-sample-header": True, "remove-refcalls": True}
a_intervals = get_analysis_intervals(data, vrn_file, base_dir)
if a_intervals:
... | Create a bcbio.variation configuration input for validation. |
5,804 | def sendmail(self, msg_from, msg_to, msg):
SMTP_dummy.msg_from = msg_from
SMTP_dummy.msg_to = msg_to
SMTP_dummy.msg = msg | Remember the recipients. |
5,805 | def cmd_partition(opts):
config = load_config(opts.config)
b = get_blockade(config, opts)
if opts.random:
if opts.partitions:
raise BlockadeError("Either specify individual partitions "
"or --random, but not both")
b.random_partition()
e... | Partition the network between containers
Replaces any existing partitions outright. Any containers NOT specified
in arguments will be globbed into a single implicit partition. For
example if you have three containers: c1, c2, and c3 and you run:
blockade partition c1
The result will be a part... |
5,806 | def new_cells(self, name=None, formula=None):
return self._impl.new_cells(name, formula).interface | Create a cells in the space.
Args:
name: If omitted, the model is named automatically ``CellsN``,
where ``N`` is an available number.
func: The function to define the formula of the cells.
Returns:
The new cells. |
5,807 | def _compute_ll_matrix(self, idx, param_vals, num_pts):
if idx >= len(num_pts):
return -1.0 * self.update_hyperparameters(
scipy.asarray(param_vals, dtype=float)
)
else:
vals = scipy.zeros(num_pts[idx:], dtype=float)
... | Recursive helper function for compute_ll_matrix.
Parameters
----------
idx : int
The index of the parameter for this layer of the recursion to
work on. `idx` == len(`num_pts`) is the base case that terminates
the recursion.
param_vals : List o... |
5,808 | def build(self, X, Y, w=None, edges=None):
super(MorseComplex, self).build(X, Y, w, edges)
if self.debug:
sys.stdout.write("Decomposition: ")
start = time.clock()
morse_complex = MorseComplexFloat(
vectorFloat(self.Xnorm.flatten()),
vect... | Assigns data to this object and builds the Morse-Smale
Complex
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w... |
5,809 | def create_release_id(short, version, type, bp_short=None, bp_version=None, bp_type=None):
if not is_valid_release_short(short):
raise ValueError("Release short name is not valid: %s" % short)
if not is_valid_release_version(version):
raise ValueError("Release short version is not valid: %s... | Create release_id from given parts.
:param short: Release short name
:type short: str
:param version: Release version
:type version: str
:param version: Release type
:type version: str
:param bp_short: Base Product short name
:type bp_short: str
:param bp_version: Base Product versi... |
5,810 | def graph_from_seeds(seeds, cell_source):
if hasattr(cell_source, ):
cellmap = cell_source.cellmap
cells = cellmap
G = cell_source.G
for c in seeds:
G.add_node(c)
cellmap[c.address()] = c
else:
cellmap = dict([(x.address(),x) for ... | This creates/updates a networkx graph from a list of cells.
The graph is created when the cell_source is an instance of ExcelCompiler
The graph is updated when the cell_source is an instance of Spreadsheet |
5,811 | def economic_svd(G, epsilon=sqrt(finfo(float).eps)):
r
from scipy.linalg import svd
G = asarray(G, float)
(U, S, V) = svd(G, full_matrices=False, check_finite=False)
ok = S >= epsilon
S = S[ok]
U = U[:, ok]
V = V[ok, :]
return (U, S, V) | r"""Economic Singular Value Decomposition.
Args:
G (array_like): Matrix to be factorized.
epsilon (float): Threshold on the square root of the eigen values.
Default is ``sqrt(finfo(float).eps)``.
Returns:
:class:`numpy.ndarray`: Unitary matrix.
:class:`... |
5,812 | def invoke(self, headers, body):
xml = Service._create_request(headers, body)
try:
response = self.session.post(self.endpoint, verify=False, data=xml)
logging.debug(response.content)
except Exception as e:
traceback.print_exc()
raise WSMa... | Invokes the soap service |
5,813 | def autohook(ui, repo, hooktype, **kwargs):
cmd = hooktype.replace("-", "_")
if not repo or not cmd.replace("_", "").isalpha():
return False
result = False
trusted = ui.configlist("autohooks", "trusted")
if "" not in trusted:
default_path = ui.config("paths", "default")
... | Look for hooks inside the repository to run. |
5,814 | def qscan(self, cursor=0, count=None, busyloop=None, minlen=None,
maxlen=None, importrate=None):
command = ["QSCAN", cursor]
if count:
command += ["COUNT", count]
if busyloop:
command += ["BUSYLOOP"]
if minlen:
command += ["MINLE... | Iterate all the existing queues in the local node.
:param count: An hint about how much work to do per iteration.
:param busyloop: Block and return all the elements in a busy loop.
:param minlen: Don't return elements with less than count jobs queued.
:param maxlen: Don't return element... |
5,815 | def filter(self, filter_func, reverse=False):
new_log_file = Log()
new_log_file.logfile = self.logfile
new_log_file.total_lines = 0
new_log_file._valid_lines = []
new_log_file._invalid_lines = self._invalid_lines[:]
if not reverse:
... | Filter current log lines by a given filter function.
This allows to drill down data out of the log file by filtering the
relevant log lines to analyze.
For example, filter by a given IP so only log lines for that IP are
further processed with commands (top paths, http status counter...... |
5,816 | def _store_outputs_in_object_store(self, object_ids, outputs):
for i in range(len(object_ids)):
if isinstance(outputs[i], ray.actor.ActorHandle):
raise Exception("Returning an actor handle from a remote "
"function is not allowed).")
... | Store the outputs of a remote function in the local object store.
This stores the values that were returned by a remote function in the
local object store. If any of the return values are object IDs, then
these object IDs are aliased with the object IDs that the scheduler
assigned for t... |
5,817 | def _fix_attribute_names(attrs, change_map):
new_attr = {}
for k in attrs.keys():
if k in change_map:
new_attr[change_map[k]] = attrs[k]
else:
new_attr[k] = attrs[k]
return new_attr | Change attribute names as per values in change_map dictionary.
Parameters
----------
:param attrs : dict Dict of operator attributes
:param change_map : dict Dict of onnx attribute name to mxnet attribute names.
Returns
-------
:return new_attr : dict Converted dict of operator attributes. |
5,818 | def walkWords(self, showPadding: bool=False):
wIndex = 0
lastEnd = self.startBitAddr
parts = []
for p in self.parts:
end = p.startOfPart
if showPadding and end != lastEnd:
while end != lastEnd:
assert e... | Walk enumerated words in this frame
:attention: not all indexes has to be present, only words
with items will be generated when not showPadding
:param showPadding: padding TransParts are also present
:return: generator of tuples (wordIndex, list of TransParts
in this wor... |
5,819 | def get_base_path() -> Path:
env_data_path = os.environ.get("EFB_DATA_PATH", None)
if env_data_path:
base_path = Path(env_data_path).resolve()
else:
base_path = Path.home() / ".ehforwarderbot"
if not base_path.exists():
base_path.mkdir(parents=True)
return base_path | Get the base data path for EFB. This can be defined by the
environment variable ``EFB_DATA_PATH``.
If ``EFB_DATA_PATH`` is not defined, this gives
``~/.ehforwarderbot``.
This method creates the queried path if not existing.
Returns:
The base path. |
5,820 | def commit_confirmed(name):
20180726083540640360
confirmed = {
: name,
: None,
: {},
:
}
if __opts__[]:
confirmed[] = .format(name)
return confirmed
ret = __salt__[](name)
confirmed.update(ret)
return confirmed | .. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID... |
5,821 | def describe_ring(self, keyspace):
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_ring(keyspace)
return d | get the token ring: a map of ranges to host addresses,
represented as a set of TokenRange instead of a map from range
to list of endpoints, because you can't use Thrift structs as
map keys:
https://issues.apache.org/jira/browse/THRIFT-162
for the same reason, we can't return a set here, even though... |
5,822 | def trainTopicOnTweets(self, twitterQuery, useTweetText=True, useIdfNormalization=True,
normalization="linear", maxTweets=2000, maxUsedLinks=500, ignoreConceptTypes=[],
maxConcepts = 20, maxCategories = 10, notifyEmailAddress = None):
assert maxTweets < 5000, "we can analyze at ... | create a new topic and train it using the tweets that match the twitterQuery
@param twitterQuery: string containing the content to search for. It can be a Twitter user account (using "@" prefix or user's Twitter url),
a hash tag (using "#" prefix) or a regular keyword.
@param useTweetTex... |
5,823 | def get_slab_stats(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.send("stats slabs\n")
try:
data = ""
while True:
data += s.recv(4096)
if data.endswith():
... | Retrieve slab stats from memcached. |
5,824 | def makeB(self, buses=None, branches=None, method="XB"):
buses = self.connected_buses if buses is None else buses
branches = self.online_branches if branches is None else branches
B_buses = copy.deepcopy(buses)
Bp_branches = copy.deepcopy(branches)
Bpp_branches = copy... | Based on makeB.m from MATPOWER by Ray Zimmerman, developed at
PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more
information.
@param method: Specify "XB" or "BX" method.
@type method: string
@rtype: tuple
@return: Two matrices, B prime and B double pr... |
5,825 | def user(context, mail):
LOG.info("Running scout delete user")
adapter = context.obj[]
user_obj = adapter.user(mail)
if not user_obj:
LOG.warning("User {0} could not be found in database".format(mail))
else:
adapter.delete_user(mail) | Delete a user from the database |
5,826 | def newTextChild(self, ns, name, content):
if ns is None: ns__o = None
else: ns__o = ns._o
ret = libxml2mod.xmlNewTextChild(self._o, ns__o, name, content)
if ret is None:raise treeError()
__tmp = xmlNode(_obj=ret)
return __tmp | Creation of a new child element, added at the end of
@parent children list. @ns and @content parameters are
optional (None). If @ns is None, the newly created element
inherits the namespace of @parent. If @content is non None,
a child TEXT node will be created containing the stri... |
5,827 | def color_grid(data, palette, denom=9.0, mask_zeros=True):
grid = []
try:
float(data[0][0])
palette = matplotlib.colors.LinearSegmentedColormap.from_list(
"color_grid", palette)
palette.set_bad(alpha=0)
except:
pass
for row in ran... | Convert the given data (2d array of numbers or binary strings) to a 2d
array of RGB or RGBA values which can then be visualized as a heat map.
Arguments:
data - 2d array of numbers or binary strings
palette - a seaborn palette (list of RGB values) indicating how to convert
data to colors.... |
5,828 | def _filter_namespaces_by_route_whitelist(self):
assert self._routes is not None, "Missing route whitelist"
assert in self._routes
assert in self._routes
route_whitelist = {}
for namespace_name, route_reprs in self._routes[].items():
new_route_rep... | Given a parsed API in IR form, filter the user-defined datatypes
so that they include only the route datatypes and their direct dependencies. |
5,829 | def onchange(self, new_value):
self.disable_refresh()
self.set_value(new_value)
self.enable_refresh()
return (new_value, ) | Called when the user changes the TextInput content.
With single_line=True it fires in case of focus lost and Enter key pressed.
With single_line=False it fires at each key released.
Args:
new_value (str): the new string content of the TextInput. |
5,830 | def _RemoveForemanRule(self):
if data_store.RelationalDBEnabled():
data_store.REL_DB.RemoveForemanRule(hunt_id=self.session_id.Basename())
return
with aff4.FACTORY.Open(
"aff4:/foreman", mode="rw", token=self.token) as foreman:
aff4_rules = foreman.Get(foreman.Schema.RULES)
... | Removes the foreman rule corresponding to this hunt. |
5,831 | def get_editor_nodes(self, editor, node=None):
return [editor_node for editor_node in self.list_editor_nodes(node) if editor_node.editor == editor] | Returns the :class:`umbra.components.factory.script_editor.nodes.EditorNode` class Nodes with given editor.
:param node: Node to start walking from.
:type node: AbstractNode or AbstractCompositeNode or Object
:param editor: Editor.
:type editor: Editor
:return: EditorNode nodes.... |
5,832 | def send_sms(message, from_number, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None):
connection = connection or get_sms_connection(username=auth_user, password=auth_password, fail_silently=fail_silently)
mail = SMSMessage(message, from_number, recipient_list, connection=conn... | Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. N... |
5,833 | def require_Gtk(min_version=2):
if not _in_X:
raise RuntimeError()
if _has_Gtk < min_version:
raise RuntimeError()
if _has_Gtk == 2:
logging.getLogger(__name__).warn(
_("Missing runtime dependency GTK 3. Falling back to GTK 2 "
"for password prompt"))
... | Make sure Gtk is properly initialized.
:raises RuntimeError: if Gtk can not be properly initialized |
5,834 | def walk(self, where="/"):
_tables()
self._check_if_open()
for g in self._handle.walk_groups(where):
if getattr(g._v_attrs, , None) is not None:
continue
groups = []
leaves = []
for child in g._v_children.values():
... | Walk the pytables group hierarchy for pandas objects
This generator will yield the group path, subgroups and pandas object
names for each group.
Any non-pandas PyTables objects that are not a group will be ignored.
The `where` group itself is listed first (preorder), then each of its
... |
5,835 | def rename_table(dbconn, original, new):
cur = dbconn.cursor()
cur.execute("ALTER TABLE RENAME TO ".format(original=original, new=new)) | Rename a table in the database
:param dbconn: database connection
:param original: original table name
:param new: new table name |
5,836 | def _get_reference(self):
super()._get_reference()
self.cubeA_body_id = self.sim.model.body_name2id("cubeA")
self.cubeB_body_id = self.sim.model.body_name2id("cubeB")
self.l_finger_geom_ids = [
self.sim.model.geom_name2id(x) for x in self.gripper.left_finger_geoms
... | Sets up references to important components. A reference is typically an
index or a list of indices that point to the corresponding elements
in a flatten array, which is how MuJoCo stores physical simulation data. |
5,837 | def _post(self, url, data=None):
url = urljoin(self.base_url, url)
try:
r = self._make_request(**dict(
method=,
url=url,
json=data,
auth=self.auth,
timeout=self.timeout,
hooks=self.reques... | Handle authenticated POST requests
:param url: The url for the endpoint including path parameters
:type url: :py:class:`str`
:param data: The request body parameters
:type data: :py:data:`none` or :py:class:`dict`
:returns: The JSON output from the API or an error message |
5,838 | def get_last_day_of_month(t: datetime) -> int:
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.month, day=1)
tt = tn - timedelta(hours=1)
return tt.day | Returns day number of the last day of the month
:param t: datetime
:return: int |
5,839 | def forward(self, input_tensor):
ones = input_tensor.data.new_ones(input_tensor.shape[0], input_tensor.shape[-1])
dropout_mask = torch.nn.functional.dropout(ones, self.p, self.training, inplace=False)
if self.inplace:
input_tensor *= dropout_mask.unsqueeze(1)
... | Apply dropout to input tensor.
Parameters
----------
input_tensor: ``torch.FloatTensor``
A tensor of shape ``(batch_size, num_timesteps, embedding_dim)``
Returns
-------
output: ``torch.FloatTensor``
A tensor of shape ``(batch_size, num_timesteps... |
5,840 | def path_shift(self, count=1):
if count == 0: return
pathlist = self.path.strip().split()
scriptlist = self.environ.get(,).strip().split()
if pathlist and pathlist[0] == : pathlist = []
if scriptlist and scriptlist[0] == : scriptlist = []
if count > 0 a... | Shift some levels of PATH_INFO into SCRIPT_NAME and return the
moved part. count defaults to 1 |
5,841 | def show(ctx):
for app_name, app in ctx.obj[][].items():
click.echo(click.style(app_name, fg=, bold=True))
for migration in app[]:
applied = ctx.obj[].is_migration_applied(app_name, migration)
click.echo(.format(migration, click.style(, bold=True) if applied else )) | Show migrations list |
5,842 | def average(self, projection=None):
length = self.size()
if projection:
return sum(self.map(projection)) / length
else:
return sum(self) / length | Takes the average of elements in the sequence
>>> seq([1, 2]).average()
1.5
>>> seq([('a', 1), ('b', 2)]).average(lambda x: x[1])
:param projection: function to project on the sequence before taking the average
:return: average of elements in the sequence |
5,843 | def capture_ratio(self, benchmark, threshold=0.0, compare_op=("ge", "lt")):
if isinstance(compare_op(tuple, list)):
op1, op2 = compare_op
else:
op1, op2 = compare_op, compare_op
uc = self.up_capture(
benchmark=benchmark, threshold=threshold, compare_... | Capture ratio--ratio of upside to downside capture.
Upside capture ratio divided by the downside capture ratio.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
threshold : float, default 0.
... |
5,844 | def _extract_info_from_package(dependency,
extract_type=None,
debug=False,
include_build_requirements=False
):
output_folder = tempfile.mkdtemp(prefix="pythonpackage-metafolder-")
try... | Internal function to extract metainfo from a package.
Currently supported info types:
- name
- dependencies (a list of dependencies) |
5,845 | def peek(self):
if self.reading is None:
raise StreamEmptyError("peek called on virtual stream walker without any data", selector=self.selector)
return self.reading | Peek at the oldest reading in this virtual stream. |
5,846 | def create_db_entry(self, tfi):
if tfi.task.department.assetflag:
comment = self.asset_comment_pte.toPlainText()
else:
comment = self.shot_comment_pte.toPlainText()
return tfi.create_db_entry(comment) | Create a db entry for the given task file info
:param tfi: the info for a TaskFile entry in the db
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: the created taskfile and note
:rtype: tuple
:raises: ValidationError |
5,847 | def parseAndSave(option, urlOrPaths, outDir=None, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar,
responseMimeType=, metaExtension=,
services={: , : , : }):
_meta.json
metaPaths = []
paths = getPaths(urlOrPaths)
for path in paths:
if... | Parse the objects and write extracted metadata and/or text in JSON format to matching
filename with an extension of '_meta.json'.
:param option:
:param urlOrPaths:
:param outDir:
:param serverEndpoint:
:param verbose:
:param tikaServerJar:
:param responseMimeType:
:param metaExtensio... |
5,848 | def response_hook(self, response, **kwargs) -> HTMLResponse:
if not response.encoding:
response.encoding = DEFAULT_ENCODING
return HTMLResponse._from_response(response, self) | Change response enconding and replace it by a HTMLResponse. |
5,849 | def graceful_stop(self, signal_number=None, stack_frame=None):
stop_msg = "Hard" if self.shutdown else "Graceful"
if signal_number is None:
self.log.info("%s stop called manually. "
"Shutting down.", stop_msg)
else:
self.log.info("%s sto... | This function will be called when a graceful-stop is initiated. |
5,850 | def _decode_attributes(self):
try:
from_jid = self._element.get()
if from_jid:
self._from_jid = JID(from_jid)
to_jid = self._element.get()
if to_jid:
self._to_jid = JID(to_jid)
except ValueError:
raise J... | Decode attributes of the stanza XML element
and put them into the stanza properties. |
5,851 | def get_language_from_json(language, key):
file_name = os.path.join(
os.path.dirname(__file__),
,
).format(key.lower())
if os.path.exists(file_name):
try:
with open(file_name, , encoding=) as fh:
languages = json.loads(fh.read())
... | Finds the given language in a json file. |
5,852 | def submit_import(cls, volume, location, project=None, name=None,
overwrite=False, properties=None, parent=None,
preserve_folder_structure=True, api=None):
data = {}
volume = Transform.to_volume(volume)
if project and parent:
rais... | Submits new import job.
:param volume: Volume identifier.
:param location: Volume location.
:param project: Project identifier.
:param name: Optional file name.
:param overwrite: If true it will overwrite file if exists.
:param properties: Properties dictionary.
:... |
5,853 | def _control_transfer(self, data):
LOGGER.debug(, data)
self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09,
wValue=0x0200, wIndex=0x01, data_or_wLength=data, timeout=TIMEOUT) | Send device a control request with standard parameters and <data> as
payload. |
5,854 | def process(self, request_adu):
validate_crc(request_adu)
return super(RTUServer, self).process(request_adu) | Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request. |
5,855 | def __onclick(self, event):
if event.inaxes == self.ax1:
self.x_coord = event.xdata
self.y_coord = event.ydata
self.__reset_crosshair()
x, y = self.__map2img(self.x_coord, self.y_co... | respond to mouse clicks in the plot.
This function responds to clicks on the first (horizontal slice) plot and updates the vertical profile and
slice plots
Parameters
----------
event: matplotlib.backend_bases.MouseEvent
the click event object containing image coordi... |
5,856 | def create_portable_topology(topol, struct, **kwargs):
_topoldir, _topol = os.path.split(topol)
processed = kwargs.pop(, os.path.join(_topoldir, +_topol))
grompp_kwargs, mdp_kwargs = filter_grompp_options(**kwargs)
mdp_kwargs = add_mdp_includes(topol, mdp_kwargs)
with tempfile.NamedTemporaryFil... | Create a processed topology.
The processed (or portable) topology file does not contain any
``#include`` statements and hence can be easily copied around. It
also makes it possible to re-grompp without having any special itp
files available.
:Arguments:
*topol*
topology file
... |
5,857 | def _validate_timeout(seconds: float):
val = int(seconds * 1000)
assert 60000 <= val <= 4294967294, "Bad value: {}".format(val)
return val | Creates an int from 60000 to 4294967294 that represents a
valid millisecond wireless LAN timeout |
5,858 | def isa_to_graph(isa: ISA) -> nx.Graph:
return nx.from_edgelist(e.targets for e in isa.edges if not e.dead) | Construct a NetworkX qubit topology from an ISA object.
This discards information about supported gates.
:param isa: The ISA. |
5,859 | def _markup(p_todo, p_focus):
pri = p_todo.priority()
pri = + pri if pri else PaletteItem.DEFAULT
if not p_focus:
attr_dict = {None: pri}
else:
attr_dict = {None: pri + }
attr_dict[PaletteItem.PROJECT] = PaletteItem.PROJECT_FOCUS
attr_dict[PaletteItem.CONT... | Returns an attribute spec for the colors that correspond to the given todo
item. |
5,860 | def build_request(self, path, query_parameters):
url = + self.sanitise_path(path)
url += + urlencode(query_parameters)
return url | Build the HTTP request by adding query parameters to the path.
:param path: API endpoint/path to be used.
:param query_parameters: Query parameters to be added to the request.
:return: string |
5,861 | def refine_rectwv_coeff(input_image, rectwv_coeff,
refine_wavecalib_mode,
minimum_slitlet_width_mm,
maximum_slitlet_width_mm,
save_intermediate_results=False,
debugplot=0):
logger = logging.... | Refine RectWaveCoeff object using a catalogue of lines
One and only one among refine_with_oh_lines_mode and
refine_with_arc_lines must be different from zero.
Parameters
----------
input_image : HDUList object
Input 2D image.
rectwv_coeff : RectWaveCoeff instance
Rectification ... |
5,862 | def _register_socket(s):
queue_to_app = Queue()
with _lock:
ApplicationLayer._to_app[s._sockid()] = queue_to_app
return ApplicationLayer._from_app, queue_to_app | Internal method used by socket emulation layer to create a new "upward"
queue for an app-layer socket and to register the socket object.
Returns two queues: "downward" (fromapp) and "upward" (toapp). |
5,863 | def add_bgp_speaker_to_dragent(self, bgp_dragent, body):
return self.post((self.agent_path + self.BGP_DRINSTANCES)
% bgp_dragent, body=body) | Adds a BGP speaker to Dynamic Routing agent. |
5,864 | def _handle_blacklisted_tag(self):
strip = lambda text: text.rstrip().lower()
while True:
this, next = self._read(), self._read(1)
if this is self.END:
self._fail_route()
elif this == "<" and next == "/":
self._head += 3
... | Handle the body of an HTML tag that is parser-blacklisted. |
5,865 | def open_file(link, session=None, stream=True):
if not isinstance(link, six.string_types):
try:
link = link.url_without_fragment
except AttributeError:
raise ValueError("Cannot parse url from unkown type: {0!r}".format(link))
if not is_valid_url(link) and os.path.ex... | Open local or remote file for reading.
:type link: pip._internal.index.Link or str
:type session: requests.Session
:param bool stream: Try to stream if remote, default True
:raises ValueError: If link points to a local directory.
:return: a context manager to the opened file-like object |
5,866 | def iter_sections(self, order=Tree.ipreorder, neurite_order=NeuriteIter.FileOrder):
return iter_sections(self, iterator_type=order, neurite_order=neurite_order) | iteration over section nodes
Parameters:
order: section iteration order within a given neurite. Must be one of:
Tree.ipreorder: Depth-first pre-order iteration of tree nodes
Tree.ipreorder: Depth-first post-order iteration of tree nodes
Tree.iupstream: Iterate from a tre... |
5,867 | def if_else(self, pred, likely=None):
bb = self.basic_block
bbif = self.append_basic_block(name=_label_suffix(bb.name, ))
bbelse = self.append_basic_block(name=_label_suffix(bb.name, ))
bbend = self.append_basic_block(name=_label_suffix(bb.name, ))
br = self.cbranch(pred... | A context manager which sets up two conditional basic blocks based
on the given predicate (a i1 value).
A tuple of context managers is yield'ed. Each context manager
acts as a if_then() block.
*likely* has the same meaning as in if_then().
Typical use::
with builder... |
5,868 | def sha256(content):
if isinstance(content, str):
content = content.encode()
return hashlib.sha256(content).hexdigest() | Finds the sha256 hash of the content. |
5,869 | def internal_only(view_func):
@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):
forwards = request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")
if len(forwards) > 1:
raise PermissionDenied()
return view_func(request, *args,... | A view decorator which blocks access for requests coming through the load balancer. |
5,870 | def time_relaxations_direct(P, p0, obs, times=[1]):
r
n_t = len(times)
times = np.sort(times)
if times[-1] > P.shape[0]:
use_diagonalization = True
R, D, L = rdl_decomposition(P)
if not np.any(np.iscomplex(R)):
R = np.real(R)
if not np.any(np.is... | r"""Compute time-relaxations of obs with respect of given initial distribution.
relaxation(k) = p0 P^k obs
Parameters
----------
P : ndarray, shape=(n, n) or scipy.sparse matrix
Transition matrix
p0 : ndarray, shape=(n)
initial distribution
obs : ndarray, shape=(n)
Vect... |
5,871 | def _get_timit(directory):
if os.path.exists(os.path.join(directory, "timit")):
return
assert FLAGS.timit_paths
for path in FLAGS.timit_paths.split(","):
with tf.gfile.GFile(path) as f:
with tarfile.open(fileobj=f, mode="r:gz") as timit_compressed:
timit_compressed.extractall(directory) | Extract TIMIT datasets to directory unless directory/timit exists. |
5,872 | def run_command(self, args):
parsed_args = self.parser.parse_args(args)
if hasattr(parsed_args, ):
parsed_args.func(parsed_args)
else:
self.parser.print_help() | Parse command line arguments and run function registered for the appropriate command.
:param args: [str] command line arguments |
5,873 | def get_list_database(self):
url = "db"
response = self.request(
url=url,
method=,
expected_response_code=200
)
return response.json() | Get the list of databases. |
5,874 | def _descendants(self):
children = self._children
if children is not None:
for child in children.values():
yield from child._descendants
yield child | Scans full list of node descendants.
:return: Generator of nodes. |
5,875 | def update(self):
self.t += 1000 / INTERVAL
self.average *= np.random.lognormal(0, 0.04)
high = self.average * np.exp(np.abs(np.random.gamma(1, 0.03)))
low = self.average / np.exp(np.abs(np.random.gamma(1, 0.03)))
delta = high - low
open = low + delta *... | Compute the next element in the stream, and update the plot data |
5,876 | def UpdateUser(self, user, ssh_keys):
if not bool(USER_REGEX.match(user)):
self.logger.warning(, user)
return False
if not self._GetUser(user):
if not (self._AddUser(user)
and self._UpdateUserGroups(user, self.groups)):
return False
if not self... | Update a Linux user with authorized SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Returns:
bool, True if the user account updated successfully. |
5,877 | def remove_point(self, time):
if self.tier_type != :
raise Exception()
self.intervals = [i for i in self.intervals if i[0] != time] | Remove a point, if no point is found nothing happens.
:param int time: Time of the point.
:raises TierTypeException: If the tier is not a TextTier. |
5,878 | def shutdown(self, reason = ConnectionClosed()):
if self._shutdown:
raise ShutdownError()
self.stop()
self._closing = True
for connection in self.connections:
connection.close()
self.connections = set()
self._shutdown = Tr... | Shutdown the socket server.
The socket server will stop accepting incoming connections.
All connections will be dropped. |
5,879 | def connect(args):
p = OptionParser(connect.__doc__)
p.add_option("--clip", default=2000, type="int",
help="Only consider end of contigs [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, blastfile = args
cl... | %prog connect assembly.fasta read_mapping.blast
Connect contigs using long reads. |
5,880 | def competition_view_leaderboard(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.competition_view_leaderboard_with_http_info(id, **kwargs)
else:
(data) = self.competition_view_leaderboard_with_http_info(id, **kwargs)
return dat... | VIew competition leaderboard # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.competition_view_leaderboard(id, async_req=True)
>>> result = thread.get()
:param async_req bool... |
5,881 | def matchmaker_delete(institute_id, case_name):
user_obj = store.user(current_user.email)
if not in user_obj[]:
flash(, )
return redirect(request.referrer)
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
mme_base_url = current_app.config.get... | Remove a case from MatchMaker |
5,882 | def plot_periodicvar_recovery_results(
precvar_results,
aliases_count_as_recovered=None,
magbins=None,
periodbins=None,
amplitudebins=None,
ndetbins=None,
minbinsize=1,
plotfile_ext=,
):
allrecoveredactualrecoveredtwicehalfratio_over_1plusratio_over_1m... | This plots the results of periodic var recovery.
This function makes plots for periodicvar recovered fraction as a function
of:
- magbin
- periodbin
- amplitude of variability
- ndet
with plot lines broken down by:
- magcol
- periodfinder
- vartype
- recovery status
... |
5,883 | def getDescendantsUIDs(self, all_descendants=False):
descendants = self.getDescendants(all_descendants=all_descendants)
return map(api.get_uid, descendants) | Returns the UIDs of the descendant Analysis Requests
This method is used as metadata |
5,884 | def get_installation_order(self, req_set):
order = []
ordered_reqs = set()
def schedule(req):
if req.satisfied_by or req in ordered_reqs:
return
if req.constraint:
return
ordered_r... | Create the installation order.
The installation order is topological - requirements are installed
before the requiring thing. We break cycles at an arbitrary point,
and make no other guarantees. |
5,885 | def _X509__asn1date_to_datetime(asn1date):
bio = Membio()
libcrypto.ASN1_TIME_print(bio.bio, asn1date)
pydate = datetime.strptime(str(bio), "%b %d %H:%M:%S %Y %Z")
return pydate.replace(tzinfo=utc) | Converts openssl ASN1_TIME object to python datetime.datetime |
5,886 | def start(main_gui_class, **kwargs):
debug = kwargs.pop(, False)
standalone = kwargs.pop(, False)
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO,
format=)
logging.getLogger().setLevel(
level=logging.DEBUG if debug else logging.INFO)
if s... | This method starts the webserver with a specific App subclass. |
5,887 | def _time_to_string(self, dt, conversion_string="%Y %m %d %H %M"):
if self.output_timezone is not None:
dt = dt.replace(tzinfo=utc) \
.astimezone(self.output_timezone)
return dt.strftime(conversion_string) | This converts a UTC time integer to a string |
5,888 | def make(self):
try:
self.mkfile(self.lock_file)
except Exception as e:
self.die(.format(str(e))) | Make the lock file. |
5,889 | def write_quotes(self, quotes):
if self.first:
Base.metadata.create_all(self.engine, checkfirst=True)
self.first=False
session=self.getWriteSession()
session.add_all([self.__quoteToSql(quote) for quote in quotes]) | write quotes |
5,890 | def _createIndexesFor(self, tableClass, extantIndexes):
try:
indexes = _requiredTableIndexes[tableClass]
except KeyError:
indexes = set()
for nam, atr in tableClass.getSchema():
if atr.indexed:
indexes.add(((atr.getShortCol... | Create any indexes which don't exist and are required by the schema
defined by C{tableClass}.
@param tableClass: A L{MetaItem} instance which may define a schema
which includes indexes.
@param extantIndexes: A container (anything which can be the right-hand
argument to ... |
5,891 | def accept(kind, doc=None, error_text=None, exception_handlers=empty.dict, accept_context=False):
return create(
doc,
error_text,
exception_handlers=exception_handlers,
chain=False,
accept_context=accept_context
)(kind) | Allows quick wrapping of any Python type cast function for use as a hug type annotation |
5,892 | def load(fh, single=False, version=_default_version,
strict=False, errors=):
if isinstance(fh, stringtypes):
s = open(fh, ).read()
else:
s = fh.read()
return loads(s, single=single, version=version,
strict=strict, errors=errors) | Deserialize SimpleMRSs from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single: if `True`, only return the first read Xmrs object
strict: deprecated; a `True` value is the same as
`errors='strict'`, and a `False` value is the same as
... |
5,893 | def get_blob(
self, blob_name, client=None, encryption_key=None, generation=None, **kwargs
):
blob = Blob(
bucket=self,
name=blob_name,
encryption_key=encryption_key,
generation=generation,
**kwargs
)
try:
... | Get a blob object by name.
This will return None if the blob doesn't exist:
.. literalinclude:: snippets.py
:start-after: [START get_blob]
:end-before: [END get_blob]
If :attr:`user_project` is set, bills the API request to that project.
:type blob_name: str
... |
5,894 | def envs(self):
ret = []
for saltenv in self.opts[]:
ret.append(saltenv)
return ret | Return the available environments |
5,895 | def get_word_index(tokens, char_index):
for (i, token) in enumerate(tokens):
if token[] == 0:
continue
if token[] <= char_index and char_index <= token[]:
return i
return 0 | Given word return word index. |
5,896 | def _encode_attribute(self, name, type_):
for char in :
if char in name:
name = %name
break
if isinstance(type_, (tuple, list)):
type_tmp = [u % encode_string(type_k) for type_k in type_]
type_ = u%(u.join(type_tmp))
... | (INTERNAL) Encodes an attribute line.
The attribute follow the template::
@attribute <attribute-name> <datatype>
where ``attribute-name`` is a string, and ``datatype`` can be:
- Numerical attributes as ``NUMERIC``, ``INTEGER`` or ``REAL``.
- Strings as ``STRING``.
... |
5,897 | def lemmatize(self, text, best_guess=True, return_frequencies=False):
if isinstance(text, str):
tokens = wordpunct_tokenize(text)
elif isinstance(text, list):
tokens= text
else:
raise TypeError("lemmatize only works with strings or lists of string tokens.")
return [self._lemmatize_token(to... | Lemmatize all tokens in a string or a list. A string is first tokenized using punkt.
Throw a type error if the input is neither a string nor a list. |
5,898 | def get_version():
VERSION_FILE =
mo = re.search(r"]([^\"]rtUnable to find version string in {0}.'.format(VERSION_FILE)) | Extracts the version number from the version.py file. |
5,899 | def plot_points(points, show=True):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
points = np.asanyarray(points, dtype=np.float64)
if len(points.shape) != 2:
raise ValueError()
if points.shape[1] == 3:
fig = plt.figure()
ax = fig.add_subplo... | Plot an (n,3) list of points using matplotlib
Parameters
-------------
points : (n, 3) float
Points in space
show : bool
If False, will not show until plt.show() is called |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.