code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not self.app.config['DOCKER_URL']: raise RuntimeError('"DOCKER_URL" must be specified') if not self.app.extensions['docker.client']: self.app.extensions['docker.client'] = Client( base_url=self.app.config['DOCKER_URL'], version=self.ap...
def client(self)
The original :class:`docker.Client` object. All docker operation calling will be forwarded here. :: docker.create_container('ubuntu') docker.client.create_container('ubuntu') # equivalent
2.52293
2.480966
1.016914
self._feed_domains.add(utils.get_domain(url)) if url in self._processed_feeds: LOGGER.debug("Skipping already processed feed %s", url) return self._processed_feeds.add(url) LOGGER.debug("++WAIT: %s: get feed", url) feed, previous, updated = awa...
async def process_feed(self, url, send_mentions=True)
process a feed
3.311785
3.260415
1.015756
if add_domain: self._feed_domains.add(utils.get_domain(url)) if url in self._processed_entries: LOGGER.debug("Skipping already processed entry %s", url) return self._processed_entries.add(url) LOGGER.debug("++WAIT: get entry %s", url) ...
async def process_entry(self, url, add_domain=False, send_mentions=True)
process an entry
3.374196
3.315646
1.017659
if (entry.url, url) in self._processed_mentions: LOGGER.debug( "Skipping already processed mention %s -> %s", entry.url, url) self._processed_mentions.add((entry.url, url)) LOGGER.debug("++WAIT: webmentions.get_target %s", url) target = await webmen...
async def send_webmention(self, entry, url)
send a webmention from an entry to a URL
2.801966
2.651985
1.056554
from django.core.management import call_command with work_in(application): if DJANGO_1_11: call_command('compilemessages', all=True) else: call_command('compilemessages')
def compilemessages(application)
Compiles locale messages
3.743786
3.742939
1.000226
from django.core.management import call_command if not locale: locale = 'en' with work_in(application): call_command('makemessages', locale=(locale,))
def makemessages(application, locale)
Updates the locale message files
4.825841
4.82999
0.999141
from django.core.management import call_command try: import cms # NOQA # nopyflakes _create_db(migrate_cmd) call_command('cms', 'check') except ImportError: print('cms_check available only if django CMS is installed')
def cms_check(migrate_cmd=False)
Runs the django CMS ``cms check`` command
6.064313
5.385869
1.125967
from django.core.management import call_command apps = [application] if extra_applications: if isinstance(extra_applications, text_type): apps += [extra_applications] elif isinstance(extra_applications, list): apps += extra_applications for app in apps: ...
def makemigrations(application, merge=False, dry_run=False, empty=False, extra_applications=None)
Generate migrations
2.132719
2.107767
1.011838
print('Generating AUTHORS') # Get our list of authors print('Collecting author names') r = subprocess.Popen(['git', 'log', '--use-mailmap', '--format=%aN'], stdout=subprocess.PIPE) seen_authors = [] authors = [] for authfile in ('AUTHORS', 'AUTHORS.rst'): ...
def generate_authors()
Updates the authors list
2.909304
2.884457
1.008614
try: from cms.test_utils.util.static_analysis import pyflakes application_module = __import__(application) report = pyflakes((application_module,)) if type(report) == tuple: assert report[0] == 0 else: assert report == 0 except ImportError: ...
def static_analisys(application)
Performs a pyflakes static analysis with the same configuration as django CMS testsuite
5.268741
4.420968
1.191762
self.inputstring = inputstring self.document = document
def setup_parse(self, inputstring, document)
Initial parse setup. Call at start of `self.parse()`.
3.624982
2.783976
1.302088
with open(os.path.join(root_folder, 'VERSION'), 'r') as version_file: version = version_file.read().strip() if version != expected_version: raise EnvironmentError("Version mismatch during release, expected={}, found={}" .format(expected_version, version))
def check_version(expected_version)
Make sure the package version in setuptools matches what we expect it to be
3.091415
2.873964
1.075662
if platform in ['x86_64', 'i686']: system = 'manylinux1' else: system = 'linux' setuptools.sandbox.run_setup( 'setup.py', ['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)] )
def build_wheel(platform)
Create a wheel
3.679461
3.791194
0.970528
if 'PYPI_USER' in os.environ and 'PYPI_PASS' in os.environ: pypi_user = os.environ['PYPI_USER'] pypi_pass = os.environ['PYPI_PASS'] else: pypi_user = None pypi_pass = None print("No PYPI user information in environment") packages = glob.glob(dist_dir) # In...
def upload(dist_dir)
Upload a given component to pypi The pypi username and password must either be specified in a ~/.pypirc file or in environment variables PYPI_USER and PYPI_PASS
4.109238
3.923774
1.047267
parser = argparse.ArgumentParser( prog="Simple command-line function toolkit.", description=, ) parser.add_argument("-f", "--func_name", default="main") parser.add_argument("-a", "--args", dest="args", nargs="*") parser.add_argument("-k", "--kwargs", dest="kwargs") parser.ad...
def simple_cmd()
``Deprecated``: Not better than ``fire`` -> pip install fire
2.936388
2.875697
1.021105
try: import psutil B = float(psutil.Process(os.getpid()).memory_info().vms) KB = B / 1024 MB = KB / 1024 GB = MB / 1024 result = vars()[unit] print_info("memory usage: %.2f(%s)" % (result, unit)) return result except ImportError: prin...
def print_mem(unit="MB")
Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB.
3.446577
3.193972
1.079088
length = len(seq) if length % n == 0: size = length // n else: size = length // n + 1 for it in slice_by_size(seq, size): yield it
def slice_into_pieces(seq, n)
Slice a sequence into `n` pieces, return a generation of n pieces
3.30282
3.229022
1.022855
filling = null for it in zip(*(itertools_chain(seq, [filling] * size),) * size): if filling in it: it = tuple(i for i in it if i is not filling) if it: yield it
def slice_by_size(seq, size)
Slice a sequence into chunks, return as a generation of chunks with `size`.
7.065284
7.053395
1.001686
tzone = Config.TIMEZONE if tzone is None else tzone fix_tz = tzone * 3600 if timestamp is None: timestamp = time.time() else: timestamp = float(timestamp) if 1e12 <= timestamp < 1e13: # Compatible timestamp with 13-digit milliseconds timestamp = times...
def ttime(timestamp=None, tzone=None, fail="", fmt="%Y-%m-%d %H:%M:%S")
Translate timestamp into human-readable: %Y-%m-%d %H:%M:%S. :param timestamp: the timestamp float, or `time.time()` by default. :param tzone: time compensation, int(-time.timezone / 3600) by default, (can be set with Config.TIMEZONE). :param fail: while raising an exception, return it. ...
3.217977
3.39236
0.948595
tzone = Config.TIMEZONE if tzone is None else tzone fix_tz = -(tzone * 3600 + time.timezone) #: str(timestr) for datetime.datetime object timestr = str(timestr or ttime()) try: return int(time.mktime(time.strptime(timestr, fmt)) + fix_tz) except: return fail
def ptime(timestr=None, tzone=None, fail=0, fmt="%Y-%m-%d %H:%M:%S")
Translate %Y-%m-%d %H:%M:%S into timestamp. :param timestr: string like 2018-03-15 01:27:56, or time.time() if not set. :param tzone: time compensation, int(-time.timezone / 3600) by default, (can be set with Config.TIMEZONE). :param fail: while raising an exception, return it. :param f...
4.960708
4.853693
1.022048
ms = seconds * 1000 divisors = (1, 24, 60, 60, 1000) quotient, result = ms, [] for divisor in divisors[::-1]: quotient, remainder = divmod(quotient, divisor) result.append(quotient) if divisor == 1 else result.append(remainder) return result[::-1]
def split_seconds(seconds)
Split seconds into [day, hour, minute, second, ms] `divisor: 1, 24, 60, 60, 1000` `units: day, hour, minute, second, ms` >>> split_seconds(6666666) [77, 3, 51, 6, 0]
2.869325
3.071954
0.934039
assert format in [0, 1, 2], ValueError("format arg should be one of 0, 1, 2") negative = "-" if seconds < 0 else "" seconds = abs(seconds) if lang == "en": units = ("day", "hour", "minute", "second", "ms") elif lang == "cn": units = (u"天", u"小时", u"分钟", u"秒", u"毫秒") times = ...
def timeago(seconds=0, accuracy=4, format=0, lang="en")
Translate seconds into human-readable. :param seconds: seconds (float/int). :param accuracy: 4 by default (units[:accuracy]), determine the length of elements. :param format: index of [led, literal, dict]. :param lang: en or cn. :param units: day, hour, minute, second, ms. ...
2.896988
2.848424
1.01705
todo = string if skip_encode else unicode(string).encode(encoding) if n == 32: return hashlib.md5(todo).hexdigest() elif isinstance(n, (int, float)): return hashlib.md5(todo).hexdigest()[(32 - n) // 2 : (n - 32) // 2] elif isinstance(n, (tuple, list)): return hashlib.md5(tod...
def md5(string, n=32, encoding="utf-8", skip_encode=False)
str(obj) -> md5_string :param string: string to operate. :param n: md5_str length. >>> from torequests.utils import md5 >>> md5(1, 10) '923820dcc5' >>> md5('test') '098f6bcd4621d373cade4e832627b4f6'
2.333589
2.946287
0.792044
seen = set() add = seen.add if key: generator = (x for x in seq if key(x) not in seen and not add(key(x))) else: generator = (x for x in seq if x not in seen and not add(x)) if return_as: if return_as == str: return "".join(map(str, generator)) else: ...
def unique(seq, key=None, return_as=None)
Unique the seq and keep the order. Instead of the slow way: `lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)` :param seq: raw sequence. :param return_as: generator for default, or list / set / str... >>> from torequests.utils import unique >>> a = [1,2,3,4,2,3,4] ...
2.367411
2.905168
0.814896
result = [] items = qs.items() if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) for value in values: result.append(query_name + "=" + quote(value)) return "&".join(result)
def unparse_qs(qs, sort=False, reverse=False)
Reverse conversion for parse_qs
2.377648
2.322671
1.02367
result = [] items = qsl if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) result.append(query_name + "=" + quote(values)) return "&".join(result)
def unparse_qsl(qsl, sort=False, reverse=False)
Reverse conversion for parse_qsl
2.683407
2.767388
0.969653
pid = os.getpid() kill = os.kill run_after_async(seconds, kill, pid, signal.SIGTERM) run_after_async(seconds + timeout, kill, pid, 9)
def kill_after(seconds, timeout=2)
Kill self after seconds
5.045978
4.888619
1.032189
try: module = importlib.import_module(module_name) except ImportError: if warn: if warn is True: Config.utils_logger.warning( "Module `%s` not found. Install it to remove this warning" % module_name ) ...
def try_import(module_name, names=None, default=ImportErrorModule, warn=True)
Try import module_name, except ImportError and return default, sometimes to be used for catch ImportError and lazy-import.
2.581477
2.542656
1.015268
if isinstance(request, dict): result = request elif isinstance(request, (unicode, str)): request = request.strip() if request.startswith("http"): result = {"method": "get", "url": request} elif request.startswith("curl "): result = curlparse(request) ...
def ensure_request(request)
Used for requests.request / Requests.request with **ensure_request(request) :param request: dict or curl-string or url >>> from torequests.utils import ensure_request >>> ensure_request('''curl http://test.com''') {'url': 'http://test.com', 'method': 'get'} >>> ensure_request('http://test.com') ...
2.972678
2.945521
1.00922
if not all((isinstance(i, unicode) for i in dict_obj.keys())): return dict_obj return {key.title(): value for key, value in dict_obj.items()}
def ensure_dict_key_title(dict_obj)
Set the dict key as key.title(); keys should be str. Always be used to headers. >>> from torequests.utils import ensure_dict_key_title >>> ensure_dict_key_title({'hello-world':1, 'HELLOWORLD':2}) {'Hello-World': 1, 'Helloworld': 2}
3.130474
3.447871
0.907944
if not nums: return 0 nums = sorted([int(i) for i in nums]) if len(nums) == 1: return nums[0] diffs = [nums[i + 1] - nums[i] for i in range(len(nums) - 1)] diffs = [item for item in diffs if item >= accuracy] sorted_diff = sorted(diffs) result = sorted_diff[len(diffs) //...
def guess_interval(nums, accuracy=0)
Given a seq of number, return the median, only calculate interval >= accuracy. :: from torequests.utils import guess_interval import random seq = [random.randint(1, 100) for i in range(20)] print(guess_interval(seq, 5)) # sorted_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40,...
2.299353
2.196135
1.047
r deep = len(seps) if not deep: return string return [split_n(i, seps[1:]) for i in _re_split_mixin(string, seps[0], reg=reg)]
def split_n(string, seps, reg=False)
r"""Split strings into n-dimensional list. :: from torequests.utils import split_n ss = '''a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6''' print(split_n(ss, ('\n', ' ', ' '))) # [[['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3...
6.597898
6.796754
0.970743
@wraps(func) def wrapper(*args, **kwargs): t = Thread(target=func, args=args, kwargs=kwargs) t.daemon = True t.start() return t return wrapper
def bg(func)
Run a function in background, will not block main thread's exit.(thread.daemon=True) :: from torequests.utils import bg, print_info import time def test1(n): time.sleep(n) print_info(n, 'done') @bg def test2(n): time.sleep(n) ...
1.978512
1.882431
1.051041
def default_tick_callback(s, seconds, *args): flush_print(s, sep="", end=" ") def default_finish_callback(seconds, start_time): flush_print() def cd(seconds, interval): for s in range(seconds, 0, -interval): tick_callback(s, seconds, interval) time.sle...
def countdown( seconds=None, block=True, interval=1, daemon=True, tick_callback=None, finish_callback=None, )
Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by tick_callback. :: from torequests.utils import countdown countdown(3) # 3 2 1 # countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58. countd...
2.855046
2.93982
0.971164
# PY2 raise SyntaxError for : def flush_print(*args, sep='', end=''): sep, end, flush = ( kwargs.pop("sep", " "), kwargs.pop("end", "\n"), kwargs.pop("flush", 1), ) string = sep.join((unicode(i) for i in args)) sys.stdout.write("%s%s" % (string, end)) if flush: ...
def flush_print(*args, **kwargs)
Like print_function at python3, support flush, but not support file. :param sep: space by default :param end: '\\n' by default :param flush: True by default :: import time from torequests.utils import flush_print flush_print("=" * 10) for _ in range(10): t...
4.053049
4.300031
0.942563
req = kwargs.pop('req', tPool()) kwargs.update(curlparse(curl_string)) return req.request(**kwargs)
def curlrequests(curl_string, **kwargs)
Use tPool to request for curl string. If kwargs contains the req which hasattr request method, like req=requests. :param curl_string: standard curl string. :type curl_string: str :param kwargs: valid kwargs for tPool. :type curl_string: dict Basic Usage:: from torequests.utils import ...
9.721045
7.965166
1.220445
assert obj, "bool(obj) should be True." patterns = patterns if isinstance(patterns, (list, tuple, set)) else [patterns] instances = instances or [] instances = ( instances if isinstance(instances, (list, tuple, set)) else [instances] ) for pattern in ...
def register(self, patterns, obj=None, instances=None, **reg_kwargs)
Register one object which can be matched/searched by regex. :param patterns: a list/tuple/set of regex-pattern. :param obj: return it while search/match success. :param instances: instance list will search/match the patterns. :param reg_kwargs: kwargs for re.compile.
4.262789
4.179765
1.019863
def wrapper(function): self.register(patterns, function, instances=instances, **reg_kwargs) return function return wrapper
def register_function(self, patterns, instances=None, **reg_kwargs)
Decorator for register.
3.407533
3.051762
1.116579
return self.match(string) or self.search(string) or default
def find(self, string, default=None)
Return match or search result. :rtype: list
8.66462
5.888148
1.471536
default = default if default else [] result = [item[1] for item in self.container if item[0].search(string)] if self.ensure_mapping: assert len(result) < 2, "%s matches more than one pattern: %s" % ( string, result, ) retur...
def search(self, string, default=None)
Use re.search to find the result :rtype: list
4.915668
5.01471
0.98025
instances = [i[2] for i in self.container if i[2]] if not instances: return instances = sum(instances, []) from fuzzywuzzy import process maybe = process.extract(key, instances, limit=limit) return maybe
def fuzzy(self, key, limit=5)
Give suggestion from all instances.
5.385047
4.626611
1.163929
result = [] for item in self.container: pattern = str(item[0])[10:] if PY3 else item[0].pattern instances = item[2] or [] value = ( '%s "%s"' % (item[1].__name__, (item[1].__doc__ or "")) if callable(item[1]) el...
def show_all(self, as_string=True)
, python2 will not show flags
4.418125
4.274058
1.033707
self._log_after_del = False passed_string = self.string if self.log_func: self.log_func(self) else: print_info( "Timer [%(passed)s]: %(name)s, start at %(start)s." % ( dict( name=...
def x(self)
Call self.log_func(self) and return expect_string.
6.620348
5.351336
1.237139
string = self.passed if self.rounding: string = round(string) if self.readable: string = self.readable(string) return string
def tick(self)
Return the time cost string as expect.
8.069684
6.870146
1.174601
def wrapper(function): @wraps(function) def inner(*args, **kwargs): args1 = ", ".join(map(repr, args)) if args else "" kwargs1 = ", ".join( ["%s=%s" % (i, repr(kwargs[i])) for i in sorted(kwargs.keys())] ) ...
def watch(*timer_args, **timer_kwargs)
Decorator for Timer.
2.337402
2.22766
1.049263
text = text.replace("\r\n", "\n") text = "%s\n" % text flush_print(text, sep="", end="") return text
def default_callback(self, text)
Default clean the \\n in text.
6.924905
5.982774
1.157474
start_time = time.time() count = 0 while not timeout or time.time() - start_time < timeout: new = self.read() if new != self.temp: count += 1 self.callback(new) if count == limit: break ...
def watch(self, limit=None, timeout=None)
Block method to watch the clipboard changing.
3.077347
2.722928
1.130161
return self.watch(limit=limit, timeout=timeout)
def watch_async(self, limit=None, timeout=None)
Non-block method to watch the clipboard changing.
5.976501
5.155801
1.15918
item = re.search(pattern, string, flags=flags) return cls(item)
def find_one(cls, pattern, string, flags=0)
JS-like match object. Use index number to get groups, if not match or no group, will return ''. Basic Usage:: >>> from torequests.utils import find_one >>> string = "abcd" >>> find_one("a.*", string) <torequests.utils.RegMatch object at 0x0705F1D0> >...
4.569196
10.680561
0.427805
'''create a Github issue, given a title, body, repo, and token. Parameters ========== title: the issue title body: the issue body repo: the full name of the repo token: the user's personal Github token ''' owner, name = repo.split('/') url = 'https://api.githu...
def create_issue(title, body, repo, token)
create a Github issue, given a title, body, repo, and token. Parameters ========== title: the issue title body: the issue body repo: the full name of the repo token: the user's personal Github token
2.557933
2.115732
1.209006
previous = config.cache.get( 'target', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=headers) if not request or not request.success: return previous if reque...
async def get_target(config, url)
Given a URL, get the webmention endpoint
5.874529
5.595137
1.049935
if self.endpoint: LOGGER.debug("%s -> %s", entry.url, self.url) try: await self.endpoint.send(config, entry.url, self.url) except Exception as err: # pylint:disable=broad-except LOGGER.warning("Ping %s: got %s: %s", ...
async def send(self, config, entry)
Send a webmention to this target from the specified entry
3.853565
3.548092
1.086095
''' get the correct helper depending on the environment variable HELPME_CLIENT quiet: if True, suppress most output about the client (e.g. speak) ''' # Second priority, from environment from helpme.defaults import HELPME_CLIENT # First priority, from command line if name ...
def get_helper(name=None, quiet=True, **kwargs)
get the correct helper depending on the environment variable HELPME_CLIENT quiet: if True, suppress most output about the client (e.g. speak)
6.962862
4.107187
1.695287
mocked_bable = MockBaBLE() mocked_bable.set_controllers([ Controller(0, '11:22:33:44:55:66', '#0'), Controller(1, '22:33:44:55:66:11', '#1', settings={'powered': True, 'low_energy': True}), Controller(2, '33:44:55:66:11:22', '#2', settings={'powered': True}) ]) monkeypatch....
def mock_bable(monkeypatch)
Mock the BaBLEInterface class with some controllers inside.
2.950106
2.521363
1.170044
self.output = PyStratumStyle(self.input, self.output) command = self.get_application().find('constants') ret = command.execute(self.input, self.output) if ret: return ret command = self.get_application().find('loader') ret = command.execute(self.inp...
def handle(self)
Executes the actual Stratum program.
3.990765
3.475861
1.148137
from imp import load_module, PY_SOURCE imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module('mod', openfile, module_path, ('imported', 'r', PY_SOURCE)) return imported
def load_from_file(module_path)
Load a python module from its absolute filesystem path Borrowed from django-cms
5.110981
5.265715
0.970615
curdir = os.getcwd() try: if dirname is not None: if dirname not in sys.path: sys.path.insert(0, dirname) os.chdir(dirname) yield finally: os.chdir(curdir)
def work_in(dirname=None)
Context manager version of os.chdir. When exited, returns to the working directory prior to entering. Grabbed from cookiecutter, thanks audreyr!
2.233206
2.250162
0.992465
if settings._wrapped != empty: clear_url_caches() from django.apps import apps apps.clear_cache() settings._wrapped = empty clear_url_caches()
def _reset_django(settings)
Hackish way to reset the django instance settings and AppConfig :param settings: django settings module
5.974632
6.099305
0.979559
unicoded_args = [] for argument in args_list: argument = (six.u(argument) if not isinstance(argument, six.text_type) else argument) if argument not in unicoded_args or argument == application: unicoded_args.append(argument) return unicoded_args
def ensure_unicoded_and_unique(args_list, application)
Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order.
2.741846
2.779477
0.986461
if islink(path): unlink(path) elif os.path.isdir(path): for sub in os.listdir(path): sub = os.path.join(path, sub) if os.path.isfile(sub): if not os.access(sub, os.W_OK): # Is the error an access error? os.chmod...
def rmtree(path)
shutil.rmtree() but also handle junction points and access errors on Windows.
2.515221
2.469034
1.018706
if platform.system() == "Windows": if sys.version_info[:2] < (3, 5): try: # pylint: disable=undefined-variable attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(path)) # noqa assert attrs != -1 return bool(attrs & FILE...
def islink(path)
os.path.islink() but return True for junction points on Windows.
2.31882
2.270529
1.021269
if islink(link) and platform.system() == "Windows" and sys.version_info[:2] < (3, 5): # deleting junction points was added to os.unlink in 3.5 # https://bugs.python.org/issue18314 subprocess.check_call(["rmdir", link], shell=True) else: os.unlink(link)
def unlink(link)
os.unlink() but handle junction points on Windows.
4.151371
3.628847
1.143992
if islink(link): unlink(link) if platform.system() == "Windows": if sys.version_info[:2] < (3, 5): with open(os.devnull, "w") as nul: subprocess.check_call(["mklink", "/J", link, target], shell=True, stdout=nul) else: _winapi.CreateJunction(ta...
def symlink(target, link)
os.symlink() but use a junction point on Windows.
2.545513
2.414644
1.054198
write_flag = True if os.path.exists(filename): with open(filename, 'r') as file: old_data = file.read() if data == old_data: write_flag = False if write_flag: tmp_filename = filename + '.tmp' with o...
def write_two_phases(filename, data, io)
Writes a file in two phase to the filesystem. First write the data to a temporary file (in the same directory) and than renames the temporary file. If the file already exists and its content is equal to the data that must be written no action is taken. This has the following advantages: ...
2.320143
2.461154
0.942706
previous = config.cache.get( 'entry', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=headers) if not request or not request.success: LOGGER.error("Could no...
async def get_entry(config, url)
Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated)
5.472985
5.176909
1.057192
rels = attrs.get('rel', [None]) if rel_blacklist: # Never return True for a link whose rel appears in the blacklist for rel in rels: if rel in rel_blacklist: return False if rel_whitelist: # If there is a whiteli...
def _check_rel(attrs, rel_whitelist, rel_blacklist)
Check a link's relations against the whitelist or blacklist. First, this will reject based on blacklist. Next, if there is a whitelist, there must be at least one rel that matches. To explicitly allow links without a rel you can add None to the whitelist (e.g. ['in-reply-to',None])
3.543054
3.077652
1.15122
target = utils.get_domain(href) if not target: return False origin = utils.get_domain(self.url) return target != origin
def _domain_differs(self, href)
Check that a link is not on the same domain as the source URL
4.327761
3.973577
1.089135
return {urllib.parse.urljoin(self.url, attrs['href']) for attrs in self._targets if self._check_rel(attrs, config.rel_whitelist, config.rel_blacklist) and self._domain_differs(attrs['href'])}
def get_targets(self, config)
Given an Entry object, return all of the outgoing links.
7.706666
6.258928
1.231308
self.output = PyStratumStyle(self.input, self.output) config_file = self.argument('config_file') sources = self.argument('file_names') status = self.run_command(config_file, sources) return status
def handle(self)
Executes loader command.
10.330213
9.594691
1.076659
config = configparser.ConfigParser() config.read(config_file) rdbms = config.get('database', 'rdbms').lower() loader = self.create_routine_loader(rdbms) status = loader.main(config_file, sources) return status
def run_command(self, config_file, sources)
:param str config_file: The name of config file. :param list sources: The list with source files.
4.804789
5.34322
0.899231
# Note: We load modules and classes dynamically such that on the end user's system only the required modules # and other dependencies for the targeted RDBMS must be installed (and required modules and other # dependencies for the other RDBMSs are not required). if r...
def create_routine_loader(self, rdbms)
Factory for creating a Routine Loader objects (i.e. objects for loading stored routines into a RDBMS instance from (pseudo) SQL files. :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystratum.RoutineLoader.RoutineLoader
4.134525
3.6635
1.128572
info = { 'id': next(self._id_it), 'name': preset_name, 'ip': ['127.0.0.1'], 'created': 0, 'state': VmState.RUNNING, 'flavor': flavor, 'image': image, 'metadata': {'test-meta': 'abctest'}, 'timed_...
async def create_vm(self, *, preset_name, image, flavor, security_groups=None, userdata=None, key_name=None, availability_zone=None, subnet=None)
Dummy create_vm func.
4.161971
4.111891
1.012179
return list(vm for vm in self._vms.values() if vm.name == preset_name)
async def list_vms(self, preset_name)
Dummy list_vms func
4.888752
3.918924
1.247473
if vm_id not in self._vms: raise DummyIaasVmNotFound() del self._vms[vm_id] return None
async def terminate_vm(self, vm_id)
Dummy terminate_vm func
7.808385
5.953791
1.311498
if vm_id not in self._vms: raise DummyIaasVmNotFound() return self._vms[vm_id]
async def get_vm(self, vm_id)
Dummy get_vm func
7.490406
5.34037
1.402601
import os.path import re if not isinstance(exists, bool): exists = os.path.exists(file_path) if exists: file_path, file_extension = os.path.splitext(file_path) # print(file_path) m = re.search(r"_\d+$", file_path) if m is None: # cislo = 2 ...
def suggest_filename(file_path, exists=None)
Try if exist path and append number to its end. For debug you can set as input if file exists or not.
3.245
3.126577
1.037876
''' Read object from file ''' if filetype == 'auto': _, ext = os.path.splitext(filename) filetype = ext[1:] if filetype in ('yaml', 'yml'): from ruamel.yaml import YAML yaml = YAML(typ="unsafe") with open(filename, encoding="utf-8") as f: obj = yaml.load...
def obj_from_file(filename='annotation.yaml', filetype='auto')
Read object from file
2.471049
2.538059
0.973598
fcontent = None try: import gzip f = gzip.open(filename, 'rb') fcontent = f.read() f.close() except IOError as e: # if the problem is in not gzip file logger.info("Input gzip exception: " + str(e)) f = open(filename, 'rb') fcontent = f.rea...
def read_pkl_and_pklz(filename)
Try read zipped or not zipped pickle file
3.003411
2.880526
1.042661
'''Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray ''' # import json # with open(filename, mode='w') as f: # json.dump(annotatio...
def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True)
Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray
2.44732
2.144789
1.141054
# @TODO remove old code in except part try: # rint 'pred vyjimkou' # aise Exception ('test without skimage') # rint 'za vyjimkou' import skimage import skimage.transform # Now we need reshape seeds and segmentation to original size segm_orig_scale = skimag...
def resize_to_shape(data, shape, zoom=None, mode='nearest', order=0)
Function resize input data to specific shape. :param data: input 3d array-like data :param shape: shape of output data :param zoom: zoom is used for back compatibility :mode: default is 'nearest'
4.709735
4.722138
0.997374
import scipy import scipy.ndimage if np.all(list(new_voxelsize_mm) == 'orig'): new_voxelsize_mm = np.array(voxelsize_mm) elif np.all(list(new_voxelsize_mm) == 'orig*2'): new_voxelsize_mm = np.array(voxelsize_mm) * 2 elif np.all(list(new_voxelsize_mm) == 'orig*4'): new_v...
def resize_to_mm(data3d, voxelsize_mm, new_voxelsize_mm, mode='nearest')
Function can resize data3d or segmentation to specifed voxelsize_mm :new_voxelsize_mm: requested voxelsize. List of 3 numbers, also can be a string 'orig', 'orgi*2' and 'orgi*4'. :voxelsize_mm: size of voxel :mode: default is 'nearest'
2.312121
2.152775
1.074019
type_info = np.iinfo(dtype) if mx <= type_info.max and mn >= type_info.min: return True else: return False
def suits_with_dtype(mn, mx, dtype)
Check whether range of values can be stored into defined data type. :param mn: range minimum :param mx: range maximum :param dtype: :return:
3.03501
3.139506
0.966716
if dtype is None: dtype = data3d.dtype if issubclass(dtype.type, np.integer): mn = data3d.min() * slope + inter mx = data3d.max() * slope + inter if suits_with_dtype(mn, mx, dtype=np.uint8): dtype = np.uint8 elif suits_with_dtype(...
def use_economic_dtype(data3d, slope=1, inter=0, dtype=None)
Use more economic integer-like dtype if it is possible. :param data3d: :param dtype: if dtype is not used, the automatic is used :return:
1.833667
1.890814
0.969777
import SimpleITK as sitk rescale_intercept = None if sitk.Version.MajorVersion() > 0: if data3d.dtype == np.int8: rescale_intercept = -2**7 data3d = (data3d - rescale_intercept).astype(np.uint8) elif data3d.dtype == np.int16: # simpleitk is not able ...
def get_sitk_image_from_ndarray(data3d)
Prepare SimpleItk Image object and rescale data to unsigned types. Simple ITK with version higher than 1.0.0 can not write signed int16. This function check the SimpleITK version and use work around with Rescale Intercept and Rescale Slope :param data3d: :return:
2.436975
2.386138
1.021305
if hasattr(dcmdata, "RescaleSlope") and hasattr(dcmdata, "RescaleIntercept"): rescale_slope = dcmdata.RescaleSlope rescale_intercept = dcmdata.RescaleIntercept slope, inter = get_slope_and_intercept_from_strings(rescale_slope, rescale_intercept) else: slope = 1 inte...
def get_slope_and_intercept_from_pdcm(dcmdata)
Get scale and intercept from pydicom file object. :param dcmdata: :return:
1.916861
2.120007
0.904177
if n < chunks: raise ChunkingError("Number of chunks is greater than number") if n % chunks == 0: # Either we can evenly split or only 1 chunk left return [n / chunks] * chunks # otherwise the current chunk should be a bit larger max_size = n / chunks + 1 return [max_siz...
def split_evenly(n, chunks)
Split an integer into evenly distributed list >>> split_evenly(7, 3) [3, 2, 2] >>> split_evenly(12, 3) [4, 4, 4] >>> split_evenly(35, 10) [4, 4, 4, 4, 4, 3, 3, 3, 3, 3] >>> split_evenly(1, 2) Traceback (most recent call last): ... ChunkingError: Number of chunks is greate...
4.648038
4.310299
1.078356
'''ensure that variable envar is set to some value, otherwise exit on error. Parameters ========== envar: the environment variable name value: the setting that shouldn't be None ''' if value is None: bot.error('You must...
def check_env(self, envar, value)
ensure that variable envar is set to some value, otherwise exit on error. Parameters ========== envar: the environment variable name value: the setting that shouldn't be None
11.66761
4.922362
2.370328
'''the discourse API requires the interactions to be signed, so we generate a keypair on behalf of the user ''' from helpme.defaults import HELPME_CLIENT_SECRETS keypair_dir = os.path.join(os.path.dirname(HELPME_CLIENT_SECRETS), 'discourse')...
def _generate_keys(self)
the discourse API requires the interactions to be signed, so we generate a keypair on behalf of the user
5.344027
3.614686
1.478421
'''submit the question to the board. When we get here we should have (under self.data) {'record_environment': [('DISPLAY', ':0')], 'user_prompt_board': 'http://127.0.0.1', 'user_prompt_issue': 'I want to know why dinosaurs are so great!',...
def _submit(self)
submit the question to the board. When we get here we should have (under self.data) {'record_environment': [('DISPLAY', ':0')], 'user_prompt_board': 'http://127.0.0.1', 'user_prompt_issue': 'I want to know why dinosaurs are so great!', ...
6.092738
3.258665
1.869704
cache_key, flag_key = self.get_keys(cls, id_field, id_val) result = self.get_cached_or_set_flag(keys=(cache_key, flag_key)) # in Lua, arrays cannot hold nil values, so e.g. if [1, nil] is returned, # we'll only get [1] here. That's why we need to append None ourselves. ...
def get(self, cls, id_field, id_val)
Retrieve an object which `id_field` matches `id_val`. If it exists in the cache, it will be fetched from Redis. If not, it will be fetched via the `fetch` method and cached in Redis (unless the cache flag got invalidated in the meantime).
4.792444
4.463442
1.07371
return getattr(obj_from_cache, id_field) == id_val
def verify(self, cls, id_field, id_val, obj_from_cache)
Verify that the object we retrieved from cache matches the requested `id_field`/`id_val`.
3.598222
4.669617
0.77056
cache_key, flag_key = self.get_keys(cls, id_field, id_val) pipeline = self.redis.pipeline() pipeline.delete(cache_key) pipeline.delete(flag_key) pipeline.execute()
def invalidate(self, cls, id_field, id_val)
Invalidate the cache for a given Mongo object by deleting the cached data and the cache flag.
2.915994
2.73032
1.068005
self._vms = await self.iaas.list_vms(self.name) vms_stat = Counter([vm.get_state() for vm in self._vms]) missing = self.count - len(self._vms) if len(self._vms) < self.count else 0 logging.info( 'VMs Status: %s expected, %s in iaas, %s running, %s nearby shutdown, %...
async def manage(self)
Manage function docstring
3.08875
3.045316
1.014263
if aggressive: data = self._bridge.lock_state(self.nuki_id) if not data['success']: logger.warning( 'Failed to update the state of lock {}'.format(self.nuki_id) ) self._json.update({k: v for k, v in data.items() if k != 'su...
def update(self, aggressive=False)
Update the state of the NukiLock :param aggressive: Whether to aggressively poll the Bridge. If set to True, this will actively query the Lock, thus using more battery. :type aggressive: bool
4.580646
3.725943
1.229392
row = [] for field in fields: if field in mixed_case_fields: field_name = field.replace(' ', '_') else: field_name = field.lower().replace(' ', '_') data = item[field_name] if field_name in item else '' if field in formatters: row.append(...
def get_dict_properties(item, fields, mixed_case_fields=[], formatters={})
Return a tuple containing the item properties. :param item: a single dict resource :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to preserve case :param formatters: dictionary mapping field names to callables to format the values
2.00647
2.065665
0.971343
def decorator(func): func_name = func.__name__ @six.wraps(func) def wrapper(self, *args, **kwargs): if log.isEnabledFor(level): pretty_args = [] if args: pretty_args.extend(str(a) for a in args) if kwargs:...
def log_method(log, level=logging.DEBUG)
Logs a method and its arguments when entered.
1.853987
1.809964
1.024323
to_check = ['./replay', './replay/toDo', './replay/archive'] for i in to_check: if not os.path.exists(i): os.makedirs(i)
def check_local() -> None
Verify required directories exist. This functions checks the current working directory to ensure that the required directories exist. If they do not exist, it will create them.
6.50238
5.680925
1.144599
check_local() save_path = './replay/toDo/' filename = '{0}.txt'.format(str(uuid.uuid1())) complete_name = os.path.join(save_path, filename) with open(complete_name, 'w') as filename: filename.write('rc update-ld-api -p {0} -e {1} -f {2} -s {3}'.format( project, ...
def create_file(project: str, environment: str, feature: str, state: str) -> None
Create file to replay. Create file with ``rc`` command that will be called against the LaunchDarkly API when ``rc playback`` is called from the main CLI. :param project: LaunchDarkly Project :param environment: LaunchDarkly Environment :param feature: LaunchDarkly Feature :param state: State t...
5.645204
4.773961
1.182499
files = glob.glob('./replay/toDo/*') sorted_files = sorted(files, key=os.path.getctime) if not sorted_files: # list is not empty LOG.debug('Found %s, beginning execution.', sorted_files) for command_file in sorted_files: with open(command_file, 'r') as command: ...
def execute_replay() -> None
Execute all commands. For every command that is found in replay/toDo, execute each of them and move the file to the replay/archive directory.
4.189181
3.572411
1.172648
'''Ask the user for a prompt, and only return when one of the requested options is provided. Parameters ========== prompt: the prompt to ask the user choices: a list of choices that are valid, defaults to [Y/N/y/n] ''' if not choices: choices = ["y", "n", "Y"...
def choice_prompt(prompt, choices=None, choice=None)
Ask the user for a prompt, and only return when one of the requested options is provided. Parameters ========== prompt: the prompt to ask the user choices: a list of choices that are valid, defaults to [Y/N/y/n]
5.741225
3.597007
1.596112