code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
kwargs = self.prepare_request(method, url, data) log.debug(json.dumps(kwargs)) response = getattr(requests, method.lower())(url, **kwargs) log.debug(json.dumps(response.content)) if response.status_code >= 400: response.raise_for_status() if (expected...
def fetch(self, method, url, data=None, expected_status_code=None)
Prepare the headers, encode data, call API and provide data it returns
2.618915
2.634071
0.994246
return self.fetch(method, url, data, expected_status_code).json()
def fetch_json(self, method, url, data=None, expected_status_code=None)
Return json decoded data from fetch
3.791206
3.122248
1.214255
r @wraps(minimizer) def new_minimizer(fun, parameters, jac=True, args=(), nstarts=0, random_state=None, **minimizer_kwargs): (array1d, fbounds), shapes = flatten( parameters, hstack=bt.hstack, shape=bt.shape, ravel=partial(bt.rav...
def structured_minimizer(minimizer)
r""" Allow an optimizer to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally evaluate *random starts* (i.e. random star...
3.91341
3.653116
1.071253
r @wraps(minimizer) def new_minimizer(fun, x0, jac=True, bounds=None, **minimizer_kwargs): if bounds is None: return minimizer(fun, x0, jac=jac, bounds=bounds, **minimizer_kwargs) logx, expx, gradx, bounds = _logtrick_gen(bounds) # Intercep...
def logtrick_minimizer(minimizer)
r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from scipy.optimize import minimize as sp_min >>> from ....
2.665253
2.700365
0.986997
r @wraps(sgd) def new_sgd(fun, x0, data, bounds=None, eval_obj=False, **sgd_kwargs): if bounds is None: return sgd(fun, x0, data, bounds=bounds, eval_obj=eval_obj, **sgd_kwargs) logx, expx, gradx, bounds = _logtrick_gen(bounds) if bool(eval_obj):...
def logtrick_sgd(sgd)
r""" Log-Trick decorator for stochastic gradients. This decorator implements the "log trick" for optimizing positive bounded variables using SGD. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from ..optimize import sgd >>> from ...
2.963675
2.809744
1.054785
r @wraps(func) def new_func(*args, **kwargs): return flatten(func(*args, **kwargs), returns_shapes=False) return new_func
def flatten_grad(func)
r""" Decorator to flatten structured gradients. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return lambda_ * w, .5 * sq_norm >>> grad = cost(np.array([.5, .1, -.2]), .25) >>> len(grad) 2 >>> grad_w, grad_lambda = grad >>> np.shape(grad_w...
5.500214
9.416262
0.584119
r @wraps(func) def new_func(*args, **kwargs): val, grad = func(*args, **kwargs) return val, flatten(grad, returns_shapes=False) return new_func
def flatten_func_grad(func)
r""" Decorator to flatten structured gradients and return objective. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return .5 * lambda_ * sq_norm, [lambda_ * w, .5 * sq_norm] >>> val, grad = cost(np.array([.5, .1, -.2]), .25) >>> np.isclose(val, 0.0375...
4.640518
6.829195
0.679512
r def flatten_args_dec(func): @wraps(func) def new_func(array1d, *args, **kwargs): args = tuple(unflatten(array1d, shapes)) + args return func(*args, **kwargs) return new_func return flatten_args_dec
def flatten_args(shapes)
r""" Decorator to flatten structured arguments to a function. Examples -------- >>> @flatten_args([(5,), ()]) ... def f(w, lambda_): ... return .5 * lambda_ * w.T.dot(w) >>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546) True >>> w = np.array([2., .5, .6, -.2, .9]) ...
3.705127
3.794276
0.976504
if nstarts < 1: raise ValueError("nstarts has to be greater than or equal to 1") # Check to see if there are any random parameter types anyrand = any(flatten(map_recursive(lambda p: p.is_random, parameters), returns_shapes=False)) if not anyrand: log.info("No ran...
def _random_starts(fun, parameters, jac, args, nstarts, random_state, data_gen=None)
Generate and evaluate random starts for Parameter objects.
4.530889
4.432047
1.022302
# Test which parameters we can apply the log trick too ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool) nispos = ~ispos # Functions that implement the log trick def logx(x): xwarp = np.empty_like(x) xwarp[ispos] = np.log(x[ispos]) xwarp[nispos]...
def _logtrick_gen(bounds)
Generate warping functions and new bounds for the log trick.
2.985235
2.935066
1.017093
if '_bare' in opts: _copts = [] del opts['_bare'] else: _copts = ['-c', 'core.quotepath=false', ] safe_call = False if '_safe' in opts: #no exc on failure del opts['_safe'] safe_call = True _str_cm...
def _run_git_command(cls, cmd, **opts)
Runs given ``cmd`` as git command and returns tuple (stdout, stderr). :param cmd: git command to be executed :param opts: env options to pass into Subprocess command
4.191296
4.05029
1.034814
# check first if it's not an local url if os.path.isdir(url) or url.startswith('file:'): return True if('+' in url[:url.find('://')]): url = url[url.find('+') + 1:] handlers = [] test_uri, authinfo = hg_url(url).authinfo() if not test_u...
def _check_url(cls, url)
Functon will check given url and try to verify if it's a valid link. Sometimes it may happened that mercurial will issue basic auth request that can cause whole API to hang when used from python or other external calls. On failures it'll raise urllib2.HTTPError
4.665029
4.358642
1.070294
is_null = lambda o: len(o) == revision.count('0') try: self.revisions[0] except (KeyError, IndexError): raise EmptyRepositoryError("There are no changesets yet") if revision in (None, '', 'tip', 'HEAD', 'head', -1): return self.revisions[-1...
def _get_revision(self, revision)
For git backend we always return integer here. This way we ensure that changset's revision attribute would become integer.
4.462111
4.316652
1.033697
url = str(url) if url != 'default' and not '://' in url: url = ':///'.join(('file', url)) return url
def _get_url(self, url)
Returns normalized url. If schema is not given, would fall to filesystem (``file:///``) schema.
6.209154
4.709094
1.318545
loc = os.path.join(self.path, 'hooks') if not self.bare: loc = os.path.join(self.path, '.git', 'hooks') return loc
def get_hook_location(self)
returns absolute path to location where hooks are stored
3.546262
3.071725
1.154486
if name in self.tags: raise TagAlreadyExistError("Tag %s already exists" % name) changeset = self.get_changeset(revision) message = message or "Added tag %s for commit %s" % (name, changeset.raw_id) self._repo.refs["refs/tags/%s" % name] = changeset._comm...
def tag(self, name, user, revision=None, message=None, date=None, **kwargs)
Creates and returns a tag for the given ``revision``. :param name: name for new tag :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param revision: changeset id for which new tag would be created :param message: message of the tag's commit :param date: date of...
4.271622
4.289599
0.995809
if name not in self.tags: raise TagDoesNotExistError("Tag %s does not exist" % name) tagpath = posixpath.join(self._repo.refs.path, 'refs', 'tags', name) try: os.remove(tagpath) self._parsed_refs = self._get_parsed_refs() self.tags = self....
def remove_tag(self, name, user, message=None, date=None)
Removes tag with the given ``name``. :param name: name of the tag to be removed :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param message: message of the tag's removal commit :param date: date of tag's removal commit :raises TagDoesNotExistError: if tag w...
3.327229
3.681502
0.90377
if isinstance(revision, GitChangeset): return revision revision = self._get_revision(revision) changeset = GitChangeset(repository=self, revision=revision) return changeset
def get_changeset(self, revision=None)
Returns ``GitChangeset`` object representing commit from git repository at the given revision or head (most recent commit) if None given.
3.675253
3.032042
1.212138
if branch_name and branch_name not in self.branches: raise BranchDoesNotExistError("Branch '%s' not found" \ % branch_name) # %H at format means (full) commit hash, initial hashes are retrieved # in ascending date order cmd_t...
def get_changesets(self, start=None, end=None, start_date=None, end_date=None, branch_name=None, reverse=False)
Returns iterator of ``GitChangeset`` objects from start to end (both are inclusive), in ascending date order (unless ``reverse`` is set). :param start: changeset ID, as str; first returned changeset :param end: changeset ID, as str; last returned changeset :param start_date: if specifie...
2.725171
2.761125
0.986979
flags = ['-U%s' % context, '--full-index', '--binary', '-p', '-M', '--abbrev=40'] if ignore_whitespace: flags.append('-w') if hasattr(rev1, 'raw_id'): rev1 = getattr(rev1, 'raw_id') if hasattr(rev2, 'raw_id'): rev2 = getattr(rev2, 'raw_id') ...
def get_diff(self, rev1, rev2, path=None, ignore_whitespace=False, context=3)
Returns (git like) *diff*, as plain text. Shows changes introduced by ``rev2`` since ``rev1``. :param rev1: Entry point from which diff is shown. Can be ``self.EMPTY_CHANGESET`` - in this case, patch showing all the changes since empty state of the repository until ``rev2`` ...
2.852471
2.859201
0.997646
url = self._get_url(url) cmd = ['clone'] if bare: cmd.append('--bare') elif not update_after_clone: cmd.append('--no-checkout') cmd += ['--', '"%s"' % url, '"%s"' % self.path] cmd = ' '.join(cmd) # If error occurs run_git_command r...
def clone(self, url, update_after_clone=True, bare=False)
Tries to clone changes from external location. :param update_after_clone: If set to ``False``, git won't checkout working directory :param bare: If set to ``True``, repository would be cloned into *bare* git repository (no working directory at all).
3.927637
4.100581
0.957825
url = self._get_url(url) cmd = ['pull'] cmd.append("--ff-only") cmd.append(url) cmd = ' '.join(cmd) # If error occurs run_git_command raises RepositoryError already self.run_git_command(cmd)
def pull(self, url)
Tries to pull changes from external location.
6.762126
6.094255
1.10959
url = self._get_url(url) so, se = self.run_git_command('ls-remote -h %s' % url) refs = [] for line in (x for x in so.splitlines()): sha, ref = line.split('\t') refs.append(ref) refs = ' '.join(('+%s:%s' % (r, r) for r in refs)) cmd = '''fe...
def fetch(self, url)
Tries to pull changes from external location.
3.804871
3.588902
1.060177
if config_file is None: config_file = [] elif isinstance(config_file, basestring): config_file = [config_file] def gen_configs(): for path in config_file + self._config_files: try: yield ConfigFile.from_path(path) ...
def get_config_value(self, section, name, config_file=None)
Returns configuration value for a given [``section``] and ``name``. :param section: Section we want to retrieve value from :param name: Name of configuration we want to retrieve :param config_file: A path to file which should be used to retrieve configuration from (might also be a lis...
2.573159
2.674343
0.962165
options['linenos'] = True formatter = AnnotateHtmlFormatter(filenode=filenode, order=order, headers=headers, annotate_from_changeset_func=annotate_from_changeset_func, **options) lexer = filenode.lexer highlighted = highlight(filenode.content, lexer, formatter) return highlighte...
def annotate_highlight(filenode, annotate_from_changeset_func=None, order=None, headers=None, **options)
Returns html portion containing annotated table with 3 columns: line numbers, changeset information and pygmentized line of code. :param filenode: FileNode object :param annotate_from_changeset_func: function taking changeset and returning single annotate cell; needs break line at the end :param ...
3.274298
4.811938
0.680453
if self.annotate_from_changeset_func: return self.annotate_from_changeset_func(changeset) else: return ''.join((changeset.id, '\n'))
def annotate_from_changeset(self, changeset)
Returns full html line for single changeset per annotated line.
3.415842
2.97263
1.149098
dummyoutfile = StringIO.StringIO() lncount = 0 for t, line in inner: if t: lncount += 1 dummyoutfile.write(line) fl = self.linenostart mw = len(str(lncount + fl - 1)) sp = self.linenospecial st = self.linenostep la ...
def _wrap_tablelinenos(self, inner)
yield 0, ('<table class="%stable">' % self.cssclass + '<tr><td class="linenos"><div class="linenodiv"><pre>' + ls + '</pre></div></td>' + '<td class="code">') yield 0, dummyoutfile.getvalue() yield 0, '</td></tr></table>'
3.017622
2.70735
1.114604
if self._has_lock(): return lock_file = self._lock_file_path() if os.path.isfile(lock_file): raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file)) try: fd = os.open(lock_file...
def _obtain_lock_or_raise(self)
Create a lock file as flag for other instances, mark our instance as lock-holder :raise IOError: if a lock was already present or a lock file could not be written
3.10579
2.966484
1.04696
if not self._has_lock(): return # if someone removed our file beforhand, lets just flag this issue # instead of failing, to make it more usable. lfp = self._lock_file_path() try: # on bloody windows, the file needs write permissions to be removab...
def _release_lock(self)
Release our lock if we have one
8.323697
7.9028
1.053259
'''Prepends the http:// scheme if necessary to a url. Fails if a scheme other than http is used''' splitted = url.split('://') if len(splitted) == 2: if splitted[0] in ('http', 'https'): return url else: raise exc.WileECoyoteException( 'Bad scheme!...
def fix_scheme(url)
Prepends the http:// scheme if necessary to a url. Fails if a scheme other than http is used
5.345177
3.831647
1.395007
'''Turns the arguments to __getitem__ magic methods into a uniform list of tuples and strings ''' if not isinstance(args, tuple): args = (args,) return_val = [] for arg in args: if isinstance(arg, six.string_types + (int, )): return_val.append(arg) elif isinst...
def normalize_getitem_args(args)
Turns the arguments to __getitem__ magic methods into a uniform list of tuples and strings
3.729724
2.606888
1.430719
'''Turns a root uri into a less noisy representation that will probably make sense in most circumstances. Used by Navigator's __repr__, but can be overridden if the Navigator is created with a 'name' parameter.''' root_uri = unidecode.unidecode(decode(unquote(root_uri), 'utf-8')) generic_domains =...
def namify(root_uri)
Turns a root uri into a less noisy representation that will probably make sense in most circumstances. Used by Navigator's __repr__, but can be overridden if the Navigator is created with a 'name' parameter.
3.72282
3.064802
1.214702
'''Converts uris from path syntax to a json-like object syntax. In addition, url escaped characters are unescaped, but non-ascii characters a romanized using the unidecode library. Examples: "/blog/3/comments" becomes "blog[3].comments" "car/engine/piston" becomes "car.engine.piston" ...
def objectify_uri(relative_uri)
Converts uris from path syntax to a json-like object syntax. In addition, url escaped characters are unescaped, but non-ascii characters a romanized using the unidecode library. Examples: "/blog/3/comments" becomes "blog[3].comments" "car/engine/piston" becomes "car.engine.piston"
5.401154
2.329609
2.318481
'''Returns type, subtype, parameter tuple from an http media_type. Can be applied to the 'Accept' or 'Content-Type' http header fields. ''' media_type, sep, parameter = str(media_type).partition(';') media_type, sep, subtype = media_type.partition('/') return tuple(x.strip() or None for x in (me...
def parse_media_type(media_type)
Returns type, subtype, parameter tuple from an http media_type. Can be applied to the 'Accept' or 'Content-Type' http header fields.
4.494919
2.258123
1.990555
'''Gets a value nested in dictionaries containing dictionaries. Returns the default if any key in the path doesn't exist. ''' for key in json_path.split(sep): try: d = d[key] except (KeyError, TypeError): return default return d
def getpath(d, json_path, default=None, sep='.')
Gets a value nested in dictionaries containing dictionaries. Returns the default if any key in the path doesn't exist.
4.37073
2.035301
2.147461
'''Deep copies a dict, and returns it without the keys _links and _embedded ''' if not isinstance(d, dict): raise TypeError("Can only get the state of a dictionary") cpd = copy.deepcopy(d) cpd.pop('_links', None) cpd.pop('_embedded', None) return cpd
def getstate(d)
Deep copies a dict, and returns it without the keys _links and _embedded
5.026328
2.617667
1.920156
'''Add an item to the dictionary with the given metadata properties''' for prop, val in properties.items(): val = self.serialize(val) self._meta.setdefault(prop, {}).setdefault(val, []).append(obj) self.append(obj)
def append_with(self, obj, **properties)
Add an item to the dictionary with the given metadata properties
5.6783
4.26238
1.33219
'''Retrieve an item from the dictionary with the given metadata properties. If there is no such item, None will be returned, if there are multiple such items, the first will be returned.''' try: val = self.serialize(val) return self._meta[prop][val][0] exc...
def get_by(self, prop, val, raise_exc=False)
Retrieve an item from the dictionary with the given metadata properties. If there is no such item, None will be returned, if there are multiple such items, the first will be returned.
4.973861
2.47493
2.009698
'''Retrieves all items from the dictionary with the given metadata''' try: val = self.serialize(val) return self._meta[prop][val][:] # return a copy of the list except KeyError: return []
def getall_by(self, prop, val)
Retrieves all items from the dictionary with the given metadata
8.162983
6.191827
1.318348
'''Returns .get_by('name', name)''' name = self.serialize(name) return self.get_by('name', name)
def named(self, name)
Returns .get_by('name', name)
8.060869
3.82247
2.108812
for key, dataset in data.items(): data[key] = dict( (k.replace(old, new), v) for k, v in dataset.items() )
def do_replace_state_separator(data, old, new)
Replace state separator. Parameters ---------- data : `dict` of `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Data. old : `str` Old separator. new : `str` New separator.
3.039786
3.425264
0.88746
if data is None: return None try: return data[key] except KeyError: if create: dataset = {} data[key] = dataset return dataset else: raise
def do_get_dataset(data, key, create=False)
Get a dataset. Parameters ---------- data : `None` or `dict` of `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Data. key : `str` Dataset key. create : `bool`, optional Create a dataset if it does not exist. Returns ...
2.458396
3.21285
0.765176
try: node = dataset[source] values, links = node if isinstance(links, list): try: idx = links.index(target) values[idx] += count except ValueError: links.append(target) ...
def add_link(dataset, source, target, count=1)
Add a link. Parameters ---------- dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Dataset. source : `iterable` of `str` Link source. target : `str` Link target. count : `int`, optional Link count ...
2.736849
2.791075
0.980572
if backward and self.backward is None: raise ValueError('no backward nodes') try: node = dataset[int(backward)][self.join_state(state)] if not isinstance(node[0], list): return [(node[0], node[1])] return list(zip(*node)) e...
def get_links(self, dataset, state, backward=False)
Raises ------ ValueError If backward == `True` and self.backward is `None`.
5.695489
5.158
1.104205
if fp is None: fp = sys.stdout data = { 'settings': self.settings, 'nodes': self.nodes, 'backward': self.backward } json.dump(data, fp, ensure_ascii=False)
def do_save(self, fp=None)
Save to file. Parameters ---------- fp : `file` or `str`, optional Output file (default: stdout).
3.319719
4.035065
0.822718
if not users or not isinstance(exclude_user, get_user_model()): return '' return truncatechars( ', '.join(u'{}'.format(u) for u in users.exclude(pk=exclude_user.pk)), truncate)
def chain_user_names(users, exclude_user, truncate=35)
Tag to return a truncated chain of user names.
3.69349
3.512126
1.051639
return urlunparse((self.protocol, '%s:%s' % (self.domain, self.port), '%s/api/v1%s' % (self.prefix, URLS[key]), '', '', ''))
def url(self, key)
Creates a full URL to the API using urls dict
4.405302
4.179226
1.054095
response = self.get_manifest_validation_result(manifest_id) if response.status_code != 200: raise Exception(response.status_code) content = json.loads(response.content) if not content['processed']: return None if content['valid']: retu...
def is_manifest_valid(self, manifest_id)
Check validation shortcut :param: manifest_id (string) id received in :method:`validate_manifest` :returns: * True if manifest was valid * None if manifest wasn't checked yet * validation dict if not valid
3.408678
3.033674
1.123614
assert ('name' in data and data['name'] and 'summary' in data and 'categories' in data and data['categories'] and 'support_email' in data and data['support_email'] and 'device_types' in data ...
def update(self, app_id, data)
Update app identified by app_id with data :params: * app_id (int) id in the marketplace received with :method:`create` * data (dict) some keys are required: * *name*: the title of the app. Maximum length 127 characters. * *summary*: the ...
3.142799
2.425178
1.295904
# prepare file for upload with open(filename, 'rb') as s_file: s_content = s_file.read() s_encoded = b64encode(s_content) url = self.url('create_screenshot') % app_id mtype, encoding = mimetypes.guess_type(filename) if mtype is None: mtyp...
def create_screenshot(self, app_id, filename, position=1)
Add a screenshot to the web app identified by by ``app_id``. Screenshots are ordered by ``position``. :returns: HttpResponse: * status_code (int) 201 is successful * content (dict) containing screenshot data
3.53782
3.682532
0.960703
url = self.url('content_ratings') % app_id return self.conn.fetch('POST', url, {'submission_id': '%s' % submission_id, 'security_code': '%s' % security_code })
def add_content_ratings(self, app_id, submission_id, security_code)
Add content ratings to the web app identified by by ``app_id``, using the specified submission id and security code. :returns: HttpResponse: * status_code (int) 201 is successful
3.981648
4.91997
0.809283
assert status is not None or disabled_by_user is not None data = {} if status: data['status'] = status if disabled_by_user: data['disabled_by_user'] = disabled_by_user return self.conn.fetch('PATCH', self.url('enable') % app_id, data)
def app_state(self, app_id, status=None, disabled_by_user=None)
Once all the data has been completed and at least one screenshot created, you can push the app to the review queue status (optional): key statuses are incomplete: incomplete pending: pending public: public waiting: waiting to be public disabled_b...
3.130283
4.70114
0.665856
module = imp.new_module(name) module.__file__ = path execfile(path, module.__dict__) return module
def create_module(name, path)
Returns module created *on the fly*. Returned module would have name same as given ``name`` and would contain code read from file at the given ``path`` (it may also be a zip or package containing *__main__* module).
2.23604
2.429749
0.920276
if not self.end_chars: yield from data self.start = self.start or bool(data) self.end = False else: for char in data: if char in self.end_chars: if not self.start: continue ...
def scan(self, data, part)
Scan a string. Parameters ---------- data : `str` String to scan. part : `bool` True if data is partial. Returns ------- `generator` of (`str` or `markovchain.scanner.Scanner.END`) Token generator.
3.3774
3.075284
1.09824
data = super().save() data['end_chars'] = self.end_chars data['default_end'] = self.default_end return data
def save(self)
Convert to JSON. Returns ------- `dict` JSON data.
5.197165
6.242689
0.83252
if not self.expr.groups: for match in self.expr.finditer(data): yield match.group() self.end = self.end and not bool(data) else: for match in self.expr.finditer(data): group = self.get_group(match, 'end') if gr...
def scan(self, data, part)
Scan a string. Parameters ---------- data : `str` String to scan. part : `bool` `True` if data is partial. Returns ------- `generator` of (`str` or `markovchain.scanner.Scanner.END`) Token generator.
3.195193
2.924736
1.092472
data = super().save() data['expr'] = self.expr.pattern data['default_end'] = self.default_end return data
def save(self)
Convert the scanner to JSON. Returns ------- `dict` JSON data.
7.404373
8.10089
0.91402
splitted = class_path.split('.') mod_path = '.'.join(splitted[:-1]) class_name = splitted[-1] try: class_mod = __import__(mod_path, {}, {}, [class_name]) except ImportError, err: msg = "There was problem while trying to import backend class. "\ "Original error was:\n...
def import_class(class_path)
Returns class from the given path. For example, in order to get class located at ``vcs.backends.hg.MercurialRepository``: try: hgrepo = import_class('vcs.backends.hg.MercurialRepository') except VCSError: # hadle error
2.998273
2.653837
1.129788
if self._empty: return {} def _branchtags(localrepo): bt = {} bt_closed = {} for bn, heads in localrepo.branchmap().iteritems(): tip = heads[-1] if 'close' in localrepo.changelog.read(tip)[5]: ...
def _get_branches(self, closed=False)
Get's branches for this repository Returns only not closed branches by default :param closed: return also closed branches for mercurial
5.476181
5.30941
1.031411
if name in self.tags: raise TagAlreadyExistError("Tag %s already exists" % name) changeset = self.get_changeset(revision) local = kwargs.setdefault('local', False) if message is None: message = "Added tag %s for changeset %s" % (name, cha...
def tag(self, name, user, revision=None, message=None, date=None, **kwargs)
Creates and returns a tag for the given ``revision``. :param name: name for new tag :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param revision: changeset id for which new tag would be created :param message: message of the tag's commit :param date: date of...
3.659829
3.862476
0.947534
if name not in self.tags: raise TagDoesNotExistError("Tag %s does not exist" % name) if message is None: message = "Removed tag %s" % name if date is None: date = datetime.datetime.now().ctime() local = False try: self._re...
def remove_tag(self, name, user, message=None, date=None)
Removes tag with the given ``name``. :param name: name of the tag to be removed :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param message: message of the tag's removal commit :param date: date of tag's removal commit :raises TagDoesNotExistError: if tag w...
3.812964
3.794458
1.004877
if hasattr(rev1, 'raw_id'): rev1 = getattr(rev1, 'raw_id') if hasattr(rev2, 'raw_id'): rev2 = getattr(rev2, 'raw_id') # Check if given revisions are present at repository (may raise # ChangesetDoesNotExistError) if rev1 != self.EMPTY_CHANGESET: ...
def get_diff(self, rev1, rev2, path='', ignore_whitespace=False, context=3)
Returns (git like) *diff*, as plain text. Shows changes introduced by ``rev2`` since ``rev1``. :param rev1: Entry point from which diff is shown. Can be ``self.EMPTY_CHANGESET`` - in this case, patch showing all the changes since empty state of the repository until ``rev2`` ...
4.507027
4.102587
1.098582
try: if src_url: url = str(self._get_url(src_url)) opts = {} if not update_after_clone: opts.update({'noupdate': True}) try: MercurialRepository._check_url(url) clone...
def _get_repo(self, create, src_url=None, update_after_clone=False)
Function will check for mercurial repository in given path and return a localrepo object. If there is no repository in that path it will raise an exception unless ``create`` parameter is set to True - in that case repository would be created and returned. If ``src_url`` is given, would t...
4.281897
4.10322
1.043546
if self._empty: raise EmptyRepositoryError("There are no changesets yet") if revision in [-1, 'tip', None]: revision = 'tip' try: revision = hex(self._repo.lookup(revision)) except (IndexError, ValueError, RepoLookupError, TypeError): ...
def _get_revision(self, revision)
Get's an ID revision given as str. This will always return a fill 40 char revision number :param revision: str or int or None
5.785794
6.318064
0.915754
url = str(url) if url != 'default' and not '://' in url: url = "file:" + urllib.pathname2url(url) return url
def _get_url(self, url)
Returns normalized url. If schema is not given, would fall to filesystem (``file:///``) schema.
4.9419
4.365955
1.131917
revision = self._get_revision(revision) changeset = MercurialChangeset(repository=self, revision=revision) return changeset
def get_changeset(self, revision=None)
Returns ``MercurialChangeset`` object representing repository's changeset at the given ``revision``.
4.416175
3.725262
1.185467
start_raw_id = self._get_revision(start) start_pos = self.revisions.index(start_raw_id) if start else None end_raw_id = self._get_revision(end) end_pos = self.revisions.index(end_raw_id) if end else None if None not in [start, end] and start_pos > end_pos: ...
def get_changesets(self, start=None, end=None, start_date=None, end_date=None, branch_name=None, reverse=False)
Returns iterator of ``MercurialChangeset`` objects from start to end (both are inclusive) :param start: None, str, int or mercurial lookup format :param end: None, str, int or mercurial lookup format :param start_date: :param end_date: :param branch_name: :param...
2.693846
2.741898
0.982475
url = self._get_url(url) try: pull(self.baseui, self._repo, url) except Abort, err: # Propagate error but with vcs's type raise RepositoryError(str(err))
def pull(self, url)
Tries to pull changes from external location.
11.580305
10.487802
1.104169
if config_file is None: config_file = [] elif isinstance(config_file, basestring): config_file = [config_file] config = self._repo.ui for path in config_file: config.readconfig(path) return config.config(section, name)
def get_config_value(self, section, name=None, config_file=None)
Returns configuration value for a given [``section``] and ``name``. :param section: Section we want to retrieve value from :param name: Name of configuration we want to retrieve :param config_file: A path to file which should be used to retrieve configuration from (might also be a lis...
3.705297
3.773117
0.982025
return super().data(data, part)
def data(self, data, part=False, dataset='')
Parameters ---------- data : `str` Text to parse. part : `bool`, optional True if data is partial (default: `False`). dataset : `str`, optional Dataset key prefix (default: '').
14.280519
23.202492
0.615473
text = self.storage.state_separator.join(parts) return self.formatter(text)
def format(self, parts)
Format generated text. Parameters ---------- parts : `iterable` of `str` Text parts.
12.74796
19.093555
0.667658
if string is None: return () for _ in self.parser(self.scanner(string, True), True): if backward and len(self.parser.state[0]): break state = tuple(self.parser.state) self.scanner.reset() self.parser.reset() return state
def get_cont_state(self, string, backward=False)
Get initial states from input string. Parameters ---------- string : `str` or `None` backward : `bool` Returns ------- `tuple` of `str`
5.61716
6.296217
0.892148
words = get_words(string) if not words: return [] long_word = 4 long_words = [word for word in words if len(word) >= long_word] short_words = [word for word in words if len(word) < long_word] for words in (long_words, short_words): ret = [...
def get_reply_states(self, string, dataset)
Get initial states from input string. Parameters ---------- string : `str` Input string. dataset : `str` Dataset key. Returns ------- `list` of `list` of `str`
2.74921
3.211022
0.856179
state = self.get_cont_state(reply_to, backward) while True: parts = self.generate(state_size, state, dataset, backward) if reply_to is not None: if backward: parts = chain(reversed(list(parts)), (reply_to,)) else: ...
def generate_cont(self, max_length, state_size, reply_to, backward, dataset)
Generate texts from start/end. Parameters ---------- max_length : `int` or `None` Maximum sentence length. state_size : `int` State size. reply_to : `str` or `None` Input string. backward : `bool` `True` to generate text st...
3.207439
3.60518
0.889675
state_sets = self.get_reply_states( reply_to, dataset + state_size_dataset(state_size) ) if not state_sets: yield from self.generate_cont(max_length, state_size, None, False, dataset) return ...
def generate_replies(self, max_length, state_size, reply_to, dataset)
Generate replies. Parameters ---------- max_length : `int` or `None` Maximum sentence length. state_size : `int` State size. reply_to : `str` Input string. dataset: `str` Dataset key prefix. Returns -------...
4.666741
5.037701
0.926363
size = 0 try: tip = self.get_changeset() for topnode, dirs, files in tip.walk('/'): for f in files: size += tip.get_file_size(f.path) for dir in dirs: for f in files: size +=...
def size(self)
Returns combined size in bytes for all repository files
5.451792
4.195097
1.299563
raise NotImplementedError
def get_changesets(self, start=None, end=None, start_date=None, end_date=None, branch_name=None, reverse=False)
Returns iterator of ``MercurialChangeset`` objects from start to end not inclusive This should behave just like a list, ie. end is not inclusive :param start: None or str :param end: None or str :param start_date: :param end_date: :param branch_name: :par...
686.450256
3,672.243896
0.186929
chunk_size = kwargs.pop('chunk_size', 8192) stream = kwargs.get('stream') self.fill_archive(**kwargs) while True: data = stream.read(chunk_size) if not data: break yield data
def get_chunked_archive(self, **kwargs)
Returns iterable archive. Tiny wrapper around ``fill_archive`` method. :param chunk_size: extra parameter which controls size of returned chunks. Default:8k.
3.297201
2.599182
1.268553
topnode = self.get_node(topurl) yield (topnode, topnode.dirs, topnode.files) for dirnode in topnode.dirs: for tup in self.walk(dirnode.path): yield tup
def walk(self, topurl='')
Similar to os.walk method. Insted of filesystem it walks through changeset starting at given ``topurl``. Returns generator of tuples (topnode, dirnodes, filenodes).
3.630747
2.867672
1.266095
for topnode, dirs, files in self.walk(): for node in files: yield node
def get_filenodes_generator(self)
Returns generator that yields *all* file nodes.
8.409617
5.484448
1.533357
data = get_dict_for_attrs(self, ['id', 'raw_id', 'short_id', 'revision', 'date', 'message']) data['author'] = {'name': self.author_name, 'email': self.author_email} data['added'] = [node.path for node in self.added] data['changed'] = [node.path for node in self.chang...
def as_dict(self)
Returns dictionary with changeset's attributes and their values.
3.306661
2.755163
1.200169
# Check if not already marked as *added* first for node in filenodes: if node.path in (n.path for n in self.added): raise NodeAlreadyAddedError("Such FileNode %s is already " "marked for addition" % node.path) for node in filenodes: ...
def add(self, *filenodes)
Marks given ``FileNode`` objects as *to be committed*. :raises ``NodeAlreadyExistsError``: if node with same path exists at latest changeset :raises ``NodeAlreadyAddedError``: if node with same path is already marked as *added*
4.963985
3.757024
1.321255
for node in filenodes: if node.path in (n.path for n in self.removed): raise NodeAlreadyRemovedError("Node at %s is already marked " "as removed" % node.path) try: self.repository.get_changeset() except EmptyRepositoryError: ...
def change(self, *filenodes)
Marks given ``FileNode`` objects to be *changed* in next commit. :raises ``EmptyRepositoryError``: if there are no changesets yet :raises ``NodeAlreadyExistsError``: if node with same path is already marked to be *changed* :raises ``NodeAlreadyRemovedError``: if node with same path is...
3.599171
3.029698
1.187964
for node in filenodes: if node.path in (n.path for n in self.removed): raise NodeAlreadyRemovedError("Node is already marked to " "for removal at %s" % node.path) if node.path in (n.path for n in self.changed): raise NodeAlread...
def remove(self, *filenodes)
Marks given ``FileNode`` (or ``RemovedFileNode``) objects to be *removed* in next commit. :raises ``NodeAlreadyRemovedError``: if node has been already marked to be *removed* :raises ``NodeAlreadyChangedError``: if node has been already marked to be *changed*
3.837432
3.059023
1.254463
self.added = [] self.changed = [] self.removed = [] self.parents = []
def reset(self)
Resets this instance to initial state (cleans ``added``, ``changed`` and ``removed`` lists).
6.251056
3.430099
1.822412
for node in itertools.chain(self.added, self.changed, self.removed): yield node.path
def get_ipaths(self)
Returns generator of paths from nodes marked as added, changed or removed.
7.745381
3.314392
2.336894
if not self.parents: parents = parents or [] if len(parents) == 0: try: parents = [self.repository.get_changeset(), None] except EmptyRepositoryError: parents = [None, None] elif len(parents) == ...
def check_integrity(self, parents=None)
Checks in-memory changeset's integrity. Also, sets parents if not already set. :raises CommitError: if any error occurs (i.e. ``NodeDoesNotExistError``).
2.665742
2.645895
1.007501
return [self.repository.get_changeset(parent) for parent in self._commit.parents]
def parents(self)
Returns list of parents changesets.
10.325523
5.197199
1.986748
rev_filter = settings.GIT_REV_FILTER cmd = "rev-list %s --children | grep '^%s'" % (rev_filter, self.raw_id) so, se = self.repository.run_git_command(cmd) children = [] for l in so.splitlines(): childs = l.split(' ')[1:] children.extend(childs) ...
def children(self)
Returns list of children changesets.
4.955737
4.21919
1.174571
id = self._get_id_for_path(path) blob = self.repository._repo[id] return blob.as_pretty_string()
def get_file_content(self, path)
Returns content of the file at given ``path``.
8.32136
8.024941
1.036937
id = self._get_id_for_path(path) blob = self.repository._repo[id] return blob.raw_length()
def get_file_size(self, path)
Returns size of the file at given ``path``.
8.318588
7.519321
1.106295
self._get_filectx(path) cs_id = safe_str(self.id) f_path = safe_str(path) if limit: cmd = 'log -n %s --pretty="format: %%H" -s -p %s -- "%s"' % ( safe_int(limit, 0), cs_id, f_path ) else: cmd = 'log --pre...
def get_file_history(self, path, limit=None)
Returns history of file as reversed list of ``Changeset`` objects for which file at given ``path`` has been modified. TODO: This function now uses os underlying 'git' and 'grep' commands which is generally not good. Should be replaced with algorithm iterating commits.
4.112751
3.658765
1.124082
self._get_filectx(path) from dulwich.walk import Walker include = [self.id] walker = Walker(self.repository._repo.object_store, include, paths=[path], max_entries=1) return [self.repository.get_changeset(sha) for sha in (x.commit.i...
def get_file_history_2(self, path)
Returns history of file as reversed list of ``Changeset`` objects for which file at given ``path`` has been modified.
5.652222
5.313564
1.063735
cmd = 'blame -l --root -r %s -- "%s"' % (self.id, path) # -l ==> outputs long shas (and we need all 40 characters) # --root ==> doesn't put '^' character for bounderies # -r sha ==> blames for the given revision so, se = self.repository.run_git_command(cmd) ...
def get_file_annotate(self, path)
Returns a generator of four element tuples with lineno, sha, changeset lazy loader and line TODO: This function now uses os underlying 'git' command which is generally not good. Should be replaced with algorithm iterating commits.
8.871024
7.023341
1.263077
allowed_kinds = settings.ARCHIVE_SPECS.keys() if kind not in allowed_kinds: raise ImproperArchiveTypeError('Archive kind not supported use one' 'of %s', allowed_kinds) if prefix is None: prefix = '%s-%s' % (self.repository.name, self.short_id) ...
def fill_archive(self, stream=None, kind='tgz', prefix=None, subrepos=False)
Fills up given stream. :param stream: file like object. :param kind: one of following: ``zip``, ``tgz`` or ``tbz2``. Default: ``tgz``. :param prefix: name of root directory in archive. Default is repository name and changeset's raw_id joined with dash (``repo...
3.424805
3.155826
1.085233
added, modified, deleted = self._changes_cache return list(added.union(modified).union(deleted))
def affected_files(self)
Get's a fast accessible file changes for given changeset
8.35393
6.366652
1.312139
added, modified, deleted = self._changes_cache return sorted({ 'added': list(added), 'modified': list(modified), 'deleted': list(deleted)}[status] )
def _get_paths_for_status(self, status)
Returns sorted list of paths for given ``status``. :param status: one of: *added*, *modified* or *deleted*
5.939805
6.23554
0.952573
if not self.parents: return list(self._get_file_nodes()) return AddedFileNodesGenerator([n for n in self._get_paths_for_status('added')], self)
def added(self)
Returns list of added ``FileNode`` objects.
16.285282
11.379845
1.431064
if not self.parents: return [] return ChangedFileNodesGenerator([n for n in self._get_paths_for_status('modified')], self)
def changed(self)
Returns list of modified ``FileNode`` objects.
22.200161
13.098243
1.694896
if not self.parents: return [] return RemovedFileNodesGenerator([n for n in self._get_paths_for_status('deleted')], self)
def removed(self)
Returns list of removed ``FileNode`` objects.
21.79661
14.012053
1.555562