Search is not available for this dataset
text stringlengths 75 104k |
|---|
def factory(cls, filename, mode, on_close):
"""Create a S3File backed with a temporary file."""
_temp_file = tempfile.TemporaryFile()
proxy = cls(_temp_file, filename, mode, on_close=on_close)
return proxy |
def gravatar_url(user_or_email, size=GRAVATAR_DEFAULT_SIZE):
""" Builds a gravatar url from an user or email """
if hasattr(user_or_email, 'email'):
email = user_or_email.email
else:
email = user_or_email
try:
return escape(get_gravatar_url(email=email, size=size))
except:
... |
def gravatar(user_or_email, size=GRAVATAR_DEFAULT_SIZE, alt_text='', css_class='gravatar'):
""" Builds an gravatar <img> tag from an user or email """
if hasattr(user_or_email, 'email'):
email = user_or_email.email
else:
email = user_or_email
try:
url = escape(get_gravatar_url(e... |
def get_gravatar_url(email, size=GRAVATAR_DEFAULT_SIZE, default=GRAVATAR_DEFAULT_IMAGE,
rating=GRAVATAR_DEFAULT_RATING, secure=GRAVATAR_DEFAULT_SECURE):
"""
Builds a url to a gravatar from an email address.
:param email: The email to fetch the gravatar for
:param size: The size (in pixels) of t... |
def has_gravatar(email):
"""
Returns True if the user has a gravatar, False if otherwise
"""
# Request a 404 response if the gravatar does not exist
url = get_gravatar_url(email, default=GRAVATAR_DEFAULT_IMAGE_404)
# Verify an OK response was received
try:
request = Request(url)
... |
def get_gravatar_profile_url(email, secure=GRAVATAR_DEFAULT_SECURE):
"""
Builds a url to a gravatar profile from an email address.
:param email: The email to fetch the gravatar for
:param secure: If True use https, otherwise plain http
"""
if secure:
url_base = GRAVATAR_SECURE_URL
e... |
def graph_coloring_qubo(graph, k):
"""
the QUBO for k-coloring a graph A is as follows:
variables:
x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise
constraints:
1) each v in A gets exactly one color.
This constraint is enforced by including the term (\sum_c x_{v,c} - 1)... |
def chimera_blocks(M=16, N=16, L=4):
"""
Generator for blocks for a chimera block quotient
"""
for x in xrange(M):
for y in xrange(N):
for u in (0, 1):
yield tuple((x, y, u, k) for k in xrange(L)) |
def chimera_block_quotient(G, blocks):
"""
Extract the blocks from a graph, and returns a
block-quotient graph according to the acceptability
functions block_good and eblock_good
Inputs:
G: a networkx graph
blocks: a tuple of tuples
"""
from networkx import Graph
from i... |
def embed_with_quotient(source_graph, target_graph, M=16, N=16, L=4, **args):
"""
Produce an embedding in target_graph suitable to
check if source_graph is 4-colorable. More generally,
if target_graph is a (M,N,L) Chimera subgraph, the
test is for L-colorability. This depends heavily upon
the ... |
def enumerate_resonance_smiles(smiles):
"""Return a set of resonance forms as SMILES strings, given a SMILES string.
:param smiles: A SMILES string.
:returns: A set containing SMILES strings for every possible resonance form.
:rtype: set of strings.
"""
mol = Chem.MolFromSmiles(smiles)
#Che... |
def enumerate(self, mol):
"""Enumerate all possible resonance forms and return them as a list.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: A list of all possible resonance forms of the molecule.
:rtype: list of rdkit.Chem.rdchem.Mol
"""
... |
def normalize(self, mol):
"""Apply a series of Normalization transforms to correct functional groups and recombine charges.
A series of transforms are applied to the molecule. For each Normalization, the transform is applied repeatedly
until no further changes occur. If any changes occurred, we... |
def _apply_transform(self, mol, rule):
"""Repeatedly apply normalization transform to molecule until no changes occur.
It is possible for multiple products to be produced when a rule is applied. The rule is applied repeatedly to
each of the products, until no further changes occur or after 20 a... |
def canonicalize(self, mol):
"""Return a canonical tautomer by enumerating and scoring all possible tautomers.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: The canonical tautomer.
:rtype: rdkit.Chem.rdchem.Mol
"""
# TODO: Overload the... |
def enumerate(self, mol):
"""Enumerate all possible tautomers and return them as a list.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: A list of all possible tautomers of the molecule.
:rtype: list of rdkit.Chem.rdchem.Mol
"""
smiles =... |
def validate_smiles(smiles):
"""Return log messages for a given SMILES string using the default validations.
Note: This is a convenience function for quickly validating a single SMILES string. It is more efficient to use
the :class:`~molvs.validate.Validator` class directly when working with many molecules... |
def disconnect(self, mol):
"""Break covalent bonds between metals and organic atoms under certain conditions.
The algorithm works as follows:
- Disconnect N, O, F from any metal.
- Disconnect other non-metals from transition metals + Al (but not Hg, Ga, Ge, In, Sn, As, Tl, Pb, Bi, Po).... |
def standardize_smiles(smiles):
"""Return a standardized canonical SMILES string given a SMILES string.
Note: This is a convenience function for quickly standardizing a single SMILES string. It is more efficient to use
the :class:`~molvs.standardize.Standardizer` class directly when working with many molec... |
def enumerate_tautomers_smiles(smiles):
"""Return a set of tautomers as SMILES strings, given a SMILES string.
:param smiles: A SMILES string.
:returns: A set containing SMILES strings for every possible tautomer.
:rtype: set of strings.
"""
# Skip sanitize as standardize does this anyway
m... |
def canonicalize_tautomer_smiles(smiles):
"""Return a standardized canonical tautomer SMILES string given a SMILES string.
Note: This is a convenience function for quickly standardizing and finding the canonical tautomer for a single
SMILES string. It is more efficient to use the :class:`~molvs.standardize... |
def standardize(self, mol):
"""Return a standardized version the given molecule.
The standardization process consists of the following stages: RDKit
:py:func:`~rdkit.Chem.rdmolops.RemoveHs`, RDKit :py:func:`~rdkit.Chem.rdmolops.SanitizeMol`,
:class:`~molvs.metal.MetalDisconnector`, :cla... |
def tautomer_parent(self, mol, skip_standardize=False):
"""Return the tautomer parent of a given molecule.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:param bool skip_standardize: Set to True if mol has already been standardized.
:returns: The tautomer pare... |
def fragment_parent(self, mol, skip_standardize=False):
"""Return the fragment parent of a given molecule.
The fragment parent is the largest organic covalent unit in the molecule.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:param bool skip_standardize: Se... |
def stereo_parent(self, mol, skip_standardize=False):
"""Return the stereo parent of a given molecule.
The stereo parent has all stereochemistry information removed from tetrahedral centers and double bonds.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:para... |
def isotope_parent(self, mol, skip_standardize=False):
"""Return the isotope parent of a given molecule.
The isotope parent has all atoms replaced with the most abundant isotope for that element.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:param bool skip_... |
def charge_parent(self, mol, skip_standardize=False):
"""Return the charge parent of a given molecule.
The charge parent is the uncharged version of the fragment parent.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:param bool skip_standardize: Set to True i... |
def super_parent(self, mol, skip_standardize=False):
"""Return the super parent of a given molecule.
THe super parent is fragment, charge, isotope, stereochemistry and tautomer insensitive. From the input
molecule, the largest fragment is taken. This is uncharged and then isotope and stereochem... |
def canonicalize_tautomer(self):
"""
:returns: A callable :class:`~molvs.tautomer.TautomerCanonicalizer` instance.
"""
return TautomerCanonicalizer(transforms=self.tautomer_transforms, scores=self.tautomer_scores,
max_tautomers=self.max_tautomers) |
def main():
"""Main function for molvs command line interface."""
# Root options
parser = MolvsParser(epilog='use "molvs <command> -h" to show help for a specific command')
subparsers = parser.add_subparsers(title='Available commands')
# Options common to all commands
common_parser = MolvsPar... |
def reionize(self, mol):
"""Enforce charges on certain atoms, then perform competitive reionization.
First, charge corrections are applied to ensure, for example, that free metals are correctly ionized. Then, if
a molecule with multiple acid groups is partially ionized, ensure the strongest aci... |
def uncharge(self, mol):
"""Neutralize molecule by adding/removing hydrogens.
:param mol: The molecule to uncharge.
:type mol: rdkit.Chem.rdchem.Mol
:return: The uncharged molecule.
:rtype: rdkit.Chem.rdchem.Mol
"""
log.debug('Running Uncharger')
mol = co... |
def _get_neg_skip(self, mol, pos_count):
"""Get negatively charged atoms to skip (up to pos_count)."""
neg_skip = set()
if pos_count:
# Get negative oxygens in charge-separated nitro groups TODO: Any other special cases to skip?
for occurrence in mol.GetSubstructMatches(s... |
def remove(self, mol):
"""Return the molecule with specified fragments removed.
:param mol: The molecule to remove fragments from.
:type mol: rdkit.Chem.rdchem.Mol
:return: The molecule with fragments removed.
:rtype: rdkit.Chem.rdchem.Mol
"""
log.debug('Running ... |
def choose(self, mol):
"""Return the largest covalent unit.
The largest fragment is determined by number of atoms (including hydrogens). Ties are broken by taking the
fragment with the higher molecular weight, and then by taking the first alphabetically by SMILES if needed.
:param mol:... |
def integrate_ivp(u0=1.0, v0=0.0, mu=1.0, tend=10.0, dt0=1e-8, nt=0,
nsteps=600, t0=0.0, atol=1e-8, rtol=1e-8, plot=False,
savefig='None', method='bdf', dpi=100, verbose=False):
"""
Example program integrating an IVP problem of van der Pol oscillator
"""
f, j = get_f_... |
def integrate_adaptive(rhs, jac, y0, x0, xend, atol, rtol, dx0=.0,
dx_min=.0, dx_max=.0, nsteps=500, method=None, nderiv=0,
roots=None, nroots=0, return_on_root=False,
check_callable=False, check_indexing=False,
**kwargs):
"... |
def integrate_predefined(rhs, jac, y0, xout, atol, rtol, jac_type="dense",
dx0=.0, dx_min=.0, dx_max=.0, nsteps=500, method=None,
nderiv=0, roots=None, nroots=0, check_callable=False,
check_indexing=False, **kwargs):
""" Integrates a system ... |
def get_stats(self, username='', password='', organization='llnl',
force=True, repo_type='public'):
"""
Retrieves the statistics from the given organization with the given
credentials. Will not retreive data if file exists and force hasn't been
set to True. This is to save GH API... |
def get_mems_of_org(self):
"""
Retrieves the number of members of the organization.
"""
print 'Getting members.'
counter = 0
for member in self.org_retrieved.iter_members():
self.members_json[member.id] = member.to_json()
counter += 1
retur... |
def get_teams_of_org(self):
"""
Retrieves the number of teams of the organization.
"""
print 'Getting teams.'
counter = 0
for team in self.org_retrieved.iter_teams():
self.teams_json[team.id] = team.to_json()
counter += 1
return counter |
def repos(self, repo_type='public', organization='llnl'):
"""
Retrieves info about the repos of the current organization.
"""
print 'Getting repos.'
for repo in self.org_retrieved.iter_repos(type=repo_type):
#JSON
json = repo.to_json()
self.rep... |
def get_total_contributors(self, repo):
"""
Retrieves the number of contributors to a repo in the organization.
Also adds to unique contributor list.
"""
repo_contributors = 0
for contributor in repo.iter_contributors():
repo_contributors += 1
self... |
def get_pull_reqs(self, repo):
"""
Retrieves the number of pull requests on a repo in the organization.
"""
pull_reqs_open = 0
pull_reqs_closed = 0
for pull_request in repo.iter_pulls(state='all'):
self.pull_requests_json[repo.name].append(pull_request.to_json... |
def get_issues(self, repo, organization='llnl'):
"""
Retrieves the number of closed issues.
"""
#JSON
path = ('../github-data/' + organization + '/' + repo.name + '/issues')
is_only_today = False
if not os.path.exists(path): #no previous path, get all issues
... |
def get_languages(self, repo, temp_repo):
"""
Retrieves the languages used in the repo and increments the respective
counts of those languages. Only increments languages that have names.
Anything else is not incremented (i.e. numbers).
"""
try:
self.languages[... |
def get_readme(self, repo):
"""
Checks to see if the given repo has a ReadMe. MD means it has a correct
Readme recognized by GitHub.
"""
readme_contents = repo.readme()
if readme_contents is not None:
self.total_readmes += 1
return 'MD'
if ... |
def get_license(self, repo):
"""
Checks to see if the given repo has a top level LICENSE file.
"""
if self.search_limit >= 28:
print 'Hit search limit. Sleeping for 60 sec.'
time.sleep(60)
self.search_limit = 0
self.search_limit += 1
se... |
def get_commits(self, repo, organization='llnl'):
"""
Retrieves the number of commits to a repo in the organization. If it is
the first time getting commits for a repo, it will get all commits and
save them to JSON. If there are previous commits saved, it will only get
commits th... |
def write_org_json(self, date=(datetime.date.today()),
organization='llnl',dict_to_write={}, path_ending_type='',
is_list=False):
"""
Writes stats from the organization to JSON.
"""
path = ('../github-data/' + organization + '-org/'
+ path_ending_type + '/' + ... |
def write_repo_json(self, date=(datetime.date.today()),
organization='llnl', dict_to_write={}, path_ending_type='',
is_list=False, is_dict=False):
"""
#Writes repo specific data to JSON.
"""
for repo in dict_to_write:
path = ('../github-data/' + organization +... |
def write_to_file(self, file_path='', date=str(datetime.date.today()),
organization='N/A', members=0, teams=0):
"""
Writes the current organization information to file (csv).
"""
self.checkDir(file_path)
with open(file_path, 'w+') as output:
output.write('date... |
def write_totals(self, file_path='', date=str(datetime.date.today()),
organization='N/A', members=0, teams=0):
"""
Updates the total.csv file with current data.
"""
total_exists = os.path.isfile(file_path)
with open(file_path, 'a') as out_total:
if not total_... |
def write_languages(self, file_path='',date=str(datetime.date.today())):
"""
Updates languages.csv file with current data.
"""
self.remove_date(file_path=file_path, date=date)
languages_exists = os.path.isfile(file_path)
with open(file_path, 'a') as out_languages:
... |
def checkDir(self, file_path=''):
"""
Checks if a directory exists. If not, it creates one with the specified
file_path.
"""
if not os.path.exists(os.path.dirname(file_path)):
try:
os.makedirs(os.path.dirname(file_path))
except OSError as e... |
def remove_date(self, file_path='', date=str(datetime.date.today())):
"""
Removes all rows of the associated date from the given csv file.
Defaults to today.
"""
languages_exists = os.path.isfile(file_path)
if languages_exists:
with open(file_path, 'rb') as in... |
def delete_last_line(self, file_path='', date=str(datetime.date.today())):
"""
The following code was modified from
http://stackoverflow.com/a/10289740 &
http://stackoverflow.com/a/17309010
It essentially will check if the total for the current date already
exists in tota... |
def gov_orgs():
"""
Returns a list of the names of US Government GitHub organizations
Based on: https://government.github.com/community/
Exmample return:
{'llnl', '18f', 'gsa', 'dhs-ncats', 'spack', ...}
"""
us_gov_github_orgs = set()
gov_orgs = requests.get('https://government.gi... |
def create_session(token=None):
"""
Create a github3.py session connected to GitHub.com
If token is not provided, will attempt to use the GITHUB_API_TOKEN
environment variable if present.
"""
if token is None:
token = os.environ.get('GITHUB_API_TOKEN', None)
gh_session = github3.lo... |
def create_enterprise_session(url, token=None):
"""
Create a github3.py session for a GitHub Enterprise instance
If token is not provided, will attempt to use the GITHUB_API_TOKEN
environment variable if present.
"""
gh_session = github3.enterprise_login(url=url, token=token)
if gh_sessio... |
def _check_api_limits(gh_session, api_required=250, sleep_time=15):
"""
Simplified check for API limits
If necessary, spin in place waiting for API to reset before returning.
See: https://developer.github.com/v3/#rate-limiting
"""
api_rates = gh_session.rate_limit()
api_remaining = api_ra... |
def connect(url='https://github.com', token=None):
"""
Create a GitHub session for making requests
"""
gh_session = None
if url == 'https://github.com':
gh_session = create_session(token)
else:
gh_session = create_enterprise_session(url, token)
if gh_session is None:
... |
def query_repos(gh_session, orgs=None, repos=None, public_only=True):
"""
Yields GitHub3.py repo objects for provided orgs and repo names
If orgs and repos are BOTH empty, execute special mode of getting ALL
repositories from the GitHub Server.
If public_only is True, will return only those repos ... |
def get_stats(self, username='', password='', organization='llnl', force=True):
"""
Retrieves the traffic for the users of the given organization.
Requires organization admin credentials token to access the data.
"""
date = str(datetime.date.today())
stargazers_file_path ... |
def get_org(self, organization_name=''):
"""
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
"""
self.organization_name = organization_name
if(organization_name == ''):
self.organization_name = raw_input('Orga... |
def get_repos(self):
"""
Gets the repos for the organization and builds the URL/headers for
getting timestamps of stargazers.
"""
print 'Getting repos.'
#Uses the developer API. Note this could change.
headers = {'Accept': 'application/vnd.github.v3.star+json', '... |
def get_stargazers(self, url, headers={}):
"""
Return a list of the stargazers of a GitHub repo
Includes both the 'starred_at' and 'user' data.
param: url
url is the 'stargazers_url' of the form:
https://api.github.com/repos/LLNL/spack/stargazers
"""... |
def write_to_file(self, file_path='', date=(datetime.date.today()),
organization='llnl'):
"""
Writes stargazers data to file.
"""
with open(file_path, 'w+') as out:
out.write('date,organization,stargazers\n')
sorted_stargazers = sorted(self.stargazers)#sor... |
def from_github3(klass, repository, labor_hours=True):
"""
Create CodeGovProject object from github3 Repository object
"""
if not isinstance(repository, github3.repos.repo._Repository):
raise TypeError('Repository must be a github3 Repository object')
logger.info('Pr... |
def from_gitlab(klass, repository, labor_hours=True):
"""
Create CodeGovProject object from GitLab Repository
"""
if not isinstance(repository, gitlab.v4.objects.Project):
raise TypeError('Repository must be a gitlab Repository object')
project = klass()
log... |
def from_stashy(klass, repository, labor_hours=True):
"""
Handles crafting Code.gov Project for Bitbucket Server repositories
"""
# if not isinstance(repository, stashy.repos.Repository):
# raise TypeError('Repository must be a stashy Repository object')
if not isinst... |
def from_doecode(klass, record):
"""
Create CodeGovProject object from DOE CODE record
Handles crafting Code.gov Project
"""
if not isinstance(record, dict):
raise TypeError('`record` must be a dict')
project = klass()
# -- REQUIRED FIELDS --
... |
def from_tfs(klass, tfs_project, labor_hours=True):
"""
Creates CodeGovProject object from TFS/VSTS/AzureDevOps Instance
"""
project = klass()
project_web_url = ''
# -- REQUIRED FIELDS --
project['name'] = tfs_project.projectInfo.name
if 'web' in tfs_pro... |
def process_config(config):
"""
Master function to process a Scraper config file
Returns a Code.gov Metadata file
"""
agency = config.get('agency', 'UNKNOWN')
logger.debug('Agency: %s', agency)
method = config.get('method', 'other')
logger.debug('Inventory Method: %s', method)
co... |
def force_attributes(metadata, config):
"""
Forces certain fields in the Code.gov Metadata json
"""
organization = config.get('organization', '')
logger.debug('Organization: %s', organization)
contact_email = config.get('contact_email')
logger.debug('Contact Email: %s', contact_email)
... |
def _license_obj(license):
"""
A helper function to look up license object information
Use names from: https://api.github.com/licenses
"""
obj = None
if license in ('MIT', 'MIT License'):
obj = {
'URL': 'https://api.github.com/licenses/mit',
'name': 'MIT'
... |
def get_stats(self, username='', password='', organization='llnl', force=True):
"""
Retrieves the traffic for the users of the given organization.
Requires organization admin credentials token to access the data.
"""
date = str(datetime.date.today())
referrers_file_path =... |
def get_traffic(self):
"""
Retrieves the traffic for the repositories of the given organization.
"""
print 'Getting traffic.'
#Uses the developer API. Note this could change.
headers = {'Accept': 'application/vnd.github.spiderman-preview', 'Authorization': 'token ' + self... |
def get_releases(self, url='', headers={}, repo_name=''):
"""
Retrieves the releases for the given repo in JSON.
"""
url_releases = (url + '/releases')
r = requests.get(url_releases, headers=headers)
self.releases_json[repo_name] = r.json() |
def get_referrers(self, url='', headers={}, repo_name=''):
"""
Retrieves the total referrers and unique referrers of all repos in json
and then stores it in a dict.
"""
#JSON
url_referrers = (url + '/traffic/popular/referrers')
r1 = requests.get(url_referrers, hea... |
def get_data(self, url='',headers={}, date=str(datetime.date.today()),
dict_to_store={}, type='', repo_name=''):
"""
Retrieves data from json and stores it in the supplied dict. Accepts
'clones' or 'views' as type.
"""
#JSON
url = (url + '/traffic/' + type)
... |
def write_json(self, date=(datetime.date.today()),
organization='llnl',dict_to_write={}, path_ending_type=''):
"""
Writes all traffic data to file in JSON form.
"""
for repo in dict_to_write:
if len(dict_to_write[repo]) != 0:#don't need to write out empty lists
... |
def write_to_file(self, referrers_file_path='', views_file_path='',
clones_file_path='', date=(datetime.date.today()), organization='llnl',
views_row_count=0, clones_row_count=0):
"""
Writes all traffic data to file.
"""
self.write_referrers_to_file(file_path=referrers_fi... |
def check_data_redundancy(self, file_path='', dict_to_check={}):
"""
Checks the given csv file against the json data scraped for the given
dict. It will remove all data retrieved that has already been recorded
so we don't write redundant data to file. Returns count of rows from
f... |
def write_data_to_file(self, file_path='', date=str(datetime.date.today()),
organization='llnl',dict_to_write={}, name='', row_count=0):
"""
Writes given dict to file.
"""
exists = os.path.isfile(file_path)
with open(file_path, 'a') as out:
if not exists:
... |
def write_referrers_to_file(self, file_path='',
date=str(datetime.date.today()), organization='llnl'):
"""
Writes the referrers data to file.
"""
self.remove_date(file_path=file_path, date=date)
referrers_exists = os.path.isfile(file_path)
with open(file_path, 'a'... |
def process_json(filename):
"""
Converts a DOE CODE .json file into DOE CODE projects
Yields DOE CODE records from a DOE CODE .json file
"""
logger.debug('Processing DOE CODE json: %s', filename)
doecode_json = json.load(open(filename))
for record in doecode_json['records']:
yield... |
def process_url(url, key):
"""
Yields DOE CODE records from a DOE CODE .json URL response
Converts a DOE CODE API .json URL response into DOE CODE projects
"""
logger.debug('Fetching DOE CODE JSON: %s', url)
if key is None:
raise ValueError('DOE CODE API Key value is missing!')
re... |
def process(filename=None, url=None, key=None):
"""
Yeilds DOE CODE records based on provided input sources
param:
filename (str): Path to a DOE CODE .json file
url (str): URL for a DOE CODE server json file
key (str): API Key for connecting to DOE CODE server
"""
if filena... |
def login(self, username='', password=''):
"""
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Fac... |
def get_mems_of_org(self):
"""
Retrieves the emails of the members of the organization. Note this Only
gets public emails. Private emails would need authentication for each
user.
"""
print 'Getting members\' emails.'
for member in self.org_retrieved.iter_members()... |
def write_to_file(self, file_path=''):
"""
Writes the user emails to file.
"""
with open(file_path, 'w+') as out:
out.write('user, email\n')
sorted_names = sorted(self.logins_lower)#sort based on lowercase
for login in sorted_names:
out... |
def connect(url, username, password):
"""
Return a connected Bitbucket session
"""
bb_session = stashy.connect(url, username, password)
logger.info('Connected to: %s as %s', url, username)
return bb_session |
def get_stargazers(url, session=None):
"""
Return a list of the stargazers of a GitHub repo
Includes both the 'starred_at' and 'user' data.
param: url
url is the 'stargazers_url' of the form:
https://api.github.com/repos/LLNL/spack/stargazers
"""
headers = {'Accept': 'appli... |
def connect(url='https://gitlab.com', token=None):
"""
Return a connected GitLab session
``token`` should be a ``private_token`` from Gitlab
"""
if token is None:
token = os.environ.get('GITLAB_API_TOKEN', None)
gl_session = gitlab.Gitlab(url, token)
try:
gl_session.versi... |
def query_repos(gl_session, repos=None):
"""
Yields Gitlab project objects for all projects in Bitbucket
"""
if repos is None:
repos = []
for repo in repos:
yield gl_session.projects.get(repo)
if not repos:
for project in gl_session.projects.list(as_list=False):
... |
def git_repo_to_sloc(url):
"""
Given a Git repository URL, returns number of lines of code based on cloc
Reference:
- cloc: https://github.com/AlDanial/cloc
- https://www.omg.org/spec/AFP/
- Another potential way to calculation effort
Sample cloc output:
{
"header":... |
def compute_labor_hours(sloc, month_hours='cocomo_book'):
"""
Compute the labor hours, given a count of source lines of code
The intention is to use the COCOMO II model to compute this value.
References:
- http://csse.usc.edu/tools/cocomoii.php
- http://docs.python-guide.org/en/latest/scenario... |
def _prune_dict_null_str(dictionary):
"""
Prune the "None" or emptry string values from dictionary items
"""
for key, value in list(dictionary.items()):
if value is None or str(value) == '':
del dictionary[key]
if isinstance(value, dict):
dictionary[key] = _prune... |
def _readGQL(self, filePath, verbose=False):
"""Read a 'pretty' formatted GraphQL query file into a one-line string.
Removes line breaks and comments. Condenses white space.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQL query.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.