code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
api_params = { "addresses[]": addresses, "contract_hashes[]": contracts } return self.request.get(path='/balances', params=api_params)
def get_balance(self, addresses, contracts)
Function to fetch the current account balance for the given address in the Switcheo smart contract. Execution of this function is as follows:: get_balance(address=neo_get_scripthash_from_address(address=address)) The expected return result for this function is as follows:: { ...
5.126862
6.038536
0.849024
logger.info('Ignoring file extension: {}'.format(extension)) self.watcher.ignore_file_extension(extension)
def ignore_file_extension(self, extension)
Configure a file extension to be ignored. :param extension: file extension to be ignored (ex. .less, .scss, etc)
4.734528
4.938478
0.958702
if isinstance(func, string_types): func = shell(func) self.watcher.watch(filepath, func, delay)
def watch(self, filepath, func=None, delay=None)
Add the given filepath for watcher list. Once you have intialized a server, watch file changes before serve the server:: server.watch('static/*.stylus', 'make static') def alert(): print('foo') server.watch('foo.txt', alert) server.serve(...
5.317578
6.255458
0.85007
host = host or '127.0.0.1' logger.info('Serving on http://%s:%s' % (host, liveport)) self.application(host, liveport=liveport) try: self.watcher._changes.append(('__livereload__', restart_delay)) LiveReloadHandler.start_tasks() IOLoop.instan...
def serve(self, liveport=None, host=None, restart_delay=2)
Start serve the server with the given port. :param liveport: live reload on this port :param host: serve on this hostname, default is 127.0.0.1 :param open_url_delay: open webbrowser after the delay seconds
4.631172
5.414121
0.855388
_, ext = os.path.splitext(filename) return ext in self.ignored_file_extensions
def should_ignore(self, filename)
Should ignore a given filename?
4.68628
3.926008
1.19365
if self._changes: return self._changes.pop() # clean filepath self.filepath = None delays = set([0]) for path in self._tasks: item = self._tasks[path] if self.is_changed(path, item['ignore']): func = item['func'] ...
def examine(self)
Check if there are changes, if true, run the given task.
5.640695
4.916093
1.147394
style = color_style() verbosity = int(options['verbosity']) host = '%s:%d' % ( options['livereload_host'], options['livereload_port'], ) try: urlopen('http://%s/forcereload' % host) self.message('LiveReload request emitted....
def livereload_request(self, **options)
Performs the LiveReload request.
5.808509
5.403899
1.074874
handler = super(Command, self).get_handler(*args, **options) if options['use_livereload']: threading.Timer(1, self.livereload_request, kwargs=options).start() return handler
def get_handler(self, *args, **options)
Entry point to plug the LiveReload feature.
4.497826
3.805301
1.181989
try: signing.loads(value, salt=salt, max_age=-999999) except signing.SignatureExpired as e: age = float(str(e).split('Signature age ')[1].split(' >')[0]) timestamp = timezone.now() - datetime.timedelta(seconds=age) return timestamp, signing.loads(value, salt=salt)
def loads_with_timestamp(value, salt)
Returns the unsigned value along with its timestamp, the time when it got dumped.
3.878797
4.034492
0.961409
if hasattr(socket, "SO_KEEPALIVE"): sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if hasattr(socket, "TCP_KEEPIDLE"): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec) if hasattr(socket, "TCP_KEEPINTVL"): sock.setsockopt(socket.IPPROTO_TCP, so...
def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5)
Set TCP keepalive on an open socket. It activates after 1 second (after_idle_sec) of idleness, then sends a keepalive ping once every 3 seconds (interval_sec), and closes the connection after 5 failed ping (max_fails), or 15 seconds
1.247401
1.363777
0.914666
self.log.debug('starting the ``get`` method') dictList = self._create_dictionary_of_veron() tableName = self.dbTableName createStatement = % locals() self.add_data_to_database_table( dictList=dictList, createStatement=createStatement )...
def ingest(self)
ingest the veron catalogue into the catalogues database See class docstring for usage.
11.537303
7.871314
1.46574
self.log.debug( 'starting the ``_create_dictionary_of_veron`` method') dictList = [] lines = string.split(self.catData, '\n') totalCount = len(lines) count = 0 switch = 0 for line in lines: if (len(line) == 0 or line[0] in ["#", ...
def _create_dictionary_of_veron( self)
create a list of dictionaries containing all the rows in the veron catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the veron catalogue .. todo :: - update key arguments values and definitions with defaults - update return va...
2.945665
2.854582
1.031908
try: copy = self.image.copy() except AttributeError: raise Exception("You need to set the Filter.image attribute for displaying") copy = BrightnessProcessor(brightness=0.6).process(copy) s, g = self._input, self.good_segments_indexes draw_segments...
def display(self, display_before=False)
shows the effect of this filter
6.481345
6.11885
1.059242
outdata = _define_output_dict() _config(mip_config_raw, outdata) _qc_metrics(outdata, qcmetrics_raw) _qc_sample_info(outdata, sampleinfo_raw) return outdata
def parse_mip_analysis(mip_config_raw: dict, qcmetrics_raw: dict, sampleinfo_raw: dict) -> dict
Parse the output analysis files from MIP for adding info to trend database Args: mip_config_raw (dict): raw YAML input from MIP analysis config file qcmetrics_raw (dict): raw YAML input from MIP analysis qc metric file sampleinfo_raw (dict): raw YAML input from MIP analysis qc sample in...
4.357593
4.377483
0.995456
self.log.debug('starting the ``get`` method') self._update_tcs_helper_catalogue_tables_info_with_new_tables() self._updated_row_counts_in_tcs_helper_catalogue_tables_info() self._clean_up_columns() self._update_tcs_helper_catalogue_views_info_with_new_views() se...
def clean(self)
*clean up and run some maintance tasks on the crossmatch catalogue helper tables* .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text -...
4.620155
4.001851
1.154504
self.log.debug( 'starting the ``_updated_row_counts_in_tcs_helper_catalogue_tables_info`` method') sqlQuery = u % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, quiet=False ) ...
def _updated_row_counts_in_tcs_helper_catalogue_tables_info( self)
updated row counts in tcs catalogue tables .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists ...
2.239242
2.272736
0.985263
self.log.debug( 'starting the ``_update_tcs_helper_catalogue_tables_info_with_new_tables`` method') sqlQuery = u % locals() thisId = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, quiet=False ...
def _update_tcs_helper_catalogue_tables_info_with_new_tables( self)
update tcs helper catalogue tables info with new tables .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exi...
2.374247
2.401544
0.988633
self.log.debug('starting the ``_clean_up_columns`` method') sqlQueries = [ "update tcs_helper_catalogue_tables_info set old_table_name = table_name where old_table_name is null;", "update tcs_helper_catalogue_tables_info set version_number = 'stream' where table_name li...
def _clean_up_columns( self)
clean up columns .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text ...
2.597002
2.603959
0.997328
self.log.debug( 'starting the ``_update_tcs_helper_catalogue_views_info_with_new_views`` method') sqlQuery = u % locals() thisId = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, quiet=False )...
def _update_tcs_helper_catalogue_views_info_with_new_views( self)
update tcs helper catalogue tables info with new tables .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exi...
2.622097
2.611545
1.00404
'''Restart listener after configuration update. ''' if self.listener is not None: if self.listener.running: self.stop() self.__init__(topics=topics)
def restart_listener(self, topics)
Restart listener after configuration update.
6.726367
5.514036
1.219863
'''Stop listener.''' self.logger.debug("Stopping listener.") self.listener.stop() if self.thread is not None: self.thread.join() self.thread = None self.logger.debug("Listener stopped.")
def stop(self)
Stop listener.
3.287263
3.112659
1.056095
'''Create a subscriber instance using specified addresses and message types. ''' if self.subscriber is None: if self.topics: self.subscriber = NSSubscriber(self.services, self.topics, addr_listener=True, ...
def create_subscriber(self)
Create a subscriber instance using specified addresses and message types.
9.352229
6.373929
1.467263
'''Run listener ''' self.running = True for msg in self.recv(1): if msg is None: if self.running: continue else: break self.logger.debug("New message received: %s", str(msg)) se...
def run(self)
Run listener
5.469552
5.091317
1.07429
'''Stop subscriber and delete the instance ''' self.running = False time.sleep(1) if self.subscriber is not None: self.subscriber.stop() self.subscriber = None
def stop(self)
Stop subscriber and delete the instance
5.200469
3.42072
1.520285
# get the not-none values from data known = { key: data.get(alias) for key, alias in config._forward_aliases.items() if data.get(alias) is not None } # prefer the strict field, if available potentials = [ known.pop(Constants.VERSION_STRICT_FIELD, None), ...
def get_current_semver(data)
Given a dictionary of all version data available, determine the current version
4.734942
4.741988
0.998514
new_semver = {} bumped = False for sig_fig in SemVerSigFig: # iterate sig figs in order of significance value = getattr(current_semver, sig_fig) override = overrides.get(sig_fig) if override is not None: new_semver[sig_fig] = override if int(override) > ...
def make_new_semver(current_semver, all_triggers, **overrides)
Defines how to increment semver based on which significant figure is triggered
2.673014
2.362039
1.131655
data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP # Get headers match_dest = RE_HEADER.search(data) dest_name = match_dest.group(1) dest_ip = match_dest.group(2) # The Traceroute is the root of the tree. traceroute = Traceroute(dest_name, dest_ip) # Get hops ma...
def loads(data)
Parser entry point. Parses the output of a traceroute execution
3.611286
3.537288
1.020919
if self.probes: probe_last = self.probes[-1] if not probe.ip: probe.ip = probe_last.ip probe.name = probe_last.name self.probes.append(probe)
def add_probe(self, probe)
Adds a Probe instance to this hop's results.
3.07817
2.95447
1.041869
if not (args and hasattr(args[0], '_lock')): return func(*args, **kwargs) with args[0]._lock: # pylint: disable=W0212 return func(*args, **kwargs)
def synchronized(func, *args, **kwargs)
Function decorator to make function synchronized on ``self._lock``. If the first argument to the function (hopefully self) does not have a _lock attribute, then this decorator does nothing.
2.986954
2.844141
1.050213
if not isinstance(job_id, uuid.UUID): job_id = uuid.UUID(job_id) return job_id
def normalize_job_id(job_id)
Convert a value to a job id. :param job_id: Value to convert. :type job_id: int, str :return: The job id. :rtype: :py:class:`uuid.UUID`
2.374953
2.267843
1.04723
if self.use_utc: return datetime.datetime.utcnow() else: return datetime.datetime.now()
def now(self)
Return a :py:class:`datetime.datetime` instance representing the current time. :rtype: :py:class:`datetime.datetime`
2.933819
2.801852
1.0471
if self._thread_running.is_set(): raise RuntimeError('the JobManager has already been started') self._thread.start() self._thread_running.wait() return
def start(self)
Start the JobManager thread.
4.479011
3.252851
1.376949
self.logger.debug('stopping the job manager') self._thread_running.clear() self._thread_shutdown.wait() self._job_lock.acquire() self.logger.debug('waiting on ' + str(len(self._jobs)) + ' job threads') for job_desc in self._jobs.values(): if job_desc['job'] is None: continue if not job_desc['jo...
def stop(self)
Stop the JobManager thread.
4.14192
3.943445
1.05033
if not self._thread_running.is_set(): raise RuntimeError('the JobManager is not running') parameters = (parameters or ()) if not isinstance(parameters, (list, tuple)): parameters = (parameters,) job_desc = {} job_desc['job'] = JobRun(callback, parameters) job_desc['last_run'] = None job_desc['run...
def job_run(self, callback, parameters=None)
Add a job and run it once immediately. :param function callback: The function to run asynchronously. :param parameters: The parameters to be provided to the callback. :type parameters: list, tuple :return: The job id. :rtype: :py:class:`uuid.UUID`
2.836582
2.718472
1.043448
if not self._thread_running.is_set(): raise RuntimeError('the JobManager is not running') parameters = (parameters or ()) if not isinstance(parameters, (list, tuple)): parameters = (parameters,) job_desc = {} job_desc['job'] = JobRun(callback, parameters) job_desc['last_run'] = None job_desc['run...
def job_add(self, callback, parameters=None, hours=0, minutes=0, seconds=0, tolerate_exceptions=True, expiration=None)
Add a job to the job manager. :param function callback: The function to run asynchronously. :param parameters: The parameters to be provided to the callback. :type parameters: list, tuple :param int hours: Number of hours to sleep between running the callback. :param int minutes: Number of minutes to sleep b...
2.09038
2.058922
1.015279
enabled = 0 for job_desc in self._jobs.values(): if job_desc['enabled']: enabled += 1 return enabled
def job_count_enabled(self)
Return the number of enabled jobs. :return: The number of jobs that are enabled. :rtype: int
3.615466
3.824916
0.945241
job_id = normalize_job_id(job_id) with self._job_lock: job_desc = self._jobs[job_id] job_desc['enabled'] = True
def job_enable(self, job_id)
Enable a job. :param job_id: Job identifier to enable. :type job_id: :py:class:`uuid.UUID`
3.088072
3.885559
0.794756
job_id = normalize_job_id(job_id) with self._job_lock: job_desc = self._jobs[job_id] job_desc['enabled'] = False
def job_disable(self, job_id)
Disable a job. Disabled jobs will not be executed. :param job_id: Job identifier to disable. :type job_id: :py:class:`uuid.UUID`
3.158767
3.929667
0.803826
job_id = normalize_job_id(job_id) self.logger.info('deleting job with id: ' + str(job_id) + ' and callback function: ' + self._jobs[job_id]['callback'].__name__) job_desc = self._jobs[job_id] with self._job_lock: job_desc['enabled'] = False if wait and self.job_is_running(job_id): job_desc['job'].j...
def job_delete(self, job_id, wait=True)
Delete a job. :param job_id: Job identifier to delete. :type job_id: :py:class:`uuid.UUID` :param bool wait: If the job is currently running, wait for it to complete before deleting it.
2.832789
3.22546
0.878259
job_id = normalize_job_id(job_id) job_desc = self._jobs[job_id] return job_desc['enabled']
def job_is_enabled(self, job_id)
Check if a job is enabled. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool
3.4335
4.555286
0.75374
job_id = normalize_job_id(job_id) if job_id not in self._jobs: return False job_desc = self._jobs[job_id] if job_desc['job']: return job_desc['job'].is_alive() return False
def job_is_running(self, job_id)
Check if a job is currently running. False is returned if the job does not exist. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool
2.472313
2.812356
0.87909
try: arg = base64.standard_b64decode(arg) except (binascii.Error, TypeError): raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg))) return arg
def bin_b64_type(arg)
An argparse type representing binary data encoded in base64.
2.676559
2.552828
1.048468
if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I): arg = arg.replace(':', '') elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I): arg = arg.replace('\\x', '') try: arg = binascii.a2b_hex(arg) except (binascii.Error, TypeError): raise argparse.ArgumentTypeError("{0} is invalid hex data".format(repr(arg...
def bin_hex_type(arg)
An argparse type representing binary data encoded in hex.
2.251569
2.117113
1.063509
if not os.path.isdir(arg): raise argparse.ArgumentTypeError("{0} is not a valid directory".format(repr(arg))) return arg
def dir_type(arg)
An argparse type representing a valid directory.
2.441316
2.254424
1.0829
if not is_valid_email_address(arg): raise argparse.ArgumentTypeError("{0} is not a valid email address".format(repr(arg))) return arg
def email_type(arg)
An argparse type representing an email address.
2.650815
2.596853
1.02078
if not arg.upper() in ('NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'): raise argparse.ArgumentTypeError("{0} is not a valid log level".format(repr(arg))) return getattr(logging, arg.upper())
def log_level_type(arg)
An argparse type representing a logging level.
2.466285
2.358889
1.045528
error_msg = "{0} is not a valid port".format(repr(arg)) try: arg = ast.literal_eval(arg) except ValueError: raise argparse.ArgumentTypeError(error_msg) if arg < 0 or arg > 65535: raise argparse.ArgumentTypeError(error_msg) return arg
def port_type(arg)
An argparse type representing a tcp or udp port number.
2.102724
2.009983
1.04614
try: arg = parse_timespan(arg) except ValueError: raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg))) return arg
def timespan_type(arg)
An argparse type representing a timespan such as 6h for 6 hours.
2.8691
2.793429
1.027089
self.log.debug('starting the ``search`` method') # ACCOUNT FOR TYPE OF SEARCH sqlWhere = False magnitudeLimitFilter = self.magnitudeLimitFilter disCols = ["zColName", "distanceColName", "semiMajorColName"] sqlWhere = "" if self.physic...
def search(self)
*trigger the conesearch* **Return:** - ``matchIndies`` -- the indicies of the input transient sources (syncs with ``uniqueMatchDicts``) - ``uniqueMatchDicts`` -- the crossmatch results **Usage:** See class docstring for usage examples .. todo :: ...
4.602901
4.225334
1.089358
self.log.debug('starting the ``_bright_star_match`` method') import decimal decimal.getcontext().prec = 10 # MATCH BRIGHT STAR ASSOCIATIONS brightStarMatches = [] for row in matchedObjects: mag = decimal.Decimal(row[magnitudeLimitFilter]) ...
def _bright_star_match( self, matchedObjects, catalogueName, magnitudeLimitFilter, lowerMagnitudeLimit)
*perform a bright star match on the crossmatch results if required by the catalogue search* **Key Arguments:** - ``matchedObjects`` -- the list of matched sources from the catalogue crossmatch - ``catalogueName`` -- the name of the catalogue the crossmatch results from - ``m...
3.990339
3.519347
1.133829
self.log.debug('starting the ``_galaxy_association_cuts`` method') import decimal decimal.getcontext().prec = 10 # MATCH BRIGHT STAR ASSOCIATIONS galaxyMatches = [] for row in matchedObjects: if not magnitudeLimitFilter or row[magnitudeLimitFilter] ...
def _galaxy_association_cuts( self, matchedObjects, catalogueName, magnitudeLimitFilter, upperMagnitudeLimit, lowerMagnitudeLimit)
*perform a bright star match on the crossmatch results if required by the catalogue search* **Key Arguments:** - ``matchedObjects`` -- the list of matched sources from the catalogue crossmatch - ``catalogueName`` -- the name of the catalogue the crossmatch results from - ``m...
3.712656
3.269439
1.135563
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("8.8.8.8", 80)) except socket.gaierror: ip_ = "127.0.0.1" else: ip_ = sock.getsockname()[0] finally: sock.close() return ip_
def get_own_ip()
Get the host's ip number.
1.608514
1.612993
0.997223
with self._pub_lock: self.publish.send_string(msg) return self
def send(self, msg)
Send the given message.
10.279814
10.033978
1.0245
self.publish.setsockopt(zmq.LINGER, 1) self.publish.close() return self
def stop(self)
Stop the publisher.
7.060263
4.491468
1.571928
if not self._heartbeat: self._heartbeat = _PublisherHeartbeat(self) self._heartbeat(min_interval)
def heartbeat(self, min_interval=0)
Send a heartbeat ... but only if *min_interval* seconds has passed since last beat.
7.389233
6.80028
1.086607
pub_addr = "tcp://*:" + str(self._port) self._publisher = self._publisher_class(pub_addr, self._name) LOGGER.debug("entering publish %s", str(self._publisher.destination)) addr = ("tcp://" + str(get_own_ip()) + ":" + str(self._publisher.port_number)) self...
def start(self)
Start the publisher.
7.146442
6.557852
1.089753
LOGGER.debug("exiting publish") if self._publisher is not None: self._publisher.stop() self._publisher = None if self._broadcaster is not None: self._broadcaster.stop() self._broadcaster = None
def stop(self)
Stop the publisher.
3.386023
2.94602
1.149355
t = np.atleast_1d(t) return CythonSolver().simple_light_curve(self._get_params(), t, texp, tol, maxdepth)
def light_curve(self, t, texp=0.0, tol=1e-8, maxdepth=4)
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
6.097469
10.483358
0.581633
t = np.atleast_1d(t) f, df = CythonSolver().simple_gradient(self._get_params(), t, texp, tol, maxdepth) return f, df
def light_curve_gradient(self, t, texp=0.0, tol=1e-8, maxdepth=4)
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
6.801661
10.588332
0.642373
level = level or logging.WARNING if isinstance(level, str): level = getattr(logging, level, None) if level is None: raise ValueError('invalid log level: ' + level) root_logger = logging.getLogger('') for handler in root_logger.handlers: root_logger.removeHandler(handler) logging.getLogger(logger).setLe...
def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s')
Configure the default stream handler for logging messages to the console, remove other logging handlers, and enable capturing warnings. .. versionadded:: 1.3.0 :param str logger: The logger to add the stream handler for. :param level: The level to set the logger to, will default to WARNING if no level is specifie...
1.775967
1.833157
0.968802
# requirements os, shutil, urllib.parse, urllib.request if not filename: url_parts = urllib.parse.urlparse(url) filename = os.path.basename(url_parts.path) url_h = urllib.request.urlopen(url) with open(filename, 'wb') as file_h: shutil.copyfileobj(url_h, file_h) url_h.close() return
def download(url, filename=None)
Download a file from a url and save it to disk. :param str url: The URL to fetch the file from. :param str filename: The destination file to write the data to.
2.288616
2.570042
0.890498
if not val: return '0 bytes' for sz_name in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']: if val < 1024.0: return "{0:.2f} {1}".format(val, sz_name) val /= 1024.0 raise OverflowError()
def format_bytes_size(val)
Take a number of bytes and convert it to a human readable number. :param int val: The number of bytes to format. :return: The size in a human readable format. :rtype: str
2.144213
2.272909
0.943378
# requirements = re if isinstance(file, str): file = open(file) lines = [] for line in file: if bool(re.search(expression, line, flags=flags)) ^ invert: lines.append(line) return lines
def grep(expression, file, flags=0, invert=False)
Search a file and return a list of all lines that match a regular expression. :param str expression: The regex to search for. :param file: The file to search in. :type file: str, file :param int flags: The regex flags to use when searching. :param bool invert: Select non matching lines instead. :return: All the ...
2.960289
3.052215
0.969882
close_fds = True startupinfo = None proc_args = [] if sys.platform.startswith('win'): proc_args.append(which('cmd.exe')) proc_args.append('/c') proc_args.append('start') uri = uri.replace('&', '^&') close_fds = False startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USE...
def open_uri(uri)
Open a URI in a platform intelligent way. On Windows this will use 'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open depending on which is available. If no suitable application can be found to open the URI, a RuntimeError will be raised. .. versionadded:: 1.3.0 :param str uri: The URI to open.
2.047857
2.012818
1.017408
snake = snake.split('_') first_part = snake[0] if upper_first: first_part = first_part.title() return first_part + ''.join(word.title() for word in snake[1:])
def parse_case_snake_to_camel(snake, upper_first=True)
Convert a string from snake_case to CamelCase. :param str snake: The snake_case string to convert. :param bool upper_first: Whether or not to capitalize the first character of the string. :return: The CamelCase version of string. :rtype: str
2.135255
2.693294
0.792804
server = server.rsplit(':', 1) host = server[0] if host.startswith('[') and host.endswith(']'): host = host[1:-1] if len(server) == 1: return (host, default_port) port = server[1] if not port: port = default_port else: port = int(port) return (host, port)
def parse_server(server, default_port)
Convert a server string to a tuple suitable for passing to connect, for example converting 'www.google.com:443' to ('www.google.com', 443). :param str server: The server string to convert. :param int default_port: The port to use in case one is not specified in the server string. :return: The parsed server infor...
1.799115
2.064997
0.871243
if isinstance(timedef, int): return timedef converter_order = ('w', 'd', 'h', 'm', 's') converters = { 'w': 604800, 'd': 86400, 'h': 3600, 'm': 60, 's': 1 } timedef = timedef.lower() if timedef.isdigit(): return int(timedef) elif len(timedef) == 0: return 0 seconds = -1 for spec in converter_...
def parse_timespan(timedef)
Convert a string timespan definition to seconds, for example converting '1m30s' to 90. If *timedef* is already an int, the value will be returned unmodified. :param timedef: The timespan definition to convert to seconds. :type timedef: int, str :return: The converted value in seconds. :rtype: int
2.014001
2.016981
0.998523
slug = '' maxlen = min(maxlen, len(words)) for c in words: if len(slug) == maxlen: break c = ord(c) if c == 0x27: continue elif c >= 0x30 and c <= 0x39: slug += chr(c) elif c >= 0x41 and c <= 0x5a: slug += chr(c + 0x20) elif c >= 0x61 and c <= 0x7a: slug += chr(c) elif len(slug) and sl...
def parse_to_slug(words, maxlen=24)
Parse a string into a slug format suitable for use in URLs and other character restricted applications. Only utf-8 strings are supported at this time. :param str words: The words to parse. :param int maxlen: The maximum length of the slug. :return: The parsed words as a slug. :rtype: str
1.765133
1.912382
0.923002
# requirements = random, string return ''.join(random.choice(string.ascii_letters + string.digits) for x in range(size))
def random_string_alphanumeric(size)
Generate a random string of *size* length consisting of mixed case letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str
5.004055
5.981369
0.836607
# requirements = random, string return ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(size))
def random_string_lower_numeric(size)
Generate a random string of *size* length consisting of lowercase letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str
5.182741
5.886608
0.880429
# requirments = sys probability = 100.0 poolsize = float(poolsize) for i in range(selections): probability = probability * (poolsize - i) / poolsize probability = (100.0 - probability) return probability
def selection_collision(selections, poolsize)
Calculate the probability that two random values selected from an arbitrary sized pool of unique values will be equal. This is commonly known as the "Birthday Problem". :param int selections: The number of random selections. :param int poolsize: The number of unique random values in the pool to choose from. :rtyp...
5.491433
5.921056
0.927442
if key is None: key = lambda x: x preserved_type = type(seq) if preserved_type not in (list, tuple): raise TypeError("unique argument 1 must be list or tuple, not {0}".format(preserved_type.__name__)) seen = [] result = [] for item in seq: marker = key(item) if marker in seen: continue seen.append(...
def unique(seq, key=None)
Create a unique list or tuple from a provided list or tuple and preserve the order. :param seq: The list or tuple to preserve unique items from. :type seq: list, tuple :param key: If key is provided it will be called during the comparison process. :type key: function, None
2.062981
2.301133
0.896507
# requirements = random weights = [] # get weight values for each of the choices for choice in choices: choice_weight = weight(choice) if not (isinstance(choice_weight, int) and choice_weight > 0): raise TypeError('weight results must be positive integers') weights.append(choice_weight) # make a select...
def weighted_choice(choices, weight)
Make a random selection from the specified choices. Apply the *weight* function to each to return a positive integer representing shares of selection pool the choice should received. The *weight* function is passed a single argument of the choice from the *choices* iterable. :param choices: The choices to select f...
3.469421
3.453122
1.00472
if stop is None: stop = start start = 0.0 start = float(start) while start < stop: yield start start += step
def xfrange(start, stop=None, step=1)
Iterate through an arithmetic progression. :param start: Starting number. :type start: float, int, long :param stop: Stopping number. :type stop: float, int, long :param step: Stepping size. :type step: float, int, long
2.386068
2.543583
0.938073
now = time.time() keys_for_removal = collections.deque() for key, (_, expiration) in self.__cache.items(): if expiration < now: keys_for_removal.append(key) for key in keys_for_removal: del self.__cache[key]
def cache_clean(self)
Remove expired items from the cache.
2.501323
2.290859
1.091871
self.config_parser.set(self.section_name, option, value)
def set(self, option, value)
Set an option to an arbitrary value. :param str option: The name of the option to set. :param value: The value to set the option to.
3.924736
6.348238
0.61824
final_message = message.format(*format_args, **format_kwds) final_message = "{} -- {}: {}".format( final_message, type(err).__name__, str(err), ) final_message = cls.sanitize_errstr(final_message) return final_message
def reformat_exception(cls, message, err, *format_args, **format_kwds)
Reformats an exception by adding a message to it and reporting the original exception name and message
3.375593
3.509295
0.961901
try: yield except exception_class as err: try: final_message = cls.reformat_exception( message, err, *format_args, **format_kwds ) except Exception as msg_err: raise cls( ...
def handle_errors( cls, message, *format_args, re_raise=True, exception_class=Exception, do_finally=None, do_except=None, do_else=None, **format_kwds )
provides a context manager that will intercept exceptions and repackage them as Buzz instances with a message attached: .. code-block:: python with Buzz.handle_errors("It didn't work"): some_code_that_might_raise_an_exception() :param: message: The message to attach...
2.564571
2.811106
0.9123
if not expr: raise cls(message, *format_args, **format_kwds)
def require_condition(cls, expr, message, *format_args, **format_kwds)
used to assert a certain state. If the expression renders a false value, an exception will be raised with the supplied message :param: message: The failure message to attach to the raised Buzz :param: expr: A boolean value indicating an evaluated expression :param: format_arg...
3.019491
5.137599
0.587724
user = super(AccountActivationManager, self).create_user(username, email, password) if isinstance(user.username, str): username = user.username.encode('utf-8') salt, activation_key = generate_sha1(username) user.is_active = active user.activation_key = acti...
def create_user(self, username, email, password, active=False, send_email=True)
A simple wrapper that creates a new :class:`User`. :param username: String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. ...
3.291503
3.785295
0.86955
if SHA1_RE.search(activation_key): try: user = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False if not user.activation_key_expired(): user.activation_key = defaults.ACCOUNTS_ACTIVATED...
def activate_user(self, username, activation_key)
Activate an :class:`User` by supplying a valid ``activation_key``. If the key is valid and an user is found, activates the user and return it. Also sends the ``activation_complete`` signal. :param activation_key: String containing the secret SHA1 for a valid activation. :r...
3.538172
3.442955
1.027655
deleted_users = [] for user in self.filter(is_staff=False, is_active=False): if user.activation_key_expired(): deleted_users.append(user) user.delete() return deleted_users
def delete_expired_users(self)
Checks for expired users and delete's the ``User`` associated with it. Skips if the user ``is_staff``. :return: A list containing the deleted users.
3.308837
3.214337
1.0294
if SHA1_RE.search(confirmation_key): try: user = self.select_related().get(username=username, email_confirmation_key=confirmation_key, email_unconfirmed__isnull=False) except self.model.DoesN...
def confirm_email(self, username, confirmation_key)
Confirm an email address by checking a ``confirmation_key``. A valid ``confirmation_key`` will set the newly wanted email address as the current email address. Returns the user after success or ``False`` when the confirmation key is invalid. :param confirmation_key: String ...
3.41298
3.574891
0.954709
profiles = self.select_related().all() filter_kwargs = {'is_active': True} profiles = profiles.filter(**filter_kwargs) if user and isinstance(user, AnonymousUser): profiles = [] return profiles
def get_visible_profiles(self, user=None)
Returns all the visible profiles available to this user. For now keeps it simple by just applying the cases when a user is not active, a user has it's profile closed to everyone or a user only allows registered users to view their profile. :param user: A Django :class:`User...
4.72689
5.654695
0.835923
parentClsNode = node.parent.parent assert parentClsNode.attributes['objtype'] == 'class' assert parentClsNode.attributes['domain'] == 'py' sign = node.parent.parent.children[0] assert isinstance(sign, desc_signature) absolute_name = sign.attributes['ids'][0] ...
def visit_html(self, node)
Generate html elements and schematic json
5.257319
5.192738
1.012437
has_npm = npm_installation_check() if has_npm: run_npm_install() else: print("Warning: npm not installed using prebuilded js files!", file=sys.stderr) for js in JS_FILES: downloaded_js_name = os.path.join(TOP_DIR, js) ...
def run(self)
Download npm packages required by package.json and extract required files from them
5.166371
4.812751
1.073476
r = self.radius * _Rsun m = self.mass * _Msun return 0.75 * m / (np.pi * r * r * r)
def density(self)
Stellar density in CGS units
6.473836
4.968331
1.30302
self._check_ps() rstar = self.system.central.radius k = self.r/rstar dur = self.period / np.pi arg = rstar/self.a * np.sqrt((1+k)**2 - self.b**2) arg /= np.sin(np.radians(self.incl)) dur *= np.arcsin(arg) if self.e > 0.0: dur *= np.sq...
def duration(self)
The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010).
5.714556
5.021198
1.138086
body.system = self self.bodies.append(body) self.unfrozen = np.concatenate(( self.unfrozen[:-2], np.zeros(7, dtype=bool), self.unfrozen[-2:] ))
def add_body(self, body)
Add a :class:`Body` to the system. This function also sets the ``system`` attribute of the body. :param body: The :class:`Body` to add.
6.466759
6.383208
1.013089
t = np.atleast_1d(t) if len(self.bodies) == 0: return self.central.flux + np.zeros_like(t) return CythonSolver().kepler_light_curve(len(self.bodies), self._get_params(), t, tex...
def light_curve(self, t, texp=0.0, tol=1e-8, maxdepth=4, use_batman=False)
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
4.473235
5.791965
0.772317
t = np.atleast_1d(t) if len(self.bodies) == 0: grad = np.zeros((len(t), 5), dtype=float) grad[:, 0] = 1.0 return self.central.flux + np.zeros_like(t), grad[:, self.unfrozen] f, df = CythonSolver().kepler_gradient(len(self.bodies), ...
def light_curve_gradient(self, t, texp=0.0, tol=1e-8, maxdepth=4)
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
5.483809
6.576817
0.833809
# see: # https://packaging.python.org/tutorials/distributing-packages/#uploading-your-project-to-pypi twine_repo = os.getenv('TWINE_REPOSITORY_URL') or os.getenv('TWINE_REPOSITORY') print('tagging and releasing to %s as %s' % ( twine_repo, os.getenv('TWINE_USERNAME') )) if ...
def main()
Tags the current repository and commits changes to news files
2.609201
2.59772
1.00442
pid = os.getpid() if pid not in context: context[pid] = zmq.Context() logger.debug('renewed context for PID %d', pid) return context[pid]
def get_context()
Provide the context to use. This function takes care of creating new contexts in case of forks.
4.594457
4.645615
0.988988
if isinstance(strg, datetime): return strg if len(strg) < 19 or len(strg) > 26: if len(strg) > 30: strg = strg[:30] + '...' raise ValueError("Invalid ISO formatted time string '%s'"%strg) if strg.find(".") == -1: strg += '.000000' if sys.version[0:3] >= '...
def strp_isoformat(strg)
Decode an ISO formatted string to a datetime object. Allow a time-string without microseconds. We handle input like: 2011-11-14T12:51:25.123456
2.243519
2.27242
0.987282
analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: print(click.style('analysis log not found', fg='red')) context.abort() print(click.style(f"{analysis_obj.family}: {analysis_obj.status}")) if analysis_obj.is_temp: if yes or click.confirm(f"...
def delete(context, force, yes, analysis_id)
Delete an analysis log from the database.
2.319506
2.309306
1.004417
self.log.debug('starting the ``add_data_to_database_table`` method') if len(dictList) == 0: return myPid = self.myPid dbTableName = self.dbTableName if createStatement: writequery( log=self.log, sqlQuery=createSt...
def add_data_to_database_table( self, dictList, createStatement=False)
*Import data in the list of dictionaries in the requested database table* Also adds HTMIDs and updates the sherlock-catalogue database helper table with the time-stamp of when the imported catlogue was last updated **Key Arguments:** - ``dictList`` - a list of dictionaries containing all t...
5.499814
4.77663
1.1514
self.log.debug('starting the ``add_htmids_to_database_table`` method') tableName = self.dbTableName self.log.info("Adding HTMIds to %(tableName)s" % locals()) add_htm_ids_to_mysql_database_table( raColName=self.raColName, declColName=self.declColName, ...
def _add_htmids_to_database_table( self)
*Add HTMIDs to database table once all the data has been imported (HTM Levels 10,13,16)* **Usage:** .. code-block:: python self._add_htmids_to_database_table()
3.531204
3.829346
0.922143
self.log.debug('starting the ``_update_database_helper_table`` method') tableName = self.dbTableName sqlQuery = u % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, ) self.log.debug( ...
def _update_database_helper_table( self)
*Update the sherlock catalogues database helper table with the time-stamp of when this catlogue was last updated* **Usage:** .. code-block:: python self._update_database_helper_table()
6.140018
5.687709
1.079524
for resource in self.items_mapped['Entry'].values(): for dct in [getattr(resource, '_cf_cda', {}), resource.fields]: for k, v in dct.items(): if isinstance(v, ResourceLink): resolved = self._resolve_resource_link(v) ...
def resolve_links(self)
Attempt to resolve all internal links (locally). In case the linked resources are found either as members of the array or within the `includes` element, those will be replaced and reference the actual resources. No network calls will be performed.
4.77827
4.761966
1.003424
UserModel = get_user_model() try: validators.validate_email(identification) try: user = UserModel.objects.get(email__iexact=identification) except UserModel.DoesNotExist: return None except: validators.Val...
def authenticate(self, request, identification, password=None, check_password=True)
Authenticates a user through the combination email/username with password. :param identification: A string containing the username or email of the user that is trying to authenticate. :password: Optional string containing the password for the user. ...
2.251027
2.516216
0.894608