code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if cwd is None: from os import getcwd cwd = getcwd() # TODO do I need to normalize this on Windows out = check_output(cmd, cwd=cwd, stderr=stderr, universal_newlines=True) return _clean_output(out)
def shell_out(cmd, stderr=STDOUT, cwd=None)
Friendlier version of check_output.
4.979298
4.5897
1.084885
try: return shell_out(cmd, stderr=stderr, cwd=cwd) except CalledProcessError as c: return _clean_output(c.output)
def shell_out_ignore_exitcode(cmd, stderr=STDOUT, cwd=None)
Same as shell_out but doesn't raise if the cmd exits badly.
3.658615
3.441166
1.06319
"Context manager to ensure in the cwd directory." import os curdir = os.getcwd() try: os.chdir(cwd) yield finally: os.chdir(curdir)
def from_dir(cwd)
Context manager to ensure in the cwd directory.
4.432611
2.814199
1.575088
'''Returns a function such that a call to it is equivalent to: if indicator(x): return function(x) else: return alternative Note that ``function`` is not called if indicator evaluates to False. :param function: The function to be called when indicator returns True. ...
def merge_function_with_indicator(function, indicator, alternative)
Returns a function such that a call to it is equivalent to: if indicator(x): return function(x) else: return alternative Note that ``function`` is not called if indicator evaluates to False. :param function: The function to be called when indicator returns True. :param ...
3.85344
1.529798
2.518921
from thumbnails import get_thumbnail regex = regex_base % { 'caption': '[a-zA-Z0-9\.\,:;/_ \(\)\-\!\?\"]+', 'image': '[a-zA-Z0-9\.:/_\-\% ]+' } images = re.findall(regex, value) for i in images: image_url = i[1] image = get_thumbnail( image_url, ...
def text_filter(regex_base, value)
A text-filter helper, used in ``markdown_thumbnails``-filter and ``html_thumbnails``-filter. It can be used to build custom thumbnail text-filters. :param regex_base: A string with a regex that contains ``%(captions)s`` and ``%(image)s`` where the caption and image should be. :param ...
4.719385
4.578585
1.030752
# The setup phase, here KeyboardInterrupt is a silent sign to exit the # application. Any error that happens here will result in a raw # backtrace being printed to the user. try: self.context.argv = argv self._added() self._build_early_parser(...
def eat(self, argv=None)
Eat the guacamole. :param argv: Command line arguments or None. None means that sys.argv is used :return: Whatever is returned by the first ingredient that agrees to perform the command dispatch. The eat method is called to run the application, as if it was ...
7.000473
7.131441
0.981635
for ingredient in self.ingredients: result = ingredient.dispatch(self.context) if result is not None: return result
def _dispatch(self)
Run the dispatch() method on all ingredients.
5.933997
3.60019
1.648245
'''Call the parallelized sampler's ``run`` method. Each process will run for ``N`` iterations. Then, the master process (process with ``rank = 0``) collects the samples and weights from all processes and stores it into ``self.samples_list`` and ``self.weights_list``. Master proce...
def run(self, N=1, *args, **kwargs)
Call the parallelized sampler's ``run`` method. Each process will run for ``N`` iterations. Then, the master process (process with ``rank = 0``) collects the samples and weights from all processes and stores it into ``self.samples_list`` and ``self.weights_list``. Master process: Retur...
5.011654
1.682439
2.978803
self.sampler.clear() self.samples_list = self._comm.gather(self.sampler.samples, root=0) if hasattr(self.sampler, 'weights'): self.weights_list = self._comm.gather(self.sampler.weights, root=0) else: self.weights_list = None
def clear(self)
Delete the history.
2.912322
2.84108
1.025076
if os.path.isabs(path): return path return os.path.join(self.location, path)
def path(self, path)
Creates a path based on the location attribute of the backend and the path argument of the function. If the path argument is an absolute path the path is returned. :param path: The path that should be joined with the backends location.
3.032658
3.378407
0.897659
d = c2.log_det_sigma - c1.log_det_sigma d += np.trace(c2.inv_sigma.dot(c1.sigma)) mean_diff = c1.mu - c2.mu d += mean_diff.transpose().dot(c2.inv_sigma).dot(mean_diff) d -= len(c1.mu) return 0.5 * d
def kullback_leibler(c1, c2)
Kullback Leibler divergence of two Gaussians, :math:`KL(1||2)`
3.329509
3.216696
1.035071
if kill: removed_indices = self.g.prune() self.nout -= len(removed_indices) if verbose and removed_indices: print('Removing %s' % removed_indices) for j in removed_indices: self.inv_map.pop(j[0])
def _cleanup(self, kill, verbose)
Look for dead components (weight=0) and remove them if enabled by ``kill``. Resize storage. Recompute determinant and covariance.
6.66881
6.325589
1.054259
return np.average(self.min_kl, weights=self.f.weights)
def _distance(self)
Compute the distance function d(f,g,\pi), Eq. (3)
24.10331
19.202538
1.255215
# temporary variables for manipulation mu_diff = np.empty_like(self.f.components[0].mu) sigma = np.empty_like(self.f.components[0].sigma) mean = np.empty_like(mu_diff) cov = np.empty_like(sigma) for j, c in enumerate(self.g.components): # st...
def _refit(self)
Update the map :math:`\pi` keeping the output :math:`g` fixed Use Eq. (7) and below in [GR04]_
3.260277
3.225488
1.010786
# clean up old maps for j in range(self.nout): self.inv_map[j] = [] # find smallest divergence between input component i # and output component j of the cluster mixture density for i in range(self.nin): self.min_kl[i] = np.inf j_min =...
def _regroup(self)
Update the output :math:`g` keeping the map :math:`\pi` fixed. Compute the KL between all input and output components.
3.955661
3.336402
1.185607
r old_distance = np.finfo(np.float64).max new_distance = np.finfo(np.float64).max if verbose: print('Starting hierarchical clustering with %d components.' % len(self.g.components)) converged = False for step in range(1, max_steps + 1): self._clean...
def run(self, eps=1e-4, kill=True, max_steps=50, verbose=False)
r"""Perform the clustering on the input components updating the initial guess. The result is available in the member ``self.g``. Return the number of iterations at convergence, or None. :param eps: If relative change of distance between current and last step falls below ``eps``, ...
3.46641
3.24143
1.069408
headerinfo, data = payload.split('\n', 1) headers = get_headers(headerinfo) return headers, data
def eventdata(payload)
Parse a Supervisor event.
7.27035
6.893241
1.054707
while True: stdout.write('READY\n') stdout.flush() line = stdin.readline() headers = get_headers(line) payload = stdin.read(int(headers['len'])) event_headers, event_data = eventdata(payload) yield event_headers, event_data stdout.write('RESU...
def supervisor_events(stdin, stdout)
An event stream from Supervisor.
4.686219
4.622648
1.013752
env = os.environ try: host = env['SYSLOG_SERVER'] port = int(env['SYSLOG_PORT']) socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \ else socket.SOCK_STREAM except KeyError: sys.exit("SYSLOG_SERVER, SYSLOG_PORT and SYSLOG_PROTO are required.") ...
def main()
Main application loop.
2.995315
2.874871
1.041895
formatted = super(PalletFormatter, self).formatTime( record, datefmt=datefmt) return formatted + '.%03dZ' % record.msecs
def formatTime(self, record, datefmt=None)
Format time, including milliseconds.
6.362209
5.237479
1.214746
chunks = re.split('\n@@ [^\n]+\n', udiff)[1:] line_numbers = re.findall('@@\s[+-]\d+,\d+ \+(\d+)', udiff) line_numbers = list(map(int, line_numbers)) for c, start in zip(chunks, line_numbers): ilines = enumerate((line for line in c.splitlines() if not line.star...
def modified_lines_from_udiff(udiff)
Extract from a udiff an iterator of tuples of (start, end) line numbers.
3.583761
3.685146
0.972488
original, fixed = original.splitlines(True), fixed.splitlines(True) newline = '\n' from difflib import unified_diff diff = unified_diff(original, fixed, os.path.join(original_label, file_name), os.path.join(fixed_label, file_name), ...
def get_diff(original, fixed, file_name, original_label='original', fixed_label='fixed')
Return text of unified diff between original and fixed.
2.974401
2.663484
1.116733
import colorama if not diff: return if not color: colorama.init = lambda autoreset: None colorama.Fore.RED = '' colorama.Back.RED = '' colorama.Fore.GREEN = '' colorama.deinit = lambda: None colorama.init(autoreset=True) # TODO use context_manager...
def print_diff(diff, color=True)
Pretty printing for a diff, if color then we use a simple color scheme (red for removed lines, green for added lines).
4.097617
4.050111
1.011729
'''Run the chain and store the history of visited points into the member variable ``self.samples``. Returns the number of accepted points during the run. .. seealso:: :py:class:`pypmc.tools.History` :param N: An int which defines the number of steps to ...
def run(self, N=1)
Run the chain and store the history of visited points into the member variable ``self.samples``. Returns the number of accepted points during the run. .. seealso:: :py:class:`pypmc.tools.History` :param N: An int which defines the number of steps to run the cha...
3.956505
3.069407
1.289013
return self._get_log_rho_metropolis(proposed_point, proposed_eval)\ - self.proposal.evaluate (proposed_point, self.current) \ + self.proposal.evaluate (self.current, proposed_point)
def _get_log_rho_metropolis_hastings(self, proposed_point, proposed_eval)
calculate log(metropolis ratio times hastings factor)
4.72011
4.542548
1.039089
r last_run = self.samples[-1] accept_rate = float(self._last_accept_count) / len(last_run) # careful with rowvar! # in this form it is expected that each column of ``points`` # represents sampling values of a variable # this is the case if points is a list of sa...
def adapt(self)
r"""Update the proposal using the points stored in ``self.samples[-1]`` and the parameters which can be set via :py:meth:`.set_adapt_params`. In the above referenced function's docstring, the algorithm is described in detail. If the resulting matrix is not a valid covariance, its...
6.06819
5.278627
1.149577
'''Private function. Updates the covariance scaling factor ``covar_scale_factor`` according to its limits ''' if accept_rate > self.force_acceptance_max and self.covar_scale_factor < self.covar_scale_factor_max: self.covar_scale_factor *= self.covar_scale_multiplier ...
def _update_scale_factor(self, accept_rate)
Private function. Updates the covariance scaling factor ``covar_scale_factor`` according to its limits
3.046774
1.961924
1.552952
try: image = self.create(original, size, crop, options) except ThumbnailError: image = None finally: self.cleanup(original) return image
def get_thumbnail(self, original, size, crop, options)
Wrapper for .create() with cleanup. :param original: :param size: :param crop: :param options: :return: An image object
3.52531
3.307809
1.065754
if options is None: options = self.evaluate_options() image = self.engine_load_image(original) image = self.scale(image, size, crop, options) crop = self.parse_crop(crop, self.get_image_size(image), size) image = self.crop(image, size, crop, options) ...
def create(self, original, size, crop, options=None)
Creates a thumbnail. It loads the image, scales it and crops it. :param original: :param size: :param crop: :param options: :return:
3.646267
3.727803
0.978127
original_size = self.get_image_size(image) factor = self._calculate_scaling_factor(original_size, size, crop is not None) if factor < 1 or options['scale_up']: width = int(original_size[0] * factor) height = int(original_size[1] * factor) image = sel...
def scale(self, image, size, crop, options)
Wrapper for ``engine_scale``, checks if the scaling factor is below one or that scale_up option is set to True before calling ``engine_scale``. :param image: :param size: :param crop: :param options: :return:
3.130116
2.505926
1.249086
if not crop: return image return self.engine_crop(image, size, crop, options)
def crop(self, image, size, crop, options)
Wrapper for ``engine_crop``, will return without calling ``engine_crop`` if crop is None. :param image: :param size: :param crop: :param options: :return:
4.996663
3.935289
1.269707
mode = options['colormode'] return self.engine_colormode(image, mode)
def colormode(self, image, options)
Wrapper for ``engine_colormode``. :param image: :param options: :return:
6.777528
6.500724
1.04258
if size.startswith('x'): return None, int(size.replace('x', '')) if 'x' in size: return int(size.split('x')[0]), int(size.split('x')[1]) return int(size), None
def parse_size(size)
Parses size string into a tuple :param size: String on the form '100', 'x100 or '100x200' :return: Tuple of two integers for width and height :rtype: tuple
2.57516
2.417253
1.065325
if crop is None: return None crop = crop.split(' ') if len(crop) == 1: crop = crop[0] x_crop = 50 y_crop = 50 if crop in CROP_ALIASES['x']: x_crop = CROP_ALIASES['x'][crop] elif crop in CROP_ALIASES...
def parse_crop(self, crop, original_size, size)
Parses crop into a tuple usable by the crop function. :param crop: String with the crop settings. :param original_size: A tuple of size of the image that should be cropped. :param size: A tuple of the wanted size. :return: Tuple of two integers with crop settings :rtype: tuple
2.049508
2.029352
1.009932
return int( max( 0, min(percent * original_length / 100.0, original_length - length / 2) - length / 2) )
def calculate_offset(percent, original_length, length)
Calculates crop offset based on percentage. :param percent: A percentage representing the size of the offset. :param original_length: The length the distance that should be cropped. :param length: The desired length. :return: The offset in pixels :rtype: int
4.249828
4.794261
0.886441
if app_name in _cache: return _cache[app_name] template_dir = None for app in settings.INSTALLED_APPS: if app.split('.')[-1] == app_name: # Do not hide import errors; these should never happen at this # point anyway mod = import_module(app) ...
def get_app_template_dir(app_name)
Get the template directory for an application We do not use django.db.models.get_app, because this will fail if an app does not have any models. Returns a full path, or None if the app was not found.
3.046704
3.120832
0.976248
if ':' not in template_name: return [] app_name, template_name = template_name.split(":", 1) template_dir = get_app_template_dir(app_name) if template_dir: return [get_template_path(template_dir, template_name, self)] return []
def get_template_sources(self, template_name, template_dirs=None)
Return the absolute paths to "template_name" in the specified app If the name does not contain an app name (no colon), an empty list is returned. The parent FilesystemLoader.load_template_source() will take care of the actual loading for us.
2.692851
2.409822
1.117448
parser = argparse.ArgumentParser(prog=sys.argv[0], description='Send Webhooks Channel events to IFTTT', epilog='Visit https://ifttt.com/channels/maker_webhooks for more information') parser.add_argument('--version', action='version'...
def parse_arguments()
Parse command line arguments
2.716577
2.674221
1.015838
args = parse_arguments() if args.key is None: print("Error: Must provide IFTTT secret key.") sys.exit(1) try: res = pyfttt.send_event(api_key=args.key, event=args.event, value1=args.value1, value2=args.value2, val...
def main()
Main function for pyfttt command line tool
2.185075
2.050318
1.065725
'''Classify the 2D ``data`` according to the ``responsibility`` and make a scatter plot of each data point with the color of the component it is most likely from. The ``responsibility`` is normalized internally such that each row sums to unity. :param data: matrix-like; one row = one 2D sa...
def plot_responsibility(data, responsibility, cmap='nipy_spectral')
Classify the 2D ``data`` according to the ``responsibility`` and make a scatter plot of each data point with the color of the component it is most likely from. The ``responsibility`` is normalized internally such that each row sums to unity. :param data: matrix-like; one row = one 2D sample ...
4.068946
2.074699
1.961223
try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImportError('%s doesn\'t look like a valid path' % dotted_path) module = __import__(module_path, fromlist=[class_name]) try: return getattr(module, class_name) except AttributeError: ...
def import_string(dotted_path)
Import a dotted module path. Returns the attribute/class designated by the last name in the path. Raises ImportError if the import fails.
1.668317
1.814173
0.919602
'''Returns the indicator function of a ball. :param center: A vector-like numpy array, defining the center of the ball.\n len(center) fixes the dimension. :param radius: Float or int, the radius of the ball :param bdy: Bool, When ``x`` is at the ball's boundary then...
def ball(center, radius=1., bdy=True)
Returns the indicator function of a ball. :param center: A vector-like numpy array, defining the center of the ball.\n len(center) fixes the dimension. :param radius: Float or int, the radius of the ball :param bdy: Bool, When ``x`` is at the ball's boundary then ...
3.161949
1.924727
1.642804
'''Returns the indicator function of a hyperrectangle. :param lower: Vector-like numpy array, defining the lower boundary of the hyperrectangle.\n len(lower) fixes the dimension. :param upper: Vector-like numpy array, defining the upper boundary of the hyperrectangle.\n :par...
def hyperrectangle(lower, upper, bdy=True)
Returns the indicator function of a hyperrectangle. :param lower: Vector-like numpy array, defining the lower boundary of the hyperrectangle.\n len(lower) fixes the dimension. :param upper: Vector-like numpy array, defining the upper boundary of the hyperrectangle.\n :param bdy:...
3.042034
1.966322
1.547068
engine = get_engine() cache = get_cache_backend() original = SourceFile(original) crop = options.get('crop', None) options = engine.evaluate_options(options) thumbnail_name = generate_filename(original, size, crop) if settings.THUMBNAIL_DUMMY: engine = DummyEngine() re...
def get_thumbnail(original, size, **options)
Creates or gets an already created thumbnail for the given image with the given size and options. :param original: File-path, url or base64-encoded string of the image that you want an thumbnail. :param size: String with the wanted thumbnail size. On the form: ``200x200``, ``200`` or ...
3.234895
3.267774
0.989938
a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
def argsort_indices(a, axis=-1)
Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional
2.463046
2.820405
0.873295
url = 'https://maker.ifttt.com/trigger/{e}/with/key/{k}/'.format(e=event, k=api_key) payload = {'value1': value1, 'value2': value2, 'value3': value3} return requests.post(url, data=payload)
def send_event(api_key, event, value1=None, value2=None, value3=None)
Send an event to the IFTTT maker channel Parameters: ----------- api_key : string Your IFTTT API key event : string The name of the IFTTT event to trigger value1 : Optional: Extra data sent with the event (default: None) value2 : Optional: Extra data sent with th...
2.105435
2.030578
1.036865
if obj.__class__.__doc__ is not None: return inspect.cleandoc( gettext.dgettext(domain, obj.__class__.__doc__))
def get_localized_docstring(obj, domain)
Get a cleaned-up, localized copy of docstring of this class.
4.84039
4.526552
1.069333
try: return self.help except AttributeError: pass try: return get_localized_docstring( self, self.get_gettext_domain() ).splitlines()[0].rstrip('.').lower() except (AttributeError, IndexError, ValueError): ...
def get_cmd_help(self)
Get the single-line help of this command. :returns: ``self.help``, if defined :returns: The first line of the docstring, without the trailing dot, if present. :returns: None, otherwise
5.750452
4.956684
1.160141
try: return self.description except AttributeError: pass try: return '\n'.join( get_localized_docstring( self, self.get_gettext_domain() ).splitlines()[1:] ).split('@EPILOG@', 1)[0].strip...
def get_cmd_description(self)
Get the leading, multi-line description of this command. :returns: ``self.description``, if defined :returns: A substring of the class docstring between the first line (which is discarded) and the string ``@EPILOG@``, if present, or the end of the docstri...
5.641041
4.424366
1.274994
try: return self.source.epilog except AttributeError: pass try: return '\n'.join( get_localized_docstring( self, self.get_gettext_domain() ).splitlines()[1:] ).split('@EPILOG@', 1)[1].str...
def get_cmd_epilog(self)
Get the trailing, multi-line description of this command. :returns: ``self.epilog``, if defined :returns: A substring of the class docstring between the string ``@EPILOG`` and the end of the docstring, if defined :returns: None, otherwise ...
5.826248
5.44765
1.069498
return CommandRecipe(self).main(argv, exit)
def main(self, argv=None, exit=True)
Shortcut for running a command. See :meth:`guacamole.recipes.Recipe.main()` for details.
20.153816
15.76324
1.278533
return [ cmdtree.CommandTreeBuilder(self.command), cmdtree.CommandTreeDispatcher(), argparse.AutocompleteIngredient(), argparse.ParserIngredient(), crash.VerboseCrashHandler(), ansi.ANSIIngredient(), log.Logging(), ...
def get_ingredients(self)
Get a list of ingredients for guacamole.
27.506502
25.873652
1.063109
parser.add_argument('x', type=int, help='the first value') parser.add_argument('y', type=int, help='the second value')
def register_arguments(self, parser)
Guacamole method used by the argparse ingredient. :param parser: Argument parser (from :mod:`argparse`) specific to this command.
2.600273
2.899297
0.896863
print("{} + {} = {}".format( ctx.args.x, ctx.args.y, ctx.args.x + ctx.args.y))
def invoked(self, ctx)
Guacamole method used by the command ingredient. :param ctx: The guacamole context object. Context provides access to all features of guacamole. The argparse ingredient adds the ``args`` attribute to it. That attribute contains the result of parsing command line ...
4.050024
4.818169
0.840573
if 360 < h < 0: raise ValueError("h out of range: {}".format(h)) if 1 < s < 0: raise ValueError("s out of range: {}".format(h)) if 1 < v < 0: raise ValueError("v out of range: {}".format(h)) c = v * s # chroma h1 = h / 60 x = c * (1 - abs(h1 % 2 - 1)) if 0 <= h1...
def hsv(h, s, v)
Convert HSV (hue, saturation, value) to RGB.
1.400849
1.391986
1.006367
if not ctx.ansi.is_enabled: print("You need color support to use this demo") else: print(ctx.ansi.cmd('erase_display')) self._demo_fg_color(ctx) self._demo_bg_color(ctx) self._demo_bg_indexed(ctx) self._demo_rgb(ctx) ...
def invoked(self, ctx)
Method called when the command is invoked.
6.129557
6.476773
0.946391
if isinstance(thumbnail_name, list): thumbnail_name = '/'.join(thumbnail_name) return self._get(thumbnail_name)
def get(self, thumbnail_name)
Wrapper for ``_get``, which converts the thumbnail_name to String if necessary before calling ``_get`` :rtype: Thumbnail
2.994304
3.967143
0.754776
host = '127.0.0.1' port = 6379 db = 0 if self.connection_uri is not None: re_connection_uri = r'redis://(?:([\w]+)@)?([\w\d\.]+):(\d+)(?:/(\d+))?' match = re.match(re_connection_uri, self.connection_uri) if match: if match.grou...
def get_settings(self)
This creates a dict with keyword arguments used to create the redis client. It is used like ``redis.StrictClient(**self.get_settings())``. Thus, if the settings string is not enough to generate the wanted setting you can override this function. :return: A dict with keyword arguments for...
2.086834
2.083134
1.001776
return parse(os.environ[name], parse_class, **defaults)
def parse_environ(name, parse_class=ParseResult, **defaults)
same as parse() but you pass in an environment variable name that will be used to fetch the dsn :param name: string, the environment variable name that contains the dsn to parse :param parse_class: ParseResult, the class that will be used to hold parsed values :param **defaults: dict, any values you wa...
5.405527
7.719049
0.700284
ret = [] if name in os.environ: ret.append(parse_environ(name, parse_class, **defaults)) # now try importing _1 -> _N dsns increment_name = lambda name, num: '{name}_{num}'.format(name=name, num=num) dsn_num = 0 if increment_name(name, 0) in os.environ else 1 dsn_env_num_name = inc...
def parse_environs(name, parse_class=ParseResult, **defaults)
same as parse_environ() but will also check name_1, name_2, ..., name_N and return all the found dsn strings from the environment this will look for name, and name_N (where N is 1 through infinity) in the environment, if it finds them, it will assume they are dsn urls and will parse them. The num che...
2.853599
2.873764
0.992983
r = parse_class(dsn, **defaults) return r
def parse(dsn, parse_class=ParseResult, **defaults)
parse a dsn to parts similar to parseurl :param dsn: string, the dsn to parse :param parse_class: ParseResult, the class that will be used to hold parsed values :param **defaults: dict, any values you want to have defaults for if they aren't in the dsn :returns: ParseResult() tuple-like instance
6.002851
18.93903
0.316957
s = '' prefix = '' if self.username: s += self.username prefix = '@' if self.password: s += ":{password}".format(password=self.password) prefix = '@' s += "{prefix}{hostloc}".format(prefix=prefix, hostloc=self.hostloc) ...
def netloc(self)
return username:password@hostname:port
3.497315
3.195584
1.094421
hostloc = self.hostname if self.port: hostloc = '{hostloc}:{port}'.format(hostloc=hostloc, port=self.port) return hostloc
def hostloc(self)
return host:port
2.967456
2.85298
1.040125
if not getattr(self, key, None): setattr(self, key, val)
def setdefault(self, key, val)
set a default value for key this is different than dict's setdefault because it will set default either if the key doesn't exist, or if the value at the key evaluates to False, so an empty string or a None value will also be updated :param key: string, the attribute to update :...
3.858046
6.63574
0.581404
return urlparse.urlunparse(( self.scheme, self.netloc, self.path, self.params, self.query_str, self.fragment, ))
def geturl(self)
return the dsn back into url form
2.737523
2.248716
1.217372
context.early_args, unused = ( context.early_parser.parse_known_args(context.argv))
def preparse(self, context)
Parse a portion of command line arguments with the early parser. This method relies on ``context.argv`` and ``context.early_parser`` and produces ``context.early_args``. The ``context.early_args`` object is the return value from argparse. It is the dict/object like namespace object.
15.941522
8.088128
1.970978
context.parser, context.max_level = self._create_parser(context)
def build_parser(self, context)
Create the final argument parser. This method creates the non-early (full) argparse argument parser. Unlike the early counterpart it is expected to have knowledge of the full command tree. This method relies on ``context.cmd_tree`` and produces ``context.parser``. Other ingredi...
15.677788
16.175068
0.969256
context.args = context.parser.parse_args(context.argv)
def parse(self, context)
Parse command line arguments. This method relies on ``context.argv`` and ``context.early_parser`` and produces ``context.args``. Note that ``.argv`` is modified by :meth:`preparse()` so it actually has _less_ things in it. The ``context.args`` object is the return value from argparse. ...
10.014777
7.465455
1.341482
try: import argcomplete except ImportError: return try: parser = context.parser except AttributeError: raise RecipeError( ) else: argcomplete.autocomplete(parser)
def parse(self, context)
Optionally trigger argument completion in the invoking shell. This method is called to see if bash argument completion is requested and to honor the request, if needed. This causes the process to exit (early) without giving other ingredients a chance to initialize or shut down. ...
7.43705
5.743355
1.294896
try: obj = getattr(ANSI, str('cmd_{}'.format(cmd))) except AttributeError: raise ValueError( "incorrect command: {!r}".format(cmd)) if isinstance(obj, type("")): return obj else: return obj(*args)
def ansi_cmd(cmd, *args)
Get ANSI command code by name.
5.447371
4.819229
1.130341
if isinstance(color, (str, type(""))): try: return getattr(_Visible, str('{}'.format(color))) except AttributeError: raise ValueError("incorrect color: {!r}".format(color)) elif isinstance(color, tuple): return (0x80 ^ color[0], 0x80 ^ color[1], 0x80 ^ color[...
def get_visible_color(color)
Get the visible counter-color.
2.479283
2.440253
1.015994
# Ensure that text is really a string text = type("")(text) # NOTE: SGR stands for "set graphics rendition" sgr_list = [] # List of SGR codes # Load SGR code associated with desired foreground color if isinstance(fg, (str, type(""))): try: sgr_code = getattr(ANSI, str('...
def ansi_sgr(text, fg=None, bg=None, style=None, reset=True, **sgr)
Apply desired SGR commands to given text. :param text: Text or anything convertible to text :param fg: (optional) Foreground color. Choose one of ``black``, ``red``, ``green``, ``yellow``, ``blue``, ``magenta`` ``cyan`` or ``white``. Note that the ``bright`` *SGR* impacts ...
1.867907
1.898415
0.98393
assert r in range(256) assert g in range(256) assert b in range(256) return '38;2;{};{};{}'.format(r, g, b)
def sgr_fg_rgb(r, g, b)
Get SGR (Set Graphics Rendition) foreground RGB color.
2.25831
2.126508
1.061981
assert r in range(256) assert g in range(256) assert b in range(256) return '48;2;{};{};{}'.format(r, g, b)
def sgr_bg_rgb(r, g, b)
Get SGR (Set Graphics Rendition) background RGB color.
2.485525
2.309603
1.076169
sep = kwargs.pop(str('sep'), ' ') end = kwargs.pop(str('end'), '\n') file = kwargs.pop(str('file'), None) or sys.stdout flush = kwargs.pop(str('flush'), False) fg = kwargs.pop(str('fg'), None) bg = kwargs.pop(str('bg'), None) style = kwargs.pop(str('style...
def _aprint2(self, *values, **kwargs)
ANSI formatting-aware print(). This method is a version of print() (function) that understands additional ansi control parameters. :param value: The values to print, same as with ``print()`` :param sep: Separator between values, same as with ``print()`` ...
2.170597
1.91194
1.135285
context.ansi = ANSIFormatter(self._enable) context.aprint = context.ansi.aprint
def added(self, context)
Ingredient method called before anything else.
21.272999
18.244787
1.165977
try: git_log = shell_out(["git", "log"], cwd=cwd) return True except (CalledProcessError, OSError): # pragma: no cover return False
def using_git(cwd)
Test whether the directory cwd is contained in a git repository.
3.839545
4.030849
0.95254
try: hg_log = shell_out(["hg", "log"], cwd=cwd) return True except (CalledProcessError, OSError): return False
def using_hg(cwd)
Test whether the directory cwd is contained in a mercurial repository.
5.297866
6.080935
0.871226
try: bzr_log = shell_out(["bzr", "log"], cwd=cwd) return True except (CalledProcessError, OSError): return False
def using_bzr(cwd)
Test whether the directory cwd is contained in a bazaar repository.
4.063155
4.106669
0.989404
try: # Note: this means all version controls must have # a title naming convention (!) vc = globals()[vc.title()] assert(issubclass(vc, VersionControl)) return vc except (KeyError, AssertionError): raise NotImplementedError...
def from_string(vc)
Return the VersionControl superclass from a string, for example VersionControl.from_string('git') will return Git.
10.004281
7.567654
1.321979
cwd = os.getcwd() for (k, using_vc) in globals().items(): if k.startswith('using_') and using_vc(cwd=cwd): return VersionControl.from_string(k[6:]) # Not supported (yet) raise NotImplementedError("Unknown version control system, " ...
def which(cwd=None): # pragma: no cover if cwd is None
Try to find which version control system contains the cwd directory. Returns the VersionControl superclass e.g. Git, if none were found this will raise a NotImplementedError.
9.036048
7.516462
1.202168
cmd = self.file_diff_cmd(r, file_name) diff = shell_out_ignore_exitcode(cmd, cwd=self.root) return list(self.modified_lines_from_diff(diff))
def modified_lines(self, r, file_name)
Returns the line numbers of a file which have been changed.
5.808535
5.731861
1.013377
from pep8radius.diff import modified_lines_from_udiff for start, end in modified_lines_from_udiff(diff): yield start, end
def modified_lines_from_diff(self, diff)
Returns the changed lines in a diff. - Potentially this is vc specific (if not using udiff). Note: this returns the line numbers in descending order.
7.703022
7.044105
1.093542
cmd = self.filenames_diff_cmd(r) diff_files = shell_out_ignore_exitcode(cmd, cwd=self.root) diff_files = self.parse_diff_filenames(diff_files) return set(f for f in diff_files if f.endswith('.py'))
def get_filenames_diff(self, r)
Get the py files which have been changed since rev.
5.146012
4.770759
1.078657
# ? .gitignore # M 0.txt files = [] for line in diff_files.splitlines(): line = line.strip() fn = re.findall('[^ ]+\s+(.*.py)', line) if fn and not line.startswith('?'): files.append(fn[0]) return files
def parse_diff_filenames(diff_files)
Parse the output of filenames_diff_cmd.
6.365594
6.108716
1.042051
return HttpResponse(self.serialize(obj), content_type='application/json', **response_kwargs)
def render_to_response(self, obj, **response_kwargs)
Returns an ``HttpResponse`` object instance with Content-Type: application/json. The response body will be the return value of ``self.serialize(obj)``
3.486669
2.898229
1.203034
resp = super(JsonResponseMixin, self).http_method_not_allowed(*args, **kwargs) resp['Content-Type'] = 'application/json' return resp
def http_method_not_allowed(self, *args, **kwargs)
Returns super after setting the Content-Type header to ``application/json``
2.906837
2.707996
1.073427
if self.request.method == 'GET': return self.request.GET else: assert self.request.META['CONTENT_TYPE'].startswith('application/json') charset = self.request.encoding or settings.DEFAULT_CHARSET return json.loads(self.request.body.decode(charset))
def data(self)
Helper class for parsing JSON POST data into a Python object.
2.971675
2.543369
1.168401
try: self.auth(*args, **kwargs) return super(RestView, self).dispatch(*args, **kwargs) except ValidationError as e: return self.render_to_response(e.message_dict, status=409) except Http404 as e: return self.render_to_response(str(e), stat...
def dispatch(self, *args, **kwargs)
Authenticates the request and dispatches to the correct HTTP method function (GET, POST, PUT,...). Translates exceptions into proper JSON serialized HTTP responses: - ValidationError: HTTP 409 - Http404: HTTP 404 - PermissionDenied: HTTP 403 - ValueError:...
1.977193
1.620368
1.220212
allow = [] for method in self.http_method_names: if hasattr(self, method): allow.append(method.upper()) r = self.render_to_response(None) r['Allow'] = ','.join(allow) return r
def options(self, request, *args, **kwargs)
Implements a OPTIONS HTTP method function returning all allowed HTTP methods.
3.616464
2.72255
1.328337
import signal try: # pragma: no cover # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: if args is None: args = [] try: ...
def main(args=None, vc=None, cwd=None, apply_config=False)
PEP8 clean only the parts of the files touched since the last commit, a previous commit or branch.
3.614688
3.605041
1.002676
if arguments is None: arguments = [] parser = create_parser() args = parser.parse_args(arguments) if apply_config: parser = apply_config_defaults(parser, args, root=root) args = parser.parse_args(arguments) # sanity check args (from autopep8) if args.max_line_lengt...
def parse_args(arguments=None, root=None, apply_config=False)
Parse the arguments from the CLI. If apply_config then we first look up and apply configs using apply_config_defaults.
2.657733
2.601691
1.021541
if root is None: try: from pep8radius.vcs import VersionControl root = VersionControl.which().root_dir() except NotImplementedError: pass # don't update local, could be using as module config = SafeConfigParser() config.read(args.global_config) ...
def apply_config_defaults(parser, args, root)
Update the parser's defaults from either the arguments' config_arg or the config files given in config_files(root).
6.662893
6.487229
1.027078
result = 0 count = 0 while True: if count > 4: raise ValueError("Corrupt VarInt32") b = self.read_byte() result = result | (b & 0x7F) << (7 * count) count += 1 if not b & 0x80: return result
def read_vint32(self)
This seems to be a variable length integer ala utf-8 style
2.727419
2.470968
1.103785
if read_size: size = self.read_vint32() b = self.read(size) else: b = self.read() if compressed: b = snappy.decompress(b) m = message_type() m.ParseFromString(b) return m
def read_message(self, message_type, compressed=False, read_size=True)
Read a protobuf message
2.656623
2.481751
1.070463
if packet.__class__ in self.internal_hooks: self.internal_hooks[packet.__class__](packet) if packet.__class__ in self.hooks: self.hooks[packet.__class__](packet)
def run_hooks(self, packet)
Run any additional functions that want to process this type of packet. These can be internal parser hooks, or external hooks that process information
2.488508
2.605352
0.955152
self.info("String table: %s" % (tables.tables, )) for table in tables.tables: if table.table_name == "userinfo": for item in table.items: if len(item.data) > 0: if len(item.data) == 140: p = Pla...
def parse_string_table(self, tables)
Need to pull out player information from string table
4.370961
4.233561
1.032455
if event.eventid in self.event_lookup: #Bash this into a nicer data format to work with event_type = self.event_lookup[event.eventid] ge = GameEvent(event_type.name) for i, key in enumerate(event.keys): key_type = event_type.keys[i] ...
def parse_game_event(self, event)
So CSVCMsg_GameEventList is a list of all events that can happen. A game event has an eventid which maps to a type of event that happened
6.413719
6.199604
1.034537
self.important("Parsing demo file '%s'" % (self.filename, )) with open(self.filename, 'rb') as f: reader = Reader(StringIO(f.read())) filestamp = reader.read(8) offset = reader.read_int32() if filestamp != "PBUFDEM\x00": raise ...
def parse(self)
Parse a replay
4.960016
4.667573
1.062654
try: st = basestring except NameError: st = str if isinstance(data, st): return str(data) elif isinstance(data, Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, Iterable): return type(data)(map(convert, data)) else: ...
def convert(data)
Convert from unicode to native ascii
2.140336
2.041607
1.048359