Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _get(self, route, stream=False):
"""
run a get request against an url. Returns the response which can optionally be streamed
"""
log.debug("Running GET request against %s" % route)
return r.get(self._url(route), auth=c.auth, stream=stream) |
def get_contents(self, folder: Folder):
"""
List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder.
"""
log.debug("Listing Contents of %s/%s" % (folder.course.id, folder.id))
if isinstance(folder, Course):
response = j... |
def download_document(self, document: Document, overwrite=True, path=None):
"""
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
If overwrite is set the local version will be overwritten if the file was changed on... |
def get_semester_title(self, node: BaseNode):
"""
get the semester of a node
"""
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) |
def get_courses(self):
"""
use the base_url and auth data from the configuration to list all courses the user is subscribed to
"""
log.info("Listing Courses...")
courses = json.loads(self._get('/api/courses').text)["courses"]
courses = [Course.from_response(course) for co... |
def _minimize_scalar(
self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True
):
"""
Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise.
"""
... |
def digest(self, alg='sha256', b64=True, strip=True):
"""return a url-safe hash of the string, optionally (and by default) base64-encoded
alg='sha256' = the hash algorithm, must be in hashlib
b64=True = whether to base64-encode the output
strip=True = wheth... |
def camelify(self):
"""turn a string to CamelCase, omitting non-word characters"""
outstring = self.titleify(allwords=True)
outstring = re.sub(r"&[^;]+;", " ", outstring)
outstring = re.sub(r"\W+", "", outstring)
return String(outstring) |
def titleify(self, lang='en', allwords=False, lastword=True):
"""takes a string and makes a title from it"""
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
... |
def identifier(self, camelsplit=False, ascii=True):
"""return a python identifier from the string (underscore separators)"""
return self.nameify(camelsplit=camelsplit, ascii=ascii, sep='_') |
def nameify(self, camelsplit=False, ascii=True, sep='-'):
"""return an XML name (hyphen-separated by default, initial underscore if non-letter)"""
s = String(str(self)) # immutable
if camelsplit == True:
s = s.camelsplit()
s = s.hyphenify(ascii=ascii).replace('-', sep)
... |
def hyphenify(self, ascii=False):
"""Turn non-word characters (incl. underscore) into single hyphens.
If ascii=True, return ASCII-only.
If also lossless=True, use the UTF-8 codes for the non-ASCII characters.
"""
s = str(self)
s = re.sub("""['"\u2018\u2019\u201c\u20... |
def camelsplit(self):
"""Turn a CamelCase string into a string with spaces"""
s = str(self)
for i in range(len(s) - 1, -1, -1):
if i != 0 and (
(s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper())
or (s[i].isnumeric() and s[i - 1].i... |
def includeme(config):
"""Pyramid pluggable and discoverable function."""
global_settings = config.registry.settings
settings = local_settings(global_settings, PREFIX)
try:
file = settings['file']
except KeyError:
raise KeyError("Must supply '{}.file' configuration value "
... |
def run(self):
"""Executed on startup of application"""
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
for call, calldata in self.context.get("calls", {}).items():
def loop():
"""Loop on event... |
def call(self, callname, arguments=None):
"""Executed on each scheduled iteration"""
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
excep... |
def _generate_request(self, callname, request):
"""Generate a request object for delivery to the API"""
# Retrieve path from API class
schema = self.api.request_schema()
schema.context['callname'] = callname
return schema.dump(request).data.get("payload") |
def _generate_result(self, callname, result):
"""Generate a results object for delivery to the context object"""
# Retrieve path from API class
schema = self.api.result_schema()
schema.context['callname'] = callname
self.callback(schema.load(result), self.context) |
def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters."""
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) |
def convert_to_crash_data(raw_crash, processed_crash):
"""
Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed cr... |
def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
"""
# Strip all non-ascii and non-printable characters
te... |
def parse_source_file(source_file):
"""Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the fil... |
def _is_exception(exceptions, before_token, after_token, token):
"""Predicate for whether the open token is in an exception context
:arg exceptions: list of strings or None
:arg before_token: the text of the function up to the token delimiter
:arg after_token: the text of the function after the token d... |
def collapse(
function,
open_string,
close_string,
replacement='',
exceptions=None,
):
"""Collapses the text between two delimiters in a frame function value
This collapses the text between two delimiters and either removes the text
altogether or replaces it with a replacement string.
... |
def drop_prefix_and_return_type(function):
"""Takes the function value from a frame and drops prefix and return type
For example::
static void * Allocator<MozJemallocBase>::malloc(unsigned __int64)
^ ^^^^^^ return type
prefix
This gets changes to this::
Allocator<Moz... |
def wait_connected(self, conns=None, timeout=None):
'''Wait for connections to be made and their handshakes to finish
:param conns:
a single or list of (host, port) tuples with the connections that
must be finished before the method will return. defaults to all the
p... |
def shutdown(self):
'Close all peer connections and stop listening for new ones'
log.info("shutting down")
for peer in self._dispatcher.peers.values():
peer.go_down(reconnect=False)
if self._listener_coro:
backend.schedule_exception(
errors._... |
def accept_publish(
self, service, mask, value, method, handler=None, schedule=False):
'''Set a handler for incoming publish messages
:param service: the incoming message must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-an... |
def unsubscribe_publish(self, service, mask, value):
'''Remove a publish subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value i... |
def publish(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False, udp=False):
'''Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int routing_id:
the id used for routing w... |
def publish_receiver_count(self, service, routing_id):
'''Get the number of peers that would handle a particular publish
:param service: the service name
:type service: anything hash-able
:param routing_id: the id used for limiting the service handlers
:type routing_id: int
... |
def accept_rpc(self, service, mask, value, method,
handler=None, schedule=True):
'''Set a handler for incoming RPCs
:param service: the incoming RPC must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-and'ed against the incom... |
def unsubscribe_rpc(self, service, mask, value):
'''Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the su... |
def send_rpc(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False):
'''Send out an RPC request
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the r... |
def rpc(self, service, routing_id, method, args=None, kwargs=None,
timeout=None, broadcast=False):
'''Send an RPC request and return the corresponding response
This will block waiting until the response has been received.
:param service: the service name (the routing top level)
... |
def rpc_receiver_count(self, service, routing_id):
'''Get the number of peers that would handle a particular RPC
:param service: the service name
:type service: anything hash-able
:param routing_id:
the id used for narrowing within the service handlers
:type routing_... |
def start(self):
"Start up the hub's server, and have it start initiating connections"
log.info("starting")
self._listener_coro = backend.greenlet(self._listener)
self._udp_listener_coro = backend.greenlet(self._udp_listener)
backend.schedule(self._listener_coro)
backend... |
def add_peer(self, peer_addr):
"Build a connection to the Hub at a given ``(host, port)`` address"
peer = connection.Peer(
self._ident, self._dispatcher, peer_addr, backend.Socket())
peer.start()
self._started_peers[peer_addr] = peer |
def peers(self):
"list of the (host, port) pairs of all connected peer Hubs"
return [addr for (addr, peer) in self._dispatcher.peers.items()
if peer.up] |
def main(argv=None):
"""Takes crash data via args and generates a Socorro signature
"""
parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
parser.add_argument(
'... |
def send_result(self, return_code, output, service_description='', time_stamp=0, specific_servers=None):
'''
Send result to the Skinken WS
'''
if time_stamp == 0:
time_stamp = int(time.time())
if specific_servers == None:
specific_servers = self.servers
... |
def close_cache(self):
'''
Close cache of WS Shinken
'''
# Close all WS_Shinken cache files
for server in self.servers:
if self.servers[server]['cache'] == True:
self.servers[server]['file'].close() |
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, d... |
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :clas... |
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the f... |
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autos... |
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, `... |
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a pac... |
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding pac... |
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:rais... |
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classe... |
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:... |
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
... |
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
""... |
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type en... |
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes] |
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root ==... |
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`s... |
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix... |
def _isclose(obja, objb, rtol=1e-05, atol=1e-08):
"""Return floating point equality."""
return abs(obja - objb) <= (atol + rtol * abs(objb)) |
def _isreal(obj):
"""
Determine if an object is a real number.
Both Python standard data types and Numpy data types are supported.
:param obj: Object
:type obj: any
:rtype: boolean
"""
# pylint: disable=W0702
if (obj is None) or isinstance(obj, bool):
return False
try... |
def _no_exp(number):
r"""
Convert a number to a string without using scientific notation.
:param number: Number to convert
:type number: integer or float
:rtype: string
:raises: RuntimeError (Argument \`number\` is not valid)
"""
if isinstance(number, bool) or (not isinstance(number,... |
def _to_scientific_tuple(number):
r"""
Return mantissa and exponent of a number expressed in scientific notation.
Full precision is maintained if the number is represented as a string.
:param number: Number
:type number: integer, float or string
:rtype: Tuple whose first item is the mantissa... |
def gcd(vector):
"""
Calculate the greatest common divisor (GCD) of a sequence of numbers.
The sequence can be a list of numbers or a Numpy vector of numbers. The
computations are carried out with a precision of 1E-12 if the objects are
not `fractions <https://docs.python.org/3/library/fractions.ht... |
def normalize(value, series, offset=0):
r"""
Scale a value to the range defined by a series.
:param value: Value to normalize
:type value: number
:param series: List of numbers that defines the normalization range
:type series: list
:param offset: Normalization offset, i.e. the returned... |
def per(arga, argb, prec=10):
r"""
Calculate percentage difference between numbers.
If only two numbers are given, the percentage difference between them is
computed. If two sequences of numbers are given (either two lists of
numbers or Numpy vectors), the element-wise percentage difference is
... |
def pgcd(numa, numb):
"""
Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5... |
def connect_ws(self, post_connect_callback, channels, reconnect=False):
"""
Connect to a websocket
:channels: List of SockChannel instances
"""
self.post_conn_cb = post_connect_callback
self.channels = channels
self.wsendpoint = self.context["conf"]["endpoints"].... |
def wscall(self, method, query=None, callback=None):
"""Submit a request on the websocket"""
if callback is None:
self.sock.emit(method, query)
else:
self.sock.emitack(method, query, callback) |
def connect_channels(self, channels):
"""Connect the provided channels"""
self.log.info(f"Connecting to channels...")
for chan in channels:
chan.connect(self.sock)
self.log.info(f"\t{chan.channel}") |
def _on_set_auth(self, sock, token):
"""Set Auth request received from websocket"""
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) |
def _on_auth(self, sock, authenticated): # pylint: disable=unused-argument
"""Message received from websocket"""
def ack(eventname, error, data): # pylint: disable=unused-argument
"""Ack"""
if error:
self.log.error(f"""OnAuth: {error}""")
else:
... |
def _on_connect_error(self, sock, err): # pylint: disable=unused-argument
"""Error received from websocket"""
if isinstance(err, SystemExit):
self.log.error(f"Shutting down websocket connection")
else:
self.log.error(f"Websocket error: {err}") |
def connect(self, sock):
"""Attach a given socket to a channel"""
def cbwrap(*args, **kwargs):
"""Callback wrapper; passes in response_type"""
self.callback(self.response_type, *args, **kwargs)
self.sock = sock
self.sock.subscribe(self.channel)
self.sock.... |
def run_cmd(cmd, input=None, timeout=30, max_try=3, num_try=1):
'''Run command `cmd`.
It's like that, and that's the way it is.
'''
if type(cmd) == str:
cmd = cmd.split()
process = subprocess.Popen(cmd,
stdin=open('/dev/null', 'r'),
... |
def pop_first_arg(argv):
"""
find first positional arg (does not start with -), take it out of array and return it separately
returns (arg, array)
"""
for arg in argv:
if not arg.startswith('-'):
argv.remove(arg)
return (arg, argv)
return (None, argv) |
def check_options(options, parser):
"""
check options requirements, print and return exit value
"""
if not options.get('release_environment', None):
print("release environment is required")
parser.print_help()
return os.EX_USAGE
return 0 |
def write(self):
""" write all needed state info to filesystem """
dumped = self._fax.codec.dump(self.__state, open(self.state_file, 'w')) |
def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params):
"""configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
... |
def write(self, fn=None, sorted=False, wait=0):
"""write the contents of this config to fn or its __filename__.
"""
config = ConfigParser(interpolation=None)
if sorted==True: keys.sort()
for key in self.__dict__.get('ordered_keys') or self.keys():
config[key] = ... |
def expected_param_keys(self):
"""returns a list of params that this ConfigTemplate expects to receive"""
expected_keys = []
r = re.compile('%\(([^\)]+)\)s')
for block in self.keys():
for key in self[block].keys():
s = self[block][key]
i... |
def render(self, fn=None, prompt=False, **params):
"""return a Config with the given params formatted via ``str.format(**params)``.
fn=None : If given, will assign this filename to the rendered Config.
prompt=False : If True, will prompt for any param that is None.
"""
... |
def main():
"""Takes a crash id, pulls down data from Socorro, generates signature data"""
parser = argparse.ArgumentParser(
formatter_class=WrappedTextHelpFormatter,
description=DESCRIPTION
)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store... |
def _fill_text(self, text, width, indent):
"""Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs.
"""
parts = text.split('\n\n')
for i, part in enumerate(parts):
# Check to see if it's a bulleted list--if so, then... |
def get_api_services_by_name(self):
"""Return a dict of services by name"""
if not self.services_by_name:
self.services_by_name = dict({s.get('name'): s for s in self.conf
.get("api")
.get("services")})
... |
def get_api_endpoints(self, apiname):
"""Returns the API endpoints"""
try:
return self.services_by_name\
.get(apiname)\
.get("endpoints")\
.copy()
except AttributeError:
raise Exception(f"Couldn't find the API en... |
def get_ws_subscriptions(self, apiname):
"""Returns the websocket subscriptions"""
try:
return self.services_by_name\
.get(apiname)\
.get("subscriptions")\
.copy()
except AttributeError:
raise Exception(f"Couldn'... |
def get_api(self, name=None):
"""Returns the API configuration"""
if name is None:
try:
return self.conf.get("api").copy()
except: # NOQA
raise Exception(f"Couldn't find the API configuration") |
def get_api_service(self, name=None):
"""Returns the specific service config definition"""
try:
svc = self.services_by_name.get(name, None)
if svc is None:
raise ValueError(f"Couldn't find the API service configuration")
return svc
except: # N... |
def _ex_type_str(exobj):
"""Return a string corresponding to the exception type."""
regexp = re.compile(r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>")
exc_type = str(exobj)
if regexp.match(exc_type):
exc_type = regexp.match(exc_type).groups()[0]
exc_type = exc_type[11:] if exc_type.starts... |
def _unicode_to_ascii(obj): # pragma: no cover
"""Convert to ASCII."""
# pylint: disable=E0602,R1717
if isinstance(obj, dict):
return dict(
[
(_unicode_to_ascii(key), _unicode_to_ascii(value))
for key, value in obj.items()
]
)
if i... |
def send_result(self, return_code, output, service_description='', specific_servers=None):
'''
Send results
'''
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.servers).intersection(specific_servers)
... |
def get_remote_executors(hub_ip, port = 4444):
''' Get remote hosts from Selenium Grid Hub Console
@param hub_ip: hub ip of selenium grid hub
@param port: hub port of selenium grid hub
'''
resp = requests.get("http://%s:%s/grid/console" %(hub_ip, port))
re... |
def gen_remote_driver(executor, capabilities):
''' Generate remote drivers with desired capabilities(self.__caps) and command_executor
@param executor: command executor for selenium remote driver
@param capabilities: A dictionary of capabilities to request when starting the browser session.
... |
def gen_local_driver(browser, capabilities):
''' Generate localhost drivers with desired capabilities(self.__caps)
@param browser: firefox or chrome
@param capabilities: A dictionary of capabilities to request when starting the browser session.
@return: localhost driver
'... |
def _production(self):
"""Calculate total energy production. Not rounded"""
return self._nuclear + self._diesel + self._gas + self._wind + self._combined + self._vapor + self._solar + self._hydraulic + self._carbon + self._waste + self._other |
def _links(self):
"""Calculate total energy production. Not Rounded"""
total = 0.0
for value in self.link.values():
total += value
return total |
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer i... |
def wall_of_name(self):
'''
Appends identifiers for the different databases (such as Entrez id's)
and returns them. Uses the CrossRef class below.
'''
names = []
if self.standard_name:
names.append(self.standard_name)
if self.systematic_name:
... |
def save(self, *args, **kwargs):
"""
Override save() method to make sure that standard_name and
systematic_name won't be null or empty, or consist of only space
characters (such as space, tab, new line, etc).
"""
empty_std_name = False
if not self.standard_name or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.