Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
350,700 | def query_rpdns(self):
results = requests.get(.format(self.get_data())).text.split()
jsonresults = []
for idx, r in enumerate(results):
if len(r) > 0:
jsonresults.append(json.loads(r))
return jsonresults | Queries robtex reverse pdns-api using an ip as parameter
:return: Dictionary containing results
:rtype: list |
350,701 | def on(signals, callback=None, max_calls=None):
if isinstance(callback, int) or callback is None:
if isinstance(callback, int):
callback, max_calls = max_calls, callback
return partial(_on, signals, max_calls=max_calls)
elif isinstance(callback, types.Metho... | Registers a single callback for receiving an event (or event list). Optionally,
can specify a maximum number of times the callback should receive a signal. This
method works as both a function and a decorator::
smokesignal.on('foo', my_callback)
@smokesignal.on('foo')
def my_callback()... |
350,702 | def _read_csv(self):
expected_header = self._csv_header()
for fname in self.datafiles:
with open(fname, encoding=) as f:
fields = next(csv.reader(f))
header = set(fields)
if len(header) < len(fields):
raise InvalidF... | :yields: asset nodes |
350,703 | def tbframes(tb):
frames=[tb.tb_frame]
while tb.tb_next: tb=tb.tb_next; frames.append(tb.tb_frame)
return frames | unwind traceback tb_next structure to array |
350,704 | def get_shape(self, ds_id, ds_info):
var_path = ds_info[]
shape = self[var_path + ]
if ((ds_info.get() == "longitude" or ds_info.get() == "latitude") and
ds_id.resolution == 10000):
return shape[0], int(shape[1] / 2)
return shape | Get output shape of specified dataset. |
350,705 | def _decrypt(self, value, encrypted_value):
if sys.platform == :
return self._decrypt_windows_chrome(value, encrypted_value)
if value or (encrypted_value[:3] != b):
return value
encrypted_value = encrypted_value[3:]
encrypted_value_ha... | Decrypt encoded cookies |
350,706 | def on_doctree_read(app, document):
literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document)
cache_mapping = uqbar.book.sphinx.group_literal_blocks_by_cache_path(literal_blocks)
node_mapping = {}
use_cache = bool(app.config["uqbar_book_use_cache"])
for cache_path, literal_block_group... | Hooks into Sphinx's ``doctree-read`` event. |
350,707 | def make_dataset_models(dataset, schemas_and_tables, metadata_dict = None, version: int = 1, include_contacts=False):
if metadata_dict is None:
metadata_dict={}
validate_types(schemas_and_tables)
dataset_dict = {}
cell_segment_model = make_cell_segment_model(dataset, version=version)
da... | make all the models for a dataset
Parameters
----------
dataset: str
name of dataset
table_and_types: list[(schema_name, table_name)]
list of tuples with types and model names to make
metadata_dict:
a dictionary with keys of table_names and values of metadata dicts needed
... |
350,708 | def run_exec(self, cmd, start_opts=None, globals_=None, locals_=None):
if globals_ is None:
globals_ = globals()
if locals_ is None:
locals_ = globals_
if not isinstance(cmd, types.CodeType):
cmd = cmd+
pass
self.core.start(start_o... | Run debugger on string `cmd' which will executed via the
builtin function exec. Arguments `globals_' and `locals_' are
the dictionaries to use for local and global variables. By
default, the value of globals is globals(), the current global
variables. If `locals_' is not given, it become... |
350,709 | def addAttachment(self, attachment):
if not isinstance(attachment, (list, tuple)):
attachment = [attachment]
original = self.getAttachment() or []
original = map(api.get_uid, original)
attachment = map(api.get_uid, attachment)
attachment ... | Adds an attachment or a list of attachments to the Analysis Request |
350,710 | def main(command_line=True, **kwargs):
version_num=pmag.get_version()
meas_file=
spec_file=
samp_file=
site_file=
csv_file=
ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
MagRecs=[]
citation="This study"
dir_path,demag=,
args=sys.argv
noave=0
dept... | NAME
iodp_srm_magic.py
DESCRIPTION
converts IODP LIMS and LORE SRM archive half sample format files to magic_measurements format files
SYNTAX
iodp_srm_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input .csv file, ... |
350,711 | def get_count_query(self):
return (
super().get_count_query()
.filter(models.DagModel.is_active)
.filter(~models.DagModel.is_subdag)
) | Default filters for model |
350,712 | def remove(self, matcher, obj):
current = self.subtree(matcher, False)
if current is None:
return
if current._use_dict:
try:
del current.matchers_dict[(obj, matcher)]
except KeyError:
pass
else:
... | Remove the matcher
:param matcher: an EventMatcher
:param obj: the object to remove |
350,713 | def has_parent(self, router):
parent = self
while parent and parent is not router:
parent = parent._parent
return parent is not None | Check if ``router`` is ``self`` or a parent or ``self`` |
350,714 | def _connection(self, value):
if isinstance(value, _Pipeline):
self._pipelined_connection = value
else:
self._direct_connection = value
self._pipelined_connection = None | If the value is a pipeline, save it as the connection to use for pipelines if to be shared
in threads or goot thread. Do not remove the direct connection.
If it is not a pipeline, clear it, and set the direct connection again. |
350,715 | def html_annotate(doclist, markup=default_markup):
tokenlist = [tokenize_annotated(doc, version)
for doc, version in doclist]
cur_tokens = tokenlist[0]
for tokens in tokenlist[1:]:
html_annotate_merge_annotations(cur_tokens, tokens)
cur_tokens =... | doclist should be ordered from oldest to newest, like::
>>> version1 = 'Hello World'
>>> version2 = 'Goodbye World'
>>> print(html_annotate([(version1, 'version 1'),
... (version2, 'version 2')]))
<span title="version 2">Goodbye</span> <span title="version 1... |
350,716 | def might_need_auth(f):
@wraps(f)
def wrapper(cli_args):
try:
return_value = f(cli_args)
except UnauthorizedException as e:
config = config_from_env(config_from_file())
username = _get_username(cli_args, config)
if username is None:
... | Decorate a CLI function that might require authentication.
Catches any UnauthorizedException raised, prints a helpful message and
then exits. |
350,717 | def fail(self, text=None):
return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) | Shows and persists fail symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside fail symbol.
Returns
-------
self |
350,718 | def process_m2m(self, obj, pk_set=None, action=None, update_fields=None, cache_key=None, **kwargs):
if action not in (None, , , , ):
return
if action == :
build_kwargs = self.remove_cache.take(cache_key)
else:
build_kwargs = self._get_build_kwargs(ob... | Process signals from dependencies.
Remove signal is processed in two parts. For details see:
:func:`~Dependency.connect` |
350,719 | def from_graph(cls, graph, length=0):
nodes = []
hyper = []
edges = defaultdict(list)
j = 0
for i, node in enumerate(graph.nodes_iter()):
nodes.append(node)
preds = graph.in_edges(node, data=True)
l = len(preds)
if length... | Creates a hypergraph (expanded graph) from a :class:`caspo.core.graph.Graph` object instance
Parameters
----------
graph : :class:`caspo.core.graph.Graph`
The base interaction graph to be expanded
length : int
Maximum length for hyperedges source sets. If 0, use... |
350,720 | def get_aggregate_balance(self, _async=False):
params = {}
path =
return api_key_get(params, path, _async=_async) | 查询所有子账户汇总
:param _async: 是否异步执行
:return: |
350,721 | def _read_weights(self):
weights = []
grams_per_pound = 453.592
for ser in self._serials:
ser.write()
ser.flush()
time.sleep(0.02)
for ser in self._serials:
try:
output_str = ser.readline()
we... | Reads weights from each of the load cells. |
350,722 | def resetCustomConfig(cls):
_getLogger().info("Resetting all custom configuration properties; "
"caller=%r", traceback.format_stack())
super(Configuration, cls).clear()
_CustomConfigurationFileWrapper.clear(persistent=True) | Clear all custom configuration settings and delete the persistent
custom configuration store. |
350,723 | def kl_reverse(logu, self_normalized=False, name=None):
with tf.compat.v1.name_scope(name, "kl_reverse", [logu]):
return amari_alpha(logu, alpha=0., self_normalized=self_normalized) | The reverse Kullback-Leibler Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the KL-reverse Csiszar-function is:
```none
f(u) = -log(u) + (u - 1)
```
When `self_normalized = False` the `(u - 1)` term is om... |
350,724 | def schnabel_eskow(mat, eps=1e-16):
mat = numpy.asfarray(mat)
tau = eps**(1/3.)
size = mat.shape[0]
mat0 = mat
mat = 1*mat
err = numpy.zeros(size, dtype=float)
perm = numpy.eye(size)
gamma = abs(mat.diagonal()).max()
def invariant(mat, k):
... | Scnabel-Eskow algorithm for modified Cholesky factorisation algorithm.
Args:
mat (numpy.ndarray) : Must be a non-singular and symmetric matrix If
sparse, the result will also be sparse.
eps (float) : Error tolerance used in algorithm.
Returns
-------
perm : 2d array
... |
350,725 | def __configure_roles(mapper, cls):
cls.__roles__ = deepcopy(cls.__roles__)
processed = set()
for base in cls.__mro__:
for name, attr in base.__dict__.items():
if name in processed or name.startswith():
continue
... | Run through attributes of the class looking for role decorations from
:func:`with_roles` and add them to :attr:`cls.__roles__` |
350,726 | def bourgain_embedding_matrix(distance_matrix):
distance_matrix = np.array(distance_matrix)
n = len(distance_matrix)
if n == 1:
return distance_matrix
np.random.seed(123)
distort_elements = []
r = range(n)
k = int(math.ceil(math.log(n) / math.log(2) - 1))
t = int(math.ceil(m... | Use Bourgain algorithm to embed the neural architectures based on their edit-distance.
Args:
distance_matrix: A matrix of edit-distances.
Returns:
A matrix of distances after embedding. |
350,727 | def transpose(self) -> :
out = TextDiagramDrawer()
out.entries = {(y, x): _DiagramText(v.transposed_text, v.text)
for (x, y), v in self.entries.items()}
out.vertical_lines = [_VerticalLine(*e)
for e in self.horizontal_lines]
o... | Returns the same diagram, but mirrored across its diagonal. |
350,728 | def motion_commanded(self):
rsp = self.driver.send_command(, immediate=True)
if self.driver.command_error(rsp) or len(rsp[4]) != 1 \
or rsp[4][0][0:4] != :
return False
else:
return (rsp[4][0][4] == ) | Whether motion is commanded or not.
``bool``
Can't be set.
Notes
-----
It is the value of the first bit of the 'TAS' command. |
350,729 | def DueToRun(self):
if self.Get(self.Schema.DISABLED):
return False
cron_args = self.Get(self.Schema.CRON_ARGS)
last_run_time = self.Get(self.Schema.LAST_RUN_TIME)
now = rdfvalue.RDFDatetime.Now()
if (last_run_time is None or
now > cron_args.periodicity.Expiry(last_run_time... | Called periodically by the cron daemon, if True Run() will be called.
Returns:
True if it is time to run based on the specified frequency. |
350,730 | def setXlimits(self, lims):
self.responseSignalPlot.setXlim(lims)
self.stimSignalPlot.setXlim(lims) | Sets the X axis limits of the signal plots
:param lims: (min, max) of x axis, in same units as data
:type lims: (float, float) |
350,731 | def _date_to_datetime(value):
if not isinstance(value, datetime.date):
raise TypeError(
% value)
return datetime.datetime(value.year, value.month, value.day) | Convert a date to a datetime for Cloud Datastore storage.
Args:
value: A datetime.date object.
Returns:
A datetime object with time set to 0:00. |
350,732 | def is_open_chunk(self, chk):
cs = self.get_chunk_status(chk)
if cs & 0x4 != 0:
return True
return False | Check the chunk is free or not |
350,733 | def open(dataset_dir, access_mode=READ_ONLY_ACCESS):
if access_mode == WRITE_ACCESS:
raise ValueError()
try:
config_filename = os.path.join(dataset_dir, )
config = json.load(open(config_filename, ))
except:
... | Opens a tensor dataset. |
350,734 | def get_object(self, queryset=None):
if self._cached_object is None:
self._cached_object = super(EntryCacheMixin, self).get_object(
queryset)
return self._cached_object | Implement cache on ``get_object`` method to
avoid repetitive calls, in POST. |
350,735 | def update(cls, resource, new_name, algorithm, ssl_enable, ssl_disable):
params = {}
if new_name:
params[] = new_name
if algorithm:
params[] = {: algorithm}
if ssl_enable:
params[] = ssl_enable
if ssl_disable:
params[] = Fa... | Update a webaccelerator |
350,736 | def model_schema(
model: Type[], by_alias: bool = True, ref_prefix: Optional[str] = None
) -> Dict[str, Any]:
ref_prefix = ref_prefix or default_prefix
flat_models = get_flat_models_from_model(model)
model_name_map = get_model_name_map(flat_models)
m_schema, m_definitions = model_process_schema... | Generate a JSON Schema for one model. With all the sub-models defined in the ``definitions`` top-level
JSON key.
:param model: a Pydantic model (a class that inherits from BaseModel)
:param by_alias: generate the schemas using the aliases defined, if any
:param ref_prefix: the JSON Pointer prefix for s... |
350,737 | def fetch(self, is_dl_forced=False):
file_paths = self._get_file_paths(self.tax_ids, )
self.get_files(is_dl_forced, file_paths)
self.get_files(is_dl_forced, self.id_map_files) | Override Source.fetch()
Fetches resources from String
We also fetch ensembl to determine if protein pairs are from
the same species
Args:
:param is_dl_forced (bool): Force download
Returns:
:return None |
350,738 | def load_values(self):
for config_name, evar in self.evar_defs.items():
if evar.is_required and evar.name not in os.environ:
raise RuntimeError((
"Missing required environment variable: {evar_name}\n"
"{help_txt}"
).fo... | Go through the env var map, transferring the values to this object
as attributes.
:raises: RuntimeError if a required env var isn't defined. |
350,739 | def get_content(self, language, ctype, language_fallback=False):
return Content.objects.get_content(self, language, ctype,
language_fallback) | Shortcut method for retrieving a piece of page content
:param language: wanted language, if not defined default is used.
:param ctype: the type of content.
:param fallback: if ``True``, the content will also be searched in \
other languages. |
350,740 | def _find_hstreaming():
global WARNED_HADOOP_HOME, HADOOP_STREAMING_PATH_CACHE
if HADOOP_STREAMING_PATH_CACHE:
return HADOOP_STREAMING_PATH_CACHE
try:
search_root = os.environ[]
except KeyError:
search_root =
cmd = % (search_root)
p = subprocess.Popen(cmd.split(), ... | Finds the whole path to the hadoop streaming jar.
If the environmental var HADOOP_HOME is specified, then start the search
from there.
Returns:
Full path to the hadoop streaming jar if found, else return an empty
string. |
350,741 | def calculate_tree_differences(self, pytree, doctree):
pykeys = set(pytree.keys())
dockeys = set(doctree.keys())
missing_doc_keys = pykeys - dockeys
missing_docs = {pytree[pyfile] for pyfile in missing_doc_keys}
missing_py_keys = dockeys - pykeys
... | Calculate the differences between the given trees.
:param dict pytree: The dictionary of the parsed Python tree.
:param dict doctree: The dictionary of the parsed documentation tree.
:rtype: tuple
:returns: A two-tuple of sets, where the first is the missing Python files, and the second... |
350,742 | def list_actions():
for name, action in _current_actions.items():
click.echo(.format(
name, if hasattr(action, ) else
)) | List all registered actions. |
350,743 | def show_portindex_interface_info_output_show_portindex_interface_show_portindex_port_type(self, **kwargs):
config = ET.Element("config")
show_portindex_interface_info = ET.Element("show_portindex_interface_info")
config = show_portindex_interface_info
output = ET.SubElement(sho... | Auto Generated Code |
350,744 | def get_stability_criteria(self, s, n):
n = get_uvec(n)
stress = s * np.outer(n, n)
sym_wallace = self.get_symmetric_wallace_tensor(stress)
return np.linalg.det(sym_wallace.voigt) | Gets the stability criteria from the symmetric
Wallace tensor from an input vector and stress
value.
Args:
s (float): Stress value at which to evaluate
the stability criteria
n (3x1 array-like): direction of the applied
stress |
350,745 | def build(self, limit_states, discretization, steps_per_interval):
new = copy.copy(self)
add_zero = (self.format == and
self.nodamage and self.nodamage <= self.imls[0])
new.imls = build_imls(new, discretization)
if steps_per_interval > 1:
new.int... | :param limit_states: a sequence of limit states
:param discretization: continouos fragility discretization parameter
:param steps_per_interval: steps_per_interval parameter
:returns: a populated FragilityFunctionList instance |
350,746 | def insertBulkBlock(self):
try:
body = request.body.read()
indata = cjson.decode(body)
if (indata.get("file_parent_list", []) and indata.get("dataset_parent_list", [])):
dbsExceptionHandler("dbsException-invalid-input2", "insertBulkBlock: dataset and... | API to insert a bulk block
:param blockDump: Output of the block dump command
:type blockDump: dict |
350,747 | def blob_to_pyasn1(blob):
return pyasn1.codec.der.decoder.decode(
blob,
asn1Spec=pyasn1_modules.rfc2459.Certificate()
)[0] | Convert an ASN.1 encoded certificate (such as obtained from
:func:`extract_blob`) to a :mod:`pyasn1` structure and return the result. |
350,748 | def write_path(target, path, value, separator=):
parts = path.split(separator)
current = target
for part in parts[:-1]:
if part not in current:
current[part] = current = {}
else:
current = current[part]
current[parts[-1]] = value | Write a value deep into a dict building any intermediate keys.
:param target: a dict to write data to
:param path: a key or path to a key (path is delimited by `separator`)
:param value: the value to write to the key
:keyword separator: the separator used in the path (ex. Could be "." for a
jso... |
350,749 | def _zipped(self, docs_base):
with pushd(docs_base):
with tempfile.NamedTemporaryFile(prefix=, delete=False) as ziphandle:
pass
zip_name = shutil.make_archive(ziphandle.name, )
notify.info("Uploading {:.1f} MiB from to ..."
.format(o... | Provide a zipped stream of the docs tree. |
350,750 | def file_handle(fnh, mode="rU"):
handle = None
if isinstance(fnh, file):
if fnh.closed:
raise ValueError("Input file is closed.")
handle = fnh
elif isinstance(fnh, str):
handle = open(fnh, mode)
return handle | Takes either a file path or an open file handle, checks validity and returns an open
file handle or raises an appropriate Exception.
:type fnh: str
:param fnh: It is the full path to a file, or open file handle
:type mode: str
:param mode: The way in which this file will be used, for example to re... |
350,751 | def _cmd_run(cmd):
cmd.insert(0, )
cmd_ret = __salt__[](cmd, ignore_retcode=True)
if cmd_ret[] != 0:
log.debug(, cmd,
cmd_ret[])
return cmd_ret[] | Run the aptly command.
:return: The string output of the command.
:rtype: str |
350,752 | def get_range_selector(steps=[,],bgcolor=,x=0,y=0.9,
visible=True,**kwargs):
import string
def get_step(s):
term=[]
stepmode=
_s=s
_s=_s.replace(,)
_s=_s.lower()
if _s in [,]:
return {:1,:s,:}
if _s[-2:]==:
_s=_s[:-2]
stepmode=
if _s[0] not in string.digits:
_s=+_s
if _s[0] ... | Returns a range selector
Reference: https://plot.ly/python/reference/#layout-xaxis-rangeselector
Parameters:
-----------
steps : string or list(string)
Steps for the range
Examples:
['1y','2 months','5 weeks','ytd','2mtd']
bgocolor : string or tuple(color,alpha)
Background color
Examples:
... |
350,753 | def jsonify(obj):
if hasattr(obj, ):
d = obj.to_json()
_push_metadata(d, obj)
return jsonify(d)
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, (np.int32, np.int64)):
return int(obj)
if isinstance(obj, np.float64):
... | Return a JSON-encodable representation of an object, recursively using
any available ``to_json`` methods, converting NumPy arrays and datatypes to
native lists and types along the way. |
350,754 | def _phir(self, rho, T, x):
Tc12 = 0.9648407/2*(IAPWS95.Tc+NH3.Tc)
Tn = (1-x)**2*IAPWS95.Tc + x**2*NH3.Tc + 2*x*(1-x**1.125455)*Tc12
dTnx = -2*IAPWS95.Tc*(1-x) + 2*x*NH3.Tc + 2*Tc12*(1-x**1.125455) - \
2*Tc12*1.12455*x**1.12455
b = 0.8978069
... | Residual contribution to the free Helmholtz energy
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
x : float
Mole fraction of ammonia in mixture, [mol/mol]
Returns
-------
prop : dict
... |
350,755 | def wrap_json(cls, json):
u = User(usertype=json[],
name=json[],
logo=json[],
twitchid=json[],
displayname=json[],
bio=json[])
return u | Create a User instance for the given json
:param json: the dict with the information of the user
:type json: :class:`dict` | None
:returns: the new user instance
:rtype: :class:`User`
:raises: None |
350,756 | def query(cls, name=None, offset=None, limit=None, api=None):
api = api or cls._API
return super(Automation, cls)._query(
url=cls._URL[],
name=name,
offset=offset,
limit=limit,
api=api,
) | Query (List) automations.
:param name: Automation name.
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return: collection object |
350,757 | def item_selection_changed(self):
is_selection = len(self.selectedItems()) > 0
self.expand_selection_action.setEnabled(is_selection)
self.collapse_selection_action.setEnabled(is_selection) | Item selection has changed |
350,758 | def sysrq(vm, action=, key=):
vm***
ret = {}
if key not in [, , ]:
ret[] =
return ret
if action not in [, ]:
ret[] =
return ret
vm = lookup(.format(key, vm), one=True)
if in vm:
return vm
cmd = .format(
uuid=vm,
action=action
... | Send non-maskable interrupt to vm or capture a screenshot
vm : string
vm to be targeted
action : string
nmi or screenshot -- Default: nmi
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*' vmadm.sysrq 186da9a... |
350,759 | def create_toc(doctree, depth=9223372036854775807, writer_name=,
exclude_first_section=True, href_prefix=None, id_prefix=):
doctree = doctree.deepcopy()
doctree.settings.auto_id_prefix = id_prefix
details = {
: depth,
}
startnode = None
if ... | Create a Table of Contents (TOC) from the given doctree
Returns: (docutils.core.Publisher instance, output string)
`writer_name`: represents a reST writer name and determines the type of
output returned.
Example:
pub = blazeutils.rst.rst2pub(toc_rst)
pub, html_output = blazeutils... |
350,760 | def _all_shorten(self):
self.shorten = not self.shorten
urls = iter(self.urls)
for item in self.items:
if isinstance(item, urwid.Columns):
item[1].set_label(shorten_url(next(urls),
self.size[... | S |
350,761 | def __execute_validations(self, validations, data, property_name, ancestors, negation=False, prefix=None):
if not isinstance(ancestors, OrderedDict):
raise TypeError("ancestors must be an OrderedDict. type: {0} was passed.".format(type(ancestors)))
if not isinstance(validations, di... | Validate the data for a specific configuration value. This method will look up all of the validations provided
and dynamically call any validation methods. If a validation fails a error will be thrown. If no errors are found
a attributes will be dynamically created on the Config object for the configur... |
350,762 | def minimal_random_graph(num_vertices, seed=None, **kwargs):
if isinstance(seed, numbers.Integral):
np.random.seed(seed)
points = np.random.random((num_vertices, 2)) * 10
edges = []
for k in range(num_vertices - 1):
for j in range(k + 1, num_vertices):
v = points[k] - ... | Creates a connected graph with random vertex locations.
Parameters
----------
num_vertices : int
The number of vertices in the graph.
seed : int (optional)
An integer used to initialize numpy's psuedorandom number
generators.
**kwargs :
Unused.
Returns
-----... |
350,763 | def describe_jobflows(self, states=None, jobflow_ids=None,
created_after=None, created_before=None):
params = {}
if states:
self.build_list_params(params, states, )
if jobflow_ids:
self.build_list_params(params, jobflow_ids, )
... | Retrieve all the Elastic MapReduce job flows on your account
:type states: list
:param states: A list of strings with job flow states wanted
:type jobflow_ids: list
:param jobflow_ids: A list of job flow IDs
:type created_after: datetime
:param created_after: Bound on j... |
350,764 | def parse_ensembl_gene_request(result):
LOG.info("Parsing genes from request")
for index, row in result.iterrows():
ensembl_info = {}
if type(row[]) is float:
continue
ensembl_info[] = row[]
ensembl_info[] = int(row[])
en... | Parse a dataframe with ensembl gene information
Args:
res(pandas.DataFrame)
Yields:
gene_info(dict) |
350,765 | def resolve_url(to, *args, **kwargs):
from compat import six, force_text
if not in to and not in to:
raise
return to | Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the name.
* A URL, which will be returned... |
350,766 | def shape(self, i=0):
shp = self.__getFileObj(self.shp)
i = self.__restrictIndex(i)
offset = self.__shapeIndex(i)
if not offset:
for j,k in enumerate(self.iterShapes()):
if j == i:
return k
shp.seek(of... | Returns a shape object for a shape in the the geometry
record file. |
350,767 | def include_callback_query_chat_id(fn=pair, types=):
@_ensure_seeders_list
def p(seeders, delegator_factory, *args, **kwargs):
return fn(seeders + [per_callback_query_chat_id(types=types)],
delegator_factory, *args, include_callback_query=True, **kwargs)
return p | :return:
a pair producer that enables static callback query capturing
across seeder and delegator.
:param types:
``all`` or a list of chat types (``private``, ``group``, ``channel``) |
350,768 | def get_github_cache(self, kind, key_):
cache = {}
res_size = 100
from_ = 0
index_github = "github/" + kind
url = self.elastic.url + "/" + index_github
url += "/_search" + "?" + "size=%i" % res_size
r = self.requests.get(url)
type_items = r.j... | Get cache data for items of _type using key_ as the cache dict key |
350,769 | def find_files(filenames, recursive, exclude):
while filenames:
name = filenames.pop(0)
if recursive and os.path.isdir(name):
for root, directories, children in os.walk(name):
filenames += [os.path.join(root, f) for f in children
if matc... | Yield filenames. |
350,770 | def _set_transmaps(self):
if self._std == :
self._lower_chars = string.ascii_lowercase
self._upper_chars = string.ascii_uppercase
elif self._std == :
self._lower_chars = (string.ascii_lowercase +
.join(chr(i) for i in range(1... | Set translation maps for our standard. |
350,771 | def add_error(self, code, line, char, description):
if code not in self.violations:
self.violations[code] = 0
self.violations[code] += 1
self.lines.append((code, line, char, description)) | Registers an error for this container with code on line at char.
:param code: The PEP 8 error code
:param line: The line number of the reported error
:param char: Line location of first offending character
:param description: The human readable description of the thrown error/warning |
350,772 | def load_into_collection_from_file(collection, filename,
content_type=None):
if content_type is None:
ext = os.path.splitext(filename)[1]
try:
content_type = MimeTypeRegistry.get_type_for_extension(ext)
except KeyError:
raise Va... | Loads resources from the specified file into the given collection
resource.
If no content type is provided, an attempt is made to look up the
extension of the given filename in the MIME content type registry. |
350,773 | def create_tileset(ctx, dataset, tileset, name):
access_token = (ctx.obj and ctx.obj.get()) or None
service = mapbox.Uploader(access_token=access_token)
uri = "mapbox://datasets/{username}/{dataset}".format(
username=tileset.split()[0], dataset=dataset)
res = service.create(uri, tileset,... | Create a vector tileset from a dataset.
$ mapbox datasets create-tileset dataset-id username.data
Note that the tileset must start with your username and the dataset
must be one that you own. To view processing status, visit
https://www.mapbox.com/data/. You may not generate another tilesets
f... |
350,774 | def format(self, maxline=0, pstyle=, nline=None, extend=True):
if nline is not None and maxline == 0:
maxline = nline
if maxline is True:
maxline = sys.maxsize
if maxline is False or maxline is None:
maxline = -1
... | Formats fit output details into a string for printing.
The output tabulates the ``chi**2`` per degree of freedom of the fit
(``chi2/dof``), the number of degrees of freedom, the ``Q`` value of
the fit (ie, p-value), and the logarithm of the Gaussian Bayes Factor
for the fit (``logGBF``... |
350,775 | async def on_raw_kill(self, message):
by, bymeta = self._parse_user(message.source)
target, targetmeta = self._parse_user(message.params[0])
reason = message.params[1]
self._sync_user(target, targetmeta)
if by in self.users:
self._sync_user(by, bymeta)
... | KILL command. |
350,776 | def simBirth(self,which_agents):
IndShockConsumerType.simBirth(self,which_agents)
if not self.global_markov:
N = np.sum(which_agents)
base_draws = drawUniform(N,seed=self.RNG.randint(0,2**31-1))
Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit))
... | Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and
discrete states. Calls IndShockConsumerType.simBirth, then draws from initial Markov distribution.
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.Agen... |
350,777 | def force_list(data):
if data is None:
return []
elif not isinstance(data, (list, tuple, set)):
return [data]
elif isinstance(data, (tuple, set)):
return list(data)
return data | Force ``data`` to become a list.
You should use this method whenever you don't want to deal with the
fact that ``NoneType`` can't be iterated over. For example, instead
of writing::
bar = foo.get('bar')
if bar is not None:
for el in bar:
...
you can write::... |
350,778 | def get_changed_files(self, first_sha, second_sha, exclude_paths=None):
if not exclude_paths:
exclude_paths = []
first_commit = self.repo.commit(first_sha)
second_commit = self.repo.commit(second_sha)
diffs = first_commit.diff(second_commit)
changed_files =... | :param first_sha:
:param second_sha:
:param exclude_paths:
:return: |
350,779 | def move_content_to_origin(self):
tcs = list(self.iter_tcs())
origin_tc = tcs[0]
for spanned_tc in tcs[1:]:
origin_tc.append_ps_from(spanned_tc) | Move all paragraphs in range to origin cell. |
350,780 | def _check_gle_response(result):
_check_command_response(result)
if result.get("wtimeout", False):
raise WTimeoutError(result.get("errmsg", result.get("err")),
result.get("code"),
result)
error_msg = resul... | Return getlasterror response as a dict, or raise OperationFailure. |
350,781 | def __setup_connection(self):
if self.payload != None and type(self.payload) is dict and in self.payload:
config.plugin_client_settings = self.payload[]
config.offline = self.args.offline
config.connection = PluginConnection(
client=self.args.client or ,
... | each operation requested represents a session
the session holds information about the plugin running it
and establishes a project object |
350,782 | def tags(self):
tags = self.config.get(, {})
env_tags = os.environ.get(, )
if env_tags:
for kv in env_tags.split():
key, value = kv.split()
tags[key.strip()] = value.strip()
return tags | :return: Returns tags from config and `JAEGER_TAGS` environment variable
to use as process-wide tracer tags |
350,783 | def handle(cls, value, **kwargs):
value = read_value_from_path(value)
table_info = None
table_keys = None
region = None
table_name = None
if in value:
table_info, table_keys = value.split(, 1)
if in table_info:
region, ta... | Get a value from a dynamodb table
dynamodb field types should be in the following format:
[<region>:]<tablename>@<primarypartionkey>:<keyvalue>.<keyvalue>...
Note: The region is optional, and defaults to the environment's
`AWS_DEFAULT_REGION` if not specified. |
350,784 | def extractRuntime(runtime_dirs):
names = [str(item) for name in runtime_dirs for item in os.listdir(name)]
string = .join(names)
result = extract(RUNTIME_PATTERN, string, condense=True)
return result | Used to find the correct static lib name to pass to gcc |
350,785 | def _process_ddg2p_annotations(self, limit):
line_counter = 0
if self.graph is not None:
graph = self.graph
else:
graph = self.graph
hgnc = HGNC(self.graph_type, self.are_bnodes_skolemized)
hgnc_symbol_id_map = hgnc.get_symbol_id_map()
... | The ddg2p annotations associate a gene symbol to an omim disease,
along with some HPO ids and pubs. The gene symbols come from gencode,
which in turn come from HGNC official gene symbols. Therefore,
we use the HGNC source class to get the id/symbol mapping for
use in our annotations her... |
350,786 | def text(self):
if self.driver.w3c:
return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"]
else:
return self.driver.execute(Command.GET_ALERT_TEXT)["value"] | Gets the text of the Alert. |
350,787 | def create_peaklist(self, spectrum, chain, chain_idx, source):
sequence_sites = self.create_sequence_sites(chain, spectrum.seq_site_length)
spin_systems = []
peaklist = plsimulator.PeakList(spectrum.name, spectrum.labels, source, chain_idx)
for seq_site in sequence_sites:
... | Create peak list file.
:param spectrum: Spectrum object instance.
:type spectrum: :class:`~nmrstarlib.plsimulator.Spectrum`
:param dict chain: Chain object that contains chemical shift values and assignment information.
:param int chain_idx: Protein chain index.
:param str sourc... |
350,788 | def wait(self, timeout=None):
if timeout is None:
timeout = self._timeout
while self._process.check_readable(timeout):
self._flush() | Wait for response until timeout.
If timeout is specified to None, ``self.timeout`` is used.
:param float timeout: seconds to wait I/O |
350,789 | def get_mesh(sitecol, complete=True):
sc = sitecol.complete if complete else sitecol
if sc.at_sea_level():
mesh = numpy.zeros(len(sc), [(, F64), (, F64)])
mesh[] = sc.lons
mesh[] = sc.lats
else:
mesh = numpy.zeros(len(sc), [(, F64), (, F64),
... | :returns:
a lon-lat or lon-lat-depth array depending if the site collection
is at sea level or not |
350,790 | def diff_to_new_interesting_lines(unified_diff_lines: List[str]
) -> Dict[int, str]:
interesting_lines = dict()
for diff_line in unified_diff_lines:
if not diff_line.startswith():
continue
change = diff_line[3:diff_line.index(, 3)]
... | Extracts a set of 'interesting' lines out of a GNU unified diff format.
Format:
gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html
@@ from-line-numbers to-line-numbers @@
line-from-either-file
...
@@ start,count start,count @@
line-from-either-file
... |
350,791 | def NextToken(self):
self._previous_line = self._line
self._previous_column = self._column
self._column += len(self.token)
self._SkipWhitespace()
if not self._more_lines:
self.token =
return
match = self._TOKEN.match(self._current_line, self._column)
if not match and not... | Reads the next meaningful token. |
350,792 | async def close(self):
if self._conn is None:
return
await self._run_operation(self._impl.close)
self._conn = None | Close the cursor now (rather than whenever __del__ is called).
The cursor will be unusable from this point forward; an Error
(or subclass) exception will be raised if any operation is attempted
with the cursor. |
350,793 | def DyStrData(cls, name, regx, index = 0):
123
text = Web.PageSource()
if not text:
return
if not isinstance(regx, re._pattern_type):
raise Exception("DyStrData need the arg which have compiled the regular expression.")
values = regx.f... | set dynamic value from the string data of response
@param name: glob parameter name
@param regx: re._pattern_type
e.g.
DyStrData("a",re.compile('123')) |
350,794 | def override_subcommand(section_name, section_items, args):
_boolean_states = {: True, : True, : True,
: False, : False, : False}
for k, v, in section_items:
try:
normalized_value = v.lower()
except AttributeError:
... | Given a specific section in the configuration file that maps to
a subcommand (except for the global section) read all the keys that are
actual argument flags and slap the values for that one subcommand.
Return the altered ``args`` object at the end. |
350,795 | def get_freesurfer_dir(directory):
dir_files = [f for f in os.listdir(directory)]
if in dir_files and in dir_files:
return directory
for f in os.listdir(directory):
sub_dir = os.path.join(directory, f)
if os.path.isdir(sub_dir):
if get_freesurfer_dir... | Find a subfolder in the given directory that contains a Freesurfer
anatomy (this may be the directory itself). Currently, the test is whether
there are sub-folders with name 'surf' and 'mri'. Processes all sub-folders
recursively until a freesurfer directory is found. If no matching folder is
found the ... |
350,796 | def append(name,
text=None,
makedirs=False,
source=None,
source_hash=None,
template=,
sources=None,
source_hashes=None,
defaults=None,
context=None,
ignore_whitespace=True):
ret = {: name,
:... | Ensure that some text appears at the end of a file.
The text will not be appended if it already exists in the file.
A single string of text or a list of strings may be appended.
name
The location of the file to append to.
text
The text to be appended, which can be a single string or a... |
350,797 | def get_true_function(obj):
"Returns the actual function and a boolean indicated if this is a method or not."
if not callable(obj):
raise TypeError("%r is not callable." % (obj,))
ismethod = inspect.ismethod(obj)
if inspect.isfunction(obj) or ismethod:
return obj, ismethod
if hasattr... | Returns the actual function and a boolean indicated if this is a method or not. |
350,798 | def build_artefact(self, src_project=None):
path_to_zip_file = self.build.run(src_project or self.config.get_projectdir())
self.set_artefact_path(path_to_zip_file)
deploy_method = self.config["deploy"]["deploy_method"]
if deploy_method == "S3":
deploy_bucket = self... | Run deploy the lambdas defined in our project.
Steps:
* Build Artefact
* Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"]
:param src_project: str. Name of the folder or path of the project where our code lives
:return: bool |
350,799 | def manhattan(x, y):
result = 0.0
for i in range(x.shape[0]):
result += np.abs(x[i] - y[i])
return result | Manhatten, taxicab, or l1 distance.
..math::
D(x, y) = \sum_i |x_i - y_i| |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.