_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q272500
delete
test
def delete(self, name): '''delete an image from Google Storage. Parameters ========== name: the name of the file (or image) to delete ''' bot.debug("DELETE %s" % name) for file_object in files: if isinstance(file_object, dict): if "kind" in file_object: ...
python
{ "resource": "" }
q272501
destroy
test
def destroy(self, name): '''destroy an instance, meaning take down the instance and stop the build. Parameters ========== name: the name of the instance to stop building. ''' instances = self._get_instances() project = self._get_project() zone = self._get_zone() found = Fa...
python
{ "resource": "" }
q272502
get_subparsers
test
def get_subparsers(parser): '''get_subparser will get a dictionary of subparsers, to help with printing help ''' actions = [action for action in parser._actions if isinstance(action, argparse._SubParsersAction)] subparsers = dict() for action in actions: # get all subparser...
python
{ "resource": "" }
q272503
RobotNamer.generate
test
def generate(self, delim='-', length=4, chars='0123456789'): ''' Generate a robot name. Inspiration from Haikunator, but much more poorly implemented ;) Parameters ========== delim: Delimiter length: TokenLength chars: TokenChars ''' ...
python
{ "resource": "" }
q272504
get_tmpdir
test
def get_tmpdir(requested_tmpdir=None, prefix="", create=True): '''get a temporary directory for an operation. If SREGISTRY_TMPDIR is set, return that. Otherwise, return the output of tempfile.mkdtemp Parameters ========== requested_tmpdir: an optional requested temporary directory, firs...
python
{ "resource": "" }
q272505
extract_tar
test
def extract_tar(archive, output_folder, handle_whiteout=False): '''extract a tar archive to a specified output folder Parameters ========== archive: the archive file to extract output_folder: the output folder to extract to handle_whiteout: use docker2oci variation to handle...
python
{ "resource": "" }
q272506
_extract_tar
test
def _extract_tar(archive, output_folder): '''use blob2oci to handle whiteout files for extraction. Credit for this script goes to docker2oci by Olivier Freyermouth, and see script folder for license. Parameters ========== archive: the archive to extract output_folder the o...
python
{ "resource": "" }
q272507
get_file_hash
test
def get_file_hash(filename): '''find the SHA256 hash string of a file ''' hasher = hashlib.sha256() with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hasher.update(chunk) return hasher.hexdigest()
python
{ "resource": "" }
q272508
read_file
test
def read_file(filename, mode="r", readlines=True): '''write_file will open a file, "filename" and write content, "content" and properly close the file ''' with open(filename, mode) as filey: if readlines is True: content = filey.readlines() else: content = file...
python
{ "resource": "" }
q272509
read_json
test
def read_json(filename, mode='r'): '''read_json reads in a json file and returns the data structure as dict. ''' with open(filename, mode) as filey: data = json.load(filey) return data
python
{ "resource": "" }
q272510
clean_up
test
def clean_up(files): '''clean up will delete a list of files, only if they exist ''' if not isinstance(files, list): files = [files] for f in files: if os.path.exists(f): bot.verbose3("Cleaning up %s" % f) os.remove(f)
python
{ "resource": "" }
q272511
push
test
def push(self, path, name, tag=None): '''push an image to an S3 endpoint''' path = os.path.abspath(path) image = os.path.basename(path) bot.debug("PUSH %s" % path) if not os.path.exists(path): bot.error('%s does not exist.' %path) sys.exit(1) # Extract the metadata names =...
python
{ "resource": "" }
q272512
get_or_create_collection
test
def get_or_create_collection(self, name): '''get a collection if it exists. If it doesn't exist, create it first. Parameters ========== name: the collection name, usually parsed from get_image_names()['name'] ''' from sregistry.database.models import Collection collection = self.get_collec...
python
{ "resource": "" }
q272513
get_collection
test
def get_collection(self, name): '''get a collection, if it exists, otherwise return None. ''' from sregistry.database.models import Collection return Collection.query.filter(Collection.name == name).first()
python
{ "resource": "" }
q272514
get_container
test
def get_container(self, name, collection_id, tag="latest", version=None): '''get a container, otherwise return None. ''' from sregistry.database.models import Container if version is None: container = Container.query.filter_by(collection_id = collection_id, ...
python
{ "resource": "" }
q272515
images
test
def images(self, query=None): '''List local images in the database, optionally with a query. Paramters ========= query: a string to search for in the container or collection name|tag|uri ''' from sregistry.database.models import Collection, Container rows = [] if query is not...
python
{ "resource": "" }
q272516
inspect
test
def inspect(self, name): '''Inspect a local image in the database, which typically includes the basic fields in the model. ''' print(name) container = self.get(name) if container is not None: collection = container.collection.name fields = container.__dict__.copy() fi...
python
{ "resource": "" }
q272517
rename
test
def rename(self, image_name, path): '''rename performs a move, but ensures the path is maintained in storage Parameters ========== image_name: the image name (uri) to rename to. path: the name to rename (basename is taken) ''' container = self.get(image_name, quiet=True) i...
python
{ "resource": "" }
q272518
mv
test
def mv(self, image_name, path): '''Move an image from it's current location to a new path. Removing the image from organized storage is not the recommended approach however is still a function wanted by some. Parameters ========== image_name: the parsed image name. path: t...
python
{ "resource": "" }
q272519
rmi
test
def rmi(self, image_name): '''Remove an image from the database and filesystem. ''' container = self.rm(image_name, delete=True) if container is not None: bot.info("[rmi] %s" % container)
python
{ "resource": "" }
q272520
add
test
def add(self, image_path=None, image_uri=None, image_name=None, url=None, metadata=None, save=True, copy=False): '''get or create a container, including the collection to add it to. This function can be used from a file on the...
python
{ "resource": "" }
q272521
push
test
def push(self, path, name, tag=None): '''push an image to Singularity Registry''' path = os.path.abspath(path) image = os.path.basename(path) bot.debug("PUSH %s" % path) if not os.path.exists(path): bot.error('%s does not exist.' %path) sys.exit(1) # Interaction with a registr...
python
{ "resource": "" }
q272522
parse_header
test
def parse_header(recipe, header="from", remove_header=True): '''take a recipe, and return the complete header, line. If remove_header is True, only return the value. Parameters ========== recipe: the recipe file headers: the header key to find and parse remove_header: if t...
python
{ "resource": "" }
q272523
find_single_recipe
test
def find_single_recipe(filename, pattern="Singularity", manifest=None): '''find_single_recipe will parse a single file, and if valid, return an updated manifest Parameters ========== filename: the filename to assess for a recipe pattern: a default pattern to search for man...
python
{ "resource": "" }
q272524
create_build_package
test
def create_build_package(package_files): '''given a list of files, copy them to a temporary folder, compress into a .tar.gz, and rename based on the file hash. Return the full path to the .tar.gz in the temporary folder. Parameters ========== package_files: a list of files to inc...
python
{ "resource": "" }
q272525
run_build
test
def run_build(self, config, bucket, names): '''run a build, meaning creating a build. Retry if there is failure ''' project = self._get_project() # prefix, message, color bot.custom('PROJECT', project, "CYAN") bot.custom('BUILD ', config['steps'][0]['name'], "CYAN") response ...
python
{ "resource": "" }
q272526
update_blob_metadata
test
def update_blob_metadata(blob, response, config, bucket, names): '''a specific function to take a blob, along with a SUCCESS response from Google build, the original config, and update the blob metadata with the artifact file name, dependencies, and image hash. ''' manifest = os.path.basenam...
python
{ "resource": "" }
q272527
format_container_name
test
def format_container_name(name, special_characters=None): '''format_container_name will take a name supplied by the user, remove all special characters (except for those defined by "special-characters" and return the new image name. ''' if special_characters is None: special_characters = [] ...
python
{ "resource": "" }
q272528
SRegistryMessage.useColor
test
def useColor(self): '''useColor will determine if color should be added to a print. Will check if being run in a terminal, and if has support for asci''' COLORIZE = get_user_color_preference() if COLORIZE is not None: return COLORIZE streams = [self.errorStrea...
python
{ "resource": "" }
q272529
SRegistryMessage.emitError
test
def emitError(self, level): '''determine if a level should print to stderr, includes all levels but INFO and QUIET''' if level in [ABORT, ERROR, WARNING, VERBOSE, VERBOSE1, VERBOSE2, ...
python
{ "resource": "" }
q272530
SRegistryMessage.write
test
def write(self, stream, message): '''write will write a message to a stream, first checking the encoding ''' if isinstance(message, bytes): message = message.decode('utf-8') stream.write(message)
python
{ "resource": "" }
q272531
SRegistryMessage.table
test
def table(self, rows, col_width=2): '''table will print a table of entries. If the rows is a dictionary, the keys are interpreted as column names. if not, a numbered list is used. ''' labels = [str(x) for x in range(1,len(rows)+1)] if isinstance(rows, dict): ...
python
{ "resource": "" }
q272532
push
test
def push(self, path, name, tag=None): '''push an image to Globus endpoint. In this case, the name is the globus endpoint id and path. --name <endpointid>:/path/for/image ''' # Split the name into endpoint and rest endpoint, remote = self._parse_endpoint_name(name) path = os.path.a...
python
{ "resource": "" }
q272533
get_template
test
def get_template(name): '''return a default template for some function in sregistry If there is no template, None is returned. Parameters ========== name: the name of the template to retrieve ''' name = name.lower() templates = dict() templates['tarinfo'] = {"gid": 0, ...
python
{ "resource": "" }
q272534
get_manifest
test
def get_manifest(self, repo_name, tag): '''return the image manifest via the aws client, saved in self.manifest ''' image = None repo = self.aws.describe_images(repositoryName=repo_name) if 'imageDetails' in repo: for contender in repo.get('imageDetails'): if tag in contender['i...
python
{ "resource": "" }
q272535
get_build_template
test
def get_build_template(name=None, manager='apt'): '''get a particular build template, by default we return templates that are based on package managers. Parameters ========== name: the full path of the template file to use. manager: the package manager to use in the template (yum...
python
{ "resource": "" }
q272536
Client._update_secrets
test
def _update_secrets(self): '''update secrets will take a secrets credential file either located at .sregistry or the environment variable SREGISTRY_CLIENT_SECRETS and update the current client secrets as well as the associated API base. This is where you should do an...
python
{ "resource": "" }
q272537
_make_repr
test
def _make_repr(class_name, *args, **kwargs): """ Generate a repr string. Positional arguments should be the positional arguments used to construct the class. Keyword arguments should consist of tuples of the attribute value and default. If the value is the default, then it won't be rendered in ...
python
{ "resource": "" }
q272538
s3errors
test
def s3errors(path): """Translate S3 errors to FSErrors.""" try: yield except ClientError as error: _error = error.response.get("Error", {}) error_code = _error.get("Code", None) response_meta = error.response.get("ResponseMetadata", {}) http_status = response_meta.get...
python
{ "resource": "" }
q272539
S3File.factory
test
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
python
{ "resource": "" }
q272540
gravatar_url
test
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: ...
python
{ "resource": "" }
q272541
get_gravatar_url
test
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...
python
{ "resource": "" }
q272542
has_gravatar
test
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) ...
python
{ "resource": "" }
q272543
get_gravatar_profile_url
test
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...
python
{ "resource": "" }
q272544
chimera_blocks
test
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))
python
{ "resource": "" }
q272545
chimera_block_quotient
test
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...
python
{ "resource": "" }
q272546
enumerate_resonance_smiles
test
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...
python
{ "resource": "" }
q272547
ResonanceEnumerator.enumerate
test
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 """ ...
python
{ "resource": "" }
q272548
Normalizer.normalize
test
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...
python
{ "resource": "" }
q272549
Normalizer._apply_transform
test
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...
python
{ "resource": "" }
q272550
TautomerCanonicalizer.canonicalize
test
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...
python
{ "resource": "" }
q272551
validate_smiles
test
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...
python
{ "resource": "" }
q272552
MetalDisconnector.disconnect
test
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)....
python
{ "resource": "" }
q272553
standardize_smiles
test
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...
python
{ "resource": "" }
q272554
enumerate_tautomers_smiles
test
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...
python
{ "resource": "" }
q272555
canonicalize_tautomer_smiles
test
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...
python
{ "resource": "" }
q272556
Standardizer.standardize
test
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...
python
{ "resource": "" }
q272557
Standardizer.tautomer_parent
test
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...
python
{ "resource": "" }
q272558
Standardizer.fragment_parent
test
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...
python
{ "resource": "" }
q272559
Standardizer.stereo_parent
test
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...
python
{ "resource": "" }
q272560
Standardizer.isotope_parent
test
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_...
python
{ "resource": "" }
q272561
Standardizer.charge_parent
test
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...
python
{ "resource": "" }
q272562
Standardizer.super_parent
test
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...
python
{ "resource": "" }
q272563
main
test
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...
python
{ "resource": "" }
q272564
FragmentRemover.remove
test
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 ...
python
{ "resource": "" }
q272565
LargestFragmentChooser.choose
test
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:...
python
{ "resource": "" }
q272566
integrate_ivp
test
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_...
python
{ "resource": "" }
q272567
GitHub_LLNL_Stats.get_stats
test
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...
python
{ "resource": "" }
q272568
GitHub_LLNL_Stats.get_mems_of_org
test
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...
python
{ "resource": "" }
q272569
GitHub_LLNL_Stats.get_teams_of_org
test
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
python
{ "resource": "" }
q272570
GitHub_LLNL_Stats.repos
test
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...
python
{ "resource": "" }
q272571
GitHub_LLNL_Stats.get_total_contributors
test
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...
python
{ "resource": "" }
q272572
GitHub_LLNL_Stats.get_pull_reqs
test
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...
python
{ "resource": "" }
q272573
GitHub_LLNL_Stats.get_issues
test
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 ...
python
{ "resource": "" }
q272574
GitHub_LLNL_Stats.get_readme
test
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 ...
python
{ "resource": "" }
q272575
GitHub_LLNL_Stats.get_license
test
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...
python
{ "resource": "" }
q272576
GitHub_LLNL_Stats.get_commits
test
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...
python
{ "resource": "" }
q272577
GitHub_LLNL_Stats.write_org_json
test
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 + '/' + ...
python
{ "resource": "" }
q272578
GitHub_LLNL_Stats.write_totals
test
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_...
python
{ "resource": "" }
q272579
GitHub_LLNL_Stats.write_languages
test
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: ...
python
{ "resource": "" }
q272580
GitHub_LLNL_Stats.checkDir
test
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...
python
{ "resource": "" }
q272581
GitHub_LLNL_Stats.remove_date
test
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...
python
{ "resource": "" }
q272582
gov_orgs
test
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...
python
{ "resource": "" }
q272583
create_enterprise_session
test
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...
python
{ "resource": "" }
q272584
_check_api_limits
test
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...
python
{ "resource": "" }
q272585
connect
test
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: ...
python
{ "resource": "" }
q272586
query_repos
test
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 ...
python
{ "resource": "" }
q272587
GitHub_Stargazers.get_org
test
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...
python
{ "resource": "" }
q272588
GitHub_Stargazers.write_to_file
test
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...
python
{ "resource": "" }
q272589
Project.from_gitlab
test
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...
python
{ "resource": "" }
q272590
Project.from_doecode
test
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 -- ...
python
{ "resource": "" }
q272591
_license_obj
test
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' ...
python
{ "resource": "" }
q272592
GitHub_Traffic.get_traffic
test
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...
python
{ "resource": "" }
q272593
GitHub_Traffic.get_releases
test
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()
python
{ "resource": "" }
q272594
GitHub_Traffic.get_referrers
test
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...
python
{ "resource": "" }
q272595
GitHub_Traffic.get_data
test
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) ...
python
{ "resource": "" }
q272596
GitHub_Traffic.write_json
test
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 ...
python
{ "resource": "" }
q272597
GitHub_Traffic.write_to_file
test
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...
python
{ "resource": "" }
q272598
GitHub_Traffic.check_data_redundancy
test
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...
python
{ "resource": "" }
q272599
GitHub_Traffic.write_data_to_file
test
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: ...
python
{ "resource": "" }