Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
366,400 | def iterprogress( sized_iterable ):
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | Iterate something printing progress bar to stdout |
366,401 | def session(self):
if self._session is None:
self._session = requests.Session()
self._session.headers.update(self._headers)
return self._session | Get session object to benefit from connection pooling.
http://docs.python-requests.org/en/master/user/advanced/#session-objects
:rtype: requests.Session |
366,402 | def remove_device(self, device: Union[DeviceType, str]) -> None:
try:
if self.mutable:
_device = self.get_contentclass()(device)
try:
del self._name2device[_device.name]
except KeyError:
raise ValueError... | Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
>>> node_x, node_y = nodes
>>> nodes.remove_device(Node('node_y'))... |
366,403 | def get_dsn(d):
try:
return d["dataSetName"]
except Exception as e:
logger_misc.warn("get_dsn: Exception: No datasetname found, unable to continue: {}".format(e))
exit(1) | Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name |
366,404 | def check_ontology(fname):
with open(fname, ) as stream:
y = yaml.safe_load(stream)
import pprint
pprint.pprint(y) | reads the ontology yaml file and does basic verifcation |
366,405 | def normalize_path(path):
return os.path.normcase(os.path.realpath(os.path.expanduser(path))) | Convert a path to its canonical, case-normalized, absolute version. |
366,406 | def _authn_response(self, in_response_to, consumer_url,
sp_entity_id, identity=None, name_id=None,
status=None, authn=None, issuer=None, policy=None,
sign_assertion=False, sign_response=False,
best_effort=False, encrypt_asse... | Create a response. A layer of indirection.
:param in_response_to: The session identifier of the request
:param consumer_url: The URL which should receive the response
:param sp_entity_id: The entity identifier of the SP
:param identity: A dictionary with attributes and values that are
... |
366,407 | def only_newer(copy_func):
@functools.wraps(copy_func)
def wrapper(src, dst, *args, **kwargs):
is_newer_dst = (
dst.exists()
and dst.getmtime() >= src.getmtime()
)
if is_newer_dst:
return dst
return copy_func(src, dst, *args, **kwargs)
... | Wrap a copy function (like shutil.copy2) to return
the dst if it's newer than the source. |
366,408 | def canonicalize_edge(edge_data: EdgeData) -> Tuple[str, Optional[Tuple], Optional[Tuple]]:
return (
edge_data[RELATION],
_canonicalize_edge_modifications(edge_data.get(SUBJECT)),
_canonicalize_edge_modifications(edge_data.get(OBJECT)),
) | Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications. |
366,409 | def plugin_for(cls, model):
logger.debug("Getting a plugin for: %s", model)
if not issubclass(model, Model):
return
if model in cls.plugins:
return cls.plugins[model]
for b in model.__bases__:
p = cls.plugin_for(b)
if p:
... | Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered. |
366,410 | def LoadFromXml(self, node, handle):
self.SetHandle(handle)
if node.hasAttributes():
attributes = node.attributes
attCount = len(attributes)
for i in range(attCount):
attNode = attributes.item(i)
attr = UcsUtils.WordU(attNode.localName)
if (UcsUtils.FindClassIdInMoMetaIgnoreCase... | Method updates the object from the xml representation of the managed object. |
366,411 | def get_src_or_dst(mode, path_type):
logger_directory.info("enter set_src_or_dst")
_path = ""
_files = ""
invalid = True
count = 0
if not mode:
invalid = False
elif mode == "read" and path_type == "file":
_path, _files = browse_dialog_file()
... | User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen |
366,412 | def main(master_dsn, slave_dsn, tables, blocking=False):
assert master_dsn.startswith("mysql")
logger = logging.getLogger(__name__)
logger.info("replicating tables: %s" % ", ".join(tables))
repl_db_sub(master_dsn, slave_dsn, tables)
mysql_pub(master_dsn, blocking=blocking) | DB Replication app.
This script will replicate data from mysql master to other databases(
including mysql, postgres, sqlite).
This script only support a very limited replication:
1. data only. The script only replicates data, so you have to make sure
the tables already exists in slave db.
2. ... |
366,413 | def main(verbose=True):
find_executable(MAKE_CMD)
if not find_executable(MAKE_CMD):
print(
% MAKE_CMD
)
exit(1)
subprocess.check_output([MAKE_CMD, "-C", SAMPLE_C_CODE_DIR, "--quiet"])
gdbmi = GdbController(verbose=verbose)
... | Build and debug an application programatically
For a list of GDB MI commands, see https://www.sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html |
366,414 | def deserialize_properties(props_struct: struct_pb2.Struct) -> Any:
if _special_sig_key in props_struct:
if props_struct[_special_sig_key] == _special_asset_sig:
if "path" in props_struct:
return known_types.new_file_asset(props_struct["... | Deserializes a protobuf `struct_pb2.Struct` into a Python dictionary containing normal
Python types. |
366,415 | def do_pot(self):
files_to_translate = []
log.debug("Collecting python sources for pot ...")
for source_path in self._source_paths:
for source_path in self._iter_suffix(path=source_path, suffix=".py"):
log.debug("... add to pot: {source}".format(source=str(so... | Sync the template with the python code. |
366,416 | def IDENTITY(val):
value
if not val:
return None
if not isinstance(val, six.string_types_ex):
val = str(val)
return [val] | This is a basic "equality" index keygen, primarily meant to be used for
things like::
Model.query.filter(col='value')
Where ``FULL_TEXT`` would transform a sentence like "A Simple Sentence" into
an inverted index searchable by the words "a", "simple", and/or "sentence",
``IDENTITY`` will only ... |
366,417 | def near_reduce(self, coords_set, threshold=1e-4):
unique_coords = []
coords_set = [self.slab.lattice.get_fractional_coords(coords)
for coords in coords_set]
for coord in coords_set:
if not in_coord_list_pbc(unique_coords, coord, threshold):
... | Prunes coordinate set for coordinates that are within
threshold
Args:
coords_set (Nx3 array-like): list or array of coordinates
threshold (float): threshold value for distance |
366,418 | def prepare_searchlight_mvpa_data(images, conditions, data_type=np.float32,
random=RandomType.NORANDOM):
time1 = time.time()
epoch_info = generate_epochs_info(conditions)
num_epochs = len(epoch_info)
processed_data = None
logger.info(
%
(len(co... | obtain the data for activity-based voxel selection using Searchlight
Average the activity within epochs and z-scoring within subject,
while maintaining the 3D brain structure. In order to save memory,
the data is processed subject by subject instead of reading all in before
processing. Assuming all sub... |
366,419 | async def synchronize(self, pid, vendor_specific=None):
return await self._request_pyxb(
"post",
["synchronize", pid],
{},
mmp_dict={"pid": pid},
vendor_specific=vendor_specific,
) | Send an object synchronization request to the CN. |
366,420 | def p_compilerDirective(p):
directive = p[3].lower()
param = p[5]
if directive == :
fname = param
if p.parser.file:
if os.path.dirname(p.parser.file):
fname = os.path.join(os.path.dirname(p.parser.file),
fname)
p.p... | compilerDirective : '#' PRAGMA pragmaName '(' pragmaParameter ') |
366,421 | def start(self):
if self.__running:
raise RuntimeError()
[t.start() for t in self.__threads]
self.__running = True | Starts the #ThreadPool. Must be ended with #stop(). Use the context-manager
interface to ensure starting and the #ThreadPool. |
366,422 | def get_reply(self, message):
session_storage = self.session_storage
id = None
session = None
if session_storage and hasattr(message, "source"):
id = to_binary(message.source)
session = session_storage[id]
handlers = self.get_handlers(message.ty... | 根据 message 的内容获取 Reply 对象。
:param message: 要处理的 message
:return: 获取的 Reply 对象 |
366,423 | def pip_r(self, requirements, raise_on_error=True):
cmd = "pip install -r %s" % requirements
return self.wait(cmd, raise_on_error=raise_on_error) | Install all requirements contained in the given file path
Waits for command to finish.
Parameters
----------
requirements: str
Path to requirements.txt
raise_on_error: bool, default True
If True then raise ValueError if stderr is not empty |
366,424 | def grid_widgets(self):
sticky = {"sticky": "nswe"}
self.label.grid(row=1, column=1, columnspan=2, **sticky)
self.dropdown.grid(row=2, column=1, **sticky)
self.entry.grid(row=2, column=2, **sticky)
self.button.grid(row=3, column=1, columnspan=2, **sticky)
self.ra... | Put widgets in the grid |
366,425 | def __clear_covers(self):
for i in range(self.n):
self.row_covered[i] = False
self.col_covered[i] = False | Clear all covered matrix cells |
366,426 | def get_rest_token(self):
uri = urllib.parse.quote_plus(
"https://{}.{}/{}".format(self.sb_name, self.namespace_suffix, self.eh_name))
sas = self.sas_key.encode()
expiry = str(int(time.time() + 10000))
string_to_sign = (.format(uri, expiry)).encode()
signed_h... | Returns an auth token for making calls to eventhub REST API.
:rtype: str |
366,427 | def parse_data(data, type, **kwargs):
suffixes = {
: ,
: ,
}
try:
suffix = suffixes[type]
except KeyError:
raise ValueError( % type)
fd, filename = tempfile.mkstemp(suffix=suffix)
try:
os.write(fd, data)
os.close(fd)
return parse_file... | Return an OSM networkx graph from the input OSM data
Parameters
----------
data : string
type : string ('xml' or 'pbf')
>>> graph = parse_data(data, 'xml') |
366,428 | def get_visible_elements(self, locator, params=None, timeout=None):
return self.get_present_elements(locator, params, timeout, True) | Get elements both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param locator: locator tuple
:param params: (optional) locator params
:pa... |
366,429 | def visible_to_user(self, user):
return Poll.objects.filter(Q(groups__in=user.groups.all()) | Q(groups__isnull=True)) | Get a list of visible polls for a given user (usually request.user).
These visible polls will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member. |
366,430 | def get_version_from_tag(tag_name: str) -> Optional[str]:
debug(.format(tag_name))
check_repo()
for i in repo.tags:
if i.name == tag_name:
return i.commit.hexsha
return None | Get git hash from tag
:param tag_name: Name of the git tag (i.e. 'v1.0.0')
:return: sha1 hash of the commit |
366,431 | def _gamma_difference_hrf(tr, oversampling=50, time_length=32., onset=0.,
delay=6, undershoot=16., dispersion=1.,
u_dispersion=1., ratio=0.167):
from scipy.stats import gamma
dt = tr / oversampling
time_stamps = np.linspace(0, time_length, np.rint(flo... | Compute an hrf as the difference of two gamma functions
Parameters
----------
tr : float
scan repeat time, in seconds
oversampling : int, optional (default=16)
temporal oversampling factor
time_length : float, optional (default=32)
hrf kernel length, in seconds
onset... |
366,432 | def load(self, path):
DB = joblib.load(path)
self.catalog = DB.catalog
self.n_sources = DB.n_sources
self.name = DB.name
self.history = DB.history
del DB | Load the catalog from file
Parameters
----------
path: str
The path to the file |
366,433 | def clean_single_word(word, lemmatizing="wordnet"):
if lemmatizing == "porter":
porter = PorterStemmer()
lemma = porter.stem(word)
elif lemmatizing == "snowball":
snowball = SnowballStemmer()
lemma = snowball.stem(word)
elif lemmatizing == "wordnet":
wordnet = Wo... | Performs stemming or lemmatizing on a single word.
If we are to search for a word in a clean bag-of-words, we need to search it after the same kind of preprocessing.
Inputs: - word: A string containing the source word.
- lemmatizing: A string containing one of the following: "porter", "snowball" o... |
366,434 | def get_index_list(self, as_json=False):
url = self.index_url
req = Request(url, None, self.headers)
resp = self.opener.open(req)
resp = byte_adaptor(resp)
resp_list = json.load(resp)[]
index_list = [str(item[]) for item in resp_list]
return sel... | get list of indices and codes
params:
as_json: True | False
returns: a list | json of index codes |
366,435 | def main():
parser = argparse.ArgumentParser(description = ,
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument(, metavar = ,
help = )
parser.add_argument(, metavar = , nargs = ,
help = ... | Parse the command-line arguments and run the tool. |
366,436 | def add_side_to_basket(self, item, quantity=1):
item_variant = item[VARIANT.PERSONAL]
params = {
: item_variant[],
: quantity,
: []
}
return self.__post(, json=params) | Add a side to the current basket.
:param Item item: Item from menu.
:param int quantity: The quantity of side to be added.
:return: A response having added a side to the current basket.
:rtype: requests.Response |
366,437 | def simple_cache(func):
saved_results = {}
def wrapper(cls, module):
if module in saved_results:
return saved_results[module]
saved_results[module] = func(cls, module)
return saved_results[module]
return wrapper | Save results for the :meth:'path.using_module' classmethod.
When Python 3.2 is available, use functools.lru_cache instead. |
366,438 | def check(actions, request, target=None):
if target is None:
target = {}
user = auth_utils.get_user(request)
if target.get() is None:
target[] = user.project_id
if target.get() is None:
target[] = target[]
if target.get() is None:
... | Check user permission.
Check if the user has permission to the action according
to policy setting.
:param actions: list of scope and action to do policy checks on,
the composition of which is (scope, action). Multiple actions
are treated as a logical AND.
* scope: service type man... |
366,439 | def unpack_directory(filename, extract_dir, progress_filter=default_filter):
if not os.path.isdir(filename):
raise UnrecognizedFormat("%s is not a directory" % (filename,))
paths = {filename:(,extract_dir)}
for base, dirs, files in os.walk(filename):
src,dst = paths[base]
for d... | Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory |
366,440 | def add_plugins(self, page, placeholder):
for language_code, lang_name in iter_languages(self.languages):
for no in range(1, self.dummy_text_count + 1):
add_plugin_kwargs = self.get_add_plugin_kwargs(
page, no, placeholder, language_code, lang_name)
... | Add a "TextPlugin" in all languages. |
366,441 | def register(self, receiver_id, receiver):
assert receiver_id not in self.receivers
self.receivers[receiver_id] = receiver(receiver_id) | Register a receiver. |
366,442 | def wrap(ptr, base=None):
if ptr is None:
return None
ptr = long(ptr)
if base is None:
qObj = shiboken.wrapInstance(long(ptr), QtCore.QObject)
metaObj = qObj.metaObject()
cls = metaObj.className()
superCls = metaObj.superClass().className()
if hasattr(Qt... | Wrap the given pointer with shiboken and return the appropriate QObject
:returns: if ptr is not None returns a QObject that is cast to the appropriate class
:rtype: QObject | None
:raises: None |
366,443 | def indian_punctuation_tokenize_regex(self, untokenized_string: str):
modified_punctuations = string.punctuation.replace("|",
"")
indian_punctuation_pattern = re.compile(
+ modified_punctuations + + )
tok_str = i... | A trivial tokenizer which just tokenizes on the punctuation boundaries.
This also includes punctuation, namely the the purna virama ("|") and
deergha virama ("॥"), for Indian language scripts.
:type untokenized_string: str
:param untokenized_string: A string containing one of more sente... |
366,444 | def destroy(self):
fragment = self.fragment
if fragment:
fragment.setFragmentListener(None)
if self.adapter is not None:
self.adapter.removeFragment(self.fragment)
del self.fragment
super(AndroidFra... | Custom destructor that deletes the fragment and removes
itself from the adapter it was added to. |
366,445 | def fake_getaddrinfo(
host, port, family=None, socktype=None, proto=None, flags=None):
return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP,
, (host, port))] | drop-in replacement for :py:func:`socket.getaddrinfo` |
366,446 | def _load_multipolygon(tokens, string):
open_paren = next(tokens)
if not open_paren == :
raise ValueError(INVALID_WKT_FMT % string)
polygons = []
while True:
try:
poly = _load_polygon(tokens, string)
polygons.append(poly[])
t = next(tokens)
... | Has similar inputs and return value to to :func:`_load_point`, except is
for handling MULTIPOLYGON geometry.
:returns:
A GeoJSON `dict` MultiPolygon representation of the WKT ``string``. |
366,447 | def next_color(self):
next_rgb_color = ImageColor.getrgb(random.choice(BrBG_11.hex_colors))
return next_rgb_color | Returns the next color. Currently returns a random
color from the Colorbrewer 11-class diverging BrBG palette.
Returns
-------
next_rgb_color: tuple of ImageColor |
366,448 | def create_client(self, client_id, client_secret):
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.create_client(client_id, client_secret) | Create a new client for use by applications. |
366,449 | def import_signed(cls, name, certificate, private_key):
ca = ClientProtectionCA.create(name=name)
try:
ca.import_certificate(certificate)
ca.import_private_key(private_key)
except CertificateImportError:
ca.delete()
raise
return ca | Import a signed certificate and private key as a client protection CA.
This is a shortcut method to the 3 step process:
* Create CA with name
* Import certificate
* Import private key
Create the CA::
ClientProtectionCA.i... |
366,450 | def add_function(self, func):
try:
code = func.__code__
except AttributeError:
import warnings
warnings.warn("Could not extract a code object for the object %r"
% (func,))
return
if code not in self.c... | Record line profiling information for the given Python function. |
366,451 | def pipeline_name(self):
if in self.data:
return self.data.get()
elif self.pipeline is not None:
return self.pipeline.data.name | Get pipeline name of current stage instance.
Because instantiating stage instance could be performed in different ways and those return different results,
we have to check where from to get name of the pipeline.
:return: pipeline name. |
366,452 | def rectify_acquaintance_strategy(
circuit: circuits.Circuit,
acquaint_first: bool=True
) -> None:
if not is_acquaintance_strategy(circuit):
raise TypeError()
rectified_moments = []
for moment in circuit:
gate_type_to_ops = collections.defaultdict(list
... | Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
Args:
circuit: The acquaintance strategy to rectify.
acquaint_first: Whether to make acquaintance moment firs... |
366,453 | def get_tpm_status(d_info):
ipmicmd = ipmi_command.Command(bmc=d_info[],
userid=d_info[],
password=d_info[])
try:
response = _send_raw_command(ipmicmd, GET_TPM_STATUS)
if response... | Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status |
366,454 | def get_wd(self, path):
path = self.__format_path(path)
for iwd in self._wmd.items():
if iwd[1].path == path:
return iwd[0] | Returns the watch descriptor associated to path. This method
presents a prohibitive cost, always prefer to keep the WD
returned by add_watch(). If the path is unknown it returns None.
@param path: Path.
@type path: str
@return: WD or None.
@rtype: int or None |
366,455 | def quantile(self, q, dim=None, interpolation=,
numeric_only=False, keep_attrs=None):
if isinstance(dim, str):
dims = set([dim])
elif dim is None:
dims = set(self.dims)
else:
dims = set(dim)
_assert_empty([d for d in dims if... | Compute the qth quantile of the data along the specified dimension.
Returns the qth quantiles(s) of the array elements for each variable
in the Dataset.
Parameters
----------
q : float in range of [0,1] (or sequence of floats)
Quantile to compute, which must be betw... |
366,456 | def QA_SU_save_index_list(engine, client=DATABASE):
engine = select_save_engine(engine)
engine.QA_SU_save_index_list(client=client) | save index_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) |
366,457 | def create_cluster(cluster_dict, datacenter=None, cluster=None,
service_instance=None):
name**
schema = ESXClusterConfigSchema.serialize()
try:
jsonschema.validate(cluster_dict, schema)
except jsonschema.exceptions.ValidationError as exc:
raise InvalidConfigError(... | Creates a cluster.
Note: cluster_dict['name'] will be overridden by the cluster param value
config_dict
Dictionary with the config values of the new cluster.
datacenter
Name of datacenter containing the cluster.
Ignored if already contained by proxy details.
Default value ... |
366,458 | def gdalwarp(src, dst, options):
try:
out = gdal.Warp(dst, src, options=gdal.WarpOptions(**options))
except RuntimeError as e:
raise RuntimeError(.format(str(e), src, dst, options))
out = None | a simple wrapper for :osgeo:func:`gdal.Warp`
Parameters
----------
src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set
dst: str
the output data set
options: dict
additional parameters passed to gdal.Warp; see :osgeo:func:`gdal.WarpOption... |
366,459 | def horz_offset(self, offset):
if offset == 0.0:
self._remove_manualLayout()
return
manualLayout = self.get_or_add_manualLayout()
manualLayout.horz_offset = offset | Set the value of ./c:manualLayout/c:x@val to *offset* and
./c:manualLayout/c:xMode@val to "factor". Remove ./c:manualLayout if
*offset* == 0. |
366,460 | def add_lifecycle_delete_rule(self, **kw):
rules = list(self.lifecycle_rules)
rules.append(LifecycleRuleDelete(**kw))
self.lifecycle_rules = rules | Add a "delete" rule to lifestyle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. literalinclude:: snippets.py
:start-after: [START add_lifecycle_delete_rule]
:end-bef... |
366,461 | def randomBinaryField(self):
lst = [
b"hello world",
b"this is bytes",
b"awesome django",
b"djipsum is awesome",
b"\x00\x01\x02\x03\x04\x05\x06\x07",
b"\x0b\x0c\x0e\x0f"
]
return self.randomize(lst) | Return random bytes format. |
366,462 | def savefig(filename, path="figs", fig=None, ext=, verbose=False, **kwargs):
filename = os.path.join(path, filename)
final_filename = .format(filename, ext).replace(" ", "").replace("\n", "")
final_filename = os.path.abspath(final_filename)
final_path = os.path.dirname(final_filename)
if... | Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.
*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`. |
366,463 | def _find(api_method, query, limit, return_handler, first_page_size, **kwargs):
num_results = 0
if "limit" not in query:
query["limit"] = first_page_size
while True:
resp = api_method(query, **kwargs)
by_parent = resp.get()
descriptions = resp.get()
def format... | Takes an API method handler (dxpy.api.find*) and calls it with *query*,
and then wraps a generator around its output. Used by the methods below.
Note that this function may only be used for /system/find* methods. |
366,464 | def get_data_dir(module_name: str) -> str:
module_name = module_name.lower()
data_dir = os.path.join(BIO2BEL_DIR, module_name)
os.makedirs(data_dir, exist_ok=True)
return data_dir | Ensure the appropriate Bio2BEL data directory exists for the given module, then returns the file path.
:param module_name: The name of the module. Ex: 'chembl'
:return: The module's data directory |
366,465 | def do_list_cap(self, line):
def f(p, args):
for i in p.netconf.server_capabilities:
print(i)
self._request(line, f) | list_cap <peer> |
366,466 | def modified_Wilson_Tc(zs, Tcs, Aijs):
r
if not none_and_length_check([zs, Tcs]):
raise Exception()
C = -2500
Tcm = sum(zs[i]*Tcs[i] for i in range(len(zs)))
for i in range(len(zs)):
Tcm += C*zs[i]*log(zs[i] + sum(zs[j]*Aijs[i][j] for j in range(len(zs))))
return Tcm | r'''Calculates critical temperature of a mixture according to
mixing rules in [1]_. Equation
.. math::
T_{cm} = \sum_i x_i T_{ci} + C\sum_i x_i \ln \left(x_i + \sum_j x_j A_{ij}\right)T_{ref}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} = x_1 T_{c1} + x_2 T_{c2} + C[x_1 ... |
366,467 | def mavlink_packet(self, msg):
if not isinstance(self.checklist, mp_checklist.CheckUI):
return
if not self.checklist.is_alive():
return
type = msg.get_type()
master = self.master
if type == :
if self.mpstate.status.heart... | handle an incoming mavlink packet |
366,468 | def main():
if os.environ.get():
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logging.getLogger().setLevel(logging.ERROR)
cli_arguments = fix_hyphen_commands(docopt(__doc__, version=version))
| Provide main CLI entrypoint. |
366,469 | def references_json_authors(ref_authors, ref_content):
"build the authors for references json here for testability"
all_authors = references_authors(ref_authors)
if all_authors != {}:
if ref_content.get("type") in ["conference-proceeding", "journal", "other",
... | build the authors for references json here for testability |
366,470 | def convtable2dict(convtable, locale, update=None):
rdict = update.copy() if update else {}
for r in convtable:
if in r:
if locale in r:
rdict[r[]] = r[locale]
elif locale[:-1] == :
if locale in r:
for word in r.values():
... | Convert a list of conversion dict to a dict for a certain locale.
>>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items())
[('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('里茲', '利兹')] |
366,471 | def viewAt(self, point):
widget = self.childAt(point)
if widget:
return projexui.ancestor(widget, XView)
else:
return None | Looks up the view at the inputed point.
:param point | <QtCore.QPoint>
:return <projexui.widgets.xviewwidget.XView> || None |
366,472 | def insert_or_merge_entity(self, table_name, entity, timeout=None):
_validate_not_none(, table_name)
request = _insert_or_merge_entity(entity)
request.host = self._get_host()
request.query += [(, _int_to_str(timeout))]
request.path = _get_entity_path(table_name, entity[]... | Merges an existing entity or inserts a new entity if it does not exist
in the table.
If insert_or_merge_entity is used to merge an entity, any properties from
the previous entity will be retained if the request does not define or
include them.
:param str table_name:
... |
366,473 | def run_ppm_server(pdb_file, outfile, force_rerun=False):
if ssbio.utils.force_rerun(outfile=outfile, flag=force_rerun):
url =
files = {: open(pdb_file, )}
r = requests.post(url, files=files)
info = r.text
with open(outfile, ) as f:
f.write(info)
... | Run the PPM server from OPM to predict transmembrane residues.
Args:
pdb_file (str): Path to PDB file
outfile (str): Path to output HTML results file
force_rerun (bool): Flag to rerun PPM if HTML results file already exists
Returns:
dict: Dictionary of information from the PPM ... |
366,474 | def _use_tables(objs):
from ..models.widgets import TableWidget
return _any(objs, lambda obj: isinstance(obj, TableWidget)) | Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[Model or Document]) :
Returns:
bool |
366,475 | def update_replication_schedule(self, schedule_id, schedule):
return self._put("replications/%s" % schedule_id, ApiReplicationSchedule,
data=schedule, api_version=3) | Update a replication schedule.
@param schedule_id: The id of the schedule to update.
@param schedule: The modified schedule.
@return: The updated replication schedule.
@since: API v3 |
366,476 | def align_transcriptome(fastq_file, pair_file, ref_file, data):
work_bam = dd.get_work_bam(data)
base, ext = os.path.splitext(work_bam)
out_file = base + ".transcriptome" + ext
if utils.file_exists(out_file):
data = dd.set_transcriptome_bam(data, out_file)
return data
bowtie2 = ... | bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc |
366,477 | def proj_path(*path_parts):
path_parts = path_parts or []
if not os.path.isabs(path_parts[0]):
proj_path = _find_proj_root()
if proj_path is not None:
path_parts = [proj_path] + list(path_parts)
return os.path.normpath(os.path.join(*path_parts)) | Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path. |
366,478 | def between(arg, lower, upper):
lower = as_value_expr(lower)
upper = as_value_expr(upper)
op = ops.Between(arg, lower, upper)
return op.to_expr() | Check if the input expr falls between the lower/upper bounds
passed. Bounds are inclusive. All arguments must be comparable.
Returns
-------
is_between : BooleanValue |
366,479 | def all_tags_of_type(self, type_or_types, recurse_into_sprites = True):
for t in self.tags:
if isinstance(t, type_or_types):
yield t
if recurse_into_sprites:
for t in self.tags:
if isinstance(t, SWFTimelineContainer):
... | Generator for all tags of the given type_or_types.
Generates in breadth-first order, optionally including all sub-containers. |
366,480 | def _output(cls, fluents: Sequence[FluentPair]) -> Sequence[tf.Tensor]:
output = []
for _, fluent in fluents:
tensor = fluent.tensor
if tensor.dtype != tf.float32:
tensor = tf.cast(tensor, tf.float32)
output.append(tensor)
return tuple... | Converts `fluents` to tensors with datatype tf.float32. |
366,481 | def parse_file(self, fpath):
s base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read.
rb') as f:
return f.readlines() | Read a file on the file system (relative to salt's base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read. |
366,482 | def fost_hmac_url_signature(
key, secret, host, path, query_string, expires):
if query_string:
document = % (host, path, query_string, expires)
else:
document = % (host, path, expires)
signature = sha1_hmac(secret, document)
return signature | Return a signature that corresponds to the signed URL. |
366,483 | def configuration(self):
if self._configuration is None:
self._configuration = ConfigurationList(self)
return self._configuration | :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationList |
366,484 | def cleanup(self, ctime=None):
ctime = ctime or time.time()
if self.last_cleanup:
self.average_cleanup_time.add_point(ctime - self.last_cleanup)
self.last_cleanup = ctime
log.debug(, "Running cache cleanup().")
expire = list()
... | This method is called iteratively by the connection owning it.
Its job is to control the size of cache and remove old entries. |
366,485 | def _run_program(self, bin, fastafile, params=None):
params = self._parse_params(params)
fgfile = os.path.join(self.tmpdir, "AMD.in.fa")
outfile = fgfile + ".Matrix"
shutil.copy(fastafile, fgfile)
current_path = os.getcwd()
os.chdir(self.tmpdir)
... | Run AMD and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict, optional
Optional parameters. For some of the tools required par... |
366,486 | def enumerate_sources(self):
sources = []
for source_id in range(1, 17):
try:
name = yield from self.get_source_variable(source_id, )
if name:
sources.append((source_id, name))
except CommandException:
b... | Return a list of (source_id, source_name) tuples |
366,487 | def _tidy(self) -> None:
if self.no_overlap:
self.remove_overlap(self.no_contiguous)
else:
self._sort() | Removes overlaps, etc., and sorts. |
366,488 | def compile(self, options=[]):
try:
self._interface.nvrtcCompileProgram(self._program, options)
ptx = self._interface.nvrtcGetPTX(self._program)
return ptx
except NVRTCException as e:
log = self._interface.nvrtcGetProgramLog(self._program)
... | Compiles the program object to PTX using the compiler options
specified in `options`. |
366,489 | def cmdline_split(s: str, platform: Union[int, str] = ) -> List[str]:
if platform == :
platform = (sys.platform != )
if platform == 1:
re_cmd_lex = r([^|(\\.)|(&&?|\|\|?|\d?\>|[<])|([^\s
elif platform == 0:
re_cmd_lex = r
else:
raise AssertionError( % pla... | As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` injection etc. Using fast REGEX.
Args:
s:
string to split
... |
366,490 | def insert(name, table=, family=, **kwargs):
t take arguments should be passed in with an empty
string.
namechangesresultcommentruleschangeslocalerulesrulesrules__agg____agg__savesavesavesavesavelocalechangeschangeslocalechangeslocalecommentresultresultiptables.savechangeslocalechangeslocalecomment\nnametab... | .. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either i... |
366,491 | def calc_mean(c0, c1=[]):
if c1 != []:
return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2.
else:
return numpy.mean(c0, 0) | Calculates the mean of the data. |
366,492 | def add_interrupt_callback(gpio_id, callback, edge=, \
pull_up_down=PUD_OFF, threaded_callback=False, \
debounce_timeout_ms=None):
_rpio.add_interrupt_callback(gpio_id, callback, edge, pull_up_down, \
threaded_callback, debounce_timeout_ms) | Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='both').
`pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and
`RPIO.PUD_OFF`.
If `threaded_callback` is True, the callback will be started
inside a Thread.
If ... |
366,493 | def dataframe_except(df, *cols, **filters):
ii = np.ones(len(df), dtype=)
for (k,v) in six.iteritems(filters):
vals = df[k].values
if pimms.is_set(v): jj = np.isin(vals, list(v))
elif pimms.is_vector(v) and len(v) == 2: jj = (v[0] <= vals) & (vals < v[1])
... | dataframe_except(df, k1=v1, k2=v2...) yields df after selecting all the columns in which the
given keys (k1, k2, etc.) have been selected such that the associated columns in the dataframe
contain only the rows whose cells match the given values.
dataframe_except(df, col1, col2...) selects all columns ex... |
366,494 | def fcoe_get_login_input_fcoe_login_vlan(self, **kwargs):
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get_login")
config = fcoe_get_login
input = ET.SubElement(fcoe_get_login, "input")
fcoe_login_vlan = ET.SubElement(input, "fcoe-login-vlan")
... | Auto Generated Code |
366,495 | def _create_config_translation(cls, config, lang):
config.set_current_language(lang, initialize=True)
for field, data in cls.auto_setup[].items():
setattr(config, field, data)
config.save_translations() | Creates a translation for the given ApphookConfig
Only django-parler kind of models are currently supported.
``AutoCMSAppMixin.auto_setup['config_translated_fields']`` is used to fill in the data
of the instance for all the languages.
:param config: ApphookConfig instance
:par... |
366,496 | def ticket1to2(old):
if isinstance(old.benefactor, Multifactor):
types = list(chain(*[b.powerupNames for b in
old.benefactor.benefactors()]))
elif isinstance(old.benefactor, InitializerBenefactor):
types = list(chain(*[b.powerupNames for b in
old.ben... | change Ticket to refer to Products and not benefactor factories. |
366,497 | def get_boot_device(self):
operation =
try:
boot_device = None
boot_devices = get_children_by_dn(self.__handle, self.__boot_policy_dn)
if boot_devices:
for boot_device_mo in boot_devices:
if boot_device_mo.Order ==... | Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:raises: MissingParameterValue if a requ... |
366,498 | def set_project_path(self, path):
if path is None:
self.project_path = None
self.model().item(PROJECT, 0).setEnabled(False)
if self.currentIndex() == PROJECT:
self.setCurrentIndex(CWD)
else:
path = osp.abspath(path)
... | Sets the project path and disables the project search in the combobox
if the value of path is None. |
366,499 | def _calculate_cloud_ice_perc(self):
self.output(, normal=True, arrow=True)
a = rasterio.open(join(self.scene_path, self._get_full_filename())).read_band(1)
cloud_high_conf = int(, 2)
snow_high_conf = int(, 2)
fill_pixels = int(, 2)
cloud_mask = numpy.bitwise_an... | Return the percentage of pixels that are either cloud or snow with
high confidence (> 67%). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.