Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
347,100 | def _ip_int_from_string(self, ip_str):
if not ip_str:
raise AddressValueError()
octets = ip_str.split()
if len(octets) != 4:
raise AddressValueError("Expected 4 octets in %r" % ip_str)
try:
return _int_from_bytes(map(self._parse_octet, octet... | Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address. |
347,101 | def col_isbool(df,col_name = None):
col_list = df.select_dtypes(include = ).columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type 'bool'. If col_name is specified, returns
whether the column in the DataFrame is of type 'bool' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_name] is of t... |
347,102 | def _parse(self):
atom_counter = 0
structure_build = self.structure_builder
residues = self._extract_residues()
cur_model = None
cur_chain = None
structure_build.init_seg()
for r in residues:
... | Parse atomic data of the XML file. |
347,103 | def __get_metrics(self):
esfilters_merge = None
esfilters_abandon = None
if self.esfilters:
esfilters_merge = self.esfilters.copy()
esfilters_abandon = self.esfilters.copy()
merged = Merged(self.es_url, self.es_index,
start=self.s... | Each metric must have its own filters copy to modify it freely |
347,104 | async def grant(self, username, acl=):
controller_facade = client.ControllerFacade.from_connection(
self.connection())
user = tag.user(username)
changes = client.ModifyControllerAccess(acl, , user)
try:
await controller_facade.ModifyControllerAccess([chan... | Grant access level of the given user on the controller.
Note that if the user already has higher permissions than the
provided ACL, this will do nothing (see revoke for a way to
remove permissions).
:param str username: Username
:param str acl: Access control ('login', 'add-model... |
347,105 | def clear_taker(self):
if (self.get_taker_metadata().is_read_only() or
self.get_taker_metadata().is_required()):
raise errors.NoAccess()
self._my_map[] = self._taker_default | Clears the resource.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
347,106 | def fromSchedulerConstructorArgs(change_filter=None,
branch=NotABranch, categories=None):
if change_filter:
if (branch is not NotABranch or categories is not None):
raise RuntimeError("cannot specify both change_filter and "
... | Static method to create a filter based on constructor args
change_filter, branch, and categories; use default values @code{None},
@code{NotABranch}, and @code{None}, respectively. These arguments are
interpreted as documented for the
L{buildbot.schedulers.basic.Scheduler} class.
... |
347,107 | def combinecrinfo(crinfo1, crinfo2):
crinfo1 = fix_crinfo(crinfo1)
crinfo2 = fix_crinfo(crinfo2)
crinfo = [
[crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]],
[crinfo1[1][0] + crinfo2[1][0], crinfo1[1][0] + crinfo2[1][1]],
[crinfo1[2][0] + crinfo2[2][0], crinfo1[2]... | Combine two crinfos. First used is crinfo1, second used is crinfo2. |
347,108 | def tokenize_annotated(doc, annotation):
tokens = tokenize(doc, include_hrefs=False)
for tok in tokens:
tok.annotation = annotation
return tokens | Tokenize a document and add an annotation attribute to each token |
347,109 | def publishToMyself(self, roomId, name, data):
self.publishToRoom(roomId, name, data, [self]) | Publish to only myself |
347,110 | def draw(self):
str_wires = [["-"]*7 * self.depth]
str_wires[0][0] = "0"
str_wires[0][1] = " o"
str_spaces = []
for i in range(1, self.dimension):
str_wires.append(["-"]*7 * self.depth)
str_spaces.append([" "]*7 * self.depth)
str_wire... | Return an ASCII representation of the network. |
347,111 | def set_key_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _key_callback_repository:
previous_callback = _key_callback_repository[window_addr]
else:
previous_callbac... | Sets the key callback.
Wrapper for:
GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); |
347,112 | def _supports_colors(term, raise_err, colors):
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedErro... | Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support r... |
347,113 | def get_group_floors(df, cat_labels):
group_maxes = collections.defaultdict(list)
group_diffs = collections.defaultdict(list)
diff_pad = 0.1
for name, group in df.groupby(["category", "variant.type"]):
label, stype = name
if label in cat_labels:
diff = max(group["value... | Retrieve the floor for a given row of comparisons, creating a normalized set of differences.
We need to set non-zero floors so large numbers (like concordance) don't drown out small
numbers (like discordance). This defines the height for a row of comparisons as either
the minimum height of any sub-plot, or... |
347,114 | def internal_to_external_delta(self, internal_value, internal_delta):
external_value = self.transformation.backward(internal_value)
bound_internal = internal_value + internal_delta
bound_external = self.transformation.backward(bound_internal)
external_delta = bound_external - e... | Transform an interval from the internal to the external reference (through the transformation). It is useful
if you have for example a confidence interval in internal reference and you want to transform it to the
external reference
:param interval_value: value in internal reference
:par... |
347,115 | def blog_post_detail(request, slug, year=None, month=None, day=None,
template="blog/blog_post_detail.html",
extra_context=None):
blog_posts = BlogPost.objects.published(
for_user=request.user).select_related()
blog_post = get_ob... | . Custom templates are checked for using the name
``blog/blog_post_detail_XXX.html`` where ``XXX`` is the blog
posts's slug. |
347,116 | def _check_parse_modtime(self, filepath, fname):
file_mtime = self._get_mod_mtime(filepath)
if filepath.lower() in self._parsed:
module_mtime = None
if fname in self._modulefiles:
... | Checks whether the modules in the specified file path need
to be reparsed because the file was changed since it was
last loaded. |
347,117 | def is_subdirectory(potential_subdirectory, expected_parent_directory):
def _get_normalized_parts(path):
return DKCloudCommandRunner.os_path_split_asunder(os.path.realpath(os.path.abspath(os.path.normpath(path))))
sub_parts = _get_normalized_parts(potential_subdirectory)
... | Is the first argument a sub-directory of the second argument?
:param potential_subdirectory:
:param expected_parent_directory:
:return: True if the potential_subdirectory is a child of the expected parent directory |
347,118 | def construct_blastall_cmdline(
fname1, fname2, outdir, blastall_exe=pyani_config.BLASTALL_DEFAULT
):
fstem1 = os.path.splitext(os.path.split(fname1)[-1])[0]
fstem2 = os.path.splitext(os.path.split(fname2)[-1])[0]
fstem1 = fstem1.replace("-fragments", "")
prefix = os.path.join(outdir, "%s_vs_%s... | Returns a single blastall command.
- blastall_exe - path to BLASTALL executable |
347,119 | def set_account_password(self, account, raw_password):
luser = self._get_account(account.username)
changes = changeset(luser, {
: raw_password,
})
save(changes, database=self._database) | Account's password was changed. |
347,120 | def get_signature(func):
code = func.__code__
parameters = tuple(code.co_varnames[:code.co_argcount])
has_varargs = bool(code.co_flags & inspect.CO_VARARGS)
has_varkw = bool(code.co_flags & inspect.CO_VARKEYWORDS)
has_kwonly = bool(code.co_kwonlyargcount)
default_values = ... | Gathers information about the call signature of `func`. |
347,121 | def read(self):
with closing(self.open()) as f:
data = f.read()
return data.decode("utf-8") or None | Reads the contents of the GPFile and returns the contents as a string (assumes UTF-8) |
347,122 | def _find_mirror(self, axis):
mirror_type = ""
if self.is_valid_op(SymmOp.reflection(axis)):
self.symmops.append(SymmOp.reflection(axis))
mirror_type = "h"
else:
for s1, s2 in itertools.combinations(self.centered_mol, 2):
... | Looks for mirror symmetry of specified type about axis. Possible
types are "h" or "vd". Horizontal (h) mirrors are perpendicular to
the axis while vertical (v) or diagonal (d) mirrors are parallel. v
mirrors has atoms lying on the mirror plane while d mirrors do
not. |
347,123 | def paste(**kwargs):
try:
os.environ[] =
return subprocess.Popen(
[], stdout=subprocess.PIPE).communicate()[0].decode()
except OSError as why:
raise XcodeNotFound | Returns system clipboard contents. |
347,124 | def address_families_for_dir(cls, address_families_dict, spec_dir_path):
maybe_af = address_families_dict.get(spec_dir_path, None)
if maybe_af is None:
raise cls.AddressFamilyResolutionError(
.format(spec_dir_path))
return [maybe_af] | Implementation of `matching_address_families()` for specs matching at most one directory. |
347,125 | def get_assignments(self, hit_id, status=None,
sort_by=, sort_direction=,
page_size=10, page_number=1, response_groups=None):
params = { : hit_id,
: sort_by,
: sort_direction,
: page_size,
... | Retrieves completed assignments for a HIT.
Use this operation to retrieve the results for a HIT.
The returned ResultSet will have the following attributes:
NumResults
The number of assignments on the page in the filtered results
list, equivalent to the number o... |
347,126 | def get_proxy_ticket(self, pgt):
response = urllib_request.urlopen(self.get_proxy_url(pgt))
if response.code == 200:
from lxml import etree
root = etree.fromstring(response.read())
tickets = root.xpath(
"//cas:proxyTicket",
nam... | Returns proxy ticket given the proxy granting ticket |
347,127 | def json_encode(obj: Instance, **kwargs) -> str:
return json.dumps(obj, cls=JsonClassEncoder, **kwargs) | Encodes an object to JSON using our custom encoder.
The ``**kwargs`` can be used to pass things like ``'indent'``, for
formatting. |
347,128 | def detach(self, overlay):
for i, a in enumerate(self.animations):
a.layout = a.layout.clone()
if overlay and i:
a.preclear = False | Give each animation a unique, mutable layout so they can run
independently. |
347,129 | def _try_convert_value(conversion_finder, attr_name: str, attr_value: S, desired_attr_type: Type[T], logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
if is_typed_collection(desired_attr_type):
return ConversionFinder.convert_collection... | Utility method to try to use provided conversion_finder to convert attr_value into desired_attr_type.
If no conversion is required, the conversion finder is not even used (it can be None)
:param conversion_finder:
:param attr_name:
:param attr_value:
:param desired_attr_type:
... |
347,130 | def fill_n(self, values, weights=None, **kwargs):
if weights is not None:
if weights.shape != values.shape[0]:
raise RuntimeError("Wrong shape of weights")
for i, value in enumerate(values):
if weights is not None:
self.fill(value, weights... | Add more values at once.
This (default) implementation uses a simple loop to add values using `fill` method.
Actually, it is not used in neither Histogram1D, nor HistogramND.
Parameters
----------
values: Iterable
Values to add
weights: Optional[Iterable]
... |
347,131 | def init(name, storage_backend=, trust_password=None,
network_address=None, network_port=None, storage_create_device=None,
storage_create_loop=None, storage_pool=None,
done_file=):
t tell if its initialized
we touch the the done_file and check if it exist.
This can only be called... | Initalizes the LXD Daemon, as LXD doesn't tell if its initialized
we touch the the done_file and check if it exist.
This can only be called once per host unless you remove the done_file.
name :
Ignore this. This is just here for salt.
storage_backend :
Storage backend to use (zfs or d... |
347,132 | def _callback(self, ch, method, properties, body):
get_logger().info("Message received! Calling listeners...")
topic = method.routing_key
dct = json.loads(body.decode())
for listener in self.listeners:
listener(self, topic, dct) | Internal method that will be called when receiving message. |
347,133 | def get_nehrp_classes(self, sites):
classes = sorted(self.NEHRP_VS30_UPPER_BOUNDS.keys())
bounds = [self.NEHRP_VS30_UPPER_BOUNDS[item] for item in classes]
bounds = np.reshape(np.array(bounds), (-1, 1))
vs30s = np.reshape(sites.vs30, (1, -1))
site_classes = np.choose((v... | Site classification threshholds from Section 4 "Site correction
coefficients" p. 205. Note that site classes E and F are not
supported. |
347,134 | def highestMax(requestContext, seriesList, n=1):
result_list = sorted(seriesList, key=lambda s: safeMax(s))[-n:]
return sorted(result_list, key=lambda s: max(s), reverse=True) | Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the N metrics with the highest
maximum value in the time period specified.
Example::
&target=highestMax(server*.instance*.threads.busy,5)
Draws the top 5 servers who have had the most bu... |
347,135 | def exists_case_sensitive(path):
result = os.path.exists(path)
if sys.platform.startswith() and result:
directory, basename = os.path.split(path)
result = basename in os.listdir(directory)
return result | Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while
file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows, Python
can only import using the case of the rea... |
347,136 | def set_location(self, uri, size, checksum, storage_class=None):
self.file = FileInstance()
self.file.set_uri(
uri, size, checksum, storage_class=storage_class
)
db.session.add(self.file)
return self | Set only URI location of for object.
Useful to link files on externally controlled storage. If a file
instance has already been set, this methods raises an
``FileInstanceAlreadySetError`` exception.
:param uri: Full URI to object (which can be interpreted by the storage
int... |
347,137 | def Merge(text, message, allow_unknown_extension=False,
allow_field_number=False):
return MergeLines(text.split(), message, allow_unknown_extension,
allow_field_number) | Parses an text representation of a protocol message into a message.
Like Parse(), but allows repeated values for a non-repeated field, and uses
the last one.
Args:
text: Message text representation.
message: A protocol buffer message to merge into.
allow_unknown_extension: if True, skip over missing... |
347,138 | def to_key_val_dict(values):
if values is None:
return {}
if isinstance(values, (str, bytes, bool, int)):
raise ValueError()
if isinstance(values, collections.Mapping):
values = values.items()
dict_to_return = dict()
for k, v in values:
if k in dict_to_return ... | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_dict([('key', 'val')])
{'key': 'val'}
>>> to_key_val_dict({'key': 'val'})
{'key': 'val'}
>>> to_key_val_dict('string')
ValueErro... |
347,139 | def _compute_magnitude_term(self, C, mag):
fmag = C[] + C[] * mag
if mag <= 5.5:
return fmag
elif mag > 6.5:
return fmag + (C[] * (mag - 5.5)) + (C[] * (mag - 6.5))
else:
return fmag + (C[] * (mag - 5.5)) | Returns the magnitude scaling factor (equation (2), page 144) |
347,140 | def get_modname_from_modpath(module_fpath):
modsubdir_list = get_module_subdir_list(module_fpath)
modname = .join(modsubdir_list)
modname = modname.replace(, ).strip()
modname = modname.replace(, ).strip()
return modname | returns importable name from file path
get_modname_from_modpath
Args:
module_fpath (str): module filepath
Returns:
str: modname
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> module_fpath = ut.util_pa... |
347,141 | def add(self, new_child, label=None, containment=True, replace=False,
inherit_periodicity=True, reset_rigid_ids=True):
if (isinstance(new_child, collections.Iterable) and
not isinstance(new_child, string_types)):
for child in new_child:
s... | Add a part to the Compound.
Note:
This does not necessarily add the part to self.children but may
instead be used to add a reference to the part to self.labels. See
'containment' argument.
Parameters
----------
new_child : mb.Compound or list-like of... |
347,142 | def _define_format(self, occur):
if hasattr(self, "default"):
self.attr["nma:default"] = self.default
middle = self._chorder() if self.rng_children() else "<empty/>%s"
return (self.start_tag() + self.serialize_annots().replace("%", "%%")
+ middle + self.end_... | Return the serialization format for a define node. |
347,143 | def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]:
result = tuple(self.visit(node=dim) for dim in node.dims)
self.recomputed_values[node] = result
return result | Visit each dimension of the advanced slicing and assemble the dimensions in a tuple. |
347,144 | def init():
su()
args = sys.argv
args.pop(0)
cmd = "{0}sun_daemon".format(bin_path)
if len(args) == 1:
if args[0] == "start":
print("Starting SUN daemon: {0} &".format(cmd))
subprocess.call("{0} &".format(cmd), shell=True)
elif args[0] == "stop":
... | Initialization , all begin from here |
347,145 | def __receiver(self):
try:
self.__read_frame()
except errno.EAGAIN:
gevent.sleep(nsq.config.client.READ_THROTTLE_S)
self.__receive_thread_ev.set() | Receive-loop. |
347,146 | def functions(self, value):
if value is not None:
assert type(value) is tuple, " attribute: type is not !".format("functions", value)
for element in value:
assert type(element) is LibraryHook, " attribute: type is not !".format(
"functions"... | Setter for **self.__functions** attribute.
:param value: Attribute value.
:type value: tuple |
347,147 | def common_options(func):
def parse_preset(ctx, param, value):
return PRESETS.get(value, (None, None))
def parse_private(ctx, param, value):
return hex_from_b64(value) if value else None
func = click.option(, default=None, help=, callback=parse_private)(func)
func = click.option... | Commonly used command options. |
347,148 | def memcached_client(servers=config.memcached_uri, debug=config.debug_memcache):
key = None
try:
client, key = scoped_instance_manager.acquire(servers, debug=debug)
yield client
finally:
if key:
scoped_instance_manager.release(key) | Get a shared memcached instance.
This function shares the same memcached instance across nested invocations.
This is done so that memcached connections can be kept to a minimum, but at
the same time unnecessary extra reconnections are avoided. Typically an
initial scope (using 'with' construct) is made... |
347,149 | def _proxy(self):
if self._context is None:
self._context = PayloadContext(
self._version,
account_sid=self._solution[],
reference_sid=self._solution[],
add_on_result_sid=self._solution[],
sid=self._solution[],
... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: PayloadContext for this PayloadInstance
:rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext |
347,150 | def get_line_matches(input_file: str,
pattern: str,
max_occurrencies: int = 0,
loose_matching: bool = True) -> dict:
r
assert max_occurrencies >= 0
occurrency_counter = 0.0
occurrency_matches = dict()
if max_occurrencies == 0:
... | r"""Get the line numbers of matched patterns.
:parameter input_file: the file that needs to be read.
:parameter pattern: the pattern that needs to be searched.
:parameter max_occurrencies: the maximum number of expected occurrencies.
Defaults to ``0`` which means that all occurrencies will be matc... |
347,151 | def fit(self, weighted, show_progress=True):
self.similarity = all_pairs_knn(weighted, self.K,
show_progress=show_progress,
num_threads=self.num_threads).tocsr()
self.scorer = NearestNeighboursScorer(self.similarity... | Computes and stores the similarity matrix |
347,152 | def infer(cls, data, **kwargs):
def value_to_schema_type(value):
if isinstance(value, dict):
if len(value) == 0:
return dict
return {k: value_to_schema_type(v)
for k, v in iteritems(value)}
if isinstance... | Create a Schema from concrete data (e.g. an API response).
For example, this will take a dict like:
{
'foo': 1,
'bar': {
'a': True,
'b': False
},
'baz': ['purple', 'monkey', 'dishwasher']
}
And return a Sc... |
347,153 | def delete(self, order_id, data=None):
if not order_id or not order_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid order ID: . An order ID should start with .".format(
id=order_id, prefix=self.RESOURCE_ID_PREFIX)
)
... | Cancel order and return the order object.
Deleting an order causes the order status to change to canceled.
The updated order object is returned. |
347,154 | def dtpool(name):
name = stypes.stringToCharP(name)
found = ctypes.c_int()
n = ctypes.c_int()
typeout = ctypes.c_char()
libspice.dtpool_c(name, ctypes.byref(found), ctypes.byref(n),
ctypes.byref(typeout))
return n.value, stypes.toPythonString(typeout.value), bool(found... | Return the data about a kernel pool variable.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html
:param name: Name of the variable whose value is to be returned.
:type name: str
:return:
Number of values returned for name,
Type of the variable "C", "N", or "X... |
347,155 | def main():
parser = argparse.ArgumentParser(description=)
parser.add_argument(, nargs=,
type=str, default=sys.stdin)
parser.add_argument(, , nargs=,
type=argparse.FileType(), default=sys.stdout)
args = parser.parse_args()
input_list = args.input... | This main function implements the CLI |
347,156 | async def _on_message(self, channel, body, envelope, properties) -> None:
subscribers = self._get_subscribers(envelope.routing_key)
if not subscribers:
logger.debug("No route for message with key ", envelope.routing_key)
return
body = self._serializer.deseriali... | Fires up when message is received by this consumer.
:param channel: Channel, through which message is received
:param body: Body of the message (serialized).
:param envelope: Envelope object with message meta
:type envelope: aioamqp.Envelope
:param properties: Properties of the ... |
347,157 | def area_of_polygon(polygon):
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
poly = geometry.Polygon(zip(x, y))
return poly.area | Returns the area of an OpenQuake polygon in square kilometres |
347,158 | def random_sparse(strategy, prob, obj_reaction, flux_threshold):
essential = set()
deleted = set()
for entity, deleted_reactions in strategy.iter_tests():
if obj_reaction in deleted_reactions:
logger.info(
.format(entity))
essential.add(... | Find a random minimal network of model reactions.
Given a reaction to optimize and a threshold, delete entities randomly
until the flux of the reaction to optimize falls under the threshold.
Keep deleting until no more entities can be deleted. It works
with two strategies: deleting reactions or deletin... |
347,159 | def params(self):
params = dict(format=RESPONSE_FORMAT,
verbose=self.verbose,
epoch1=str(self.search_start_date),
epoch2=str(self.search_end_date),
search=self.orbit_method,
eunits=self.error_u... | :return: A dictionary of SSOS query parameters.
:rtype: dict |
347,160 | def setup_psd_workflow(workflow, science_segs, datafind_outs,
output_dir=None, tags=None):
if tags is None:
tags = []
logging.info("Entering static psd module.")
make_analysis_dir(output_dir)
cp = workflow.cp
try:
psdMethod = cp.get_opt_tags("w... | Setup static psd section of CBC workflow. At present this only supports pregenerated
psd files, in the future these could be created within the workflow.
Parameters
----------
workflow: pycbc.workflow.core.Workflow
An instanced class that manages the constructed workflow.
science_segs : Key... |
347,161 | def leak(self):
capacity, last_leak = self.storage.mget(self.key_amount, self.key_last_leak,
coherent=True)
now = time.time()
if last_leak:
elapsed = now - last_leak
decrement = elapsed * self.rate
new_capacity = max(int(capacity - ... | Leak the adequate amount of data from the bucket.
This should be called before any consumption takes place.
Returns:
int: the new capacity of the bucket |
347,162 | def get_contents(self, el, no_iframe=False):
if not no_iframe or not self.is_iframe(el):
for content in el.contents:
yield content | Get contents or contents in reverse. |
347,163 | def df_all(self, phot):
df = pd.concat([self.to_df(f) for f in self.get_filenames(phot)])
return df | Subclasses may want to sort this |
347,164 | def get_map(self):
if self._cache[]:
return self._cache[]
map_id = self._header.scenario.game_settings.map_id
instructions = self._header.scenario.messages.instructions
size = mgz.const.MAP_SIZES.get(self._header.map_info.size_x)
dimension = self._header.map_... | Get the map metadata. |
347,165 | def weight2codon(self, weight, length=None):
if length is None:
length = self.clen
retval = 0
weight = min(max(weight + 5.0, 0), 10.0) * (10 ** (length - 1))
for i in range(length):
if i == length - 1:
d = int(round(weight / (10 ** (lengt... | Given a weight between -5 and 5, turn it into
a codon, eg "000" to "999" |
347,166 | def parse_meta(filename, data):
if "." not in filename:
raise MetaParsingException(
"Can%st parse file of type !" % suffix)
fp = validator.FieldParser()
for key, val in SUPPORTED_FILES[suffix](data).items():
fp.process(key, val)
return fp.get_epublication() | Parse `data` to EPublication.
Args:
filename (str): Used to choose right parser based at suffix.
data (str): Content of the metadata file.
Returns:
EPublication: object. |
347,167 | def add_to_timestamp(timestamp, time_delta,
str_format=):
date_time = str_to_datetime(timestamp, str_format) + time_delta
return datetime_to_str(timestamp, str_format) | This will convert the timestamp to datetime, add the timedelta
and then return it as a timestamp
:param timestamp: str of the date and time
:param time_delta: datetime.timedelta of the time to add
:param str_format: str of the format of the timestamp
:return: str of the new ti... |
347,168 | def inverse_jacobian(self, maps):
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)
eta = conversions.eta_from_mass1_mass2(m1, m2)
return -1. * mchirp / eta**(6./5) | Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta. |
347,169 | def ekops():
handle = ctypes.c_int()
libspice.ekops_c(ctypes.byref(handle))
return handle.value | Open a scratch (temporary) E-kernel file and prepare the file
for writing.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekops_c.html
:return: Handle attached to new EK file.
:rtype: int |
347,170 | def validate_node(self, node_ip, node_port=None, same_nodes=1):
self.debug_print("Validating: " + node_ip)
if not is_ip_valid(node_ip) or node_ip == "0.0.0.0":
self.debug_print("Invalid node ip in validate node")
return 0
if node_port != 0 and n... | Don't accept connections from self to passive server
or connections to already connected nodes. |
347,171 | def set_windows_dll_path():
lib_path = os.path.dirname(os.path.abspath(_pylambda_worker.__file__))
lib_path = os.path.abspath(os.path.join(lib_path, os.pardir))
def errcheck_bool(result, func, args):
if not result:
last_error = ctypes.get_last_error()
if last_error != ... | Sets the dll load path so that things are resolved correctly. |
347,172 | def finalize(self):
if self._finalized:
return
if self._remove_files:
for filename in self._remove_files:
self.prefix(, , filename)
self.blank()
if self._volumes is not None:
self.prefix(, json.dumps(self._volumes))
... | Finalizes the Dockerfile. Before the buffer is practically marked as read-only, the following Dockerfile
commands are written:
* ``RUN rm -R`` on each files marked for automatic removal;
* ``VOLUME`` for shared volumes;
* ``USER`` as the default user for following commands;
* ``... |
347,173 | def source_foreign(args, stdin=None):
parser = _ensure_source_foreign_parser()
ns = parser.parse_args(args)
if ns.prevcmd is not None:
pass
fsenv = foreign_shell_data(shell=ns.shell, login=ns.login,
interactive=ns.interactive,
... | Sources a file written in a foreign shell language. |
347,174 | def _bdtr(k, n, p):
ones = tf.ones_like(n - k)
k_eq_n = tf.equal(k, n)
safe_dn = tf.where(k_eq_n, ones, n - k)
dk = tf.math.betainc(a=safe_dn, b=k + 1, x=1 - p)
return tf.where(k_eq_n, ones, dk) | The binomial cumulative distribution function.
Args:
k: floating point `Tensor`.
n: floating point `Tensor`.
p: floating point `Tensor`.
Returns:
`sum_{j=0}^k p^j (1 - p)^(n - j)`. |
347,175 | def get_markable(self,markable_id):
if markable_id in self.idx:
return Cmarkable(self.idx[markable_id],self.type)
else:
return None | Returns the markable object for the supplied identifier
@type markable_id: string
@param markable_id: term identifier |
347,176 | def _stderr_filed(func):
def wrapper(self, msg, file=None):
if file:
return func(self, msg, file=file)
elif self.io_manager:
with self.io_manager.with_stderr() as stderr:
return func(self, msg, file=stderr)
else:
return func(self, msg,... | Instance method decorator to convert an optional file keyword
argument into an actual value, whether it be a passed value, a
value obtained from an io_manager, or sys.stderr. |
347,177 | def _next_batch(self) -> Optional[Batch]:
if self._epoch_limit_reached():
self._batch_count = 0
return None
try:
batch = next(self._get_stream())
self._batch_count += 1
return batch
except StopIteration:
self._strea... | Return a single batch or ``None`` signaling epoch end.
.. note::
Signal the epoch end with ``None``.
Stop when:
- stream ends and epoch size is not set
- specified number of batches is returned
:return: a single batch or ``None`` signaling epoch end |
347,178 | def publish(self):
while True:
event = yield from self.event_source.get()
str_buffer = []
if event == POISON_PILL:
return
if isinstance(event, str):
str_buffer.append(event)
elif event.type == EventTypes.BLO... | Publish new events to the subscribers. |
347,179 | def NewFromHtml(html, alpha=1.0, wref=_DEFAULT_WREF):
return Color(Color.HtmlToRgb(html), , alpha, wref) | Create a new instance based on the specifed HTML color definition.
Parameters:
:html:
The HTML definition of the color (#RRGGBB or #RGB or a color name).
:alpha:
The color transparency [0...1], default is opaque.
:wref:
The whitepoint reference, default is 2° D65.
Ret... |
347,180 | def lz4_encode_old_kafka(payload):
assert xxhash is not None
data = lz4_encode(payload)
header_size = 7
flg = data[4]
if not isinstance(flg, int):
flg = ord(flg)
content_size_bit = ((flg >> 3) & 1)
if content_size_bit:
flg -= 8
data = bytearray... | Encode payload for 0.8/0.9 brokers -- requires an incorrect header checksum. |
347,181 | def _shapeletOutput(self, r, phi, beta, shapelets):
if type(r) == float or type(r) == int or type(r) == type(np.float64(1)) or len(r) <= 1:
values = 0.
else:
values = np.zeros(len(r), )
for nl in range(0,len(shapelets)):
for nr in range(0,len(shapele... | returns the the numerical values of a set of shapelets at polar coordinates
:param shapelets: set of shapelets [l=,r=,a_lr=]
:type shapelets: array of size (n,3)
:param coordPolar: set of coordinates in polar units
:type coordPolar: array of size (n,2)
:returns: array of same si... |
347,182 | def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque):
_salt_send_event(opaque, conn, {
: {
: pool.name(),
: pool.UUIDString()
},
: _get_libvirt_enum_string(, event),
:
}) | Storage pool lifecycle events handler |
347,183 | def best_buy_3(self):
return self.data.continuous(self.data.moving_average(self.data.price, 3)) == 1 | 三日均價由下往上 |
347,184 | def _create(self, rawtitle):
slug = util.make_slug(rawtitle)
if self.site.page_exists_on_disk(slug):
raise ValueError
self._title = unicode(rawtitle,"UTF-8")
self._slug = slug
self._dirs[] = os.path.join(self.site.dirs[], slug)
... | Create a page with this title, if it doesn't exist.
This method first checks whether a page with the same slug
(sanitized name) exists_on_disk. If it does, it doesn't do antyhing.
Otherwise, the relevant attributes are created.
Nothing is written to disc (to the source file). You must c... |
347,185 | def key_rm(self, key_name, *key_names, **kwargs):
args = (key_name,) + key_names
return self._client.request(, args, decoder=, **kwargs) | Remove a keypair
.. code-block:: python
>>> c.key_rm("bla")
{"Keys": [
{"Name": "bla",
"Id": "QmfJpR6paB6h891y7SYXGe6gapyNgepBeAYMbyejWA4FWA"}
]}
Parameters
----------
key_name : str
Name of the key(s) to... |
347,186 | def delete_usage_plan(plan_id, region=None, key=None, keyid=None, profile=None):
usage plan id
try:
existing = describe_usage_plans(plan_id=plan_id, region=region, key=key, keyid=keyid, profile=profile)
| Deletes usage plan identified by plan_id
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.delete_usage_plan plan_id='usage plan id' |
347,187 | def clausius_clapeyron(T):
Tcel = T - tempCtoK
es = 6.112 * exp(17.67*Tcel/(Tcel+243.5))
return es | Compute saturation vapor pressure as function of temperature T.
Input: T is temperature in Kelvin
Output: saturation vapor pressure in mb or hPa
Formula from Rogers and Yau "A Short Course in Cloud Physics" (Pergammon Press), p. 16
claimed to be accurate to within 0.1% between -30degC and 35 degC
... |
347,188 | def list2cmdline(seq):
result = []
needquote = False
for arg in seq:
bs_buf = []
if result:
result.append()
needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
if needquote:
result.append()
... | Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:
1) Arguments are delimited by white space, which is either a
space or a tab.
2) A string surrounded by double quotation marks is
interpreted as a single argument, regardless of white space... |
347,189 | def add(mode_id: str) -> list:
if not has(mode_id):
_current_modes.append(mode_id)
return _current_modes.copy() | Adds the specified mode identifier to the list of active modes and returns
a copy of the currently active modes list. |
347,190 | def walk(self, walk_root=, reverse_order=False, previous_file=):
__name__ = % self.__class__.__name__
input_kwargs = [walk_root, previous_file]
input_names = [, ]
for i in range(len(input_kwargs)):
if input_kwargs[i]:
self.fields.va... | a generator method of file paths on localhost from walk of directories
:param walk_root: string with path from which to root walk of localhost directories
:param reverse_order: boolean to determine alphabetical direction of walk
:param previous_file: string with path of file after which to ... |
347,191 | def get_QApplication(args=[]):
global _qapp
if _qapp is None:
QCoreApplication.setAttribute(Qt.AA_X11InitThreads)
_qapp = QApplication(args)
return _qapp | Returns the QApplication instance, creating it is does not yet exist. |
347,192 | def _volume_command(ramp, volume):
if volume is not None:
ramp.set_volume(float(volume))
else:
print ramp.volume | Set the value if a volume level is provided, else print the current
volume level. |
347,193 | def get_colorscale(scale):
if type(scale) in string_types:
scale = get_scales(scale)
else:
if type(scale) != list:
raise Exception(
"scale needs to be either a scale name or list of colors")
cs = [[1.0 * c / (len(scale) - 1), scale[c]] for c in range(len(sc... | Returns a color scale to be used for a plotly figure
Parameters:
-----------
scale : str or list
Color scale name
If the color name is preceded by a minus (-)
then the scale is inversed.
Also accepts a list of colors (... |
347,194 | def apply(self, topology, references_file=None, use_residue_map=True,
assert_bond_params=True, assert_angle_params=True,
assert_dihedral_params=True, assert_improper_params=False,
*args, **kwargs):
if self.atomTypeDefinitions == {}:
raise FoyerError... | Apply the force field to a molecular structure
Parameters
----------
topology : openmm.app.Topology or parmed.Structure or mbuild.Compound
Molecular structure to apply the force field to
references_file : str, optional, default=None
Name of file where force field... |
347,195 | def _plot_kmf_single(df,
condition_col,
survival_col,
censor_col,
threshold,
title,
xlabel,
ylabel,
ax,
with_condition_color,
... | Helper function to produce a single KM survival plot, among observations in df by groups defined by condition_col.
All inputs are required - this function is intended to be called by `plot_kmf`. |
347,196 | def get_reconstructed_band_structure(list_bs, efermi=None):
if efermi is None:
efermi = sum([b.efermi for b in list_bs]) / len(list_bs)
kpoints = []
labels_dict = {}
rec_lattice = list_bs[0].lattice_rec
nb_bands = min([list_bs[i].nb_bands for i in range(len(list_bs))])
kpoints = n... | This method takes a list of band structures and reconstructs
one band structure object from all of them.
This is typically very useful when you split non self consistent
band structure runs in several independent jobs and want to merge back
the results
Args:
list_bs: A list of BandStructur... |
347,197 | def do_template(self,args):
parser = CommandArgumentParser("template")
args = vars(parser.parse_args(args))
print "reading template for stack."
rawStack = self.wrappedStack[]
template = AwsConnectionFactory.getCfClient().get_template(StackName=rawStack.name)
pri... | Print the template for the current stack. template -h for detailed help |
347,198 | def do_for(parser, token):
code = ast.parse( % token, mode=)
loop = code.body[0]
loop.iter = visitor.visit(loop.iter)
body, end = parser.parse_nodes_until(, )
if isinstance(loop.target, ast.Tuple):
targets = [elt.id for elt in loop.target.elts]
else:
t... | {% for a, b, c in iterable %}
{% endfor %}
We create the structure:
with ContextWrapper(context) as context:
for a, b, c in iterable:
context.update(a=a, b=b, c=c)
...
If there is a {% empty %} clause, we create:
if iterable:
{ above code }
else:
... |
347,199 | def parse_human_datetime(s):
if not s:
return None
try:
dttm = parse(s)
except Exception:
try:
cal = parsedatetime.Calendar()
parsed_dttm, parsed_flags = cal.parseDT(s)
if parsed_flags & 2 == 0:
parsed_dttm = parse... | Returns ``datetime.datetime`` from human readable strings
>>> from datetime import date, timedelta
>>> from dateutil.relativedelta import relativedelta
>>> parse_human_datetime('2015-04-03')
datetime.datetime(2015, 4, 3, 0, 0)
>>> parse_human_datetime('2/3/1969')
datetime.datetime(1969, 2, 3, 0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.