text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def dataset_resource(self, ref_id, friendly_name=None, description=None,
access=None, location=None, project_id=None):
"""See
https://developers.google.com/bigquery/docs/reference/v2/datasets#resource
Parameters
----------
ref_id : str
Datase... | 0.004118 |
def prefixsearch(self, prefix, results=10):
""" Perform a prefix search using the provided prefix string
Args:
prefix (str): Prefix string to use for search
results (int): Number of pages with the prefix to return
Returns:
list: List of pa... | 0.001633 |
def node_branch(self, astr_node, abranch):
"""
Adds a branch to a node, i.e. depth addition. The given
node's md_nodes is set to the abranch's mdict_branch.
"""
self.dict_branch[astr_node].node_dictBranch(abranch.dict_branch) | 0.007018 |
def contains(self, name):
"""Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket.
"""
try:
self._api.buck... | 0.009881 |
def time_calls_with_dims(**dims):
"""Decorator to time the execution of the function with dimensions."""
def time_wrapper(fn):
@functools.wraps(fn)
def fn_wrapper(*args, **kwargs):
_timer = timer("%s_calls" %
pyformance.registry.get_qualname(fn), **dims)
... | 0.002079 |
def save(self, to_save, **kwargs):
"""save method
"""
check = kwargs.pop('check', True)
if check:
self._valid_record(to_save)
if '_id' in to_save:
self.__collect.replace_one(
{'_id': to_save['_id']}, to_save, **kwargs)
return to... | 0.004444 |
def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the given element."""
xml_value = self._processor.parse_at_element(element, state)
return _hooks_apply_after_parse(self._hooks,... | 0.011834 |
def get_referenced_object(self):
"""
:rtype: core.BunqModel
:raise: BunqException
"""
if self._TabUsageSingle is not None:
return self._TabUsageSingle
if self._TabUsageMultiple is not None:
return self._TabUsageMultiple
raise exception.B... | 0.005602 |
def resize_pty(self, width=80, height=24):
"""
Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous L{get_pty} call.
@param width: new width (in characters) of the terminal screen
@type width: int
@p... | 0.002967 |
def _get_plugin_map(self, compiler, options_src, target):
"""Returns a map of plugin to args, for the given compiler.
Only plugins that must actually be activated will be present as keys in the map.
Plugins with no arguments will have an empty list as a value.
Active plugins and their args will be gat... | 0.005173 |
def dict_find_key(dd, value):
""" Find first suitable key in dict.
:param dd:
:param value:
:return:
"""
key = next(key for key, val in dd.items() if val == value)
return key | 0.004926 |
def log_every_n(n, level, message, *args): # pylint: disable=invalid-name
"""Logs a message every n calls. See _log_every_n_to_logger."""
return _log_every_n_to_logger(n, None, level, message, *args) | 0.014706 |
def saveConfig(self, request):
"""I save the config, and run check_config, potencially returning errors"""
res = yield self.assertAllowed(request)
if res:
defer.returnValue(res)
request.setHeader('Content-Type', 'application/json')
if self._in_progress:
de... | 0.005214 |
def image_groups_list(self, limit=-1, offset=-1):
"""Retrieve list of all image groups in the data store.
Parameters
----------
limit : int
Limit number of results in returned object listing
offset : int
Set offset in list (order as defined by object stor... | 0.003953 |
def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
vals = re.split(r'[,\s]+', query.strip())
coords = [float(v) for v in vals]
return tuple(coords[:2]) | 0.00346 |
def start_distribution(project_name, template_dir, dist, noadmin):
"""
Custom startproject command to override django default
"""
directory = os.getcwd()
# Check that the project_name cannot be imported.
try:
import_module(project_name)
except ImportError:
pass
else:
... | 0.008399 |
def install_rpm_py():
"""Install RPM Python binding."""
python_path = sys.executable
cmd = '{0} install.py'.format(python_path)
exit_status = os.system(cmd)
if exit_status != 0:
raise Exception('Command failed: {0}'.format(cmd)) | 0.003906 |
def get_bit_values(number, size=32):
"""
Get bit values as a list for a given number
>>> get_bit_values(1) == [0]*31 + [1]
True
>>> get_bit_values(0xDEADBEEF)
[1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, \
1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1]
You may override the default word size of... | 0.03263 |
def get_comments(self):
"""Gets all comments.
return: (osid.commenting.CommentList) - a list of comments
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""... | 0.003606 |
def define_function(self, function, name=None):
"""Define the Python function within the CLIPS environment.
If a name is given, it will be the function name within CLIPS.
Otherwise, the name of the Python function will be used.
The Python function will be accessible within CLIPS via it... | 0.003454 |
def check_user(user):
'''
Check user and assign process uid/gid.
'''
if salt.utils.platform.is_windows():
return True
if user == salt.utils.user.get_user():
return True
import pwd # after confirming not running Windows
try:
pwuser = pwd.getpwnam(user)
try:
... | 0.001808 |
def websettings():
'''Generate websettings'''
web = makeelement('webSettings')
web.append(makeelement('allowPNG'))
web.append(makeelement('doNotSaveAsSingleFile'))
return web | 0.005155 |
def retrieve_agent_profile(self, agent, profile_id):
"""Retrieve agent profile with the specified parameters
:param agent: Agent object of the desired agent profile
:type agent: :class:`tincan.agent.Agent`
:param profile_id: UUID of the desired agent profile
:type profile_id: st... | 0.001918 |
def add_default_module_dir(self):
"""
Add directory to store built-in plugins to `module_dir` parameter.
Default directory to store plugins is `BLACKBIRD_INSTALL_DIR/plugins`.
:rtype: None
:return: None
"""
default_module_dir = os.path.join(
os.path.ab... | 0.002825 |
def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._em... | 0.006042 |
def parse(self, text):
'''Parses input string and returns list of DDLObjects'''
in_comment = False
result = []
for s in iter(text.splitlines()):
self.log.debug('Parsing string: {}'.format(s))
rsc = self.RE_START_COMMENT.match(s)
if rsc:
... | 0.001295 |
def sync(self):
"""
Goes through the directory and builds a local cache based on
the content of the directory.
"""
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir)
for f in os.listdir(self.fdir):
fname = os.path.join(self.fdir, f)
... | 0.00303 |
def real_time_sequencing(self, availability, oauth, event, target_calendars=()):
"""Generates an real time sequencing link to start the OAuth process with
an event to be automatically upserted
:param dict availability: - A dict describing the availability details for the event:
:s... | 0.00626 |
def get_collections(db, collection=None, prefix=None, suffix=None):
'''
Returns a sorted list of collection names found in ``db``.
Arguments:
db (Database): A pymongo Database object. Can be obtained
with ``get_db``.
collection (str): Name of a collection. If the collection is... | 0.000754 |
def _grow(list_of_lists, num_new):
""" Given a list of lists, and a number of new lists to add, copy the
content of the first list into the new ones, and add them to the list
of lists.
"""
first = list_of_lists[0]
for i in range(num_new):
list_of_lists.append(copy.deepcopy(first))
re... | 0.002959 |
def aap_to_bp (ant1, ant2, pol):
"""Create a basepol from antenna numbers and a CASA polarization code."""
if ant1 < 0:
raise ValueError ('first antenna is below 0: %s' % ant1)
if ant2 < ant1:
raise ValueError ('second antenna is below first: %s' % ant2)
if pol < 1 or pol > 12:
... | 0.009901 |
def commit_log(self, log_json):
""" Commits a run log to the Mongo backend.
Due to limitations of maximum document size in Mongo,
stdout and stderr logs are truncated to a maximum size for
each task.
"""
log_json['_id'] = log_json['log_id']
append = {'save_date'... | 0.002291 |
def allclose_variable(a, b, limits, rtols=None, atols=None):
'''Returns True if two arrays are element-wise equal within several
different tolerances. Tolerance values are always positive, usually
very small. Based on numpy's allclose function.
Only atols or rtols needs to be specified; both are u... | 0.005935 |
def collect(tp, *args):
"""
Decorator to attach a collector function to a triple pattern
:param tp:
:param args:
:return:
"""
def decorator(f):
add_triple_pattern(tp, f, args)
return decorator | 0.004274 |
def long_description(*filenames):
"""Provide a long description."""
res = ['']
for filename in filenames:
with open(filename) as fp:
for line in fp:
res.append(' ' + line)
res.append('')
res.append('\n')
return EMPTYSTRING.join(res) | 0.003268 |
def logout(self):
"""Logout of a vSphere server."""
if self._logged_in is True:
self.si.flush_cache()
self.sc.sessionManager.Logout()
self._logged_in = False | 0.009569 |
def contains_value(self, value):
"""
Determines whether this map contains one or more keys for the specified value.
:param value: (object), the specified value.
:return: (bool), ``true`` if this map contains an entry for the specified value.
"""
check_not_none(value, "va... | 0.008696 |
def close_all_but_this(self):
"""Close all files but the current one"""
self.close_all_right()
for i in range(0, self.get_stack_count()-1 ):
self.close_file(0) | 0.015 |
def social_widget_render(parser, token):
""" Renders the selected social widget. You can specify optional settings
that will be passed to widget template.
Sample usage:
{% social_widget_render widget_template ke1=val1 key2=val2 %}
For example to render Twitter follow button you can use code like ... | 0.000771 |
def infix(self, node, children):
'infix = "(" expr operator expr ")"'
_, expr1, operator, expr2, _ = children
return operator(expr1, expr2) | 0.01227 |
def bisect(args):
"""
%prog bisect acc accession.fasta
determine the version of the accession by querying entrez, based on a fasta file.
This proceeds by a sequential search from xxxx.1 to the latest record.
"""
p = OptionParser(bisect.__doc__)
p.set_email()
opts, args = p.parse_args(a... | 0.001779 |
def attention_lm_moe_small():
"""Cheap model for single-gpu training.
on lm1b_32k:
~312M params
1.6 steps/sec on [GeForce GTX TITAN X]
After 50K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.31
Returns:
an hparams object.
"""
hparams = attention_lm_moe_base()
hparam... | 0.018908 |
def nasm_mutable_data_finalizer(env, code, data):
"""
Simple data allocation strategy that expects the code to be in a writable
segment. We just append the data to the end of the code.
"""
if env.target.bits == 32:
get_pc = [
'\tcall __getpc0',
'__getpc0:',
... | 0.001595 |
def request(self, send_terminator = False):
"""Required request() override for v3 and standard method to read meter.
Args:
send_terminator (bool): Send termination string at end of read.
Returns:
bool: CRC request flag result from most recent read
"""
se... | 0.006667 |
def factory(cls, target_type, alias=None):
"""Creates an addressable factory for the given target type and alias.
:returns: A factory that can capture :class:`TargetAddressable` instances.
:rtype: :class:`Addressable.Factory`
"""
class Factory(Addressable.Factory):
@property
def target_... | 0.008065 |
def handle_send(
entity: BaseEntity,
author_user: UserType,
recipients: List[Dict],
parent_user: UserType = None,
) -> None:
"""Send an entity to remote servers.
Using this we will build a list of payloads per protocol. After that, each recipient will get the generated
proto... | 0.004311 |
def obspy_3d_plot(inventory, catalog, size=(10.5, 7.5), **kwargs):
"""
Plot obspy Inventory and obspy Catalog classes in three dimensions.
:type inventory: obspy.core.inventory.inventory.Inventory
:param inventory: Obspy inventory class containing station metadata
:type catalog: obspy.core.event.ca... | 0.000345 |
def get_last_id(self, cur, table='reaction'):
"""
Get the id of the last written row in table
Parameters
----------
cur: database connection().cursor() object
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
Returns: id
... | 0.00346 |
def cp_string(self, source, dest, **kwargs):
"""
Copies source string into the destination location.
Parameters
----------
source: string
the string with the content to copy
dest: string
the s3 location
"""
assert isinstance(sourc... | 0.004065 |
def from_records(cls, data, index=None, exclude=None, columns=None,
coerce_float=False, nrows=None):
"""
Convert structured or record ndarray to DataFrame.
Parameters
----------
data : ndarray (structured dtype), list of tuples, dict, or DataFrame
in... | 0.000649 |
async def fire(self, name, payload=None, *,
dc=None, node=None, service=None, tag=None):
"""Fires a new event
Parameters:
name (str): Event name
payload (Payload): Opaque data
node (Filter): Regular expression to filter by node name
ser... | 0.002514 |
def fix_objective_as_constraint(model, fraction=1, bound=None,
name='fixed_objective_{}'):
"""Fix current objective as an additional constraint.
When adding constraints to a model, such as done in pFBA which
minimizes total flux, these constraints can become too powerful,
... | 0.000534 |
def poa_components(aoi, dni, poa_sky_diffuse, poa_ground_diffuse):
r'''
Determine in-plane irradiance components.
Combines DNI with sky diffuse and ground-reflected irradiance to calculate
total, direct and diffuse irradiance components in the plane of array.
Parameters
----------
aoi : nu... | 0.000497 |
def clear_modules(self):
"""Clears all modules from the list"""
for child in self.module_selection.winfo_children():
child.destroy()
self.clear_ui()
tk.Label(self.module_ui, text="Start Modis and select a module").grid(
column=0, row=0, padx=0, pady=0, sticky="W... | 0.004057 |
def invalidate_api_key(self, body, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-api-key.html>`_
:arg body: The api key request to invalidate API key(s)
"""
if body in SKIP_IN_PATH:
raise ValueError("Empty... | 0.006085 |
def _season_overflow(season, moved_year, now):
"""Pushes illegal seasons ints into the next/previous year."""
if season > 4:
while season > 4:
if moved_year is None:
moved_year = now.year + 1
else:
moved_year += 1
season -= 5
elif ... | 0.001859 |
def ParseRow(header,
row):
"""Parses a single row of osquery output.
Args:
header: A parsed header describing the row format.
row: A row in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryRow` instance.
"""
precondition.AssertDictType(row, Text, Text)
result... | 0.013699 |
def _unpack(formatstring, packed):
"""Unpack a bytestring into a value.
Uses the built-in :mod:`struct` Python module.
Args:
* formatstring (str): String for the packing. See the :mod:`struct` module for details.
* packed (str): The bytestring to be unpacked.
Returns:
A value.... | 0.004348 |
def router_del(self, cluster_id, router_id):
"""remove router from the ShardedCluster"""
cluster = self._storage[cluster_id]
result = cluster.router_remove(router_id)
self._storage[cluster_id] = cluster
return result | 0.007813 |
async def rename(self, name):
"""Change name of node."""
set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name)
await set_node_name.do_api_call()
if not set_node_name.success:
raise PyVLXException("Unable to rename node")
self.name = name | 0.009554 |
def filterAcceptsRow(self, sourceRow, sourceParent):
""" If onlyShowImported is True, regItems that were not (successfully) imported are
filtered out.
"""
if not self.onlyShowImported:
return True
item = self.sourceModel().registry.items[sourceRow]
return... | 0.008523 |
def updateResultsForJob(self, forceUpdate=True):
""" Chooses the best model for a given job.
Parameters
-----------------------------------------------------------------------
forceUpdate: (True/False). If True, the update will ignore all the
restrictions on the minimum time to updat... | 0.009054 |
def comment_form(context, object):
"""
Usage:
{% comment_form obj as comment_form %}
Will read the `user` var out of the contex to know if the form should be
form an auth'd user or not.
"""
user = context.get("user")
form_class = context.get("form", CommentForm)
form = form_class... | 0.002786 |
def user_delete(self, uid, channel=None):
"""Delete user (helper)
Note that in IPMI, user 'deletion' isn't a concept. This function
will make a best effort to provide the expected result (e.g.
web interfaces skipping names and ipmitool skipping as well.
:param uid: user number... | 0.001373 |
def _make_pretty_note(note):
"""
Makes the note description pretty and returns a formatted string if `note` is not
an empty string. Otherwise, returns None.
Expected input:
...
Expected output:
**Note:**
...
"""
if note != "":
note = "\n".join(map(lambda n: n[4:... | 0.005249 |
def get_per_pixel_mean(self, names=('train', 'test')):
"""
Args:
names (tuple[str]): the names ('train' or 'test') of the datasets
Returns:
a mean image of all images in the given datasets, with size 32x32x3
"""
for name in names:
assert name ... | 0.003871 |
def canonic_signame(name_num):
"""Return a signal name for a signal name or signal
number. Return None is name_num is an int but not a valid signal
number and False if name_num is a not number. If name_num is a
signal name or signal number, the canonic if name is returned."""
signum = lookup_signum... | 0.004219 |
def init_jvm(java_home=None,
jvm_dll=None,
jvm_maxmem=None,
jvm_classpath=None,
jvm_properties=None,
jvm_options=None,
config_file=None,
config=None):
"""
Creates a configured Java virtual machine which will be used by jp... | 0.004122 |
def __process(self, event):
"""处理事件"""
# 检查是否存在对该事件进行监听的处理函数
if event.type_ in self.__handlers:
# 若存在,则按顺序将事件传递给处理函数执行
[handler(event) for handler in self.__handlers[event.type_]]
# 以上语句为Python列表解析方式的写法,对应的常规循环写法为:
#for handler in self... | 0.015625 |
def extract_filestem(data):
"""Extract filestem from Entrez eSummary data.
Function expects esummary['DocumentSummarySet']['DocumentSummary'][0]
Some illegal characters may occur in AssemblyName - for these, a more
robust regex replace/escape may be required. Sadly, NCBI don't just
use standard pe... | 0.001661 |
def get_time_interval(time1, time2):
'''get the interval of two times'''
try:
#convert time to timestamp
time1 = time.mktime(time.strptime(time1, '%Y/%m/%d %H:%M:%S'))
time2 = time.mktime(time.strptime(time2, '%Y/%m/%d %H:%M:%S'))
seconds = (datetime.datetime.fromtimestamp(time2)... | 0.007299 |
def close_log(log_file):
""" Closes the open file and returns :py:class:`sys.stdout` to the default (i.e., console output).
Args:
log_file (file): The file object to close.
"""
sys.stdout = sys.__stdout__
if log_file is not None:
log_file.close()
del log_file | 0.006557 |
def get_from_string(cls, string_condition):
"""
Convert string value obtained from k8s API to PodCondition enum value
:param string_condition: str, condition value from Kubernetes API
:return: PodCondition
"""
if string_condition == 'PodScheduled':
return cls... | 0.002894 |
def financials(symbol, token='', version=''):
'''Pulls income statement, balance sheet, and cash flow data from the four most recent reported quarters.
https://iexcloud.io/docs/api/#financials
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access... | 0.00396 |
def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum... | 0.000733 |
def visit_functiondef(self, node):
'''
Verifies no logger statements inside __virtual__
'''
if (not isinstance(node, astroid.FunctionDef) or
node.is_method()
or node.type != 'function'
or not node.body
):
# only process functions... | 0.00354 |
def write_roi(self, outfile=None,
save_model_map=False, **kwargs):
"""Write current state of the analysis to a file. This method
writes an XML model definition, a ROI dictionary, and a FITS
source catalog file. A previously saved analysis state can be
reloaded from th... | 0.0011 |
def _get_source(link):
"""
Return source of the `link` whether it is filename or url.
Args:
link (str): Filename or URL.
Returns:
str: Content.
Raises:
UserWarning: When the `link` couldn't be resolved.
"""
if link.startswith("http://") or link.startswith("https://... | 0.001818 |
def postage_update(self, tid, post_fee, session):
'''taobao.trade.postage.update 修改订单邮费价格
修改订单邮费接口,通过传入订单编号和邮费价格,修改订单的邮费,返回修改时间modified,邮费post_fee,总费用total_fee。'''
request = TOPRequest('taobao.trade.postage.update')
request['tid'] = tid
request['post_fee'] = post_fee
... | 0.010076 |
def visit_any_conditionnal(self, node1, node2):
"""
Set and restore the in_cond variable before visiting subnode.
Compute correct dependencies on a value as both branch are possible
path.
"""
true_naming = false_naming = None
try:
tmp = self.naming.... | 0.001575 |
def getEventType(self, eventTypeId, draft=False):
"""
Gets an event type. Parameters: eventTypeId (string), draft (boolean). Throws APIException on failure.
"""
if draft:
req = ApiClient.oneEventTypeUrl % (self.host, "/draft", eventTypeId)
else:
req = Ap... | 0.007353 |
def _rebuild_all_command_chains(self):
"""
Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (typically it will be done in ... | 0.00722 |
def __purge():
"""Remove all dead signal receivers from the global receivers collection.
Note:
It is assumed that the caller holds the __lock.
"""
global __receivers
newreceivers = collections.defaultdict(list)
for signal, receivers in six.iteritems(__receivers):
alive = [x for... | 0.002353 |
def _view_deps(self, path, package):
"""View dependencies before remove
"""
self.size = 0
packages = []
dependencies = (Utils().read_file(path + package)).splitlines()
for dep in dependencies:
if GetFromInstalled(dep).name():
ver = GetFromInsta... | 0.001019 |
def __read_source_file(self):
"""
Reads the file with the source of the stored routine.
"""
with open(self._source_filename, 'r', encoding=self._routine_file_encoding) as file:
self._routine_source_code = file.read()
self._routine_source_code_lines = self._routine_so... | 0.008798 |
def send_message(self, text: str, reply: int=None, link_preview: bool=None,
on_success: callable=None, reply_markup: botapi.ReplyMarkup=None):
"""
Send message to this peer.
:param text: Text to send.
:param reply: Message object or message_id to reply to.
:p... | 0.020649 |
def random_sample(list_, nSample, strict=False, rng=None, seed=None):
"""
Grabs data randomly
Args:
list_ (list):
nSample (?):
strict (bool): (default = False)
rng (module): random number generator(default = numpy.random)
seed (None): (default = None)
Returns:
... | 0.000787 |
def connection_made(self, transport):
'''
override asyncio.Protocol
'''
self._connected = True
self.transport = transport
self.remote_ip, self.port = transport.get_extra_info('peername')[:2]
logging.debug(
'Connection made (address: {} port: {})'
... | 0.002635 |
def SVG_path(path, transform=None, simplify=False):
"""Construct the vertices and SVG codes for the path
Parameters
----------
path : matplotlib.Path object
transform : matplotlib transform (optional)
if specified, the path will be transformed before computing the output.
Returns
... | 0.000751 |
def _replace_bm(self):
"""Replace ``_block_matcher`` with current values."""
self._block_matcher = cv2.StereoSGBM(minDisparity=self._min_disparity,
numDisparities=self._num_disp,
SADWindowSize=self._sad_window_size,
uniquenessRatio=... | 0.017107 |
def dodge(field_name, value, range=None):
''' Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
value (float) : the fixed offset to add to column data
... | 0.001634 |
def reg_project(self, field_list=None, all_but=None, new_field_dict=None):
"""
*Wrapper of* ``PROJECT``
Project the region data based on a list of field names
:param field_list: list of the fields to select
:param all_but: keep only the region fields different from the ones
... | 0.006207 |
def remove_stale_css(portal):
"""Removes stale CSS
"""
logger.info("Removing stale css ...")
for css in CSS_TO_REMOVE:
logger.info("Unregistering CSS %s" % css)
portal.portal_css.unregisterResource(css) | 0.004274 |
def os_discovery():
"""
Performs os (and domain) discovery of smb hosts.
"""
hs = HostSearch()
hosts = hs.get_hosts(ports=[445], tags=['!nmap_os'])
# TODO fix filter for emtpy fields.
hosts = [host for host in hosts if not host.os]
host_dict = {}
for host in hosts:
hos... | 0.001375 |
def stop(self, sig=signal.SIGINT):
'''Stop all the workers, and then wait for them'''
for cpid in self.sandboxes:
logger.warn('Stopping %i...' % cpid)
try:
os.kill(cpid, sig)
except OSError: # pragma: no cover
logger.exception('Error s... | 0.0022 |
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functo... | 0.007407 |
def create(self, width, height):
"""Create an image of type.
Parameters
----------
width: `int`
Image width.
height: `int`
Image height.
Returns
-------
`PIL.Image.Image`
"""
return Image.new(self.mode, (width, hei... | 0.006154 |
def read_identities(self, descriptors=None, identity_ids=None, subject_descriptors=None, search_filter=None, filter_value=None, query_membership=None, properties=None, include_restricted_visibility=None, options=None):
"""ReadIdentities.
:param str descriptors:
:param str identity_ids:
:... | 0.006032 |
def freeze(o):
"""
Recursively convert simple Python containers into pyrsistent versions
of those containers.
- list is converted to pvector, recursively
- dict is converted to pmap, recursively on values (but not keys)
- set is converted to pset, but not recursively
- tuple is converted to... | 0.00093 |
def get_profile_model():
"""
Returns the yacms profile model, defined in
``settings.ACCOUNTS_PROFILE_MODEL``, or ``None`` if no profile
model is configured.
"""
if not getattr(settings, "ACCOUNTS_PROFILE_MODEL", None):
raise ProfileNotConfigured
try:
return apps.get_model(s... | 0.001321 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.