Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
379,200 | def add_system(self, system):
if system not in self._systems:
system.set_world(self)
self._systems.append(system)
else:
raise DuplicateSystemError(system) | Add system to the world.
All systems will be processed on World.process()
system is of type System |
379,201 | def alias_repository(self, repository_id=None, alias_id=None):
if not self._can():
raise PermissionDenied()
else:
return self._provider_session.alias_repository(repository_id) | Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Repository`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
the alias is a pointer to another repository, it is reassigned
to the given reposito... |
379,202 | def createRandomObjectDescriptions(numObjects,
numLocationsPerObject,
featurePool=("A", "B", "C")):
return dict(("Object %d" % i,
zip(xrange(numLocationsPerObject),
[random.choice(featurePool)
... | Returns {"Object 1": [(0, "C"), (1, "B"), (2, "C"), ...],
"Object 2": [(0, "C"), (1, "A"), (2, "B"), ...]} |
379,203 | def simBirth(self,which_agents):
N = np.sum(which_agents)
self.aNrmNow[which_agents] = drawLognormal(N,mu=self.aNrmInitMean,sigma=self.aNrmInitStd,seed=self.RNG.randint(0,2**31-1))
pLvlInitMeanNow = self.pLvlInitMean + np.log(self.PlvlAggNow)
self.pLvlNow[which_agents... | Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and permanent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
... |
379,204 | def generate_openmp_enabled_py(packagename, srcdir=, disable_openmp=None):
if packagename.lower() == :
packagetitle =
else:
packagetitle = packagename
epoch = int(os.environ.get(, time.time()))
timestamp = datetime.datetime.utcfromtimestamp(epoch)
if disable_openmp is not No... | Generate ``package.openmp_enabled.is_openmp_enabled``, which can then be used
to determine, post build, whether the package was built with or without
OpenMP support. |
379,205 | def interpolate_to_isosurface(level_var, interp_var, level, **kwargs):
r
bottom_up_search = kwargs.pop(, True)
above, below, good = metpy.calc.find_bounding_indices(level_var, [level], axis=0,
from_below=bottom_up_search)
in... | r"""Linear interpolation of a variable to a given vertical level from given values.
This function assumes that highest vertical level (lowest pressure) is zeroth index.
A classic use of this function would be to compute the potential temperature on the
dynamic tropopause (2 PVU surface).
Parameters
... |
379,206 | def getlist(self, key):
value = self.get(key, [])
if value is None or isinstance(value, (list, tuple)):
return value
else:
return [value] | Returns a Storage value as a list.
If the value is a list it will be returned as-is.
If object is None, an empty list will be returned.
Otherwise, `[value]` will be returned.
Example output for a query string of `?x=abc&y=abc&y=def`::
>>> request = Storage()
>>... |
379,207 | def start(self):
log.info(, self.host, self.port)
if not self.base_pathname:
tmpl = (
)
raise NotInitializedError(tmpl % self.base_pathname)
conf_file = os.path.join(self.base_pathname, )
if not os.path.exists(conf_file):
... | Launch this postgres server. If it's already running, do nothing.
If the backing storage directory isn't configured, raise
NotInitializedError.
This method is optional. If you're running in an environment
where the DBMS is provided as part of the basic infrastructure,
you pro... |
379,208 | def get_process_curses_data(self, p, first, args):
ret = [self.curse_new_line()]
if in p and p[] is not None and p[] != :
if args.disable_irix and self.nb_log_core != 0:
msg = self.layout_stat[].format(p[] / float(self.nb_log_core))
else:
... | Get curses data to display for a process.
- p is the process to display
- first is a tag=True if the process is the first on the list |
379,209 | def get(self, key, failobj=None, exact=0):
if not exact:
key = self.getfullkey(key,new=1)
return self.data.get(key,failobj) | Raises exception if key is ambiguous |
379,210 | def parse(self, limit=None):
if limit is not None:
LOG.info("Only parsing first %d rows", limit)
LOG.info("Parsing files...")
if self.test_only:
self.test_mode = True
self.geno = Genotype(s... | Override Source.parse()
Parses version and interaction information from CTD
Args:
:param limit (int, optional) limit the number of rows processed
Returns:
:return None |
379,211 | def hydrate_target(hydrated_struct):
target_adaptor = hydrated_struct.value
hydrated_fields = yield [Get(HydratedField, HydrateableField, fa)
for fa in target_adaptor.field_adaptors]
kwargs = target_adaptor.kwargs()
for field in hydrated_fields:
kwargs[field.name] = field.va... | Construct a HydratedTarget from a TargetAdaptor and hydrated versions of its adapted fields. |
379,212 | def eject_media(self):
try:
super(VirtualMedia, self).eject_media()
except sushy_exceptions.SushyError:
target_uri = self._get_action_element().target_uri
self._conn.post(target_uri, data={}) | Ejects Virtual Media.
:raises: SushyError, on an error from iLO. |
379,213 | def RepackTemplate(self,
template_path,
output_dir,
upload=False,
token=None,
sign=False,
context=None,
signed_template=False):
orig_config = config.CONFIG
repa... | Repack binaries based on the configuration.
We repack all templates in the templates directory. We expect to find only
functioning templates, all other files should be removed. Each template
contains a build.yaml that specifies how it was built and how it should be
repacked.
Args:
template_p... |
379,214 | def is_choked_turbulent_l(dP, P1, Psat, FF, FL=None, FLP=None, FP=None):
r
if FLP and FP:
return dP >= (FLP/FP)**2*(P1-FF*Psat)
elif FL:
return dP >= FL**2*(P1-FF*Psat)
else:
raise Exception() | r'''Calculates if a liquid flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 liquid valve sizing calculations.
Either FL may be provided or FLP and FP, depending on the calculation
process.
.. math::
\Delta P > F_L^2(P_1 - F_F P_{sat})
.. math::
\Delta P >= \l... |
379,215 | def colored_pygments_excepthook(type_, value, tb):
tbtext = .join(traceback.format_exception(type_, value, tb))
try:
from utool import util_str
formatted_text = util_str.highlight_text(tbtext, lexer_name=,
stripall=True)
except Exception:... | References:
https://stackoverflow.com/questions/14775916/color-exceptions-python
CommandLine:
python -m utool.util_inject --test-colored_pygments_excepthook |
379,216 | def read_rels(archive):
xml_source = archive.read(ARC_WORKBOOK_RELS)
tree = fromstring(xml_source)
for element in safe_iterator(tree, % PKG_REL_NS):
rId = element.get()
pth = element.get("Target")
typ = element.get()
if pth.startswith("/xl"):
pth = ... | Read relationships for a workbook |
379,217 | def removeApplicationManifest(self, pchApplicationManifestFullPath):
fn = self.function_table.removeApplicationManifest
result = fn(pchApplicationManifestFullPath)
return result | Removes an application manifest from the list to load when building the list of installed applications. |
379,218 | def messages(request, year=None, month=None, day=None,
template="gnotty/messages.html"):
query = request.REQUEST.get("q")
prev_url, next_url = None, None
messages = IRCMessage.objects.all()
if hide_joins_and_leaves(request):
messages = messages.filter(join_or_leave=False)
... | Show messages for the given query or day. |
379,219 | def ChangeUserStatus(self, Status):
if self.CurrentUserStatus.upper() == Status.upper():
return
self._ChangeUserStatus_Event = threading.Event()
self._ChangeUserStatus_Status = Status.upper()
self.RegisterEventHandler(, self._ChangeUserStatus_UserStatus)
self... | Changes the online status for the current user.
:Parameters:
Status : `enums`.cus*
New online status for the user.
:note: This function waits until the online status changes. Alternatively, use the
`CurrentUserStatus` property to perform an immediate change of stat... |
379,220 | def unlock_key(key_name,
stash,
passphrase,
backend):
stash = _get_stash(backend, stash, passphrase)
try:
click.echo()
stash.unlock(key_name=key_name)
click.echo()
except GhostError as ex:
sys.exit(ex) | Unlock a key to allow it to be modified, deleted or purged
`KEY_NAME` is the name of the key to unlock |
379,221 | def encodeSplines(x, n_bases=10, spline_order=3, start=None, end=None, warn=True):
if len(x.shape) == 1:
x = x.reshape((-1, 1))
if start is None:
start = np.nanmin(x)
else:
if x.min() < start:
if warn:
print("WARNING, x.min() < start for some e... | **Deprecated**. Function version of the transformer class `EncodeSplines`.
Get B-spline base-function expansion
# Details
First, the knots for B-spline basis functions are placed
equidistantly on the [start, end] range.
(inferred from the data if None). Next, b_n(x) value is
is ... |
379,222 | def dimap_V(D, I):
DI = np.array([D, I]).transpose()
X = dir2cart(DI).transpose()
R = np.sqrt(1. - abs(X[2]))/(np.sqrt(X[0]**2 + X[1]**2))
XY = np.array([X[1] * R, X[0] * R]).transpose()
return XY | FUNCTION TO MAP DECLINATION, INCLINATIONS INTO EQUAL AREA PROJECTION, X,Y
Usage: dimap_V(D, I)
D and I are both numpy arrays |
379,223 | def load_model(path):
assert_is_type(path, str)
res = api("POST /99/Models.bin/%s" % "", data={"dir": path})
return get_model(res["models"][0]["model_id"]["name"]) | Load a saved H2O model from disk. (Note that ensemble binary models can now be loaded using this method.)
:param path: the full path of the H2O Model to be imported.
:returns: an :class:`H2OEstimator` object
:examples:
>>> path = h2o.save_model(my_model, dir=my_path)
>>> h2o.load_model(pa... |
379,224 | def _escalation_rules_to_string(escalation_rules):
result =
for rule in escalation_rules:
result += .format(rule[])
for target in rule[]:
result += .format(target[], target[])
return result | convert escalation_rules dict to a string for comparison |
379,225 | def merge(self, workdir, ddb_files, out_ddb, description, delete_source_ddbs=True):
ddb_files = [os.path.abspath(s) for s in list_strings(ddb_files)]
if not os.path.isabs(out_ddb):
out_ddb = os.path.join(os.path.abspath(workdir), os.path.basename(out_ddb))
if self.... | Merge DDB file, return the absolute path of the new database in workdir. |
379,226 | def initialize_zones(self):
zone_list = self.location_info.get(, {: True})
for zone_id in zone_list:
if zone_list[zone_id]:
self.zones[zone_id] = Zone(self, zone_id=zone_id)
else:
_LOGGER.debug("Ignoring zone: %s", zo... | initialize receiver zones |
379,227 | def get_root():
root = os.path.realpath(os.path.abspath(os.getcwd()))
setup_py = os.path.join(root, "setup.py")
versioneer_py = os.path.join(root, "versioneer.py")
if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
root = os.path.dirname(os.path.realpath(os.path.ab... | Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg, and versioneer.py . |
379,228 | def valueReadPreprocessor(valueString, replaceParamsFile=None):
if type(valueString) is bool:
log.warning("Only numerical variable types can be handled by the valueReadPreprocessor function.")
return valueString
processedValue = valueString
if replaceParamsFile is not None a... | Apply global pre-processing to values during reading throughout the project.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if
replacement variables are i... |
379,229 | def deletescript(self, name):
code, data = self.__send_command(
"DELETESCRIPT", [name.encode("utf-8")])
if code == "OK":
return True
return False | Delete a script from the server
See MANAGESIEVE specifications, section 2.10
:param name: script's name
:rtype: boolean |
379,230 | def parse_serialdiff(sd_dict):
"helper for translate_check"
if isinstance(sd_dict,list):
if len(sd_dict)!=2 or sd_dict[0]!=: raise NotImplementedError(sd_dict[0],len(sd_dict))
return CheckStale(sd_dict[1])
if isinstance(sd_dict[],list):
sd_dict[]=[diff.Delta(d[][],d[][],d[]) for d in sd_dict[]]
... | helper for translate_check |
379,231 | def get_log_entry_ids_by_log(self, log_id):
id_list = []
for log_entry in self.get_log_entries_by_log(log_ids):
id_list.append(log_entry.get_id())
return IdList(id_list) | Gets the list of ``LogEntry`` ``Ids`` associated with a ``Log``.
arg: log_id (osid.id.Id): ``Id`` of a ``Log``
return: (osid.id.IdList) - list of related logEntry ``Ids``
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``log_id`` is ``null``
raise: Operati... |
379,232 | def raw(node):
o = nodes.raw(node.literal, node.literal, format=)
if node.sourcepos is not None:
o.line = node.sourcepos[0][0]
for n in MarkDown(node):
o += n
return o | Add some raw html (possibly as a block) |
379,233 | def _read_header(filename):
with filename.open() as f:
h = f.read(HDR_LENGTH).decode()
header = {}
for line in h.split():
if in line:
key, value = line.split()
key = key.strip()[7:]
value = value.strip()[:-1]
... | Read the text header for each file
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
dict
header |
379,234 | def custom_config(request):
if request.method == :
config_dict = json_body(request.body.decode())
CustomConfig.objects.try_create(
config_dict[],
config_dict[],
config_dict[],
request.user.id,
config_dict.get() if config_dict.get() els... | Save user-specific configuration property.
POST parameters (JSON keys):
app_name: application name for which the configuration property is
valid (e.g., proso_models)
key: name of the property (e.g., predictive_model.class)
value: value of the property (number, string, boolean, .... |
379,235 | def reg_load(self, reg, value):
if isinstance(value, (six.text_type, six.binary_type)):
value = self.alloc_data(value)
if value is None:
return self.reg_load_imm(reg, 0)
elif isinstance(value, Register):
if reg is not value:
return ... | Load a value into a register. The value can be a string or binary (in
which case the value is passed to :meth:`alloc_data`), another
:class:`Register`, an :class:`Offset` or :class:`Buffer`, an integer
immediate, a ``list`` or ``tuple`` or a syscall invocation.
Arguments:
re... |
379,236 | def get_waveform_filter_norm(approximant, psd, length, delta_f, f_lower):
if approximant in _filter_norms:
return _filter_norms[approximant](psd, length, delta_f, f_lower)
else:
return None | Return the normalization vector for the approximant |
379,237 | def handle_message(self, ch, method, properties, body):
input = {}
headers = {}
try:
self.sessid = method.routing_key
input = json_decode(body)
data = input[]
self.send_output(output) | this is a pika.basic_consumer callback
handles client inputs, runs appropriate workflows and views
Args:
ch: amqp channel
method: amqp method
properties:
body: message body |
379,238 | def make_accessors(self, columns):
accessors = list(self.accessors_def or range(columns))
for i, x in enumerate(accessors):
if not callable(x):
if isinstance(x, collections.abc.Sequence) and \
not isinstance(x, str):
key, defaul... | Accessors can be numeric keys for sequence row data, string keys
for mapping row data, or a callable function. For numeric and string
accessors they can be inside a 2 element tuple where the 2nd value is
the default value; Similar to dict.get(lookup, default). |
379,239 | def get_id(self, natural_key, enhancement=None):
if natural_key in self._map:
return self._map[natural_key]
self.pre_call_stored_procedure()
success = False
try:
key = self.call_stored_procedure(natural_key, enhancement)
... | Returns the technical ID for a natural key or None if the given natural key is not valid.
:param T natural_key: The natural key.
:param T enhancement: Enhancement data of the dimension row.
:rtype: int|None |
379,240 | def write(pkg_file, pkg_rels, parts):
phys_writer = PhysPkgWriter(pkg_file)
PackageWriter._write_content_types_stream(phys_writer, parts)
PackageWriter._write_pkg_rels(phys_writer, pkg_rels)
PackageWriter._write_parts(phys_writer, parts)
phys_writer.close() | Write a physical package (.pptx file) to *pkg_file* containing
*pkg_rels* and *parts* and a content types stream based on the
content types of the parts. |
379,241 | def spine_to_terminal_wedge(mol):
for i, a in mol.atoms_iter():
if mol.neighbor_count(i) == 1:
ni, nb = list(mol.neighbors(i).items())[0]
if nb.order == 1 and nb.type in (1, 2) \
and ni > i != nb.is_lower_first:
nb.is_lower_first = not nb.is_l... | Arrange stereo wedge direction from spine to terminal atom |
379,242 | def create(self, sid=values.unset, phone_number=values.unset,
is_reserved=values.unset):
data = values.of({: sid, : phone_number, : is_reserved, })
payload = self._version.create(
,
self._uri,
data=data,
)
return PhoneNumberIn... | Create a new PhoneNumberInstance
:param unicode sid: The SID of a Twilio IncomingPhoneNumber resource
:param unicode phone_number: The phone number in E.164 format
:param bool is_reserved: Whether the new phone number should be reserved
:returns: Newly created PhoneNumberInstance
... |
379,243 | def compare(self, otherdigest, ishex=False):
bits = 0
myd = self.digest()
if ishex:
otherdigest = tuple([int(otherdigest[i:i+2],16) for i in range(0,63,2)])
for i in range(32):
bits += POPC[255 & myd[i] ^ otherdigest[i]]
return 128 - ... | Compute difference in bits between own digest and another.
returns -127 to 128; 128 is the same, -127 is different |
379,244 | def api_version_elb_backend(*args, **kwargs):
request = args[0]
if hasattr(request, ):
version = request.values.get()
elif isinstance(request, AWSPreparedRequest):
version = parse_qs(request.body).get()[0]
else:
request.parse_request()
ver... | ELB and ELBV2 (Classic and Application load balancers) use the same
hostname and url space. To differentiate them we must read the
`Version` parameter out of the url-encoded request body. TODO: There
has _got_ to be a better way to do this. Please help us think of
one. |
379,245 | def delete_resource(self, resource_id):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
if not isinstance(resource_id, ABCId):
raise errors.InvalidArgument()
... | Deletes a ``Resource``.
arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource``
to remove
raise: NotFound - ``resource_id`` not found
raise: NullArgument - ``resource_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: Permiss... |
379,246 | def correct(self, images,
bgImages=None,
exposure_time=None,
light_spectrum=None,
threshold=0.1,
keep_size=True,
date=None,
deblur=False,
denoise=False):
30. Nov 15dark curren... | exposure_time [s]
date -> string e.g. '30. Nov 15' to get a calibration on from date
-> {'dark current':'30. Nov 15',
'flat field':'15. Nov 15',
'lens':'14. Nov 15',
'noise':'01. Nov 15'} |
379,247 | def MessageToJson(message, include_fields=None):
result = _ProtoJsonApiTools.Get().encode_message(message)
return _IncludeFields(result, message, include_fields) | Convert the given message to JSON. |
379,248 | def from_filename(cls, filename, sync_from_start=True):
from pygments.util import ClassNotFound
from pygments.lexers import get_lexer_for_filename
try:
pygments_lexer = get_lexer_for_filename(filename)
except ClassNotFound:
return SimpleLexer()
... | Create a `Lexer` from a filename. |
379,249 | def get_default_config_help(self):
config = super(StatsdHandler, self).get_default_config_help()
config.update({
: ,
: ,
: ,
})
return config | Returns the help text for the configuration options for this handler |
379,250 | def update(self):
con = self.subpars.pars.control
self(0.)
for idx in range(2):
if (con.bbv[idx] > 0.) and (con.bnv[idx] > 0.):
self.values[idx] = con.bbv[idx]/con.bnv[idx] | Update value based on :math:`HV=BBV/BNV`.
Required Parameters:
|BBV|
|BNV|
Examples:
>>> from hydpy.models.lstream import *
>>> parameterstep('1d')
>>> bbv(left=10., right=40.)
>>> bnv(left=10., right=20.)
>>> derived.... |
379,251 | def get_web_auth_session_key(self, url, token=""):
session_key, _username = self.get_web_auth_session_key_username(url, token)
return session_key | Retrieves the session key of a web authorization process by its URL. |
379,252 | def make_grid(xx, yy):
n = len(xx)
xx, yy = np.meshgrid(xx, yy)
grid = np.array([xx.ravel(), yy.ravel()]).T
x = grid[:, 0].reshape(n, n)
y = grid[:, 1].reshape(n, n)
return x, y | Returns two n-by-n matrices. The first one contains all the x values
and the second all the y values of a cartesian product between `xx` and `yy`. |
379,253 | def get_login_information(self, code=None):
access_token = self._get_access_token(code)
return self._get_user_info(access_token) | Return Clef user info after exchanging code for OAuth token. |
379,254 | def make_osm_query(query):
osm_url =
req = requests.get(osm_url, params={: query})
req.raise_for_status()
return req.json() | Make a request to OSM and return the parsed JSON.
Parameters
----------
query : str
A string in the Overpass QL format.
Returns
-------
data : dict |
379,255 | def read_stream (stream):
section = None
key = None
data = None
for fullline in stream:
line = fullline.split (, 1)[0]
m = sectionre.match (line)
if m is not None:
if section is not None:
if key is not None:
sec... | Python 3 compat note: we're assuming `stream` gives bytes not unicode. |
379,256 | def interpolate2dStructuredPointSpreadIDW(grid, mask, kernel=15, power=2,
maxIter=1e5, copy=True):
gridmask
assert grid.shape == mask.shape,
border = np.zeros(shape=mask.shape, dtype=np.bool)
if copy:
mask = mask.copy()
grid = ... | same as interpolate2dStructuredIDW but using the point spread method
this is faster if there are bigger connected masked areas and the border
length is smaller
replace all values in [grid] indicated by [mask]
with the inverse distance weighted interpolation of all values within
px+-kernel
... |
379,257 | def psq2(d1, d2):
d1, d2 = flatten(d1), flatten(d2)
def f(p):
return sum((p ** 2) * np.nan_to_num(np.log(p * len(p))))
return abs(f(d1) - f(d2)) | Compute the PSQ2 measure.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution. |
379,258 | def add_proxy_auth(possible_proxy_url, proxy_auth):
if possible_proxy_url == :
return possible_proxy_url
parsed = urlparse(possible_proxy_url)
return .format(parsed.scheme, proxy_auth.username, proxy_auth.password, parsed.netloc) | Add a username and password to a proxy URL, if the input value is a proxy URL.
:param str possible_proxy_url: Proxy URL or ``DIRECT``.
:param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info.
:returns: Proxy URL with auth info added, or ``DIRECT``.
:rtype: str |
379,259 | def owner(self):
r
if os.name == :
if win32security is None:
raise Exception("path.owner requires win32all to be installed")
desc = win32security.GetFileSecurity(
self, win32security.OWNER_SECURITY_INFORMATION)
sid = desc.GetSecurityDes... | r""" Return the name of the owner of this file or directory.
This follows symbolic links.
On Windows, this returns a name of the form ur'DOMAIN\User Name'.
On Windows, a group can own a file or directory. |
379,260 | def netconf_session_end_termination_reason(self, **kwargs):
config = ET.Element("config")
netconf_session_end = ET.SubElement(config, "netconf-session-end", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
termination_reason = ET.SubElement(netconf_session_end, "terminati... | Auto Generated Code |
379,261 | def main():
args = docopt(__doc__, version=__version__)
if in args:
bam_coverage(args[],
args[],
int(args[]),
min_mapq=int(args[]),
min_len=float(args[])) | Main entry point for the bioinfo CLI. |
379,262 | def makeLUTfromCTF(sclist, N=None):
ctf = vtk.vtkColorTransferFunction()
ctf.SetColorSpaceToDiverging()
for sc in sclist:
scalar, col = sc
r, g, b = getColor(col)
ctf.AddRGBPoint(scalar, r, g, b)
if N is None:
N = len(sclist)
lut = vtk.vtkLookupTable()
lut... | Use a Color Transfer Function to generate colors in a vtk lookup table.
See `here <http://www.vtk.org/doc/nightly/html/classvtkColorTransferFunction.html>`_.
:param list sclist: a list in the form ``[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]``.
:return: the lookup table object ``vtkLookupTable``. This ca... |
379,263 | def blast_seqs_to_pdb(self, seq_ident_cutoff=0, evalue=0.0001, all_genes=False, display_link=False,
outdir=None, force_rerun=False):
counter = 0
for g in tqdm(self.genes_with_a_representative_sequence):
if g.protein.num_structures_experimental... | BLAST each representative protein sequence to the PDB. Saves raw BLAST results (XML files).
Args:
seq_ident_cutoff (float, optional): Cutoff results based on percent coverage (in decimal form)
evalue (float, optional): Cutoff for the E-value - filters for significant hits. 0.001 is libe... |
379,264 | def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
mean, stddevs = super().get_mean_and_stddevs(
sctx, rctx, dctx, imt, stddev_types)
cff = SInterCan15Mid.SITE_COEFFS[imt]
mean += np.log(cff[])
return mean, stddevs | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
379,265 | def reset_generation(self, trigger):
self.tone_lock.acquire()
npts = self.stim.size
try:
self.aotask = AOTaskFinite(self.aochan, self.fs, npts, trigsrc=trigger)
self.aotask.write(self.stim)
if self.attenuator is not None:
self.attenu... | Re-arms the analog output according to current settings
:param trigger: name of the trigger terminal. ``None`` value means generation begins immediately on run
:type trigger: str |
379,266 | def visit_BinOp(self, node: AST, dfltChaining: bool = True) -> str:
op = node.op
with self.op_man(op):
if isinstance(op, ast.Pow):
src = self.visit(op).join((self.visit(node.left,
dfltChaining=Fal... | Return `node`s operator and operands as inlined expression. |
379,267 | def create(self, fail_on_found=False, force_on_exists=False, **kwargs):
config_item = self._separate(kwargs)
jt_id = kwargs.pop(, None)
status = kwargs.pop(, )
old_endpoint = self.endpoint
if jt_id is not None:
jt = get_resource()
jt.get(pk=jt_id)... | Create a notification template.
All required configuration-related fields (required according to
notification_type) must be provided.
There are two types of notification template creation: isolatedly
creating a new notification template and creating a new notification
template ... |
379,268 | def _get_link_status_code(link, allow_redirects=False, timeout=5):
status_code = None
try:
response = requests.get(
link, allow_redirects=allow_redirects, timeout=timeout)
status_code = response.status_code
except Exception:
status_code = 404
return status_code | Get the status code of a link.
If the timeout is exceeded, will return a 404.
For a list of available status codes, see:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes |
379,269 | def toDict(self):
return {
: [hsp.toDict() for hsp in self.hsps],
: self.read.toDict(),
} | Get information about a title alignment as a dictionary.
@return: A C{dict} representation of the title aligment. |
379,270 | def _compute(self):
i = 0
while i < len(self.setd):
if self.ucld:
self.do_cld_check(self.setd[i:])
i = 0
if self.setd:
if self.oracle.solve(assumptions=self.ss_assumps + self.bb_assumps + [self.setd[i]... | The main method of the class, which computes an MCS given its
over-approximation. The over-approximation is defined by a model
for the hard part of the formula obtained in :func:`compute`.
The method is essentially a simple loop going over all literals
unsatisfied by the... |
379,271 | def delete_user(self, user_email):
res = self.get_user_ids([user_email])
if res[0] == False:
return res
userid = res[1][0]
res = requests.delete(self.url + + str(userid), headers=self.hdrs, verify=self.ssl_verify)
if not self._checkResponse(res):
... | **Description**
Deletes a user from Sysdig Monitor.
**Arguments**
- **user_email**: the email address of the user that will be deleted from Sysdig Monitor
**Example**
`examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_... |
379,272 | def get_content_metadata(self, enterprise_customer):
content_metadata = OrderedDict()
if enterprise_customer.catalog:
response = self._load_data(
self.ENTERPRISE_CUSTOMER_ENDPOINT,
detail_resource=,
resource_id=str(enterprise... | Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.
Arguments:
enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.
Returns:
list: List of dicts containing content metadata. |
379,273 | def get_failing_line(xml_string, exc_msg):
max_before = 500
max_after = 500
max_unknown = 1000
assert isinstance(xml_string, six.binary_type)
m = re.search(r, exc_msg)
if not m:
xml_string, _ = truncate_line(xml_string, 1, 0, max_unknown - 1)
return None, None, None, x... | Extract the failing line from the XML string, as indicated by the
line/column information in the exception message.
Returns a tuple (lineno, colno, new_pos, line), where lineno and colno
and marker_pos may be None. |
379,274 | def get_evcodes(self, inc_set=None, exc_set=None):
codes = self.get_evcodes_all(inc_set, exc_set)
codes.discard()
return codes | Get evidence code for all but NOT 'No biological data |
379,275 | def get_unit_property_names(self, unit_id=None):
if unit_id is None:
property_names = []
for unit_id in self.get_unit_ids():
curr_property_names = self.get_unit_property_names(unit_id)
for curr_property_name in curr_property_names:
... | Get a list of property names for a given unit, or for all units if unit_id is None
Parameters
----------
unit_id: int
The unit id for which the property names will be returned
If None (default), will return property names for all units
Returns
----------
... |
379,276 | def _convert_to_bytes(type_name, value):
int_types = {: , : , : , : , : , : }
type_name = type_name.lower()
if type_name not in int_types and type_name not in [, ]:
raise ArgumentError(, known_integers=int_types.keys(), actual_type=type_name)
if type_name == :
bytevalue... | Convert a typed value to a binary array |
379,277 | def grep(expression, file, flags=0, invert=False):
if isinstance(file, str):
file = open(file)
lines = []
for line in file:
if bool(re.search(expression, line, flags=flags)) ^ invert:
lines.append(line)
return lines | Search a file and return a list of all lines that match a regular expression.
:param str expression: The regex to search for.
:param file: The file to search in.
:type file: str, file
:param int flags: The regex flags to use when searching.
:param bool invert: Select non matching lines instead.
:return: All the ... |
379,278 | def _escape_sequence(self, char):
num = ord(char)
if char == "[":
self.state = "escape-lb"
elif char == "(":
self.state = "charset-g0"
elif char == ")":
self.state = "charset-g1"
elif num in self.escape:
self.dispatch(self... | Handle characters seen when in an escape sequence. Most non-vt52
commands start with a left-bracket after the escape and then a
stream of parameters and a command. |
379,279 | def plot_campaign_outline(self, campaign=0, facecolor="
fov = getKeplerFov(campaign)
corners = fov.getCoordsOfChannelCorners()
for rectangle in [[4, 75, 84, 11], [15, 56, 71, 32]]:
ra_outline, dec_outline = [], []
for channel in rectangle:
... | Plot the outline of a campaign as a contiguous gray patch.
Parameters
----------
campaign : int
K2 Campaign number.
facecolor : str
Color of the patch. |
379,280 | def asbaseline(self, pos):
if not is_measure(pos) or pos[] not in [, ]:
raise TypeError()
if pos[] == :
loc = self.measure(pos, )
loc[] =
return self.measure(loc, )
return pos | Convert a position measure into a baseline measure. No actual
baseline is calculated, since operations can be done on positions,
with subtractions to obtain baselines at a later stage.
:param pos: a position measure
:returns: a baseline measure |
379,281 | def get_permissions(self):
path = Client.urls[]
conns = self._call(path, )
return conns | :returns: list of dicts, or an empty list if there are no permissions. |
379,282 | def get_memory_usage(pid=None,timeout=1):
rss = []
vms = []
pid = get_pid(pid)
process = psutil.Process(pid)
print(process.status())
while process.status() == :
mem = process.memory_info()
rss.append(mem.rss)
vms.append(mem.vms)
time.sleep(timeout)
... | get_memory_usage returns a dictionary of resident set size (rss) and virtual
memory size (vms) for a process of interest, for as long as the process is running
:param pid: the pid to use:
:param timeout: the timeout
:: notes
example:
sleep 3 & exec python -m memory "$!" |
379,283 | def _add_entry(self, formdata=None, data=unset_value, index=None):
if formdata:
prefix = .join((self.name, str(index)))
basekey = .join((prefix, ))
idkey = basekey.format()
if prefix in formdata:
formdata[idkey] = formdata.pop(prefix)
... | Fill the form with previous data if necessary to handle partial update |
379,284 | def bunzip2(filename):
log.debug("Uncompressing %s", filename)
tmpfile = "%s.tmp" % filename
os.rename(filename, tmpfile)
b = bz2.BZ2File(tmpfile)
f = open(filename, "wb")
while True:
block = b.read(512 * 1024)
if not block:
break
f.write(block)
f.clo... | Uncompress `filename` in place |
379,285 | def commit(self, **kwargs):
r
if self.model is None or self.model.json is None:
raise MissingModelError()
with db.session.begin_nested():
before_record_update.send(
current_app._get_current_object(),
record=self
)
... | r"""Store changes of the current record instance in the database.
#. Send a signal :data:`invenio_records.signals.before_record_update`
with the current record to be committed as parameter.
#. Validate the current record data.
#. Commit the current record in the database.
... |
379,286 | def open_new_window(self, switch_to=True):
self.driver.execute_script("window.open();")
time.sleep(0.01)
if switch_to:
self.switch_to_window(len(self.driver.window_handles) - 1) | Opens a new browser tab/window and switches to it by default. |
379,287 | def _add_app_menu(self):
mainMenu = AppKit.NSMenu.alloc().init()
self.app.setMainMenu_(mainMenu)
mainAppMenuItem = AppKit.NSMenuItem.alloc().init()
mainMenu.addItem_(mainAppMenuItem)
appMenu = AppKit.NSMenu.alloc().init()
mainAppMenuItem.setSub... | Create a default Cocoa menu that shows 'Services', 'Hide',
'Hide Others', 'Show All', and 'Quit'. Will append the application name
to some menu items if it's available. |
379,288 | def ingest(self):
self.log.debug()
self.primaryIdColumnName = "primaryId"
self.raColName = "raDeg"
self.declColName = "decDeg"
self.dbTableName = "tcs_cat_ifs_stream"
self.databaseInsertbatchSize = 500
dictList = self._create_dictionary_of_IFS()
... | *Import the IFS catalogue into the sherlock-catalogues database*
The method first generates a list of python dictionaries from the IFS datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table.
**Usage:**
See class docstring for usage |
379,289 | def _get_minutes_from_last_update(self, time):
time_from_last_update = time - self.last_update_time
return int(time_from_last_update.total_seconds() / 60) | How much minutes passed from last update to given time |
379,290 | def course_modal(context, course=None):
if course:
context.update({
: course.get(, ),
: course.get(, ),
: course.get(, ),
: course.get(, ),
: course.get(, ),
: course.get(, ),
: course.get(, []),
: course.ge... | Django template tag that returns course information to display in a modal.
You may pass in a particular course if you like. Otherwise, the modal will look for course context
within the parent context.
Usage:
{% course_modal %}
{% course_modal course %} |
379,291 | def display(self, data, x=None, y=None, xlabel=None, ylabel=None,
style=None, nlevels=None, levels=None, contour_labels=None,
store_data=True, col=0, unzoom=True, auto_contrast=False,
contrast_level=0, **kws):
if style is not None:
self.conf.s... | generic display, using imshow (default) or contour |
379,292 | def highlight(self, **kwargs):
self.debug_log("Highlighting element")
style = kwargs.get()
highlight_time = kwargs.get(, .3)
driver = self._element._parent
try:
original_style = self._element.get_attribute()
driver.execute_script(
... | kwargs:
style: css
highlight_time: int; default: .3 |
379,293 | def persist(self, storageLevel=StorageLevel.MEMORY_AND_DISK):
self.is_cached = True
javaStorageLevel = self._sc._getJavaStorageLevel(storageLevel)
self._jdf.persist(javaStorageLevel)
return self | Sets the storage level to persist the contents of the :class:`DataFrame` across
operations after the first time it is computed. This can only be used to assign
a new storage level if the :class:`DataFrame` does not have a storage level set yet.
If no storage level is specified defaults to (C{MEM... |
379,294 | def preview(src_path):
previews = []
for page in list_artboards(src_path):
previews.append(page.export())
for artboard in page.artboards:
previews.append(artboard.export())
return previews | Generates a preview of src_path as PNG.
:returns: A list of preview paths, one for each page. |
379,295 | def barmatch2(data, tups, cutters, longbar, matchdict, fnum):
waitchunk = int(1e6)
epid = os.getpid()
filestat = np.zeros(3, dtype=np.int)
samplehits = {}
dsort1 = {}
dsort2 = {}
dbars = {}
for sname in data.barcodes:
if "-technical-r... | cleaner barmatch func... |
379,296 | def write(self, country_code, frames, scaling_factors=None):
if scaling_factors is None:
scaling_factors = DEFAULT_SCALING_FACTORS
with self.h5_file(mode=) as h5_file:
h5_file.attrs[] = VERSION
country_group = h5_file.create_group(country_code)... | Write the OHLCV data for one country to the HDF5 file.
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row
for each dat... |
379,297 | def create(self, target, configuration_url=values.unset,
configuration_method=values.unset,
configuration_filters=values.unset,
configuration_triggers=values.unset,
configuration_flow_sid=values.unset,
configuration_retry_count=values.unset,
... | Create a new WebhookInstance
:param WebhookInstance.Target target: The target of this webhook.
:param unicode configuration_url: The absolute url the webhook request should be sent to.
:param WebhookInstance.Method configuration_method: The HTTP method to be used when sending a webhook request.... |
379,298 | def process_tick(self, tup):
curtime = int(time.time())
window_info = WindowContext(curtime - self.window_duration, curtime)
tuple_batch = []
for (tup, tm) in self.current_tuples:
tuple_batch.append(tup)
self.processWindow(window_info, tuple_batch)
self._expire(curtime) | Called every slide_interval |
379,299 | def inverse(self):
inv = self.__class__()
inv.add_nodes(self.nodes())
inv.complete()
for each in self.edges():
if (inv.has_edge(each)):
inv.del_edge(each)
return inv | Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.