Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
363,800 | def midi_inputs(self):
return self.client.get_ports(is_midi=True, is_physical=True, is_input=True) | :return: A list of MIDI input :class:`Ports`. |
363,801 | def full(self):
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n | Return True if the queue is full, False otherwise (not reliable!). |
363,802 | def partition(cls, iterable, pred):
t1, t2 = itertools.tee(iterable)
return cls(itertools.filterfalse(pred, t1), filter(pred, t2)) | Use a predicate to partition items into false and true entries. |
363,803 | def finish_plot():
plt.legend()
plt.grid(color=)
plt.xlabel()
plt.ylabel()
plt.show() | Helper for plotting. |
363,804 | def load_network(self, layers=1):
if layers:
ctor = payload_type(self.type)[0]
if ctor:
ctor = ctor
payload = self.payload
self.payload = ctor(payload, layers - 1)
else:
pass | Given an Ethernet frame, determine the appropriate sub-protocol;
If layers is greater than zerol determine the type of the payload
and load the appropriate type of network packet. It is expected
that the payload be a hexified string. The layers argument determines
how many layers to desc... |
363,805 | def remove_symbol_add_symbol(string_item, remove_symbol, add_symbol):
string_item = add_symbol.join(string_item.split(remove_symbol))
return string_item | Remove a symbol from a string, and replace it with a different one
Args:
string_item: String that you want to replace symbols in
remove_symbol: Symbol to remove
add_symbol: Symbol to add
Returns: returns a string with symbols swapped |
363,806 | def GenomicRangeFromString(range_string,payload=None,dir=None):
m = re.match(,range_string)
if not m:
sys.stderr.write("ERROR bad genomic range string\n"+range_string+"\n")
sys.exit()
chr = m.group(1)
start = int(m.group(2))
end = int(m.group(3))
return GenomicRange(chr,start,end,payload,dir) | Constructor for a GenomicRange object that takes a string |
363,807 | def authAddress(val):
ret = []
for a in val:
if a[0] == :
ret.append(.join(a.split()[1:]))
else:
ret.append(a)
return ret | # The C1 Tag
extracts the address of the authors as given by WOS. **Warning** the mapping of author to address is not very good and is given in multiple ways.
# Parameters
_val_: `list[str]`
> The raw data from a WOS file
# Returns
`list[str]`
> A list of addresses |
363,808 | def run_chunk(environ, lowstate):
client = environ[]
for chunk in lowstate:
yield client.run(chunk) | Expects a list of lowstate dictionaries that are executed and returned in
order |
363,809 | def parse_match_info(self, req: Request, name: str, field: Field) -> typing.Any:
return core.get_value(req.match_info, name, field) | Pull a value from the request's ``match_info``. |
363,810 | def _validate(self):
errors = {}
for name, validator in self._validators.items():
value = getattr(self, name)
try:
validator(self, value)
except ValidationError as e:
errors[name] = str(e)
self._validate_errors = err... | Validate model data and save errors |
363,811 | def is_valid(cls, oid):
if not oid:
return False
try:
ObjectId(oid)
return True
except (InvalidId, TypeError):
return False | Checks if a `oid` string is valid or not.
:Parameters:
- `oid`: the object id to validate
.. versionadded:: 2.3 |
363,812 | def _parse_use(self, string):
result = {}
for ruse in self.RE_USE.finditer(string):
name = ruse.group("name").split("!")[0].strip()
if name.lower() == "mpi":
continue
if ruse.group("only"):
... | Extracts use dependencies from the innertext of a module. |
363,813 | def make_coursera_absolute_url(url):
if not bool(urlparse(url).netloc):
return urljoin(COURSERA_URL, url)
return url | If given url is relative adds coursera netloc,
otherwise returns it without any changes. |
363,814 | def load(self, name, *, arguments=None, validate_arguments=True, strict_dag=False):
arguments = {} if arguments is None else arguments
try:
workflow_module = importlib.import_module(name)
dag_present = False
for key, obj in workflow_module.__d... | Import the workflow script and load all known objects.
The workflow script is treated like a module and imported
into the Python namespace. After the import, the method looks
for instances of known classes and stores a reference for further
use in the workflow object.
Args:
... |
363,815 | def request(self, message, timeout=False, *args, **kwargs):
if not self.connection_pool.full():
self.connection_pool.put(self._register_socket())
_socket = self.connection_pool.get()
if timeout or timeout is None:
_socket.settimeout(timeout)
d... | Populate connection pool, send message, return BytesIO, and cleanup |
363,816 | def setNonExpert(self):
self._expert = False
if self._active:
self.enable()
else:
self.disable() | Turns off 'expert' status whereby to allow a button to be disabled |
363,817 | def sample(self, frame):
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
stats = parent_stats.ensure_child(frame.f_code, RecordingStatisti... | Samples the given frame. |
363,818 | def crypto_box(message, nonce, pk, sk):
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce size")
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid... | Encrypts and returns a message ``message`` using the secret key ``sk``,
public key ``pk``, and the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes |
363,819 | def restore_from_cluster_snapshot(self, cluster_identifier, snapshot_identifier):
response = self.get_conn().restore_from_cluster_snapshot(
ClusterIdentifier=cluster_identifier,
SnapshotIdentifier=snapshot_identifier
)
return response[] if response[] else None | Restores a cluster from its snapshot
:param cluster_identifier: unique identifier of a cluster
:type cluster_identifier: str
:param snapshot_identifier: unique identifier for a snapshot of a cluster
:type snapshot_identifier: str |
363,820 | def get_credit_card_payment_by_id(cls, credit_card_payment_id, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._get_credit_card_payment_by_id_with_http_info(credit_card_payment_id, **kwargs)
else:
(data) = cls._get_credit_card_payment_by_id_with_http_info(... | Find CreditCardPayment
Return single instance of CreditCardPayment by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_credit_card_payment_by_id(credit_card_payment_id, async=True)
... |
363,821 | def demonstrate_colored_logging():
decorated_levels = []
defined_levels = coloredlogs.find_defined_levels()
normalizer = coloredlogs.NameNormalizer()
for name, level in defined_levels.items():
if name != :
item = (level, normalizer.normalize_name(name))
if item ... | Interactively demonstrate the :mod:`coloredlogs` package. |
363,822 | def row(self, *args):
btn_array = []
for button in args:
btn_array.append(button.to_dic())
self.keyboard.append(btn_array)
return self | Adds a list of KeyboardButton to the keyboard. This function does not consider row_width.
ReplyKeyboardMarkup#row("A")#row("B", "C")#to_json() outputs '{keyboard: [["A"], ["B", "C"]]}'
See https://core.telegram.org/bots/api#inlinekeyboardmarkup
:param args: strings
:return: self, to allo... |
363,823 | def analysis_question_report(feature, parent):
_ = feature, parent
project_context_scope = QgsExpressionContextUtils.projectScope()
key = provenance_layer_analysis_impacted[]
if not project_context_scope.hasVariable(key):
return None
analysis_dir = dirname(project_context_scope.varia... | Retrieve the analysis question section from InaSAFE report. |
363,824 | def info():
*
cmd = r
out = __salt__[](cmd)
match = re.search(r, out,
re.MULTILINE)
if match is not None:
groups = match.groups()
return {
: groups[0],
: groups[1],
: groups[2],
: in groups[3]
}
ret... | Return information about the license, if the license is not
correctly activated this will return None.
CLI Example:
.. code-block:: bash
salt '*' license.info |
363,825 | def handle_read_value(self, buff, start, end):
segmenttype = self._state[1].value.segmenttype
value = None
eventtype = None
ftype = self._state[0]
if segmenttype <= SegmentType.VARIABLE_LENGTH_VALUE:
self._scstate = self.next_state_afterraw(... | handle read of the value based on the expected length
:param buff:
:param start:
:param end: |
363,826 | def select_resample_op(da, op, freq="YS", **indexer):
da = select_time(da, **indexer)
r = da.resample(time=freq, keep_attrs=True)
if isinstance(op, str):
return getattr(r, op)(dim=, keep_attrs=True)
return r.apply(op) | Apply operation over each period that is part of the index selection.
Parameters
----------
da : xarray.DataArray
Input data.
op : str {'min', 'max', 'mean', 'std', 'var', 'count', 'sum', 'argmax', 'argmin'} or func
Reduce operation. Can either be a DataArray method or a function that can b... |
363,827 | def links(self):
if self._links is None:
self._links = list()
self.__pull_combined_properties()
return self._links | list: List of all MediaWiki page links on the page
Note:
Not settable |
363,828 | def setup_table(self):
self.horizontalHeader().setStretchLastSection(True)
self.adjust_columns()
self.setSortingEnabled(True)
self.sortByColumn(0, Qt.AscendingOrder) | Setup table |
363,829 | def run_job(self):
try:
self.load_parsers()
self.load_filters()
self.load_outputs()
self.config_args()
if self.args.list_parsers:
self.list_parsers()
if self.args.verbosemode: print()
self.load_inputs()
... | Execute a logdissect job |
363,830 | def copy_selection(self, _cut=False):
new_document, clipboard_data = self.document.cut_selection()
if _cut:
self.document = new_document
self.selection_state = None
return clipboard_data | Copy selected text and return :class:`.ClipboardData` instance. |
363,831 | def parse_arg(arg):
if type(arg) == str:
arg = arg.strip()
if in arg:
arg = arg.split()
arg = [x.strip() for x in arg]
else:
arg = [arg]
return arg | Parses arguments for convenience. Argument can be a
csv list ('a,b,c'), a string, a list, a tuple.
Returns a list. |
363,832 | def describe_api_model(restApiId, modelName, flatten=True, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
model = conn.get_model(restApiId=restApiId, modelName=modelName, flatten=flatten)
return {: _convert_d... | Get a model by name for a given API
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.describe_api_model restApiId modelName [True] |
363,833 | def createMappings(self, name, body, verbose=None):
PARAMS=set_param([,],[name,body])
response=api(url=self.___url++str(name)+, PARAMS=PARAMS, method="POST", verbose=verbose)
return response | Create a new Visual Mapping function and add it to the Visual Style specified by the `name` parameter. Existing mappings in the Visual Style will be overidden by the new mappings created.
The types of mapping available in Cytoscape are explained in depth [here](http://manual.cytoscape.org/en/stable/Sty... |
363,834 | def _compare_across(collections, key):
if len(collections) < 2:
return True
c0 = key(collections[0])
return all(c0 == key(c) for c in collections[1:]) | Return whether all the collections return equal values when called with
`key`. |
363,835 | def _Open(self, path_spec, mode=):
if not path_spec.HasParent():
raise errors.PathSpecError(
)
compression_method = getattr(path_spec, , None)
if not compression_method:
raise errors.PathSpecError(
)
self._compression_method = compression_method | Opens the file system defined by path specification.
Args:
path_spec (PathSpec): a path specification.
mode (Optional[str]): file access mode. The default is 'rb' which
represents read-only binary.
Raises:
AccessError: if the access to open the file was denied.
IOError: if th... |
363,836 | def get_primary_at(source_code, offset, retry=True):
obj =
left = re.split(r"[^0-9a-zA-Z_.]", source_code[:offset])
if left and left[-1]:
obj = left[-1]
right = re.split(r"\W", source_code[offset:])
if right and right[0]:
obj += right[0]
if obj and obj[0].isdigit()... | Return Python object in *source_code* at *offset*
Periods to the left of the cursor are carried forward
e.g. 'functools.par^tial' would yield 'functools.partial'
Retry prevents infinite recursion: retry only once |
363,837 | def book(self, name):
self._validate_order_book(name)
return OrderBook(name, self._rest_client, self._logger) | Return an API wrapper for the given order book.
:param name: Order book name (e.g. "btc_cad").
:type name: str | unicode
:return: Order book API wrapper.
:rtype: quadriga.book.OrderBook
:raise InvalidOrderBookError: If an invalid order book is given.
**Example**:
... |
363,838 | def ion_equals(a, b, timestamps_instants_only=False):
if timestamps_instants_only:
return _ion_equals_timestamps_instants(a, b)
return _ion_equals_timestamps_data_model(a, b) | Tests two objects for equivalence under the Ion data model.
There are three important cases:
* When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the
values of both operands are equivalent under the Ion data model.
* When only one of the... |
363,839 | def delete_view(self, request, object_id, extra_context=None):
try:
obj = self.get_queryset(request).get(pk=unquote(object_id))
parent_folder = obj.parent
except self.model.DoesNotExist:
parent_folder = None
if request.POST:
self.delete_f... | Overrides the default to enable redirecting to the directory view after
deletion of a folder.
we need to fetch the object and find out who the parent is
before super, because super will delete the object and make it
impossible to find out the parent folder to redirect to.
The d... |
363,840 | def transfer_from(self, spender_acct: Account, b58_from_address: str, b58_to_address: str, value: int,
payer_acct: Account, gas_limit: int, gas_price: int):
func = InvokeFunction()
Oep4.__b58_address_check(b58_from_address)
Oep4.__b58_address_check(b58_to_address)
... | This interface is used to call the Allowance method in ope4
that allow spender to withdraw amount of oep4 token from from-account to to-account.
:param spender_acct: an Account class that actually spend oep4 token.
:param b58_from_address: an base58 encode address that actually pay oep4 token f... |
363,841 | def findBinomialNsWithExpectedSampleMinimum(desiredValuesSorted, p, numSamples, nMax):
actualValues = [
getExpectedValue(
SampleMinimumDistribution(numSamples,
BinomialDistribution(n, p, cache=True)))
for n in xrange(nMax + 1)]
results = []
n = 0
for desir... | For each desired value, find an approximate n for which the sample minimum
has a expected value equal to this value.
For each value, find an adjacent pair of n values whose expected sample minima
are below and above the desired value, respectively, and return a
linearly-interpolated n between these two values.... |
363,842 | def query_by_login(self, login_id, end_time=None, start_time=None):
path = {}
data = {}
params = {}
path["login_id"] = login_id
if start_time is not None:
params["start_time"] = start_time
... | Query by login.
List authentication events for a given login. |
363,843 | def encode(df, encoding=, verbosity=1):
if verbosity > 0:
pbar = progressbar.ProgressBar(maxval=df.shape[1])
pbar.start()
series[strmask] = np.array(newseries).astype()
df[col] = series
... | If you try to encode each element individually with python, this would take days! |
363,844 | def is_conditional(self, include_loop=True):
if self.contains_if(include_loop) or self.contains_require_or_assert():
return True
if self.irs:
last_ir = self.irs[-1]
if last_ir:
if isinstance(last_ir, Return):
for r in last_... | Check if the node is a conditional node
A conditional node is either a IF or a require/assert or a RETURN bool
Returns:
bool: True if the node is a conditional node |
363,845 | def _log(self, x):
xshape = x.shape
_x = x.flatten()
y = utils.masked_log(_x)
return y.reshape(xshape) | Modified version of np.log that manually sets values <=0 to -inf
Parameters
----------
x: ndarray of floats
Input to the log function
Returns
-------
log_ma: ndarray of floats
log of x, with x<=0 values replaced with -inf |
363,846 | def itemAdded(self):
localCount = self.store.query(
_ReliableListener,
attributes.AND(_ReliableListener.processor == self,
_ReliableListener.style == iaxiom.LOCAL),
limit=1).count()
remoteCount = self.store.query(
_Reli... | Called to indicate that a new item of the type monitored by this batch
processor is being added to the database.
If this processor is not already scheduled to run, this will schedule
it. It will also start the batch process if it is not yet running and
there are any registered remote l... |
363,847 | def _status_filter_to_query(clause):
if clause["value"] == "RUNNING":
mongo_clause = MongoRunDAO.RUNNING_NOT_DEAD_CLAUSE
elif clause["value"] == "DEAD":
mongo_clause = MongoRunDAO.RUNNING_DEAD_RUN_CLAUSE
if clause["operator"] == "!=":
mongo_clause = {... | Convert a clause querying for an experiment state RUNNING or DEAD.
Queries that check for experiment state RUNNING and DEAD need to be
replaced by the logic that decides these two states as both of them
are stored in the Mongo Database as "RUNNING". We use querying by last
heartbeat tim... |
363,848 | def data(self):
if isinstance(self.data_to_print, list):
to_print = {}
to_print_size = []
alone_cases = ["Percentage", "HTTP"]
without_header = ["FullHosts",... | Management and input of data to the table.
:raises:
:code:`Exception`
When self.data_to_print is not a list. |
363,849 | def magic_api(word):
result = sum(ord(x)-65 + randint(1,50) for x in word)
delta = timedelta(seconds=result)
cached_until = datetime.now() + delta
return result, cached_until | This is our magic API that we're simulating.
It'll return a random number and a cache timer. |
363,850 | def inherit_docstrings(cls):
@functools.wraps(cls)
def _inherit_docstrings(cls):
if not isinstance(cls, (type, colorise.compat.ClassType)):
raise RuntimeError("Type is not a class")
for name, value in colorise.compat.iteritems(vars(cls)):
if isinstance(getattr(cls, ... | Class decorator for inheriting docstrings.
Automatically inherits base class doc-strings if not present in the
derived class. |
363,851 | def principal_rotation_axis(gyro_data):
N = np.zeros((3,3))
for x in gyro_data.T:
y = x.reshape(3,1)
N += y.dot(y.T)
(eig_val, eig_vec) = np.linalg.eig(N)
i = np.argmax(eig_val)
v = eig_vec[:,i]
s = 0
for x in gyro_data.T:
s += v.T.dot(x.resh... | Get the principal rotation axis of angular velocity measurements.
Parameters
-------------
gyro_data : (3, N) ndarray
Angular velocity measurements
Returns
-------------
v : (3,1) ndarray
The principal rotation axis for the chosen sequence |
363,852 | def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]):
x, y = give_dots(200, r, r_, spins=20)
xy = np.array([x, y]).T
xy = np.array(np.around(xy), dtype=np.int64)
xy = xy[(xy[:, 0] >= -250) & (xy[:, 1] >= -250) &
(xy[:, 0] < 250) & (xy[:, 1] < 250)]
xy = xy + 250
... | Create image with given Spirograph parameters using numpy and scipy. |
363,853 | def convert_msg(self, msg):
source = msg.msgid
if not source:
}
msg.msgstr_plural = plural
else:
foreign = self.convert(source)
msg.msgstr = self.final_newline(source, foreign) | Takes one POEntry object and converts it (adds a dummy translation to it)
msg is an instance of polib.POEntry |
363,854 | def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num,
mlm_metric, nsp_metric, trainer, log_interval):
end_time = time.time()
duration = end_time - begin_time
throughput = running_num_tks / duration / 1000.0
running_mlm_loss = running_mlm_loss / log_interval
... | Log training progress. |
363,855 | def displayTriples(triples, qname=qname):
[print(*(e[:5]
if isinstance(e, rdflib.BNode) else
qname(e)
for e in t), )
for t in sorted(triples)] | triples can also be an rdflib Graph instance |
363,856 | def inline(self) -> str:
inlined = [str(info) for info in (self.server, self.ipv4, self.ipv6, self.port, self.path) if info]
return SecuredBMAEndpoint.API + " " + " ".join(inlined) | Return endpoint string
:return: |
363,857 | def get_skype(self):
skype_inst = x11.XInternAtom(self.disp, , True)
if not skype_inst:
return
type_ret = Atom()
format_ret = c_int()
nitems_ret = c_ulong()
bytes_after_ret = c_ulong()
winp = pointer(Window())
fail = x11.XGetWindowProp... | Returns Skype window ID or None if Skype not running. |
363,858 | def get_scan_parameters_table_from_meta_data(meta_data_array, scan_parameters=None):
if scan_parameters is None:
try:
last_not_parameter_column = meta_data_array.dtype.names.index()
except ValueError:
return
if last_not_parameter_column == len(meta_data_array.... | Takes the meta data array and returns the scan parameter values as a view of a numpy array only containing the parameter data .
Parameters
----------
meta_data_array : numpy.ndarray
The array with the scan parameters.
scan_parameters : list of strings
The name of the scan parameters to t... |
363,859 | def epiweek_to_date(ew: Epiweek) -> datetime.date:
day_one = _start_date_of_year(ew.year)
diff = 7 * (ew.week - 1) + (ew.day - 1)
return day_one + datetime.timedelta(days=diff) | Return date from epiweek (starts at Sunday) |
363,860 | def make_geojson(contents):
if isinstance(contents, six.string_types):
return contents
if hasattr(contents, ):
features = [_geo_to_feature(contents)]
else:
try:
feature_iter = iter(contents)
except TypeError:
raise ValueError()
features ... | Return a GeoJSON string from a variety of inputs.
See the documentation for make_url for the possible contents
input.
Returns
-------
GeoJSON string |
363,861 | def get_scrollbar_position_height(self):
vsb = self.editor.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
groove_rect = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self)... | Return the pixel span height of the scrollbar area in which
the slider handle may move |
363,862 | def first_or_create(
self, _attributes=None, _joining=None, _touch=True, **attributes
):
if _attributes is not None:
attributes.update(_attributes)
instance = self._query.where(attributes).first()
if instance is None:
instance = self.create(attribute... | Get the first related model record matching the attributes or create it.
:param attributes: The attributes
:type attributes: dict
:rtype: Model |
363,863 | def metamodel_from_str(lang_desc, metamodel=None, **kwargs):
if not metamodel:
metamodel = TextXMetaModel(**kwargs)
language_from_str(lang_desc, metamodel)
return metamodel | Creates a new metamodel from the textX description given as a string.
Args:
lang_desc(str): A textX language description.
metamodel(TextXMetaModel): A metamodel that should be used.
other params: See TextXMetaModel. |
363,864 | def list_extra_features(self):
return FeatureLister(self._mX,
self._metadata_idx_store,
self.get_num_docs()).output() | Returns
-------
List of dicts. One dict for each document, keys are metadata, values are counts |
363,865 | def updateConfig(self, eleobj, config, type=):
eleobj.setConf(config, type=type) | write new configuration to element
:param eleobj: define element object
:param config: new configuration for element, string or dict
:param type: 'simu' by default, could be online, misc, comm, ctrl |
363,866 | def expression_statement(self):
node = self.assignment()
self._process(Nature.SEMI)
return node | expression_statement: assignment ';' |
363,867 | def set_ram(self, ram):
yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
log.info("GNS3 VM RAM amount set to {}".format(ram)) | Set the RAM amount for the GNS3 VM.
:param ram: amount of memory |
363,868 | def create_floating_ip(self, droplet_id=None, region=None, **kwargs):
if (droplet_id is None) == (region is None):
raise TypeError(
)
if droplet_id is not None:
if isinstance(droplet_id, Droplet):
droplet_id = drop... | Create a new floating IP assigned to a droplet or reserved to a region.
Either ``droplet_id`` or ``region`` must be specified, but not both.
The returned `FloatingIP` object will represent the IP at the moment of
creation; if the IP address is supposed to be assigned to a droplet,
the a... |
363,869 | def _equaBreaks(self, orbit_index_period=24.):
if self.orbit_index is None:
raise ValueError( +
+
)
else:
try:
self.sat[self.orbit_index]
except ValueError:
raise Val... | Determine where breaks in an equatorial satellite orbit occur.
Looks for negative gradients in local time (or longitude) as well as
breaks in UT.
Parameters
----------
orbit_index_period : float
The change in value of supplied index parameter for a single orbit |
363,870 | def delocalization_analysis(self, defect_entry):
defect_entry.parameters.update({: True})
if in defect_entry.parameters.keys():
defect_entry = self.is_freysoldt_delocalized(defect_entry)
else:
print(
)
... | Do delocalization analysis. To do this, one considers:
i) sampling region of planar averaged electrostatic potential (freysoldt approach)
ii) sampling region of atomic site averaged potentials (kumagai approach)
iii) structural relaxation amount outside of radius considered in kumaga... |
363,871 | def find_executable(executable, path=None):
if path is None:
path = os.environ[]
paths = path.split(os.pathsep)
base, ext = os.path.splitext(executable)
if (sys.platform == or os.name == ) and (ext != ):
executable = executable +
if not os.path.isfile(executable):
for p in paths:
f = ... | Tries to find 'executable' in the directories listed in 'path'.
A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found. |
363,872 | def parse_posting_id(text, city):
parts = text.split()
if len(parts) == 2:
post_id = parts[1].split()[0]
if post_id:
return post_id + post_id_bp_groups[city] | Parse the posting ID from the Backpage ad.
text -> The ad's HTML (or the a substring containing the "Post ID:" section)
city -> The Backpage city of the ad |
363,873 | def file_list(*packages, **kwargs):
s package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt pkg.file_list httpd
salt pkg.file_list httpd postfix
salt pkg.file_list
pacman-Ql-rcmd.runtrace\nerror errorsfiles': ret} | List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' p... |
363,874 | def at(self, t):
if not isinstance(t, Time):
raise ValueError(
.format(t))
observer_data = ObserverData()
observer_data.ephemeris = self.ephemeris
p, v, observer_data.gcrs_position, message = self._at(t)
... | At time ``t``, compute the target's position relative to the center.
If ``t`` is an array of times, then the returned position object
will specify as many positions as there were times. The kind of
position returned depends on the value of the ``center``
attribute:
* Solar Sys... |
363,875 | def main():
if len(sys.argv) < 3:
print()
print()
exit(-1)
_HELPER.project_name = sys.argv[1]
file_type = sys.argv[2]
allow_type = []
if file_type == or file_type == :
allow_type += [x for x in PYTHON_SUFFIX]
if file_type == or file_type == :
allow_... | Main entry function. |
363,876 | def library_directories(self) -> typing.List[str]:
def listify(value):
return [value] if isinstance(value, str) else list(value)
is_local_project = not self.is_remote_project
folders = [
f
for f in listify(self.settings.fet... | The list of directories to all of the library locations |
363,877 | def doeqdi(x, y, UP=False):
xp, yp = y, x
r = np.sqrt(xp**2+yp**2)
z = 1.-r**2
t = np.arcsin(z)
if UP == 1:
t = -t
p = np.arctan2(yp, xp)
dec, inc = np.degrees(p) % 360, np.degrees(t)
return dec, inc | Takes digitized x,y, data and returns the dec,inc, assuming an
equal area projection
Parameters
__________________
x : array of digitized x from point on equal area projection
y : array of igitized y from point on equal area projection
UP : if True, is an upper hemisphere projection... |
363,878 | def jpath_parse(jpath):
result = []
breadcrumbs = []
chunks = jpath.split()
for chnk in chunks:
match = RE_JPATH_CHUNK.match(chnk)
if match:
res = {}
res[] = chnk
breadcrumbs.append(chnk)
res[] = .join... | Parse given JPath into chunks.
Returns list of dictionaries describing all of the JPath chunks.
:param str jpath: JPath to be parsed into chunks
:return: JPath chunks as list of dicts
:rtype: :py:class:`list`
:raises JPathException: in case of invalid JPath syntax |
363,879 | def remove_board(board_id):
log.debug(, board_id)
lines = boards_txt().lines()
lines = filter(lambda x: not x.strip().startswith(board_id + ), lines)
boards_txt().write_lines(lines) | remove board.
:param board_id: board id (e.g. 'diecimila')
:rtype: None |
363,880 | def _load_same_codes(self, refresh=False):
if refresh is True:
self._get_same_codes()
else:
self._cached_same_codes() | Loads the Same Codes into this object |
363,881 | def ip_check(*args, func=None):
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, ipaddress._IPAddressBase):
name = type(var).__name__
raise IPError(
f) | Check if arguments are IP addresses. |
363,882 | def build_pattern(body, features):
line_patterns = apply_features(body, features)
return reduce(lambda x, y: [i + j for i, j in zip(x, y)], line_patterns) | Converts body into a pattern i.e. a point in the features space.
Applies features to the body lines and sums up the results.
Elements of the pattern indicate how many times a certain feature occurred
in the last lines of the body. |
363,883 | def input_dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1):
return dataset_from_dataframe(df=df, delays=delays, inputs=inputs, outputs=outputs,
normalize=normalize, verbosity=verbosity) | Build a dataset with an empty output/target vector
Identical to `dataset_from_dataframe`, except that default values for 2 arguments:
outputs: None |
363,884 | def weapon_cooldown(self) -> Union[int, float]:
if self.can_attack:
return self._proto.weapon_cooldown
return -1 | Returns some time (more than game loops) until the unit can fire again,
returns -1 for units that can't attack.
Usage:
if unit.weapon_cooldown == 0:
await self.do(unit.attack(target))
elif unit.weapon_cooldown < 0:
await self.do(unit.move(closest_allied_unit_becau... |
363,885 | def dist_location(dist):
egg_link = egg_link_path(dist)
if os.path.exists(egg_link):
return egg_link
return dist.location | Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is. |
363,886 | def bounding_box(self):
xmin = self.center.x - self.radius
xmax = self.center.x + self.radius
ymin = self.center.y - self.radius
ymax = self.center.y + self.radius
return BoundingBox.from_float(xmin, xmax, ymin, ymax) | Bounding box (`~regions.BoundingBox`). |
363,887 | def check_frame_id(frame_id):
if frame_id is None:
return
if frame_id.strip() == "":
raise H2OValueError("Frame id cannot be an empty string: %r" % frame_id)
for i, ch in enumerate(frame_id):
if ch == "$" and i == 0: continue
if ch not in _id_allowed_characters:... | Check that the provided frame id is valid in Rapids language. |
363,888 | def namedb_get_account_diff(current, prior):
if current[] != prior[] or current[] != prior[]:
raise ValueError("Accounts for two different addresses and/or token types")
return namedb_get_account_balance(current) - namedb_get_account_balance(prior) | Figure out what the expenditure difference is between two accounts.
They must be for the same token type and address.
Calculates current - prior |
363,889 | def partition(self, dimension):
for i, channel in enumerate(self.u):
if self.v[i].shape[1] < dimension:
raise IndexError(
% self.v[i].shape[1])
self.data[i] = channel[:, 0:dimension]
self.dimension = dimension
... | Partition subspace into desired dimension.
:type dimension: int
:param dimension: Maximum dimension to use. |
363,890 | def _get_permission(self, authorizer_name, authorizer_lambda_function_arn):
rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes)
api_id = rest_api.get_runtime_attr()
partition = ArnGenerator.get_partition_name()
resource... | Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function.
:returns: the permission resource
:rtype: model.lambda_.LambdaPermission |
363,891 | def _fixup_cdef_enums(string, reg=re.compile(r"=\s*(\d+)\s*<<\s*(\d+)")):
def repl_shift(match):
shift_by = int(match.group(2))
value = int(match.group(1))
int_value = ctypes.c_int(value << shift_by).value
return "= %s" % str(int_value)
return reg.sub(repl_shift, string) | Converts some common enum expressions to constants |
363,892 | def _report_error(self, request, exp):
message = (
"Failure to perform %s due to [ %s ]" % (request, exp)
)
self.log.fatal(message)
raise requests.RequestException(message) | When making the request, if an error happens, log it. |
363,893 | def getserialized(self, key, decoder_func=None, **kwargs):
value = self.get(key, cast_func=None, **kwargs)
if isinstance(value, (dict, list, tuple)) or value is None:
return value
if decoder_func: return decoder_func(value)
try:
o = json.loads(value)
... | Gets the setting value as a :obj:`dict` or :obj:`list` trying :meth:`json.loads`, followed by :meth:`yaml.load`.
:rtype: dict, list |
363,894 | def get(self, filepath):
try:
res = self.fs.get_file_details(filepath)
res = res.to_dict()
self.write(res)
except OSError:
raise tornado.web.HTTPError(404) | Get file details for the specified file. |
363,895 | def size_str(size_in_bytes):
if not size_in_bytes:
return "?? GiB"
size_in_bytes = float(size_in_bytes)
for (name, size_bytes) in _NAME_LIST:
value = size_in_bytes / size_bytes
if value >= 1.0:
return "{:.2f} {}".format(value, name)
return "{} {}".format(int(size_in_bytes), "bytes") | Returns a human readable size string.
If size_in_bytes is None, then returns "?? GiB".
For example `size_str(1.5 * tfds.units.GiB) == "1.50 GiB"`.
Args:
size_in_bytes: `int` or `None`, the size, in bytes, that we want to
format as a human-readable size string. |
363,896 | def json_decode(data):
if isinstance(data, six.binary_type):
data = data.decode()
return json.loads(data) | Decodes the given JSON as primitives |
363,897 | def _get_erred_shared_settings_module(self):
result_module = modules.LinkList(title=_())
result_module.template =
erred_state = structure_models.SharedServiceSettings.States.ERRED
queryset = structure_models.SharedServiceSettings.objects
settings_in_erred_state = query... | Returns a LinkList based module which contains link to shared service setting instances in ERRED state. |
363,898 | def object_new(self, template=None, **kwargs):
args = (template,) if template is not None else ()
return self._client.request(, args,
decoder=, **kwargs) | Creates a new object from an IPFS template.
By default this creates and returns a new empty merkledag node, but you
may pass an optional template argument to create a preformatted node.
.. code-block:: python
>>> c.object_new()
{'Hash': 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqF... |
363,899 | def entityTriples(self, aURI):
aURI = aURI
qres = self.rdfgraph.query(
% (aURI, aURI ))
lres = list(qres)
def recurse(triples_list):
out = []
for tripl in triples_list:
if isBlankNode(tripl[2]):
... | Builds all triples for an entity
Note: if a triple object is a blank node (=a nested definition)
we try to extract all relevant data recursively (does not work with
sparql endpoins)
2015-10-18: updated |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.