positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def get_queryset(self, request):
''' Restrict the listed courses for the current user.'''
qs = super(CourseAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(Q(tutors__pk=request.user.pk) | Q(owner=request.user)).dist... | Restrict the listed courses for the current user. |
def get(self, key: str, default: Any = DEFAULT):
"""
Performs the functionality associated with dict.get(key) but also checks for returned
dicts and returns a Params object in their place with an updated history.
"""
if default is self.DEFAULT:
try:
va... | Performs the functionality associated with dict.get(key) but also checks for returned
dicts and returns a Params object in their place with an updated history. |
def run(self, funcs):
"""Run a set of functions in parallel, returning their results.
Make sure any function you pass exits with a reasonable timeout. If it
doesn't return within the timeout or the result is ignored due an exception
in a separate thread it will continue to stick around until it finishe... | Run a set of functions in parallel, returning their results.
Make sure any function you pass exits with a reasonable timeout. If it
doesn't return within the timeout or the result is ignored due an exception
in a separate thread it will continue to stick around until it finishes,
including blocking pro... |
def _credentials_found_in_envars():
"""Check for credentials in envars.
Returns:
bool: ``True`` if at least one is found, otherwise ``False``.
"""
return any([os.getenv('PAN_ACCESS_TOKEN'),
os.getenv('PAN_CLIENT_ID'),
os.getenv('PAN_C... | Check for credentials in envars.
Returns:
bool: ``True`` if at least one is found, otherwise ``False``. |
def check_username_uniqueness(self, username):
"""
Checks if the given username is available for registration.
Results are returned in the on_username_uniqueness_received() callback
:param username: The username to check for its existence
"""
log.info("[+] Checking for U... | Checks if the given username is available for registration.
Results are returned in the on_username_uniqueness_received() callback
:param username: The username to check for its existence |
def get_form_kwargs(self):
""" Returns the keyword arguments to provide tp the associated form. """
kwargs = super(ModelFormMixin, self).get_form_kwargs()
kwargs['poll'] = self.object
return kwargs | Returns the keyword arguments to provide tp the associated form. |
def importobject(module_name, object_name):
"""
Imports the object with the given name from the inputted module.
:param module_name | <str>
object_name | <str>
:usage |>>> import projex
|>>> modname = 'projex.envmanager'
|>>> attr = 'En... | Imports the object with the given name from the inputted module.
:param module_name | <str>
object_name | <str>
:usage |>>> import projex
|>>> modname = 'projex.envmanager'
|>>> attr = 'EnvManager'
|>>> EnvManager = projex.impor... |
def coordinate_system(self, coordsys):
"""Sets instrument coordinate system. Accepts an int or string."""
if coordsys.upper() == "ENU":
ncs = 0
elif coordsys.upper() == "XYZ":
ncs = 1
elif coordsys.upper() == "BEAM":
ncs = 2
elif coordsys in [0... | Sets instrument coordinate system. Accepts an int or string. |
def lpc(blk, order=None):
"""
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation uses the autocorrelation
method, using numpy.linalg.pinv as a linear system solver.
Parameters
----------
blk :
An iterable with well-defined leng... | Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation uses the autocorrelation
method, using numpy.linalg.pinv as a linear system solver.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with S... |
def check_ratelimit_budget(self, seconds_waited):
""" If we have a ratelimit_budget, ensure it is not exceeded. """
if self.ratelimit_budget is not None:
self.ratelimit_budget -= seconds_waited
if self.ratelimit_budget < 1:
raise RatelimitBudgetExceeded("Rate limi... | If we have a ratelimit_budget, ensure it is not exceeded. |
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
key_spec=None, grant_tokens=None, region=None, key=None,
keyid=None, profile=None):
'''
Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias... | Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 |
def verbose(self, msg, *args, **kw):
"""Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`."""
if self.isEnabledFor(VERBOSE):
self._log(VERBOSE, msg, args, **kw) | Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`. |
def respond_via_request(self, task):
"""
Handle response after 55 second.
:param task:
:return:
"""
warn(f"Detected slow response into webhook. "
f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
f"Recommended to use 'async_task' decorator from Dis... | Handle response after 55 second.
:param task:
:return: |
def wait_for(self, predicate, timeout=None):
"""Like :meth:`wait` but additionally for *predicate* to be true.
The *predicate* argument must be a callable that takes no arguments.
Its result is interpreted as a boolean value.
"""
if not is_locked(self._lock):
raise R... | Like :meth:`wait` but additionally for *predicate* to be true.
The *predicate* argument must be a callable that takes no arguments.
Its result is interpreted as a boolean value. |
def authority_issuer_serial(self):
"""
:return:
None or a byte string of the SHA-256 hash of the isser from the
authority key identifier extension concatenated with the ascii
character ":", concatenated with the serial number from the
authority key identif... | :return:
None or a byte string of the SHA-256 hash of the isser from the
authority key identifier extension concatenated with the ascii
character ":", concatenated with the serial number from the
authority key identifier extension as an ascii string |
def ddtodms(self, dd):
"""Take in dd string and convert to dms"""
negative = dd < 0
dd = abs(dd)
minutes,seconds = divmod(dd*3600,60)
degrees,minutes = divmod(minutes,60)
if negative:
if degrees > 0:
degrees = -degrees
elif minutes ... | Take in dd string and convert to dms |
def compare(self, other, base=None):
""" comparison, will return the first difference """
if self.__class__ != other.__class__:
return False, ''
names = self._field_names_
def cmp_func(name, s, o):
# special case for string types
if isinstance(s, six... | comparison, will return the first difference |
def dnld_goa(self, species, ext='gaf', item=None, fileout=None):
"""Download GOA source file name on EMBL-EBI ftp server."""
basename = self.get_basename(species, ext, item)
src = os.path.join(self.ftp_src_goa, species.upper(), "{F}.gz".format(F=basename))
dst = os.path.join(os.getcwd(),... | Download GOA source file name on EMBL-EBI ftp server. |
def get_scenenode(self, nodes):
"""Get the scenenode in the given nodes
There should only be one scenenode in nodes!
:param nodes:
:type nodes:
:returns: None
:rtype: None
:raises: AssertionError
"""
scenenodes = cmds.ls(nodes, type='jb_sceneNode... | Get the scenenode in the given nodes
There should only be one scenenode in nodes!
:param nodes:
:type nodes:
:returns: None
:rtype: None
:raises: AssertionError |
def get_content(self):
"""performs es search and gets content objects
"""
if "query" in self.query:
q = self.query["query"]
else:
q = self.query
search = custom_search_model(Content, q, field_map={
"feature-type": "feature_type.slug",
... | performs es search and gets content objects |
def unpersist(self, blocking=False):
"""Marks the :class:`DataFrame` as non-persistent, and remove all blocks for it from
memory and disk.
.. note:: `blocking` default has changed to False to match Scala in 2.0.
"""
self.is_cached = False
self._jdf.unpersist(blocking)
... | Marks the :class:`DataFrame` as non-persistent, and remove all blocks for it from
memory and disk.
.. note:: `blocking` default has changed to False to match Scala in 2.0. |
def parse_pictures(self, picture_page):
"""Parses the DOM and returns character pictures attributes.
:type picture_page: :class:`bs4.BeautifulSoup`
:param picture_page: MAL character pictures page's DOM
:rtype: dict
:return: character pictures attributes.
"""
character_info = self.parse_s... | Parses the DOM and returns character pictures attributes.
:type picture_page: :class:`bs4.BeautifulSoup`
:param picture_page: MAL character pictures page's DOM
:rtype: dict
:return: character pictures attributes. |
def neighbour_and_arc_simplices(self):
"""
Get indices of neighbour simplices for each simplex and arc indices.
Identical to get_neighbour_simplices() but also returns an array
of indices that reside on boundary hull, -1 denotes no neighbour.
"""
nt, ltri, lct, ierr = _tr... | Get indices of neighbour simplices for each simplex and arc indices.
Identical to get_neighbour_simplices() but also returns an array
of indices that reside on boundary hull, -1 denotes no neighbour. |
def get_msms_annotations(self, outdir, force_rerun=False):
"""Run MSMS on this structure and store the residue depths/ca depths in the corresponding ChainProp SeqRecords
"""
# Now can run on Biopython Model objects exclusively thanks to Biopython updates
# if self.file_type != 'pdb':
... | Run MSMS on this structure and store the residue depths/ca depths in the corresponding ChainProp SeqRecords |
def execute(self, command):
"""
Execute (or simulate) a command. Add to our log.
@param command: Either a C{str} command (which will be passed to the
shell) or a C{list} of command arguments (including the executable
name), in which case the shell is not used.
@r... | Execute (or simulate) a command. Add to our log.
@param command: Either a C{str} command (which will be passed to the
shell) or a C{list} of command arguments (including the executable
name), in which case the shell is not used.
@return: A C{CompletedProcess} instance. This has ... |
def convert_noun_phrases(self, id_run, pos_run):
"""
Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
... | Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
:return: a run of token and phrase ids. |
def your_tips_on_tip_submission_form(context):
"""
A template tag to display the most recent and popular tip
on the tip submission form.
:param context: takes context
"""
context = copy(context)
site_main = context['request'].site.root_page
most_recent_tip = (YourTipsArticlePage.objects... | A template tag to display the most recent and popular tip
on the tip submission form.
:param context: takes context |
def load_truetype_font(
path: str, tile_width: int, tile_height: int
) -> Tileset:
"""Return a new Tileset from a `.ttf` or `.otf` file.
Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead.
You can send this Tileset to :any:`set_default`.
This function is provisional. The API m... | Return a new Tileset from a `.ttf` or `.otf` file.
Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead.
You can send this Tileset to :any:`set_default`.
This function is provisional. The API may change. |
def generate_output_events(self, source, key, val, line='2', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP events results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(req... | The function for generating CLI output RDAP events results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictio... |
def config(self, name, suffix):
"Return config variable value, defaulting to environment"
var = '%s_%s' % (name, suffix)
var = var.upper().replace('-', '_')
if var in self._config:
return self._config[var]
return os.environ[var] | Return config variable value, defaulting to environment |
def _parse_datetime_value(value):
"""Deserialize a DateTime object from its proper ISO-8601 representation."""
if value.endswith('Z'):
# Arrow doesn't support the "Z" literal to denote UTC time.
# Strip the "Z" and add an explicit time zone instead.
value = value[:-1] + '+00:00'
ret... | Deserialize a DateTime object from its proper ISO-8601 representation. |
def plural_verb(self, text, count=None):
"""
Return the plural of text, where text is a verb.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
... | Return the plural of text, where text is a verb.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved. |
def convtable2dict(convtable, locale, update=None):
"""
Convert a list of conversion dict to a dict for a certain locale.
>>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items())
[('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('... | Convert a list of conversion dict to a dict for a certain locale.
>>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items())
[('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('里茲', '利兹')] |
def collectData(reads1, reads2, square, matchAmbiguous):
"""
Get pairwise matching statistics for two sets of reads.
@param reads1: An C{OrderedDict} of C{str} read ids whose values are
C{Read} instances. These will be the rows of the table.
@param reads2: An C{OrderedDict} of C{str} read ids w... | Get pairwise matching statistics for two sets of reads.
@param reads1: An C{OrderedDict} of C{str} read ids whose values are
C{Read} instances. These will be the rows of the table.
@param reads2: An C{OrderedDict} of C{str} read ids whose values are
C{Read} instances. These will be the columns ... |
def set_pointer0d(subseqs):
"""Set_pointer function for 0-dimensional link sequences."""
print(' . set_pointer0d')
lines = Lines()
lines.add(1, 'cpdef inline set_pointer0d'
'(self, str name, pointerutils.PDouble value):')
for seq in subseqs:
... | Set_pointer function for 0-dimensional link sequences. |
def onThemeColor(self, color, item):
"""pass theme colors to bottom panel"""
bconf = self.panel_bot.conf
if item == 'grid':
bconf.set_gridcolor(color)
elif item == 'bg':
bconf.set_bgcolor(color)
elif item == 'frame':
bconf.set_framecolor(color)... | pass theme colors to bottom panel |
def from_file(pkg_file):
"""
Return a |PackageReader| instance loaded with contents of *pkg_file*.
"""
phys_reader = PhysPkgReader(pkg_file)
content_types = _ContentTypeMap.from_xml(phys_reader.content_types_xml)
pkg_srels = PackageReader._srels_for(phys_reader, PACKAGE_U... | Return a |PackageReader| instance loaded with contents of *pkg_file*. |
def slow_highlight(img1, img2, opts):
"""Try to find similar areas between two images.
Produces two masks for img1 and img2.
The algorithm works by comparing every possible alignment of the images,
smoothing it a bit to reduce spurious matches in areas that are
perceptibly different (e.g. text), a... | Try to find similar areas between two images.
Produces two masks for img1 and img2.
The algorithm works by comparing every possible alignment of the images,
smoothing it a bit to reduce spurious matches in areas that are
perceptibly different (e.g. text), and then taking the point-wise minimum
of ... |
def add_parameter(self, parameter, overload=False):
'''
Adds a `Parameter` object to the instance.
If a `Parameter` with the same name or alias has already been added
and `overload` is False (the default), a `ValueError` is thrown.
If a class member or method wi... | Adds a `Parameter` object to the instance.
If a `Parameter` with the same name or alias has already been added
and `overload` is False (the default), a `ValueError` is thrown.
If a class member or method with the same name or alias is already
defined, a `ValueError` is ... |
def ParsePartitionsTable(
self, parser_mediator, database=None, table=None, **unused_kwargs):
"""Parses the Partitions table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.fil... | Parses the Partitions table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.file]): ESE database.
table (Optional[pyesedb.table]): table.
Raises:
ValueError: if the data... |
def require(self, key: str) -> str:
"""
Returns a configuration value by its given key. If it doesn't exist, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
:rtype: str
:raises ConfigMissingError: The configur... | Returns a configuration value by its given key. If it doesn't exist, an error is thrown.
:param str key: The requested configuration key.
:return: The configuration key's value.
:rtype: str
:raises ConfigMissingError: The configuration value did not exist. |
def unload_plug_in(self, name):
"""Unloads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' unloads all plug-ins.
"""
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
s... | Unloads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' unloads all plug-ins. |
def get_last_line_number(node):
"""Estimate last line number of the given AST node.
The estimate is based on the line number of the last descendant of
`node` that has a lineno attribute. Therefore, it underestimates the
size of code ending with, e.g., multiline strings and comments.
When traversin... | Estimate last line number of the given AST node.
The estimate is based on the line number of the last descendant of
`node` that has a lineno attribute. Therefore, it underestimates the
size of code ending with, e.g., multiline strings and comments.
When traversing the tree, we may see a mix of nodes w... |
def clean(self):
"""
Cleans/checks user has entered all required attributes. This might save
some queries from being sent to server if they are totally wrong.
"""
if not all([self._type, self._requested, self._value, self._action]):
raise MalFormattedSource(
... | Cleans/checks user has entered all required attributes. This might save
some queries from being sent to server if they are totally wrong. |
def _generic_search(cls, name, search_string, metadata={}, ignore=''):
""" Searches for a specific string given three types of regex search types. Also auto-checks for camel casing.
:param name: str, name of object in question
:param search_string: str, string to find and insert into the searc... | Searches for a specific string given three types of regex search types. Also auto-checks for camel casing.
:param name: str, name of object in question
:param search_string: str, string to find and insert into the search regexes
:param metadata: dict, metadata to add to the result if we find a... |
def update_device(self, device_id=None, uuid=None, major=None,
minor=None, comment=None):
"""
更新设备信息
详情请参考
http://mp.weixin.qq.com/wiki/15/b9e012f917e3484b7ed02771156411f3.html
:param device_id: 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
:par... | 更新设备信息
详情请参考
http://mp.weixin.qq.com/wiki/15/b9e012f917e3484b7ed02771156411f3.html
:param device_id: 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
:param uuid: UUID
:param major: major
:param minor: minor
:param comment: 设备的备注信息,不超过15个汉字或30个英文字母。
:ret... |
def to_json(value, **kwargs):
"""Convert array to JSON list
nan values are converted to string 'nan', inf values to 'inf'.
"""
def _recurse_list(val):
if val and isinstance(val[0], list):
return [_recurse_list(v) for v in val]
return [str(v) if np... | Convert array to JSON list
nan values are converted to string 'nan', inf values to 'inf'. |
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text... | Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
... |
def set_user_loc(self, master_or_instance, value):
"""Set the user location of a Glyphs master or instance."""
if hasattr(master_or_instance, "instanceInterpolations"):
# The following code is only valid for instances.
# Masters also the keys `weight` and `width` but they should ... | Set the user location of a Glyphs master or instance. |
def get_daemon_stats(self, details=False):
"""Increase the stats provided by the Daemon base class
:return: stats dictionary
:rtype: dict
"""
# Call the base Daemon one
res = super(Receiver, self).get_daemon_stats(details=details)
res.update({'name': self.name, ... | Increase the stats provided by the Daemon base class
:return: stats dictionary
:rtype: dict |
def totals(iter, keyfunc, sumfunc):
"""groups items by field described in keyfunc and counts totals using value
from sumfunc
"""
data = sorted(iter, key=keyfunc)
res = {}
for k, group in groupby(data, keyfunc):
res[k] = sum([sumfunc(entry) for entry in group])
return res | groups items by field described in keyfunc and counts totals using value
from sumfunc |
def _writeString(self, obj, use_reference=True):
"""
Appends a string to the serialization stream
:param obj: String to serialize
:param use_reference: If True, allow writing a reference
"""
# TODO: Convert to "modified UTF-8"
# http://docs.oracle.com/javase/7/do... | Appends a string to the serialization stream
:param obj: String to serialize
:param use_reference: If True, allow writing a reference |
def get_private_file(self):
"""
Return all relevant data in a single object, so this is easy to extend
and server implementations can pick what they need.
"""
return PrivateFile(
request=self.request,
storage=self.get_storage(),
relative_name=s... | Return all relevant data in a single object, so this is easy to extend
and server implementations can pick what they need. |
def setCurrentSchemaColumn(self, column):
"""
Sets the current item based on the inputed column.
:param column | <orb.Column> || None
"""
if column == self._column:
self.treeWidget().setCurrentItem(self)
return True
... | Sets the current item based on the inputed column.
:param column | <orb.Column> || None |
def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
... | Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential dis... |
def add_account_alias(self, account, alias):
"""
:param account: an account object to be used as a selector
:param alias: email alias address
:returns: None (the API itself returns nothing)
"""
self.request('AddAccountAlias', {
'id': self._get_or_... | :param account: an account object to be used as a selector
:param alias: email alias address
:returns: None (the API itself returns nothing) |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(Block, self).Serialize(writer)
writer.WriteSerializableArray(self.Transactions) | Serialize full object.
Args:
writer (neo.IO.BinaryWriter): |
def get_groupname(taskfileinfo):
"""Return a suitable name for a groupname for the given taskfileinfo.
:param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:rai... | Return a suitable name for a groupname for the given taskfileinfo.
:param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:raises: None |
def insertTopLevelItem( self, index, item ):
"""
Inserts the inputed item at the given index in the tree.
:param index | <int>
item | <XGanttWidgetItem>
"""
self.treeWidget().insertTopLevelItem(index, item)
if self.... | Inserts the inputed item at the given index in the tree.
:param index | <int>
item | <XGanttWidgetItem> |
def split(self, text):
"""Split text into a list of cells."""
import re
if re.search('\n\n', text):
return text.split('\n\n')
elif re.search('\r\n\r\n', text):
return text.split('\r\n\r\n')
else:
LOGGER.error("'%s' does not appear to be a 'srt... | Split text into a list of cells. |
def _add_helpingmaterials(config, helping_file, helping_type):
"""Add helping materials to a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
... | Add helping materials to a project. |
def categorization(self, domains, labels=False):
'''Get the domain status and categorization of a domain or list of domains.
'domains' can be either a single domain, or a list of domains.
Setting 'labels' to True will give back categorizations in human-readable
form.
For more de... | Get the domain status and categorization of a domain or list of domains.
'domains' can be either a single domain, or a list of domains.
Setting 'labels' to True will give back categorizations in human-readable
form.
For more detail, see https://investigate.umbrella.com/docs/api#categori... |
def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0]... | Translate a type comment into a list of tokens. |
def _scheme_propagation(self, scheme, definitions):
""" Will updated a scheme based on inheritance. This is defined in a scheme objects with ``'inherit': '$definition'``.
Will also updated parent objects for nested inheritance.
Usage::
>>> SCHEME = {
>>> 'thing1': {... | Will updated a scheme based on inheritance. This is defined in a scheme objects with ``'inherit': '$definition'``.
Will also updated parent objects for nested inheritance.
Usage::
>>> SCHEME = {
>>> 'thing1': {
>>> 'inherit': '$thing2'
>>> ... |
def prefetchDeclarativeIds(self, Declarative, count) -> DelcarativeIdGen:
""" Prefetch Declarative IDs
This function prefetches a chunk of IDs from a database sequence.
Doing this allows us to preallocate the IDs before an insert, which significantly
speeds up :
* Orm inserts, ... | Prefetch Declarative IDs
This function prefetches a chunk of IDs from a database sequence.
Doing this allows us to preallocate the IDs before an insert, which significantly
speeds up :
* Orm inserts, especially those using inheritance
* When we need the ID to assign it to a rel... |
def getblockhash(self, index: int) -> str:
'''Returns the hash of the block at ; index 0 is the genesis block.'''
return cast(str, self.api_fetch('getblockhash?index=' + str(index))) | Returns the hash of the block at ; index 0 is the genesis block. |
def _canonicalize_name(prefix, qvm_type, noisy):
"""Take the output of _parse_name to create a canonical name.
"""
if noisy:
noise_suffix = '-noisy'
else:
noise_suffix = ''
if qvm_type is None:
qvm_suffix = ''
elif qvm_type == 'qvm':
qvm_suffix = '-qvm'
elif ... | Take the output of _parse_name to create a canonical name. |
def course_unregister_user(self, course, username=None):
"""
Unregister a user to the course
:param course: a Course object
:param username: The username of the user that we want to unregister. If None, uses self.session_username()
"""
if username is None:
use... | Unregister a user to the course
:param course: a Course object
:param username: The username of the user that we want to unregister. If None, uses self.session_username() |
def refund_reward(self, agreement_id, amount, account):
"""
Refund reaward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return:
"""
return self.release_reward(agreement_id, amou... | Refund reaward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return: |
def DeleteGRRUser(self, username, cursor=None):
"""Deletes the user and all related metadata with the given username."""
cursor.execute("DELETE FROM grr_users WHERE username_hash = %s",
(mysql_utils.Hash(username),))
if cursor.rowcount == 0:
raise db.UnknownGRRUserError(username) | Deletes the user and all related metadata with the given username. |
def get_vert_connectivity(mesh_v, mesh_f):
"""Returns a sparse matrix (of size #verts x #verts) where each nonzero
element indicates a neighborhood relation. For example, if there is a
nonzero element in position (15,12), that means vertex 15 is connected
by an edge to vertex 12."""
vpv = sp.csc_ma... | Returns a sparse matrix (of size #verts x #verts) where each nonzero
element indicates a neighborhood relation. For example, if there is a
nonzero element in position (15,12), that means vertex 15 is connected
by an edge to vertex 12. |
def get_new_profile_template(self):
"""
Retrieves the profile template for a given server profile.
Returns:
dict: Server profile template.
"""
uri = '{}/new-profile-template'.format(self.data["uri"])
return self._helper.do_get(uri) | Retrieves the profile template for a given server profile.
Returns:
dict: Server profile template. |
def _parse_reports_by_type(self):
""" Returns a data dictionary
Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type.
"""
data = dict()
for file_meta in self.find_log_files('picard/sam_file_validation', filehandles=True):
sample = file_meta['s_name']
... | Returns a data dictionary
Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type. |
def read_phase(ph_file):
"""
Read hypoDD phase files into Obspy catalog class.
:type ph_file: str
:param ph_file: Phase file to read event info from.
:returns: Catalog of events from file.
:rtype: :class:`obspy.core.event.Catalog`
>>> from obspy.core.event.catalog import Catalog
>>> #... | Read hypoDD phase files into Obspy catalog class.
:type ph_file: str
:param ph_file: Phase file to read event info from.
:returns: Catalog of events from file.
:rtype: :class:`obspy.core.event.Catalog`
>>> from obspy.core.event.catalog import Catalog
>>> # Get the path to the test data
>>... |
def delete_alarm(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a cloudwatch alarm
CLI example to delete a queue::
salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.de... | Delete a cloudwatch alarm
CLI example to delete a queue::
salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1 |
def _subtask_error(self, idx, error):
"""Receive an error from a single subtask."""
self.set_exception(error)
self.errbacks.clear() | Receive an error from a single subtask. |
def add_user(uid, password, desc=None):
""" Adds user to the DCOS Enterprise. If not description
is provided the uid will be used for the description.
:param uid: user id
:type uid: str
:param password: password
:type password: str
:param desc: description of user
... | Adds user to the DCOS Enterprise. If not description
is provided the uid will be used for the description.
:param uid: user id
:type uid: str
:param password: password
:type password: str
:param desc: description of user
:type desc: str |
def _build_session(self, name, start_info, end_info):
"""Builds a session object."""
assert start_info is not None
result = api_pb2.Session(
name=name,
start_time_secs=start_info.start_time_secs,
model_uri=start_info.model_uri,
metric_values=self._build_session_metric_values... | Builds a session object. |
def Update(self,name,description=None,location=None):
"""Updates the attributes of a given Network via PUT.
https://www.ctl.io/api-docs/v2/#networks-update-network
{
"name": "VLAN for Development Servers",
"description": "Development Servers on 11.22.33.0/24"
}
Returns a 204 and no content
""... | Updates the attributes of a given Network via PUT.
https://www.ctl.io/api-docs/v2/#networks-update-network
{
"name": "VLAN for Development Servers",
"description": "Development Servers on 11.22.33.0/24"
}
Returns a 204 and no content |
def _listen(sockets):
"""Main server loop. Listens for incoming events and dispatches them to appropriate chatroom"""
while True:
(i , o, e) = select.select(sockets.keys(),[],[],1)
for socket in i:
if isinstance(sockets[socket], Chatroom):
data_len = sockets[socket].c... | Main server loop. Listens for incoming events and dispatches them to appropriate chatroom |
def report(self, simulation, state):
"""Generate a report.
Parameters
----------
simulation : Simulation
The Simulation to generate a report for
state : State
The current state of the simulation
"""
if not self._initialized:
se... | Generate a report.
Parameters
----------
simulation : Simulation
The Simulation to generate a report for
state : State
The current state of the simulation |
def remove_system(self, system):
'''
Removes system from world and kills system
'''
if system in self._systems:
self._systems.remove(system)
else:
raise UnmanagedSystemError(system) | Removes system from world and kills system |
def doeigs_s(tau, Vdirs):
"""
get elements of s from eigenvaulues - note that this is very unstable
Input:
tau,V:
tau is an list of eigenvalues in decreasing order:
[t1,t2,t3]
V is an list of the eigenvector directions
[[V1_dec,V1_inc],[V2_dec,V2_... | get elements of s from eigenvaulues - note that this is very unstable
Input:
tau,V:
tau is an list of eigenvalues in decreasing order:
[t1,t2,t3]
V is an list of the eigenvector directions
[[V1_dec,V1_inc],[V2_dec,V2_inc],[V3_dec,V3_inc]]
Output:
... |
def set_day_time(self, hour):
"""Queue up a change day time command. It will be applied when `tick` or `step` is called next.
By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere
or directional light in the world, the command will not funct... | Queue up a change day time command. It will be applied when `tick` or `step` is called next.
By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere
or directional light in the world, the command will not function properly but will not cause a crash.
... |
def buildMask(dqarr, bitvalue):
""" Builds a bit-mask from an input DQ array and a bitvalue flag """
return bitfield_to_boolean_mask(dqarr, bitvalue, good_mask_value=1,
dtype=np.uint8) | Builds a bit-mask from an input DQ array and a bitvalue flag |
def _load_version(cls, state, version):
"""
A function to load a previously saved NearestNeighborClassifier model.
Parameters
----------
unpickler : GLUnpickler
A GLUnpickler file handler.
version : int
Version number maintained by the class writ... | A function to load a previously saved NearestNeighborClassifier model.
Parameters
----------
unpickler : GLUnpickler
A GLUnpickler file handler.
version : int
Version number maintained by the class writer. |
def age(self, as_at_date=None):
"""
Compute the person's age
"""
if self.date_of_death != None or self.is_deceased == True:
return None
as_at_date = date.today() if as_at_date == None else as_at_date
if self.date_of_birth != None:
if (as_... | Compute the person's age |
def write_hier_all(self, out=sys.stdout,
len_dash=1, max_depth=None, num_child=None, short_prt=False):
"""Write hierarchy for all GO Terms in obo file."""
# Print: [biological_process, molecular_function, and cellular_component]
for go_id in ['GO:0008150', 'GO:0003674', 'GO... | Write hierarchy for all GO Terms in obo file. |
def joined(self, a, b):
"""
Returns True if a and b are members of the same set.
"""
mapping = self._mapping
try:
return mapping[a] is mapping[b]
except KeyError:
return False | Returns True if a and b are members of the same set. |
def modify(self, monitor_id, options):
"""Create a monitor using passed configuration."""
if not self._state:
raise InvalidState("State was not properly obtained from the app")
monitors = self.list() # Get the latest set of monitors
obj = None
for monitor in monitors... | Create a monitor using passed configuration. |
def find_matching_symlink(path, source):
"""Find a symlink under `path` that points at `source`.
If source is relative, it is considered relative to `path`.
Returns:
str: Name of symlink found, or None.
"""
def to_abs(target):
if os.path.isabs(target):
return target
... | Find a symlink under `path` that points at `source`.
If source is relative, it is considered relative to `path`.
Returns:
str: Name of symlink found, or None. |
def get_model(self):
"""
Get a model if the formula was previously satisfied.
"""
if self.minisat and self.status == True:
model = pysolvers.minisat22_model(self.minisat)
return model if model != None else [] | Get a model if the formula was previously satisfied. |
def parse_selinux(parts):
"""
Parse part of an ls output line that is selinux.
Args:
parts (list): A four element list of strings representing the initial
parts of an ls line after the permission bits. The parts are owner
group, selinux info, and the path.
Returns:
... | Parse part of an ls output line that is selinux.
Args:
parts (list): A four element list of strings representing the initial
parts of an ls line after the permission bits. The parts are owner
group, selinux info, and the path.
Returns:
A dict containing owner, group, se... |
def collect(self):
"""
Collect and publish S.M.A.R.T. attributes
"""
devices = re.compile(self.config['devices'])
for device in os.listdir('/dev'):
if devices.match(device):
command = [self.config['bin'], "-A", os.path.join('/dev',
... | Collect and publish S.M.A.R.T. attributes |
def convert_coord(coord_from,matrix_file,base_to_aligned=True):
'''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False... | Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False`` |
def read(self, filename):
"""Reads the file specified by filename
This method will load the eapi.conf file specified by filename into
the instance object. It will also add the default connection localhost
if it was not defined in the eapi.conf file
Args:
filename (... | Reads the file specified by filename
This method will load the eapi.conf file specified by filename into
the instance object. It will also add the default connection localhost
if it was not defined in the eapi.conf file
Args:
filename (str): The full path to the file to lo... |
def make_image_cache(img_cache):
"""
Initiates the image cache if it does not exist
"""
log.info('Initiating the image cache at {0}'.format(img_cache))
if not os.path.isdir(img_cache):
utils.mkdir_p(img_cache)
utils.mkdir_p(os.path.join(img_cache, '10.1371'))
utils.mkdir_p(os... | Initiates the image cache if it does not exist |
def wrap_method(
func,
default_retry=None,
default_timeout=None,
client_info=client_info.DEFAULT_CLIENT_INFO,
):
"""Wrap an RPC method with common behavior.
This applies common error wrapping, retry, and timeout behavior a function.
The wrapped function will take optional ``retry`` and ``ti... | Wrap an RPC method with common behavior.
This applies common error wrapping, retry, and timeout behavior a function.
The wrapped function will take optional ``retry`` and ``timeout``
arguments.
For example::
import google.api_core.gapic_v1.method
from google.api_core import retry
... |
def clone(self):
"""Return a new Scope object that has the curr_scope
pinned at the current one
:returns: A new scope object
"""
self._dlog("cloning the stack")
# TODO is this really necessary to create a brand new one?
# I think it is... need to think about it mo... | Return a new Scope object that has the curr_scope
pinned at the current one
:returns: A new scope object |
def visit_and_update(self, visitor_fn):
"""Create an updated version (if needed) of BinaryComposition via the visitor pattern."""
new_left = self.left.visit_and_update(visitor_fn)
new_right = self.right.visit_and_update(visitor_fn)
if new_left is not self.left or new_right is not self.r... | Create an updated version (if needed) of BinaryComposition via the visitor pattern. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.