text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_operator(name):
"""Get an operator class from a provider plugin.
Attrs:
name: The name of the operator class.
Returns: The operator *class object* (i.e. not an instance).
"""
sep = name.index('/')
provider_name = name[:sep]
operator_name = name[sep + 1:]
provider = OPE... | 0.002597 |
def get_strings(self):
"""
Yields all StringAnalysis for all unique Analysis objects
"""
seen = []
for digest, dx in self.analyzed_vms.items():
if dx in seen:
continue
seen.append(dx)
yield digest, self.analyzed_digest[digest], ... | 0.008696 |
def p_input_assignment(self, t):
'''input_assignment : IDENT EQ INPUT'''
self.accu.add(Term('input', [self.name,"gen(\""+t[1]+"\")"])) | 0.014085 |
def jwt_proccessor():
"""Context processor for jwt."""
def jwt():
"""Context processor function to generate jwt."""
token = current_accounts.jwt_creation_factory()
return Markup(
render_template(
current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
... | 0.001757 |
async def on_raw_762(self, message):
""" End of metadata. """
# No way to figure out whose query this belongs to, so make a best guess
# it was the first one.
if not self._metadata_queue:
return
nickname = self._metadata_queue.pop()
future = self._pending['me... | 0.007444 |
def sys_getrandom(self, buf, size, flags):
"""
The getrandom system call fills the buffer with random bytes of buflen.
The source of random (/dev/random or /dev/urandom) is decided based on
the flags value.
Manticore's implementation simply fills a buffer with zeroes -- choosing... | 0.003883 |
def compile_suffix_regex(entries):
"""Compile a sequence of suffix rules into a regex object.
entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search.
"""
expression = "|".join([piece + "$" f... | 0.007653 |
def merge_da(ts_d, ts_par_d, ts_a, ts_par_a):
"""Merge donor and acceptor timestamps and particle arrays.
Parameters:
ts_d (array): donor timestamp array
ts_par_d (array): donor particles array
ts_a (array): acceptor timestamp array
ts_par_a (array): acceptor particles array
... | 0.001439 |
def configure(cls, host_name: str = '', service_name: str = '', service_version='',
http_host: str = '127.0.0.1', http_port: int = 8000,
tcp_host: str = '127.0.0.1', tcp_port: int = 8001, ssl_context=None,
registry_host: str = "0.0.0.0", registry_port: int = 4500,
... | 0.008633 |
def str_rfind(x, sub, start=0, end=None):
"""Returns the highest indices in each string in a column, where the provided substring is fully contained between within a
sample. If the substring is not found, -1 is returned.
:param str sub: A substring to be found in the samples
:param int start:
:para... | 0.003988 |
def read_from(cls, data_stream, num_to_read):
""" Reads vlrs and parse them if possible from the stream
Parameters
----------
data_stream : io.BytesIO
stream to read from
num_to_read : int
number of vlrs to be read
Returns
... | 0.002809 |
def bintoihex(buf, spos=0x0000):
"""Convert binary buffer to ihex and return as string."""
c = 0
olen = len(buf)
ret = ""
# 16 byte lines
while (c+0x10) <= olen:
adr = c + spos
l = ':10{0:04X}00'.format(adr)
sum = 0x10+((adr>>8)&M8)+(adr&M8)
for j in range(0,0x10)... | 0.021119 |
def parse_first_number(s):
"""Parse the first number in the string we encounter.
s - The string to parse.
parse_first_number('123')
>>> 123
parse_first_number(' 12 meters')
>>> 12
parse_first_number('area: 156 meters')
>>> 156
parse_first_numbe... | 0.010714 |
def reissueMissingJobs(self, killAfterNTimesMissing=3):
"""
Check all the current job ids are in the list of currently running batch system jobs.
If a job is missing, we mark it as so, if it is missing for a number of runs of
this function (say 10).. then we try deleting the job (though ... | 0.009804 |
def _history_move(self, p_step):
"""
Changes current value of the command-line to the value obtained from
history_tmp list with index calculated by addition of p_step to the
current position in the command history (history_pos attribute).
Also saves value of the command-line (be... | 0.004367 |
def _recenter(self):
"""
one iteration of k-means
"""
for split_idx in range(len(self._splits)):
split = self._splits[split_idx]
len_idx = self._split2len_idx[split]
if split == self._splits[-1]:
continue
right_split = self.... | 0.003008 |
def make_request(url, data, on_complete):
"""
Make AJAX request to `url` with given POST `data`. Call `on_complete`
callback when complete.
Args:
url (str): URL.
data (dict): Dictionary with POST data.
on_complete (ref): Reference to function / method which will be called
... | 0.001845 |
def loads(self, value):
"""
Deserialize value using ``msgpack.loads``.
:param value: bytes
:returns: obj
"""
raw = False if self.encoding == "utf-8" else True
if value is None:
return None
return msgpack.loads(value, raw=raw, use_list=self.use... | 0.006135 |
def listRunSummaries(self, dataset="", run_num=-1):
"""
API to list run summaries, like the maximal lumisection in a run.
:param dataset: dataset name (Optional)
:type dataset: str
:param run_num: Run number (Required)
:type run_num: str, long, int
:rtype: list c... | 0.006021 |
def explode(self, hostgroups):
# pylint: disable=too-many-locals, too-many-branches
"""Explode all service dependency for each member of hostgroups
Each member of dependent hostgroup or hostgroup in dependency have to get a copy of
service dependencies (quite complex to parse)
:... | 0.002829 |
def r_oauth_logout(self):
"""
Route to clear the oauth data from the session
:return: {"template"}
"""
session.pop('oauth_user_uri', None)
session.pop('oauth_user_name', None)
next = request.args.get('next','')
if next is not None:
return redir... | 0.006881 |
def writeObject(self, obj, is_proxy=False):
"""
Writes an object to the stream.
"""
if self.use_proxies and not is_proxy:
self.writeProxy(obj)
return
self.stream.write(TYPE_OBJECT)
ref = self.context.getObjectReference(obj)
if ref != -1... | 0.001508 |
def reset(self):
"""!
\~english Reset display
\~chinese 复位显示屏
"""
if self._spi_reset == None: return
GPIO.output( self._spi_reset, 1 )
time.sleep(0.002)
GPIO.output( self._spi_reset, 0 )
time.sleep(0.015)
GPIO.output( self._spi_reset, 1 ) | 0.037736 |
def create_course_section(self, course_id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None, enable_sis_reactivation=None):
"""
Create course section.
Creates a n... | 0.003742 |
def files(self):
"""Returns the URLs of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url | 0.007246 |
def list_objects(self, query=None, limit=-1, offset=-1):
"""List of all objects in the database. Optinal parameter limit and
offset for pagination. A dictionary of key,value-pairs can be given as
addictional query condition for document properties.
Parameters
----------
... | 0.003531 |
async def on_shutdown(self):
"""
Cleans up any outstanding subscriptions.
"""
await self._unregister_subscriptions()
self._accepting = False
for (ws, _) in self._subscribers:
await ws.close(code=aiohttp.WSCloseCode.GOING_AWAY,
mess... | 0.005848 |
def flags(self, index):
""" Returns the item flags for the given index.
"""
if not index.isValid():
return QtCore.Qt.NoItemFlags
item = index.internalPointer()
# return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable |
# QtCore.Qt.ItemIsDragEnabled
... | 0.005764 |
def _queue_models(self, models, context):
"""
Work an an appropriate ordering for the models.
This isn't essential, but makes the script look nicer because
more instances can be defined on their first try.
"""
model_queue = []
number_remaining_models = len(models)... | 0.002946 |
def value(self):
"""Returns the positive value to subtract from the total."""
originalPrice = self.lineItem.totalPrice
if self.flatRate == 0:
return originalPrice * self.percent
return self.flatRate | 0.026087 |
def create(self, client=None, project=None, location=None):
"""Creates current bucket.
If the bucket already exists, will raise
:class:`google.cloud.exceptions.Conflict`.
This implements "storage.buckets.insert".
If :attr:`user_project` is set, bills the API request to that pr... | 0.001436 |
def git_sequence_editor_squash(fpath):
r"""
squashes wip messages
CommandLine:
python -m utool.util_git --exec-git_sequence_editor_squash
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> import utool as ut
>>> from utool.util_git import * # NOQA
>>> fpat... | 0.000533 |
def extend_settings(self, data_id, files, secrets):
"""Prevent processes requiring access to secrets from being run."""
process = Data.objects.get(pk=data_id).process
if process.requirements.get('resources', {}).get('secrets', False):
raise PermissionDenied(
"Process ... | 0.006369 |
def get_model(self, model_ref, retry=DEFAULT_RETRY):
"""[Beta] Fetch the model referenced by ``model_ref``.
Args:
model_ref (Union[ \
:class:`~google.cloud.bigquery.model.ModelReference`, \
str, \
]):
A reference to the model to f... | 0.001873 |
def _WriteFlowProcessingRequests(self, requests, cursor):
"""Returns a (query, args) tuple that inserts the given requests."""
templates = []
args = []
for req in requests:
templates.append("(%s, %s, %s, FROM_UNIXTIME(%s))")
args.append(db_utils.ClientIDToInt(req.client_id))
args.appen... | 0.009602 |
def on_btn_add_fit(self, event):
"""
add a new interpretation to the current specimen
Parameters
----------
event : the wx.ButtonEvent that triggered this function
Alters
------
pmag_results_data
"""
if self.auto_save.GetValue():
... | 0.005405 |
def index_impl(self):
"""Return {runName: {tagName: {displayName: ..., description: ...}}}."""
if self._db_connection_provider:
# Read tags from the database.
db = self._db_connection_provider()
cursor = db.execute('''
SELECT
Tags.tag_name,
Tags.display_name,
... | 0.005222 |
def to_json(self):
"""
Returns a json representation
"""
data = {}
for k, v in self.__dict__.items():
if not k.startswith('_'):
# values not serializable, should be converted to strings
if isinstance(v, datetime):
v ... | 0.00312 |
def protoFast():
"""
Runs the protocol but omits proof generation and verification.
"""
r, x = blind(m)
y,kw,tTilde = eval(w,t,x,msk,s)
z = deblind(r, y) | 0.039548 |
def present(name, auth=None, **kwargs):
'''
Ensure domain exists and is up-to-date
name
Name of the domain
enabled
Boolean to control if domain is enabled
description
An arbitrary description of the domain
'''
ret = {'name': name,
'changes': {},
... | 0.000715 |
def readU8(self, register):
"""Read an unsigned byte from the specified register."""
result = self._bus.read_byte_data(self._address, register) & 0xFF
self._logger.debug("Read 0x%02X from register 0x%02X",
result, register)
return result | 0.010345 |
def set_state(self, sync_data):
"""Called when a state is received from the front-end."""
# The order of these context managers is important. Properties must
# be locked when the hold_trait_notification context manager is
# released and notifications are fired.
with self._lock_pr... | 0.002999 |
def parse_env(config_schema, env):
"""Parse the values from a given environment against a given config schema
Args:
config_schema: A dict which maps the variable name to a Schema object
that describes the requested value.
env: A dict which represents the value of each variable in th... | 0.001563 |
def channels_kick(self, room_id, user_id, **kwargs):
"""Removes a user from the channel."""
return self.__call_api_post('channels.kick', roomId=room_id, userId=user_id, kwargs=kwargs) | 0.015075 |
def before_start(self, when=None):
""" Returns True if the task/course is not yet accessible """
if when is None:
when = datetime.now()
return self._val[0] > when | 0.01005 |
def comparison_negative(logical_line):
r"""Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:\n pass
Okay: assert (X in Y or X is Z)
Okay: if not (X in Y):\n pass
Okay: zz = x is not y
E713: Z = not X in Y
E713: if not X.B in Y:\n pass
E714: if... | 0.001497 |
def set_input(self, input_id):
"""Send Input command."""
req_url = ENDPOINTS["setInput"].format(self.ip_address, self.zone_id)
params = {"input": input_id}
return request(req_url, params=params) | 0.00885 |
def copy(string, **kwargs):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(
string.encode("utf-8"))
except OSError as why:
raise XcodeNotFound
return | 0.003745 |
def make_optimize_action(self, model, session=None, var_list=None, **kwargs):
"""
Build Optimization action task with Tensorflow optimizer.
:param model: GPflow model.
:param session: Tensorflow session.
:param var_list: List of Tensorflow variables to train.
... | 0.003359 |
async def rpc_server_info(self, request):
'''Return a dictionary of information regarding the server and workers.
It invokes the :meth:`extra_server_info` for adding custom
information.
'''
info = await send('arbiter', 'info')
info = self.extra_server_info(request, info)... | 0.004695 |
def validate_file(parser, arg):
"""Validates that `arg` is a valid file."""
if not os.path.isfile(arg):
parser.error("%s is not a file." % arg)
return arg | 0.005747 |
def create_headers(requester: str, *, accept: str = accept_format(),
oauth_token: Optional[str] = None,
jwt: Optional[str] = None) -> Dict[str, str]:
"""Create a dict representing GitHub-specific header fields.
The user agent is set according to who the requester is. GitHu... | 0.002049 |
def callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'Invoke callback, adjusting variable names as needed'
if isinstance(output, (list, tuple)):
fixed_outputs = [self._fix_callback_item(x) for x in output]
# Temporary check; can b... | 0.009963 |
def xpathNextPreceding(self, cur):
"""Traversal function for the "preceding" direction the
preceding axis contains all nodes in the same document as
the context node that are before the context node in
document order, excluding any ancestors and excluding
attribute nodes ... | 0.009036 |
def off(self):
"""
Turn all the output devices off.
"""
for device in self:
if isinstance(device, (OutputDevice, CompositeOutputDevice)):
device.off() | 0.009524 |
def starting_offset(source_code, offset):
"""Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[offset:])
Where... | 0.001767 |
def hwif(self, as_private=False):
"""Yield a 111-byte string corresponding to this node."""
return self._network.bip32_as_string(self.serialize(as_private=as_private), as_private=as_private) | 0.014563 |
def update_nested_dict(a, b):
"""
update nested dict `a` with another dict b.
usage::
>>> a = {'x' : { 'y': 1}}
>>> b = {'x' : {'z':2, 'y':3}, 'w': 4}
>>> update_nested_dict(a,b)
{'x': {'y': 3, 'z': 2}, 'w': 4}
"""
for k, v in b.iteritems():
if isinstance(v,... | 0.002232 |
def nastygram(nick, rest):
"""
A random passive-agressive comment, optionally directed toward
some(one|thing).
"""
recipient = ""
if rest:
recipient = rest.strip()
karma.Karma.store.change(recipient, -1)
return util.passagg(recipient, nick.lower()) | 0.03861 |
def update(self, fields=None, update=None, async_=None, jira=None, notify=True, **fieldargs):
"""Update this issue on the server.
Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value
is treated as the intended value for that field -- if the ... | 0.004559 |
def p_lpartselect_minus(self, p):
'lpartselect : identifier LBRACKET expression MINUSCOLON expression RBRACKET'
p[0] = Partselect(p[1], p[3], Minus(p[3], p[5]), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | 0.012876 |
def decoder(decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
name="decoder",
save_weights_to=None,
make_image_summary=True,):
"""A stack of transformer layers.
Args:
decoder_i... | 0.005271 |
def isarray(array, test, dim=2):
"""Returns True if test is True for all array elements.
Otherwise, returns False.
"""
if dim > 1:
return all(isarray(array[i], test, dim - 1)
for i in range(len(array)))
return all(test(i) for i in array) | 0.003521 |
def get_version_text(self):
"""Return the version information from Unix host."""
try:
version_text = self.device.send('uname -sr', timeout=10)
except CommandError:
self.log("Non Unix jumphost type detected")
return None
raise ConnectionError("Non U... | 0.005305 |
def __validate_dates(start_date, end_date):
"""Validate if a date string.
Validate if a string is a date on yyyy-mm-dd format and it the
period between them is less than a year.
"""
try:
start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
end_date = datetime.datetime.str... | 0.001362 |
def load(fnames, tag=None, sat_id=None, **kwargs):
"""Loads data using pysat.utils.load_netcdf4 .
This routine is called as needed by pysat. It is not intended
for direct user interaction.
Parameters
----------
fnames : array-like
iterable of filename strings, full path, to data fi... | 0.005758 |
def is_valid_input_meshgrid(x, ndim):
"""Test if ``x`` is a `meshgrid` sequence for points in R^d."""
# This case is triggered in FunctionSpaceElement.__call__ if the
# domain does not have an 'ndim' attribute. We return False and
# continue.
if ndim is None:
return False
if not isinsta... | 0.00156 |
def load_configuration_file(self, configuration_file):
"""
Load configuration defaults from a configuration file.
:param configuration_file: The pathname of a configuration file (a
string).
:raises: :exc:`Exception` when the configuration file cannot b... | 0.001992 |
def infer_edge(tpm, a, b, contexts):
"""Infer the presence or absence of an edge from node A to node B.
Let |S| be the set of all nodes in a network. Let |A' = S - {A}|. We call
the state of |A'| the context |C| of |A|. There is an edge from |A| to |B|
if there exists any context |C(A)| such that |Pr(B... | 0.000831 |
def is_list(node):
"""Does the node represent a list literal?"""
return (isinstance(node, Node)
and len(node.children) > 1
and isinstance(node.children[0], Leaf)
and isinstance(node.children[-1], Leaf)
and node.children[0].value == u"["
and node.childr... | 0.002933 |
def _preallocate_samples(self):
"""Preallocate samples for faster adaptive sampling.
"""
self.prealloc_samples_ = []
for i in range(self.num_prealloc_samples_):
self.prealloc_samples_.append(self.sample()) | 0.008032 |
def datagram_received(self, data, addr):
"""Method run when data is received from the devices
This method will unpack the data according to the LIFX protocol.
If a new device is found, the Light device will be created and started aa
a DatagramProtocol and will be registered with the par... | 0.003104 |
def _create_m2m_links_step(self, rel_model_name,
rel_key, rel_value, relation_name):
"""
Link many-to-many models together.
Syntax:
And `model` with `field` "`value`" is linked to `other model` in the
database:
Example:
.. code-block:: gherkin
... | 0.000838 |
def force_log(self, logType, message, data=None, tback=None, stdout=True, file=True):
"""
Force logging a message of a certain logtype whether logtype level is allowed or not.
:Parameters:
#. logType (string): A defined logging type.
#. message (string): Any message to log... | 0.00718 |
def extent(self):
"""
The extent of the mask, defined as the ``(xmin, xmax, ymin,
ymax)`` bounding box from the bottom-left corner of the
lower-left pixel to the upper-right corner of the upper-right
pixel.
The upper edges here are the actual pixel positions of the
... | 0.00316 |
def assert_instance_deleted(self, model_class, **kwargs):
"""
Checks if the model instance was deleted from the database.
For example::
>>> with self.assert_instance_deleted(Article, slug='lorem-ipsum'):
... Article.objects.get(slug='lorem-ipsum').delete()
"""
... | 0.004057 |
def submit(self, coro, callback=None):
"""Submit a coro as NewTask to self.loop without loop.frequncy control.
::
from torequests.dummy import Loop
import asyncio
loop = Loop()
async def test(i):
result = await asyncio.sleep(1)
... | 0.00324 |
def list_documents(
self,
parent,
collection_id,
page_size=None,
order_by=None,
mask=None,
transaction=None,
read_time=None,
show_missing=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.D... | 0.00295 |
def fishqq(lon=None, lat=None, di_block=None):
"""
Test whether a distribution is Fisherian and make a corresponding Q-Q plot.
The Q-Q plot shows the data plotted against the value expected from a
Fisher distribution. The first plot is the uniform plot which is the
Fisher model distribution in terms... | 0.00031 |
def _expectation(p, kern, feat, none1, none2, nghp=None):
"""
Compute the expectation:
<K_{X, Z}>_p(X)
- K_{.,.} :: Linear kernel
:return: NxM
"""
with params_as_tensors_for(kern, feat):
# use only active dimensions
Z, Xmu = kern._slice(feat.Z, p.mu)
return tf.m... | 0.002725 |
def load_metamodel(resource):
'''
Load and return a metamodel from a *resource*. The *resource* may be either
a filename, or a list of filenames.
Usage example:
>>> metamodel = xtuml.load_metamodel(['schema.sql', 'data.sql'])
'''
if isinstance(resource, str):
resource = [re... | 0.010549 |
def _check_file(self, filename):
"""Process python file looking for indications of problems.
:param filename: (str) Python source filename
:return: (int) number of failures
"""
# If the user specifies an invalid severity use comment.
log_threshold = Nit.SEVERITY.get(self._severity, Nit.COMMENT)... | 0.006766 |
def check_minions(self,
expr,
tgt_type='glob',
delimiter=DEFAULT_TARGET_DELIM,
greedy=True):
'''
Check the passed regex against the available minions' public keys
stored for authentication. This should return... | 0.005814 |
def get_print_bbox(x, y, zoom, width, height, dpi):
"""
Calculate the tile bounding box based on position, map size and resolution.
The function returns the next larger tile-box, that covers the specified
page size in mm.
Args:
x (float): map center x-coordinate in Mercator projection (EPS... | 0.002217 |
def export_osm_file(self):
"""Generate OpenStreetMap element tree from ``Osm``."""
osm = create_elem('osm', {'generator': self.generator,
'version': self.version})
osm.extend(obj.toosm() for obj in self)
return etree.ElementTree(osm) | 0.006667 |
def on_idle(self, event):
'''prevent the main loop spinning too fast'''
state = self.state
if state.close_window.acquire(False):
self.state.app.ExitMainLoop()
now = time.time()
if now - self.last_layout_send > 1:
self.last_layout_send = now
s... | 0.002098 |
def random_date(start_year=2000, end_year=2020):
"""
Generates a random "sensible" date for use in things like issue dates and maturities
"""
return date(random.randint(start_year, end_year), random.randint(1, 12), random.randint(1, 28)) | 0.011858 |
def query_sequence(self):
""" Overrides align. corrects orientation with reverse complement if on negative strand
.. warning:: this returns the full query sequence, not just the aligned portion, but i also does not include hard clipped portions (only soft clipped)
"""
if not self.entries.seq: return No... | 0.012255 |
def name(self):
"""获取用户名字.
:return: 用户名字
:rtype: str
"""
if self.url is None:
return '匿名用户'
if self.soup is not None:
return self.soup.find('div', class_='title-section').span.text
else:
assert self.card is not None
... | 0.005405 |
def _spawn_kafka_consumer_thread(self):
"""Spawns a kafka continuous consumer thread"""
self.logger.debug("Spawn kafka consumer thread""")
self._consumer_thread = Thread(target=self._consumer_loop)
self._consumer_thread.setDaemon(True)
self._consumer_thread.start() | 0.006557 |
def get_client_ip_address(request: HttpRequest) -> str:
"""
Get client IP address as configured by the user.
The django-ipware package is used for address resolution
and parameters can be configured in the Axes package.
"""
client_ip_address, _ = ipware.ip2.get_client_ip(
request,
... | 0.001704 |
def thumbUrl(self):
""" Return the first first thumbnail url starting on
the most specific thumbnail for that item.
"""
thumb = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(thumb, includeToken=True) if thumb else None | 0.006711 |
def get_segment_projects(segment_id):
"""
Returns all projects from a segment.
"""
df = data.all_items
return (
df[df['idSegmento'] == str(segment_id)]
.drop_duplicates(["PRONAC"])
.values
) | 0.004202 |
def do_pre_construct(self, request_args, **kwargs):
"""
Will run the pre_construct methods one by one in the order given.
:param request_args: Request arguments
:param kwargs: Extra key word arguments
:return: A tuple of request_args and post_args. post_args are to be
... | 0.00458 |
def superuser_required(view_func):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
@wraps(view_func)
def _checklogin(request, *args, **kwargs):
if request.user.is_active and request.user.is_superuser:
... | 0.001898 |
def get_object_directory(self, obj):
"""
Return the directory containing an object's defining class.
Returns None if there is no such directory, for example if the
class was defined in an interactive Python session, or in a
doctest that appears in a text file (rather than a Pyth... | 0.003101 |
def ensure_timezone(func, argname, arg):
"""Argument preprocessor that converts the input into a tzinfo object.
Examples
--------
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(tz=ensure_timezone)
... def foo(tz):
... return tz
>>> foo('utc')
<UTC>
"""
... | 0.001511 |
def _families_and_addresses(self, hostname, port):
"""
Yield pairs of address families and addresses to try for connecting.
:param str hostname: the server to connect to
:param int port: the server port to connect to
:returns: Yields an iterable of ``(family, address)`` tuples
... | 0.002092 |
def _send_command_list(self, commands):
"""Wrapper for Netmiko's send_command method (for list of commands."""
output = ""
for command in commands:
output += self.device.send_command(
command, strip_prompt=False, strip_command=False
)
return output | 0.00625 |
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.focus_changed.connect(self.main.plugin_focus_changed)
self.main.add_dockwidget(self)
# Connecting the following signal once the dockwidget has been created:
self.shell.exception_occurred.connect(se... | 0.005848 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.