Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
359,500 | def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None):
path = {}
data = {}
params = {}
path["id"] = id
... | Edit a user.
Modify an existing user. To modify a user's login, see the documentation for logins. |
359,501 | def get_func_sourcecode(func):
def getsource(func):
lines, lnum = getsourcelines(func)
return .join(lines)
def getsourcelines(func):
lines, lnum = findsource(func)
return inspect.getblock(lines[lnum:]), lnum + 1
def findsource(func):
file = getfile(func)
... | Try to get sourcecode using standard inspect.getsource().
If the function comes from a module which has been created dynamically
(not from the filesystem), then it tries to read the sourcecode on the
filesystem anyway.
WARNING: can do weird things if the filesystem code slightly differs from
... |
359,502 | def get_public(self):
node = self.node.find()
if node is not None:
return Cpublic(node=node)
else:
return None | Returns the public object or None if there is no such element
@return: the public object
@rtype: L{Cpublic} |
359,503 | def _default_headers(self):
headers = {
"Authorization": .format(self.api_key),
"User-agent": self.useragent,
"Accept":
}
if self.impersonate_subuser:
headers[] = self.impersonate_subuser
return headers | Set the default header for a Twilio SendGrid v3 API call |
359,504 | def uncache(self, name):
delme = []
if self._is_pattern(name):
expr = re.compile(self._pattern_to_regex(name))
for key, obj in self._cached.items():
if expr.match(key):
delme.append(key)
else:
if name in self._cache... | Remove all created query engines that match `name` from
the cache (this disconnects from MongoDB, which is the point).
:param name: Name used for :meth:`add`, or pattern
:return: None |
359,505 | def traceroute_batch(input_list, results={}, method="udp", cmd_arguments=None,
delay_time=0.1, max_threads=100):
threads = []
thread_error = False
thread_wait_timeout = 200
ind = 1
total_item_count = len(input_list)
for domain in input_list:
wait_time = 0
... | This is a parallel version of the traceroute primitive.
:param input_list: the input is a list of domain names
:param method: the packet type used for traceroute, UDP by default
:param cmd_arguments: the list of arguments that need to be passed
to traceroute.
:param delay_time: ... |
359,506 | def deprecated(message):
def deprecated_decorator(func):
@wraps(func)
def deprecated_func(*args, **kwargs):
warnings.warn(
" is deprecated. {}".format(func.__name__, message),
category=DeprecationWarning,
sta... | Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026 |
359,507 | def alter_and_get(self, function):
check_not_none(function, "function can't be None")
return self._encode_invoke(atomic_long_alter_and_get_codec, function=self._to_data(function)) | Alters the currently stored value by applying a function on it and gets the result.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with... |
359,508 | def GNN_instance(x, idx=0, device=None, nh=20, **kwargs):
device = SETTINGS.get_default(device=device)
xy = scale(x).astype()
inputx = th.FloatTensor(xy[:, [0]]).to(device)
target = th.FloatTensor(xy[:, [1]]).to(device)
GNNXY = GNN_model(x.shape[0], device=device, nh=nh).to(device)
GNNYX = ... | Run an instance of GNN, testing causal direction.
:param m: data corresponding to the config : (N, 2) data, [:, 0] cause and [:, 1] effect
:param pair_idx: print purposes
:param run: numner of the run (for GPU dispatch)
:param device: device on with the algorithm is going to be run on.
:return: |
359,509 | def getCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBinds, cbCtx):
lookupMib, future = cbCtx
if future.cancelled():
... | Creates a generator to perform SNMP GET query.
When iterator gets advanced by :py:mod:`asyncio` main loop,
SNMP GET request is send (:RFC:`1905#section-4.2.1`).
The iterator yields :py:class:`asyncio.Future` which gets done whenever
response arrives or error occurs.
Parameters
----------
s... |
359,510 | def sequences(self):
seqs = [x.sequence for x in self._molecules if hasattr(x, )]
return seqs | Returns the sequence of each `Polymer` in the `Assembly` as a list.
Returns
-------
sequences : [str]
List of sequences. |
359,511 | def get_ins_off(self, off):
idx = 0
for i in self.get_instructions():
if idx == off:
return i
idx += i.get_length()
return None | Get a particular instruction by using the address
:param off: address of the instruction
:type off: int
:rtype: an :class:`Instruction` object |
359,512 | def find(value):
value = str(value).lower()
rtn_dict = RegistryDictionary()
for attr in dir(MODULE.rdfclass):
if value in attr.lower():
try:
item = getattr(MODULE.rdfclass, attr)
if issubclass(item, RdfClassBase):
... | returns a dictionary of rdfclasses based on the a lowercase search
args:
value: the value to search by |
359,513 | def load_stl(file_obj, file_type=None, **kwargs):
file_pos = file_obj.tell()
try:
return load_stl_ascii(file_obj) | Load an STL file from a file object.
Parameters
----------
file_obj: open file- like object
file_type: not used
Returns
----------
loaded: kwargs for a Trimesh constructor with keys:
vertices: (n,3) float, vertices
faces: (m,3) int, indexes of vertice... |
359,514 | def is_valid(self):
self.errors = []
for field in self.get_all_field_names_declared_by_user():
getattr(type(self), field).is_valid(self, type(self), field)
field_errors = getattr(type(self), field).errors(self)
self.errors.extend(field_errors)
retur... | Validates single instance. Returns boolean value and store errors in self.errors |
359,515 | def absent(name, persist=False, comment=True, mods=None):
if not isinstance(mods, (list, tuple)):
mods = [name]
ret = {: name,
: True,
: {},
: }
loaded_mods = __salt__[]()
if persist:
persist_mods = __salt__[](True)
loaded_mods = li... | Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than remove it
mods
A list of modules to verify are unloaded.... |
359,516 | def read_pdb(pdbfname, as_string=False):
pybel.ob.obErrorLog.StopLogging()
if os.name != :
maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1]
resource.setrlimit(resource.RLIMIT_STACK, (min(2 ** 28, maxsize), maxsize))
sys.setrecursionlimit(10 ** 5)
return readmol(pdbfname... | Reads a given PDB file and returns a Pybel Molecule. |
359,517 | def mksls(src, dst=None):
ps_opts = {}
with salt.utils.files.fopen(src, ) as fh_:
for line in fh_:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith():
continue
if not line.strip():
continue
comps = shl... | Convert a preseed file to an SLS file |
359,518 | def plugins():
plugins = current_app.config[]
for name, description in entrypoints.ENTRYPOINTS.items():
echo(.format(white(description), name))
if name == :
actives = [current_app.config[]]
elif name == :
actives = [avatar_config()]
else:
... | Display some details about the local plugins |
359,519 | def _exec_module(
self,
fullname: str,
loader_state: Mapping[str, str],
path_stats: Mapping[str, int],
module: types.ModuleType,
):
filename = loader_state["filename"]
cache_filename = loader_state["cache_filename"]
with timed(
la... | Load and execute a non-cached Basilisp module. |
359,520 | def ngram_similarity(samegrams, allgrams, warp=1.0):
if abs(warp - 1.0) < 1e-9:
similarity = float(samegrams) / allgrams
else:
diffgrams = float(allgrams - samegrams)
similarity = ((allgrams ** warp - diffgrams ** warp)
/ (allgrams ** warp... | Similarity for two sets of n-grams.
:note: ``similarity = (a**e - d**e)/a**e`` where `a` is \
"all n-grams", `d` is "different n-grams" and `e` is the warp.
:param samegrams: number of n-grams shared by the two strings.
:param allgrams: total of the distinct n-grams across the two str... |
359,521 | def hmac_sha256(key, msg):
return hmac.new(key, msg, hashlib.sha256).digest() | Adapted from rransom's tor-utils git repository. Returns the
digest (binary) of an HMAC with SHA256 over msg with key. |
359,522 | def _explode_raster(raster, band_names=[]):
if not band_names:
band_names = raster.band_names
else:
band_names = list(IndexedSet(raster.band_names).intersection(band_names))
return [_Raster(image=raster.bands_data([band_name]), band_names=[band_name]) for band_name in ba... | Splits a raster into multiband rasters. |
359,523 | def getenv(name, **kwargs):
default_value = kwargs.pop(, None)
desired_type = kwargs.pop(, str)
list_separator = kwargs.pop(, )
value = os.getenv(name, None)
if value is None:
if default_value is None:
return None
else:
return default_value
if desi... | Retrieves environment variable by name and casts the value to desired type.
If desired type is list or tuple - uses separator to split the value. |
359,524 | def getPos(self):
sx,sy = self.widget.pos[0]+self.border[0]+self.offset[0], self.widget.pos[1]+self.border[1]+self.offset[1]
ex,ey = self.widget.pos[0]+self.widget.size[0]-self.border[0]+self.offset[0], self.widget.pos[1]+self.widget.size[1]-se... | Returns the absolute position and size of the layer.
This method is intended for use in vertex position calculation, as the border and offset have already been applied.
The returned value is a 4-tuple of ``(sx,sy,ex,ey)``\ .
The two values starting with an s are the "start" pos... |
359,525 | def render_to_string(self, *args, **kwargs):
try:
template_name, args = args[0], args[1:]
except IndexError:
raise TypeError()
return self.get_template(template_name).render(*args, **kwargs) | Load and render a template into a unicode string. |
359,526 | def json(self):
insndescs = [{insndesc[]: insndesc[]} for insndesc in self.structure]
return json.dumps(insndescs) | :return: JSON formatted string with instructions & values from Dockerfile |
359,527 | def _get_non_tempy_contents(self):
for thing in filter(
lambda x: not issubclass(x.__class__, DOMElement), self.childs
):
yield thing | Returns rendered Contents and non-DOMElement stuff inside this Tag. |
359,528 | def partition_source(src):
ast_obj = ast.parse(src.encode())
visitor = TopLevelImportVisitor()
visitor.visit(ast_obj)
line_offsets = get_line_offsets_by_line_no(src)
chunks = []
startpos = 0
pending_chunk_type = None
possible_ending_tokens = None
seen_import = False
... | Partitions source into a list of `CodePartition`s for import
refactoring. |
359,529 | def _find_header_row(self):
th_max = 0
header_idx = 0
for idx, tr in enumerate(self._tr_nodes):
th_count = len(tr.contents.filter_tags(matches=ftag()))
if th_count > th_max:
th_max = th_count
header_idx = idx
if not th_max... | Evaluate all rows and determine header position, based on
greatest number of 'th' tagged elements |
359,530 | def set_signal_handler(self, sigs=None):
if sigs is None:
sigs = (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGHUP)
func = self.manage_signal
if os.name == "nt":
try:
import win32api
win32api.SetConso... | Set the signal handler to manage_signal (defined in this class)
Only set handlers for:
- signal.SIGTERM, signal.SIGINT
- signal.SIGUSR1, signal.SIGUSR2
- signal.SIGHUP
:return: None |
359,531 | def get_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):
rCutHard = rCut + 5
assert Lmax <= 9, "l cannot exceed 9. Lmax={}".format(Lmax)
assert Lmax >= 0, "l cannot be negative.Lmax={}".format(Lmax)
assert rCutHard < 17.0001, "hard radius cutt... | Get the RBF basis SOAP output for the given positions in a finite system.
Args:
obj(ase.Atoms): Atomic structure for which the SOAP output is
calculated.
Hpos: Positions at which to calculate SOAP
alp: Alphas
bet: Betas
rCut: Radial cutoff.
nMax: Maximum ... |
359,532 | def isInNet(host, pattern, mask):
host_ip = host if is_ipv4_address(host) else dnsResolve(host)
if not host_ip or not is_ipv4_address(pattern) or not is_ipv4_address(mask):
return False
return _address_in_network(host_ip, pattern, mask) | Pattern and mask specification is done the same way as for SOCKS configuration.
:param str host: a DNS hostname, or IP address.
If a hostname is passed, it will be resolved into an IP address by this function.
:param str pattern: an IP address pattern in the dot-separated format
:param str mask: ma... |
359,533 | def _parse_array_member_state(self, block):
members = block.split()[0].split()[1].split()[2:]
device_regexp = re.compile(
)
ret = {
: 0,
: 0,
: 0
}
for member in members:
mem... | Parse the state of the the md array members.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_member_state(block)
{
... |
359,534 | def melt(table, key=None, variables=None, variablefield=,
valuefield=):
return MeltView(table, key=key, variables=variables,
variablefield=variablefield,
valuefield=valuefield) | Reshape a table, melting fields into data. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'gender', 'age'],
... [1, 'F', 12],
... [2, 'M', 17],
... [3, 'M', 16]]
>>> table2 = etl.melt(table1, 'id')
>>> table2.lookall()
+-... |
359,535 | def checkout(self):
self.pillar_dirs = OrderedDict()
self.pillar_linked_dirs = []
for repo in self.remotes:
cachedir = self.do_checkout(repo)
if cachedir is not None:
if repo.branch == and hasattr(repo, ):
env... | Checkout the targeted branches/tags from the git_pillar remotes |
359,536 | def create_cache(self, **kwargs):
cache = predix.admin.cache.Cache(**kwargs)
cache.create(**kwargs)
cache.add_to_manifest(self)
return cache | Creates an instance of the Cache Service. |
359,537 | def convert_map_type(cls, name, value):
converted_map = []
for k, v in zip(value.keys(), value.values()):
converted_map.append({
: cls.convert_value(, k),
: cls.convert_value(, v)
})
return converted_map | Converts a map to a repeated RECORD that contains two fields: 'key' and 'value',
each will be converted to its corresponding data type in BQ. |
359,538 | def min(self):
if self._prop.fmin is None:
return -_INF
return self._prop.fmin(self._obj) | Minimum value. |
359,539 | def mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None):
try:
stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1)
except Exception as e:
raise
sys.stderr.write("ERROR: {}\n".format(str(e)))
stats = {}
if not bg_name:
bg_name = "default"
return bg_name, stats | Parallel calculation of motif statistics. |
359,540 | def _write(self, session, openFile, replaceParamFile):
hmetRecords = self.hmetRecords
for record in hmetRecords:
openFile.write( % (
record.hmetDateTime.year,
record.hmetDateTime.month,
record.hmetDateTime.day,
... | Write HMET WES to File Method |
359,541 | def check_remove_particle(st, ind, im_change_frac=0.2, min_derr=,
**kwargs):
if min_derr == :
min_derr = 3 * st.sigma
present_err = st.error
present_d = st.residuals.copy()
p, r = st.obj_remove_particle(ind)
p = p[0]
r = r[0]
absent_err = st.error
... | Checks whether to remove particle 'ind' from state 'st'. If removing the
particle increases the error by less than max( min_derr, change in image *
im_change_frac), then the particle is removed.
Parameters
----------
st : :class:`peri.states.State`
The state to check adding particles to.
... |
359,542 | def is_valid_password(password):
pattern = re.compile(r"^.{4,75}$")
return bool(pattern.match(password)) | Check if a password is valid |
359,543 | def split_auth_from_netloc(netloc):
if not in netloc:
return netloc, (None, None)
auth, netloc = netloc.rsplit(, 1)
if in auth:
else:
user_pass = auth, None
user_pass = tuple(
None if x is None else urllib_unquote(x) for x in user_pass
)
return... | Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)). |
359,544 | def gen_enum_completions(self, arg_name):
try:
for choice in self.cmdtab[self.current_command].arguments[arg_name].choices:
if self.validate_completion(choice):
yield Completion(choice, -len(self.unfinished_word))
except TypeError:
... | generates dynamic enumeration completions |
359,545 | def input_data(self):
ordererd = np.sort(np.asarray(list(self.plot_info.keys())).astype(int))
trans_cont_dict = OrderedDict()
for i in ordererd:
trans_cont_dict[str(i)] = self.plot_info[str(i)]
self.plot_info = trans_cont_dict
x = [[]for i in np.a... | Function to extract data from files according to pid.
This function will read in the data with
:class:`bowie.plotutils.readdata.ReadInData`. |
359,546 | def _parse_object_header(self, header_line):
tokens = header_line.split()
if len(tokens) != 3:
if not tokens:
raise ValueError("SHA could not be resolved, git returned: %r" % (header_line.strip()))
else:
raise ValueError("SHA %s could not ... | :param header_line:
<hex_sha> type_string size_as_int
:return: (hex_sha, type_string, size_as_int)
:raise ValueError: if the header contains indication for an error due to
incorrect input sha |
359,547 | def get(self, id):
ctx = self.context.copy()
ctx[] = False
results = self.rpc_model.search_read(
[(, , id)],
None, None, None, self.fields,
context=ctx
)
return results and results[0] or None | Return an instance based on the given primary key identifier,
or None if not found.
This returns a record whether active or not. |
359,548 | def _init_metadata(self):
self._start_timestamp_metadata = {
: Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
),
: ,
: ,
: False,
: False,
: Fa... | stub |
359,549 | def data_preprocess(data, size=None, min_axis=None, batch=False):
if batch:
return [data_preprocess(el, size=size, min_axis=min_axis, batch=False) for el in data]
if isinstance(data, string_types):
if file_exists(data):
preprocessed = Image.open(data)
else:... | Takes data and prepares it for sending to the api including
resizing and image data/structure standardizing. |
359,550 | def _parse_mode(self, mode, allowed=None, single=False):
r
if type(mode) is str:
mode = [mode]
for item in mode:
if (allowed is not None) and (item not in allowed):
raise Exception(mode\ +
allowed.__str__())
... | r"""
This private method is for checking the \'mode\' used in the calling
method.
Parameters
----------
mode : string or list of strings
The mode(s) to be parsed
allowed : list of strings
A list containing the allowed modes. This list is defined... |
359,551 | def parse_dereplicated_uc(dereplicated_uc_lines):
dereplicated_clusters = {}
seed_hit_ix = 0
seq_id_ix = 8
seed_id_ix = 9
for line in dereplicated_uc_lines:
if line.startswith("
continue
curr_line = line.strip().split()
if curr_line[seed_hit_ix] == "S":
... | Return dict of seq ID:dereplicated seq IDs from dereplicated .uc lines
dereplicated_uc_lines: list of lines of .uc file from dereplicated seqs from
usearch61 (i.e. open file of abundance sorted .uc data) |
359,552 | def get_client(self, client_id):
self.assert_has_permission()
uri = self.uri + + client_id
headers = self.get_authorization_headers()
response = requests.get(uri, headers=headers)
if response.status_code == 200:
return response.json()
else:
... | Returns details about a specific client by the client_id. |
359,553 | def sentences(self):
prevp = 0
prevs = 0
sentence = [];
sentence_id = ""
for word, id, pos, lemma in iter(self):
try:
doc_id, ptype, p, s, w = re.findall(,id)[0]
if ((p != prevp) or (s != prevs)) and sentence:
... | Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma) |
359,554 | def _latex_(self):
r
if self.allowed:
return self.e1._latex_()++self.e2._latex_()
elif not self.allowed:
return self.e1._latex_()++self.e2._latex_()
else:
return self.e1._latex_()++self.e2._latex_()
return self.e1._latex_()++self.e2._latex_() | r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^{3}' |
359,555 | def add_page(self, route, target, link_name=None):
req = proto.Proxy(route=route, target=target, link_name=link_name)
self._client._call(, req)
return ProxiedPage(route, target, link_name, self.address,
self.proxy_prefix) | Add a new proxied page to the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application.
target : str
... |
359,556 | def bfd(self, **kwargs):
int_type = str(kwargs.pop().lower())
kwargs[] = str(kwargs.pop())
kwargs[] = kwargs.pop()
kwargs[] = kwargs.pop()
kwargs[] = kwargs.pop(, False)
callback = kwargs.pop(, self._callback)
valid_int_types = [, ,
... | Configure BFD for Interface.
Args:
name (str): name of the interface to configure (230/0/1 etc)
int_type (str): interface type (gigabitethernet etc)
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BFD receive interval in milliseconds (30... |
359,557 | def set_model_doc_string(model, doc, override=False):
if model is None or not isinstance(model, onnx_proto.ModelProto):
raise ValueError("Model is not a valid ONNX model.")
if not convert_utils.is_string_type(doc):
raise ValueError("Doc must be a string type.")
if model.doc_string and n... | Sets the doc string of the ONNX model.
:param model: instance of an ONNX model
:param doc: string containing the doc string that describes the model.
:param override: bool if true will always override the doc string with the new value
Example:
::
from onnxmltools.utils import set_model_do... |
359,558 | def open(self, new=1):
import webbrowser
webbrowser.open(self.url, new=new) | Open this viewer in a new browser window or tab.
(requires `webbrowser` module) |
359,559 | def _folder_to_dict(self, path):
res = {}
for key in os.listdir(path):
if key.startswith():
continue
key_path = os.path.join(path, key)
if os.path.isfile(key_path):
val = open(key_path).read()
key = key.split()[... | Recursively reads the files from the directory given by `path` and
writes their contents to a nested dictionary, which is then returned. |
359,560 | def registration_settings(request):
context = {}
for setting in (
,
,
,
,
,
,
):
context[setting] = getattr(settings, setting, None)
return context | Expose selected settings to templates |
359,561 | def get_erasure_profile(service, name):
try:
out = check_output([, , service,
, , ,
name, ])
if six.PY3:
out = out.decode()
return json.loads(out)
except (CalledProcessError, OSError, ValueError):
return Non... | :param service: six.string_types. The Ceph user name to run the command under
:param name:
:return: |
359,562 | def raises(self, exc):
exp = self._get_current_call()
exp.exception_to_raise = exc
return self | Set last call to raise an exception class or instance.
For example::
>>> import fudge
>>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert"))
>>> db.insert()
Traceback (most recent call last):
...
... |
359,563 | def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
self.location_from = infer_location(
self.points[0],
location... | In-place location inferring
See infer_location function
Args:
Returns:
:obj:`Segment`: self |
359,564 | def stop(self):
self.clearRemoteServices()
self.clearLocalServices()
self._stopThreads()
self._serverStarted = False | cleans up and stops the discovery server |
359,565 | def truncate_cwd(full_filename):
if full_filename.startswith(os.getcwd()):
truncated_filename = full_filename.split(os.getcwd(), 1)[1]
truncated_filename = truncated_filename.split(os.sep, 1)[1]
else:
truncated_filename = full_filename
return truncated_filename | Remove the cwd from the full filename. |
359,566 | def __create_event(self):
if not event.contains(self.field, , self.__validate):
event.listen(self.field, , self.__validate, retval=True) | Create an SQLAlchemy event listening the 'set' in a particular column.
:rtype : object |
359,567 | def precise_matcher(text_log_error):
failure_line = text_log_error.metadata.failure_line
logger.debug("Looking for test match in failure %d", failure_line.id)
if failure_line.action != "test_result" or failure_line.message is None:
return
f = {
: ,
: failure_line.test,
... | Query for TextLogErrorMatches identical to matches of the given TextLogError. |
359,568 | def Tb(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[PSAT_DEFINITION]):
rs boiling
point. Lookup is based on CASRNs. Will automatically select a data
source to use if no Method is provided; returns None if the data is not
available.
Prefered sources are for organic
chemicals, and ... | r'''This function handles the retrieval of a chemical's boiling
point. Lookup is based on CASRNs. Will automatically select a data
source to use if no Method is provided; returns None if the data is not
available.
Prefered sources are 'CRC Physical Constants, organic' for organic
chemicals, and 'CR... |
359,569 | def as_iframe(self, html_data):
srcdoc = html_data.replace(, "<iframe id="{div_id}", srcdoc="{srcdoc}" style="width: {width}; height: {height};"></iframe>'.format(
div_id=self.div_id,
srcdoc=srcdoc,
width=self.width,
heigh... | Build the HTML representation for the mapviz. |
359,570 | def mcscanx(args):
p = OptionParser(mcscanx.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
blastfile = args[0]
bedfiles = args[1:]
prefix = "_".join(op.basename(x)[:2] for x in bedfiles)
symlink(blastfile, prefix + ".blast")
allbedf... | %prog mcscanx athaliana.athaliana.last athaliana.bed
Wrap around MCScanX. |
359,571 | def isEmpty(self):
if self.obj is None:
return True
if self._clean.isString():
ret = self.obj.strip() is ""
elif self._clean.isDict():
ret = len(self.obj.keys()) == 0
else:
ret = len(self.obj) == 0
return self._wrap(ret) | Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties. |
359,572 | def validate_overlap(self,force):
self.spectrum, self.bandpass, warn = validate_overlap(self.spectrum,
self.bandpass, force)
self.warnings.update(warn) | Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. Partial overlap is allowed if this is set to
... |
359,573 | def run_r_script(r_script_filename, cwd = ):
p = subprocess.Popen(["R", "CMD", "BATCH", r_script_filename], cwd = cwd)
while True:
time.sleep(0.3)
errcode = p.poll()
if errcode != None:
break
rout = "{0}out".format(r_script_filename)
rout_contents = None
if o... | This function was adapted from the covariation benchmark. |
359,574 | def headerData(self, section, orientation, role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return to_qvariant()
labels = self.xlabels if orientation == Qt.Horizontal else self.ylabels
if labels is None:
return to_qvariant(int(section))
else:
... | Set header data |
359,575 | def config_mode(self, config_command="sudo su"):
delay_factor = self.select_delay_factor(delay_factor=1)
output = ""
if not self.check_config_mode():
output += self.send_command_timing(
config_command, strip_prompt=False, strip_command=False
)
... | Attempt to become root. |
359,576 | def set_temperature(self, temperature):
velocities = np.random.randn(len(self.structure), 3)
atomic_masses = np.array([site.specie.atomic_mass.to("kg")
for site in self.structure])
dof = 3 * len(self.structure) - 3
... | Initializes the velocities based on Maxwell-Boltzmann distribution.
Removes linear, but not angular drift (same as VASP)
Scales the energies to the exact temperature (microcanonical ensemble)
Velocities are given in A/fs. This is the vasp default when
direct/cartesian is not specified (... |
359,577 | def assert_sigfigs_equal(x, y, sigfigs=3):
xpow = np.floor(np.log10(x))
x = x * 10**(- xpow)
y = y * 10**(- xpow)
assert_almost_equal(x, y, sigfigs) | Tests if all elements in x and y
agree up to a certain number of
significant figures.
:param np.ndarray x: Array of numbers.
:param np.ndarray y: Array of numbers you want to
be equal to ``x``.
:param int sigfigs: How many significant
figures you demand that they share.
Defa... |
359,578 | def get_service_location_info(self, service_location_id):
url = urljoin(URLS[], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json() | Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict |
359,579 | def ignore_comments(iterator):
for line in iterator:
line = COMMENT_RE.sub(, line)
line = line.strip()
if line:
yield line | Strips and filters empty or commented lines. |
359,580 | def solution(events, slots, objective_function=None, solver=None, **kwargs):
shape = Shape(len(events), len(slots))
problem = pulp.LpProblem()
X = lp.utils.variables(shape)
beta = pulp.LpVariable("upper_bound")
for constraint in lp.constraints.all_constraints(
events, slots, X, beta,
... | Compute a schedule in solution form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.solver
a pulp solver
objective_function: callable
from lp_problem... |
359,581 | def html_color_to_rgba(html_colour, alpha):
html_colour = html_colour.upper()
if html_colour[0] == :
html_colour = html_colour[1:]
r_str = html_colour[0:2]
g_str = html_colour[2:4]
b_str = html_colour[4:6]
r = int(r_str, 16)
g = int(g_str, 16)
b = int(b_str, 16)
retur... | :param html_colour: Colour string like FF0088
:param alpha: Alpha value (opacity)
:return: RGBA semitransparent version of colour for use in css |
359,582 | def detectEquilibration(A_t, fast=True, nskip=1):
T = A_t.size
if A_t.std() == 0.0:
return (0, 1, 1)
g_t = np.ones([T - 1], np.float32)
Neff_t = np.ones([T - 1], np.float32)
for t in range(0, T - 1, nskip):
try:
g_t[t] = statisticalInefficiency(A_t[t:T], fas... | Automatically detect equilibrated region of a dataset using a heuristic that maximizes number of effectively uncorrelated samples.
Parameters
----------
A_t : np.ndarray
timeseries
nskip : int, optional, default=1
number of samples to sparsify data by in order to speed equilibration de... |
359,583 | def build_row(row, left, center, right):
if not row or not row[0]:
yield combine((), left, center, right)
return
for row_index in range(len(row[0])):
yield combine((c[row_index] for c in row), left, center, right) | Combine single or multi-lined cells into a single row of list of lists including borders.
Row must already be padded and extended so each cell has the same number of lines.
Example return value:
[
['>', 'Left ', '|', 'Center', '|', 'Right', '<'],
['>', 'Cell1', '|', 'Cell2 ', '|', 'Cell3',... |
359,584 | def list_clients():
p = % (tempfile.gettempdir(), getpass.getuser())
for path in glob.glob(p):
try:
yield PosixClient(path)
except socket.error:
pass | List all the servers that are running. |
359,585 | def is_full(cls, pid):
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full | Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool |
359,586 | def from_list(cls, values):
self = cls()
for value in values:
self.add(value)
return self | Construct a tree from a list with paths. |
359,587 | def matrix_product(mat1, mat2):
return np.dot(mat2.T, mat1.T).T | Compute the product of two Fortran contiguous matrices.
This is to avoid the overhead of NumPy converting to C-contiguous
before computing a matrix product.
Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be
C-contiguous without a copy, then the product ``P = B^T A^T`` will
be C-c... |
359,588 | def create_items(self):
if not self.mode[] or len(self.mode[]) == 0: return
self.collman.add(self.player)
for k in self.mode[]:
item = self.mode[][k]
radius = item[] * self.player.radius
for i in range(item[]):
... | Create collidable items |
359,589 | def muscle_seqs(seqs,
add_seq_names=False,
out_filename=None,
input_handler=None,
params={},
WorkingDir=tempfile.gettempdir(),
SuppressStderr=None,
SuppressStdout=None):
if out_filename:
... | Muscle align list of sequences.
seqs: a list of sequences as strings or objects, you must set add_seq_names=True
or sequences in a multiline string, as read() from a fasta file
or sequences in a list of lines, as readlines() from a fasta file
or a fasta seq filename.
== for eg, testcode for guessi... |
359,590 | def papermill_process(self, nb_man, resources):
nb = nb_man.nb
for index, cell in enumerate(nb.cells):
try:
nb_man.cell_start(cell, index)
if not cell.source:
continue
nb.cells[index], resources = self.prep... | This function acts as a replacement for the grandparent's `preprocess`
method.
We are doing this for the following reasons:
1. Notebooks will stop executing when they encounter a failure but not
raise a `CellException`. This allows us to save the notebook with the
traceba... |
359,591 | def _combined_items(self):
result = dict(self._items)
par = self._parent
while par:
result.update(par._items)
par = par._parent
return result | Returns a dictionary with this object's properties merged with all its parent's
properties.
The returned dictionary is all the available properties for this object (and their
associated values). |
359,592 | def iter_encode(self, obj):
if obj.get(, None):
for row in obj[].split():
yield self._encode_comment(row)
if not obj.get():
raise BadObject()
yield self._encode_relation(obj[])
yield u
if not obj.get()... | The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as unicode strings. |
359,593 | def repeat(obj, times=None):
if times is None:
return AsyncIterWrapper(sync_itertools.repeat(obj))
return AsyncIterWrapper(sync_itertools.repeat(obj, times)) | Make an iterator that returns object over and over again. |
359,594 | def wrap_json(cls, json):
if json is None:
return None
channel = Channel.wrap_json(json.get())
s = Stream(game=json.get(),
channel=channel,
twitchid=json.get(),
viewers=json.get(),
preview=json.get()... | Create a Stream instance for the given json
:param json: the dict with the information of the stream
:type json: :class:`dict` | None
:returns: the new stream instance
:rtype: :class:`Stream` | None
:raises: None |
359,595 | def set_pkg_source_info(self, doc, text):
self.assert_package_exists()
if not self.package_source_info_set:
self.package_source_info_set = True
if validations.validate_pkg_src_info(text):
doc.package.source_info = str_from_text(text)
retur... | Sets the package's source information, if not already set.
text - Free form text.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
SPDXValueError if text is not free form text. |
359,596 | def scale_and_crop_with_ranges(
im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs):
min_width, min_height = size
if min_width == 0 or min_height == 0 or not size_range:
return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs)
m... | An easy_thumbnails processor that accepts a `size_range` tuple, which
indicates that one or both dimensions can give by a number of pixels in
order to minimize cropping. |
359,597 | def add_rich_rule(zone, rule, permanent=True):
*rule
cmd = "--zone={0} --add-rich-rule=".format(zone, rule)
if permanent:
cmd +=
return __firewall_cmd(cmd) | Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_rich_rule zone 'rule' |
359,598 | def execute(self, input_data):
fields = [, , , , , ]
view = {key:input_data[][key] for key in fields}
return view | Execute Method |
359,599 | def unquote(text):
while in text:
newtext = url_unquote(text)
if newtext == text:
break
text = newtext
return text | Replace all percent-encoded entities in text. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.