code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
try: x = iterable.next()
except StopIteration: x = None
except AttributeError: x = None
return x | def get_next_item(iterable) | Gets the next item of an iterable.
If the iterable is exhausted, returns None. | 4.638847 | 4.176493 | 1.110704 |
import datetime, tzlocal
time_zone = tzlocal.get_localzone()
now = datetime.datetime.now(time_zone)
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z") | def pretty_now() | Returns some thing like '2019-02-15 15:58:22 CET+0100 | 2.707951 | 2.463413 | 1.099268 |
result = ', '.join(list_of_strings)
comma_index = result.rfind(',')
if comma_index > -1: result = result[:comma_index] + ' and' + result[comma_index+1:]
return result | def andify(list_of_strings) | Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos' | 2.666943 | 3.636744 | 0.733333 |
value = str(num)
before_last_digit = value[-2]
last_digit = value[-1]
if len(value) > 1 and before_last_digit == '1': return value +'th'
if last_digit == '1': return value + 'st'
if last_digit == '2': return value + 'nd'
if last_digit == '3': return value + 'rd'
r... | def num_to_ith(num) | 1 becomes 1st, 2 becomes 2nd, etc. | 2.296733 | 2.166248 | 1.060236 |
# Determine length #
if not full_sample_len: full_sample_len = len(full_sample)
# Check size coherence #
if not 0 <= k <= full_sample_len:
raise ValueError('Required that 0 <= k <= full_sample_length')
# Do it #
picked = 0
for i, element in enumerate(full_sample):
prob =... | def isubsample(full_sample, k, full_sample_len=None) | Down-sample an enumerable list of things | 3.77025 | 3.869753 | 0.974287 |
# The window size in half #
half = int(math.floor(windowsize/2.0))
# The normalized rectangular signal #
window = numpy.ones(int(windowsize))/float(windowsize)
# How do we deal with borders #
if borders == None:
return numpy.convolve(interval, window, 'valid')
if borders == 'zer... | def moving_average(interval, windowsize, borders=None) | This is essentially a convolving operation. Several option exist for dealing with the border cases.
* None: Here the returned signal will be smaller than the inputted interval.
* zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original inte... | 2.116173 | 1.867988 | 1.132862 |
ball, next_ball = u"|/-\\", "|"
sys.stdout.write(" \033[K")
sys.stdout.flush()
while not predicate():
time.sleep(1)
next_ball = ball[(ball.index(next_ball) + 1) % len(ball)]
sys.stdout.write("\r " + str(message()) + " " + next_ball + " \033[K")
sys.stdout.flush()
... | def wait(predicate, interval=1, message=lambda: "Waiting...") | Wait until the predicate turns true and display a turning ball. | 3.23027 | 3.199253 | 1.009695 |
dre = re.compile(r'(\d+)')
return [int(s) if s.isdigit() else s.lower() for s in re.split(dre, item)] | def natural_sort(item) | Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" | 2.478538 | 3.827976 | 0.64748 |
# Check input #
if s is None: return "0"
# If it's a string #
if isinstance(s, basestring): s = float(s)
# If it's a float that should be an int #
if isinstance(s, float) and s.is_integer(): s = int(s)
# Use python built-in #
result = "{:,}".format(s)
# But we want single quotes... | def split_thousands(s) | Splits a number on thousands.
>>> split_thousands(1000012)
"1'000'012" | 4.097065 | 4.179217 | 0.980343 |
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | def reverse_compl_with_name(old_seq) | Reverse a SeqIO sequence, but keep its name intact. | 1.980877 | 1.835549 | 1.079174 |
with open(path) as handle:
try: return json.load(handle, object_pairs_hook=collections.OrderedDict)
except ValueError as error:
message = "Could not decode JSON file '%s'." % path
message = "-"*20 + "\n" + message + "\n" + str(error) + "\n" + "-"*20 + "\n"
sy... | def load_json_path(path) | Load a file with the json module, but report errors better if it
fails. And have it ordered too ! | 2.759386 | 2.69904 | 1.022358 |
md5 = hashlib.md5()
with open(file_path, "rb") as f:
for block in iter(lambda: f.read(blocksize), ""):
md5.update(block)
return md5.hexdigest() | def md5sum(file_path, blocksize=65536) | Compute the md5 of a file. Pretty fast. | 1.507833 | 1.480971 | 1.018138 |
# Modules #
from tqdm import tqdm
import requests
from autopaths.file_path import FilePath
# Check destination exists #
destination = FilePath(destination)
destination.directory.create_if_not_exists()
# Over HTTP #
response = requests.get(source, stream=True)
total_size = in... | def download_from_url(source, destination, progress=False, uncompress=False) | Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory | 2.897016 | 2.817986 | 1.028045 |
with open(path, 'r') as handle:
part = ''
for block in reversed_blocks(handle):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
part += c
if part: yield part[::-1] | def reversed_lines(path) | Generate the lines of file in reverse order. | 3.338141 | 3.329433 | 1.002615 |
handle.seek(0, os.SEEK_END)
here = handle.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
handle.seek(here, os.SEEK_SET)
yield handle.read(delta) | def reversed_blocks(handle, blocksize=4096) | Generate blocks of file's contents in reverse order. | 2.35521 | 2.291529 | 1.02779 |
# Backup the file #
backupname = path + os.extsep + 'bak'
# Remove previous backup if it exists #
try: os.unlink(backupname)
except OSError: pass
os.rename(path, backupname)
# Open input/output files, note: outputfile's permissions lost #
with open(backupname) as inputfile:
... | def prepend_to_file(path, data, bufsize=1<<15) | TODO:
* Add a random string to the backup file.
* Restore permissions after copy. | 3.394684 | 3.273042 | 1.037165 |
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_executable(cmd): return FilePath(cmd)
else:
for path in os.environ['PATH'... | def which(cmd, safe=False) | https://github.com/jc0n/python-which | 2.487579 | 2.448075 | 1.016137 |
path = get_path_from_tokens(token)
tokens = token.split_contents()
if len(tokens) > 2:
# Get the media types from the tag call provided by the user.
media_type = tokens[2][1:-1]
else:
# Default values.
media_type = "screen, projection"
return CssTagNode(path, m... | def css_tag(parser, token) | Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
{% css "myfile.css" "screen, projec... | 4.169168 | 4.699335 | 0.887183 |
path = get_path_from_tokens(token)
# Hard wired media type, since this is for media type of 'print'.
media_type = "print"
return CssTagNode(path, media_type=media_type) | def css_print_tag(parser, token) | Shortcut to render CSS as a print stylesheet.
Usage::
{% css_print "myfile.css" %}
Which is equivalent to
{% css "myfile.css" "print" %} | 8.170368 | 11.498214 | 0.710577 |
if 'request' in context and client.supports_gzip():
enc = context['request'].META.get('HTTP_ACCEPT_ENCODING', '')
return 'gzip' in enc and msettings['SERVE_REMOTE']
return False | def supports_gzip(self, context) | Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be served the original media. | 9.228291 | 8.761159 | 1.053318 |
use_ssl = msettings['USE_SSL']
is_secure = use_ssl if use_ssl is not None else self.is_secure(context)
return client.media_url(with_ssl=True) if is_secure else client.media_url() | def get_media_url(self, context) | Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends implement SSL media. In this case, they'll just
re... | 5.484362 | 4.371232 | 1.254649 |
if path:
url = "%s/%s" % (url.rstrip('/'), path.strip('/'))
if filename:
url = "%s/%s" % (url, filename.lstrip('/'))
content_type = mimetypes.guess_type(url)[0]
if gzip and content_type in mediasync.TYPES_TO_COMPRESS:
url = "%s.gzt" ... | def mkpath(self, url, path, filename=None, gzip=False) | Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
filename: (str) The file name to serve.
gzip: (bool) True if clien... | 4.773307 | 4.692452 | 1.017231 |
if msettings['DOCTYPE'] == 'xhtml':
markup =
elif msettings['DOCTYPE'] == 'html5':
markup =
else:
markup =
return markup % (self.mkpath(url, path, filename, gzip=self.supports_gzip(context)), media) | def linktag(self, url, path, filename, media, context) | Renders a <link> tag for the stylesheet(s). | 9.220804 | 8.999329 | 1.02461 |
if msettings['DOCTYPE'] == 'html5':
markup =
else:
markup =
return markup % self.mkpath(url, path, filename, gzip=self.supports_gzip(context)) | def scripttag(self, url, path, filename, context) | Renders a <script> tag for the JS file(s). | 17.751137 | 18.337885 | 0.968004 |
before_run = [] if before_run is None else before_run
on_start = [] if on_start is None else on_start
shutdown = [] if shutdown is None else shutdown
if not isinstance(application, Application):
application = _ApplicationAdapter(application)
application.before_run_callbacks.extend(be... | def wrap_application(application, before_run, on_start, shutdown) | Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
:param list|NoneType on_start: optional list of callbacks to
register ... | 1.836389 | 2.048508 | 0.896452 |
for callback in self.before_run_callbacks:
try:
callback(self.tornado_application, io_loop)
except Exception:
self.logger.error('before_run callback %r cancelled start',
callback, exc_info=1)
self.... | def start(self, io_loop) | Run the ``before_run`` callbacks and queue to ``on_start`` callbacks.
:param tornado.ioloop.IOLoop io_loop: loop to start the app on. | 3.528486 | 3.188421 | 1.106656 |
running_async = False
shutdown = _ShutdownHandler(io_loop)
for callback in self.on_shutdown_callbacks:
try:
maybe_future = callback(self.tornado_application)
if asyncio.iscoroutine(maybe_future):
maybe_future = asyncio.cre... | def stop(self, io_loop) | Asynchronously stop the application.
:param tornado.ioloop.IOLoop io_loop: loop to run until all
callbacks, timeouts, and queued calls are complete
Call this method to start the application shutdown process.
The IOLoop will be stopped once the application is completely
shut... | 3.922569 | 3.964095 | 0.989524 |
from mediasync.conf import msettings
joinfile = joinfile.strip('/')
if joinfile.endswith('.css'):
dirname = msettings['CSS_PATH'].strip('/')
separator = '\n'
elif joinfile.endswith('.js'):
dirname = msettings['JS_PATH'].strip('/')
separator = ';\n'
else:
... | def combine_files(joinfile, sourcefiles, client) | Given a combo file name (joinfile), combine the sourcefiles into a single
monolithic file.
Returns a string containing the combo file, or None if the specified
file can not be combo'd. | 3.355244 | 3.277472 | 1.023729 |
from mediasync import backends
from mediasync.conf import msettings
from mediasync.signals import pre_sync, post_sync
# create client connection
if client is None:
client = backends.client()
client.open()
client.serve_remote = True
# send pre-sync signal
pre_sync.send... | def sync(client=None, force=False, verbose=True) | Let's face it... pushing this stuff to S3 is messy.
A lot of different things need to be calculated for each file
and they have to be in a certain order as some variables rely
on others. | 3.044116 | 3.086197 | 0.986365 |
'''
Enable all offline cpus
'''
for cpu in self.__get_ranges("offline"):
fpath = path.join("cpu%i"%cpu,"online")
self.__write_cpu_file(fpath, b"1") | def enable_all_cpu(self) | Enable all offline cpus | 13.612217 | 9.248207 | 1.471876 |
'''
Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset
'''
if type(rg) == int:
rg= [rg]
to_reset= rg if rg else self.__get_ranges("present")
self.enable_cpu(to_reset)
for cpu in to_reset:
... | def reset(self, rg=None) | Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset | 3.238504 | 2.262945 | 1.431102 |
'''
Disable all threads attached to the same core
'''
to_disable = []
online_cpus = self.__get_ranges("online")
for cpu in online_cpus:
fpath = path.join("cpu%i"%cpu,"topology","thread_siblings_list")
to_disable += self.__get_ranges(fpath)[1:]
... | def disable_hyperthread(self) | Disable all threads attached to the same core | 5.635389 | 4.684867 | 1.202892 |
'''
Disable cpus
rg: range or list of threads to disable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("online"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
self.__write_cpu_fi... | def disable_cpu(self, rg) | Disable cpus
rg: range or list of threads to disable | 7.602988 | 5.727881 | 1.327365 |
'''
Enable cpus
rg: range or list of threads to enable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("offline"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
self.__write_cpu_fil... | def enable_cpu(self, rg) | Enable cpus
rg: range or list of threads to enable | 8.69203 | 6.31676 | 1.376027 |
'''
Set cores frequencies
freq: int frequency in KHz
rg: list of range of cores
setMaxfeq: set the maximum frequency, default to true
setMinfreq: set the minimum frequency, default to true
setSpeed: only set the frequency, default to true
'''
to_c... | def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True) | Set cores frequencies
freq: int frequency in KHz
rg: list of range of cores
setMaxfeq: set the maximum frequency, default to true
setMinfreq: set the minimum frequency, default to true
setSpeed: only set the frequency, default to true | 3.054253 | 2.333556 | 1.30884 |
'''
Set governors
gov: str name of the governor
rg: list of range of cores
'''
to_change = self.__get_ranges("online")
if type(rg) == int:
rg= [rg]
if rg: to_change= set(rg) & set(self.__get_ranges("online"))
for cpu in to_change:
... | def set_governors(self, gov, rg=None) | Set governors
gov: str name of the governor
rg: list of range of cores | 6.536522 | 5.044297 | 1.295824 |
'''
Get all possible frequencies
'''
fpath = path.join("cpu0","cpufreq","scaling_available_frequencies")
data = self.__read_cpu_file(fpath).rstrip("\n").split()
return data | def get_available_frequencies(self) | Get all possible frequencies | 9.930052 | 7.551376 | 1.314999 |
if endpoint:
kwargs['endpoint'] = endpoint
keywords = self._keywords.copy()
keywords.update(kwargs)
if 'endpoint' in kwargs:
# Then we need to correctly format the endpoint.
endpoint = kwargs['endpoint']
keywords['endpoint'] = self... | def configure(self, endpoint=None, **kwargs) | Configure a previously initialized instance of the class. | 3.789041 | 3.698456 | 1.024493 |
if not endpoint.startswith('http'):
endpoint = 'https://' + endpoint
if not endpoint.endswith('/'):
endpoint += '/'
return endpoint | def _configure_endpoint(self, endpoint) | Configure the endpoint with a schema and end slash. | 2.935971 | 2.320007 | 1.265501 |
if 'convert' in kwargs:
conversion = kwargs.pop('convert')
else:
conversion = True
kwargs = self._get_keywords(**kwargs)
url = self._create_path(*args)
request = self.session.get(url, params=kwargs)
content = request.content
self._... | def get(self, *args, **kwargs) | Perform a get request. | 3.971191 | 3.784581 | 1.049308 |
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'count' in kwargs:
kwargs['page_size'] = kwargs.pop('count')
if 'start' in kwargs:
start = kwargs.pop('start')
if 'end' in kwargs:
... | def _get_keywords(self, **kwargs) | Format GET request parameters and keywords. | 2.052751 | 1.936913 | 1.059806 |
start = self._split_date(start)
end = self._split_date(end)
return start, end | def _format_dates(self, start, end) | Format start and end dates. | 3.730457 | 2.967536 | 1.257089 |
if isinstance(time, str):
month, day, year = [int(t) for t in re.split(r'-|/', time)]
if year < 100:
# Quick hack for dates < 2000.
year += 2000
time = date(year, month, day)
return time.strftime('%Y-%m-%dT%H:%M:%SZ') | def _split_date(self, time) | Split apart a date string. | 3.108767 | 2.950961 | 1.053476 |
if not conversion:
data = content
elif self.format == 'json':
data = json.loads(content)
elif self.format == 'xml':
content = xml(content)
first = list(content.keys())[0]
data = content[first]
else:
data = c... | def convert(self, content, conversion) | Convert content to Python data structures. | 3.428907 | 3.290501 | 1.042062 |
if url:
data = self.session.get(url).content
elif self.discovery_url:
response = self.session.get(self.discovery_url)
if self.format == 'xml':
# Because, SF doesn't follow the spec.
data = xml(response.text)
else:
... | def discovery(self, url=None) | Retrieve the standard discovery file that provides routing
information.
>>> Three().discovery()
{'discovery': 'data'} | 5.422365 | 6.042951 | 0.897304 |
data = self.get('services', code, **kwargs)
return data | def services(self, code=None, **kwargs) | Retrieve information about available services. You can also enter a
specific service code argument.
>>> Three().services()
{'all': {'service_code': 'data'}}
>>> Three().services('033')
{'033': {'service_code': 'data'}} | 5.811614 | 17.909172 | 0.324505 |
if code:
kwargs['service_code'] = code
data = self.get('requests', **kwargs)
return data | def requests(self, code=None, **kwargs) | Retrieve open requests. You can also enter a specific service code
argument.
>>> Three('api.city.gov').requests()
{'all': {'requests': 'data'}}
>>> Three('api.city.gov').requests('123')
{'123': {'requests': 'data'}} | 4.930516 | 6.510282 | 0.757343 |
data = self.get('requests', id, **kwargs)
return data | def request(self, id, **kwargs) | Retrieve a specific request using its service code ID.
>>> Three('api.city.gov').request('12345')
{'request': {'service_code': {'12345': 'data'}}} | 8.043066 | 13.113522 | 0.613341 |
kwargs['service_code'] = service_code
kwargs = self._post_keywords(**kwargs)
media = kwargs.pop('media', None)
if media:
files = {'media': media}
else:
files = None
url = self._create_path('requests')
self.post_response = self.sess... | def post(self, service_code='0', **kwargs) | Post a new Open311 request.
>>> t = Three('api.city.gov')
>>> t.post('123', address='123 Any St', name='Zach Williams',
... phone='555-5555', description='My issue description.',
... media=open('photo.png', 'rb'))
{'successful': {'request': 'post'}} | 3.46443 | 3.433728 | 1.008941 |
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'address' in kwargs:
address = kwargs.pop('address')
kwargs['address_string'] = address
if 'name' in kwargs:
first, last = kwargs.po... | def _post_keywords(self, **kwargs) | Configure keyword arguments for Open311 POST requests. | 2.410925 | 2.174154 | 1.108903 |
data = self.get('tokens', id, **kwargs)
return data | def token(self, id, **kwargs) | Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}} | 8.25197 | 15.716549 | 0.52505 |
attrs = dict(base_attrs, **kwargs)
if extra_attrs:
attrs.update(extra_attrs)
return attrs | def build_attrs(self, base_attrs, extra_attrs=None, **kwargs) | Helper function for building an attribute dictionary.
This is combination of the same method from Django<=1.10 and Django1.11+ | 2.443206 | 2.568756 | 0.951124 |
return pandas.io.parsers.read_csv(self.path, sep=self.d, **kwargs) | def to_dataframe(self, **kwargs) | Load up the CSV file as a pandas dataframe | 7.135097 | 5.135319 | 1.389416 |
coords = []
try:
for interval in features:
if len(interval) != 3:
raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval))
coords.extend([interval[0],interval[1]])
... | def get_elementary_intervals(self, features) | Generates a sorted list of elementary intervals | 4.086283 | 4.090279 | 0.999023 |
center = int(round(len(intervals) / 2))
left = intervals[:center]
right = intervals[center + 1:]
node = intervals[center]
if len(left) > 1:
left = self.recursive_build_tree(left)
elif len(left) == 1:
left = [left[0],[-1,-1,-1,[]],[-1,-1,... | def recursive_build_tree(self, intervals) | recursively builds a BST based on the elementary intervals.
each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]].
nodes with no descendents have a -1 value in left/right descendent positions.
for example, a node with two empty descendents:
[5... | 1.934299 | 1.763275 | 1.096992 |
try:
if pt >= int(subject[0]) and pt <= int(subject[1]):
return True
except ValueError:
raise ValueError('Interval start and stop has to be integers. %s' % str(subject))
return False | def pt_within(self, pt, subject) | Accessory function to check if a point is within a range | 4.921759 | 4.701431 | 1.046864 |
if self.pt_within(query[0], subject) and self.pt_within(query[1], subject):
return True
return False | def is_within(self, query, subject) | Accessory function to check if a range is fully within another range | 4.154739 | 3.898088 | 1.06584 |
if (self.pt_within(query[0], subject) or self.pt_within(query[1], subject) or
self.pt_within(subject[0], query) or self.pt_within(subject[1], query)):
return True
return False | def overlap(self, query, subject) | Accessory function to check if two ranges overlap | 2.624794 | 2.515894 | 1.043285 |
if node[0] != -1:
left = (start, node[0])
right = (node[0], end)
#if left is totally within coord
if self.is_within(left, coord):
node[1][-1].append(data)
elif self.overlap(left, coord):
self.recursive_insert(n... | def recursive_insert(self, node, coord, data, start, end) | Recursively inserts id data into nodes | 2.451666 | 2.473828 | 0.991042 |
for item in data:
self.recursive_insert(node, [item[0], item[1]], item[-1], start, end) | def insert_data(self, node, data, start, end) | loops through all the data and inserts them into the empty tree | 5.74938 | 5.270357 | 1.09089 |
data_len = len(node[-1])
if node[1] == -1 and node[2] == -1:
if data_len == 0:
return 1
else:
return 0
else:
if self.trim_tree(node[1]) == 1:
node[1] = -1
if self.trim_tree(node[2]) == 1:
... | def trim_tree(self, node) | trims the tree for any empty data nodes | 2.017213 | 1.954202 | 1.032244 |
data = []
if len(interval) != 2:
raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval))
left = (start, node[0])
right = (node[0], end)
if self.overlap(left, interval):
da... | def find(self, node, interval, start, end) | recursively finds ids within a range | 2.96922 | 2.984114 | 0.995009 |
return self.find(self.tree, interval, self.start, self.end) | def find_range(self, interval) | wrapper for find | 6.787528 | 6.650944 | 1.020536 |
pp = pprint.PrettyPrinter(indent=ind)
pp.pprint(self.tree) | def pprint(self, ind) | pretty prints the tree with indentation | 4.292551 | 3.508708 | 1.223399 |
model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
return registered_model_cores.get(model_label) | def get_model_core(model) | Return core view of given model or None | 5.507603 | 4.78111 | 1.151951 |
r
if vcs == 'git':
return GitRepo(url, **kwargs)
elif vcs == 'hg':
return MercurialRepo(url, **kwargs)
elif vcs == 'svn':
return SubversionRepo(url, **kwargs)
else:
raise InvalidVCS('VCS %s is not a valid VCS' % vcs) | def create_repo(url, vcs, **kwargs) | r"""Return a object representation of a VCS repository.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts import create_repo
>>> r = crea... | 2.28267 | 2.56444 | 0.890124 |
r
if pip_url.startswith('git+'):
return GitRepo.from_pip_url(pip_url, **kwargs)
elif pip_url.startswith('hg+'):
return MercurialRepo.from_pip_url(pip_url, **kwargs)
elif pip_url.startswith('svn+'):
return SubversionRepo.from_pip_url(pip_url, **kwargs)
else:
raise Inva... | def create_repo_from_pip_url(pip_url, **kwargs) | r"""Return a object representation of a VCS repository via pip-style url.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts import create_repo_fro... | 1.894702 | 2.172573 | 0.8721 |
# Make absolute paths #
if 'change_dir' in self.kwargs:
self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kwargs['change_dir']))
if 'out_file' in self.kwargs:
self.kwargs['out_file'] = FilePath(os.path.abspath(self.kwargs['out_file']))
# In... | def set_paths(self, base_dir, script_path) | Set the directory, the script path and the outfile path | 2.86821 | 2.780033 | 1.031718 |
# Main loop #
result = OrderedDict()
for param, info in self.slurm_headers.items():
if not info['needed'] and not param in self.kwargs: continue
if param in self.kwargs: result[param] = self.kwargs.get(param)
else: result[param] = i... | def slurm_params(self) | The list of parameters to give to the `sbatch` command. | 5.346738 | 5.275918 | 1.013423 |
self.shebang_header = self.shebang_headers[self.language]
self.slurm_header = [self.slurm_headers[k]['tag'] % v for k,v in self.slurm_params.items()]
self.script_header = self.script_headers[self.language]
self.script_footer = self.script_footers[self.language]
retur... | def script(self) | The script to be submitted to the SLURM queue. | 3.205835 | 2.921721 | 1.097242 |
self.script_path.write(self.script)
self.script_path.permissions.make_executable()
return self.script_path | def make_script(self) | Make the script and return a FilePath object pointing to the script above. | 4.655164 | 3.468134 | 1.342268 |
# If there is no script it is either ready or a lost duplicate #
if not self.script_path.exists:
if self.name in jobs.names: return "DUPLICATE"
if self.name not in jobs.names: return "READY"
# It is submitted already #
if self.name in jobs.names:
... | def status(self) | What is the status of the job ? | 6.382851 | 6.137414 | 1.03999 |
if self.name not in jobs: return {'status': self.status}
else: return jobs[self.name] | def info(self) | Get the existing job information dictionary | 10.546844 | 7.547512 | 1.397393 |
# Check already exists #
if self.status == "READY": return self.launch()
# Check name conflict #
if self.status == "DUPLICATE": message = "Job with same name '%s' already in queue, but we lost the script."
if self.status == "QUEUED": message = "Job '%s' already in q... | def run(self) | Will call self.launch() after performing some checks | 5.235055 | 4.955692 | 1.056372 |
# Make script file #
self.make_script()
# Do it #
sbatch_out = sh.sbatch(self.script_path)
jobs.expire()
# Message #
print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatch_out),
# Return id #
self.id = int(re.findall("Submitted batch ... | def launch(self) | Make the script file and return the newly created job id | 6.540772 | 5.522958 | 1.184288 |
self.thread = threading.Thread(target=self.execute_locally)
self.thread.daemon = True # So that they die when we die
self.thread.start() | def run_locally(self) | A convenience method to run the same result as a SLURM job
but locally in a non-blocking way. Useful for testing. | 4.727988 | 4.044979 | 1.168854 |
# Make script file #
self.make_script()
# Do it #
with open(self.kwargs['out_file'], 'w') as handle:
sh.python(self.script_path, _out=handle, _err=handle) | def execute_locally(self) | Runs the equivalent command locally in a blocking way. | 6.834892 | 7.509532 | 0.910162 |
try: self.thread.join(sys.maxint) # maxint timeout so that we can Ctrl-C them
except KeyboardInterrupt: print "Stopped waiting on job '%s'" % self.kwargs['job_name'] | def wait_locally(self) | If you have run the query in a non-blocking way, call this method to pause
until the query is finished. | 13.928185 | 14.220964 | 0.979412 |
version_tag = self.arguments.get('<version>')
special_keywords = ['current', 'latest']
if version_tag in special_keywords:
logger.error("releasing version '{}' is disallowed. Did you mean 'version upload'?".format(version_tag))
raise SystemExit(1)
placeho... | def replace_version_tag(self) | find the next major/minor/trivial version number if applicable | 3.567569 | 3.240385 | 1.100971 |
from re import match, DOTALL
only_usage_pattern = r
usage_and_options_pattern = r
usage, options = '', ''
if match(usage_and_options_pattern, docopt_string, DOTALL):
usage = match(usage_and_options_pattern, docopt_string, DOTALL).groupdict()['usage']
options = match(usage_and_op... | def parse_docopt_string(docopt_string) | returns a 2-tuple (usage, options) | 2.083415 | 1.84953 | 1.126457 |
widget = self.widget
if isinstance(widget, type):
widget = widget()
return widget | def get_widget(self, request) | Returns concrete widget that will be used for rendering table filter. | 4.495889 | 3.664775 | 1.226785 |
protocol = 'http' if with_ssl is False else 'https'
url = (self.aws_bucket_cname and "%s://%s" or "%s://s3.amazonaws.com/%s") % (protocol, self.aws_bucket)
if self.aws_prefix:
url = "%s/%s" % (url, self.aws_prefix)
return url | def remote_media_url(self, with_ssl=False) | Returns the base remote media URL. In this case, we can safely make
some assumptions on the URL string based on bucket names, and having
public ACL on.
args:
with_ssl: (bool) If True, return an HTTPS url. | 3.426883 | 3.50123 | 0.978766 |
code = 1
args = docopt(__doc__, argv=cargs)
try:
if args['--version']:
if not version:
version = 'N/A'
print(version)
code = 0
elif args['fetch']:
code = fetch(
info_url=args['<info-url>'],
i... | def distroinfo(cargs, version=__version__) | distroinfo Command-Line Interface | 2.660411 | 2.659189 | 1.00046 |
response_exceptions = {
MimerDataException: HTTPBadRequestResponseException,
NotAllowedException: HTTPForbiddenResponseException,
UnsupportedMediaTypeException: HTTPUnsupportedMediaTypeResponseException,
Http404: Http404,
ResourceNotFoundExcep... | def _get_error_response(self, exception) | Trasform pyston exceptions to Is-core exceptions and raise it | 3.826046 | 3.615227 | 1.058314 |
try:
session_id = session.sessionId
self.session_machines.rollback_fsm(session_id)
current_state = self.session_machines.current_state(session_id)
if message is None:
err_msg = choice(self._scenario_steps[current_state]['reprompt'])
... | def reprompt_error(self, message=None) | Intended to be used in case of erroneous input data | 5.97177 | 6.00871 | 0.993852 |
if step not in self._scenario_steps.keys():
raise UndefinedState("step {} not defined in scenario".format(step))
try:
session_id = session.sessionId
self.session_machines.set_state(session_id, step)
except UninitializedStateMachine as e:
l... | def move_to_step(self, step) | Use in cases when you need to move in given step depending on input | 8.222525 | 8.359747 | 0.983585 |
try:
session_id = session.sessionId
return self.session_machines.current_state(session_id)
except UninitializedStateMachine as e:
logger.error(e) | def get_current_state(self) | Get current state for user session or None if session doesn't exist | 9.318804 | 8.008176 | 1.163661 |
current_state = self.get_current_state()
if current_state is None:
return statement(INTERNAL_ERROR_MSG)
else:
try:
return choice(self._scenario_steps[current_state]['help'])
except KeyError:
return choice(self._default_... | def get_help(self) | Get context help, depending on the current step. If no help for current step
was specified in scenario description file, default one will be returned. | 5.454471 | 4.375484 | 1.246598 |
'''
Runs all enabled tests.
'''
# Run all tests.
for cls in self.get_test_classes():
# Print informational message.
self.logger.info('Running {cls.__name__} test...'.format(cls=cls))
# Create new test instance.
test = cls(runner=s... | def run(self) | Runs all enabled tests. | 2.742712 | 2.472437 | 1.109315 |
result = subprocess.call(['which', tool_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result != 0:
message = "The executable '%s' cannot be found in your $PATH" % tool_name
raise Exception(message) | def check_executable(tool_name) | Raises an warning if the executable *tool_name* is not found. | 2.498323 | 2.457089 | 1.016782 |
# Special cases #
if mod_name in module_name: mod_name = module_name[mod_name]
# Use a try except block #
try:
__import__(mod_name)
except ImportError as e:
if str(e) != 'No module named %s' % mod_name: raise e
print 'You do not seem to have the "%s" package properly ins... | def check_module(mod_name) | Calls sys.exit() if the module *mod_name* is not found. | 4.713386 | 4.587834 | 1.027366 |
if isinstance(obj, ObjectVersion):
bucket_id = obj.bucket_id
version_id = obj.version_id
key = obj.key
else:
bucket_id = obj.get('bucket')
version_id = obj.get('version_id')
key = obj.get('key')
return u'{}:{}:{}'.format(
bucket_id,
versio... | def iiif_image_key(obj) | Generate the IIIF image key. | 2.33454 | 2.342916 | 0.996425 |
return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \
u'{quality}.{image_format}'.format(
prefix=current_app.config['IIIF_UI_URL'],
version=version,
identifier=quote(
iiif_image_key(obj).encode('utf8'), safe=':'),
region=r... | def ui_iiif_image_url(obj, version='v2', region='full', size='full',
rotation=0, quality='default', image_format='png') | Generate IIIF image URL from the UI application. | 2.773516 | 2.868686 | 0.966824 |
'''
Body of a non-terminal is always a :class:`Sequence`. For an s-expr
to match, it must be of the form::
['name'] + [sexpr-0, ..., sexpr-n]
where the first list contains a name of the non-terminal,
and the second one matches its body sequence.
'''
... | def matches(self, sexp) | Body of a non-terminal is always a :class:`Sequence`. For an s-expr
to match, it must be of the form::
['name'] + [sexpr-0, ..., sexpr-n]
where the first list contains a name of the non-terminal,
and the second one matches its body sequence. | 8.012438 | 1.713034 | 4.677337 |
params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS'])
if 'image_format' not in params:
params['image_format'] = \
'png' if file.has_extensions('.png') else 'jpg'
return render_template(
current_app.config['IIIF_PREVIEW_TEMPLATE'],
file=file,
file_url... | def preview(file) | Render appropriate template with embed flag. | 4.274602 | 4.07316 | 1.049456 |
# If its class has no translatable fields, returns attribute
try:
if not hasattr(instance._meta, "translatable_fields") or len(getattr(instance._meta,"translatable_fields"))==0:
return getattr(instance, attr)
except AttributeError:
return instance
# Translatable fields of this instance
translatable_fi... | def get_translated_attribute(instance, attr) | Wraps Django Model __getattribute__ method making translation in templates less painful | 3.618446 | 3.546505 | 1.020285 |
AUTH = getattr(
settings,
'SLACKCHAT_AUTH_DECORATOR',
'django.contrib.admin.views.decorators.staff_member_required'
)
auth_decorator = import_class(AUTH)
return method_decorator(auth_decorator, name='dispatch')(view) | def secure(view) | Set an auth decorator applied for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator. | 4.676097 | 3.960793 | 1.180596 |
def _import_po_file(uploadedfile, lang):
lines = []
for line in uploadedfile:
lines.append(line)
num_lines = len(lines)
prog_ctxt = re.compile(r"msgctxt\s+\"(?P<id>\d+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"")
prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$")
prog_msgstr =... | def import_translations(request, language) | Importa las traducciones a partir de un archivo PO. Ten en cuenta
que el archivo PO ha de ser generado desde esta aplicación, de forma
que los comentarios sirvan como id de traducción (lo metemos nosotros
en la exportación). | 2.812791 | 2.759105 | 1.019458 |
try:
cloud_config = CloudConfig()
ci = None
if cloud_init:
ci = CloudInit()
cloud_controller = CloudController(cloud_config)
cloud_controller.up(ci, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time)
except CloudComposeException as ex:
... | def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time) | creates a new cluster | 3.613581 | 3.870248 | 0.933682 |
try:
cloud_config = CloudConfig()
cloud_controller = CloudController(cloud_config)
cloud_controller.down(force)
except CloudComposeException as ex:
print(ex) | def down(force) | destroys an existing cluster | 4.483053 | 4.901312 | 0.914664 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.