title
stringclasses
1 value
text
stringlengths
46
1.11M
id
stringlengths
27
30
doc/ext/docscrape.py/indent def indent(str, indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines)
negative_train_query0_00199
doc/ext/docscrape.py/dedent_lines def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n")
negative_train_query0_00200
doc/ext/docscrape.py/header def header(text, style='-'): return text + '\n' + style*len(text) + '\n'
negative_train_query0_00201
doc/ext/docscrape.py/inspect_getmembers def inspect_getmembers(object, predicate=None): """ Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate. """ results = [] for key in dir(object): try: value = getattr(object, key) except AttributeError: continue if not predicate or predicate(value): results.append((key, value)) results.sort() return results def _is_show_member(self, name): if self.show_inherited_members: return True # show all class members if name not in self._cls.__dict__: return False # class member is inherited, we do not show it return True
negative_train_query0_00202
doc/ext/docscrape.py/_is_show_member def _is_show_member(self, name): if self.show_inherited_members: return True # show all class members if name not in self._cls.__dict__: return False # class member is inherited, we do not show it return True
negative_train_query0_00203
doc/ext/docscrape.py/is_unindented def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line)))
negative_train_query0_00204
doc/ext/docscrape.py/parse_item_name def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not an item name" % text)
negative_train_query0_00205
doc/ext/docscrape.py/push_item def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:]
negative_train_query0_00206
doc/ext/docscrape.py/strip_each_in def strip_each_in(lst): return [s.strip() for s in lst]
negative_train_query0_00207
doc/ext/docscrape.py/splitlines_x def splitlines_x(s): if not s: return [] else: return s.splitlines()
negative_train_query0_00208
doc/ext/docscrape.py/Reader/__init__ class Reader: def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data, list): self._str = data else: self._str = data.split('\n') # store string as list of lines self.reset()
negative_train_query0_00209
doc/ext/docscrape.py/Reader/__getitem__ class Reader: def __getitem__(self, n): return self._str[n]
negative_train_query0_00210
doc/ext/docscrape.py/Reader/reset class Reader: def reset(self): self._l = 0 # current line nr
negative_train_query0_00211
doc/ext/docscrape.py/Reader/read class Reader: def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return ''
negative_train_query0_00212
doc/ext/docscrape.py/Reader/seek_next_non_empty_line class Reader: def seek_next_non_empty_line(self): for l in self[self._l:]: if l.strip(): break else: self._l += 1
negative_train_query0_00213
doc/ext/docscrape.py/Reader/eof class Reader: def eof(self): return self._l >= len(self._str)
negative_train_query0_00214
doc/ext/docscrape.py/Reader/read_to_condition class Reader: def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start:self._l] self._l += 1 if self.eof(): return self[start:self._l + 1] return []
negative_train_query0_00215
doc/ext/docscrape.py/Reader/read_to_next_empty_line class Reader: def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty)
negative_train_query0_00216
doc/ext/docscrape.py/Reader/read_to_next_unindented_line class Reader: def read_to_next_unindented_line(self): def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line))) return self.read_to_condition(is_unindented)
negative_train_query0_00217
doc/ext/docscrape.py/Reader/peek class Reader: def peek(self, n=0): if self._l + n < len(self._str): return self[self._l + n] else: return ''
negative_train_query0_00218
doc/ext/docscrape.py/Reader/is_empty class Reader: def is_empty(self): return not ''.join(self._str).strip()
negative_train_query0_00219
doc/ext/docscrape.py/NumpyDocString/__init__ class NumpyDocString: def __init__(self, docstring, config={}): docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Yields': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], 'Notes': [], 'Warnings': [], 'References': '', 'Examples': '', 'index': {} } self._other_keys = [] self._parse()
negative_train_query0_00220
doc/ext/docscrape.py/NumpyDocString/__getitem__ class NumpyDocString: def __getitem__(self, key): return self._parsed_data[key]
negative_train_query0_00221
doc/ext/docscrape.py/NumpyDocString/__setitem__ class NumpyDocString: def __setitem__(self, key, val): if key not in self._parsed_data: self._other_keys.append(key) self._parsed_data[key] = val
negative_train_query0_00222
doc/ext/docscrape.py/NumpyDocString/__iter__ class NumpyDocString: def __iter__(self): return iter(self._parsed_data)
negative_train_query0_00223
doc/ext/docscrape.py/NumpyDocString/__len__ class NumpyDocString: def __len__(self): return len(self._parsed_data)
negative_train_query0_00224
doc/ext/docscrape.py/NumpyDocString/_is_at_section class NumpyDocString: def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1))
negative_train_query0_00225
doc/ext/docscrape.py/NumpyDocString/_strip class NumpyDocString: def _strip(self, doc): i = 0 j = 0 for i, line in enumerate(doc): if line.strip(): break for j, line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc) - j]
negative_train_query0_00226
doc/ext/docscrape.py/NumpyDocString/_read_to_next_section class NumpyDocString: def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section
negative_train_query0_00227
doc/ext/docscrape.py/NumpyDocString/_read_sections class NumpyDocString: def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:])
negative_train_query0_00228
doc/ext/docscrape.py/NumpyDocString/_parse_param_list class NumpyDocString: def _parse_param_list(self, content): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) params.append((arg_name, arg_type, desc)) return params
negative_train_query0_00229
doc/ext/docscrape.py/NumpyDocString/_parse_see_also class NumpyDocString: def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not an item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): if func.strip(): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items
negative_train_query0_00230
doc/ext/docscrape.py/NumpyDocString/_parse_index class NumpyDocString: def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out
negative_train_query0_00231
doc/ext/docscrape.py/NumpyDocString/_parse_summary class NumpyDocString: def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): continue break if summary is not None: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section()
negative_train_query0_00232
doc/ext/docscrape.py/NumpyDocString/_parse class NumpyDocString: def _parse(self): self._doc.reset() self._parse_summary() sections = list(self._read_sections()) section_names = set([section for section, content in sections]) has_returns = 'Returns' in section_names has_yields = 'Yields' in section_names # We could do more tests, but we are not. Arbitrarily. if has_returns and has_yields: msg = 'Docstring contains both a Returns and Yields section.' raise ValueError(msg) for (section, content) in sections: if not section.startswith('..'): section = (s.capitalize() for s in section.split(' ')) section = ' '.join(section) if section in ('Parameters', 'Returns', 'Yields', 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content
negative_train_query0_00233
doc/ext/docscrape.py/NumpyDocString/_str_header class NumpyDocString: def _str_header(self, name, symbol='-'): return [name, len(name)*symbol]
negative_train_query0_00234
doc/ext/docscrape.py/NumpyDocString/_str_indent class NumpyDocString: def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out
negative_train_query0_00235
doc/ext/docscrape.py/NumpyDocString/_str_signature class NumpyDocString: def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*', '\*')] + [''] else: return ['']
negative_train_query0_00236
doc/ext/docscrape.py/NumpyDocString/_str_summary class NumpyDocString: def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return []
negative_train_query0_00237
doc/ext/docscrape.py/NumpyDocString/_str_extended_summary class NumpyDocString: def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return []
negative_train_query0_00238
doc/ext/docscrape.py/NumpyDocString/_str_param_list class NumpyDocString: def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param, param_type, desc in self[name]: if param_type: out += ['%s : %s' % (param, param_type)] else: out += [param] out += self._str_indent(desc) out += [''] return out
negative_train_query0_00239
doc/ext/docscrape.py/NumpyDocString/_str_section class NumpyDocString: def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out
negative_train_query0_00240
doc/ext/docscrape.py/NumpyDocString/_str_see_also class NumpyDocString: def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") last_had_desc = True for func, desc, role in self['See Also']: if role: link = ':%s:`%s`' % (role, func) elif func_role: link = ':%s:`%s`' % (func_role, func) else: link = "`%s`_" % func if desc or last_had_desc: out += [''] out += [link] else: out[-1] += ", %s" % link if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += [''] return out
negative_train_query0_00241
doc/ext/docscrape.py/NumpyDocString/_str_index class NumpyDocString: def _str_index(self): idx = self['index'] out = [] out += ['.. index:: %s' % idx.get('default', '')] for section, references in idx.items(): if section == 'default': continue out += [' :%s: %s' % (section, ', '.join(references))] return out
negative_train_query0_00242
doc/ext/docscrape.py/NumpyDocString/__str__ class NumpyDocString: def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Returns', 'Yields', 'Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes', 'References', 'Examples'): out += self._str_section(s) for param_list in ('Attributes', 'Methods'): out += self._str_param_list(param_list) out += self._str_index() return '\n'.join(out)
negative_train_query0_00243
doc/ext/docscrape.py/FunctionDoc/__init__ class FunctionDoc: def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: # try to read signature if sys.version_info[0] >= 3: argspec = inspect.getfullargspec(func) else: argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*', '\*') signature = '%s%s' % (func_name, argspec) except TypeError as e: signature = '%s()' % func_name self['Signature'] = signature
negative_train_query0_00244
doc/ext/docscrape.py/FunctionDoc/get_func class FunctionDoc: def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, '__call__', self._f.__init__) else: func = self._f return func, func_name
negative_train_query0_00245
doc/ext/docscrape.py/FunctionDoc/__str__ class FunctionDoc: def __str__(self): out = '' func, func_name = self.get_func() signature = self['Signature'].replace('*', '\*') roles = {'func': 'function', 'meth': 'method'} if self._role: if self._role not in roles: print("Warning: invalid role %s" % self._role) out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''), func_name) out += super(FunctionDoc, self).__str__(func_role=self._role) return out
negative_train_query0_00246
doc/ext/docscrape.py/ClassDoc/__init__ class ClassDoc: def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config={}): if not inspect.isclass(cls) and cls is not None: raise ValueError("Expected a class or None, but got %r" % cls) self._cls = cls self.show_inherited_members = config.get( 'show_inherited_class_members', True) if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename if doc is None: if cls is None: raise ValueError("No class or documentation string given") doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) if config.get('show_class_members', True): def splitlines_x(s): if not s: return [] else: return s.splitlines() for field, items in [('Methods', self.methods), ('Attributes', self.properties)]: if not self[field]: doc_list = [] for name in sorted(items): try: doc_item = pydoc.getdoc(getattr(self._cls, name)) doc_list.append((name, '', splitlines_x(doc_item))) except AttributeError: pass # method doesn't exist self[field] = doc_list
negative_train_query0_00247
doc/ext/docscrape.py/ClassDoc/methods class ClassDoc: def methods(self): if self._cls is None: return [] return [name for name, func in inspect_getmembers(self._cls) if ((not name.startswith('_') or name in self.extra_public_methods) and callable(func))]
negative_train_query0_00248
doc/ext/docscrape.py/ClassDoc/properties class ClassDoc: def properties(self): if self._cls is None: return [] return [name for name, func in inspect_getmembers(self._cls) if not name.startswith('_') and func is None]
negative_train_query0_00249
doc/ext/sympylive.py/builder_inited def builder_inited(app): if not app.config.sympylive_url: raise ExtensionError('sympylive_url config value must be set' ' for the sympylive extension to work') app.add_javascript(app.config.sympylive_url + '/static/utilities.js') app.add_javascript(app.config.sympylive_url + '/static/external/classy.js') app.add_stylesheet(app.config.sympylive_url + '/static/live-core.css') app.add_stylesheet(app.config.sympylive_url + '/static/live-autocomplete.css') app.add_stylesheet(app.config.sympylive_url + '/static/live-sphinx.css') app.add_javascript(app.config.sympylive_url + '/static/live-core.js') app.add_javascript(app.config.sympylive_url + '/static/live-autocomplete.js') app.add_javascript(app.config.sympylive_url + '/static/live-sphinx.js')
negative_train_query0_00250
doc/ext/sympylive.py/setup def setup(app): app.add_config_value('sympylive_url', 'http://live.sympy.org', False) app.connect('builder-inited', builder_inited)
negative_train_query0_00251
.ci/parse_durations_log.py/read_log def read_log(): start_token = '= slowest test durations =' start_token_seen = False for line in open(os.path.join(ci_folder, 'durations.log')): if start_token_seen: try: dur, kind, test_id = line.split() except: return else: if dur[0] not in '0123456789': return if kind != 'call': continue if dur[-1] != 's': raise NotImplementedError("expected seconds") yield test_id, float(dur[:-1]) elif start_token in line: start_token_seen = True
negative_train_query0_00252
.ci/parse_durations_log.py/main def main(ref_timing, limits=(10, .1)): """ parses durations.log (made by generate_durations_log.sh) """ groupings = [defaultdict(list) for _ in range(len(limits))] accumul_n = [0 for _ in range(len(limits))] accumul_t = [0.0 for _ in range(len(limits))] for test_id, dur in read_log(): if test_id.startswith('sympy/utilities/tests/test_code_quality.py'): continue # white-listed (worth running since it catches many errors) for idx, lim in enumerate(limits): if dur/ref_timing >= lim: fname, tname = test_id.split('::') groupings[idx][fname].append(tname) accumul_t[idx] += dur accumul_n[idx] += 1 break json_data = json.dumps([{k: sorted(v) for k, v in gr.items()} for gr in groupings], indent=4, sort_keys=True) open(os.path.join(ci_folder, 'durations.json'), 'wt').write(json_data) print('number in group, accumulated_time: %s' % str(list(zip(accumul_n, accumul_t))))
negative_train_query0_00253
.ci/parse_durations_log.py/slow_function def slow_function(): t = time.time() a = 0 for i in range(5): a += sum([x**.3 - x**i for x in range(1000000) if x % 3 == 0]) return time.time() - t
negative_train_query0_00254
release/fabfile.py/full_path_split def full_path_split(path): """ Function to do a full split on a path. """ # Based on http://stackoverflow.com/a/13505966/161801 rest, tail = os.path.split(path) if not rest or rest == os.path.sep: return (tail,) return full_path_split(rest) + (tail,)
negative_train_query0_00255
release/fabfile.py/use_venv def use_venv(pyversion): """ Change make_virtualenv to use a given cmd pyversion should be '2' or '3' """ pyversion = str(pyversion) if pyversion == '2': yield elif pyversion == '3': oldvenv = env.virtualenv env.virtualenv = 'virtualenv -p /usr/bin/python3' yield env.virtualenv = oldvenv else: raise ValueError("pyversion must be one of '2' or '3', not %s" % pyversion)
negative_train_query0_00256
release/fabfile.py/prepare def prepare(): """ Setup the VM This only needs to be run once. It downloads all the necessary software, and a git cache. To reset this, use vagrant destroy and vagrant up. Note, this may take a while to finish, depending on your internet connection speed. """ prepare_apt() checkout_cache()
negative_train_query0_00257
release/fabfile.py/prepare_apt def prepare_apt(): """ Download software from apt Note, on a slower internet connection, this will take a while to finish, because it has to download many packages, include latex and all its dependencies. """ sudo("apt-get -qq update") sudo("apt-get -y install git python3 make python-virtualenv zip python-dev python-mpmath python3-setuptools") # Need 7.1.2 for Python 3.2 support sudo("easy_install3 pip==7.1.2") sudo("pip3 install mpmath") # Be sure to use the Python 2 pip sudo("/usr/bin/pip install twine") # Needed to build the docs sudo("apt-get -y install graphviz inkscape texlive texlive-xetex texlive-fonts-recommended texlive-latex-extra librsvg2-bin docbook2x") # Our Ubuntu is too old to include Python 3.3 sudo("apt-get -y install python-software-properties") sudo("add-apt-repository -y ppa:fkrull/deadsnakes") sudo("apt-get -y update") sudo("apt-get -y install python3.3")
negative_train_query0_00258
release/fabfile.py/remove_userspace def remove_userspace(): """ Deletes (!) the SymPy changes. Use with great care. This should be run between runs to reset everything. """ run("rm -rf repos") if os.path.exists("release"): error("release directory already exists locally. Remove it to continue.")
negative_train_query0_00259
release/fabfile.py/checkout_cache def checkout_cache(): """ Checkout a cache of SymPy This should only be run once. The cache is use as a --reference for git clone. This makes deleting and recreating the SymPy a la remove_userspace() and gitrepos() and clone very fast. """ run("rm -rf sympy-cache.git") run("git clone --bare https://github.com/sympy/sympy.git sympy-cache.git")
negative_train_query0_00260
release/fabfile.py/gitrepos def gitrepos(branch=None, fork='sympy'): """ Clone the repo fab vagrant prepare (namely, checkout_cache()) must be run first. By default, the branch checked out is the same one as the one checked out locally. The master branch is not allowed--use a release branch (see the README). No naming convention is put on the release branch. To test the release, create a branch in your fork, and set the fork option. """ with cd("/home/vagrant"): if not exists("sympy-cache.git"): error("Run fab vagrant prepare first") if not branch: # Use the current branch (of this git repo, not the one in Vagrant) branch = local("git rev-parse --abbrev-ref HEAD", capture=True) if branch == "master": raise Exception("Cannot release from master") run("mkdir -p repos") with cd("/home/vagrant/repos"): run("git clone --reference ../sympy-cache.git https://github.com/{fork}/sympy.git".format(fork=fork)) with cd("/home/vagrant/repos/sympy"): run("git checkout -t origin/%s" % branch)
negative_train_query0_00261
release/fabfile.py/get_sympy_version def get_sympy_version(version_cache=[]): """ Get the full version of SymPy being released (like 0.7.3.rc1) """ if version_cache: return version_cache[0] if not exists("/home/vagrant/repos/sympy"): gitrepos() with cd("/home/vagrant/repos/sympy"): version = run('python -c "import sympy;print(sympy.__version__)"') assert '\n' not in version assert ' ' not in version assert '\t' not in version version_cache.append(version) return version
negative_train_query0_00262
release/fabfile.py/get_sympy_short_version def get_sympy_short_version(): """ Get the short version of SymPy being released, not including any rc tags (like 0.7.3) """ version = get_sympy_version() parts = version.split('.') non_rc_parts = [i for i in parts if i.isdigit()] return '.'.join(non_rc_parts) # Remove any rc tags
negative_train_query0_00263
release/fabfile.py/test_sympy def test_sympy(): """ Run the SymPy test suite """ with cd("/home/vagrant/repos/sympy"): run("./setup.py test")
negative_train_query0_00264
release/fabfile.py/test_tarball def test_tarball(release='2'): """ Test that the tarball can be unpacked and installed, and that sympy imports in the install. """ if release not in {'2', '3'}: # TODO: Add win32 raise ValueError("release must be one of '2', '3', not %s" % release) venv = "/home/vagrant/repos/test-{release}-virtualenv".format(release=release) tarball_formatter_dict = tarball_formatter() with use_venv(release): make_virtualenv(venv) with virtualenv(venv): run("cp /vagrant/release/{source} releasetar.tar".format(**tarball_formatter_dict)) run("tar xvf releasetar.tar") with cd("/home/vagrant/{source-orig-notar}".format(**tarball_formatter_dict)): run("python setup.py install") run('python -c "import sympy; print(sympy.__version__)"')
negative_train_query0_00265
release/fabfile.py/release def release(branch=None, fork='sympy'): """ Perform all the steps required for the release, except uploading In particular, it builds all the release files, and puts them in the release/ directory in the same directory as this one. At the end, it prints some things that need to be pasted into various places as part of the release. To test the release, push a branch to your fork on GitHub and set the fork option to your username. """ remove_userspace() gitrepos(branch, fork) # This has to be run locally because it itself uses fabric. I split it out # into a separate script so that it can be used without vagrant. local("../bin/mailmap_update.py") test_sympy() source_tarball() build_docs() copy_release_files() test_tarball('2') test_tarball('3') compare_tar_against_git() print_authors()
negative_train_query0_00266
release/fabfile.py/source_tarball def source_tarball(): """ Build the source tarball """ with cd("/home/vagrant/repos/sympy"): run("git clean -dfx") run("./setup.py clean") run("./setup.py sdist --keep-temp") run("./setup.py bdist_wininst") run("mv dist/{win32-orig} dist/{win32}".format(**tarball_formatter()))
negative_train_query0_00267
release/fabfile.py/build_docs def build_docs(): """ Build the html and pdf docs """ with cd("/home/vagrant/repos/sympy"): run("mkdir -p dist") venv = "/home/vagrant/docs-virtualenv" make_virtualenv(venv, dependencies=['sphinx==1.1.3', 'numpy', 'mpmath']) with virtualenv(venv): with cd("/home/vagrant/repos/sympy/doc"): run("make clean") run("make html") run("make man") with cd("/home/vagrant/repos/sympy/doc/_build"): run("mv html {html-nozip}".format(**tarball_formatter())) run("zip -9lr {html} {html-nozip}".format(**tarball_formatter())) run("cp {html} ../../dist/".format(**tarball_formatter())) run("make clean") run("make latex") with cd("/home/vagrant/repos/sympy/doc/_build/latex"): run("make") run("cp {pdf-orig} ../../../dist/{pdf}".format(**tarball_formatter()))
negative_train_query0_00268
release/fabfile.py/copy_release_files def copy_release_files(): """ Move the release files from the VM to release/ locally """ with cd("/home/vagrant/repos/sympy"): run("mkdir -p /vagrant/release") run("cp dist/* /vagrant/release/")
negative_train_query0_00269
release/fabfile.py/show_files def show_files(file, print_=True): """ Show the contents of a tarball. The current options for file are source: The source tarball win: The Python 2 Windows installer (Not yet implemented!) html: The html docs zip Note, this runs locally, not in vagrant. """ # TODO: Test the unarchived name. See # https://github.com/sympy/sympy/issues/7087. if file == 'source': ret = local("tar tf release/{source}".format(**tarball_formatter()), capture=True) elif file == 'win': # TODO: Windows raise NotImplementedError("Windows installers") elif file == 'html': ret = local("unzip -l release/{html}".format(**tarball_formatter()), capture=True) else: raise ValueError(file + " is not valid") if print_: print(ret) return ret
negative_train_query0_00270
release/fabfile.py/compare_tar_against_git def compare_tar_against_git(): """ Compare the contents of the tarball against git ls-files """ with hide("commands"): with cd("/home/vagrant/repos/sympy"): git_lsfiles = set([i.strip() for i in run("git ls-files").split("\n")]) tar_output_orig = set(show_files('source', print_=False).split("\n")) tar_output = set() for file in tar_output_orig: # The tar files are like sympy-0.7.3/sympy/__init__.py, and the git # files are like sympy/__init__.py. split_path = full_path_split(file) if split_path[-1]: # Exclude directories, as git ls-files does not include them tar_output.add(os.path.join(*split_path[1:])) # print tar_output # print git_lsfiles fail = False print() print(blue("Files in the tarball from git that should not be there:", bold=True)) print() for line in sorted(tar_output.intersection(git_whitelist)): fail = True print(line) print() print(blue("Files in git but not in the tarball:", bold=True)) print() for line in sorted(git_lsfiles - tar_output - git_whitelist): fail = True print(line) print() print(blue("Files in the tarball but not in git:", bold=True)) print() for line in sorted(tar_output - git_lsfiles - tarball_whitelist): fail = True print(line) if fail: error("Non-whitelisted files found or not found in the tarball")
negative_train_query0_00271
release/fabfile.py/md5 def md5(file='*', print_=True): """ Print the md5 sums of the release files """ out = local("md5sum release/" + file, capture=True) # Remove the release/ part for printing. Useful for copy-pasting into the # release notes. out = [i.split() for i in out.strip().split('\n')] out = '\n'.join(["%s\t%s" % (i, os.path.split(j)[1]) for i, j in out]) if print_: print(out) return out
negative_train_query0_00272
release/fabfile.py/size def size(file='*', print_=True): """ Print the sizes of the release files """ out = local("du -h release/" + file, capture=True) out = [i.split() for i in out.strip().split('\n')] out = '\n'.join(["%s\t%s" % (i, os.path.split(j)[1]) for i, j in out]) if print_: print(out) return out
negative_train_query0_00273
release/fabfile.py/table def table(): """ Make an html table of the downloads. This is for pasting into the GitHub releases page. See GitHub_release(). """ # TODO: Add the file size tarball_formatter_dict = tarball_formatter() shortversion = get_sympy_short_version() tarball_formatter_dict['version'] = shortversion md5s = [i.split('\t') for i in md5(print_=False).split('\n')] md5s_dict = {name: md5 for md5, name in md5s} sizes = [i.split('\t') for i in size(print_=False).split('\n')] sizes_dict = {name: size for size, name in sizes} table = [] version = get_sympy_version() # http://docs.python.org/2/library/contextlib.html#contextlib.contextmanager. Not # recommended as a real way to generate html, but it works better than # anything else I've tried. @contextmanager def tag(name): table.append("<%s>" % name) yield table.append("</%s>" % name) @contextmanager def a_href(link): table.append("<a href=\"%s\">" % link) yield table.append("</a>") with tag('table'): with tag('tr'): for headname in ["Filename", "Description", "size", "md5"]: with tag("th"): table.append(headname) for key in descriptions: name = get_tarball_name(key) with tag('tr'): with tag('td'): with a_href('https://github.com/sympy/sympy/releases/download/sympy-%s/%s' %(version,name)): with tag('b'): table.append(name) with tag('td'): table.append(descriptions[key].format(**tarball_formatter_dict)) with tag('td'): table.append(sizes_dict[name]) with tag('td'): table.append(md5s_dict[name]) out = ' '.join(table) return out
negative_train_query0_00274
release/fabfile.py/get_tarball_name def get_tarball_name(file): """ Get the name of a tarball file should be one of source-orig: The original name of the source tarball source-orig-notar: The name of the untarred directory source: The source tarball (after renaming) win32-orig: The original name of the win32 installer win32: The name of the win32 installer (after renaming) html: The name of the html zip html-nozip: The name of the html, without ".zip" pdf-orig: The original name of the pdf file pdf: The name of the pdf file (after renaming) """ version = get_sympy_version() doctypename = defaultdict(str, {'html': 'zip', 'pdf': 'pdf'}) winos = defaultdict(str, {'win32': 'win32', 'win32-orig': 'linux-i686'}) if file in {'source-orig', 'source'}: name = 'sympy-{version}.tar.gz' elif file == 'source-orig-notar': name = "sympy-{version}" elif file in {'win32', 'win32-orig'}: name = "sympy-{version}.{wintype}.exe" elif file in {'html', 'pdf', 'html-nozip'}: name = "sympy-docs-{type}-{version}" if file == 'html-nozip': # zip files keep the name of the original zipped directory. See # https://github.com/sympy/sympy/issues/7087. file = 'html' else: name += ".{extension}" elif file == 'pdf-orig': name = "sympy-{version}.pdf" else: raise ValueError(file + " is not a recognized argument") ret = name.format(version=version, type=file, extension=doctypename[file], wintype=winos[file]) return ret
negative_train_query0_00275
release/fabfile.py/tarball_formatter def tarball_formatter(): return {name: get_tarball_name(name) for name in tarball_name_types}
negative_train_query0_00276
release/fabfile.py/get_previous_version_tag def get_previous_version_tag(): """ Get the version of the previous release """ # We try, probably too hard, to portably get the number of the previous # release of SymPy. Our strategy is to look at the git tags. The # following assumptions are made about the git tags: # - The only tags are for releases # - The tags are given the consistent naming: # sympy-major.minor.micro[.rcnumber] # (e.g., sympy-0.7.2 or sympy-0.7.2.rc1) # In particular, it goes back in the tag history and finds the most recent # tag that doesn't contain the current short version number as a substring. shortversion = get_sympy_short_version() curcommit = "HEAD" with cd("/home/vagrant/repos/sympy"): while True: curtag = run("git describe --abbrev=0 --tags " + curcommit).strip() if shortversion in curtag: # If the tagged commit is a merge commit, we cannot be sure # that it will go back in the right direction. This almost # never happens, so just error parents = local("git rev-list --parents -n 1 " + curtag, capture=True).strip().split() # rev-list prints the current commit and then all its parents # If the tagged commit *is* a merge commit, just comment this # out, and make sure `fab vagrant get_previous_version_tag` is correct assert len(parents) == 2, curtag curcommit = curtag + "^" # The parent of the tagged commit else: print(blue("Using {tag} as the tag for the previous " "release.".format(tag=curtag), bold=True)) return curtag error("Could not find the tag for the previous release.")
negative_train_query0_00277
release/fabfile.py/get_authors def get_authors(): """ Get the list of authors since the previous release Returns the list in alphabetical order by last name. Authors who contributed for the first time for this release will have a star appended to the end of their names. Note: it's a good idea to use ./bin/mailmap_update.py (from the base sympy directory) to make AUTHORS and .mailmap up-to-date first before using this. fab vagrant release does this automatically. """ def lastnamekey(name): """ Sort key to sort by last name Note, we decided to sort based on the last name, because that way is fair. We used to sort by commit count or line number count, but that bumps up people who made lots of maintenance changes like updating mpmath or moving some files around. """ # Note, this will do the wrong thing for people who have multi-word # last names, but there are also people with middle initials. I don't # know of a perfect way to handle everyone. Feel free to fix up the # list by hand. # Note, you must call unicode() *before* lower, or else it won't # lowercase non-ASCII characters like Č -> č text = unicode(name.strip().split()[-1], encoding='utf-8').lower() # Convert things like Čertík to Certik return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') old_release_tag = get_previous_version_tag() with cd("/home/vagrant/repos/sympy"), hide('commands'): releaseauthors = set(run('git --no-pager log {tag}.. --format="%aN"'.format(tag=old_release_tag)).strip().split('\n')) priorauthors = set(run('git --no-pager log {tag} --format="%aN"'.format(tag=old_release_tag)).strip().split('\n')) releaseauthors = {name.strip() for name in releaseauthors if name.strip()} priorauthors = {name.strip() for name in priorauthors if name.strip()} newauthors = releaseauthors - priorauthors starred_newauthors = {name + "*" for name in newauthors} authors = releaseauthors - newauthors | starred_newauthors return (sorted(authors, key=lastnamekey), len(releaseauthors), len(newauthors))
negative_train_query0_00278
release/fabfile.py/print_authors def print_authors(): """ Print authors text to put at the bottom of the release notes """ authors, authorcount, newauthorcount = get_authors() print(blue("Here are the authors to put at the bottom of the release " "notes.", bold=True)) print() print("""## Authors The following people contributed at least one patch to this release (names are given in alphabetical order by last name). A total of {authorcount} people contributed to this release. People with a * by their names contributed a patch for the first time for this release; {newauthorcount} people contributed for the first time for this release. Thanks to everyone who contributed to this release! """.format(authorcount=authorcount, newauthorcount=newauthorcount)) for name in authors: print("- " + name) print()
negative_train_query0_00279
release/fabfile.py/check_tag_exists def check_tag_exists(): """ Check if the tag for this release has been uploaded yet. """ version = get_sympy_version() tag = 'sympy-' + version with cd("/home/vagrant/repos/sympy"): all_tags = run("git ls-remote --tags origin") return tag in all_tags
negative_train_query0_00280
release/fabfile.py/update_websites def update_websites(): """ Update various websites owned by SymPy. So far, supports the docs and sympy.org """ update_docs() update_sympy_org()
negative_train_query0_00281
release/fabfile.py/get_location def get_location(location): """ Read/save a location from the configuration file. """ locations_file = os.path.expanduser('~/.sympy/sympy-locations') config = ConfigParser.SafeConfigParser() config.read(locations_file) the_location = config.has_option("Locations", location) and config.get("Locations", location) if not the_location: the_location = raw_input("Where is the SymPy {location} directory? ".format(location=location)) if not config.has_section("Locations"): config.add_section("Locations") config.set("Locations", location, the_location) save = raw_input("Save this to file [yes]? ") if save.lower().strip() in ['', 'y', 'yes']: print("saving to ", locations_file) with open(locations_file, 'w') as f: config.write(f) else: print("Reading {location} location from config".format(location=location)) return os.path.abspath(os.path.expanduser(the_location))
negative_train_query0_00282
release/fabfile.py/update_docs def update_docs(docs_location=None): """ Update the docs hosted at docs.sympy.org """ docs_location = docs_location or get_location("docs") print("Docs location:", docs_location) # Check that the docs directory is clean local("cd {docs_location} && git diff --exit-code > /dev/null".format(docs_location=docs_location)) local("cd {docs_location} && git diff --cached --exit-code > /dev/null".format(docs_location=docs_location)) # See the README of the docs repo. We have to remove the old redirects, # move in the new docs, and create redirects. current_version = get_sympy_version() previous_version = get_previous_version_tag().lstrip('sympy-') print("Removing redirects from previous version") local("cd {docs_location} && rm -r {previous_version}".format(docs_location=docs_location, previous_version=previous_version)) print("Moving previous latest docs to old version") local("cd {docs_location} && mv latest {previous_version}".format(docs_location=docs_location, previous_version=previous_version)) print("Unzipping docs into repo") release_dir = os.path.abspath(os.path.expanduser(os.path.join(os.path.curdir, 'release'))) docs_zip = os.path.abspath(os.path.join(release_dir, get_tarball_name('html'))) local("cd {docs_location} && unzip {docs_zip} > /dev/null".format(docs_location=docs_location, docs_zip=docs_zip)) local("cd {docs_location} && mv {docs_zip_name} {version}".format(docs_location=docs_location, docs_zip_name=get_tarball_name("html-nozip"), version=current_version)) print("Writing new version to releases.txt") with open(os.path.join(docs_location, "releases.txt"), 'a') as f: f.write("{version}:SymPy {version}\n".format(version=current_version)) print("Generating indexes") local("cd {docs_location} && ./generate_indexes.py".format(docs_location=docs_location)) local("cd {docs_location} && mv {version} latest".format(docs_location=docs_location, version=current_version)) print("Generating redirects") local("cd {docs_location} && ./generate_redirects.py latest {version} ".format(docs_location=docs_location, version=current_version)) print("Committing") local("cd {docs_location} && git add -A {version} latest".format(docs_location=docs_location, version=current_version)) local("cd {docs_location} && git commit -a -m \'Updating docs to {version}\'".format(docs_location=docs_location, version=current_version)) print("Pushing") local("cd {docs_location} && git push origin".format(docs_location=docs_location))
negative_train_query0_00283
release/fabfile.py/update_sympy_org def update_sympy_org(website_location=None): """ Update sympy.org This just means adding an entry to the news section. """ website_location = website_location or get_location("sympy.github.com") # Check that the website directory is clean local("cd {website_location} && git diff --exit-code > /dev/null".format(website_location=website_location)) local("cd {website_location} && git diff --cached --exit-code > /dev/null".format(website_location=website_location)) release_date = time.gmtime(os.path.getctime(os.path.join("release", tarball_formatter()['source']))) release_year = str(release_date.tm_year) release_month = str(release_date.tm_mon) release_day = str(release_date.tm_mday) version = get_sympy_version() with open(os.path.join(website_location, "templates", "index.html"), 'r') as f: lines = f.read().split('\n') # We could try to use some html parser, but this way is easier try: news = lines.index(r" <h3>{% trans %}News{% endtrans %}</h3>") except ValueError: error("index.html format not as expected") lines.insert(news + 2, # There is a <p> after the news line. Put it # after that. r""" <span class="date">{{ datetime(""" + release_year + """, """ + release_month + """, """ + release_day + """) }}</span> {% trans v='""" + version + """' %}Version {{ v }} released{% endtrans %} (<a href="https://github.com/sympy/sympy/wiki/Release-Notes-for-""" + version + """">{% trans %}changes{% endtrans %}</a>)<br/> </p><p>""") with open(os.path.join(website_location, "templates", "index.html"), 'w') as f: print("Updating index.html template") f.write('\n'.join(lines)) print("Generating website pages") local("cd {website_location} && ./generate".format(website_location=website_location)) print("Committing") local("cd {website_location} && git commit -a -m \'Add {version} to the news\'".format(website_location=website_location, version=version)) print("Pushing") local("cd {website_location} && git push origin".format(website_location=website_location))
negative_train_query0_00284
release/fabfile.py/upload def upload(): """ Upload the files everywhere (PyPI and GitHub) """ distutils_check() GitHub_release() pypi_register() pypi_upload() test_pypi(2) test_pypi(3)
negative_train_query0_00285
release/fabfile.py/distutils_check def distutils_check(): """ Runs setup.py check """ with cd("/home/vagrant/repos/sympy"): run("python setup.py check") run("python3 setup.py check")
negative_train_query0_00286
release/fabfile.py/pypi_register def pypi_register(): """ Register a release with PyPI This should only be done for the final release. You need PyPI authentication to do this. """ with cd("/home/vagrant/repos/sympy"): run("python setup.py register")
negative_train_query0_00287
release/fabfile.py/pypi_upload def pypi_upload(): """ Upload files to PyPI. You will need to enter a password. """ with cd("/home/vagrant/repos/sympy"): run("twine upload dist/*.tar.gz") run("twine upload dist/*.exe")
negative_train_query0_00288
release/fabfile.py/test_pypi def test_pypi(release='2'): """ Test that the sympy can be pip installed, and that sympy imports in the install. """ # This function is similar to test_tarball() version = get_sympy_version() release = str(release) if release not in {'2', '3'}: # TODO: Add win32 raise ValueError("release must be one of '2', '3', not %s" % release) venv = "/home/vagrant/repos/test-{release}-pip-virtualenv".format(release=release) with use_venv(release): make_virtualenv(venv) with virtualenv(venv): run("pip install sympy") run('python -c "import sympy; assert sympy.__version__ == \'{version}\'"'.format(version=version))
negative_train_query0_00289
release/fabfile.py/GitHub_release_text def GitHub_release_text(): """ Generate text to put in the GitHub release Markdown box """ shortversion = get_sympy_short_version() htmltable = table() out = """\ See https://github.com/sympy/sympy/wiki/release-notes-for-{shortversion} for the release notes. {htmltable} **Note**: Do not download the **Source code (zip)** or the **Source code (tar.gz)** files below. """ out = out.format(shortversion=shortversion, htmltable=htmltable) print(blue("Here are the release notes to copy into the GitHub release " "Markdown form:", bold=True)) print() print(out) return out
negative_train_query0_00290
release/fabfile.py/GitHub_release def GitHub_release(username=None, user='sympy', token=None, token_file_path="~/.sympy/release-token", repo='sympy', draft=False): """ Upload the release files to GitHub. The tag must be pushed up first. You can test on another repo by changing user and repo. """ if not requests: error("requests and requests-oauthlib must be installed to upload to GitHub") release_text = GitHub_release_text() version = get_sympy_version() short_version = get_sympy_short_version() tag = 'sympy-' + version prerelease = short_version != version urls = URLs(user=user, repo=repo) if not username: username = raw_input("GitHub username: ") token = load_token_file(token_file_path) if not token: username, password, token = GitHub_authenticate(urls, username, token) # If the tag in question is not pushed up yet, then GitHub will just # create it off of master automatically, which is not what we want. We # could make it create it off the release branch, but even then, we would # not be sure that the correct commit is tagged. So we require that the # tag exist first. if not check_tag_exists(): error("The tag for this version has not been pushed yet. Cannot upload the release.") # See http://developer.github.com/v3/repos/releases/#create-a-release # First, create the release post = {} post['tag_name'] = tag post['name'] = "SymPy " + version post['body'] = release_text post['draft'] = draft post['prerelease'] = prerelease print("Creating release for tag", tag, end=' ') result = query_GitHub(urls.releases_url, username, password=None, token=token, data=json.dumps(post)).json() release_id = result['id'] print(green("Done")) # Then, upload all the files to it. for key in descriptions: tarball = get_tarball_name(key) params = {} params['name'] = tarball if tarball.endswith('gz'): headers = {'Content-Type':'application/gzip'} elif tarball.endswith('pdf'): headers = {'Content-Type':'application/pdf'} elif tarball.endswith('zip'): headers = {'Content-Type':'application/zip'} else: headers = {'Content-Type':'application/octet-stream'} print("Uploading", tarball, end=' ') sys.stdout.flush() with open(os.path.join("release", tarball), 'rb') as f: result = query_GitHub(urls.release_uploads_url % release_id, username, password=None, token=token, data=f, params=params, headers=headers).json() print(green("Done"))
negative_train_query0_00291
release/fabfile.py/GitHub_check_authentication def GitHub_check_authentication(urls, username, password, token): """ Checks that username & password is valid. """ query_GitHub(urls.api_url, username, password, token)
negative_train_query0_00292
release/fabfile.py/GitHub_authenticate def GitHub_authenticate(urls, username, token=None): _login_message = """\ Enter your GitHub username & password or press ^C to quit. The password will be kept as a Python variable as long as this script is running and https to authenticate with GitHub, otherwise not saved anywhere else:\ """ if username: print("> Authenticating as %s" % username) else: print(_login_message) username = raw_input("Username: ") authenticated = False if token: print("> Authenticating using token") try: GitHub_check_authentication(urls, username, None, token) except AuthenticationFailed: print("> Authentication failed") else: print("> OK") password = None authenticated = True while not authenticated: password = getpass("Password: ") try: print("> Checking username and password ...") GitHub_check_authentication(urls, username, password, None) except AuthenticationFailed: print("> Authentication failed") else: print("> OK.") authenticated = True if password: generate = raw_input("> Generate API token? [Y/n] ") if generate.lower() in ["y", "ye", "yes", ""]: name = raw_input("> Name of token on GitHub? [SymPy Release] ") if name == "": name = "SymPy Release" token = generate_token(urls, username, password, name=name) print("Your token is", token) print("Use this token from now on as GitHub_release:token=" + token + ",username=" + username) print(red("DO NOT share this token with anyone")) save = raw_input("Do you want to save this token to a file [yes]? ") if save.lower().strip() in ['y', 'yes', 'ye', '']: save_token_file(token) return username, password, token
negative_train_query0_00293
release/fabfile.py/generate_token def generate_token(urls, username, password, OTP=None, name="SymPy Release"): enc_data = json.dumps( { "scopes": ["public_repo"], "note": name } ) url = urls.authorize_url rep = query_GitHub(url, username=username, password=password, data=enc_data).json() return rep["token"]
negative_train_query0_00294
release/fabfile.py/save_token_file def save_token_file(token): token_file = raw_input("> Enter token file location [~/.sympy/release-token] ") token_file = token_file or "~/.sympy/release-token" token_file_expand = os.path.expanduser(token_file) token_file_expand = os.path.abspath(token_file_expand) token_folder, _ = os.path.split(token_file_expand) try: if not os.path.isdir(token_folder): os.mkdir(token_folder, 0o700) with open(token_file_expand, 'w') as f: f.write(token + '\n') os.chmod(token_file_expand, stat.S_IREAD | stat.S_IWRITE) except OSError as e: print("> Unable to create folder for token file: ", e) return except IOError as e: print("> Unable to save token file: ", e) return return token_file
negative_train_query0_00295
release/fabfile.py/load_token_file def load_token_file(path="~/.sympy/release-token"): print("> Using token file %s" % path) path = os.path.expanduser(path) path = os.path.abspath(path) if os.path.isfile(path): try: with open(path) as f: token = f.readline() except IOError: print("> Unable to read token file") return else: print("> Token file does not exist") return return token.strip()
negative_train_query0_00296
release/fabfile.py/query_GitHub def query_GitHub(url, username=None, password=None, token=None, data=None, OTP=None, headers=None, params=None, files=None): """ Query GitHub API. In case of a multipage result, DOES NOT query the next page. """ headers = headers or {} if OTP: headers['X-GitHub-OTP'] = OTP if token: auth = OAuth2(client_id=username, token=dict(access_token=token, token_type='bearer')) else: auth = HTTPBasicAuth(username, password) if data: r = requests.post(url, auth=auth, data=data, headers=headers, params=params, files=files) else: r = requests.get(url, auth=auth, headers=headers, params=params, stream=True) if r.status_code == 401: two_factor = r.headers.get('X-GitHub-OTP') if two_factor: print("A two-factor authentication code is required:", two_factor.split(';')[1].strip()) OTP = raw_input("Authentication code: ") return query_GitHub(url, username=username, password=password, token=token, data=data, OTP=OTP) raise AuthenticationFailed("invalid username or password") r.raise_for_status() return r
negative_train_query0_00297
release/fabfile.py/vagrant def vagrant(): """ Run commands using vagrant """ vc = get_vagrant_config() # change from the default user to 'vagrant' env.user = vc['User'] # connect to the port-forwarded ssh env.hosts = ['%s:%s' % (vc['HostName'], vc['Port'])] # use vagrant ssh key env.key_filename = vc['IdentityFile'].strip('"') # Forward the agent if specified: env.forward_agent = vc.get('ForwardAgent', 'no') == 'yes'
negative_train_query0_00298