code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if isinstance(haystack, list):
return any([_check_value_recursively(key, val, l) for l in haystack])
elif isinstance(haystack, dict):
if not key in haystack:
return any([_check_value_recursively(key, val, d) for k, d in haystack.items()
if isinstance(d, l... | def _check_value_recursively(key, val, haystack) | Check if there is key _key_ with value _val_ in the given dictionary.
..warning:
This is geared at JSON dictionaries, so some corner cases are ignored,
we assume all iterables are either arrays or dicts | 1.996843 | 1.949722 | 1.024168 |
return [x for x in l if _check_value_recursively(key, val, x)] | def _get_by(key, val, l) | Out of list *l* return all elements that have *key=val*
This comes in handy when you are working with aggregated/bucketed queries | 5.623909 | 6.02774 | 0.933005 |
data = self._es.search(body={
"size": max_query_results,
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"term": {
... | def check_no_proxy_errors(self, **kwargs) | Helper method to determine if the proxies logged any major errors related to the functioning of the proxy itself | 3.631659 | 3.682611 | 0.986164 |
data = self._es.search(body={
"size": max_query_results,
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"exists": {
... | def get_requests_with_errors(self) | Helper method to determine if proxies logged any error related to the requests passing through | 3.913428 | 3.774757 | 1.036736 |
# TODO: Does the proxy support logging of instances so that grouping by instance is possible?
if self.debug:
print 'in check_at_most_requests (%s, %s, %s, %s)' % (source, dest, num_requests, self._id)
# Fetch requests for src->dst
data = self._es.search(body={
... | def check_at_most_requests(self, source, dest, num_requests, **kwargs) | Check that source service sent at most num_request to the dest service
:param source the source service name
:param dest the destination service name
:param num_requests the maximum number of requests that we expect
:return: | 3.467229 | 3.486261 | 0.994541 |
#Remove slow dest
dependencies.remove(slow_dest)
s =str(float(1)/float(rate))
max_spacing = _parse_duration(s+'s')
for dest in dependencies:
data = self._es.search(body={
"size": max_query_results,
"quer... | def check_bulkhead(self, source, dependencies, slow_dest, rate) | Asserts bulkheads by ensuring that the rate of requests to other dests is kept when slow_dest is slow
:param source the source service name
:param dependencies list of dependency names of source
:param slow_dest the name of the dependency that independence is being tested for
:param rate... | 3.565413 | 3.602521 | 0.989699 |
assert isinstance(checklist, dict) and 'checks' in checklist
retval = None
retlist = []
for assertion in checklist['checks']:
retval = self.check_assertion(**assertion)
retlist.append(retval)
if not retval.success and not all:
... | def check_assertions(self, checklist, all=False) | Check a set of assertions
@param all boolean if False, stop at first failure
@return: False if any assertion fails. | 5.433995 | 5.358058 | 1.014172 |
return self.component_scope.instance(lambda: self._create(component_context, overriding_args)) | def create(self, component_context, overriding_args) | Creates a new instance of the component, respecting the scope.
:param component_context: The context to resolve dependencies from.
:param overriding_args: Overriding arguments to use (by name) instead of resolving them.
:return: An instance of the component. | 8.493293 | 8.914295 | 0.952772 |
def isconstructor(object):
return inspect.isfunction(object) and object.__name__ == '__init__'
# find all the dependencies from the constructor
constructors = inspect.getmembers(self.class_type, predicate=isconstructor)
if constructors:
name, func = co... | def _find_constructor(self) | Finds the constructor from the class_type.
:return: The constructor function. | 5.808702 | 4.98167 | 1.166015 |
with self._resolve_lock:
context = _ComponentContext(self)
return context.resolve(component_type, **kwargs) | def resolve(self, component_type, **kwargs) | Resolves an instance of the component type.
:param component_type: The type of the component (e.g. a class).
:param kwargs: Overriding arguments to use (by name) instead of resolving them.
:return: An instance of the component. | 5.13803 | 6.188094 | 0.830309 |
registration = _ConstructorRegistration(class_type, component_scope())
self._register(class_type, registration, register_as) | def register_class(self, class_type, component_scope=scope.InstancePerDependency, register_as=None) | Registers the given class for creation via its constructor.
:param class_type: The class type.
:param component_scope: The scope of the component, defaults to instance per dependency.
:param register_as: The types to register the class as, defaults to the given class_type. | 7.221737 | 8.435761 | 0.856086 |
registration = _CallbackRegistration(callback, component_scope())
self._register(class_type, registration, register_as) | def register_callback(self, class_type, callback, component_scope=scope.InstancePerDependency, register_as=None) | Registers the given class for creation via the given callback.
:param class_type: The class type.
:param callback: The function to call to create/get an instance, of the form fn(component_context)
:param component_scope: The scope of the component, defaults to instance per dependency.
:p... | 6.241558 | 8.482011 | 0.735858 |
registration = _InstanceRegistration(instance)
self._register(class_type, registration, register_as) | def register_instance(self, class_type, instance, register_as=None) | Registers the given instance (already created).
:param class_type: The class type.
:param instance: The instance to register.
:param register_as: The types to register the class as, defaults to the given class_type. | 5.570449 | 8.797391 | 0.633193 |
assert len(irng) == 2, 'specify start, stop indices'
odir = Path(odir).expanduser()
odir.mkdir(parents=True, exist_ok=True)
ri = int(source_url.split('/')[-2][:2])
for i in range(*irng):
fn = f'index-{ri:2d}{i:02d}.fits'
url = f'{source_url}{fn}'
ofn = odir / fn
... | def download(odir: Path, source_url: str, irng: Sequence[int]) | Download star index files.
The default range was useful for my cameras. | 3.591892 | 3.223465 | 1.114295 |
if hasattr(exclude, "search") and exclude.search(link_value):
return True
if exclude == link_value:
return True
return False | def exclude_match(exclude, link_value) | Check excluded value against the link's current value | 3.725287 | 3.273986 | 1.137845 |
last_slash = hyperlink.rfind('/')
return re.sub(r' +|-', ' ', hyperlink[last_slash + 1:]) | def seoify_hyperlink(hyperlink) | Modify a hyperlink to make it SEO-friendly by replacing
hyphens with spaces and trimming multiple spaces.
:param hyperlink: URL to attempt to grab SEO from | 4.799107 | 5.724023 | 0.838415 |
if exclude is None:
exclude = []
if 'href' not in filters:
filters['href'] = True
search = self._soup.findAll('a', **filters)
if reverse:
search.reverse()
links = []
for anchor in search:
build_link = anchor.attr... | def find(self, limit=None, reverse=False, sort=None,
exclude=None, duplicates=True, pretty=False, **filters) | Using filters and sorts, this finds all hyperlinks
on a web page
:param limit: Crop results down to limit specified
:param reverse: Reverse the list of links, useful for before limiting
:param exclude: Remove links from list
:param duplicates: Determines if identical URLs should... | 2.725844 | 2.791487 | 0.976485 |
SETKEY_BINARY = '/usr/sbin/setkey'
fd, filename = tempfile.mkstemp('w')
f = os.fdopen(fd, 'w')
f.write(input)
f.close()
output = subprocess.check_output(['sudo', SETKEY_BINARY, '-f', filename])
os.remove(filename)
return output.decode('utf-8') | def run_setkey(input) | Runs a script through the 'setkey' command that is a user space insterface for PFKEY.
:param input: setkey configuration file contents. | 2.732141 | 2.721395 | 1.003949 |
with fits.open(fn, mode='readonly', memmap=False) as f:
img = f[0].data
yPix, xPix = f[0].shape[-2:]
x, y = np.meshgrid(range(xPix), range(yPix)) # pixel indices to find RA/dec of
xy = np.column_stack((x.ravel(order='C'), y.ravel(order='C')))
radec = wcs.WCS(f[0].hea... | def add_plot(fn: Path, cm, ax, alpha=1) | Astrometry.net makes file ".new" with the image and the WCS SIP 2-D polynomial fit coefficients in the FITS header
We use DECL as "x" and RA as "y".
pcolormesh() is used as it handles arbitrary pixel shapes.
Note that pcolormesh() cannot tolerate NaN in X or Y (NaN in C is OK).
This is handled in https... | 2.704125 | 2.592911 | 1.042892 |
return a * ((((1 + i) ** n) - (((1 + g) ** n)))/(i - g)) | def fvga(a, i, g, n) | This function is for the future value of an annuity
with growth rate. It is the future value of a growing
stream of periodic investments.
a = Periodic Investment (1000)
i = interest rate as decimal (.0675)
g = the growth rate (.05)
n = the number of compound periods (20)
Example: fv(1000, .... | 8.125578 | 5.999132 | 1.354459 |
return [(c-s) * (x/(l*(l+1)/2)) for x in range(l,0,-1)] | def syd(c, s, l) | This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l = expected useful life of the ... | 8.284877 | 6.805561 | 1.217369 |
ad = 0
res = []
for x in range(l):
if x == (l -1):
dexp = (c - s -ad)
else:
dexp = (((c)/l)/(c) * r) * (c - ad)
res.append(dexp)
ad = ad + dexp
return res | def dbal(c, s, r, l) | This accountancy function computes declining balance
depreciation for an asset purchased for cash with
a known life span and salvage value. The depreciation
is returned as a list in Python.
c = historcal cost or price paid
s = the expected salvage proceeds
r = declining percetage rate(ie 1, 1.2... | 7.206662 | 5.876457 | 1.226362 |
pv_nci = 0
for x in range(n):
pv_nci = pv_nci + (nci/((1 + r) ** (x + 1)))
return pv_nci - ico | def npv(ico, nci, r, n) | This capital budgeting function computes the net present
value on a cash flow generating investment.
ico = Initial Capital Outlay
nci = net cash inflows per period
r = discounted rate
n = number of periods
Example: npv(100000, 15000, .03, 10) | 4.26634 | 4.14257 | 1.029878 |
return b' '.join(binascii.hexlify(bytes(x)) for x in zip(src[::4], src[1::4], src[2::4], src[3::4])) | def dump(src) | Returns data in hex format in groups of 4 octets delimited by spaces for debugging purposes. | 3.652657 | 2.815338 | 1.297413 |
global productpage
table = json2html.convert(json = json.dumps(productpage),
table_attributes="class=\"table table-condensed table-bordered table-hover\"")
return render_template('index.html', serviceTable=table) | def index() | Display productpage with normal user and test user buttons | 6.873445 | 6.109325 | 1.125074 |
if start <= end:
step = abs(step)
else:
step = -abs(step)
while start < end:
yield start
start += step | def frange(start, end, step) | A range implementation which can handle floats | 2.769203 | 2.741237 | 1.010202 |
for x in frange(start.real, end.real, step.real):
for y in frange(start.imag, end.imag, step.imag):
yield x + y * 1j | def gridrange(start, end, step) | Generate a grid of complex numbers | 2.421932 | 2.081676 | 1.163453 |
padlen = blocksize - len(data) % blocksize
return bytes(data + bytearray(range(1, padlen)) + bytearray((padlen - 1,))) | def pad(data, blocksize=16) | Pads data to blocksize according to RFC 4303. Pad length field is included in output. | 4.846302 | 4.653725 | 1.041381 |
fitsfn = Path(fitsfn).expanduser()
if fitsfn.suffix == '.fits':
WCSfn = fitsfn.with_suffix('.wcs') # using .wcs will also work but gives a spurious warning
elif fitsfn.suffix == '.wcs':
WCSfn = fitsfn
else:
raise ValueError(f'please convert {fitsfn} to GRAYSCALE .fits e.g. wit... | def fits2radec(fitsfn: Path, solve: bool=False, args: str=None) -> xarray.Dataset | http://docs.astropy.org/en/stable/api/astropy.wcs.WCS.html#astropy.wcs.WCS
naxis=[0,1] is to take x,y axes in case a color photo was input e.g. to astrometry.net cloud solver | 3.426832 | 3.257876 | 1.051861 |
# binpath = Path(find_executable('solve-field')).parent
opts = args.split(' ') if args else []
# %% build command
cmd = ['solve-field', '--overwrite', str(fitsfn)]
cmd += opts
print('\n', ' '.join(cmd), '\n')
# %% execute
ret = subprocess.check_output(cmd, universal_newlines=True)
# so... | def doSolve(fitsfn: Path, args: str=None) | Astrometry.net from at least version 0.67 is OK with Python 3. | 5.726024 | 5.040809 | 1.135934 |
r, g, b = [int(min(255, max(0, component * 256)))
for component in colorsys.hsv_to_rgb(*hsv)]
return "%02x%02x%02x" % (r, g, b) | def to_rgb(hsv) | Converts a color from HSV to a hex RGB.
HSV should be in range 0..1, though hue wraps around. Output is a
hexadecimal color value as used by CSS, HTML and SVG | 2.283065 | 2.795025 | 0.816831 |
global setup_arguments
if os.path.isdir('scripts'):
setup_arguments['scripts'] = [
os.path.join('scripts', f) for f in os.listdir('scripts')
] | def add_scripts_to_package() | Update the "scripts" parameter of the setup_arguments with any scripts
found in the "scripts" directory.
:return: | 3.80812 | 3.065567 | 1.242224 |
global setup_arguments
global METADATA_FILENAME
if not os.path.exists('.git') and os.path.exists(METADATA_FILENAME):
with open(METADATA_FILENAME) as fh:
metadata = json.load(fh)
else:
git = Git(version=setup_arguments['version'])
metadata = {
'versio... | def get_and_update_package_metadata() | Update the package metadata for this package if we are building the package.
:return:metadata - Dictionary of metadata information | 2.861019 | 2.870467 | 0.996709 |
git_rev = len(os.popen('git rev-list HEAD').readlines())
if git_rev != 0:
self.version_list[-1] = '%d' % git_rev
version = '.'.join(self.version_list)
return version | def version(self) | Generate a Unique version value from the git information
:return: | 4.159194 | 4.216275 | 0.986462 |
for item in os.popen('git remote -v'):
split_item = item.strip().split()
if split_item[0] == 'origin' and split_item[-1] == '(push)':
return split_item[1] | def origin(self) | Return the fetch url for the git origin
:return: | 3.716001 | 3.387021 | 1.09713 |
ret = 0
if verbosity == 1:
ret = logging.INFO
elif verbosity >= 2:
ret = logging.DEBUG
return ret | def verbosityToLogLevel(verbosity) | Returns the specfied verbosity level interpreted as a logging level. | 2.601176 | 2.615095 | 0.994677 |
addVariantSetIdArgument(parser)
addReferenceNameArgument(parser)
addCallSetIdsArgument(parser)
addStartArgument(parser)
addEndArgument(parser)
addPageSizeArgument(parser) | def addVariantSearchOptions(parser) | Adds common options to a variant searches command line parser. | 3.416991 | 3.27059 | 1.044763 |
addAnnotationSetIdArgument(parser)
addReferenceNameArgument(parser)
addReferenceIdArgument(parser)
addStartArgument(parser)
addEndArgument(parser)
addEffectsArgument(parser)
addPageSizeArgument(parser) | def addAnnotationsSearchOptions(parser) | Adds common options to a annotation searches command line parser. | 3.634139 | 3.449961 | 1.053386 |
addFeatureSetIdArgument(parser)
addFeaturesReferenceNameArgument(parser)
addStartArgument(parser)
addEndArgument(parser)
addParentFeatureIdArgument(parser)
addFeatureTypesArgument(parser) | def addFeaturesSearchOptions(parser) | Adds common options to a features search command line parser. | 4.321086 | 4.075104 | 1.060362 |
addContinuousSetIdArgument(parser)
addContinuousReferenceNameArgument(parser)
addStartArgument(parser)
addEndArgument(parser) | def addContinuousSearchOptions(parser) | Adds common options to a continuous search command line parser. | 7.054651 | 6.403944 | 1.10161 |
parser.add_argument(
"--phenotype_association_set_id", "-s", default=None,
help="Only return associations from this phenotype_association_set.")
parser.add_argument(
"--feature_ids", "-f", default=None,
help="Only return associations for these features.")
parser.add_argu... | def addGenotypePhenotypeSearchOptions(parser) | Adds options to a g2p searches command line parser. | 2.432567 | 2.485069 | 0.978873 |
parser.add_argument(
"--phenotype_association_set_id", "-s", default=None,
help="Only return phenotypes from this phenotype_association_set.")
parser.add_argument(
"--phenotype_id", "-p", default=None,
help="Only return this phenotype.")
parser.add_argument(
"--d... | def addPhenotypeSearchOptions(parser) | Adds options to a phenotype searches command line parser. | 2.051166 | 2.066433 | 0.992612 |
for gaObject in gaObjects:
if hasattr(gaObject, 'name'):
print(gaObject.id, gaObject.name, sep="\t")
else:
print(gaObject.id, sep="\t") | def _textOutput(self, gaObjects) | Outputs a text summary of the specified protocol objects, one
per line. | 2.550126 | 2.47076 | 1.032122 |
for dataset in self.getAllDatasets():
iterator = self._client.search_variant_sets(
dataset_id=dataset.id)
for variantSet in iterator:
yield variantSet | def getAllVariantSets(self) | Returns all variant sets on the server. | 5.207086 | 5.203857 | 1.00062 |
for dataset in self.getAllDatasets():
iterator = self._client.search_feature_sets(
dataset_id=dataset.id)
for featureSet in iterator:
yield featureSet | def getAllFeatureSets(self) | Returns all feature sets on the server. | 5.458035 | 5.226925 | 1.044215 |
for dataset in self.getAllDatasets():
iterator = self._client.search_continuous_sets(
dataset_id=dataset.id)
for continuousSet in iterator:
yield continuousSet | def getAllContinuousSets(self) | Returns all continuous sets on the server. | 5.809922 | 5.211214 | 1.114888 |
for dataset in self.getAllDatasets():
iterator = self._client.search_read_group_sets(
dataset_id=dataset.id)
for readGroupSet in iterator:
yield readGroupSet | def getAllReadGroupSets(self) | Returns all readgroup sets on the server. | 4.05396 | 4.045408 | 1.002114 |
for dataset in self.getAllDatasets():
iterator = self._client.search_read_group_sets(
dataset_id=dataset.id)
for readGroupSet in iterator:
readGroupSet = self._client.get_read_group_set(
readGroupSet.id)
for rea... | def getAllReadGroups(self) | Get all read groups in a read group set | 2.771275 | 2.660648 | 1.041579 |
for variant in gaObjects:
print(
variant.id, variant.variant_set_id, variant.names,
variant.reference_name, variant.start, variant.end,
variant.reference_bases, variant.alternate_bases,
sep="\t", end="\t")
for key, ... | def _textOutput(self, gaObjects) | Prints out the specified Variant objects in a VCF-like form. | 3.588867 | 3.310716 | 1.084015 |
for variantAnnotation in gaObjects:
print(
variantAnnotation.id, variantAnnotation.variant_id,
variantAnnotation.variant_annotation_set_id,
variantAnnotation.created, sep="\t", end="\t")
for effect in variantAnnotation.transcript_e... | def _textOutput(self, gaObjects) | Prints out the specified Variant objects in a VCF-like form. | 4.109406 | 3.848671 | 1.067747 |
for variantSet in self.getAllVariantSets():
iterator = self._client.search_variant_annotation_sets(
variant_set_id=variantSet.id)
for variantAnnotationSet in iterator:
yield variantAnnotationSet | def getAllAnnotationSets(self) | Returns all variant annotation sets on the server. | 4.367347 | 3.606474 | 1.210974 |
# check if we can get reference id from rg
if referenceId is None:
referenceId = self._referenceId
if referenceId is None:
rg = self._client.get_read_group(
read_group_id=referenceGroupId)
iterator = self._client.search_references(rg.r... | def _run(self, referenceGroupId, referenceId=None) | automatically guess reference id if not passed | 3.46667 | 3.241054 | 1.069612 |
if not self._readGroupIds:
for referenceGroupId in self.getAllReadGroups():
self._run(referenceGroupId)
else:
for referenceGroupId in self._readGroupIds:
self._run(referenceGroupId) | def run(self) | Iterate passed read group ids, or go through all available read groups | 5.212709 | 3.013518 | 1.729776 |
napoleon_sections = ["Short Summary", "Attributes", "Methods", "Warning", "Note", "Parameters", "Other Parameters",
"Keyword Arguments", "Returns", "Yields", "Raises", "Warns", "See Also", "References", "Todo",
"Example", "Examples"]
aliases = {"Args": "P... | def parse_napoleon_doc(doc, style) | Extract the text from the various sections of a numpy-formatted docstring.
Parameters
----------
doc: Union[str, None]
The docstring to parse.
style: str
'google' or 'numpy'
Returns
-------
OrderedDict[str, Union[None,str]]
T... | 2.936727 | 2.809661 | 1.045225 |
doc = []
prnt_only_raises = prnt_sctns["Raises"] and not (prnt_sctns["Returns"] or prnt_sctns["Yields"])
if prnt_only_raises and (child_sctns["Returns"] or child_sctns["Yields"]):
prnt_sctns["Raises"] = None
for key in prnt_sctns:
sect = merge_section(key, prnt_sctns[key], child_s... | def merge_all_sections(prnt_sctns, child_sctns, style) | Merge the doc-sections of the parent's and child's attribute into a single docstring.
Parameters
----------
prnt_sctns: OrderedDict[str, Union[None,str]]
child_sctns: OrderedDict[str, Union[None,str]]
Returns
-------
str
Output docstring of the merge... | 2.369 | 2.471601 | 0.958488 |
style = "numpy"
return merge_all_sections(parse_napoleon_doc(prnt_doc, style), parse_napoleon_doc(child_doc, style), style) | def merge_numpy_napoleon_docs(prnt_doc=None, child_doc=None) | Merge two numpy-style docstrings into a single docstring, according to napoleon docstring sections.
Given the numpy-style docstrings from a parent and child's attributes, merge the docstring
sections such that the child's section is used, wherever present, otherwise the parent's
section is used... | 4.378262 | 5.307576 | 0.824908 |
style = "google"
return merge_all_sections(parse_napoleon_doc(prnt_doc, style), parse_napoleon_doc(child_doc, style), style) | def merge_google_napoleon_docs(prnt_doc=None, child_doc=None) | Merge two google-style docstrings into a single docstring, according to napoleon docstring sections.
Given the google-style docstrings from a parent and child's attributes, merge the docstring
sections such that the child's section is used, wherever present, otherwise the parent's
section is us... | 4.096574 | 5.097831 | 0.803591 |
off, dim = x1.shape
ir = nm.zeros( (off + x2.shape[0],), dtype = nm.int32 )
ir[off:] = off
x1 = nm.round( x1.T / eps ) * eps
x2 = nm.round( x2.T / eps ) * eps
xx = nm.c_[x1, x2]
keys = [xx[ii] for ii in range( dim )]
iis = nm.lexsort( keys = keys )
xs = xx.T[iis]
## impor... | def find_map( x1, x2, eps = 1e-8, allow_double = False, join = True ) | Find a mapping between common coordinates in x1 and x2, such that
x1[cmap[:,0]] == x2[cmap[:,1]] | 2.92169 | 2.885478 | 1.01255 |
n1 = x1.shape[0]
n2 = x2.shape[0]
err = nm.sum( nm.sum( nm.abs( x1[cmap[:,0],:-1] - x2[cmap[:,1],:-1] ) ) )
if abs( err ) > (10.0 * eps):
print 'nonmatching meshes!', err
raise ValueError
mask = nm.ones( (n2,), dtype = nm.int32 )
mask[cmap[:,1]] = 0
# print mask, nm.cum... | def merge_mesh( x1, ngroups1, conns1, x2, ngroups2, conns2, cmap, eps = 1e-8 ) | Merge two meshes in common coordinates found in x1, x2. | 2.87971 | 2.918989 | 0.986544 |
n_nod, dim = coor.shape
cmap = find_map( coor, nm.zeros( (0,dim) ), eps = eps, allow_double = True )
if cmap.size:
output('double nodes in input mesh!')
output('trying to fix...')
while cmap.size:
print cmap.size
# Just like in Variable.equation_mapping... | def fix_double_nodes(coor, ngroups, conns, eps) | Detect and attempt fixing double nodes in a mesh.
The double nodes are nodes having the same coordinates
w.r.t. precision given by `eps`. | 4.198256 | 4.232797 | 0.99184 |
mes = 1e16
for conn in conns:
n_ep = conn.shape[1]
for ir in range( n_ep ):
x1 = coor[conn[:,ir]]
for ic in range( ir + 1, n_ep ):
x2 = coor[conn[:,ic]]
aux = nm.sqrt( nm.sum( (x2 - x1)**2.0, axis = 1 ).min() )
mes = mi... | def get_min_edge_size(coor, conns) | Get the smallest edge length. | 3.374916 | 3.300604 | 1.022515 |
# Sort by x.
ix = nm.argsort( coor[:,0] )
scoor = coor[ix]
mvd = 1e16
# Get mvd in chunks potentially smaller than guess.
n_coor = coor.shape[0]
print n_coor
i0 = i1 = 0
x0 = scoor[i0,0]
while 1:
while ((scoor[i1,0] - x0) < guess) and (i1 < (n_coor - 1)):
... | def get_min_vertex_distance( coor, guess ) | Can miss the minimum, but is enough for our purposes. | 3.605591 | 3.576658 | 1.008089 |
mat_ids = []
for ii, conn in enumerate( conns ):
mat_id = nm.empty( (conn.shape[0],), dtype = nm.int32 )
mat_id.fill( mesh_in.mat_ids[ii][0] )
mat_ids.append( mat_id )
mesh_out = Mesh.from_data( 'merged mesh', coor, ngroups, conns,
mat_ids... | def make_mesh( coor, ngroups, conns, mesh_in ) | Create a mesh reusing mat_ids and descs of mesh_in. | 2.868728 | 2.436665 | 1.177318 |
from itertools import chain
iconn = [[] for ii in xrange( n_nod )]
n_els = [0] * n_nod
for ig, conn in enumerate( conns ):
for iel, row in enumerate( conn ):
for node in row:
iconn[node].extend([ig, iel])
n_els[node] += 1
n_els = nm.array(n_... | def make_inverse_connectivity(conns, n_nod, ret_offsets=True) | For each mesh node referenced in the connectivity conns, make a list of
elements it belongs to. | 2.932906 | 2.939852 | 0.997637 |
aux = nm.concatenate([faces.ravel() for faces in surf_faces])
inod = nm.unique(aux)
n_nod = len( inod )
n_nod_m, dim = mesh_in.coors.shape
aux = nm.arange( n_nod, dtype=nm.int32 )
remap = nm.zeros( (n_nod_m,), nm.int32 )
remap[inod] = aux
mesh ... | def from_surface( surf_faces, mesh_in ) | Create a mesh given a set of surface faces and the original mesh. | 3.313833 | 3.292832 | 1.006378 |
if isinstance(filename, Mesh):
return filename
if io == 'auto':
if filename is None:
output( 'filename or io must be specified!' )
raise ValueError
else:
io = MeshIO.any_from_filename(filename, prefix_dir=prefi... | def from_file(filename=None, io='auto', prefix_dir=None,
omit_facets=False) | Read a mesh from a file.
Parameters
----------
filename : string or function or MeshIO instance or Mesh instance
The name of file to read the mesh from. For convenience, a
mesh creation function or a MeshIO instance or directly a Mesh
instance can be passed i... | 3.938424 | 4.051178 | 0.972168 |
mesh = Mesh( mesh_in.name + "_reg" )
mesh.coors = mesh_in.coors.copy()
mesh.ngroups = mesh_in.ngroups.copy()
mesh.conns = []
mesh.descs = []
mesh.mat_ids = []
if not is_surface:
if region.has_cells():
for ig in region.igs:
... | def from_region(region, mesh_in, save_edges=False, save_faces=False,
localize=False, is_surface=False) | Create a mesh corresponding to a given region. | 3.127001 | 3.10171 | 1.008154 |
if igs is None:
igs = range( len( conns ) )
mesh = Mesh(name)
mesh._set_data(coors = coors,
ngroups = ngroups,
conns = [conns[ig] for ig in igs],
mat_ids = [mat_ids[ig] for ig in igs],
... | def from_data( name, coors, ngroups, conns, mat_ids, descs, igs = None ) | Create a mesh from mesh data. | 2.157259 | 2.052115 | 1.051237 |
return Struct.copy(self, deep=True, name=name) | def copy(self, name=None) | Make a deep copy of self.
Parameters
----------
name : str
Name of the copied mesh. | 12.187679 | 20.406635 | 0.597241 |
self.coors = nm.ascontiguousarray(coors)
if ngroups is None:
self.ngroups = nm.zeros((self.coors.shape[0],), dtype=nm.int32)
else:
self.ngroups = nm.ascontiguousarray(ngroups)
self.conns = [nm.asarray(conn, dtype=nm.int32) for conn in conns]
se... | def _set_data(self, coors, ngroups, conns, mat_ids, descs, nodal_bcs=None) | Set mesh data.
Parameters
----------
coors : array
Coordinates of mesh nodes.
ngroups : array
Node groups.
conns : list of arrays
The array of mesh elements (connectivities) for each element group.
mat_ids : list of arrays
... | 1.857489 | 1.954397 | 0.950415 |
if filename is None:
filename = self.name + '.mesh'
if io is None:
io = self.io
if io is None:
io = 'auto'
if io == 'auto':
io = MeshIO.any_from_filename( filename )
if coors is None:
coors = self.coo... | def write(self, filename=None, io=None,
coors=None, igs=None, out=None, float_format=None, **kwargs) | Write mesh + optional results in `out` to a file.
Parameters
----------
filename : str, optional
The file name. If None, the mesh name is used instead.
io : MeshIO instance or 'auto', optional
Passing 'auto' respects the extension of `filename`.
coors : a... | 3.011899 | 2.863362 | 1.051875 |
cc = self.coors
n_ep_max = self.n_e_ps.max()
coors = nm.empty((self.n_el, n_ep_max, self.dim), dtype=cc.dtype)
for ig, conn in enumerate(self.conns):
i1, i2 = self.el_offsets[ig], self.el_offsets[ig + 1]
coors[i1:i2, :conn.shape[1], :] = cc[conn]
... | def get_element_coors(self, ig=None) | Get the coordinates of vertices elements in group `ig`.
Parameters
----------
ig : int, optional
The element group. If None, the coordinates for all groups
are returned, filled with zeros at places of missing
vertices, i.e. where elements having less then the... | 3.604501 | 3.140695 | 1.147676 |
remap = nm.empty((self.n_nod,), dtype=nm.int32)
remap.fill(-1)
remap[inod] = nm.arange(inod.shape[0], dtype=nm.int32)
self.coors = self.coors[inod]
self.ngroups = self.ngroups[inod]
conns = []
mat_ids = []
for ig, conn in enumerate(self.conns):
... | def localize(self, inod) | Strips nodes not in inod and remaps connectivities.
Omits elements where remap[conn] contains -1... | 2.566569 | 2.414247 | 1.063093 |
if ref_coors is None:
ref_coors = self.coors
if mtx_t.shape[1] > self.coors.shape[1]:
self.coors[:] = nm.dot(ref_coors, mtx_t[:,:-1].T) + mtx_t[:,-1]
else:
self.coors[:] = nm.dot(ref_coors, mtx_t.T) | def transform_coors(self, mtx_t, ref_coors=None) | Transform coordinates of the mesh by the given transformation matrix.
Parameters
----------
mtx_t : array
The transformation matrix `T` (2D array). It is applied
depending on its shape:
- `(dim, dim): x = T * x`
- `(dim, dim + 1): x = T[:, :-1] * x +... | 2.108337 | 2.130023 | 0.989819 |
assert_(0.0 <= eps <= 1.0)
remap = nm.empty((self.n_nod,), dtype=nm.int32)
offset = 0
if return_emap:
rows, cols = [], []
coors = []
ngroups = []
conns = []
mat_ids = []
descs = []
for ig, conn in enumerate(self.conn... | def explode_groups(self, eps, return_emap=False) | Explode the mesh element groups by `eps`, i.e. split group
interface nodes and shrink each group towards its centre by
`eps`.
Parameters
----------
eps : float in `[0.0, 1.0]`
The group shrinking factor.
return_emap : bool, optional
If True, also ... | 2.289326 | 2.22555 | 1.028656 |
job = gevent.spawn(super(GConnection, self)._read_message)
job.join() | def _read_message(self) | 必须启动新的greenlet,否则会有内存泄漏 | 11.941416 | 7.93811 | 1.504315 |
if self.timer:
if force:
# 如果已经存在,那么先要把现在的清空
self.clear()
else:
# 已经存在的话,就返回了
return
def callback_wrapper():
# 必须要确定,这次调用就是这个timer引起的
if self.timer == timer:
# 必须加这句,... | def set(self, interval, callback, repeat=False, force=True) | 添加timer | 7.65305 | 7.289648 | 1.049852 |
if not self.timer:
return
# 不阻塞
try:
self.timer.kill(block=False)
except:
pass
self.timer = None | def clear(self) | 直接把现在的清空 | 6.454551 | 5.716413 | 1.129126 |
el = dict_from_keys_init( descs, list )
for ig, desc in enumerate( descs ):
el[desc].append( ig )
groups = [ii for ii in el.values() if ii]
## print el, groups
descs_out, conns_out, mat_ids_out = [], [], []
for group in groups:
n_ep = conns[group[0]].shape[1]
conn... | def join_conn_groups( conns, descs, mat_ids, concat = False ) | Join groups of the same element type. | 2.502585 | 2.471827 | 1.012443 |
out = {}
for key, val in out_in.iteritems():
if val.data.dtype in complex_types:
rval = copy(val)
rval.data = val.data.real
out['real(%s)' % key] = rval
ival = copy(val)
ival.data = val.data.imag
out['imag(%s)' % key] = ival... | def convert_complex_output(out_in) | Convert complex values in the output dictionary `out_in` to pairs of
real and imaginary parts. | 2.806011 | 2.631493 | 1.066319 |
ok = False
for format in formats:
output( 'guessing %s' % format )
try:
ok = io_table[format].guess( filename )
except AttributeError:
pass
if ok: break
else:
raise NotImplementedError('cannot guess format of a *%s file!' % ext)
retu... | def guess_format( filename, ext, formats, io_table ) | Guess the format of filename, candidates are in formats. | 5.265666 | 4.855896 | 1.084386 |
if not isinstance(filename, basestr):
if isinstance(filename, MeshIO):
return filename
else:
return UserMeshIO(filename)
ext = op.splitext(filename)[1].lower()
try:
format = supported_formats[ext]
except KeyError:
raise ValueError('unsupport... | def any_from_filename(filename, prefix_dir=None) | Create a MeshIO instance according to the kind of `filename`.
Parameters
----------
filename : str, function or MeshIO subclass instance
The name of the mesh file. It can be also a user-supplied function
accepting two arguments: `mesh`, `mode`, where `mesh` is a Mesh
instance and `m... | 4.226822 | 3.842168 | 1.100114 |
ext = op.splitext(filename)[1].lower()
try:
_format = supported_formats[ext]
except KeyError:
_format = None
format = get_default(format, _format)
if format is None:
io = MeshIO.any_from_filename(filename, prefix_dir=prefix_dir)
else:
if not isinstance(for... | def for_format(filename, format=None, writable=False, prefix_dir=None) | Create a MeshIO instance for file `filename` with forced `format`.
Parameters
----------
filename : str
The name of the mesh file.
format : str
One of supported formats. If None,
:func:`MeshIO.any_from_filename()` is called instead.
writable : bool
If True, verify th... | 4.314703 | 4.039325 | 1.068174 |
aux = nm.array([], dtype=nm.float64)
return aux.astype(nm.int32), aux, aux | def read_times(self, filename=None) | Read true time step data from individual time steps.
Returns
-------
steps : array
The time steps.
times : array
The times of the time steps.
nts : array
The normalized times of the time steps, in [0, 1].
Notes
-----
T... | 10.968375 | 7.393379 | 1.48354 |
filename = get_default( filename, self.filename )
out = {}
fd = open( self.filename, 'r' )
while 1:
line = skip_read_line(fd, no_eof=True).split()
if line[0] == 'POINT_DATA':
break
n_nod = int(line[1])
while 1:
... | def read_data( self, step, filename = None ) | Point data only! | 2.632575 | 2.537363 | 1.037524 |
f=open(fnods)
l=[int(x) for x in f.readline().split()]
npoints,dim,nattrib,nbound=l
if dim == 2:
ndapp = [0.0]
else:
ndapp = []
if verbose and up is not None: up.init(npoints)
nodes=[]
for line in f:
if line[0]=... | def getnodes(fnods, up=None, verbose=False) | Reads t.1.nodes, returns a list of nodes.
Example:
>>> self.getnodes("t.1.node", MyBar("nodes:"))
[(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0),
(0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0), (-2.0, 0.0,
-2.0), (-2.0, 2.0, 0.0), (0.0, 2.0, -2.0), (... | 4.006265 | 4.445194 | 0.901258 |
filename = get_default(filename, self.filename)
fd = pt.openFile(filename, mode='r')
steps = sorted(int(name[4:]) for name in fd.root._v_groups.keys()
if name.startswith('step'))
times = []
nts = []
for step in steps:
ts_group ... | def read_times(self, filename=None) | Read true time step data from individual time steps.
Returns
-------
steps : array
The time steps.
times : array
The times of the time steps.
nts : array
The normalized times of the time steps, in [0, 1]. | 2.776033 | 2.736725 | 1.014363 |
l = f.readline().strip()
while l == "" or l[0] == "#": # comment or an empty line
l = f.readline().strip()
return l | def _read_line(self, f) | Reads one non empty line (if it's a comment, it skips it). | 3.667192 | 3.337125 | 1.098908 |
if integer:
dtype=int
else:
dtype=float
l = self._read_line(f)
N = int(l)
rows = []
for i in range(N):
l = self._read_line(f)
row = nm.fromstring(l, sep=" ", dtype=dtype)
rows.append(row)
return ... | def _read_section(self, f, integer=True) | Reads one section from the mesh3d file.
integer ... if True, all numbers are passed to int(), otherwise to
float(), before returning
Some examples how a section can look like:
2
1 2 5 4 7 8 11 10
2 3 6 5 8 9 12 11
or
5
1 2 3 4 1
... | 2.701913 | 2.998466 | 0.901098 |
if cls not in cls._instances:
cls._instances[cls] = cls()
return cls._instances[cls] | def create(cls) | Return always the same instance of the backend class | 3.093402 | 2.533269 | 1.221111 |
try:
v = next(self._iter)
self._iter = itertools.chain((v,), self._iter)
return v
except StopIteration:
return PeekableIterator.Nothing | def peek(self) | Returns PeekableIterator.Nothing when the iterator is exhausted. | 5.053142 | 3.098637 | 1.630763 |
if self.__appended:
return
if self._parent is not None:
self._parent.append_fresh_table(self)
self.__appended = True | def _append_to_parent(self) | Causes this ephemeral table to be persisted on the TOMLFile. | 6.466248 | 4.38528 | 1.474535 |
if self.validate(value, request) is not None:
return None
access_token = AccessToken.objects.for_token(value)
return access_token | def access_token(self, value, request) | Try to get the `AccessToken` associated with the provided token.
*The provided value must pass `BearerHandler.validate()`* | 5.615584 | 4.629185 | 1.213083 |
from django.http import HttpResponseBadRequest
from doac.http import HttpResponseUnauthorized
if not value:
response = HttpResponseBadRequest()
response["WWW-Authenticate"] = request_error_header(CredentialsNotProvided)
return r... | def validate(self, value, request) | Try to get the `AccessToken` associated with the given token.
The return value is determined based n a few things:
- If no token is provided (`value` is None), a 400 response will be returned.
- If an invalid token is provided, a 401 response will be returned.
- If the token provided ... | 4.233028 | 3.26141 | 1.297914 |
# Fetch the token key and secret
if USING_ALLAUTH:
social_app = SocialApp.objects.get_current('twitter')
consumer_key = social_app.key
consumer_secret = social_app.secret
oauth_token = SocialToken.objects.get(account=user, app=social_app).token
... | def fetch_friends(self, user) | fetches the friends from twitter using the
information on django-social-auth models
user is an instance of UserSocialAuth
Returns:
collection of friend objects fetched from facebook | 2.481607 | 2.443711 | 1.015508 |
friends = self.fetch_friends(user)
friend_ids = []
for friend in friends:
friend_ids.append(friend.id)
return friend_ids | def fetch_friend_ids(self, user) | fethces friend id's from twitter
Return:
collection of friend ids | 2.298112 | 2.571508 | 0.893682 |
doc_sections = OrderedDict([("Short Summary", None),
("Deprecation Warning", None),
("Attributes", None),
("Extended Summary", None),
("Parameters", None),
... | def parse_numpy_doc(doc) | Extract the text from the various sections of a numpy-formatted docstring.
Parameters
----------
doc: Union[str, None]
Returns
-------
OrderedDict[str, Union[None,str]]
The extracted numpy-styled docstring sections. | 2.389297 | 2.258154 | 1.058075 |
if prnt_sec is None and child_sec is None:
return None
if key == "Short Summary":
header = ''
else:
header = "\n".join((key, "".join("-" for i in range(len(key))), ""))
if child_sec is None:
body = prnt_sec
else:
body = child_sec
return header + bo... | def merge_section(key, prnt_sec, child_sec) | Synthesize a output numpy docstring section.
Parameters
----------
key: str
The numpy-section being merged.
prnt_sec: Optional[str]
The docstring section from the parent's attribute.
child_sec: Optional[str]
The docstring section from the chil... | 3.897124 | 3.643857 | 1.069505 |
if exists(filename):
with file(filename, 'r') as fp:
for line in fp:
try:
data = json.loads(line)
except:
continue
matches = True
for key, value in pattern.iteritems():
... | def find_lines(filename, **pattern) | Find a line (JSON-formatted) in the given file where
all keys in `pattern` are present as keys in the line's
JSON, and where their values equal the corresponding
values in `pattern`. Additional keys in the line are
ignored. If no matching line is found, or if the
file does not exist, return None. | 2.600649 | 2.473016 | 1.05161 |
global lock
data = json.dumps(line, separators=(',', ':')) + '\n'
with lock:
with file(filename, 'a') as fp:
fp.seek(0, SEEK_END)
fp.write(data) | def append_line(filename, **line) | Safely (i.e. with locking) append a line to
the given file, serialized as JSON. | 3.494895 | 3.115195 | 1.121886 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.