Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
356,000 | def commit(self, message, author, parents=None, branch=None, date=None,
**kwargs):
self.check_integrity(parents)
from .repository import MercurialRepository
if not isinstance(message, unicode) or not isinstance(author, unicode):
raise RepositoryError(
... | Performs in-memory commit (doesn't check workdir in any way) and
returns newly created ``Changeset``. Updates repository's
``revisions``.
:param message: message of the commit
:param author: full username, i.e. "Joe Doe <joe.doe@example.com>"
:param parents: single parent or seq... |
356,001 | def post_build(self, container_builder, container):
app = container.get()
app.config.update(container_builder.parameters.get())
if container.has():
jinja2 = container.get()
jinja2.loader.loaders.append(app.create_global_j... | This method make sure the flask configuration is fine, and
check the if ioc.extra.jinja2 service is available. If so, the
flask instance will use this service, by keeping the flask template
loader and the one registered at the jinja2 |
356,002 | def load_py_instance(self, is_spout):
try:
if is_spout:
spout_proto = self.pplan_helper.get_my_spout()
py_classpath = spout_proto.comp.class_name
self.logger.info("Loading Spout from: %s", py_classpath)
else:
bolt_proto = self.pplan_helper.get_my_bolt()
py_cl... | Loads user defined component (spout/bolt) |
356,003 | def export(self, nidm_version, export_dir):
if nidm_version[] in ["1.0.0", "1.1.0"]:
self.label = self.label.replace("Supra-Threshold", "Significant")
atts = (
(PROV[], NIDM_SIGNIFICANT_CLUSTER),
(PROV[], self.label),
(NIDM_CLUSTER_LABEL... | Create prov entities and activities. |
356,004 | def login(self, email=None, password=None, gsfId=None, authSubToken=None):
if email is not None and password is not None:
encryptedPass = self.encryptPassword(email, password).decode()
params = self.deviceBuilder.getLoginParams(email, encr... | Login to your Google Account.
For first time login you should provide:
* email
* password
For the following logins you need to provide:
* gsfId
* authSubToken |
356,005 | def write_checktime (self, url_data):
self.write(self.part("checktime") + self.spaces("checktime"))
self.writeln(_("%.3f seconds") % url_data.checktime,
color=self.colordltime) | Write url_data.checktime. |
356,006 | def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
return cls(types.KeyboardButtonRequestPhone(text),
resize=resize, single_use=single_use, selective=selective) | Creates a new button that will request
the user's phone number upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`. |
356,007 | def parents(self):
return [self.repository.get_changeset(parent.rev())
for parent in self._ctx.parents() if parent.rev() >= 0] | Returns list of parents changesets. |
356,008 | def inverse_transform(self, X, copy=None):
check_is_fitted(self, )
copy = copy if copy is not None else self.copy
if sparse.issparse(X):
if self.with_mean:
raise ValueError(
"Cannot uncenter sparse matrices: pass `with_mean=False` "
... | Scale back the data to the original representation.
:param X: Scaled data matrix.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param bool copy: Copy the X data matrix.
:return: X data matrix with the scaling operation reverted.
:rtype: numpy.ndarray, shape [n_samples, ... |
356,009 | def start_tag(self, indent):
return u"%s<%s%s/>" % (indent, self.tagName, u"".join(u" %s=\"%s\"" % keyvalue for keyvalue in self.attributes.items())) | Generate the string for the element's start tag. |
356,010 | def setup_manager_context():
setup_manager = SetupManager()
setup_manager.connect_to_game()
try:
yield setup_manager
finally:
setup_manager.shut_down(kill_all_pids=True) | Creates a initialized context manager which shuts down at the end of the
`with` block.
usage:
>>> with setup_manager_context() as setup_manager:
... setup_manager.load_config(...)
... # ... Run match |
356,011 | def quartus_prop(self, buff: List[str], intfName: str, name: str, value,
escapeStr=True):
if escapeStr and isinstance(value, str):
value = % value
elif isinstance(value, bool):
value = str(value).lower()
else:
value = str(value)
... | Set property on interface in Quartus TCL
:param buff: line buffer for output
:param intfName: name of interface to set property on
:param name: property name
:param value: property value
:param escapeStr: flag, if True put string properties to extra "" |
356,012 | def fit_transform(self, X, y=None, **params):
return self.fit(X, y).transform(X, y) | Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
list : document id matrix.
list: label id matrix. |
356,013 | def get_templates(model):
for template_name, template in templates.items():
if issubclass(template.model, model):
yield (template_name, template.layout._meta.verbose_name) | Return a list of templates usable by a model. |
356,014 | def get_all_files(folder):
for path, dirlist, filelist in os.walk(folder):
for fn in filelist:
yield op.join(path, fn) | Generator that loops through all absolute paths of the files within folder
Parameters
----------
folder: str
Root folder start point for recursive search.
Yields
------
fpath: str
Absolute path of one file in the folders |
356,015 | def _input_to_raw_value(self, value: int) -> float:
return (float(value) - self.min_raw_value) / self.max_raw_value | Convert the value read from evdev to a 0.0 to 1.0 range.
:internal:
:param value:
a value ranging from the defined minimum to the defined maximum value.
:return:
0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points. |
356,016 | def build_prev_op(self):
code = self.code
codelen = len(code)
self.prev = self.prev_op = [0]
for offset in self.op_range(0, codelen):
op = code[offset]
for _ in range(instruction_size(op, self.opc)):
self.prev_op.append(o... | Compose 'list-map' which allows to jump to previous
op, given offset of current op as index. |
356,017 | def longest_service_name(self):
return max([len(service_handle.service.name) for service_handle in self.service_handles] + [0]) | Length of the longest service name. |
356,018 | def get_update_tile(self, params, values):
doglobal, particles = self._update_type(params)
if doglobal:
return self.shape.copy()
values0 = self.get_values(params)
tiles0 = [self._tile(n) for n in particles]
self.set_values(params,... | Get the amount of support size required for a particular update. |
356,019 | def tags(self):
if not self.raw_content:
return set()
return {word.strip(" | Returns a `set` of unique tags contained in `raw_content`. |
356,020 | def source_lines(self):
return [self.source_buffer.source_line(line)
for line in range(self.line(), self.end().line() + 1)] | Returns the lines of source code containing the entirety of this range. |
356,021 | def shellne(command):
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError( % (command, err))
return data | Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors. |
356,022 | def to_dict(self):
result = OrderedDict()
result[] = self.mrz_type
result[] = self.valid_score
if self.mrz_type is not None:
result[] = self.type
result[] = self.country
result[] = self.number
result[] = self.date_of_birth
... | Converts this object to an (ordered) dictionary of field-value pairs.
>>> m = MRZ(['IDAUT10000999<6<<<<<<<<<<<<<<<', '7109094F1112315AUT<<<<<<<<<<<6', 'MUSTERFRAU<<ISOLDE<<<<<<<<<<<<']).to_dict()
>>> assert m['type'] == 'ID' and m['country'] == 'AUT' and m['number'] == '10000999<'
>>> assert m[... |
356,023 | def _dissect_roles(metadata):
for role_key in cnxepub.ATTRIBUTED_ROLE_KEYS:
for user in metadata.get(role_key, []):
if user[] != :
raise ValueError("Archive only accepts Connexions users.")
uid = parse_user_uri(user[])
yield uid, role_key
raise St... | Given a model's ``metadata``, iterate over the roles.
Return values are the role identifier and role type as a tuple. |
356,024 | def p_annotation(self, p):
if len(p) < 8:
args, kwargs = p[5]
p[0] = AstAnnotationDef(
self.path, p.lineno(1), p.lexpos(1), p[2], p[4], None, args, kwargs)
else:
args, kwargs = p[7]
p[0] = AstAnnotationDef(
self.pat... | annotation : ANNOTATION ID EQ ID args NL
| ANNOTATION ID EQ ID DOT ID args NL |
356,025 | def list_states(self, saltenv):
states = set()
for path in self.file_list(saltenv):
if salt.utils.platform.is_windows():
path = path.replace(, )
if path.endswith():
if path.endswith():
states.add(path.r... | Return a list of all available sls modules on the master for a given
environment |
356,026 | def JSONList(*args, **kwargs):
type_ = JSON
try:
if kwargs.pop("unique_sorted"):
type_ = JSONUniqueListType
except KeyError:
pass
return MutationList.as_mutable(type_(*args, **kwargs)) | Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted. |
356,027 | def get_resources(self, types=None, names=None, languages=None):
return GetResources(self.filename, types, names, languages) | Get resources.
types = a list of resource types to search for (None = all)
names = a list of resource names to search for (None = all)
languages = a list of resource languages to search for (None = all)
Return a dict of the form {type_: {name: {language: data}}} which
m... |
356,028 | def padded_split(value, sep, maxsplit=None, pad=None):
result = value.split(sep, maxsplit)
if maxsplit is not None:
result.extend(
[pad] * (1+maxsplit-len(result)))
return result | Modified split() to include padding
See http://code.activestate.com/lists/python-ideas/3366/
:attr value: see str.split()
:attr sep: see str.split()
:attr maxsplit: see str.split()
:attr pad: Value to use for padding maxsplit
>>> padded_split('text/html', ';', 1)
['text/html', None]
>>... |
356,029 | def _show_no_gui():
messagebox = QtWidgets.QMessageBox()
messagebox.setIcon(messagebox.Warning)
messagebox.setWindowIcon(QtGui.QIcon(os.path.join(
os.path.dirname(pyblish.__file__),
"icons",
"logo-32x32.svg"))
)
spacer = QtWidgets.QWidget()
spacer.setMinimumSize(40... | Popup with information about how to register a new GUI
In the event of no GUI being registered or available,
this information dialog will appear to guide the user
through how to get set up with one. |
356,030 | def _helioXYZ(self,*args,**kwargs):
obs, ro, vo= self._parse_radec_kwargs(kwargs)
thiso= self(*args,**kwargs)
if not len(thiso.shape) == 2: thiso= thiso.reshape((thiso.shape[0],1))
if len(thiso[:,0]) != 4 and len(thiso[:,0]) != 6:
raise AttributeError("orbit must tr... | Calculate heliocentric rectangular coordinates |
356,031 | def pull_image(self, image, progress_callback=None):
try:
yield from self.query("GET", "images/{}/json".format(image))
return
except DockerHttp404Error:
pass
if progress_callback:
progress_callback("Pull {} from docker hub".format(imag... | Pull image from docker repository
:params image: Image name
:params progress_callback: A function that receive a log message about image download progress |
356,032 | def pending():
signalbus = current_app.extensions[]
pending = []
total_pending = 0
for signal_model in signalbus.get_signal_models():
count = signal_model.query.count()
if count > 0:
pending.append((count, signal_model.__name__))
total_pending += count
if pe... | Show the number of pending signals by signal type. |
356,033 | def attach_protocol(self, proto):
if self._protocol is not None:
raise RuntimeError("Already have a protocol.")
self.save()
self.__dict__[] = proto
del self.__dict__[]
self.__dict__[] = defer.Deferred()
if proto.post_bootstrap:
... | returns a Deferred that fires once we've set this object up to
track the protocol. Fails if we already have a protocol. |
356,034 | def print_traceback(self, always_print=False):
if self._exception or always_print:
self.__echo.critical("--{ TRACEBACK }" + "-" * 100)
self.__format_lines_error(self.traceback)
self.__echo.critical("---------------" + "-" * 100) | Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false) |
356,035 | def __try_to_json(self, request, attr):
if hasattr(attr, ):
return attr.__json__(request)
raise TypeError( % str(attr)) | Try to run __json__ on the given object.
Raise TypeError is __json__ is missing
:param request: Pyramid Request object
:type request: <Request>
:param obj: Object to JSONify
:type obj: any object that has __json__ method
:exception: TypeError |
356,036 | def _is_univariate_marginal(self, index_points):
num_index_points = tf.compat.dimension_value(
index_points.shape[-(self.kernel.feature_ndims + 1)])
if num_index_points is None:
warnings.warn(
)
return num_index_points == 1 | True if the given index_points would yield a univariate marginal.
Args:
index_points: the set of index set locations at which to compute the
marginal Gaussian distribution. If this set is of size 1, the marginal is
univariate.
Returns:
is_univariate: Boolean indicating whether the marg... |
356,037 | def help_center_article_subscription_show(self, article_id, id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/subscriptions
api_path = "/api/v2/help_center/articles/{article_id}/subscriptions/{id}.json"
api_path = api_path.format(article_id=article_id, id=id)
... | https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#show-article-subscription |
356,038 | def get_next_action(self, request, application, roles):
application.reopen()
link, is_secret = base.get_email_link(application)
emails.send_invite_email(application, link, is_secret)
messages.success(
request,
"Sent an invitation to %s."
% app... | Retrieve the next state. |
356,039 | def _build_obs_point(self, sensor_info, obs_recs):
cur_point = sensor_info["location"]["point"]
keys = [m["name"] for m in obs_recs]
if "binIndex" in keys:
zidx = keys.index("binIndex")
bin_index = int(obs_recs[zidx]["value"])
z = sensor_info["profil... | Pulls bin/profile height info out and calcs a z.
TODO: currently extremely naive
Returns a 2-tuple: point, remaining obs_recs |
356,040 | def _joinrealpath(self, path, rest, seen):
curdir = self.filesystem._matching_string(path, )
pardir = self.filesystem._matching_string(path, )
sep = self.filesystem._path_separator(path)
if self.isabs(rest):
rest = rest[1:]
path = sep
while rest... | Join two paths, normalizing and eliminating any symbolic links
encountered in the second path.
Taken from Python source and adapted. |
356,041 | def process_op(self, rc, nbytes, overlap):
act = overlap.object
overlap.object = None
if act in self.tokens:
ol, perform, complete = self.tokens[act]
assert ol is overlap
if rc == 0:
ract = self.try_run_act(act, complete, rc, n... | Handles the possible completion or re-queueing if conditions haven't
been met (the `complete` callable returns false) of a overlapped request. |
356,042 | def _get_converter(self, converter_str):
ret = None
if converter_str is not None:
converter_desc_list = converter_str.split()
if len(converter_desc_list) == 1:
converter = converter_desc_list[0]
ret = getattr(cvt, converte... | find converter function reference by name
find converter by name, converter name follows this convention:
Class.method
or:
method
The first type of converter class/function must be available in
current module.
The second type of converter must be avai... |
356,043 | def thread_view(request, pk):
if request.is_ajax():
if not request.user.is_authenticated():
return HttpResponse(json.dumps(dict()),
content_type="application/json")
try:
user_profile = UserProfile.objects.get(user=request.user)
exc... | View an individual thread. |
356,044 | def changecolourmode(self, newcolour):
if type(newcolour) != type(0) and self.pilimage.mode != "RGB":
if self.verbose :
print "Switching to RGB !"
self.pilimage = self.pilimage.convert("RGB")
self.draw = None
self.makedraw() | Auxiliary method to change the colour mode.
Give me a colour (either an int, or a 3-tuple, values 0 to 255) and I decide if the image mode has to
be switched from "L" to "RGB". |
356,045 | def validate(self, input, is_substitute):
constraint = self.__get_constraint(input)
to_validate = self.__get_to_validate(input)
return self.__compare(to_validate, constraint) | Performs validation
:param input: object to validate
:param is_substitute: will be used for what-if in the future
:return: validation result if violated or None |
356,046 | def _findAll(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
elif text is None and not limit and not attrs and not kwargs:
if name is... | Iterates over a generator looking for things that match. |
356,047 | def is_sub_plate(self, other):
if all(v in set(other.values) for v in self.values):
return True
if all(any(all(spv in m for spv in v) for m in map(set, other.values)) for v in self.values):
return True
if other in self.ancestor_plates:
return True
... | Determines if this plate is a sub-plate of another plate -
i.e. has the same meta data but a restricted set of values
:param other: The other plate
:return: True if this plate is a sub-plate of the other plate |
356,048 | def create_session(
self,
kind: SessionKind,
proxy_user: str = None,
jars: List[str] = None,
py_files: List[str] = None,
files: List[str] = None,
driver_memory: str = None,
driver_cores: int = None,
executor_memory: str = None,
executor_cor... | Create a new session in Livy.
The py_files, files, jars and archives arguments are lists of URLs,
e.g. ["s3://bucket/object", "hdfs://path/to/file", ...] and must be
reachable by the Spark driver process. If the provided URL has no
scheme, it's considered to be relative to the default ... |
356,049 | def hasFeature(featureList, feature):
for f in featureList:
if f[0] == feature or Features[f[0]] == feature:
return f[1] | return the controlCode for a feature or None
@param feature: feature to look for
@param featureList: feature list as returned by L{getFeatureRequest()}
@return: feature value or None |
356,050 | def _next_token(sql):
i = 0
def always_true(s, i):
return True
while i < len(sql):
start = i
if start_multi_line_comment(sql, i):
i += 1
end_checker = end_multi_line_comment
elif start_single_line_comment(sql, i):
i += 1
end_checker = end_single_line... | This is a basic tokenizer for our limited purposes.
It splits a SQL statement up into a series of segments, where a segment is one of:
- identifiers
- left or right parentheses
- multi-line comments
- single line comments
- white-space sequences
- string literals
- consecutive strings of characters that... |
356,051 | def flatten_evidence(stmts, collect_from=None):
if collect_from is None:
collect_from =
if collect_from not in (, ):
raise ValueError(
)
logger.info( % collect_from)
stmts = fast_deepcopy(stmts)
for stmt in stmts:
ori... | Add evidence from *supporting* stmts to evidence for *supported* stmts.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
A list of top-level statements with associated supporting statements
resulting from building a statement hierarchy with
:py:meth:`comb... |
356,052 | def register(xmlstream,
query_xso,
timeout=60,
):
iq = aioxmpp.IQ(
to=aioxmpp.JID.fromstr(xmlstream._to),
type_=aioxmpp.IQType.SET,
payload=query_xso
)
iq.autoset_id()
yield from aioxmpp.protocol.send_and_wait_for(xmlstream,
... | Create a new account on the server.
:param query_xso: XSO with the information needed for the registration.
:type query_xso: :class:`~aioxmpp.ibr.Query`
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aiox... |
356,053 | def save_model(model: AbstractModel, name_suffix: str, on_failure: str) -> None:
try:
logging.debug()
save_path = model.save(name_suffix)
logging.info(, save_path)
except Exception as ex:
if on_failure == :
raise IOError() from e... | Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: action to be taken on failure; one of :py:attr:`SAVE_FAILURE_ACTIONS`
:raise IOError: on save fai... |
356,054 | def unpack_rsp(cls, rsp_pb):
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
order_id = str(rsp_pb.s2c.orderID)
return RET_OK, "", order_id | Convert from PLS response to user response |
356,055 | def run(cmd, cwd=None, silent=None, return_output=False, raises=True, **subprocess_args):
if isinstance(cmd, str):
cmd = cmd.split()
cmd_str = .join(cmd)
if in subprocess_args and subprocess_args[]:
cmd = cmd_str
log.debug(, cmd_str, % cwd if cwd else )
if return_output a... | Runs a CLI command.
:param list/str cmd: Command with args to run.
:param str cwd: Change directory to cwd before running
:param bool/int silent: Suppress stdout/stderr.
If True, completely silent.
If 2, print cmd output on error.
:param bool retu... |
356,056 | def get_user_password (self):
if self.userinfo:
return urllib.splitpasswd(self.userinfo)
return self.aggregate.config.get_user_password(self.url) | Get tuple (user, password) from configured authentication.
Both user and password can be None. |
356,057 | def add_comment(self, text):
response = self.reddit_session._add_comment(self.fullname, text)
self.reddit_session.evict(self._api_link)
return response | Comment on the submission using the specified text.
:returns: A Comment object for the newly created comment. |
356,058 | def spell(word: str, engine: str = "pn") -> List[str]:
return DEFAULT_SPELL_CHECKER.spell(word) | :param str word: word to check spelling
:param str engine:
* pn - Peter Norvig's algorithm (default)
:return: list of words |
356,059 | def Publish(self, event_name, msg, delay=0):
events_lib.Events.PublishEvent(event_name, msg, delay=delay) | Sends the message to event listeners. |
356,060 | def add_convolution(self, name, kernel_channels, output_channels, height,
width, stride_height, stride_width, border_mode, groups, W, b, has_bias,
is_deconv = False, output_shape = None,
input_name = , output_name = ,
dilation_factors = [1,1],
padding_top = 0,... | Add a convolution layer to the network.
Please see the ConvolutionLayerParams in Core ML neural network
protobuf message for more information about input and output blob dimensions.
Parameters
----------
name: str
The name of this layer.
kernel_channels: int... |
356,061 | def getCentreAndSpreadOffsets(spaceShape,
spreadShape,
stepSize=1):
from nupic.math.cross import cross
shape = spaceShape
if shape[0] == 1 and shape[1] == 1:
centerOffsets = [(0,0)]
else:
xMin = -1 * (shape[1] // 2)
xMax = ... | Generates centre offsets and spread offsets for block-mode based training
regimes - star, cross, block.
Parameters:
-----------------------------------------------
spaceShape: The (height, width) of the 2-D space to explore. This
sets the number of center-points.
spreadShape: The... |
356,062 | def open(self):
device_type =
if self.transport == :
device_type =
self.device = ConnectHandler(device_type=device_type,
host=self.hostname,
username=self.username,
... | Open a connection to the device. |
356,063 | def flatten(attrs, inputs, proto_obj):
if in attrs and attrs[] != 1:
raise RuntimeError("Flatten operator only supports axis=1")
new_attrs = translation_utils._remove_attributes(attrs, [])
return , new_attrs, inputs | Flattens the input array into a 2-D array by collapsing the higher dimensions. |
356,064 | def get_next_valid_time_from_t(self, timestamp):
if self.is_time_valid(timestamp):
return timestamp
t_day = self.get_next_valid_day(timestamp)
if t_day is None:
return t_day
if timestamp < t_day:
sec_from_morning =... | Get next valid time for time range
:param timestamp: time we compute from
:type timestamp: int
:return: timestamp of the next valid time (LOCAL TIME)
:rtype: int | None |
356,065 | def request(self, _cache_key, _cache_ignore, _cache_timeout, **kwargs):
if _cache_key:
url, items = _cache_key
_cache_key = (url, (items[0], items[1], items[3], items[4]))
if kwargs[].method != :
... | This is a wrapper function that handles the caching of the request.
See DefaultHandler.with_cache for reference. |
356,066 | def get(self, name, *subkey):
if subkey == []:
return self.get_atomic(name)
else:
return self.get_subkey(name, tuple(subkey)) | retrieves a data item, or loads it if it
is not present. |
356,067 | async def handle_disconnect_callback(self):
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.res... | Reconnect automatically unless stopping. |
356,068 | def write_lammpsdata(structure, filename, atom_style=):
if atom_style not in [, , , ]:
raise ValueError(.format(atom_style))
xyz = np.array([[atom.xx,atom.xy,atom.xz] for atom in structure.atoms])
forcefield = True
if structure[0].type == :
forcefield = False
box = Box(... | Output a LAMMPS data file.
Outputs a LAMMPS data file in the 'full' atom style format. Assumes use
of 'real' units. See http://lammps.sandia.gov/doc/atom_style.html for
more information on atom styles.
Parameters
----------
structure : parmed.Structure
ParmEd structure object
f... |
356,069 | def drop_table(model, keyspaces=None, connections=None):
context = _get_context(keyspaces, connections)
for connection, keyspace in context:
with query.ContextQuery(model, keyspace=keyspace) as m:
_drop_table(m, connection=connection) | Drops the table indicated by the model, if it exists.
If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case.
If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__c... |
356,070 | def _tValueForPointOnCubicCurve(point, cubicCurve, isHorizontal=0):
pt1, pt2, pt3, pt4 = cubicCurve
a, b, c, d = bezierTools.calcCubicParameters(pt1, pt2, pt3, pt4)
solutions = bezierTools.solveCubic(a[isHorizontal], b[isHorizontal], c[isHorizontal],
d[isHorizontal] - point[isHorizontal])
s... | Finds a t value on a curve from a point.
The points must be originaly be a point on the curve.
This will only back trace the t value, needed to split the curve in parts |
356,071 | def get_privatekey(keydata):
key = serialization.load_pem_private_key(
keydata,
password=None,
backend=default_backend(),
)
return key | Load the private key from a PEM encoded string. |
356,072 | def getPrevUrl(self, url, data):
if in url:
return url.replace(, )
if in url:
return url.replace(, )
if in url:
return url.replace(, )
return None | Find previous URL. |
356,073 | def main():
try:
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
device.on_message += handle_message
| Example application that opens a serial device and prints messages to the terminal. |
356,074 | def send(self, cmd):
with self.ws_sendlock:
self.ws.send(json.dumps(cmd)) | Send the given command thru the websocket |
356,075 | def render_vars(self):
return {
: [
{
: record.getMessage(),
: dt.datetime.fromtimestamp(record.created).strftime(),
} for record in self.handler.records
]
} | Template variables. |
356,076 | def recall(y, y_pred):
tp = true_positives(y, y_pred)
fn = false_negatives(y, y_pred)
return tp / (tp + fn) | Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float |
356,077 | def select_as_multiple(self, keys, where=None, selector=None, columns=None,
start=None, stop=None, iterator=False,
chunksize=None, auto_close=False, **kwargs):
where = _ensure_term(where, scope_level=1)
if isinstance(keys, (list, t... | Retrieve pandas objects from multiple tables
Parameters
----------
keys : a list of the tables
selector : the table to apply the where criteria (defaults to keys[0]
if not supplied)
columns : the columns I want back
start : integer (defaults to None), row num... |
356,078 | def add(self, other):
if other.empty():
return
to_add = set()
for inter in self:
if inter.overlaps(other):
to_add.add(inter.union(other))
if len(to_add) == 0:
to_add.add(other)
if len(to_add) > 1:
... | Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing
Interval objects in self.
This has no effect if the Interval is already represented.
:param other: an Interval to add to this IntervalSet. |
356,079 | def meryl(args):
p = OptionParser(meryl.__doc__)
p.add_option("-k", default=19, type="int", help="Kmer size")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
folder, = args
K = opts.k
cpus = opts.cpus
mm = MakeManager()
... | %prog meryl folder
Run meryl on Illumina reads. |
356,080 | def organization_related(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organizations
api_path = "/api/v2/organizations/{id}/related.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/organizations#show-organizations-related-information |
356,081 | def calc_windowed_sum(aa_mut_pos,
germ_aa,
somatic_aa,
window=[3]):
pos_ctr, pos_sum = {}, {w: {} for w in window}
num_pos = len(aa_mut_pos)
for i in range(num_pos):
pos = aa_mut_pos[i]
if germ_aa[i] and som... | Calculate the sum of mutations within a window around a particular mutated
codon.
Parameters
----------
aa_mut_pos : list
list of mutated amino acid positions
germ_aa : list
Reference amino acid
somatic_aa : list
Somatic amino acid (if missense)
window : list
... |
356,082 | def gen(self, num, cat=None, cat_group=None, preferred=None, preferred_ratio=0.5, max_recursion=None, auto_process=True):
import gramfuzz.fields
gramfuzz.fields.REF_LEVEL = 1
if cat is None and cat_group is None:
raise gramfuzz.errors.GramFuzzError("cat and cat_group are No... | Generate ``num`` rules from category ``cat``, optionally specifying
preferred category groups ``preferred`` that should be preferred at
probability ``preferred_ratio`` over other randomly-chosen rule definitions.
:param int num: The number of rules to generate
:param str cat: The name o... |
356,083 | def _get_stockprices(symbols, chart_range=):
s 100 stocks limit per request.
dateopenhighlowclosevolumedate')
df.index = pd.to_datetime(df.index, utc=True)
result[symbol] = df
return result
return parallelize(fetch, splitlen=99)(symbols) | Get stock data (key stats and previous) from IEX.
Just deal with IEX's 100 stocks limit per request. |
356,084 | def lowres_tensor(shape, underlying_shape, offset=None, sd=None):
sd = sd or 0.01
init_val = sd * np.random.randn(*underlying_shape).astype("float32")
underlying_t = tf.Variable(init_val)
t = resize_bilinear_nd(underlying_t, shape)
if offset is not None:
if not isinstance(offse... | Produces a tensor paramaterized by a interpolated lower resolution tensor.
This is like what is done in a laplacian pyramid, but a bit more general. It
can be a powerful way to describe images.
Args:
shape: desired shape of resulting tensor
underlying_shape: shape of the tensor being resized into final ... |
356,085 | def _get_value(self, key, context):
string_quotes = (, "'")
if key[0] in string_quotes and key[-1] in string_quotes:
return key[1:-1]
if key in string.digits:
return int(key)
return context.get(key, None) | Works out whether key is a value or if it's a variable referencing a
value in context and returns the correct value. |
356,086 | def node(self, nodeid):
_assert_valid_nodeid(nodeid)
return Node(hub=Hub(nodeid=nodeid)) | Creates a new node with the specified name, with `MockSocket` instances as incoming and outgoing sockets.
Returns the implementation object created for the node from the cls, args and address specified, and the sockets.
`cls` must be a callable that takes the insock and outsock, and the specified args ... |
356,087 | def rmultivariate_hypergeometric(n, m, size=None):
N = len(m)
urn = np.repeat(np.arange(N), m)
if size:
draw = np.array([[urn[i] for i in np.random.permutation(len(urn))[:n]]
for j in range(size)])
r = [[np.sum(draw[j] == i) for i in range(len(m))]
... | Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy. |
356,088 | def setCurrentSchemaPath(self, path):
if not path:
return False
parts = path.split()
name = parts[0]
next = parts[1:]
if name == self.text(0):
if next:
self.load()
path = .join(next)
... | Sets the current item based on the inputed column.
:param path | <str> |
356,089 | def write_gexf(docgraph, output_file):
dg_copy = deepcopy(docgraph)
remove_root_metadata(dg_copy)
layerset2str(dg_copy)
attriblist2str(dg_copy)
nx_write_gexf(dg_copy, output_file) | takes a document graph, converts it into GEXF format and writes it to
a file. |
356,090 | def parent_is_inet():
result = False
sock = socket.fromfd(
sys.__stdin__.fileno(),
socket.AF_INET,
socket.SOCK_RAW)
try:
sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
result = True
except (OSError, socket.error) as err:
if not err.args[0] == errn... | Check if parent is inet
Check if our parent seems ot be a superserver, aka inetd/xinetd.
This is done by checking if sys.__stdin__ is a network socket.
:return: bool |
356,091 | def generate_doc_length_stats(self):
heuristic = self.heuristic_pct
histdf = (pd.DataFrame([(a, b) for a, b in self.document_length_histogram.items()],
columns=[, ])
.sort_values(by=))
histdf[] = histdf.doc_count.cumsum() / histdf.doc_cou... | Analyze document length statistics for padding strategy |
356,092 | def iter_chunks(chunksize, *iterables):
iterables = iter(zip(*iterables))
while 1:
chunk = tuple(islice(iterables, chunksize))
if not chunk:
return
yield chunk | Iterates over zipped iterables in chunks. |
356,093 | def center_of_mass(self):
weights = [s.species.weight for s in self]
center_of_mass = np.average(self.frac_coords,
weights=weights, axis=0)
return center_of_mass | Calculates the center of mass of the slab |
356,094 | def nl_wait_for_ack(sk):
cb = nl_cb_clone(sk.s_cb)
nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, lambda *_: NL_STOP, None)
return int(nl_recvmsgs(sk, cb)) | Wait for ACK.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1058
Waits until an ACK is received for the latest not yet acknowledged Netlink message.
Positional arguments:
sk -- Netlink socket (nl_sock class instance).
Returns:
Number of received messages or a negative error cod... |
356,095 | def daily_returns(self, start, end=None):
if end is None:
return self._daily_returns[start]
return self._daily_returns[start:end] | Returns the daily returns for the given period.
Parameters
----------
start : datetime
The inclusive starting session label.
end : datetime, optional
The inclusive ending session label. If not provided, treat
``start`` as a scalar key.
Return... |
356,096 | def sens_power_board_send(self, timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp, force_mavlink1=False):
retur... | Monitoring of power board status
timestamp : Timestamp (uint64_t)
pwr_brd_status : Power board status register (uint8_t)
pwr_brd_led_status : Power board leds status (uint8_t)
pwr_brd_system_volt : Power board syst... |
356,097 | def generateVariant(self, referenceName, position, randomNumberGenerator):
variant = self._createGaVariant()
variant.reference_name = referenceName
variant.start = position
variant.end = position + 1
bases = ["A", "C", "G", "T"]
ref = randomNumberGenerator.choi... | Generate a random variant for the specified position using the
specified random number generator. This generator should be seeded
with a value that is unique to this position so that the same variant
will always be produced regardless of the order it is generated in. |
356,098 | def add_capability(capability,
source=None,
limit_access=False,
image=None,
restart=False):
*
if salt.utils.versions.version_cmp(__grains__[], ) == -1:
raise NotImplementedError(
.format(__grains__[]))
... | Install a capability
Args:
capability (str): The capability to install
source (Optional[str]): The optional source of the capability. Default
is set by group policy and can be Windows Update.
limit_access (Optional[bool]): Prevent DISM from contacting Windows
Update ... |
356,099 | def tokentype(self, s):
a = s[0] if len(s)>0 else ""
b = s[1] if len(s)>1 else ""
if a.isdigit() or (a in ["+","-"] and b.isdigit()):
return self.parse_number(s)
elif a == : return self.parse_string(s)
elif a == : return self.parse_colon(s)
elif a ==... | Parses string and returns a (Tokenizer.TYPE, value) tuple. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.