repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Linaro/squad
squad/core/management/commands/users.py
Command.handle_update
def handle_update(self, options): # pylint: disable=no-self-use """ Update existing user""" username = options["username"] try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("User %s does not exist" % username) if options["email"]: user.email = options["email"] # False is an allowed value, but not None. if options["active"] in [True, False]: user.is_active = options["active"] if options["staff"] in [True, False]: user.is_staff = options["staff"] if options["superuser"] in [True, False]: user.is_superuser = options["superuser"] user.save()
python
def handle_update(self, options): # pylint: disable=no-self-use """ Update existing user""" username = options["username"] try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("User %s does not exist" % username) if options["email"]: user.email = options["email"] # False is an allowed value, but not None. if options["active"] in [True, False]: user.is_active = options["active"] if options["staff"] in [True, False]: user.is_staff = options["staff"] if options["superuser"] in [True, False]: user.is_superuser = options["superuser"] user.save()
[ "def", "handle_update", "(", "self", ",", "options", ")", ":", "# pylint: disable=no-self-use", "username", "=", "options", "[", "\"username\"", "]", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "except"...
Update existing user
[ "Update", "existing", "user" ]
27da5375e119312a86f231df95f99c979b9f48f0
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L176-L192
train
30,200
Linaro/squad
squad/core/management/commands/users.py
Command.handle_details
def handle_details(self, username): """ Print user details """ try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("Unable to find user '%s'" % username) self.stdout.write("username : %s" % username) self.stdout.write("is_active : %s" % user.is_active) self.stdout.write("is_staff : %s" % user.is_staff) self.stdout.write("is_superuser: %s" % user.is_superuser) groups = [g.name for g in user.groups.all().order_by("name")] self.stdout.write("groups : [%s]" % ", ".join(groups))
python
def handle_details(self, username): """ Print user details """ try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("Unable to find user '%s'" % username) self.stdout.write("username : %s" % username) self.stdout.write("is_active : %s" % user.is_active) self.stdout.write("is_staff : %s" % user.is_staff) self.stdout.write("is_superuser: %s" % user.is_superuser) groups = [g.name for g in user.groups.all().order_by("name")] self.stdout.write("groups : [%s]" % ", ".join(groups))
[ "def", "handle_details", "(", "self", ",", "username", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "except", "User", ".", "DoesNotExist", ":", "raise", "CommandError", "(", "\"Unable to find...
Print user details
[ "Print", "user", "details" ]
27da5375e119312a86f231df95f99c979b9f48f0
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L194-L206
train
30,201
Linaro/squad
squad/core/plugins.py
apply_plugins
def apply_plugins(plugin_names): """ This function should be used by code in the SQUAD core to trigger functionality from plugins. The ``plugin_names`` argument is list of plugins names to be used. Most probably, you will want to pass the list of plugins enabled for a given project, e.g. ``project.enabled_plugins``. Example:: from squad.core.plugins import apply_plugins # ... for plugin in apply_plugins(project.enabled_plugins): plugin.method(...) """ if plugin_names is None: return for p in plugin_names: try: plugin = get_plugin_instance(p) yield(plugin) except PluginNotFound: pass
python
def apply_plugins(plugin_names): """ This function should be used by code in the SQUAD core to trigger functionality from plugins. The ``plugin_names`` argument is list of plugins names to be used. Most probably, you will want to pass the list of plugins enabled for a given project, e.g. ``project.enabled_plugins``. Example:: from squad.core.plugins import apply_plugins # ... for plugin in apply_plugins(project.enabled_plugins): plugin.method(...) """ if plugin_names is None: return for p in plugin_names: try: plugin = get_plugin_instance(p) yield(plugin) except PluginNotFound: pass
[ "def", "apply_plugins", "(", "plugin_names", ")", ":", "if", "plugin_names", "is", "None", ":", "return", "for", "p", "in", "plugin_names", ":", "try", ":", "plugin", "=", "get_plugin_instance", "(", "p", ")", "yield", "(", "plugin", ")", "except", "Plugin...
This function should be used by code in the SQUAD core to trigger functionality from plugins. The ``plugin_names`` argument is list of plugins names to be used. Most probably, you will want to pass the list of plugins enabled for a given project, e.g. ``project.enabled_plugins``. Example:: from squad.core.plugins import apply_plugins # ... for plugin in apply_plugins(project.enabled_plugins): plugin.method(...)
[ "This", "function", "should", "be", "used", "by", "code", "in", "the", "SQUAD", "core", "to", "trigger", "functionality", "from", "plugins", "." ]
27da5375e119312a86f231df95f99c979b9f48f0
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/plugins.py#L61-L88
train
30,202
Linaro/squad
squad/core/models.py
Build.metadata
def metadata(self): """ The build metadata is the union of the metadata in its test runs. Common keys with different values are transformed into a list with each of the different values. """ if self.__metadata__ is None: metadata = {} for test_run in self.test_runs.defer(None).all(): for key, value in test_run.metadata.items(): metadata.setdefault(key, []) if value not in metadata[key]: metadata[key].append(value) for key in metadata.keys(): if len(metadata[key]) == 1: metadata[key] = metadata[key][0] else: metadata[key] = sorted(metadata[key], key=str) self.__metadata__ = metadata return self.__metadata__
python
def metadata(self): """ The build metadata is the union of the metadata in its test runs. Common keys with different values are transformed into a list with each of the different values. """ if self.__metadata__ is None: metadata = {} for test_run in self.test_runs.defer(None).all(): for key, value in test_run.metadata.items(): metadata.setdefault(key, []) if value not in metadata[key]: metadata[key].append(value) for key in metadata.keys(): if len(metadata[key]) == 1: metadata[key] = metadata[key][0] else: metadata[key] = sorted(metadata[key], key=str) self.__metadata__ = metadata return self.__metadata__
[ "def", "metadata", "(", "self", ")", ":", "if", "self", ".", "__metadata__", "is", "None", ":", "metadata", "=", "{", "}", "for", "test_run", "in", "self", ".", "test_runs", ".", "defer", "(", "None", ")", ".", "all", "(", ")", ":", "for", "key", ...
The build metadata is the union of the metadata in its test runs. Common keys with different values are transformed into a list with each of the different values.
[ "The", "build", "metadata", "is", "the", "union", "of", "the", "metadata", "in", "its", "test", "runs", ".", "Common", "keys", "with", "different", "values", "are", "transformed", "into", "a", "list", "with", "each", "of", "the", "different", "values", "."...
27da5375e119312a86f231df95f99c979b9f48f0
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/models.py#L352-L371
train
30,203
Linaro/squad
squad/api/rest.py
ProjectViewSet.builds
def builds(self, request, pk=None): """ List of builds for the current project. """ builds = self.get_object().builds.prefetch_related('test_runs').order_by('-datetime') page = self.paginate_queryset(builds) serializer = BuildSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data)
python
def builds(self, request, pk=None): """ List of builds for the current project. """ builds = self.get_object().builds.prefetch_related('test_runs').order_by('-datetime') page = self.paginate_queryset(builds) serializer = BuildSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data)
[ "def", "builds", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "builds", "=", "self", ".", "get_object", "(", ")", ".", "builds", ".", "prefetch_related", "(", "'test_runs'", ")", ".", "order_by", "(", "'-datetime'", ")", "page", "=", ...
List of builds for the current project.
[ "List", "of", "builds", "for", "the", "current", "project", "." ]
27da5375e119312a86f231df95f99c979b9f48f0
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/api/rest.py#L356-L363
train
30,204
Linaro/squad
squad/api/rest.py
ProjectViewSet.suites
def suites(self, request, pk=None): """ List of test suite names available in this project """ suites_names = self.get_object().suites.values_list('slug') suites_metadata = SuiteMetadata.objects.filter(kind='suite', suite__in=suites_names) page = self.paginate_queryset(suites_metadata) serializer = SuiteMetadataSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data)
python
def suites(self, request, pk=None): """ List of test suite names available in this project """ suites_names = self.get_object().suites.values_list('slug') suites_metadata = SuiteMetadata.objects.filter(kind='suite', suite__in=suites_names) page = self.paginate_queryset(suites_metadata) serializer = SuiteMetadataSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data)
[ "def", "suites", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "suites_names", "=", "self", ".", "get_object", "(", ")", ".", "suites", ".", "values_list", "(", "'slug'", ")", "suites_metadata", "=", "SuiteMetadata", ".", "objects", ".",...
List of test suite names available in this project
[ "List", "of", "test", "suite", "names", "available", "in", "this", "project" ]
27da5375e119312a86f231df95f99c979b9f48f0
https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/api/rest.py#L366-L374
train
30,205
NoRedInk/make-lambda-package
make_lambda_package/cli.py
main
def main( source, repo_source_files, requirements_file, local_source_file, work_dir): """ Bundle up a deployment package for AWS Lambda. From your local filesystem: \b $ make-lambda-package . ... dist/lambda-package.zip Or from a remote git repository: \b $ make-lambda-package https://github.com/NoRedInk/make-lambda-package.git ... vendor/dist/NoRedInk-make-lambda-package.zip Use # fragment to specify a commit or a branch: \b $ make-lambda-package https://github.com/NoRedInk/make-lambda-package.git#v1.0.0 Dependencies specified with --requirements-file will built using a docker container that replicates AWS Lambda's execution environment, so that extension modules are correctly packaged. When packaging a local source, --work-dir defaults to `.`: \b * ./build will hold a virtualenv for building dependencies if specified. * ./dist is where the zipped package will be saved When packaging a remote source, --work-dir defaults to `./vendor`. """ scm_source = fsutil.parse_path_or_url(source) paths = fsutil.decide_paths(scm_source, work_dir) if requirements_file: with open(os.devnull, 'w') as devnull: docker_retcode = subprocess.call(['docker', '--help'], stdout=devnull) if docker_retcode != 0: raise click.UsageError( "`docker` command doesn't seem to be available. " "It's required to package dependencies.") if not (requirements_file or repo_source_files or local_source_file): click.secho( 'Warning: without --repo-source-files, --requirements-file, ' 'or --local-source-file, nothing will be included in the zip file. ' 'Assuming you have good reasons to do this and proceeding.', fg='yellow') fsutil.ensure_dirs(paths) if isinstance(scm_source, fsutil.RemoteSource): click.echo('Fetching repo..') scm.fetch_repo(scm_source.url, scm_source.ref, paths.src_dir) deps_file = None if requirements_file: click.echo('Building deps..') deps_file = deps.build_deps(paths, requirements_file) click.echo('Creating zip file..') archive.make_archive( paths, repo_source_files, local_source_file, deps_file) click.echo(os.path.relpath(paths.zip_path, os.getcwd()))
python
def main( source, repo_source_files, requirements_file, local_source_file, work_dir): """ Bundle up a deployment package for AWS Lambda. From your local filesystem: \b $ make-lambda-package . ... dist/lambda-package.zip Or from a remote git repository: \b $ make-lambda-package https://github.com/NoRedInk/make-lambda-package.git ... vendor/dist/NoRedInk-make-lambda-package.zip Use # fragment to specify a commit or a branch: \b $ make-lambda-package https://github.com/NoRedInk/make-lambda-package.git#v1.0.0 Dependencies specified with --requirements-file will built using a docker container that replicates AWS Lambda's execution environment, so that extension modules are correctly packaged. When packaging a local source, --work-dir defaults to `.`: \b * ./build will hold a virtualenv for building dependencies if specified. * ./dist is where the zipped package will be saved When packaging a remote source, --work-dir defaults to `./vendor`. """ scm_source = fsutil.parse_path_or_url(source) paths = fsutil.decide_paths(scm_source, work_dir) if requirements_file: with open(os.devnull, 'w') as devnull: docker_retcode = subprocess.call(['docker', '--help'], stdout=devnull) if docker_retcode != 0: raise click.UsageError( "`docker` command doesn't seem to be available. " "It's required to package dependencies.") if not (requirements_file or repo_source_files or local_source_file): click.secho( 'Warning: without --repo-source-files, --requirements-file, ' 'or --local-source-file, nothing will be included in the zip file. ' 'Assuming you have good reasons to do this and proceeding.', fg='yellow') fsutil.ensure_dirs(paths) if isinstance(scm_source, fsutil.RemoteSource): click.echo('Fetching repo..') scm.fetch_repo(scm_source.url, scm_source.ref, paths.src_dir) deps_file = None if requirements_file: click.echo('Building deps..') deps_file = deps.build_deps(paths, requirements_file) click.echo('Creating zip file..') archive.make_archive( paths, repo_source_files, local_source_file, deps_file) click.echo(os.path.relpath(paths.zip_path, os.getcwd()))
[ "def", "main", "(", "source", ",", "repo_source_files", ",", "requirements_file", ",", "local_source_file", ",", "work_dir", ")", ":", "scm_source", "=", "fsutil", ".", "parse_path_or_url", "(", "source", ")", "paths", "=", "fsutil", ".", "decide_paths", "(", ...
Bundle up a deployment package for AWS Lambda. From your local filesystem: \b $ make-lambda-package . ... dist/lambda-package.zip Or from a remote git repository: \b $ make-lambda-package https://github.com/NoRedInk/make-lambda-package.git ... vendor/dist/NoRedInk-make-lambda-package.zip Use # fragment to specify a commit or a branch: \b $ make-lambda-package https://github.com/NoRedInk/make-lambda-package.git#v1.0.0 Dependencies specified with --requirements-file will built using a docker container that replicates AWS Lambda's execution environment, so that extension modules are correctly packaged. When packaging a local source, --work-dir defaults to `.`: \b * ./build will hold a virtualenv for building dependencies if specified. * ./dist is where the zipped package will be saved When packaging a remote source, --work-dir defaults to `./vendor`.
[ "Bundle", "up", "a", "deployment", "package", "for", "AWS", "Lambda", "." ]
eb9326352e41f7df3a630b06ad0a7554138c174a
https://github.com/NoRedInk/make-lambda-package/blob/eb9326352e41f7df3a630b06ad0a7554138c174a/make_lambda_package/cli.py#L29-L105
train
30,206
dwavesystems/dwave-neal
neal/sampler.py
_default_ising_beta_range
def _default_ising_beta_range(h, J): """Determine the starting and ending beta from h J Args: h (dict) J (dict) Assume each variable in J is also in h. We use the minimum bias to give a lower bound on the minimum energy gap, such at the final sweeps we are highly likely to settle into the current valley. """ # Get nonzero, absolute biases abs_h = [abs(hh) for hh in h.values() if hh != 0] abs_J = [abs(jj) for jj in J.values() if jj != 0] abs_biases = abs_h + abs_J if not abs_biases: return [0.1, 1.0] # Rough approximation of min change in energy when flipping a qubit min_delta_energy = min(abs_biases) # Combine absolute biases by variable abs_bias_dict = {k: abs(v) for k, v in h.items()} for (k1, k2), v in J.items(): abs_bias_dict[k1] += abs(v) abs_bias_dict[k2] += abs(v) # Find max change in energy when flipping a single qubit max_delta_energy = max(abs_bias_dict.values()) # Selecting betas based on probability of flipping a qubit # Hot temp: We want to scale hot_beta so that for the most unlikely qubit flip, we get at least # 50% chance of flipping.(This means all other qubits will have > 50% chance of flipping # initially.) Most unlikely flip is when we go from a very low energy state to a high energy # state, thus we calculate hot_beta based on max_delta_energy. # 0.50 = exp(-hot_beta * max_delta_energy) # # Cold temp: Towards the end of the annealing schedule, we want to minimize the chance of # flipping. Don't want to be stuck between small energy tweaks. Hence, set cold_beta so that # at minimum energy change, the chance of flipping is set to 1%. # 0.01 = exp(-cold_beta * min_delta_energy) hot_beta = np.log(2) / max_delta_energy cold_beta = np.log(100) / min_delta_energy return [hot_beta, cold_beta]
python
def _default_ising_beta_range(h, J): """Determine the starting and ending beta from h J Args: h (dict) J (dict) Assume each variable in J is also in h. We use the minimum bias to give a lower bound on the minimum energy gap, such at the final sweeps we are highly likely to settle into the current valley. """ # Get nonzero, absolute biases abs_h = [abs(hh) for hh in h.values() if hh != 0] abs_J = [abs(jj) for jj in J.values() if jj != 0] abs_biases = abs_h + abs_J if not abs_biases: return [0.1, 1.0] # Rough approximation of min change in energy when flipping a qubit min_delta_energy = min(abs_biases) # Combine absolute biases by variable abs_bias_dict = {k: abs(v) for k, v in h.items()} for (k1, k2), v in J.items(): abs_bias_dict[k1] += abs(v) abs_bias_dict[k2] += abs(v) # Find max change in energy when flipping a single qubit max_delta_energy = max(abs_bias_dict.values()) # Selecting betas based on probability of flipping a qubit # Hot temp: We want to scale hot_beta so that for the most unlikely qubit flip, we get at least # 50% chance of flipping.(This means all other qubits will have > 50% chance of flipping # initially.) Most unlikely flip is when we go from a very low energy state to a high energy # state, thus we calculate hot_beta based on max_delta_energy. # 0.50 = exp(-hot_beta * max_delta_energy) # # Cold temp: Towards the end of the annealing schedule, we want to minimize the chance of # flipping. Don't want to be stuck between small energy tweaks. Hence, set cold_beta so that # at minimum energy change, the chance of flipping is set to 1%. # 0.01 = exp(-cold_beta * min_delta_energy) hot_beta = np.log(2) / max_delta_energy cold_beta = np.log(100) / min_delta_energy return [hot_beta, cold_beta]
[ "def", "_default_ising_beta_range", "(", "h", ",", "J", ")", ":", "# Get nonzero, absolute biases", "abs_h", "=", "[", "abs", "(", "hh", ")", "for", "hh", "in", "h", ".", "values", "(", ")", "if", "hh", "!=", "0", "]", "abs_J", "=", "[", "abs", "(", ...
Determine the starting and ending beta from h J Args: h (dict) J (dict) Assume each variable in J is also in h. We use the minimum bias to give a lower bound on the minimum energy gap, such at the final sweeps we are highly likely to settle into the current valley.
[ "Determine", "the", "starting", "and", "ending", "beta", "from", "h", "J" ]
c9ce6251b9486e3c5e736e2171c07a4d643a31a5
https://github.com/dwavesystems/dwave-neal/blob/c9ce6251b9486e3c5e736e2171c07a4d643a31a5/neal/sampler.py#L295-L342
train
30,207
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF._getMultiClassMap
def _getMultiClassMap(self): """ Relief algorithms handle the scoring updates a little differently for data with multiclass outcomes. In ReBATE we implement multiclass scoring in line with the strategy described by Kononenko 1994 within the RELIEF-F variant which was suggested to outperform the RELIEF-E multiclass variant. This strategy weights score updates derived from misses of different classes by the class frequency observed in the training data. 'The idea is that the algorithm should estimate the ability of attributes to separate each pair of classes regardless of which two classes are closest to each other'. In this method we prepare for this normalization by creating a class dictionary, and storing respective class frequencies. This is needed for ReliefF multiclass score update normalizations. """ mcmap = dict() for i in range(self._datalen): if(self._y[i] not in mcmap): mcmap[self._y[i]] = 0 else: mcmap[self._y[i]] += 1 for each in self._label_list: mcmap[each] = mcmap[each]/float(self._datalen) return mcmap
python
def _getMultiClassMap(self): """ Relief algorithms handle the scoring updates a little differently for data with multiclass outcomes. In ReBATE we implement multiclass scoring in line with the strategy described by Kononenko 1994 within the RELIEF-F variant which was suggested to outperform the RELIEF-E multiclass variant. This strategy weights score updates derived from misses of different classes by the class frequency observed in the training data. 'The idea is that the algorithm should estimate the ability of attributes to separate each pair of classes regardless of which two classes are closest to each other'. In this method we prepare for this normalization by creating a class dictionary, and storing respective class frequencies. This is needed for ReliefF multiclass score update normalizations. """ mcmap = dict() for i in range(self._datalen): if(self._y[i] not in mcmap): mcmap[self._y[i]] = 0 else: mcmap[self._y[i]] += 1 for each in self._label_list: mcmap[each] = mcmap[each]/float(self._datalen) return mcmap
[ "def", "_getMultiClassMap", "(", "self", ")", ":", "mcmap", "=", "dict", "(", ")", "for", "i", "in", "range", "(", "self", ".", "_datalen", ")", ":", "if", "(", "self", ".", "_y", "[", "i", "]", "not", "in", "mcmap", ")", ":", "mcmap", "[", "se...
Relief algorithms handle the scoring updates a little differently for data with multiclass outcomes. In ReBATE we implement multiclass scoring in line with the strategy described by Kononenko 1994 within the RELIEF-F variant which was suggested to outperform the RELIEF-E multiclass variant. This strategy weights score updates derived from misses of different classes by the class frequency observed in the training data. 'The idea is that the algorithm should estimate the ability of attributes to separate each pair of classes regardless of which two classes are closest to each other'. In this method we prepare for this normalization by creating a class dictionary, and storing respective class frequencies. This is needed for ReliefF multiclass score update normalizations.
[ "Relief", "algorithms", "handle", "the", "scoring", "updates", "a", "little", "differently", "for", "data", "with", "multiclass", "outcomes", ".", "In", "ReBATE", "we", "implement", "multiclass", "scoring", "in", "line", "with", "the", "strategy", "described", "...
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L258-L275
train
30,208
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF._distarray_missing
def _distarray_missing(self, xc, xd, cdiffs): """Distance array calculation for data with missing values""" cindices = [] dindices = [] # Get Boolean mask locating missing values for continuous and discrete features separately. These correspond to xc and xd respectively. for i in range(self._datalen): cindices.append(np.where(np.isnan(xc[i]))[0]) dindices.append(np.where(np.isnan(xd[i]))[0]) if self.n_jobs != 1: dist_array = Parallel(n_jobs=self.n_jobs)(delayed(get_row_missing)( xc, xd, cdiffs, index, cindices, dindices) for index in range(self._datalen)) else: # For each instance calculate distance from all other instances (in non-redundant manner) (i.e. computes triangle, and puts zeros in for rest to form square). dist_array = [get_row_missing(xc, xd, cdiffs, index, cindices, dindices) for index in range(self._datalen)] return np.array(dist_array)
python
def _distarray_missing(self, xc, xd, cdiffs): """Distance array calculation for data with missing values""" cindices = [] dindices = [] # Get Boolean mask locating missing values for continuous and discrete features separately. These correspond to xc and xd respectively. for i in range(self._datalen): cindices.append(np.where(np.isnan(xc[i]))[0]) dindices.append(np.where(np.isnan(xd[i]))[0]) if self.n_jobs != 1: dist_array = Parallel(n_jobs=self.n_jobs)(delayed(get_row_missing)( xc, xd, cdiffs, index, cindices, dindices) for index in range(self._datalen)) else: # For each instance calculate distance from all other instances (in non-redundant manner) (i.e. computes triangle, and puts zeros in for rest to form square). dist_array = [get_row_missing(xc, xd, cdiffs, index, cindices, dindices) for index in range(self._datalen)] return np.array(dist_array)
[ "def", "_distarray_missing", "(", "self", ",", "xc", ",", "xd", ",", "cdiffs", ")", ":", "cindices", "=", "[", "]", "dindices", "=", "[", "]", "# Get Boolean mask locating missing values for continuous and discrete features separately. These correspond to xc and xd respective...
Distance array calculation for data with missing values
[ "Distance", "array", "calculation", "for", "data", "with", "missing", "values" ]
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L357-L374
train
30,209
EpistasisLab/scikit-rebate
skrebate/surfstar.py
SURFstar._find_neighbors
def _find_neighbors(self, inst, avg_dist): """ Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type. """ NN_near = [] NN_far = [] min_indices = [] max_indices = [] for i in range(self._datalen): if inst != i: locator = [inst, i] if i > inst: locator.reverse() d = self._distance_array[locator[0]][locator[1]] if d < avg_dist: min_indices.append(i) if d > avg_dist: max_indices.append(i) for i in range(len(min_indices)): NN_near.append(min_indices[i]) for i in range(len(max_indices)): NN_far.append(max_indices[i]) return np.array(NN_near, dtype=np.int32), np.array(NN_far, dtype=np.int32)
python
def _find_neighbors(self, inst, avg_dist): """ Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type. """ NN_near = [] NN_far = [] min_indices = [] max_indices = [] for i in range(self._datalen): if inst != i: locator = [inst, i] if i > inst: locator.reverse() d = self._distance_array[locator[0]][locator[1]] if d < avg_dist: min_indices.append(i) if d > avg_dist: max_indices.append(i) for i in range(len(min_indices)): NN_near.append(min_indices[i]) for i in range(len(max_indices)): NN_far.append(max_indices[i]) return np.array(NN_near, dtype=np.int32), np.array(NN_far, dtype=np.int32)
[ "def", "_find_neighbors", "(", "self", ",", "inst", ",", "avg_dist", ")", ":", "NN_near", "=", "[", "]", "NN_far", "=", "[", "]", "min_indices", "=", "[", "]", "max_indices", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "_datalen", "...
Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type.
[ "Identify", "nearest", "as", "well", "as", "farthest", "hits", "and", "misses", "within", "radius", "defined", "by", "average", "distance", "over", "whole", "distance", "array", ".", "This", "works", "the", "same", "regardless", "of", "endpoint", "type", "." ]
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/surfstar.py#L46-L70
train
30,210
EpistasisLab/scikit-rebate
skrebate/scoring_utils.py
get_row_missing
def get_row_missing(xc, xd, cdiffs, index, cindices, dindices): """ Calculate distance between index instance and all other instances. """ row = np.empty(0, dtype=np.double) # initialize empty row cinst1 = xc[index] # continuous-valued features for index instance dinst1 = xd[index] # discrete-valued features for index instance # Boolean mask locating missing values for continuous features for index instance can = cindices[index] # Boolean mask locating missing values for discrete features for index instance dan = dindices[index] tf = len(cinst1) + len(dinst1) # total number of features. # Progressively compare current instance to all others. Excludes comparison with self indexed instance. (Building the distance matrix triangle). for j in range(index): dist = 0 dinst2 = xd[j] # discrete-valued features for compared instance cinst2 = xc[j] # continuous-valued features for compared instance # Manage missing values in discrete features # Boolean mask locating missing values for discrete features for compared instance dbn = dindices[j] # indexes where there is at least one missing value in the feature between an instance pair. idx = np.unique(np.append(dan, dbn)) # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison. dmc = len(idx) d1 = np.delete(dinst1, idx) # delete unique missing features from index instance d2 = np.delete(dinst2, idx) # delete unique missing features from compared instance # Manage missing values in continuous features # Boolean mask locating missing values for continuous features for compared instance cbn = cindices[j] # indexes where there is at least one missing value in the feature between an instance pair. idx = np.unique(np.append(can, cbn)) # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison. cmc = len(idx) c1 = np.delete(cinst1, idx) # delete unique missing features from index instance c2 = np.delete(cinst2, idx) # delete unique missing features from compared instance # delete unique missing features from continuous value difference scores cdf = np.delete(cdiffs, idx) # Add discrete feature distance contributions (missing values excluded) - Hamming distance dist += len(d1[d1 != d2]) # Add continuous feature distance contributions (missing values excluded) - Manhattan distance (Note that 0-1 continuous value normalization is included ~ subtraction of minimums cancel out) dist += np.sum(np.absolute(np.subtract(c1, c2)) / cdf) # Normalize distance calculation based on total number of missing values bypassed in either discrete or continuous features. tnmc = tf - dmc - cmc # Total number of unique missing counted # Distance normalized by number of features included in distance sum (this seeks to handle missing values neutrally in distance calculation) dist = dist/float(tnmc) row = np.append(row, dist) return row
python
def get_row_missing(xc, xd, cdiffs, index, cindices, dindices): """ Calculate distance between index instance and all other instances. """ row = np.empty(0, dtype=np.double) # initialize empty row cinst1 = xc[index] # continuous-valued features for index instance dinst1 = xd[index] # discrete-valued features for index instance # Boolean mask locating missing values for continuous features for index instance can = cindices[index] # Boolean mask locating missing values for discrete features for index instance dan = dindices[index] tf = len(cinst1) + len(dinst1) # total number of features. # Progressively compare current instance to all others. Excludes comparison with self indexed instance. (Building the distance matrix triangle). for j in range(index): dist = 0 dinst2 = xd[j] # discrete-valued features for compared instance cinst2 = xc[j] # continuous-valued features for compared instance # Manage missing values in discrete features # Boolean mask locating missing values for discrete features for compared instance dbn = dindices[j] # indexes where there is at least one missing value in the feature between an instance pair. idx = np.unique(np.append(dan, dbn)) # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison. dmc = len(idx) d1 = np.delete(dinst1, idx) # delete unique missing features from index instance d2 = np.delete(dinst2, idx) # delete unique missing features from compared instance # Manage missing values in continuous features # Boolean mask locating missing values for continuous features for compared instance cbn = cindices[j] # indexes where there is at least one missing value in the feature between an instance pair. idx = np.unique(np.append(can, cbn)) # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison. cmc = len(idx) c1 = np.delete(cinst1, idx) # delete unique missing features from index instance c2 = np.delete(cinst2, idx) # delete unique missing features from compared instance # delete unique missing features from continuous value difference scores cdf = np.delete(cdiffs, idx) # Add discrete feature distance contributions (missing values excluded) - Hamming distance dist += len(d1[d1 != d2]) # Add continuous feature distance contributions (missing values excluded) - Manhattan distance (Note that 0-1 continuous value normalization is included ~ subtraction of minimums cancel out) dist += np.sum(np.absolute(np.subtract(c1, c2)) / cdf) # Normalize distance calculation based on total number of missing values bypassed in either discrete or continuous features. tnmc = tf - dmc - cmc # Total number of unique missing counted # Distance normalized by number of features included in distance sum (this seeks to handle missing values neutrally in distance calculation) dist = dist/float(tnmc) row = np.append(row, dist) return row
[ "def", "get_row_missing", "(", "xc", ",", "xd", ",", "cdiffs", ",", "index", ",", "cindices", ",", "dindices", ")", ":", "row", "=", "np", ".", "empty", "(", "0", ",", "dtype", "=", "np", ".", "double", ")", "# initialize empty row\r", "cinst1", "=", ...
Calculate distance between index instance and all other instances.
[ "Calculate", "distance", "between", "index", "instance", "and", "all", "other", "instances", "." ]
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L31-L83
train
30,211
EpistasisLab/scikit-rebate
skrebate/scoring_utils.py
ramp_function
def ramp_function(data_type, attr, fname, xinstfeature, xNNifeature): """ Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds that indicate the max difference before a score of 1 is given, as well a min difference before a score of 0 is given, and any in the middle get a score that is the normalized difference between the two continuous feature values. This was done because when discrete and continuous features were mixed, continuous feature scores were underestimated. Towards simplicity, automation, and a dataset adaptable approach, here we simply check whether the difference is greater than the standard deviation for the given feature; if so we assign a score of 1, otherwise we assign the normalized feature score difference. This should help compensate for the underestimation. """ diff = 0 mmdiff = attr[fname][3] # Max/Min range of values for target feature rawfd = abs(xinstfeature - xNNifeature) # prenormalized feature value difference if data_type == 'mixed': # Ramp function utilized # Check whether feature value difference is greater than the standard deviation standDev = attr[fname][4] if rawfd > standDev: # feature value difference is is wider than a standard deviation diff = 1 else: diff = abs(xinstfeature - xNNifeature) / mmdiff else: # Normal continuous feature scoring diff = abs(xinstfeature - xNNifeature) / mmdiff return diff
python
def ramp_function(data_type, attr, fname, xinstfeature, xNNifeature): """ Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds that indicate the max difference before a score of 1 is given, as well a min difference before a score of 0 is given, and any in the middle get a score that is the normalized difference between the two continuous feature values. This was done because when discrete and continuous features were mixed, continuous feature scores were underestimated. Towards simplicity, automation, and a dataset adaptable approach, here we simply check whether the difference is greater than the standard deviation for the given feature; if so we assign a score of 1, otherwise we assign the normalized feature score difference. This should help compensate for the underestimation. """ diff = 0 mmdiff = attr[fname][3] # Max/Min range of values for target feature rawfd = abs(xinstfeature - xNNifeature) # prenormalized feature value difference if data_type == 'mixed': # Ramp function utilized # Check whether feature value difference is greater than the standard deviation standDev = attr[fname][4] if rawfd > standDev: # feature value difference is is wider than a standard deviation diff = 1 else: diff = abs(xinstfeature - xNNifeature) / mmdiff else: # Normal continuous feature scoring diff = abs(xinstfeature - xNNifeature) / mmdiff return diff
[ "def", "ramp_function", "(", "data_type", ",", "attr", ",", "fname", ",", "xinstfeature", ",", "xNNifeature", ")", ":", "diff", "=", "0", "mmdiff", "=", "attr", "[", "fname", "]", "[", "3", "]", "# Max/Min range of values for target feature\r", "rawfd", "=", ...
Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds that indicate the max difference before a score of 1 is given, as well a min difference before a score of 0 is given, and any in the middle get a score that is the normalized difference between the two continuous feature values. This was done because when discrete and continuous features were mixed, continuous feature scores were underestimated. Towards simplicity, automation, and a dataset adaptable approach, here we simply check whether the difference is greater than the standard deviation for the given feature; if so we assign a score of 1, otherwise we assign the normalized feature score difference. This should help compensate for the underestimation.
[ "Our", "own", "user", "simplified", "variation", "of", "the", "ramp", "function", "suggested", "by", "Hong", "1994", "1997", ".", "Hong", "s", "method", "requires", "the", "user", "to", "specifiy", "two", "thresholds", "that", "indicate", "the", "max", "diff...
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L86-L108
train
30,212
EpistasisLab/scikit-rebate
skrebate/scoring_utils.py
ReliefF_compute_scores
def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type): """ Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. """ scores = np.zeros(num_attributes) for feature_num in range(num_attributes): scores[feature_num] += compute_score(attr, mcmap, NN, feature_num, inst, nan_entries, headers, class_type, X, y, labels_std, data_type) return scores
python
def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type): """ Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. """ scores = np.zeros(num_attributes) for feature_num in range(num_attributes): scores[feature_num] += compute_score(attr, mcmap, NN, feature_num, inst, nan_entries, headers, class_type, X, y, labels_std, data_type) return scores
[ "def", "ReliefF_compute_scores", "(", "inst", ",", "attr", ",", "nan_entries", ",", "num_attributes", ",", "mcmap", ",", "NN", ",", "headers", ",", "class_type", ",", "X", ",", "y", ",", "labels_std", ",", "data_type", ")", ":", "scores", "=", "np", ".",...
Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance.
[ "Unique", "scoring", "procedure", "for", "ReliefF", "algorithm", ".", "Scoring", "based", "on", "k", "nearest", "hits", "and", "misses", "of", "current", "target", "instance", "." ]
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L352-L358
train
30,213
EpistasisLab/scikit-rebate
skrebate/scoring_utils.py
SURFstar_compute_scores
def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type): """ Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as 'anti-scoring' of far instances outside of radius of current target instance""" scores = np.zeros(num_attributes) for feature_num in range(num_attributes): if len(NN_near) > 0: scores[feature_num] += compute_score(attr, mcmap, NN_near, feature_num, inst, nan_entries, headers, class_type, X, y, labels_std, data_type) # Note that we are using the near scoring loop in 'compute_score' and then just subtracting it here, in line with original SURF* paper. if len(NN_far) > 0: scores[feature_num] -= compute_score(attr, mcmap, NN_far, feature_num, inst, nan_entries, headers, class_type, X, y, labels_std, data_type) return scores
python
def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type): """ Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as 'anti-scoring' of far instances outside of radius of current target instance""" scores = np.zeros(num_attributes) for feature_num in range(num_attributes): if len(NN_near) > 0: scores[feature_num] += compute_score(attr, mcmap, NN_near, feature_num, inst, nan_entries, headers, class_type, X, y, labels_std, data_type) # Note that we are using the near scoring loop in 'compute_score' and then just subtracting it here, in line with original SURF* paper. if len(NN_far) > 0: scores[feature_num] -= compute_score(attr, mcmap, NN_far, feature_num, inst, nan_entries, headers, class_type, X, y, labels_std, data_type) return scores
[ "def", "SURFstar_compute_scores", "(", "inst", ",", "attr", ",", "nan_entries", ",", "num_attributes", ",", "mcmap", ",", "NN_near", ",", "NN_far", ",", "headers", ",", "class_type", ",", "X", ",", "y", ",", "labels_std", ",", "data_type", ")", ":", "score...
Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as 'anti-scoring' of far instances outside of radius of current target instance
[ "Unique", "scoring", "procedure", "for", "SURFstar", "algorithm", ".", "Scoring", "based", "on", "nearest", "neighbors", "within", "defined", "radius", "as", "well", "as", "anti", "-", "scoring", "of", "far", "instances", "outside", "of", "radius", "of", "curr...
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L372-L384
train
30,214
EpistasisLab/scikit-rebate
skrebate/multisurfstar.py
MultiSURFstar._find_neighbors
def _find_neighbors(self, inst): """ Identify nearest as well as farthest hits and misses within radius defined by average distance and standard deviation of distances from target instanace. This works the same regardless of endpoint type. """ dist_vect = [] for j in range(self._datalen): if inst != j: locator = [inst, j] if inst < j: locator.reverse() dist_vect.append(self._distance_array[locator[0]][locator[1]]) dist_vect = np.array(dist_vect) inst_avg_dist = np.average(dist_vect) inst_std = np.std(dist_vect) / 2. near_threshold = inst_avg_dist - inst_std far_threshold = inst_avg_dist + inst_std NN_near = [] NN_far = [] for j in range(self._datalen): if inst != j: locator = [inst, j] if inst < j: locator.reverse() if self._distance_array[locator[0]][locator[1]] < near_threshold: NN_near.append(j) elif self._distance_array[locator[0]][locator[1]] > far_threshold: NN_far.append(j) return np.array(NN_near), np.array(NN_far)
python
def _find_neighbors(self, inst): """ Identify nearest as well as farthest hits and misses within radius defined by average distance and standard deviation of distances from target instanace. This works the same regardless of endpoint type. """ dist_vect = [] for j in range(self._datalen): if inst != j: locator = [inst, j] if inst < j: locator.reverse() dist_vect.append(self._distance_array[locator[0]][locator[1]]) dist_vect = np.array(dist_vect) inst_avg_dist = np.average(dist_vect) inst_std = np.std(dist_vect) / 2. near_threshold = inst_avg_dist - inst_std far_threshold = inst_avg_dist + inst_std NN_near = [] NN_far = [] for j in range(self._datalen): if inst != j: locator = [inst, j] if inst < j: locator.reverse() if self._distance_array[locator[0]][locator[1]] < near_threshold: NN_near.append(j) elif self._distance_array[locator[0]][locator[1]] > far_threshold: NN_far.append(j) return np.array(NN_near), np.array(NN_far)
[ "def", "_find_neighbors", "(", "self", ",", "inst", ")", ":", "dist_vect", "=", "[", "]", "for", "j", "in", "range", "(", "self", ".", "_datalen", ")", ":", "if", "inst", "!=", "j", ":", "locator", "=", "[", "inst", ",", "j", "]", "if", "inst", ...
Identify nearest as well as farthest hits and misses within radius defined by average distance and standard deviation of distances from target instanace. This works the same regardless of endpoint type.
[ "Identify", "nearest", "as", "well", "as", "farthest", "hits", "and", "misses", "within", "radius", "defined", "by", "average", "distance", "and", "standard", "deviation", "of", "distances", "from", "target", "instanace", ".", "This", "works", "the", "same", "...
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/multisurfstar.py#L46-L75
train
30,215
EpistasisLab/scikit-rebate
skrebate/surf.py
SURF._find_neighbors
def _find_neighbors(self, inst, avg_dist): """ Identify nearest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type. """ NN = [] min_indicies = [] for i in range(self._datalen): if inst != i: locator = [inst, i] if i > inst: locator.reverse() d = self._distance_array[locator[0]][locator[1]] if d < avg_dist: # Defining the neighborhood with an average distance radius. min_indicies.append(i) for i in range(len(min_indicies)): NN.append(min_indicies[i]) return np.array(NN, dtype=np.int32)
python
def _find_neighbors(self, inst, avg_dist): """ Identify nearest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type. """ NN = [] min_indicies = [] for i in range(self._datalen): if inst != i: locator = [inst, i] if i > inst: locator.reverse() d = self._distance_array[locator[0]][locator[1]] if d < avg_dist: # Defining the neighborhood with an average distance radius. min_indicies.append(i) for i in range(len(min_indicies)): NN.append(min_indicies[i]) return np.array(NN, dtype=np.int32)
[ "def", "_find_neighbors", "(", "self", ",", "inst", ",", "avg_dist", ")", ":", "NN", "=", "[", "]", "min_indicies", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "_datalen", ")", ":", "if", "inst", "!=", "i", ":", "locator", "=", "[...
Identify nearest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type.
[ "Identify", "nearest", "hits", "and", "misses", "within", "radius", "defined", "by", "average", "distance", "over", "whole", "distance", "array", ".", "This", "works", "the", "same", "regardless", "of", "endpoint", "type", "." ]
67dab51a7525fa5d076b059f1e6f8cff7481c1ef
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/surf.py#L71-L87
train
30,216
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker.leave_module
def leave_module(self, node): """Leave module and check remaining triple quotes. Args: node: the module node we are leaving. """ for triple_quote in self._tokenized_triple_quotes.values(): self._check_triple_quotes(triple_quote) # after we are done checking these, clear out the triple-quote # tracking collection so nothing is left over for the next module. self._tokenized_triple_quotes = {}
python
def leave_module(self, node): """Leave module and check remaining triple quotes. Args: node: the module node we are leaving. """ for triple_quote in self._tokenized_triple_quotes.values(): self._check_triple_quotes(triple_quote) # after we are done checking these, clear out the triple-quote # tracking collection so nothing is left over for the next module. self._tokenized_triple_quotes = {}
[ "def", "leave_module", "(", "self", ",", "node", ")", ":", "for", "triple_quote", "in", "self", ".", "_tokenized_triple_quotes", ".", "values", "(", ")", ":", "self", ".", "_check_triple_quotes", "(", "triple_quote", ")", "# after we are done checking these, clear o...
Leave module and check remaining triple quotes. Args: node: the module node we are leaving.
[ "Leave", "module", "and", "check", "remaining", "triple", "quotes", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L110-L121
train
30,217
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._process_for_docstring
def _process_for_docstring(self, node, node_type): """Check for docstring quote consistency. Args: node: the AST node being visited. node_type: the type of node being operated on. """ # if there is no docstring, don't need to do anything. if node.doc is not None: # the module is everything, so to find the docstring, we # iterate line by line from the start until the first element # to find the docstring, as it cannot appear after the first # element in the body. if node_type == 'module': # if there are no nodes that make up the body, then all we # have is the module docstring if not node.body: # in this case, we should only have the module docstring # parsed in the node, so the only record in the # self._tokenized_triple_quotes dict will correspond to # the module comment. this can vary by index depending # on the presence of a shebang, encoding, etc at the top # of the file. for key in list(self._tokenized_triple_quotes.keys()): quote_record = self._tokenized_triple_quotes.get(key) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[key] else: for i in range(0, node.body[0].lineno): quote_record = self._tokenized_triple_quotes.get(i) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[i] break else: # the node has a docstring so we check the tokenized triple # quotes to find a matching docstring token that follows the # function/class definition. if not node.body: # if there is no body to the class, the class def only # contains the docstring, so the only quotes we are # tracking should correspond to the class docstring. lineno = self._find_docstring_line_for_no_body(node.fromlineno) quote_record = self._tokenized_triple_quotes.get(lineno) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[lineno] else: doc_row = self._find_docstring_line(node.fromlineno, node.tolineno) quote_record = self._tokenized_triple_quotes.get(doc_row) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[doc_row]
python
def _process_for_docstring(self, node, node_type): """Check for docstring quote consistency. Args: node: the AST node being visited. node_type: the type of node being operated on. """ # if there is no docstring, don't need to do anything. if node.doc is not None: # the module is everything, so to find the docstring, we # iterate line by line from the start until the first element # to find the docstring, as it cannot appear after the first # element in the body. if node_type == 'module': # if there are no nodes that make up the body, then all we # have is the module docstring if not node.body: # in this case, we should only have the module docstring # parsed in the node, so the only record in the # self._tokenized_triple_quotes dict will correspond to # the module comment. this can vary by index depending # on the presence of a shebang, encoding, etc at the top # of the file. for key in list(self._tokenized_triple_quotes.keys()): quote_record = self._tokenized_triple_quotes.get(key) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[key] else: for i in range(0, node.body[0].lineno): quote_record = self._tokenized_triple_quotes.get(i) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[i] break else: # the node has a docstring so we check the tokenized triple # quotes to find a matching docstring token that follows the # function/class definition. if not node.body: # if there is no body to the class, the class def only # contains the docstring, so the only quotes we are # tracking should correspond to the class docstring. lineno = self._find_docstring_line_for_no_body(node.fromlineno) quote_record = self._tokenized_triple_quotes.get(lineno) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[lineno] else: doc_row = self._find_docstring_line(node.fromlineno, node.tolineno) quote_record = self._tokenized_triple_quotes.get(doc_row) if quote_record: self._check_docstring_quotes(quote_record) del self._tokenized_triple_quotes[doc_row]
[ "def", "_process_for_docstring", "(", "self", ",", "node", ",", "node_type", ")", ":", "# if there is no docstring, don't need to do anything.", "if", "node", ".", "doc", "is", "not", "None", ":", "# the module is everything, so to find the docstring, we", "# iterate line by ...
Check for docstring quote consistency. Args: node: the AST node being visited. node_type: the type of node being operated on.
[ "Check", "for", "docstring", "quote", "consistency", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L147-L206
train
30,218
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._find_docstring_line_for_no_body
def _find_docstring_line_for_no_body(self, start): """Find the docstring associated with a definition with no body in the node. In these cases, the provided start and end line number for that element are the same, so we must get the docstring based on the sequential position of known docstrings. Args: start: the row where the class / function starts. Returns: int: the row number where the docstring is found. """ tracked = sorted(list(self._tokenized_triple_quotes.keys())) for i in tracked: if min(start, i) == start: return i return None
python
def _find_docstring_line_for_no_body(self, start): """Find the docstring associated with a definition with no body in the node. In these cases, the provided start and end line number for that element are the same, so we must get the docstring based on the sequential position of known docstrings. Args: start: the row where the class / function starts. Returns: int: the row number where the docstring is found. """ tracked = sorted(list(self._tokenized_triple_quotes.keys())) for i in tracked: if min(start, i) == start: return i return None
[ "def", "_find_docstring_line_for_no_body", "(", "self", ",", "start", ")", ":", "tracked", "=", "sorted", "(", "list", "(", "self", ".", "_tokenized_triple_quotes", ".", "keys", "(", ")", ")", ")", "for", "i", "in", "tracked", ":", "if", "min", "(", "sta...
Find the docstring associated with a definition with no body in the node. In these cases, the provided start and end line number for that element are the same, so we must get the docstring based on the sequential position of known docstrings. Args: start: the row where the class / function starts. Returns: int: the row number where the docstring is found.
[ "Find", "the", "docstring", "associated", "with", "a", "definition", "with", "no", "body", "in", "the", "node", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L208-L227
train
30,219
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._find_docstring_line
def _find_docstring_line(self, start, end): """Find the row where a docstring starts in a function or class. This will search for the first match of a triple quote token in row sequence from the start of the class or function. Args: start: the row where the class / function starts. end: the row where the class / function ends. Returns: int: the row number where the docstring is found. """ for i in range(start, end + 1): if i in self._tokenized_triple_quotes: return i return None
python
def _find_docstring_line(self, start, end): """Find the row where a docstring starts in a function or class. This will search for the first match of a triple quote token in row sequence from the start of the class or function. Args: start: the row where the class / function starts. end: the row where the class / function ends. Returns: int: the row number where the docstring is found. """ for i in range(start, end + 1): if i in self._tokenized_triple_quotes: return i return None
[ "def", "_find_docstring_line", "(", "self", ",", "start", ",", "end", ")", ":", "for", "i", "in", "range", "(", "start", ",", "end", "+", "1", ")", ":", "if", "i", "in", "self", ".", "_tokenized_triple_quotes", ":", "return", "i", "return", "None" ]
Find the row where a docstring starts in a function or class. This will search for the first match of a triple quote token in row sequence from the start of the class or function. Args: start: the row where the class / function starts. end: the row where the class / function ends. Returns: int: the row number where the docstring is found.
[ "Find", "the", "row", "where", "a", "docstring", "starts", "in", "a", "function", "or", "class", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L229-L245
train
30,220
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker.process_tokens
def process_tokens(self, tokens): """Process the token stream. This is required to override the parent class' implementation. Args: tokens: the tokens from the token stream to process. """ for tok_type, token, (start_row, start_col), _, _ in tokens: if tok_type == tokenize.STRING: # 'token' is the whole un-parsed token; we can look at the start # of it to see whether it's a raw or unicode string etc. self._process_string_token(token, start_row, start_col)
python
def process_tokens(self, tokens): """Process the token stream. This is required to override the parent class' implementation. Args: tokens: the tokens from the token stream to process. """ for tok_type, token, (start_row, start_col), _, _ in tokens: if tok_type == tokenize.STRING: # 'token' is the whole un-parsed token; we can look at the start # of it to see whether it's a raw or unicode string etc. self._process_string_token(token, start_row, start_col)
[ "def", "process_tokens", "(", "self", ",", "tokens", ")", ":", "for", "tok_type", ",", "token", ",", "(", "start_row", ",", "start_col", ")", ",", "_", ",", "_", "in", "tokens", ":", "if", "tok_type", "==", "tokenize", ".", "STRING", ":", "# 'token' is...
Process the token stream. This is required to override the parent class' implementation. Args: tokens: the tokens from the token stream to process.
[ "Process", "the", "token", "stream", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L247-L259
train
30,221
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._process_string_token
def _process_string_token(self, token, start_row, start_col): """Internal method for identifying and checking string tokens from the token stream. Args: token: the token to check. start_row: the line on which the token was found. start_col: the column on which the token was found. """ for i, char in enumerate(token): if char in QUOTES: break # pylint: disable=undefined-loop-variable # ignore prefix markers like u, b, r norm_quote = token[i:] # triple-quote strings if len(norm_quote) >= 3 and norm_quote[:3] in TRIPLE_QUOTE_OPTS.values(): self._tokenized_triple_quotes[start_row] = (token, norm_quote[:3], start_row, start_col) return # single quote strings preferred_quote = SMART_QUOTE_OPTS.get(self.config.string_quote) # Smart case. if self.config.string_quote in SMART_CONFIG_OPTS: other_quote = next(q for q in QUOTES if q != preferred_quote) # If using the other quote avoids escaping, we switch to the other quote. if preferred_quote in token[i + 1:-1] and other_quote not in token[i + 1:-1]: preferred_quote = other_quote if norm_quote[0] != preferred_quote: self._invalid_string_quote( quote=norm_quote[0], row=start_row, correct_quote=preferred_quote, col=start_col, )
python
def _process_string_token(self, token, start_row, start_col): """Internal method for identifying and checking string tokens from the token stream. Args: token: the token to check. start_row: the line on which the token was found. start_col: the column on which the token was found. """ for i, char in enumerate(token): if char in QUOTES: break # pylint: disable=undefined-loop-variable # ignore prefix markers like u, b, r norm_quote = token[i:] # triple-quote strings if len(norm_quote) >= 3 and norm_quote[:3] in TRIPLE_QUOTE_OPTS.values(): self._tokenized_triple_quotes[start_row] = (token, norm_quote[:3], start_row, start_col) return # single quote strings preferred_quote = SMART_QUOTE_OPTS.get(self.config.string_quote) # Smart case. if self.config.string_quote in SMART_CONFIG_OPTS: other_quote = next(q for q in QUOTES if q != preferred_quote) # If using the other quote avoids escaping, we switch to the other quote. if preferred_quote in token[i + 1:-1] and other_quote not in token[i + 1:-1]: preferred_quote = other_quote if norm_quote[0] != preferred_quote: self._invalid_string_quote( quote=norm_quote[0], row=start_row, correct_quote=preferred_quote, col=start_col, )
[ "def", "_process_string_token", "(", "self", ",", "token", ",", "start_row", ",", "start_col", ")", ":", "for", "i", ",", "char", "in", "enumerate", "(", "token", ")", ":", "if", "char", "in", "QUOTES", ":", "break", "# pylint: disable=undefined-loop-variable"...
Internal method for identifying and checking string tokens from the token stream. Args: token: the token to check. start_row: the line on which the token was found. start_col: the column on which the token was found.
[ "Internal", "method", "for", "identifying", "and", "checking", "string", "tokens", "from", "the", "token", "stream", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L261-L300
train
30,222
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._check_triple_quotes
def _check_triple_quotes(self, quote_record): """Check if the triple quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number, column). """ _, triple, row, col = quote_record if triple != TRIPLE_QUOTE_OPTS.get(self.config.triple_quote): self._invalid_triple_quote(triple, row, col)
python
def _check_triple_quotes(self, quote_record): """Check if the triple quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number, column). """ _, triple, row, col = quote_record if triple != TRIPLE_QUOTE_OPTS.get(self.config.triple_quote): self._invalid_triple_quote(triple, row, col)
[ "def", "_check_triple_quotes", "(", "self", ",", "quote_record", ")", ":", "_", ",", "triple", ",", "row", ",", "col", "=", "quote_record", "if", "triple", "!=", "TRIPLE_QUOTE_OPTS", ".", "get", "(", "self", ".", "config", ".", "triple_quote", ")", ":", ...
Check if the triple quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number, column).
[ "Check", "if", "the", "triple", "quote", "from", "tokenization", "is", "valid", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L302-L311
train
30,223
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._check_docstring_quotes
def _check_docstring_quotes(self, quote_record): """Check if the docstring quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number). """ _, triple, row, col = quote_record if triple != TRIPLE_QUOTE_OPTS.get(self.config.docstring_quote): self._invalid_docstring_quote(triple, row, col)
python
def _check_docstring_quotes(self, quote_record): """Check if the docstring quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number). """ _, triple, row, col = quote_record if triple != TRIPLE_QUOTE_OPTS.get(self.config.docstring_quote): self._invalid_docstring_quote(triple, row, col)
[ "def", "_check_docstring_quotes", "(", "self", ",", "quote_record", ")", ":", "_", ",", "triple", ",", "row", ",", "col", "=", "quote_record", "if", "triple", "!=", "TRIPLE_QUOTE_OPTS", ".", "get", "(", "self", ".", "config", ".", "docstring_quote", ")", "...
Check if the docstring quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number).
[ "Check", "if", "the", "docstring", "quote", "from", "tokenization", "is", "valid", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L313-L322
train
30,224
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._invalid_string_quote
def _invalid_string_quote(self, quote, row, correct_quote=None, col=None): """Add a message for an invalid string literal quote. Args: quote: The quote characters that were found. row: The row number the quote character was found on. correct_quote: The quote characters that is required. If None (default), will use the one from the config. col: The column the quote characters were found on. """ if not correct_quote: correct_quote = SMART_QUOTE_OPTS.get(self.config.string_quote) self.add_message( 'invalid-string-quote', line=row, args=(quote, correct_quote), **self.get_offset(col) )
python
def _invalid_string_quote(self, quote, row, correct_quote=None, col=None): """Add a message for an invalid string literal quote. Args: quote: The quote characters that were found. row: The row number the quote character was found on. correct_quote: The quote characters that is required. If None (default), will use the one from the config. col: The column the quote characters were found on. """ if not correct_quote: correct_quote = SMART_QUOTE_OPTS.get(self.config.string_quote) self.add_message( 'invalid-string-quote', line=row, args=(quote, correct_quote), **self.get_offset(col) )
[ "def", "_invalid_string_quote", "(", "self", ",", "quote", ",", "row", ",", "correct_quote", "=", "None", ",", "col", "=", "None", ")", ":", "if", "not", "correct_quote", ":", "correct_quote", "=", "SMART_QUOTE_OPTS", ".", "get", "(", "self", ".", "config"...
Add a message for an invalid string literal quote. Args: quote: The quote characters that were found. row: The row number the quote character was found on. correct_quote: The quote characters that is required. If None (default), will use the one from the config. col: The column the quote characters were found on.
[ "Add", "a", "message", "for", "an", "invalid", "string", "literal", "quote", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L324-L342
train
30,225
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._invalid_triple_quote
def _invalid_triple_quote(self, quote, row, col=None): """Add a message for an invalid triple quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on. """ self.add_message( 'invalid-triple-quote', line=row, args=(quote, TRIPLE_QUOTE_OPTS.get(self.config.triple_quote)), **self.get_offset(col) )
python
def _invalid_triple_quote(self, quote, row, col=None): """Add a message for an invalid triple quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on. """ self.add_message( 'invalid-triple-quote', line=row, args=(quote, TRIPLE_QUOTE_OPTS.get(self.config.triple_quote)), **self.get_offset(col) )
[ "def", "_invalid_triple_quote", "(", "self", ",", "quote", ",", "row", ",", "col", "=", "None", ")", ":", "self", ".", "add_message", "(", "'invalid-triple-quote'", ",", "line", "=", "row", ",", "args", "=", "(", "quote", ",", "TRIPLE_QUOTE_OPTS", ".", "...
Add a message for an invalid triple quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on.
[ "Add", "a", "message", "for", "an", "invalid", "triple", "quote", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L364-L377
train
30,226
edaniszewski/pylint-quotes
pylint_quotes/checker.py
StringQuoteChecker._invalid_docstring_quote
def _invalid_docstring_quote(self, quote, row, col=None): """Add a message for an invalid docstring quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on. """ self.add_message( 'invalid-docstring-quote', line=row, args=(quote, TRIPLE_QUOTE_OPTS.get(self.config.docstring_quote)), **self.get_offset(col) )
python
def _invalid_docstring_quote(self, quote, row, col=None): """Add a message for an invalid docstring quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on. """ self.add_message( 'invalid-docstring-quote', line=row, args=(quote, TRIPLE_QUOTE_OPTS.get(self.config.docstring_quote)), **self.get_offset(col) )
[ "def", "_invalid_docstring_quote", "(", "self", ",", "quote", ",", "row", ",", "col", "=", "None", ")", ":", "self", ".", "add_message", "(", "'invalid-docstring-quote'", ",", "line", "=", "row", ",", "args", "=", "(", "quote", ",", "TRIPLE_QUOTE_OPTS", "....
Add a message for an invalid docstring quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on.
[ "Add", "a", "message", "for", "an", "invalid", "docstring", "quote", "." ]
f13529541d6d787b5b37611a080937f5adba6357
https://github.com/edaniszewski/pylint-quotes/blob/f13529541d6d787b5b37611a080937f5adba6357/pylint_quotes/checker.py#L379-L392
train
30,227
ethereum/py-geth
geth/chain.py
get_live_data_dir
def get_live_data_dir(): """ pygeth needs a base directory to store it's chain data. By default this is the directory that `geth` uses as it's `datadir`. """ if sys.platform == 'darwin': data_dir = os.path.expanduser(os.path.join( "~", "Library", "Ethereum", )) elif sys.platform in {'linux', 'linux2', 'linux3'}: data_dir = os.path.expanduser(os.path.join( "~", ".ethereum", )) elif sys.platform == 'win32': data_dir = os.path.expanduser(os.path.join( "\\", "~", "AppData", "Roaming", "Ethereum", )) else: raise ValueError(( "Unsupported platform: '{0}'. Only darwin/linux2/win32 are " "supported. You must specify the geth datadir manually" ).format(sys.platform)) return data_dir
python
def get_live_data_dir(): """ pygeth needs a base directory to store it's chain data. By default this is the directory that `geth` uses as it's `datadir`. """ if sys.platform == 'darwin': data_dir = os.path.expanduser(os.path.join( "~", "Library", "Ethereum", )) elif sys.platform in {'linux', 'linux2', 'linux3'}: data_dir = os.path.expanduser(os.path.join( "~", ".ethereum", )) elif sys.platform == 'win32': data_dir = os.path.expanduser(os.path.join( "\\", "~", "AppData", "Roaming", "Ethereum", )) else: raise ValueError(( "Unsupported platform: '{0}'. Only darwin/linux2/win32 are " "supported. You must specify the geth datadir manually" ).format(sys.platform)) return data_dir
[ "def", "get_live_data_dir", "(", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "data_dir", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "\"Library\"", ",", "\"Ethereum\"", ",", ")",...
pygeth needs a base directory to store it's chain data. By default this is the directory that `geth` uses as it's `datadir`.
[ "pygeth", "needs", "a", "base", "directory", "to", "store", "it", "s", "chain", "data", ".", "By", "default", "this", "is", "the", "directory", "that", "geth", "uses", "as", "it", "s", "datadir", "." ]
ad462e7c841ebd9363b318889252e1f7d7c09c56
https://github.com/ethereum/py-geth/blob/ad462e7c841ebd9363b318889252e1f7d7c09c56/geth/chain.py#L16-L46
train
30,228
ethereum/py-geth
geth/accounts.py
get_accounts
def get_accounts(data_dir, **geth_kwargs): """ Returns all geth accounts as tuple of hex encoded strings >>> geth_accounts() ... ('0x...', '0x...') """ command, proc = spawn_geth(dict( data_dir=data_dir, suffix_args=['account', 'list'], **geth_kwargs )) stdoutdata, stderrdata = proc.communicate() if proc.returncode: if "no keys in store" in stderrdata.decode("utf-8"): return tuple() else: raise ValueError(format_error_message( "Error trying to list accounts", command, proc.returncode, stdoutdata, stderrdata, )) accounts = parse_geth_accounts(stdoutdata) return accounts
python
def get_accounts(data_dir, **geth_kwargs): """ Returns all geth accounts as tuple of hex encoded strings >>> geth_accounts() ... ('0x...', '0x...') """ command, proc = spawn_geth(dict( data_dir=data_dir, suffix_args=['account', 'list'], **geth_kwargs )) stdoutdata, stderrdata = proc.communicate() if proc.returncode: if "no keys in store" in stderrdata.decode("utf-8"): return tuple() else: raise ValueError(format_error_message( "Error trying to list accounts", command, proc.returncode, stdoutdata, stderrdata, )) accounts = parse_geth_accounts(stdoutdata) return accounts
[ "def", "get_accounts", "(", "data_dir", ",", "*", "*", "geth_kwargs", ")", ":", "command", ",", "proc", "=", "spawn_geth", "(", "dict", "(", "data_dir", "=", "data_dir", ",", "suffix_args", "=", "[", "'account'", ",", "'list'", "]", ",", "*", "*", "get...
Returns all geth accounts as tuple of hex encoded strings >>> geth_accounts() ... ('0x...', '0x...')
[ "Returns", "all", "geth", "accounts", "as", "tuple", "of", "hex", "encoded", "strings" ]
ad462e7c841ebd9363b318889252e1f7d7c09c56
https://github.com/ethereum/py-geth/blob/ad462e7c841ebd9363b318889252e1f7d7c09c56/geth/accounts.py#L8-L34
train
30,229
ethereum/py-geth
geth/accounts.py
create_new_account
def create_new_account(data_dir, password, **geth_kwargs): """Creates a new Ethereum account on geth. This is useful for testing when you want to stress interaction (transfers) between Ethereum accounts. This command communicates with ``geth`` command over terminal interaction. It creates keystore folder and new account there. This function only works against offline geth processes, because geth builds an account cache when starting up. If geth process is already running you can create new accounts using `web3.personal.newAccount() <https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console#personalnewaccount>_` RPC API. Example py.test fixture for tests: .. code-block:: python import os from geth.wrapper import DEFAULT_PASSWORD_PATH from geth.accounts import create_new_account @pytest.fixture def target_account() -> str: '''Create a new Ethereum account on a running Geth node. The account can be used as a withdrawal target for tests. :return: 0x address of the account ''' # We store keystore files in the current working directory # of the test run data_dir = os.getcwd() # Use the default password "this-is-not-a-secure-password" # as supplied in geth/default_blockchain_password file. # The supplied password must be bytes, not string, # as we only want ASCII characters and do not want to # deal encoding problems with passwords account = create_new_account(data_dir, DEFAULT_PASSWORD_PATH) return account :param data_dir: Geth data fir path - where to keep "keystore" folder :param password: Path to a file containing the password for newly created account :param geth_kwargs: Extra command line arguments passwrord to geth :return: Account as 0x prefixed hex string """ if os.path.exists(password): geth_kwargs['password'] = password command, proc = spawn_geth(dict( data_dir=data_dir, suffix_args=['account', 'new'], **geth_kwargs )) if os.path.exists(password): stdoutdata, stderrdata = proc.communicate() else: stdoutdata, stderrdata = proc.communicate(b"\n".join((password, password))) if proc.returncode: raise ValueError(format_error_message( "Error trying to create a new account", command, proc.returncode, stdoutdata, stderrdata, )) match = account_regex.search(stdoutdata) if not match: raise ValueError(format_error_message( "Did not find an address in process output", command, proc.returncode, stdoutdata, stderrdata, )) return b'0x' + match.groups()[0]
python
def create_new_account(data_dir, password, **geth_kwargs): """Creates a new Ethereum account on geth. This is useful for testing when you want to stress interaction (transfers) between Ethereum accounts. This command communicates with ``geth`` command over terminal interaction. It creates keystore folder and new account there. This function only works against offline geth processes, because geth builds an account cache when starting up. If geth process is already running you can create new accounts using `web3.personal.newAccount() <https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console#personalnewaccount>_` RPC API. Example py.test fixture for tests: .. code-block:: python import os from geth.wrapper import DEFAULT_PASSWORD_PATH from geth.accounts import create_new_account @pytest.fixture def target_account() -> str: '''Create a new Ethereum account on a running Geth node. The account can be used as a withdrawal target for tests. :return: 0x address of the account ''' # We store keystore files in the current working directory # of the test run data_dir = os.getcwd() # Use the default password "this-is-not-a-secure-password" # as supplied in geth/default_blockchain_password file. # The supplied password must be bytes, not string, # as we only want ASCII characters and do not want to # deal encoding problems with passwords account = create_new_account(data_dir, DEFAULT_PASSWORD_PATH) return account :param data_dir: Geth data fir path - where to keep "keystore" folder :param password: Path to a file containing the password for newly created account :param geth_kwargs: Extra command line arguments passwrord to geth :return: Account as 0x prefixed hex string """ if os.path.exists(password): geth_kwargs['password'] = password command, proc = spawn_geth(dict( data_dir=data_dir, suffix_args=['account', 'new'], **geth_kwargs )) if os.path.exists(password): stdoutdata, stderrdata = proc.communicate() else: stdoutdata, stderrdata = proc.communicate(b"\n".join((password, password))) if proc.returncode: raise ValueError(format_error_message( "Error trying to create a new account", command, proc.returncode, stdoutdata, stderrdata, )) match = account_regex.search(stdoutdata) if not match: raise ValueError(format_error_message( "Did not find an address in process output", command, proc.returncode, stdoutdata, stderrdata, )) return b'0x' + match.groups()[0]
[ "def", "create_new_account", "(", "data_dir", ",", "password", ",", "*", "*", "geth_kwargs", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "password", ")", ":", "geth_kwargs", "[", "'password'", "]", "=", "password", "command", ",", "proc", "=",...
Creates a new Ethereum account on geth. This is useful for testing when you want to stress interaction (transfers) between Ethereum accounts. This command communicates with ``geth`` command over terminal interaction. It creates keystore folder and new account there. This function only works against offline geth processes, because geth builds an account cache when starting up. If geth process is already running you can create new accounts using `web3.personal.newAccount() <https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console#personalnewaccount>_` RPC API. Example py.test fixture for tests: .. code-block:: python import os from geth.wrapper import DEFAULT_PASSWORD_PATH from geth.accounts import create_new_account @pytest.fixture def target_account() -> str: '''Create a new Ethereum account on a running Geth node. The account can be used as a withdrawal target for tests. :return: 0x address of the account ''' # We store keystore files in the current working directory # of the test run data_dir = os.getcwd() # Use the default password "this-is-not-a-secure-password" # as supplied in geth/default_blockchain_password file. # The supplied password must be bytes, not string, # as we only want ASCII characters and do not want to # deal encoding problems with passwords account = create_new_account(data_dir, DEFAULT_PASSWORD_PATH) return account :param data_dir: Geth data fir path - where to keep "keystore" folder :param password: Path to a file containing the password for newly created account :param geth_kwargs: Extra command line arguments passwrord to geth :return: Account as 0x prefixed hex string
[ "Creates", "a", "new", "Ethereum", "account", "on", "geth", "." ]
ad462e7c841ebd9363b318889252e1f7d7c09c56
https://github.com/ethereum/py-geth/blob/ad462e7c841ebd9363b318889252e1f7d7c09c56/geth/accounts.py#L40-L129
train
30,230
obriencj/python-javatools
javatools/ziputils.py
compare
def compare(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right, which are filenames for a pair of zip files """ with open_zip(left) as l: with open_zip(right) as r: return compare_zips(l, r)
python
def compare(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right, which are filenames for a pair of zip files """ with open_zip(left) as l: with open_zip(right) as r: return compare_zips(l, r)
[ "def", "compare", "(", "left", ",", "right", ")", ":", "with", "open_zip", "(", "left", ")", "as", "l", ":", "with", "open_zip", "(", "right", ")", "as", "r", ":", "return", "compare_zips", "(", "l", ",", "r", ")" ]
yields EVENT,ENTRY pairs describing the differences between left and right, which are filenames for a pair of zip files
[ "yields", "EVENT", "ENTRY", "pairs", "describing", "the", "differences", "between", "left", "and", "right", "which", "are", "filenames", "for", "a", "pair", "of", "zip", "files" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L44-L52
train
30,231
obriencj/python-javatools
javatools/ziputils.py
compare_zips
def compare_zips(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right ZipFile instances """ ll = set(left.namelist()) rl = set(right.namelist()) for f in ll: if f in rl: rl.remove(f) if f[-1] == '/': # it's a directory entry pass elif _different(left, right, f): yield DIFF, f else: yield SAME, f else: yield LEFT, f for f in rl: yield RIGHT, f
python
def compare_zips(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right ZipFile instances """ ll = set(left.namelist()) rl = set(right.namelist()) for f in ll: if f in rl: rl.remove(f) if f[-1] == '/': # it's a directory entry pass elif _different(left, right, f): yield DIFF, f else: yield SAME, f else: yield LEFT, f for f in rl: yield RIGHT, f
[ "def", "compare_zips", "(", "left", ",", "right", ")", ":", "ll", "=", "set", "(", "left", ".", "namelist", "(", ")", ")", "rl", "=", "set", "(", "right", ".", "namelist", "(", ")", ")", "for", "f", "in", "ll", ":", "if", "f", "in", "rl", ":"...
yields EVENT,ENTRY pairs describing the differences between left and right ZipFile instances
[ "yields", "EVENT", "ENTRY", "pairs", "describing", "the", "differences", "between", "left", "and", "right", "ZipFile", "instances" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L55-L82
train
30,232
obriencj/python-javatools
javatools/ziputils.py
_different
def _different(left, right, f): """ true if entry f is different between left and right ZipFile instances """ l = left.getinfo(f) r = right.getinfo(f) if (l.file_size == r.file_size) and (l.CRC == r.CRC): # ok, they seem passibly similar, let's deep check them. return _deep_different(left, right, f) else: # yup, they're different return True
python
def _different(left, right, f): """ true if entry f is different between left and right ZipFile instances """ l = left.getinfo(f) r = right.getinfo(f) if (l.file_size == r.file_size) and (l.CRC == r.CRC): # ok, they seem passibly similar, let's deep check them. return _deep_different(left, right, f) else: # yup, they're different return True
[ "def", "_different", "(", "left", ",", "right", ",", "f", ")", ":", "l", "=", "left", ".", "getinfo", "(", "f", ")", "r", "=", "right", ".", "getinfo", "(", "f", ")", "if", "(", "l", ".", "file_size", "==", "r", ".", "file_size", ")", "and", ...
true if entry f is different between left and right ZipFile instances
[ "true", "if", "entry", "f", "is", "different", "between", "left", "and", "right", "ZipFile", "instances" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L85-L100
train
30,233
obriencj/python-javatools
javatools/ziputils.py
_deep_different
def _deep_different(left, right, entry): """ checks that entry is identical between ZipFile instances left and right """ left = chunk_zip_entry(left, entry) right = chunk_zip_entry(right, entry) for ldata, rdata in zip_longest(left, right): if ldata != rdata: return True return False
python
def _deep_different(left, right, entry): """ checks that entry is identical between ZipFile instances left and right """ left = chunk_zip_entry(left, entry) right = chunk_zip_entry(right, entry) for ldata, rdata in zip_longest(left, right): if ldata != rdata: return True return False
[ "def", "_deep_different", "(", "left", ",", "right", ",", "entry", ")", ":", "left", "=", "chunk_zip_entry", "(", "left", ",", "entry", ")", "right", "=", "chunk_zip_entry", "(", "right", ",", "entry", ")", "for", "ldata", ",", "rdata", "in", "zip_longes...
checks that entry is identical between ZipFile instances left and right
[ "checks", "that", "entry", "is", "identical", "between", "ZipFile", "instances", "left", "and", "right" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L103-L115
train
30,234
obriencj/python-javatools
javatools/ziputils.py
collect_compare_into
def collect_compare_into(left, right, added, removed, altered, same): """ collects the differences between left and right, which are filenames for valid zip files, into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same """ with open_zip(left) as l: with open_zip(right) as r: return collect_compare_zips_into(l, r, added, removed, altered, same)
python
def collect_compare_into(left, right, added, removed, altered, same): """ collects the differences between left and right, which are filenames for valid zip files, into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same """ with open_zip(left) as l: with open_zip(right) as r: return collect_compare_zips_into(l, r, added, removed, altered, same)
[ "def", "collect_compare_into", "(", "left", ",", "right", ",", "added", ",", "removed", ",", "altered", ",", "same", ")", ":", "with", "open_zip", "(", "left", ")", "as", "l", ":", "with", "open_zip", "(", "right", ")", "as", "r", ":", "return", "col...
collects the differences between left and right, which are filenames for valid zip files, into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same
[ "collects", "the", "differences", "between", "left", "and", "right", "which", "are", "filenames", "for", "valid", "zip", "files", "into", "the", "lists", "added", "removed", "altered", "and", "same", ".", "Returns", "a", "tuple", "of", "added", "removed", "a...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L128-L140
train
30,235
obriencj/python-javatools
javatools/ziputils.py
collect_compare_zips_into
def collect_compare_zips_into(left, right, added, removed, altered, same): """ collects the differences between left and right ZipFile instances into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same """ for event, filename in compare_zips(left, right): if event == LEFT: group = removed elif event == RIGHT: group = added elif event == DIFF: group = altered elif event == SAME: group = same else: assert False if group is not None: group.append(filename) return added, removed, altered, same
python
def collect_compare_zips_into(left, right, added, removed, altered, same): """ collects the differences between left and right ZipFile instances into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same """ for event, filename in compare_zips(left, right): if event == LEFT: group = removed elif event == RIGHT: group = added elif event == DIFF: group = altered elif event == SAME: group = same else: assert False if group is not None: group.append(filename) return added, removed, altered, same
[ "def", "collect_compare_zips_into", "(", "left", ",", "right", ",", "added", ",", "removed", ",", "altered", ",", "same", ")", ":", "for", "event", ",", "filename", "in", "compare_zips", "(", "left", ",", "right", ")", ":", "if", "event", "==", "LEFT", ...
collects the differences between left and right ZipFile instances into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same
[ "collects", "the", "differences", "between", "left", "and", "right", "ZipFile", "instances", "into", "the", "lists", "added", "removed", "altered", "and", "same", ".", "Returns", "a", "tuple", "of", "added", "removed", "altered", "same" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L152-L174
train
30,236
obriencj/python-javatools
javatools/ziputils.py
is_zipstream
def is_zipstream(data): """ just like zipfile.is_zipfile, but works upon buffers and streams rather than filenames. If data supports the read method, it will be treated as a stream and read from to test whether it is a valid ZipFile. If data also supports the tell and seek methods, it will be rewound after being tested. """ if isinstance(data, (str, buffer)): data = BytesIO(data) if hasattr(data, "read"): tell = 0 if hasattr(data, "tell"): tell = data.tell() try: result = bool(_EndRecData(data)) except IOError: result = False if hasattr(data, "seek"): data.seek(tell) else: raise TypeError("requies str, buffer, or stream-like object") return result
python
def is_zipstream(data): """ just like zipfile.is_zipfile, but works upon buffers and streams rather than filenames. If data supports the read method, it will be treated as a stream and read from to test whether it is a valid ZipFile. If data also supports the tell and seek methods, it will be rewound after being tested. """ if isinstance(data, (str, buffer)): data = BytesIO(data) if hasattr(data, "read"): tell = 0 if hasattr(data, "tell"): tell = data.tell() try: result = bool(_EndRecData(data)) except IOError: result = False if hasattr(data, "seek"): data.seek(tell) else: raise TypeError("requies str, buffer, or stream-like object") return result
[ "def", "is_zipstream", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "(", "str", ",", "buffer", ")", ")", ":", "data", "=", "BytesIO", "(", "data", ")", "if", "hasattr", "(", "data", ",", "\"read\"", ")", ":", "tell", "=", "0", "if...
just like zipfile.is_zipfile, but works upon buffers and streams rather than filenames. If data supports the read method, it will be treated as a stream and read from to test whether it is a valid ZipFile. If data also supports the tell and seek methods, it will be rewound after being tested.
[ "just", "like", "zipfile", ".", "is_zipfile", "but", "works", "upon", "buffers", "and", "streams", "rather", "than", "filenames", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L177-L208
train
30,237
obriencj/python-javatools
javatools/ziputils.py
file_crc32
def file_crc32(filename, chunksize=_CHUNKSIZE): """ calculate the CRC32 of the contents of filename """ check = 0 with open(filename, 'rb') as fd: for data in iter(lambda: fd.read(chunksize), ""): check = crc32(data, check) return check
python
def file_crc32(filename, chunksize=_CHUNKSIZE): """ calculate the CRC32 of the contents of filename """ check = 0 with open(filename, 'rb') as fd: for data in iter(lambda: fd.read(chunksize), ""): check = crc32(data, check) return check
[ "def", "file_crc32", "(", "filename", ",", "chunksize", "=", "_CHUNKSIZE", ")", ":", "check", "=", "0", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fd", ":", "for", "data", "in", "iter", "(", "lambda", ":", "fd", ".", "read", "(", "ch...
calculate the CRC32 of the contents of filename
[ "calculate", "the", "CRC32", "of", "the", "contents", "of", "filename" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L211-L220
train
30,238
obriencj/python-javatools
javatools/ziputils.py
_collect_infos
def _collect_infos(dirname): """ Utility function used by ExplodedZipFile to generate ZipInfo entries for all of the files and directories under dirname """ for r, _ds, fs in walk(dirname): if not islink(r) and r != dirname: i = ZipInfo() i.filename = join(relpath(r, dirname), "") i.file_size = 0 i.compress_size = 0 i.CRC = 0 yield i.filename, i for f in fs: df = join(r, f) relfn = relpath(join(r, f), dirname) if islink(df): pass elif isfile(df): i = ZipInfo() i.filename = relfn i.file_size = getsize(df) i.compress_size = i.file_size i.CRC = file_crc32(df) yield i.filename, i else: # TODO: is there any more special treatment? pass
python
def _collect_infos(dirname): """ Utility function used by ExplodedZipFile to generate ZipInfo entries for all of the files and directories under dirname """ for r, _ds, fs in walk(dirname): if not islink(r) and r != dirname: i = ZipInfo() i.filename = join(relpath(r, dirname), "") i.file_size = 0 i.compress_size = 0 i.CRC = 0 yield i.filename, i for f in fs: df = join(r, f) relfn = relpath(join(r, f), dirname) if islink(df): pass elif isfile(df): i = ZipInfo() i.filename = relfn i.file_size = getsize(df) i.compress_size = i.file_size i.CRC = file_crc32(df) yield i.filename, i else: # TODO: is there any more special treatment? pass
[ "def", "_collect_infos", "(", "dirname", ")", ":", "for", "r", ",", "_ds", ",", "fs", "in", "walk", "(", "dirname", ")", ":", "if", "not", "islink", "(", "r", ")", "and", "r", "!=", "dirname", ":", "i", "=", "ZipInfo", "(", ")", "i", ".", "file...
Utility function used by ExplodedZipFile to generate ZipInfo entries for all of the files and directories under dirname
[ "Utility", "function", "used", "by", "ExplodedZipFile", "to", "generate", "ZipInfo", "entries", "for", "all", "of", "the", "files", "and", "directories", "under", "dirname" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L223-L254
train
30,239
obriencj/python-javatools
javatools/ziputils.py
zip_file
def zip_file(fn, mode="r"): """ returns either a zipfile.ZipFile instance or an ExplodedZipFile instance, depending on whether fn is the name of a valid zip file, or a directory. """ if isdir(fn): return ExplodedZipFile(fn) elif is_zipfile(fn): return ZipFile(fn, mode) else: raise Exception("cannot treat as an archive: %r" % fn)
python
def zip_file(fn, mode="r"): """ returns either a zipfile.ZipFile instance or an ExplodedZipFile instance, depending on whether fn is the name of a valid zip file, or a directory. """ if isdir(fn): return ExplodedZipFile(fn) elif is_zipfile(fn): return ZipFile(fn, mode) else: raise Exception("cannot treat as an archive: %r" % fn)
[ "def", "zip_file", "(", "fn", ",", "mode", "=", "\"r\"", ")", ":", "if", "isdir", "(", "fn", ")", ":", "return", "ExplodedZipFile", "(", "fn", ")", "elif", "is_zipfile", "(", "fn", ")", ":", "return", "ZipFile", "(", "fn", ",", "mode", ")", "else",...
returns either a zipfile.ZipFile instance or an ExplodedZipFile instance, depending on whether fn is the name of a valid zip file, or a directory.
[ "returns", "either", "a", "zipfile", ".", "ZipFile", "instance", "or", "an", "ExplodedZipFile", "instance", "depending", "on", "whether", "fn", "is", "the", "name", "of", "a", "valid", "zip", "file", "or", "a", "directory", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L300-L312
train
30,240
obriencj/python-javatools
javatools/ziputils.py
chunk_zip_entry
def chunk_zip_entry(zipfile, name, chunksize=_CHUNKSIZE): """ opens an entry from an openex zip file archive and yields sequential chunks of data from the resulting stream. """ with open_zip_entry(zipfile, name, mode='r') as stream: data = stream.read(chunksize) while data: yield data data = stream.read(chunksize)
python
def chunk_zip_entry(zipfile, name, chunksize=_CHUNKSIZE): """ opens an entry from an openex zip file archive and yields sequential chunks of data from the resulting stream. """ with open_zip_entry(zipfile, name, mode='r') as stream: data = stream.read(chunksize) while data: yield data data = stream.read(chunksize)
[ "def", "chunk_zip_entry", "(", "zipfile", ",", "name", ",", "chunksize", "=", "_CHUNKSIZE", ")", ":", "with", "open_zip_entry", "(", "zipfile", ",", "name", ",", "mode", "=", "'r'", ")", "as", "stream", ":", "data", "=", "stream", ".", "read", "(", "ch...
opens an entry from an openex zip file archive and yields sequential chunks of data from the resulting stream.
[ "opens", "an", "entry", "from", "an", "openex", "zip", "file", "archive", "and", "yields", "sequential", "chunks", "of", "data", "from", "the", "resulting", "stream", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/ziputils.py#L344-L354
train
30,241
obriencj/python-javatools
javatools/change.py
collect_by_typename
def collect_by_typename(obj_sequence, cache=None): """ collects objects from obj_sequence and stores them into buckets by type name. cache is an optional dict into which we collect the results. """ if cache is None: cache = {} for val in obj_sequence: key = type(val).__name__ bucket = cache.get(key, None) if bucket is not None: bucket.append(val) else: cache[key] = [val] return cache
python
def collect_by_typename(obj_sequence, cache=None): """ collects objects from obj_sequence and stores them into buckets by type name. cache is an optional dict into which we collect the results. """ if cache is None: cache = {} for val in obj_sequence: key = type(val).__name__ bucket = cache.get(key, None) if bucket is not None: bucket.append(val) else: cache[key] = [val] return cache
[ "def", "collect_by_typename", "(", "obj_sequence", ",", "cache", "=", "None", ")", ":", "if", "cache", "is", "None", ":", "cache", "=", "{", "}", "for", "val", "in", "obj_sequence", ":", "key", "=", "type", "(", "val", ")", ".", "__name__", "bucket", ...
collects objects from obj_sequence and stores them into buckets by type name. cache is an optional dict into which we collect the results.
[ "collects", "objects", "from", "obj_sequence", "and", "stores", "them", "into", "buckets", "by", "type", "name", ".", "cache", "is", "an", "optional", "dict", "into", "which", "we", "collect", "the", "results", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L37-L56
train
30,242
obriencj/python-javatools
javatools/change.py
collect_by_type
def collect_by_type(obj_sequence, cache=None): """ collects objects from obj_sequence and stores them into buckets by type. cache is an optional dict into which we collect the results. """ if cache is None: cache = {} for val in obj_sequence: key = type(val) bucket = cache.get(key, None) if bucket is not None: bucket.append(val) else: cache[key] = [val] return cache
python
def collect_by_type(obj_sequence, cache=None): """ collects objects from obj_sequence and stores them into buckets by type. cache is an optional dict into which we collect the results. """ if cache is None: cache = {} for val in obj_sequence: key = type(val) bucket = cache.get(key, None) if bucket is not None: bucket.append(val) else: cache[key] = [val] return cache
[ "def", "collect_by_type", "(", "obj_sequence", ",", "cache", "=", "None", ")", ":", "if", "cache", "is", "None", ":", "cache", "=", "{", "}", "for", "val", "in", "obj_sequence", ":", "key", "=", "type", "(", "val", ")", "bucket", "=", "cache", ".", ...
collects objects from obj_sequence and stores them into buckets by type. cache is an optional dict into which we collect the results.
[ "collects", "objects", "from", "obj_sequence", "and", "stores", "them", "into", "buckets", "by", "type", ".", "cache", "is", "an", "optional", "dict", "into", "which", "we", "collect", "the", "results", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L59-L77
train
30,243
obriencj/python-javatools
javatools/change.py
yield_sorted_by_type
def yield_sorted_by_type(*typelist): """ a useful decorator for the collect_impl method of SuperChange subclasses. Caches the yielded changes, and re-emits them collected by their type. The order of the types can be specified by listing the types as arguments to this decorator. Unlisted types will be yielded last in no guaranteed order. Grouping happens by exact type match only. Inheritance is not taken into consideration for grouping. """ def decorate(fun): @wraps(fun) def decorated(*args, **kwds): return iterate_by_type(fun(*args, **kwds), typelist) return decorated return decorate
python
def yield_sorted_by_type(*typelist): """ a useful decorator for the collect_impl method of SuperChange subclasses. Caches the yielded changes, and re-emits them collected by their type. The order of the types can be specified by listing the types as arguments to this decorator. Unlisted types will be yielded last in no guaranteed order. Grouping happens by exact type match only. Inheritance is not taken into consideration for grouping. """ def decorate(fun): @wraps(fun) def decorated(*args, **kwds): return iterate_by_type(fun(*args, **kwds), typelist) return decorated return decorate
[ "def", "yield_sorted_by_type", "(", "*", "typelist", ")", ":", "def", "decorate", "(", "fun", ")", ":", "@", "wraps", "(", "fun", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "return", "iterate_by_type", "(", "fun", "("...
a useful decorator for the collect_impl method of SuperChange subclasses. Caches the yielded changes, and re-emits them collected by their type. The order of the types can be specified by listing the types as arguments to this decorator. Unlisted types will be yielded last in no guaranteed order. Grouping happens by exact type match only. Inheritance is not taken into consideration for grouping.
[ "a", "useful", "decorator", "for", "the", "collect_impl", "method", "of", "SuperChange", "subclasses", ".", "Caches", "the", "yielded", "changes", "and", "re", "-", "emits", "them", "collected", "by", "their", "type", ".", "The", "order", "of", "the", "types...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L100-L118
train
30,244
obriencj/python-javatools
javatools/change.py
Change.simplify
def simplify(self, options=None): """ returns a dict describing a simple snapshot of this change, and its children if any. """ simple = { "class": type(self).__name__, "is_change": self.is_change(), "description": self.get_description(), "label": self.label, } if options: simple["is_ignored"] = self.is_ignored(options) if isinstance(self, Addition): simple["is_addition"] = True if isinstance(self, Removal): simple["is_removal"] = True if self.entry: simple["entry"] = self.entry return simple
python
def simplify(self, options=None): """ returns a dict describing a simple snapshot of this change, and its children if any. """ simple = { "class": type(self).__name__, "is_change": self.is_change(), "description": self.get_description(), "label": self.label, } if options: simple["is_ignored"] = self.is_ignored(options) if isinstance(self, Addition): simple["is_addition"] = True if isinstance(self, Removal): simple["is_removal"] = True if self.entry: simple["entry"] = self.entry return simple
[ "def", "simplify", "(", "self", ",", "options", "=", "None", ")", ":", "simple", "=", "{", "\"class\"", ":", "type", "(", "self", ")", ".", "__name__", ",", "\"is_change\"", ":", "self", ".", "is_change", "(", ")", ",", "\"description\"", ":", "self", ...
returns a dict describing a simple snapshot of this change, and its children if any.
[ "returns", "a", "dict", "describing", "a", "simple", "snapshot", "of", "this", "change", "and", "its", "children", "if", "any", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L183-L208
train
30,245
obriencj/python-javatools
javatools/change.py
GenericChange.simplify
def simplify(self, options=None): """ provide a simple representation of this change as a dictionary """ # TODO: we might want to get rid of this method and just move # it into the JSONEncoder in report.py simple = super(GenericChange, self).simplify(options) ld = self.pretty_ldata() if ld is not None: simple["old_data"] = ld rd = self.pretty_rdata() if rd is not None: simple["new_data"] = rd return simple
python
def simplify(self, options=None): """ provide a simple representation of this change as a dictionary """ # TODO: we might want to get rid of this method and just move # it into the JSONEncoder in report.py simple = super(GenericChange, self).simplify(options) ld = self.pretty_ldata() if ld is not None: simple["old_data"] = ld rd = self.pretty_rdata() if rd is not None: simple["new_data"] = rd return simple
[ "def", "simplify", "(", "self", ",", "options", "=", "None", ")", ":", "# TODO: we might want to get rid of this method and just move", "# it into the JSONEncoder in report.py", "simple", "=", "super", "(", "GenericChange", ",", "self", ")", ".", "simplify", "(", "optio...
provide a simple representation of this change as a dictionary
[ "provide", "a", "simple", "representation", "of", "this", "change", "as", "a", "dictionary" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L364-L382
train
30,246
obriencj/python-javatools
javatools/change.py
SuperChange.clear
def clear(self): """ clears all child changes and drops the reference to them """ super(SuperChange, self).clear() for c in self.changes: c.clear() self.changes = tuple()
python
def clear(self): """ clears all child changes and drops the reference to them """ super(SuperChange, self).clear() for c in self.changes: c.clear() self.changes = tuple()
[ "def", "clear", "(", "self", ")", ":", "super", "(", "SuperChange", ",", "self", ")", ".", "clear", "(", ")", "for", "c", "in", "self", ".", "changes", ":", "c", ".", "clear", "(", ")", "self", ".", "changes", "=", "tuple", "(", ")" ]
clears all child changes and drops the reference to them
[ "clears", "all", "child", "changes", "and", "drops", "the", "reference", "to", "them" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L419-L428
train
30,247
obriencj/python-javatools
javatools/change.py
SuperChange.collect_impl
def collect_impl(self): """ instantiates each of the entries in in the overriden change_types field with the left and right data """ ldata = self.get_ldata() rdata = self.get_rdata() for change_type in self.change_types: yield change_type(ldata, rdata)
python
def collect_impl(self): """ instantiates each of the entries in in the overriden change_types field with the left and right data """ ldata = self.get_ldata() rdata = self.get_rdata() for change_type in self.change_types: yield change_type(ldata, rdata)
[ "def", "collect_impl", "(", "self", ")", ":", "ldata", "=", "self", ".", "get_ldata", "(", ")", "rdata", "=", "self", ".", "get_rdata", "(", ")", "for", "change_type", "in", "self", ".", "change_types", ":", "yield", "change_type", "(", "ldata", ",", "...
instantiates each of the entries in in the overriden change_types field with the left and right data
[ "instantiates", "each", "of", "the", "entries", "in", "in", "the", "overriden", "change_types", "field", "with", "the", "left", "and", "right", "data" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L431-L441
train
30,248
obriencj/python-javatools
javatools/change.py
SuperChange.collect
def collect(self, force=False): """ calls collect_impl and stores the results as the child changes of this super-change. Returns a tuple of the data generated from collect_impl. Caches the result rather than re-computing each time, unless force is True """ if force or not self.changes: self.changes = tuple(self.collect_impl()) return self.changes
python
def collect(self, force=False): """ calls collect_impl and stores the results as the child changes of this super-change. Returns a tuple of the data generated from collect_impl. Caches the result rather than re-computing each time, unless force is True """ if force or not self.changes: self.changes = tuple(self.collect_impl()) return self.changes
[ "def", "collect", "(", "self", ",", "force", "=", "False", ")", ":", "if", "force", "or", "not", "self", ".", "changes", ":", "self", ".", "changes", "=", "tuple", "(", "self", ".", "collect_impl", "(", ")", ")", "return", "self", ".", "changes" ]
calls collect_impl and stores the results as the child changes of this super-change. Returns a tuple of the data generated from collect_impl. Caches the result rather than re-computing each time, unless force is True
[ "calls", "collect_impl", "and", "stores", "the", "results", "as", "the", "child", "changes", "of", "this", "super", "-", "change", ".", "Returns", "a", "tuple", "of", "the", "data", "generated", "from", "collect_impl", ".", "Caches", "the", "result", "rather...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L444-L454
train
30,249
obriencj/python-javatools
javatools/change.py
SuperChange.check_impl
def check_impl(self): """ sets self.changes to the result of self.changes_impl, then if any member of those checks shows as a change, will return True,None """ c = False for change in self.collect(): change.check() c = c or change.is_change() return c, None
python
def check_impl(self): """ sets self.changes to the result of self.changes_impl, then if any member of those checks shows as a change, will return True,None """ c = False for change in self.collect(): change.check() c = c or change.is_change() return c, None
[ "def", "check_impl", "(", "self", ")", ":", "c", "=", "False", "for", "change", "in", "self", ".", "collect", "(", ")", ":", "change", ".", "check", "(", ")", "c", "=", "c", "or", "change", ".", "is_change", "(", ")", "return", "c", ",", "None" ]
sets self.changes to the result of self.changes_impl, then if any member of those checks shows as a change, will return True,None
[ "sets", "self", ".", "changes", "to", "the", "result", "of", "self", ".", "changes_impl", "then", "if", "any", "member", "of", "those", "checks", "shows", "as", "a", "change", "will", "return", "True", "None" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L457-L468
train
30,250
obriencj/python-javatools
javatools/change.py
SuperChange.is_ignored
def is_ignored(self, options): """ If we have changed children and all the children which are changes are ignored, then we are ignored. Otherwise, we are not ignored """ if not self.is_change(): return False changes = self.collect() if not changes: return False for change in changes: if change.is_change() and not change.is_ignored(options): return False return True
python
def is_ignored(self, options): """ If we have changed children and all the children which are changes are ignored, then we are ignored. Otherwise, we are not ignored """ if not self.is_change(): return False changes = self.collect() if not changes: return False for change in changes: if change.is_change() and not change.is_ignored(options): return False return True
[ "def", "is_ignored", "(", "self", ",", "options", ")", ":", "if", "not", "self", ".", "is_change", "(", ")", ":", "return", "False", "changes", "=", "self", ".", "collect", "(", ")", "if", "not", "changes", ":", "return", "False", "for", "change", "i...
If we have changed children and all the children which are changes are ignored, then we are ignored. Otherwise, we are not ignored
[ "If", "we", "have", "changed", "children", "and", "all", "the", "children", "which", "are", "changes", "are", "ignored", "then", "we", "are", "ignored", ".", "Otherwise", "we", "are", "not", "ignored" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L471-L488
train
30,251
obriencj/python-javatools
javatools/change.py
SuperChange.squash_children
def squash_children(self, options): """ reduces the memory footprint of this super-change by converting all child changes into squashed changes """ oldsubs = self.collect() self.changes = tuple(squash(c, options=options) for c in oldsubs) for change in oldsubs: change.clear()
python
def squash_children(self, options): """ reduces the memory footprint of this super-change by converting all child changes into squashed changes """ oldsubs = self.collect() self.changes = tuple(squash(c, options=options) for c in oldsubs) for change in oldsubs: change.clear()
[ "def", "squash_children", "(", "self", ",", "options", ")", ":", "oldsubs", "=", "self", ".", "collect", "(", ")", "self", ".", "changes", "=", "tuple", "(", "squash", "(", "c", ",", "options", "=", "options", ")", "for", "c", "in", "oldsubs", ")", ...
reduces the memory footprint of this super-change by converting all child changes into squashed changes
[ "reduces", "the", "memory", "footprint", "of", "this", "super", "-", "change", "by", "converting", "all", "child", "changes", "into", "squashed", "changes" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L522-L532
train
30,252
obriencj/python-javatools
javatools/jardiff.py
add_jardiff_optgroup
def add_jardiff_optgroup(parser): """ option group specific to the tests in jardiff """ og = parser.add_argument_group("JAR Checking Options") og.add_argument("--ignore-jar-entry", action="append", default=[]) og.add_argument("--ignore-jar-signature", action="store_true", default=False, help="Ignore JAR signing changes") og.add_argument("--ignore-manifest", action="store_true", default=False, help="Ignore changes to manifests") og.add_argument("--ignore-manifest-subsections", action="store_true", default=False, help="Ignore changes to manifest subsections") og.add_argument("--ignore-manifest-key", action="append", default=[], help="case-insensitive manifest keys to ignore")
python
def add_jardiff_optgroup(parser): """ option group specific to the tests in jardiff """ og = parser.add_argument_group("JAR Checking Options") og.add_argument("--ignore-jar-entry", action="append", default=[]) og.add_argument("--ignore-jar-signature", action="store_true", default=False, help="Ignore JAR signing changes") og.add_argument("--ignore-manifest", action="store_true", default=False, help="Ignore changes to manifests") og.add_argument("--ignore-manifest-subsections", action="store_true", default=False, help="Ignore changes to manifest subsections") og.add_argument("--ignore-manifest-key", action="append", default=[], help="case-insensitive manifest keys to ignore")
[ "def", "add_jardiff_optgroup", "(", "parser", ")", ":", "og", "=", "parser", ".", "add_argument_group", "(", "\"JAR Checking Options\"", ")", "og", ".", "add_argument", "(", "\"--ignore-jar-entry\"", ",", "action", "=", "\"append\"", ",", "default", "=", "[", "]...
option group specific to the tests in jardiff
[ "option", "group", "specific", "to", "the", "tests", "in", "jardiff" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jardiff.py#L554-L577
train
30,253
obriencj/python-javatools
javatools/jardiff.py
default_jardiff_options
def default_jardiff_options(updates=None): """ generate an options object with the appropriate default values in place for API usage of jardiff features. overrides is an optional dictionary which will be used to update fields on the options object. """ parser = create_optparser() options, _args = parser.parse_args(list()) if updates: # pylint: disable=W0212 options._update_careful(updates) return options
python
def default_jardiff_options(updates=None): """ generate an options object with the appropriate default values in place for API usage of jardiff features. overrides is an optional dictionary which will be used to update fields on the options object. """ parser = create_optparser() options, _args = parser.parse_args(list()) if updates: # pylint: disable=W0212 options._update_careful(updates) return options
[ "def", "default_jardiff_options", "(", "updates", "=", "None", ")", ":", "parser", "=", "create_optparser", "(", ")", "options", ",", "_args", "=", "parser", ".", "parse_args", "(", "list", "(", ")", ")", "if", "updates", ":", "# pylint: disable=W0212", "opt...
generate an options object with the appropriate default values in place for API usage of jardiff features. overrides is an optional dictionary which will be used to update fields on the options object.
[ "generate", "an", "options", "object", "with", "the", "appropriate", "default", "values", "in", "place", "for", "API", "usage", "of", "jardiff", "features", ".", "overrides", "is", "an", "optional", "dictionary", "which", "will", "be", "used", "to", "update", ...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jardiff.py#L604-L619
train
30,254
obriencj/python-javatools
javatools/jardiff.py
main
def main(args=sys.argv): """ main entry point for the jardiff CLI """ parser = create_optparser(args[0]) return cli(parser.parse_args(args[1:]))
python
def main(args=sys.argv): """ main entry point for the jardiff CLI """ parser = create_optparser(args[0]) return cli(parser.parse_args(args[1:]))
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "parser", "=", "create_optparser", "(", "args", "[", "0", "]", ")", "return", "cli", "(", "parser", ".", "parse_args", "(", "args", "[", "1", ":", "]", ")", ")" ]
main entry point for the jardiff CLI
[ "main", "entry", "point", "for", "the", "jardiff", "CLI" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jardiff.py#L622-L628
train
30,255
obriencj/python-javatools
javatools/report.py
add_general_report_optgroup
def add_general_report_optgroup(parser): """ General Reporting Options """ g = parser.add_argument_group("Reporting Options") g.add_argument("--report-dir", action="store", default=None) g.add_argument("--report", action=_opt_cb_report, help="comma-separated list of report formats")
python
def add_general_report_optgroup(parser): """ General Reporting Options """ g = parser.add_argument_group("Reporting Options") g.add_argument("--report-dir", action="store", default=None) g.add_argument("--report", action=_opt_cb_report, help="comma-separated list of report formats")
[ "def", "add_general_report_optgroup", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "\"Reporting Options\"", ")", "g", ".", "add_argument", "(", "\"--report-dir\"", ",", "action", "=", "\"store\"", ",", "default", "=", "None", ")",...
General Reporting Options
[ "General", "Reporting", "Options" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L262-L272
train
30,256
obriencj/python-javatools
javatools/report.py
add_json_report_optgroup
def add_json_report_optgroup(parser): """ Option group for the JSON report format """ g = parser.add_argument_group("JSON Report Options") g.add_argument("--json-indent", action="store", default=2, type=int)
python
def add_json_report_optgroup(parser): """ Option group for the JSON report format """ g = parser.add_argument_group("JSON Report Options") g.add_argument("--json-indent", action="store", default=2, type=int)
[ "def", "add_json_report_optgroup", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "\"JSON Report Options\"", ")", "g", ".", "add_argument", "(", "\"--json-indent\"", ",", "action", "=", "\"store\"", ",", "default", "=", "2", ",", ...
Option group for the JSON report format
[ "Option", "group", "for", "the", "JSON", "report", "format" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L305-L312
train
30,257
obriencj/python-javatools
javatools/report.py
_indent_change
def _indent_change(change, out, options, indent): """ recursive function to print indented change descriptions """ show_unchanged = getattr(options, "show_unchanged", False) show_ignored = getattr(options, "show_ignored", False) show = False desc = change.get_description() if change.is_change(): if change.is_ignored(options): if show_ignored: show = True _indent(out, indent, desc, " [IGNORED]") else: show = True _indent(out, indent, desc) elif show_unchanged: show = True _indent(out, indent, desc) if show: indent += 1 for sub in change.collect(): _indent_change(sub, out, options, indent)
python
def _indent_change(change, out, options, indent): """ recursive function to print indented change descriptions """ show_unchanged = getattr(options, "show_unchanged", False) show_ignored = getattr(options, "show_ignored", False) show = False desc = change.get_description() if change.is_change(): if change.is_ignored(options): if show_ignored: show = True _indent(out, indent, desc, " [IGNORED]") else: show = True _indent(out, indent, desc) elif show_unchanged: show = True _indent(out, indent, desc) if show: indent += 1 for sub in change.collect(): _indent_change(sub, out, options, indent)
[ "def", "_indent_change", "(", "change", ",", "out", ",", "options", ",", "indent", ")", ":", "show_unchanged", "=", "getattr", "(", "options", ",", "\"show_unchanged\"", ",", "False", ")", "show_ignored", "=", "getattr", "(", "options", ",", "\"show_ignored\""...
recursive function to print indented change descriptions
[ "recursive", "function", "to", "print", "indented", "change", "descriptions" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L359-L385
train
30,258
obriencj/python-javatools
javatools/report.py
_indent
def _indent(stream, indent, *msgs): """ write a message to a text stream, with indentation. Also ensures that the output encoding of the messages is safe for writing. """ for x in range(0, indent): stream.write(" ") for x in msgs: # Any nicer way? In Py2 x can be 'str' or 'unicode'. stream.write(x.encode("ascii", "backslashreplace").decode("ascii")) stream.write("\n")
python
def _indent(stream, indent, *msgs): """ write a message to a text stream, with indentation. Also ensures that the output encoding of the messages is safe for writing. """ for x in range(0, indent): stream.write(" ") for x in msgs: # Any nicer way? In Py2 x can be 'str' or 'unicode'. stream.write(x.encode("ascii", "backslashreplace").decode("ascii")) stream.write("\n")
[ "def", "_indent", "(", "stream", ",", "indent", ",", "*", "msgs", ")", ":", "for", "x", "in", "range", "(", "0", ",", "indent", ")", ":", "stream", ".", "write", "(", "\" \"", ")", "for", "x", "in", "msgs", ":", "# Any nicer way? In Py2 x can be 'str'...
write a message to a text stream, with indentation. Also ensures that the output encoding of the messages is safe for writing.
[ "write", "a", "message", "to", "a", "text", "stream", "with", "indentation", ".", "Also", "ensures", "that", "the", "output", "encoding", "of", "the", "messages", "is", "safe", "for", "writing", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L388-L398
train
30,259
obriencj/python-javatools
javatools/report.py
_compose_cheetah_template_map
def _compose_cheetah_template_map(cache): """ does the work of composing the cheetah template map into the given cache """ from .cheetah import get_templates # pylint: disable=W0406 # needed for introspection import javatools for template_type in get_templates(): if "_" not in template_type.__name__: # we use the _ to denote package and class names. So any # template without a _ in the name isn't meant to be # matched to a change type. continue # get the package and change class names based off of the # template class name tn = template_type.__name__ pn, cn = tn.split("_", 1) # get the package from javatools pk = getattr(javatools, pn, None) if pk is None: __import__("javatools." + pn) pk = getattr(javatools, pn, None) # get the class from the package cc = getattr(pk, cn, None) if cc is None: raise Exception("no change class for template %s" % tn) # associate a Change class with a Template class cache[cc] = template_type return cache
python
def _compose_cheetah_template_map(cache): """ does the work of composing the cheetah template map into the given cache """ from .cheetah import get_templates # pylint: disable=W0406 # needed for introspection import javatools for template_type in get_templates(): if "_" not in template_type.__name__: # we use the _ to denote package and class names. So any # template without a _ in the name isn't meant to be # matched to a change type. continue # get the package and change class names based off of the # template class name tn = template_type.__name__ pn, cn = tn.split("_", 1) # get the package from javatools pk = getattr(javatools, pn, None) if pk is None: __import__("javatools." + pn) pk = getattr(javatools, pn, None) # get the class from the package cc = getattr(pk, cn, None) if cc is None: raise Exception("no change class for template %s" % tn) # associate a Change class with a Template class cache[cc] = template_type return cache
[ "def", "_compose_cheetah_template_map", "(", "cache", ")", ":", "from", ".", "cheetah", "import", "get_templates", "# pylint: disable=W0406", "# needed for introspection", "import", "javatools", "for", "template_type", "in", "get_templates", "(", ")", ":", "if", "\"_\""...
does the work of composing the cheetah template map into the given cache
[ "does", "the", "work", "of", "composing", "the", "cheetah", "template", "map", "into", "the", "given", "cache" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L531-L569
train
30,260
obriencj/python-javatools
javatools/report.py
resolve_cheetah_template
def resolve_cheetah_template(change_type): """ return the appropriate cheetah template class for the given change type, using the method-resolution-order of the change type. """ tm = cheetah_template_map() # follow the built-in MRO for a type to find the matching # cheetah template for t in change_type.mro(): tmpl = tm.get(t) if tmpl: return tmpl # this should never happen, since we'll provide a # change_Change template, and all of the changes should be # inheriting from that type raise Exception("No template for class %s" % change_type.__name__)
python
def resolve_cheetah_template(change_type): """ return the appropriate cheetah template class for the given change type, using the method-resolution-order of the change type. """ tm = cheetah_template_map() # follow the built-in MRO for a type to find the matching # cheetah template for t in change_type.mro(): tmpl = tm.get(t) if tmpl: return tmpl # this should never happen, since we'll provide a # change_Change template, and all of the changes should be # inheriting from that type raise Exception("No template for class %s" % change_type.__name__)
[ "def", "resolve_cheetah_template", "(", "change_type", ")", ":", "tm", "=", "cheetah_template_map", "(", ")", "# follow the built-in MRO for a type to find the matching", "# cheetah template", "for", "t", "in", "change_type", ".", "mro", "(", ")", ":", "tmpl", "=", "t...
return the appropriate cheetah template class for the given change type, using the method-resolution-order of the change type.
[ "return", "the", "appropriate", "cheetah", "template", "class", "for", "the", "given", "change", "type", "using", "the", "method", "-", "resolution", "-", "order", "of", "the", "change", "type", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L588-L606
train
30,261
obriencj/python-javatools
javatools/report.py
add_html_report_optgroup
def add_html_report_optgroup(parser): """ Option group for the HTML report format """ g = parser.add_argument_group("HTML Report Options") g.add_argument("--html-stylesheet", action="append", dest="html_stylesheets", default=list()) g.add_argument("--html-javascript", action="append", dest="html_javascripts", default=list()) g.add_argument("--html-copy-data", action="store", default=None, help="Copy default resources to the given directory and" " enable them in the template")
python
def add_html_report_optgroup(parser): """ Option group for the HTML report format """ g = parser.add_argument_group("HTML Report Options") g.add_argument("--html-stylesheet", action="append", dest="html_stylesheets", default=list()) g.add_argument("--html-javascript", action="append", dest="html_javascripts", default=list()) g.add_argument("--html-copy-data", action="store", default=None, help="Copy default resources to the given directory and" " enable them in the template")
[ "def", "add_html_report_optgroup", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "\"HTML Report Options\"", ")", "g", ".", "add_argument", "(", "\"--html-stylesheet\"", ",", "action", "=", "\"append\"", ",", "dest", "=", "\"html_styl...
Option group for the HTML report format
[ "Option", "group", "for", "the", "HTML", "report", "format" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L609-L624
train
30,262
obriencj/python-javatools
javatools/report.py
quick_report
def quick_report(report_type, change, options): """ writes a change report via report_type to options.output or sys.stdout """ report = report_type(None, options) if options.output: with open(options.output, "w") as out: report.run(change, None, out) else: report.run(change, None, sys.stdout)
python
def quick_report(report_type, change, options): """ writes a change report via report_type to options.output or sys.stdout """ report = report_type(None, options) if options.output: with open(options.output, "w") as out: report.run(change, None, out) else: report.run(change, None, sys.stdout)
[ "def", "quick_report", "(", "report_type", ",", "change", ",", "options", ")", ":", "report", "=", "report_type", "(", "None", ",", "options", ")", "if", "options", ".", "output", ":", "with", "open", "(", "options", ".", "output", ",", "\"w\"", ")", "...
writes a change report via report_type to options.output or sys.stdout
[ "writes", "a", "change", "report", "via", "report_type", "to", "options", ".", "output", "or", "sys", ".", "stdout" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L627-L639
train
30,263
obriencj/python-javatools
javatools/report.py
Reporter.get_relative_breadcrumbs
def get_relative_breadcrumbs(self): """ get the breadcrumbs as relative to the basedir """ basedir = self.basedir crumbs = self.breadcrumbs return [(relpath(b, basedir), e) for b, e in crumbs]
python
def get_relative_breadcrumbs(self): """ get the breadcrumbs as relative to the basedir """ basedir = self.basedir crumbs = self.breadcrumbs return [(relpath(b, basedir), e) for b, e in crumbs]
[ "def", "get_relative_breadcrumbs", "(", "self", ")", ":", "basedir", "=", "self", ".", "basedir", "crumbs", "=", "self", ".", "breadcrumbs", "return", "[", "(", "relpath", "(", "b", ",", "basedir", ")", ",", "e", ")", "for", "b", ",", "e", "in", "cru...
get the breadcrumbs as relative to the basedir
[ "get", "the", "breadcrumbs", "as", "relative", "to", "the", "basedir" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L70-L78
train
30,264
obriencj/python-javatools
javatools/report.py
Reporter.add_formats_by_name
def add_formats_by_name(self, rfmt_list): """ adds formats by short label descriptors, such as 'txt', 'json', or 'html' """ for fmt in rfmt_list: if fmt == "json": self.add_report_format(JSONReportFormat) elif fmt in ("txt", "text"): self.add_report_format(TextReportFormat) elif fmt in ("htm", "html"): self.add_report_format(CheetahReportFormat)
python
def add_formats_by_name(self, rfmt_list): """ adds formats by short label descriptors, such as 'txt', 'json', or 'html' """ for fmt in rfmt_list: if fmt == "json": self.add_report_format(JSONReportFormat) elif fmt in ("txt", "text"): self.add_report_format(TextReportFormat) elif fmt in ("htm", "html"): self.add_report_format(CheetahReportFormat)
[ "def", "add_formats_by_name", "(", "self", ",", "rfmt_list", ")", ":", "for", "fmt", "in", "rfmt_list", ":", "if", "fmt", "==", "\"json\"", ":", "self", ".", "add_report_format", "(", "JSONReportFormat", ")", "elif", "fmt", "in", "(", "\"txt\"", ",", "\"te...
adds formats by short label descriptors, such as 'txt', 'json', or 'html'
[ "adds", "formats", "by", "short", "label", "descriptors", "such", "as", "txt", "json", "or", "html" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L81-L93
train
30,265
obriencj/python-javatools
javatools/report.py
Reporter.subreporter
def subreporter(self, subpath, entry): """ create a reporter for a sub-report, with updated breadcrumbs and the same output formats """ newbase = join(self.basedir, subpath) r = Reporter(newbase, entry, self.options) crumbs = list(self.breadcrumbs) crumbs.append((self.basedir, self.entry)) r.breadcrumbs = crumbs r.formats = set(self.formats) return r
python
def subreporter(self, subpath, entry): """ create a reporter for a sub-report, with updated breadcrumbs and the same output formats """ newbase = join(self.basedir, subpath) r = Reporter(newbase, entry, self.options) crumbs = list(self.breadcrumbs) crumbs.append((self.basedir, self.entry)) r.breadcrumbs = crumbs r.formats = set(self.formats) return r
[ "def", "subreporter", "(", "self", ",", "subpath", ",", "entry", ")", ":", "newbase", "=", "join", "(", "self", ".", "basedir", ",", "subpath", ")", "r", "=", "Reporter", "(", "newbase", ",", "entry", ",", "self", ".", "options", ")", "crumbs", "=", ...
create a reporter for a sub-report, with updated breadcrumbs and the same output formats
[ "create", "a", "reporter", "for", "a", "sub", "-", "report", "with", "updated", "breadcrumbs", "and", "the", "same", "output", "formats" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L106-L120
train
30,266
obriencj/python-javatools
javatools/report.py
Reporter.setup
def setup(self): """ instantiates all report formats that have been added to this reporter, and calls their setup methods. """ if self._formats: # setup has been run already. return basedir = self.basedir options = self.options crumbs = self.get_relative_breadcrumbs() fmts = list() for fmt_class in self.formats: fmt = fmt_class(basedir, options, crumbs) fmt.setup() fmts.append(fmt) self._formats = fmts
python
def setup(self): """ instantiates all report formats that have been added to this reporter, and calls their setup methods. """ if self._formats: # setup has been run already. return basedir = self.basedir options = self.options crumbs = self.get_relative_breadcrumbs() fmts = list() for fmt_class in self.formats: fmt = fmt_class(basedir, options, crumbs) fmt.setup() fmts.append(fmt) self._formats = fmts
[ "def", "setup", "(", "self", ")", ":", "if", "self", ".", "_formats", ":", "# setup has been run already.", "return", "basedir", "=", "self", ".", "basedir", "options", "=", "self", ".", "options", "crumbs", "=", "self", ".", "get_relative_breadcrumbs", "(", ...
instantiates all report formats that have been added to this reporter, and calls their setup methods.
[ "instantiates", "all", "report", "formats", "that", "have", "been", "added", "to", "this", "reporter", "and", "calls", "their", "setup", "methods", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L123-L143
train
30,267
obriencj/python-javatools
javatools/report.py
Reporter.run
def run(self, change): """ runs the report format instances in this reporter. Will call setup if it hasn't been called already """ if self._formats is None: self.setup() entry = self.entry for fmt in self._formats: fmt.run(change, entry) self.clear()
python
def run(self, change): """ runs the report format instances in this reporter. Will call setup if it hasn't been called already """ if self._formats is None: self.setup() entry = self.entry for fmt in self._formats: fmt.run(change, entry) self.clear()
[ "def", "run", "(", "self", ",", "change", ")", ":", "if", "self", ".", "_formats", "is", "None", ":", "self", ".", "setup", "(", ")", "entry", "=", "self", ".", "entry", "for", "fmt", "in", "self", ".", "_formats", ":", "fmt", ".", "run", "(", ...
runs the report format instances in this reporter. Will call setup if it hasn't been called already
[ "runs", "the", "report", "format", "instances", "in", "this", "reporter", ".", "Will", "call", "setup", "if", "it", "hasn", "t", "been", "called", "already" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L146-L160
train
30,268
obriencj/python-javatools
javatools/report.py
Reporter.clear
def clear(self): """ calls clear on any report format instances created during setup and drops the cache """ if self._formats: for fmt in self._formats: fmt.clear() self._formats = None
python
def clear(self): """ calls clear on any report format instances created during setup and drops the cache """ if self._formats: for fmt in self._formats: fmt.clear() self._formats = None
[ "def", "clear", "(", "self", ")", ":", "if", "self", ".", "_formats", ":", "for", "fmt", "in", "self", ".", "_formats", ":", "fmt", ".", "clear", "(", ")", "self", ".", "_formats", "=", "None" ]
calls clear on any report format instances created during setup and drops the cache
[ "calls", "clear", "on", "any", "report", "format", "instances", "created", "during", "setup", "and", "drops", "the", "cache" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L163-L172
train
30,269
obriencj/python-javatools
javatools/report.py
CheetahReportFormat._relative
def _relative(self, uri): """ if uri is relative, re-relate it to our basedir """ if uri.startswith("http:") or \ uri.startswith("https:") or \ uri.startswith("file:") or \ uri.startswith("/"): return uri elif exists(uri): return relpath(uri, self.basedir) else: return uri
python
def _relative(self, uri): """ if uri is relative, re-relate it to our basedir """ if uri.startswith("http:") or \ uri.startswith("https:") or \ uri.startswith("file:") or \ uri.startswith("/"): return uri elif exists(uri): return relpath(uri, self.basedir) else: return uri
[ "def", "_relative", "(", "self", ",", "uri", ")", ":", "if", "uri", ".", "startswith", "(", "\"http:\"", ")", "or", "uri", ".", "startswith", "(", "\"https:\"", ")", "or", "uri", ".", "startswith", "(", "\"file:\"", ")", "or", "uri", ".", "startswith",...
if uri is relative, re-relate it to our basedir
[ "if", "uri", "is", "relative", "re", "-", "relate", "it", "to", "our", "basedir" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L409-L424
train
30,270
obriencj/python-javatools
javatools/report.py
CheetahReportFormat._relative_uris
def _relative_uris(self, uri_list): """ if uris in list are relative, re-relate them to our basedir """ return [u for u in (self._relative(uri) for uri in uri_list) if u]
python
def _relative_uris(self, uri_list): """ if uris in list are relative, re-relate them to our basedir """ return [u for u in (self._relative(uri) for uri in uri_list) if u]
[ "def", "_relative_uris", "(", "self", ",", "uri_list", ")", ":", "return", "[", "u", "for", "u", "in", "(", "self", ".", "_relative", "(", "uri", ")", "for", "uri", "in", "uri_list", ")", "if", "u", "]" ]
if uris in list are relative, re-relate them to our basedir
[ "if", "uris", "in", "list", "are", "relative", "re", "-", "relate", "them", "to", "our", "basedir" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L427-L432
train
30,271
obriencj/python-javatools
javatools/report.py
CheetahReportFormat.setup
def setup(self): """ copies default stylesheets and javascript files if necessary, and appends them to the options """ from javatools import cheetah options = self.options datadir = getattr(options, "html_copy_data", None) if getattr(options, "html_data_copied", False) or not datadir: # either already run by a parent report, or not supposed # to run at all. return # this is where we've installed the default media datasrc = join(cheetah.__path__[0], "data") # record the .js and .css content we copy javascripts = list() stylesheets = list() # copy the contents of our data source to datadir for _orig, copied in copydir(datasrc, datadir): if copied.endswith(".js"): javascripts.append(copied) elif copied.endswith(".css"): stylesheets.append(copied) javascripts.extend(getattr(options, "html_javascripts", tuple())) stylesheets.extend(getattr(options, "html_stylesheets", tuple())) options.html_javascripts = javascripts options.html_stylesheets = stylesheets # keep from copying again options.html_data_copied = True
python
def setup(self): """ copies default stylesheets and javascript files if necessary, and appends them to the options """ from javatools import cheetah options = self.options datadir = getattr(options, "html_copy_data", None) if getattr(options, "html_data_copied", False) or not datadir: # either already run by a parent report, or not supposed # to run at all. return # this is where we've installed the default media datasrc = join(cheetah.__path__[0], "data") # record the .js and .css content we copy javascripts = list() stylesheets = list() # copy the contents of our data source to datadir for _orig, copied in copydir(datasrc, datadir): if copied.endswith(".js"): javascripts.append(copied) elif copied.endswith(".css"): stylesheets.append(copied) javascripts.extend(getattr(options, "html_javascripts", tuple())) stylesheets.extend(getattr(options, "html_stylesheets", tuple())) options.html_javascripts = javascripts options.html_stylesheets = stylesheets # keep from copying again options.html_data_copied = True
[ "def", "setup", "(", "self", ")", ":", "from", "javatools", "import", "cheetah", "options", "=", "self", ".", "options", "datadir", "=", "getattr", "(", "options", ",", "\"html_copy_data\"", ",", "None", ")", "if", "getattr", "(", "options", ",", "\"html_d...
copies default stylesheets and javascript files if necessary, and appends them to the options
[ "copies", "default", "stylesheets", "and", "javascript", "files", "if", "necessary", "and", "appends", "them", "to", "the", "options" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L435-L472
train
30,272
obriencj/python-javatools
javatools/report.py
CheetahReportFormat.run_impl
def run_impl(self, change, entry, out): """ sets up the report directory for an HTML report. Obtains the top-level Cheetah template that is appropriate for the change instance, and runs it. The cheetah templates are supplied the following values: * change - the Change instance to report on * entry - the string name of the entry for this report * options - the cli options object * breadcrumbs - list of backlinks * javascripts - list of .js links * stylesheets - list of .css links The cheetah templates are also given a render_change method which can be called on another Change instance to cause its template to be resolved and run in-line. """ options = self.options # translate relative paths if necessary javascripts = self._relative_uris(options.html_javascripts) stylesheets = self._relative_uris(options.html_stylesheets) # map the class of the change to a template class template_class = resolve_cheetah_template(type(change)) # instantiate and setup the template template = template_class() # create a transaction wrapping the output stream template.transaction = DummyTransaction() template.transaction.response(resp=out) # inject our values template.change = change template.entry = entry template.options = options template.breadcrumbs = self.breadcrumbs template.javascripts = javascripts template.stylesheets = stylesheets # this lets us call render_change from within the template on # a change instance to chain to another template (eg, for # sub-changes) template.render_change = lambda c: self.run_impl(c, entry, out) # execute the template, which will write its contents to the # transaction (and the underlying stream) template.respond() # clean up the template template.shutdown()
python
def run_impl(self, change, entry, out): """ sets up the report directory for an HTML report. Obtains the top-level Cheetah template that is appropriate for the change instance, and runs it. The cheetah templates are supplied the following values: * change - the Change instance to report on * entry - the string name of the entry for this report * options - the cli options object * breadcrumbs - list of backlinks * javascripts - list of .js links * stylesheets - list of .css links The cheetah templates are also given a render_change method which can be called on another Change instance to cause its template to be resolved and run in-line. """ options = self.options # translate relative paths if necessary javascripts = self._relative_uris(options.html_javascripts) stylesheets = self._relative_uris(options.html_stylesheets) # map the class of the change to a template class template_class = resolve_cheetah_template(type(change)) # instantiate and setup the template template = template_class() # create a transaction wrapping the output stream template.transaction = DummyTransaction() template.transaction.response(resp=out) # inject our values template.change = change template.entry = entry template.options = options template.breadcrumbs = self.breadcrumbs template.javascripts = javascripts template.stylesheets = stylesheets # this lets us call render_change from within the template on # a change instance to chain to another template (eg, for # sub-changes) template.render_change = lambda c: self.run_impl(c, entry, out) # execute the template, which will write its contents to the # transaction (and the underlying stream) template.respond() # clean up the template template.shutdown()
[ "def", "run_impl", "(", "self", ",", "change", ",", "entry", ",", "out", ")", ":", "options", "=", "self", ".", "options", "# translate relative paths if necessary", "javascripts", "=", "self", ".", "_relative_uris", "(", "options", ".", "html_javascripts", ")",...
sets up the report directory for an HTML report. Obtains the top-level Cheetah template that is appropriate for the change instance, and runs it. The cheetah templates are supplied the following values: * change - the Change instance to report on * entry - the string name of the entry for this report * options - the cli options object * breadcrumbs - list of backlinks * javascripts - list of .js links * stylesheets - list of .css links The cheetah templates are also given a render_change method which can be called on another Change instance to cause its template to be resolved and run in-line.
[ "sets", "up", "the", "report", "directory", "for", "an", "HTML", "report", ".", "Obtains", "the", "top", "-", "level", "Cheetah", "template", "that", "is", "appropriate", "for", "the", "change", "instance", "and", "runs", "it", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L475-L528
train
30,273
obriencj/python-javatools
javatools/distinfo.py
DistInfo.get_requires
def get_requires(self, ignored=tuple()): """ a map of requirements to what requires it. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map""" if self._requires is None: self._collect_requires_provides() d = self._requires if ignored: d = dict((k, v) for k, v in d.items() if not fnmatches(k, *ignored)) return d
python
def get_requires(self, ignored=tuple()): """ a map of requirements to what requires it. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map""" if self._requires is None: self._collect_requires_provides() d = self._requires if ignored: d = dict((k, v) for k, v in d.items() if not fnmatches(k, *ignored)) return d
[ "def", "get_requires", "(", "self", ",", "ignored", "=", "tuple", "(", ")", ")", ":", "if", "self", ".", "_requires", "is", "None", ":", "self", ".", "_collect_requires_provides", "(", ")", "d", "=", "self", ".", "_requires", "if", "ignored", ":", "d",...
a map of requirements to what requires it. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map
[ "a", "map", "of", "requirements", "to", "what", "requires", "it", ".", "ignored", "is", "an", "optional", "list", "of", "globbed", "patterns", "indicating", "packages", "classes", "etc", "that", "shouldn", "t", "be", "included", "in", "the", "provides", "map...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distinfo.py#L116-L128
train
30,274
obriencj/python-javatools
javatools/distinfo.py
DistInfo.get_provides
def get_provides(self, ignored=tuple()): """ a map of provided classes and class members, and what provides them. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map""" if self._provides is None: self._collect_requires_provides() d = self._provides if ignored: d = dict((k, v) for k, v in d.items() if not fnmatches(k, *ignored)) return d
python
def get_provides(self, ignored=tuple()): """ a map of provided classes and class members, and what provides them. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map""" if self._provides is None: self._collect_requires_provides() d = self._provides if ignored: d = dict((k, v) for k, v in d.items() if not fnmatches(k, *ignored)) return d
[ "def", "get_provides", "(", "self", ",", "ignored", "=", "tuple", "(", ")", ")", ":", "if", "self", ".", "_provides", "is", "None", ":", "self", ".", "_collect_requires_provides", "(", ")", "d", "=", "self", ".", "_provides", "if", "ignored", ":", "d",...
a map of provided classes and class members, and what provides them. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map
[ "a", "map", "of", "provided", "classes", "and", "class", "members", "and", "what", "provides", "them", ".", "ignored", "is", "an", "optional", "list", "of", "globbed", "patterns", "indicating", "packages", "classes", "etc", "that", "shouldn", "t", "be", "inc...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distinfo.py#L131-L144
train
30,275
obriencj/python-javatools
javatools/distinfo.py
DistInfo.close
def close(self): """ if this was a zip'd distribution, any introspection may have resulted in opening or creating temporary files. Call close in order to clean up. """ if self.tmpdir: rmtree(self.tmpdir) self.tmpdir = None self._contents = None
python
def close(self): """ if this was a zip'd distribution, any introspection may have resulted in opening or creating temporary files. Call close in order to clean up. """ if self.tmpdir: rmtree(self.tmpdir) self.tmpdir = None self._contents = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "tmpdir", ":", "rmtree", "(", "self", ".", "tmpdir", ")", "self", ".", "tmpdir", "=", "None", "self", ".", "_contents", "=", "None" ]
if this was a zip'd distribution, any introspection may have resulted in opening or creating temporary files. Call close in order to clean up.
[ "if", "this", "was", "a", "zip", "d", "distribution", "any", "introspection", "may", "have", "resulted", "in", "opening", "or", "creating", "temporary", "files", ".", "Call", "close", "in", "order", "to", "clean", "up", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distinfo.py#L179-L188
train
30,276
obriencj/python-javatools
javatools/opcodes.py
_unpack
def _unpack(struct, bc, offset=0): """ returns the unpacked data tuple, and the next offset past the unpacked data """ return struct.unpack_from(bc, offset), offset + struct.size
python
def _unpack(struct, bc, offset=0): """ returns the unpacked data tuple, and the next offset past the unpacked data """ return struct.unpack_from(bc, offset), offset + struct.size
[ "def", "_unpack", "(", "struct", ",", "bc", ",", "offset", "=", "0", ")", ":", "return", "struct", ".", "unpack_from", "(", "bc", ",", "offset", ")", ",", "offset", "+", "struct", ".", "size" ]
returns the unpacked data tuple, and the next offset past the unpacked data
[ "returns", "the", "unpacked", "data", "tuple", "and", "the", "next", "offset", "past", "the", "unpacked", "data" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L162-L168
train
30,277
obriencj/python-javatools
javatools/opcodes.py
_unpack_lookupswitch
def _unpack_lookupswitch(bc, offset): """ function for unpacking the lookupswitch op arguments """ jump = (offset % 4) if jump: offset += (4 - jump) (default, npairs), offset = _unpack(_struct_ii, bc, offset) switches = list() for _index in range(npairs): pair, offset = _unpack(_struct_ii, bc, offset) switches.append(pair) return (default, switches), offset
python
def _unpack_lookupswitch(bc, offset): """ function for unpacking the lookupswitch op arguments """ jump = (offset % 4) if jump: offset += (4 - jump) (default, npairs), offset = _unpack(_struct_ii, bc, offset) switches = list() for _index in range(npairs): pair, offset = _unpack(_struct_ii, bc, offset) switches.append(pair) return (default, switches), offset
[ "def", "_unpack_lookupswitch", "(", "bc", ",", "offset", ")", ":", "jump", "=", "(", "offset", "%", "4", ")", "if", "jump", ":", "offset", "+=", "(", "4", "-", "jump", ")", "(", "default", ",", "npairs", ")", ",", "offset", "=", "_unpack", "(", "...
function for unpacking the lookupswitch op arguments
[ "function", "for", "unpacking", "the", "lookupswitch", "op", "arguments" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L171-L187
train
30,278
obriencj/python-javatools
javatools/opcodes.py
_unpack_tableswitch
def _unpack_tableswitch(bc, offset): """ function for unpacking the tableswitch op arguments """ jump = (offset % 4) if jump: offset += (4 - jump) (default, low, high), offset = _unpack(_struct_iii, bc, offset) joffs = list() for _index in range((high - low) + 1): j, offset = _unpack(_struct_i, bc, offset) joffs.append(j) return (default, low, high, joffs), offset
python
def _unpack_tableswitch(bc, offset): """ function for unpacking the tableswitch op arguments """ jump = (offset % 4) if jump: offset += (4 - jump) (default, low, high), offset = _unpack(_struct_iii, bc, offset) joffs = list() for _index in range((high - low) + 1): j, offset = _unpack(_struct_i, bc, offset) joffs.append(j) return (default, low, high, joffs), offset
[ "def", "_unpack_tableswitch", "(", "bc", ",", "offset", ")", ":", "jump", "=", "(", "offset", "%", "4", ")", "if", "jump", ":", "offset", "+=", "(", "4", "-", "jump", ")", "(", "default", ",", "low", ",", "high", ")", ",", "offset", "=", "_unpack...
function for unpacking the tableswitch op arguments
[ "function", "for", "unpacking", "the", "tableswitch", "op", "arguments" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L190-L206
train
30,279
obriencj/python-javatools
javatools/opcodes.py
_unpack_wide
def _unpack_wide(bc, offset): """ unpacker for wide ops """ code = ord(bc[offset]) if code == OP_iinc: return _unpack(_struct_BHh, bc, offset) elif code in (OP_iload, OP_fload, OP_aload, OP_lload, OP_dload, OP_istore, OP_fstore, OP_astore, OP_lstore, OP_dstore, OP_ret): return _unpack(_struct_BH, bc, offset) else: # no other opcodes are valid, so shouldn't have fallen through # to here. assert False
python
def _unpack_wide(bc, offset): """ unpacker for wide ops """ code = ord(bc[offset]) if code == OP_iinc: return _unpack(_struct_BHh, bc, offset) elif code in (OP_iload, OP_fload, OP_aload, OP_lload, OP_dload, OP_istore, OP_fstore, OP_astore, OP_lstore, OP_dstore, OP_ret): return _unpack(_struct_BH, bc, offset) else: # no other opcodes are valid, so shouldn't have fallen through # to here. assert False
[ "def", "_unpack_wide", "(", "bc", ",", "offset", ")", ":", "code", "=", "ord", "(", "bc", "[", "offset", "]", ")", "if", "code", "==", "OP_iinc", ":", "return", "_unpack", "(", "_struct_BHh", ",", "bc", ",", "offset", ")", "elif", "code", "in", "("...
unpacker for wide ops
[ "unpacker", "for", "wide", "ops" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L209-L228
train
30,280
obriencj/python-javatools
javatools/distdiff.py
_mp_run_check
def _mp_run_check(tasks, results, options): """ a helper function for multiprocessing with DistReport. """ try: for index, change in iter(tasks.get, None): # this is the part that takes up all of our time and # produces side-effects like writing out files for all of # the report formats. change.check() # rather than serializing the completed change (which # could be rather large now that it's been realized), we # send back only what we want, which is the squashed # overview, and throw away the used bits. squashed = squash(change, options=options) change.clear() results.put((index, squashed)) except KeyboardInterrupt: # prevent a billion lines of backtrace from hitting the user # in the face return
python
def _mp_run_check(tasks, results, options): """ a helper function for multiprocessing with DistReport. """ try: for index, change in iter(tasks.get, None): # this is the part that takes up all of our time and # produces side-effects like writing out files for all of # the report formats. change.check() # rather than serializing the completed change (which # could be rather large now that it's been realized), we # send back only what we want, which is the squashed # overview, and throw away the used bits. squashed = squash(change, options=options) change.clear() results.put((index, squashed)) except KeyboardInterrupt: # prevent a billion lines of backtrace from hitting the user # in the face return
[ "def", "_mp_run_check", "(", "tasks", ",", "results", ",", "options", ")", ":", "try", ":", "for", "index", ",", "change", "in", "iter", "(", "tasks", ".", "get", ",", "None", ")", ":", "# this is the part that takes up all of our time and", "# produces side-eff...
a helper function for multiprocessing with DistReport.
[ "a", "helper", "function", "for", "multiprocessing", "with", "DistReport", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L525-L549
train
30,281
obriencj/python-javatools
javatools/distdiff.py
add_distdiff_optgroup
def add_distdiff_optgroup(parser): """ Option group relating to the use of a DistChange or DistReport """ # for the --processes default cpus = cpu_count() og = parser.add_argument_group("Distribution Checking Options") og.add_argument("--processes", type=int, default=cpus, help="Number of child processes to spawn to handle" " sub-reports. Set to 0 to disable multi-processing." " Defaults to the number of CPUs (%r)" % cpus) og.add_argument("--shallow", action="store_true", default=False, help="Check only that the files of this dist have" "changed, do not infer the meaning") og.add_argument("--ignore-filenames", action="append", default=[], help="file glob to ignore. Can be specified multiple" " times") og.add_argument("--ignore-trailing-whitespace", action="store_true", default=False, help="ignore trailing whitespace when comparing text" " files")
python
def add_distdiff_optgroup(parser): """ Option group relating to the use of a DistChange or DistReport """ # for the --processes default cpus = cpu_count() og = parser.add_argument_group("Distribution Checking Options") og.add_argument("--processes", type=int, default=cpus, help="Number of child processes to spawn to handle" " sub-reports. Set to 0 to disable multi-processing." " Defaults to the number of CPUs (%r)" % cpus) og.add_argument("--shallow", action="store_true", default=False, help="Check only that the files of this dist have" "changed, do not infer the meaning") og.add_argument("--ignore-filenames", action="append", default=[], help="file glob to ignore. Can be specified multiple" " times") og.add_argument("--ignore-trailing-whitespace", action="store_true", default=False, help="ignore trailing whitespace when comparing text" " files")
[ "def", "add_distdiff_optgroup", "(", "parser", ")", ":", "# for the --processes default", "cpus", "=", "cpu_count", "(", ")", "og", "=", "parser", ".", "add_argument_group", "(", "\"Distribution Checking Options\"", ")", "og", ".", "add_argument", "(", "\"--processes\...
Option group relating to the use of a DistChange or DistReport
[ "Option", "group", "relating", "to", "the", "use", "of", "a", "DistChange", "or", "DistReport" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L591-L617
train
30,282
obriencj/python-javatools
javatools/distdiff.py
create_optparser
def create_optparser(progname=None): """ an OptionParser instance filled with options and groups appropriate for use with the distdiff command """ from . import report parser = ArgumentParser(prog=progname) parser.add_argument("dist", nargs=2, help="distributions to compare") add_general_optgroup(parser) add_distdiff_optgroup(parser) add_jardiff_optgroup(parser) add_classdiff_optgroup(parser) report.add_general_report_optgroup(parser) report.add_json_report_optgroup(parser) report.add_html_report_optgroup(parser) return parser
python
def create_optparser(progname=None): """ an OptionParser instance filled with options and groups appropriate for use with the distdiff command """ from . import report parser = ArgumentParser(prog=progname) parser.add_argument("dist", nargs=2, help="distributions to compare") add_general_optgroup(parser) add_distdiff_optgroup(parser) add_jardiff_optgroup(parser) add_classdiff_optgroup(parser) report.add_general_report_optgroup(parser) report.add_json_report_optgroup(parser) report.add_html_report_optgroup(parser) return parser
[ "def", "create_optparser", "(", "progname", "=", "None", ")", ":", "from", ".", "import", "report", "parser", "=", "ArgumentParser", "(", "prog", "=", "progname", ")", "parser", ".", "add_argument", "(", "\"dist\"", ",", "nargs", "=", "2", ",", "help", "...
an OptionParser instance filled with options and groups appropriate for use with the distdiff command
[ "an", "OptionParser", "instance", "filled", "with", "options", "and", "groups", "appropriate", "for", "use", "with", "the", "distdiff", "command" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L620-L640
train
30,283
obriencj/python-javatools
javatools/distdiff.py
default_distdiff_options
def default_distdiff_options(updates=None): """ generate an options object with the appropriate default values in place for API usage of distdiff features. overrides is an optional dictionary which will be used to update fields on the options object. """ parser = create_optparser() options = parser.parse_args(list()) if updates: # pylint: disable=W0212 options._update_careful(updates) return options
python
def default_distdiff_options(updates=None): """ generate an options object with the appropriate default values in place for API usage of distdiff features. overrides is an optional dictionary which will be used to update fields on the options object. """ parser = create_optparser() options = parser.parse_args(list()) if updates: # pylint: disable=W0212 options._update_careful(updates) return options
[ "def", "default_distdiff_options", "(", "updates", "=", "None", ")", ":", "parser", "=", "create_optparser", "(", ")", "options", "=", "parser", ".", "parse_args", "(", "list", "(", ")", ")", "if", "updates", ":", "# pylint: disable=W0212", "options", ".", "...
generate an options object with the appropriate default values in place for API usage of distdiff features. overrides is an optional dictionary which will be used to update fields on the options object.
[ "generate", "an", "options", "object", "with", "the", "appropriate", "default", "values", "in", "place", "for", "API", "usage", "of", "distdiff", "features", ".", "overrides", "is", "an", "optional", "dictionary", "which", "will", "be", "used", "to", "update",...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L643-L658
train
30,284
obriencj/python-javatools
javatools/distdiff.py
DistChange.collect_impl
def collect_impl(self): """ emits change instances based on the delta of the two distribution directories """ ld = self.ldata rd = self.rdata deep = not self.shallow for event, entry in compare(ld, rd): if deep and fnmatches(entry, *JAR_PATTERNS): if event == LEFT: yield DistJarRemoved(ld, rd, entry) elif event == RIGHT: yield DistJarAdded(ld, rd, entry) elif event == DIFF: yield DistJarChange(ld, rd, entry, True) elif event == SAME: yield DistJarChange(ld, rd, entry, False) elif deep and fnmatches(entry, "*.class"): if event == LEFT: yield DistClassRemoved(ld, rd, entry) elif event == RIGHT: yield DistClassAdded(ld, rd, entry) elif event == DIFF: yield DistClassChange(ld, rd, entry, True) elif event == SAME: yield DistClassChange(ld, rd, entry, False) elif deep and fnmatches(entry, *TEXT_PATTERNS): if event == LEFT: yield DistContentRemoved(ld, rd, entry) elif event == RIGHT: yield DistContentAdded(ld, rd, entry) elif event == DIFF: yield DistTextChange(ld, rd, entry) elif event == SAME: yield DistTextChange(ld, rd, entry, False) elif deep and fnmatches(entry, "*/MANIFEST.MF"): if event == LEFT: yield DistContentRemoved(ld, rd, entry) elif event == RIGHT: yield DistContentAdded(ld, rd, entry) elif event == DIFF: yield DistManifestChange(ld, rd, entry, True) elif event == SAME: yield DistManifestChange(ld, rd, entry, False) else: if event == LEFT: yield DistContentRemoved(ld, rd, entry) elif event == RIGHT: yield DistContentAdded(ld, rd, entry) elif event == DIFF: yield DistContentChange(ld, rd, entry, True) elif event == SAME: yield DistContentChange(ld, rd, entry, False)
python
def collect_impl(self): """ emits change instances based on the delta of the two distribution directories """ ld = self.ldata rd = self.rdata deep = not self.shallow for event, entry in compare(ld, rd): if deep and fnmatches(entry, *JAR_PATTERNS): if event == LEFT: yield DistJarRemoved(ld, rd, entry) elif event == RIGHT: yield DistJarAdded(ld, rd, entry) elif event == DIFF: yield DistJarChange(ld, rd, entry, True) elif event == SAME: yield DistJarChange(ld, rd, entry, False) elif deep and fnmatches(entry, "*.class"): if event == LEFT: yield DistClassRemoved(ld, rd, entry) elif event == RIGHT: yield DistClassAdded(ld, rd, entry) elif event == DIFF: yield DistClassChange(ld, rd, entry, True) elif event == SAME: yield DistClassChange(ld, rd, entry, False) elif deep and fnmatches(entry, *TEXT_PATTERNS): if event == LEFT: yield DistContentRemoved(ld, rd, entry) elif event == RIGHT: yield DistContentAdded(ld, rd, entry) elif event == DIFF: yield DistTextChange(ld, rd, entry) elif event == SAME: yield DistTextChange(ld, rd, entry, False) elif deep and fnmatches(entry, "*/MANIFEST.MF"): if event == LEFT: yield DistContentRemoved(ld, rd, entry) elif event == RIGHT: yield DistContentAdded(ld, rd, entry) elif event == DIFF: yield DistManifestChange(ld, rd, entry, True) elif event == SAME: yield DistManifestChange(ld, rd, entry, False) else: if event == LEFT: yield DistContentRemoved(ld, rd, entry) elif event == RIGHT: yield DistContentAdded(ld, rd, entry) elif event == DIFF: yield DistContentChange(ld, rd, entry, True) elif event == SAME: yield DistContentChange(ld, rd, entry, False)
[ "def", "collect_impl", "(", "self", ")", ":", "ld", "=", "self", ".", "ldata", "rd", "=", "self", ".", "rdata", "deep", "=", "not", "self", ".", "shallow", "for", "event", ",", "entry", "in", "compare", "(", "ld", ",", "rd", ")", ":", "if", "deep...
emits change instances based on the delta of the two distribution directories
[ "emits", "change", "instances", "based", "on", "the", "delta", "of", "the", "two", "distribution", "directories" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L304-L363
train
30,285
obriencj/python-javatools
javatools/distdiff.py
DistReport.collect_impl
def collect_impl(self): """ overrides DistJarChange and DistClassChange from the underlying DistChange with DistJarReport and DistClassReport instances """ for c in DistChange.collect_impl(self): if isinstance(c, DistJarChange): if c.is_change(): ln = DistJarReport.report_name nr = self.reporter.subreporter(c.entry, ln) c = DistJarReport(c.ldata, c.rdata, c.entry, nr) elif isinstance(c, DistClassChange): if c.is_change(): ln = DistClassReport.report_name nr = self.reporter.subreporter(c.entry, ln) c = DistClassReport(c.ldata, c.rdata, c.entry, nr) yield c
python
def collect_impl(self): """ overrides DistJarChange and DistClassChange from the underlying DistChange with DistJarReport and DistClassReport instances """ for c in DistChange.collect_impl(self): if isinstance(c, DistJarChange): if c.is_change(): ln = DistJarReport.report_name nr = self.reporter.subreporter(c.entry, ln) c = DistJarReport(c.ldata, c.rdata, c.entry, nr) elif isinstance(c, DistClassChange): if c.is_change(): ln = DistClassReport.report_name nr = self.reporter.subreporter(c.entry, ln) c = DistClassReport(c.ldata, c.rdata, c.entry, nr) yield c
[ "def", "collect_impl", "(", "self", ")", ":", "for", "c", "in", "DistChange", ".", "collect_impl", "(", "self", ")", ":", "if", "isinstance", "(", "c", ",", "DistJarChange", ")", ":", "if", "c", ".", "is_change", "(", ")", ":", "ln", "=", "DistJarRep...
overrides DistJarChange and DistClassChange from the underlying DistChange with DistJarReport and DistClassReport instances
[ "overrides", "DistJarChange", "and", "DistClassChange", "from", "the", "underlying", "DistChange", "with", "DistJarReport", "and", "DistClassReport", "instances" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L383-L400
train
30,286
obriencj/python-javatools
javatools/distdiff.py
DistReport.mp_check_impl
def mp_check_impl(self, process_count): """ a multiprocessing-enabled check implementation. Will create up to process_count helper processes and use them to perform the DistJarReport and DistClassReport actions. """ from multiprocessing import Process, Queue options = self.reporter.options # this is the function that will be run in a separate process, # which will handle the tasks queue and feed into the results # queue func = _mp_run_check # normally this would happen lazily, but since we'll have # multiple processes all running reports at the same time, we # need to make sure the setup is done before-hand. This is # hackish, but in particular this keeps the HTML reports from # trying to perform the default data copy over and over. self.reporter.setup() # enqueue the sub-reports for multi-processing. Other types of # changes can happen sync. changes = list(self.collect_impl()) task_count = 0 tasks = Queue() results = Queue() try: # as soon as we start using the tasks queue, we need to be # catching the KeyboardInterrupt event so that we can # drain the queue and lets its underlying thread terminate # happily. # TODO: is there a better way to handle this shutdown # gracefully? # feed any sub-reports to the tasks queue for index in range(0, len(changes)): change = changes[index] if isinstance(change, (DistJarReport, DistClassReport)): changes[index] = None tasks.put((index, change)) task_count += 1 # infrequent edge case, but don't bother starting more # helpers than we'll ever use process_count = min(process_count, task_count) # start the number of helper processes, and make sure # there are that many stop sentinels at the end of the # tasks queue for _i in range(0, process_count): tasks.put(None) process = Process(target=func, args=(tasks, results, options)) process.daemon = False process.start() # while the helpers are running, perform our checks for change in changes: if change: change.check() # get all of the results and feed them back into our change for _i in range(0, task_count): index, change = results.get() changes[index] = change except KeyboardInterrupt: # drain the tasks queue so it will exit gracefully for _change in iter(tasks.get, None): pass raise # complete the check by setting our internal collection of # child changes and returning our overall status c = False for change in changes: c = c or change.is_change() self.changes = changes return c, None
python
def mp_check_impl(self, process_count): """ a multiprocessing-enabled check implementation. Will create up to process_count helper processes and use them to perform the DistJarReport and DistClassReport actions. """ from multiprocessing import Process, Queue options = self.reporter.options # this is the function that will be run in a separate process, # which will handle the tasks queue and feed into the results # queue func = _mp_run_check # normally this would happen lazily, but since we'll have # multiple processes all running reports at the same time, we # need to make sure the setup is done before-hand. This is # hackish, but in particular this keeps the HTML reports from # trying to perform the default data copy over and over. self.reporter.setup() # enqueue the sub-reports for multi-processing. Other types of # changes can happen sync. changes = list(self.collect_impl()) task_count = 0 tasks = Queue() results = Queue() try: # as soon as we start using the tasks queue, we need to be # catching the KeyboardInterrupt event so that we can # drain the queue and lets its underlying thread terminate # happily. # TODO: is there a better way to handle this shutdown # gracefully? # feed any sub-reports to the tasks queue for index in range(0, len(changes)): change = changes[index] if isinstance(change, (DistJarReport, DistClassReport)): changes[index] = None tasks.put((index, change)) task_count += 1 # infrequent edge case, but don't bother starting more # helpers than we'll ever use process_count = min(process_count, task_count) # start the number of helper processes, and make sure # there are that many stop sentinels at the end of the # tasks queue for _i in range(0, process_count): tasks.put(None) process = Process(target=func, args=(tasks, results, options)) process.daemon = False process.start() # while the helpers are running, perform our checks for change in changes: if change: change.check() # get all of the results and feed them back into our change for _i in range(0, task_count): index, change = results.get() changes[index] = change except KeyboardInterrupt: # drain the tasks queue so it will exit gracefully for _change in iter(tasks.get, None): pass raise # complete the check by setting our internal collection of # child changes and returning our overall status c = False for change in changes: c = c or change.is_change() self.changes = changes return c, None
[ "def", "mp_check_impl", "(", "self", ",", "process_count", ")", ":", "from", "multiprocessing", "import", "Process", ",", "Queue", "options", "=", "self", ".", "reporter", ".", "options", "# this is the function that will be run in a separate process,", "# which will hand...
a multiprocessing-enabled check implementation. Will create up to process_count helper processes and use them to perform the DistJarReport and DistClassReport actions.
[ "a", "multiprocessing", "-", "enabled", "check", "implementation", ".", "Will", "create", "up", "to", "process_count", "helper", "processes", "and", "use", "them", "to", "perform", "the", "DistJarReport", "and", "DistClassReport", "actions", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L403-L486
train
30,287
obriencj/python-javatools
javatools/pack.py
compile_struct
def compile_struct(fmt, cache=None): """ returns a struct.Struct instance compiled from fmt. If fmt has already been compiled, it will return the previously compiled Struct instance from the cache. """ if cache is None: cache = _struct_cache sfmt = cache.get(fmt, None) if not sfmt: sfmt = Struct(fmt) cache[fmt] = sfmt return sfmt
python
def compile_struct(fmt, cache=None): """ returns a struct.Struct instance compiled from fmt. If fmt has already been compiled, it will return the previously compiled Struct instance from the cache. """ if cache is None: cache = _struct_cache sfmt = cache.get(fmt, None) if not sfmt: sfmt = Struct(fmt) cache[fmt] = sfmt return sfmt
[ "def", "compile_struct", "(", "fmt", ",", "cache", "=", "None", ")", ":", "if", "cache", "is", "None", ":", "cache", "=", "_struct_cache", "sfmt", "=", "cache", ".", "get", "(", "fmt", ",", "None", ")", "if", "not", "sfmt", ":", "sfmt", "=", "Struc...
returns a struct.Struct instance compiled from fmt. If fmt has already been compiled, it will return the previously compiled Struct instance from the cache.
[ "returns", "a", "struct", ".", "Struct", "instance", "compiled", "from", "fmt", ".", "If", "fmt", "has", "already", "been", "compiled", "it", "will", "return", "the", "previously", "compiled", "Struct", "instance", "from", "the", "cache", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L55-L69
train
30,288
obriencj/python-javatools
javatools/pack.py
BufferUnpacker.unpack
def unpack(self, fmt): """ unpacks the given fmt from the underlying buffer and returns the results. Will raise an UnpackException if there is not enough data to satisfy the fmt """ sfmt = compile_struct(fmt) size = sfmt.size offset = self.offset if self.data: avail = len(self.data) - offset else: avail = 0 if avail < size: raise UnpackException(fmt, size, avail) self.offset = offset + size return sfmt.unpack_from(self.data, offset)
python
def unpack(self, fmt): """ unpacks the given fmt from the underlying buffer and returns the results. Will raise an UnpackException if there is not enough data to satisfy the fmt """ sfmt = compile_struct(fmt) size = sfmt.size offset = self.offset if self.data: avail = len(self.data) - offset else: avail = 0 if avail < size: raise UnpackException(fmt, size, avail) self.offset = offset + size return sfmt.unpack_from(self.data, offset)
[ "def", "unpack", "(", "self", ",", "fmt", ")", ":", "sfmt", "=", "compile_struct", "(", "fmt", ")", "size", "=", "sfmt", ".", "size", "offset", "=", "self", ".", "offset", "if", "self", ".", "data", ":", "avail", "=", "len", "(", "self", ".", "da...
unpacks the given fmt from the underlying buffer and returns the results. Will raise an UnpackException if there is not enough data to satisfy the fmt
[ "unpacks", "the", "given", "fmt", "from", "the", "underlying", "buffer", "and", "returns", "the", "results", ".", "Will", "raise", "an", "UnpackException", "if", "there", "is", "not", "enough", "data", "to", "satisfy", "the", "fmt" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L183-L203
train
30,289
obriencj/python-javatools
javatools/pack.py
BufferUnpacker.unpack_struct
def unpack_struct(self, struct): """ unpacks the given struct from the underlying buffer and returns the results. Will raise an UnpackException if there is not enough data to satisfy the format of the structure """ size = struct.size offset = self.offset if self.data: avail = len(self.data) - offset else: avail = 0 if avail < size: raise UnpackException(struct.format, size, avail) self.offset = offset + size return struct.unpack_from(self.data, offset)
python
def unpack_struct(self, struct): """ unpacks the given struct from the underlying buffer and returns the results. Will raise an UnpackException if there is not enough data to satisfy the format of the structure """ size = struct.size offset = self.offset if self.data: avail = len(self.data) - offset else: avail = 0 if avail < size: raise UnpackException(struct.format, size, avail) self.offset = offset + size return struct.unpack_from(self.data, offset)
[ "def", "unpack_struct", "(", "self", ",", "struct", ")", ":", "size", "=", "struct", ".", "size", "offset", "=", "self", ".", "offset", "if", "self", ".", "data", ":", "avail", "=", "len", "(", "self", ".", "data", ")", "-", "offset", "else", ":", ...
unpacks the given struct from the underlying buffer and returns the results. Will raise an UnpackException if there is not enough data to satisfy the format of the structure
[ "unpacks", "the", "given", "struct", "from", "the", "underlying", "buffer", "and", "returns", "the", "results", ".", "Will", "raise", "an", "UnpackException", "if", "there", "is", "not", "enough", "data", "to", "satisfy", "the", "format", "of", "the", "struc...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L206-L225
train
30,290
obriencj/python-javatools
javatools/pack.py
BufferUnpacker.read
def read(self, count): """ read count bytes from the underlying buffer and return them as a str. Raises an UnpackException if there is not enough data in the underlying buffer. """ offset = self.offset if self.data: avail = len(self.data) - offset else: avail = 0 if avail < count: raise UnpackException(None, count, avail) self.offset = offset + count return self.data[offset:self.offset]
python
def read(self, count): """ read count bytes from the underlying buffer and return them as a str. Raises an UnpackException if there is not enough data in the underlying buffer. """ offset = self.offset if self.data: avail = len(self.data) - offset else: avail = 0 if avail < count: raise UnpackException(None, count, avail) self.offset = offset + count return self.data[offset:self.offset]
[ "def", "read", "(", "self", ",", "count", ")", ":", "offset", "=", "self", ".", "offset", "if", "self", ".", "data", ":", "avail", "=", "len", "(", "self", ".", "data", ")", "-", "offset", "else", ":", "avail", "=", "0", "if", "avail", "<", "co...
read count bytes from the underlying buffer and return them as a str. Raises an UnpackException if there is not enough data in the underlying buffer.
[ "read", "count", "bytes", "from", "the", "underlying", "buffer", "and", "return", "them", "as", "a", "str", ".", "Raises", "an", "UnpackException", "if", "there", "is", "not", "enough", "data", "in", "the", "underlying", "buffer", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L228-L245
train
30,291
obriencj/python-javatools
javatools/pack.py
StreamUnpacker.unpack
def unpack(self, fmt): """ unpacks the given fmt from the underlying stream and returns the results. Will raise an UnpackException if there is not enough data to satisfy the fmt """ sfmt = compile_struct(fmt) size = sfmt.size if not self.data: raise UnpackException(fmt, size, 0) buff = self.data.read(size) if len(buff) < size: raise UnpackException(fmt, size, len(buff)) return sfmt.unpack(buff)
python
def unpack(self, fmt): """ unpacks the given fmt from the underlying stream and returns the results. Will raise an UnpackException if there is not enough data to satisfy the fmt """ sfmt = compile_struct(fmt) size = sfmt.size if not self.data: raise UnpackException(fmt, size, 0) buff = self.data.read(size) if len(buff) < size: raise UnpackException(fmt, size, len(buff)) return sfmt.unpack(buff)
[ "def", "unpack", "(", "self", ",", "fmt", ")", ":", "sfmt", "=", "compile_struct", "(", "fmt", ")", "size", "=", "sfmt", ".", "size", "if", "not", "self", ".", "data", ":", "raise", "UnpackException", "(", "fmt", ",", "size", ",", "0", ")", "buff",...
unpacks the given fmt from the underlying stream and returns the results. Will raise an UnpackException if there is not enough data to satisfy the fmt
[ "unpacks", "the", "given", "fmt", "from", "the", "underlying", "stream", "and", "returns", "the", "results", ".", "Will", "raise", "an", "UnpackException", "if", "there", "is", "not", "enough", "data", "to", "satisfy", "the", "fmt" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L271-L288
train
30,292
obriencj/python-javatools
javatools/pack.py
StreamUnpacker.unpack_struct
def unpack_struct(self, struct): """ unpacks the given struct from the underlying stream and returns the results. Will raise an UnpackException if there is not enough data to satisfy the format of the structure """ size = struct.size if not self.data: raise UnpackException(struct.format, size, 0) buff = self.data.read(size) if len(buff) < size: raise UnpackException(struct.format, size, len(buff)) return struct.unpack(buff)
python
def unpack_struct(self, struct): """ unpacks the given struct from the underlying stream and returns the results. Will raise an UnpackException if there is not enough data to satisfy the format of the structure """ size = struct.size if not self.data: raise UnpackException(struct.format, size, 0) buff = self.data.read(size) if len(buff) < size: raise UnpackException(struct.format, size, len(buff)) return struct.unpack(buff)
[ "def", "unpack_struct", "(", "self", ",", "struct", ")", ":", "size", "=", "struct", ".", "size", "if", "not", "self", ".", "data", ":", "raise", "UnpackException", "(", "struct", ".", "format", ",", "size", ",", "0", ")", "buff", "=", "self", ".", ...
unpacks the given struct from the underlying stream and returns the results. Will raise an UnpackException if there is not enough data to satisfy the format of the structure
[ "unpacks", "the", "given", "struct", "from", "the", "underlying", "stream", "and", "returns", "the", "results", ".", "Will", "raise", "an", "UnpackException", "if", "there", "is", "not", "enough", "data", "to", "satisfy", "the", "format", "of", "the", "struc...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L291-L307
train
30,293
obriencj/python-javatools
javatools/pack.py
StreamUnpacker.read
def read(self, count): """ read count bytes from the unpacker and return it. Raises an UnpackException if there is not enough data in the underlying stream. """ if not self.data: raise UnpackException(None, count, 0) buff = self.data.read(count) if len(buff) < count: raise UnpackException(None, count, len(buff)) return buff
python
def read(self, count): """ read count bytes from the unpacker and return it. Raises an UnpackException if there is not enough data in the underlying stream. """ if not self.data: raise UnpackException(None, count, 0) buff = self.data.read(count) if len(buff) < count: raise UnpackException(None, count, len(buff)) return buff
[ "def", "read", "(", "self", ",", "count", ")", ":", "if", "not", "self", ".", "data", ":", "raise", "UnpackException", "(", "None", ",", "count", ",", "0", ")", "buff", "=", "self", ".", "data", ".", "read", "(", "count", ")", "if", "len", "(", ...
read count bytes from the unpacker and return it. Raises an UnpackException if there is not enough data in the underlying stream.
[ "read", "count", "bytes", "from", "the", "unpacker", "and", "return", "it", ".", "Raises", "an", "UnpackException", "if", "there", "is", "not", "enough", "data", "in", "the", "underlying", "stream", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L310-L324
train
30,294
obriencj/python-javatools
javatools/pack.py
StreamUnpacker.close
def close(self): """ close this unpacker, and the underlying stream if it supports such """ data = self.data self.data = None if hasattr(data, "close"): data.close()
python
def close(self): """ close this unpacker, and the underlying stream if it supports such """ data = self.data self.data = None if hasattr(data, "close"): data.close()
[ "def", "close", "(", "self", ")", ":", "data", "=", "self", ".", "data", "self", ".", "data", "=", "None", "if", "hasattr", "(", "data", ",", "\"close\"", ")", ":", "data", ".", "close", "(", ")" ]
close this unpacker, and the underlying stream if it supports such
[ "close", "this", "unpacker", "and", "the", "underlying", "stream", "if", "it", "supports", "such" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/pack.py#L327-L336
train
30,295
obriencj/python-javatools
javatools/cheetah/setuptools.py
cheetah_build_py_cmd.build_template
def build_template(self, template, template_file, package): """ Compile the cheetah template in src into a python file in build """ try: from Cheetah.Compiler import Compiler except ImportError: self.announce("unable to import Cheetah.Compiler, build failed") raise else: comp = Compiler(file=template_file, moduleName=template) # load configuration if it exists conf_fn = DEFAULT_CONFIG if exists(conf_fn): with open(conf_fn, "rt") as config: comp.updateSettingsFromConfigFileObj(config) # and just why can't I configure these? comp.setShBang("") comp.addModuleHeader("pylint: disable=C,W,R,F") outfd = join(self.build_lib, *package.split(".")) outfn = join(outfd, template + ".py") if not exists(outfd): makedirs(outfd) if newer(template_file, outfn): self.announce("compiling %s -> %s" % (template_file, outfd), 2) with open(outfn, "w") as output: output.write(str(comp))
python
def build_template(self, template, template_file, package): """ Compile the cheetah template in src into a python file in build """ try: from Cheetah.Compiler import Compiler except ImportError: self.announce("unable to import Cheetah.Compiler, build failed") raise else: comp = Compiler(file=template_file, moduleName=template) # load configuration if it exists conf_fn = DEFAULT_CONFIG if exists(conf_fn): with open(conf_fn, "rt") as config: comp.updateSettingsFromConfigFileObj(config) # and just why can't I configure these? comp.setShBang("") comp.addModuleHeader("pylint: disable=C,W,R,F") outfd = join(self.build_lib, *package.split(".")) outfn = join(outfd, template + ".py") if not exists(outfd): makedirs(outfd) if newer(template_file, outfn): self.announce("compiling %s -> %s" % (template_file, outfd), 2) with open(outfn, "w") as output: output.write(str(comp))
[ "def", "build_template", "(", "self", ",", "template", ",", "template_file", ",", "package", ")", ":", "try", ":", "from", "Cheetah", ".", "Compiler", "import", "Compiler", "except", "ImportError", ":", "self", ".", "announce", "(", "\"unable to import Cheetah.C...
Compile the cheetah template in src into a python file in build
[ "Compile", "the", "cheetah", "template", "in", "src", "into", "a", "python", "file", "in", "build" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/cheetah/setuptools.py#L88-L120
train
30,296
obriencj/python-javatools
javatools/classdiff.py
add_classdiff_optgroup
def add_classdiff_optgroup(parser): """ option group specific to class checking """ g = parser.add_argument_group("Class Checking Options") g.add_argument("--ignore-version-up", action="store_true", default=False) g.add_argument("--ignore-version-down", action="store_true", default=False) g.add_argument("--ignore-platform-up", action="store_true", default=False) g.add_argument("--ignore-platform-down", action="store_true", default=False) g.add_argument("--ignore-absolute-lines", action="store_true", default=False) g.add_argument("--ignore-relative-lines", action="store_true", default=False) g.add_argument("--ignore-deprecated", action="store_true", default=False) g.add_argument("--ignore-added", action="store_true", default=False) g.add_argument("--ignore-pool", action="store_true", default=False) g.add_argument("--ignore-lines", nargs=0, help="ignore relative and absolute line-number changes", action=_opt_cb_ign_lines) g.add_argument("--ignore-platform", nargs=0, help="ignore platform changes", action=_opt_cb_ign_platform) g.add_argument("--ignore-version", nargs=0, help="ignore version changes", action=_opt_cb_ign_version)
python
def add_classdiff_optgroup(parser): """ option group specific to class checking """ g = parser.add_argument_group("Class Checking Options") g.add_argument("--ignore-version-up", action="store_true", default=False) g.add_argument("--ignore-version-down", action="store_true", default=False) g.add_argument("--ignore-platform-up", action="store_true", default=False) g.add_argument("--ignore-platform-down", action="store_true", default=False) g.add_argument("--ignore-absolute-lines", action="store_true", default=False) g.add_argument("--ignore-relative-lines", action="store_true", default=False) g.add_argument("--ignore-deprecated", action="store_true", default=False) g.add_argument("--ignore-added", action="store_true", default=False) g.add_argument("--ignore-pool", action="store_true", default=False) g.add_argument("--ignore-lines", nargs=0, help="ignore relative and absolute line-number changes", action=_opt_cb_ign_lines) g.add_argument("--ignore-platform", nargs=0, help="ignore platform changes", action=_opt_cb_ign_platform) g.add_argument("--ignore-version", nargs=0, help="ignore version changes", action=_opt_cb_ign_version)
[ "def", "add_classdiff_optgroup", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "\"Class Checking Options\"", ")", "g", ".", "add_argument", "(", "\"--ignore-version-up\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "F...
option group specific to class checking
[ "option", "group", "specific", "to", "class", "checking" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/classdiff.py#L981-L1012
train
30,297
obriencj/python-javatools
javatools/classdiff.py
add_general_optgroup
def add_general_optgroup(parser): """ option group for general-use features of all javatool CLIs """ g = parser.add_argument_group("General Options") g.add_argument("-q", "--quiet", dest="silent", action="store_true", default=False) g.add_argument("-v", "--verbose", nargs=0, action=_opt_cb_verbose) g.add_argument("-o", "--output", dest="output", default=None) g.add_argument("-j", "--json", dest="json", action="store_true", default=False) g.add_argument("--show-ignored", action="store_true", default=False) g.add_argument("--show-unchanged", action="store_true", default=False) g.add_argument("--ignore", action=_opt_cb_ignore, help="comma-separated list of ignores")
python
def add_general_optgroup(parser): """ option group for general-use features of all javatool CLIs """ g = parser.add_argument_group("General Options") g.add_argument("-q", "--quiet", dest="silent", action="store_true", default=False) g.add_argument("-v", "--verbose", nargs=0, action=_opt_cb_verbose) g.add_argument("-o", "--output", dest="output", default=None) g.add_argument("-j", "--json", dest="json", action="store_true", default=False) g.add_argument("--show-ignored", action="store_true", default=False) g.add_argument("--show-unchanged", action="store_true", default=False) g.add_argument("--ignore", action=_opt_cb_ignore, help="comma-separated list of ignores")
[ "def", "add_general_optgroup", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "\"General Options\"", ")", "g", ".", "add_argument", "(", "\"-q\"", ",", "\"--quiet\"", ",", "dest", "=", "\"silent\"", ",", "action", "=", "\"store_tr...
option group for general-use features of all javatool CLIs
[ "option", "group", "for", "general", "-", "use", "features", "of", "all", "javatool", "CLIs" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/classdiff.py#L1083-L1104
train
30,298
obriencj/python-javatools
javatools/cheetah/__init__.py
_iter_templates
def _iter_templates(): """ uses reflection to yield the Cheetah templates under this module """ # pylint: disable=W0406 # needed for introspection import javatools.cheetah from Cheetah.Template import Template for _, name, _ in iter_modules(__path__): __import__("javatools.cheetah." + name) found = getattr(getattr(javatools.cheetah, name), name) if issubclass(found, Template): yield found
python
def _iter_templates(): """ uses reflection to yield the Cheetah templates under this module """ # pylint: disable=W0406 # needed for introspection import javatools.cheetah from Cheetah.Template import Template for _, name, _ in iter_modules(__path__): __import__("javatools.cheetah." + name) found = getattr(getattr(javatools.cheetah, name), name) if issubclass(found, Template): yield found
[ "def", "_iter_templates", "(", ")", ":", "# pylint: disable=W0406", "# needed for introspection", "import", "javatools", ".", "cheetah", "from", "Cheetah", ".", "Template", "import", "Template", "for", "_", ",", "name", ",", "_", "in", "iter_modules", "(", "__path...
uses reflection to yield the Cheetah templates under this module
[ "uses", "reflection", "to", "yield", "the", "Cheetah", "templates", "under", "this", "module" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/cheetah/__init__.py#L28-L42
train
30,299