_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q273600
generate_sigproc_header
test
def generate_sigproc_header(f): """ Generate a serialzed sigproc header which can be written to disk. Args: f (Filterbank object): Filterbank object for which to generate header Returns: header_str (str): Serialized string corresponding to header """ header_string = b'' header...
python
{ "resource": "" }
q273601
to_sigproc_angle
test
def to_sigproc_angle(angle_val): """ Convert an astropy.Angle to the ridiculous sigproc angle format string. """ x = str(angle_val) if '.' in x: if 'h' in x: d, m, s, ss = int(x[0:x.index('h')]), int(x[x.index('h')+1:x.index('m')]), \ int(x[x.index('m')+1:x.index('.'...
python
{ "resource": "" }
q273602
calc_n_ints_in_file
test
def calc_n_ints_in_file(filename): """ Calculate number of integrations in a given file """ # Load binary data h = read_header(filename) n_bytes = int(h[b'nbits'] / 8) n_chans = h[b'nchans'] n_ifs = h[b'nifs'] idx_data = len_header(filename) f = open(filename, 'rb') f.seek(idx_da...
python
{ "resource": "" }
q273603
Traceback.to_dict
test
def to_dict(self): """Convert a Traceback into a dictionary representation""" if self.tb_next is None: tb_next = None else: tb_next = self.tb_next.to_dict() code = { 'co_filename': self.tb_frame.f_code.co_filename, 'co_name': self.tb_frame...
python
{ "resource": "" }
q273604
make_rr_subparser
test
def make_rr_subparser(subparsers, rec_type, args_and_types): """ Make a subparser for a given type of DNS record """ sp = subparsers.add_parser(rec_type) sp.add_argument("name", type=str) sp.add_argument("ttl", type=int, nargs='?') sp.add_argument(rec_type, type=str) for my_spec in arg...
python
{ "resource": "" }
q273605
make_parser
test
def make_parser(): """ Make an ArgumentParser that accepts DNS RRs """ line_parser = ZonefileLineParser() subparsers = line_parser.add_subparsers() # parse $ORIGIN sp = subparsers.add_parser("$ORIGIN") sp.add_argument("$ORIGIN", type=str) # parse $TTL sp = subparsers.add_parser...
python
{ "resource": "" }
q273606
remove_comments
test
def remove_comments(text): """ Remove comments from a zonefile """ ret = [] lines = text.split("\n") for line in lines: if len(line) == 0: continue line = serialize(tokenize_line(line)) ret.append(line) return "\n".join(ret)
python
{ "resource": "" }
q273607
add_default_name
test
def add_default_name(text): """ Go through each line of the text and ensure that a name is defined. Use '@' if there is none. """ global SUPPORTED_RECORDS lines = text.split("\n") ret = [] for line in lines: tokens = tokenize_line(line) if len(tokens) == 0: ...
python
{ "resource": "" }
q273608
parse_line
test
def parse_line(parser, record_token, parsed_records): """ Given the parser, capitalized list of a line's tokens, and the current set of records parsed so far, parse it into a dictionary. Return the new set of parsed records. Raise an exception on error. """ global SUPPORTED_RECORDS l...
python
{ "resource": "" }
q273609
parse_lines
test
def parse_lines(text, ignore_invalid=False): """ Parse a zonefile into a dict. @text must be flattened--each record must be on one line. Also, all comments must be removed. """ json_zone_file = defaultdict(list) record_lines = text.split("\n") parser = make_parser() for record_line ...
python
{ "resource": "" }
q273610
parse_zone_file
test
def parse_zone_file(text, ignore_invalid=False): """ Parse a zonefile into a dict """ text = remove_comments(text) text = flatten(text) text = remove_class(text) text = add_default_name(text) json_zone_file = parse_lines(text, ignore_invalid=ignore_invalid) return json_zone_file
python
{ "resource": "" }
q273611
quote_field
test
def quote_field(data, field): """ Quote a field in a list of DNS records. Return the new data records. """ if data is None: return None data_dup = copy.deepcopy(data) for i in xrange(0, len(data_dup)): data_dup[i][field] = '"%s"' % data_dup[i][field] data_dup[i][fie...
python
{ "resource": "" }
q273612
parse_schema_string
test
def parse_schema_string(schema_string): """ Load and return a PySchema class from an avsc string """ if isinstance(schema_string, str): schema_string = schema_string.decode("utf8") schema_struct = json.loads(schema_string) return AvroSchemaParser().parse_schema_struct(schema_struct)
python
{ "resource": "" }
q273613
to_python_package
test
def to_python_package(classes, target_folder, parent_package=None, indent=DEFAULT_INDENT): ''' This function can be used to build a python package representation of pyschema classes. One module is created per namespace in a package matching the namespace hierarchy. Args: classes: A collection o...
python
{ "resource": "" }
q273614
_class_source
test
def _class_source(schema, indent): """Generate Python source code for one specific class Doesn't include or take into account any dependencies between record types """ def_pattern = ( "class {class_name}(pyschema.Record):\n" "{indent}# WARNING: This class was generated by pyschema.to_p...
python
{ "resource": "" }
q273615
no_auto_store
test
def no_auto_store(): """ Temporarily disable automatic registration of records in the auto_store Decorator factory. This is _NOT_ thread safe >>> @no_auto_store() ... class BarRecord(Record): ... pass >>> BarRecord in auto_store False """ original_auto_register_value = PySchem...
python
{ "resource": "" }
q273616
to_json_compatible
test
def to_json_compatible(record): "Dump record in json-encodable object format" d = {} for fname, f in record._fields.iteritems(): val = getattr(record, fname) if val is not None: d[fname] = f.dump(val) return d
python
{ "resource": "" }
q273617
load_json_dct
test
def load_json_dct( dct, record_store=None, schema=None, loader=from_json_compatible ): """ Create a Record instance from a json-compatible dictionary The dictionary values should have types that are json compatible, as if just loaded from a json serialized record string. ...
python
{ "resource": "" }
q273618
loads
test
def loads( s, record_store=None, schema=None, loader=from_json_compatible, record_class=None # deprecated in favor of schema ): """ Create a Record instance from a json serialized dictionary :param s: String with a json-serialized dictionary :param record_s...
python
{ "resource": "" }
q273619
SchemaStore.add_record
test
def add_record(self, schema, _bump_stack_level=False): """ Add record class to record store for retrieval at record load time. Can be used as a class decorator """ full_name = get_full_name(schema) has_namespace = '.' in full_name self._force_add(full_name, schema, _...
python
{ "resource": "" }
q273620
SchemaStore.get
test
def get(self, record_name): """ Will return a matching record or raise KeyError is no record is found. If the record name is a full name we will first check for a record matching the full name. If no such record is found any record matching the last part of the full name (without the na...
python
{ "resource": "" }
q273621
Field.repr_vars
test
def repr_vars(self): """Return a dictionary the field definition Should contain all fields that are required for the definition of this field in a pyschema class""" d = OrderedDict() d["nullable"] = repr(self.nullable) d["default"] = repr(self.default) if self.descriptio...
python
{ "resource": "" }
q273622
Field.mixin
test
def mixin(cls, mixin_cls): """Decorator for mixing in additional functionality into field type Example: >>> @Integer.mixin ... class IntegerPostgresExtensions: ... postgres_type = 'INT' ... ... def postgres_dump(self, obj): ... self.dump(...
python
{ "resource": "" }
q273623
PySchema.from_class
test
def from_class(metacls, cls, auto_store=True): """Create proper PySchema class from cls Any methods and attributes will be transferred to the new object """ if auto_store: def wrap(cls): return cls else: wrap = no_auto_store() ...
python
{ "resource": "" }
q273624
get_schema_dict
test
def get_schema_dict(record, state=None): """Return a python dict representing the jsonschema of a record Any references to sub-schemas will be URI fragments that won't be resolvable without a root schema, available from get_root_schema_dict. """ state = state or SchemaGeneratorState() schema = ...
python
{ "resource": "" }
q273625
get_root_schema_dict
test
def get_root_schema_dict(record): """Return a root jsonschema for a given record A root schema includes the $schema attribute and all sub-record schemas and definitions. """ state = SchemaGeneratorState() schema = get_schema_dict(record, state) del state.record_schemas[record._schema_name] ...
python
{ "resource": "" }
q273626
mr_reader
test
def mr_reader(job, input_stream, loads=core.loads): """ Converts a file object with json serialised pyschema records to a stream of pyschema objects Can be used as job.reader in luigi.hadoop.JobTask """ for line in input_stream: yield loads(line),
python
{ "resource": "" }
q273627
mr_writer
test
def mr_writer(job, outputs, output_stream, stderr=sys.stderr, dumps=core.dumps): """ Writes a stream of json serialised pyschema Records to a file object Can be used as job.writer in luigi.hadoop.JobTask """ for output in outputs: try: print >> output_stream, dumps(out...
python
{ "resource": "" }
q273628
ordereddict_push_front
test
def ordereddict_push_front(dct, key, value): """Set a value at the front of an OrderedDict The original dict isn't modified, instead a copy is returned """ d = OrderedDict() d[key] = value d.update(dct) return d
python
{ "resource": "" }
q273629
Collection.query_string
test
def query_string(self, **params): """Specify query string to use with the collection. Returns: :py:class:`SearchResult` """ return SearchResult(self, self._api.get(self._href, **params))
python
{ "resource": "" }
q273630
Collection.raw_filter
test
def raw_filter(self, filters): """Sends all filters to the API. No fancy, just a wrapper. Any advanced functionality shall be implemented as another method. Args: filters: List of filters (strings) Returns: :py:class:`SearchResult` """ return SearchResult(s...
python
{ "resource": "" }
q273631
Collection.all_include_attributes
test
def all_include_attributes(self, attributes): """Returns all entities present in the collection with ``attributes`` included.""" self.reload(expand=True, attributes=attributes) entities = [Entity(self, r, attributes=attributes) for r in self._resources] self.reload() return entit...
python
{ "resource": "" }
q273632
Action._get_entity_from_href
test
def _get_entity_from_href(self, result): """Returns entity in correct collection. If the "href" value in result doesn't match the current collection, try to find the collection that the "href" refers to. """ href_result = result['href'] if self.collection._href.startswi...
python
{ "resource": "" }
q273633
give_another_quote
test
def give_another_quote(q): """When you pass a quote character, returns you an another one if possible""" for qc in QUOTES: if qc != q: return qc else: raise ValueError(u'Could not find a different quote for {}'.format(q))
python
{ "resource": "" }
q273634
escape_filter
test
def escape_filter(o): """Tries to escape the values that are passed to filter as correctly as possible. No standard way is followed, but at least it is simple. """ if o is None: return u'NULL' if isinstance(o, int): return str(o) if not isinstance(o, six.string_types): r...
python
{ "resource": "" }
q273635
elementaryRotationMatrix
test
def elementaryRotationMatrix(axis, rotationAngle): """ Construct an elementary rotation matrix describing a rotation around the x, y, or z-axis. Parameters ---------- axis - Axis around which to rotate ("x", "y", or "z") rotationAngle - the rotation angle in radians Returns ------- The ro...
python
{ "resource": "" }
q273636
construct_covariance_matrix
test
def construct_covariance_matrix(cvec, parallax, radial_velocity, radial_velocity_error): """ Take the astrometric parameter standard uncertainties and the uncertainty correlations as quoted in the Gaia catalogue and construct the covariance matrix. Parameters ---------- cvec : array_like ...
python
{ "resource": "" }
q273637
vradErrorSkyAvg
test
def vradErrorSkyAvg(vmag, spt): """ Calculate radial velocity error from V and the spectral type. The value of the error is an average over the sky. Parameters ---------- vmag - Value of V-band magnitude. spt - String representing the spectral type of the star. Returns ------- The radial veloci...
python
{ "resource": "" }
q273638
calcParallaxError
test
def calcParallaxError(args): """ Calculate the parallax error for the given input source magnitude and colour. :argument args: command line arguments """ gmag=float(args['gmag']) vmini=float(args['vmini']) sigmaPar=parallaxErrorSkyAvg(gmag, vmini) gminv=gminvFromVmini(vmini) print("G = {0}".format(gm...
python
{ "resource": "" }
q273639
gMagnitudeError
test
def gMagnitudeError(G): """ Calculate the single-field-of-view-transit photometric standard error in the G band as a function of G. A 20% margin is included. Parameters ---------- G - Value(s) of G-band magnitude. Returns ------- The G band photometric standard error in units of magnitude. "...
python
{ "resource": "" }
q273640
gMagnitudeErrorEoM
test
def gMagnitudeErrorEoM(G, nobs=70): """ Calculate the end of mission photometric standard error in the G band as a function of G. A 20% margin is included. Parameters ---------- G - Value(s) of G-band magnitude. Keywords -------- nobs - Number of observations collected (default 70). Return...
python
{ "resource": "" }
q273641
makePlot
test
def makePlot(args): """ Make the plot with photometry performance predictions. :argument args: command line arguments """ gmag=np.linspace(3.0,20.0,171) vmini = args['vmini'] vmag=gmag-gminvFromVmini(vmini) if args['eom']: sigmaG = gMagnitudeErrorEoM(gmag) sigmaGBp = bpMagnitudeError...
python
{ "resource": "" }
q273642
averageNumberOfTransits
test
def averageNumberOfTransits(beta): """ Returns the number of transits across the Gaia focal plane averaged over ecliptic longitude. Parameters ---------- beta - Value(s) of the Ecliptic latitude. Returns ------- Average number of transits for the input values of beta. """ indices = array(floor(a...
python
{ "resource": "" }
q273643
angularDistance
test
def angularDistance(phi1, theta1, phi2, theta2): """ Calculate the angular distance between pairs of sky coordinates. Parameters ---------- phi1 : float Longitude of first coordinate (radians). theta1 : float Latitude of first coordinate (radians). phi2 : float Long...
python
{ "resource": "" }
q273644
CoordinateTransformation.transformCartesianCoordinates
test
def transformCartesianCoordinates(self, x, y, z): """ Rotates Cartesian coordinates from one reference system to another using the rotation matrix with which the class was initialized. The inputs can be scalars or 1-dimensional numpy arrays. Parameters ---------- x - V...
python
{ "resource": "" }
q273645
CoordinateTransformation.transformSkyCoordinates
test
def transformSkyCoordinates(self, phi, theta): """ Converts sky coordinates from one reference system to another, making use of the rotation matrix with which the class was initialized. Inputs can be scalars or 1-dimensional numpy arrays. Parameters ---------- phi - V...
python
{ "resource": "" }
q273646
CoordinateTransformation.transformCovarianceMatrix
test
def transformCovarianceMatrix(self, phi, theta, covmat): """ Transform the astrometric covariance matrix to its representation in the new coordinate system. Parameters ---------- phi - The longitude-like angle of the position of the source (radians). theta - T...
python
{ "resource": "" }
q273647
errorScalingFactor
test
def errorScalingFactor(observable, beta): """ Look up the numerical factors to apply to the sky averaged parallax error in order to obtain error values for a given astrometric parameter, taking the Ecliptic latitude and the number of transits into account. Parameters ---------- observable - Name of astr...
python
{ "resource": "" }
q273648
makePlot
test
def makePlot(pdf=False, png=False): """ Plot relative parallax errors as a function of distance for stars of a given spectral type. Parameters ---------- args - command line arguments """ logdistancekpc = np.linspace(-1,np.log10(20.0),100) sptVabsAndVmini=OrderedDict([('K0V',(5.58,0.87)), ('G5V',(4.78...
python
{ "resource": "" }
q273649
makePlot
test
def makePlot(args): """ Make the plot with radial velocity performance predictions. :argument args: command line arguments """ gRvs=np.linspace(5.7,16.1,101) spts=['B0V', 'B5V', 'A0V', 'A5V', 'F0V', 'G0V', 'G5V', 'K0V', 'K1IIIMP', 'K4V', 'K1III'] fig=plt.figure(figsize=(10,6.5)) deltaHue = 24...
python
{ "resource": "" }
q273650
either
test
def either(*funcs): """ A utility function for selecting the first non-null query. Parameters: funcs: One or more functions Returns: A function that, when called with a :class:`Node`, will pass the input to each `func`, and return the first non-Falsey result. Examples...
python
{ "resource": "" }
q273651
_helpful_failure
test
def _helpful_failure(method): """ Decorator for eval_ that prints a helpful error message if an exception is generated in a Q expression """ @wraps(method) def wrapper(self, val): try: return method(self, val) except: exc_cls, inst, tb = sys.exc_info() ...
python
{ "resource": "" }
q273652
_uniquote
test
def _uniquote(value): """ Convert to unicode, and add quotes if initially a string """ if isinstance(value, six.binary_type): try: value = value.decode('utf-8') except UnicodeDecodeError: # Not utf-8. Show the repr value = six.text_type(_dequote(repr(value))) # ...
python
{ "resource": "" }
q273653
Collection.each
test
def each(self, *funcs): """ Call `func` on each element in the collection. If multiple functions are provided, each item in the output will be a tuple of each func(item) in self. Returns a new Collection. Example: >>> col = Collection([Scalar(1), S...
python
{ "resource": "" }
q273654
Collection.exclude
test
def exclude(self, func=None): """ Return a new Collection excluding some items Parameters: func : function(Node) -> Scalar A function that, when called on each item in the collection, returns a boolean-like value. If no function is p...
python
{ "resource": "" }
q273655
Collection.filter
test
def filter(self, func=None): """ Return a new Collection with some items removed. Parameters: func : function(Node) -> Scalar A function that, when called on each item in the collection, returns a boolean-like value. If no function i...
python
{ "resource": "" }
q273656
Collection.takewhile
test
def takewhile(self, func=None): """ Return a new Collection with the last few items removed. Parameters: func : function(Node) -> Node Returns: A new Collection, discarding all items at and after the first item where bool(func(item)) == False ...
python
{ "resource": "" }
q273657
Collection.dropwhile
test
def dropwhile(self, func=None): """ Return a new Collection with the first few items removed. Parameters: func : function(Node) -> Node Returns: A new Collection, discarding all items before the first item where bool(func(item)) == True """...
python
{ "resource": "" }
q273658
Collection.zip
test
def zip(self, *others): """ Zip the items of this collection with one or more other sequences, and wrap the result. Unlike Python's zip, all sequences must be the same length. Parameters: others: One or more iterables or Collections Returns: A...
python
{ "resource": "" }
q273659
Node.find
test
def find(self, *args, **kwargs): """ Find a single Node among this Node's descendants. Returns :class:`NullNode` if nothing matches. This inputs to this function follow the same semantics as BeautifulSoup. See http://bit.ly/bs4doc for more info. Examples: - n...
python
{ "resource": "" }
q273660
serach_path
test
def serach_path(): """Return potential locations of IACA installation.""" operating_system = get_os() # 1st choice: in ~/.kerncraft/iaca-{} # 2nd choice: in package directory / iaca-{} return [os.path.expanduser("~/.kerncraft/iaca/{}/".format(operating_system)), os.path.abspath(os.path.d...
python
{ "resource": "" }
q273661
group_iterator
test
def group_iterator(group): """ Yild all groups of simple regex-like expression. The only special character is a dash (-), which take the preceding and the following chars to compute a range. If the range is non-sensical (e.g., b-a) it will be empty Example: >>> list(group_iterator('a-f')) ...
python
{ "resource": "" }
q273662
register_options
test
def register_options(regdescr): """ Very reduced regular expressions for describing a group of registers. Only groups in square bracktes and unions with pipes (|) are supported. Examples: >>> list(register_options('PMC[0-3]')) ['PMC0', 'PMC1', 'PMC2', 'PMC3'] >>> list(register_options('MBO...
python
{ "resource": "" }
q273663
eventstr
test
def eventstr(event_tuple=None, event=None, register=None, parameters=None): """ Return a LIKWID event string from an event tuple or keyword arguments. *event_tuple* may have two or three arguments: (event, register) or (event, register, parameters) Keyword arguments will be overwritten by *event_t...
python
{ "resource": "" }
q273664
build_minimal_runs
test
def build_minimal_runs(events): """Compile list of minimal runs for given events.""" # Eliminate multiples events = [e for i, e in enumerate(events) if events.index(e) == i] # Build list of runs per register group scheduled_runs = {} scheduled_events = [] cur_run = 0 while len(scheduled...
python
{ "resource": "" }
q273665
Roofline.report
test
def report(self, output_file=sys.stdout): """Report analysis outcome in human readable form.""" max_perf = self.results['max_perf'] if self._args and self._args.verbose >= 3: print('{}'.format(pformat(self.results)), file=output_file) if self._args and self._args.verbose >=...
python
{ "resource": "" }
q273666
RooflineIACA.report
test
def report(self, output_file=sys.stdout): """Print human readable report of model.""" cpu_perf = self.results['cpu bottleneck']['performance throughput'] if self.verbose >= 3: print('{}'.format(pformat(self.results)), file=output_file) if self.verbose >= 1: prin...
python
{ "resource": "" }
q273667
LC.report
test
def report(self, output_file=sys.stdout): """Report generated model in human readable form.""" if self._args and self._args.verbose > 2: pprint(self.results) for dimension, lc_info in self.results['dimensions'].items(): print("{}D layer condition:".format(dimension), fil...
python
{ "resource": "" }
q273668
clean_code
test
def clean_code(code, comments=True, macros=False, pragmas=False): """ Naive comment and macro striping from source code :param comments: If True, all comments are stripped from code :param macros: If True, all macros are stripped from code :param pragmas: If True, all pragmas are stripped from code...
python
{ "resource": "" }
q273669
round_to_next
test
def round_to_next(x, base): """Round float to next multiple of base.""" # Based on: http://stackoverflow.com/a/2272174 return int(base * math.ceil(float(x)/base))
python
{ "resource": "" }
q273670
blocking
test
def blocking(indices, block_size, initial_boundary=0): """ Split list of integers into blocks of block_size and return block indices. First block element will be located at initial_boundary (default 0). >>> blocking([0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 8) [0,-1] >>> blocking([0], 8) [0...
python
{ "resource": "" }
q273671
ECMData.calculate_cache_access
test
def calculate_cache_access(self): """Dispatch to cache predictor to get cache stats.""" self.results.update({ 'cycles': [], # will be filled by caclculate_cycles() 'misses': self.predictor.get_misses(), 'hits': self.predictor.get_h...
python
{ "resource": "" }
q273672
ECMData.calculate_cycles
test
def calculate_cycles(self): """ Calculate performance model cycles from cache stats. calculate_cache_access() needs to have been execute before. """ element_size = self.kernel.datatypes_size[self.kernel.datatype] elements_per_cacheline = float(self.machine['cacheline siz...
python
{ "resource": "" }
q273673
ECMData.analyze
test
def analyze(self): """Run complete anaylysis and return results.""" self.calculate_cache_access() self.calculate_cycles() self.results['flops per iteration'] = sum(self.kernel._flops.values()) return self.results
python
{ "resource": "" }
q273674
ECMCPU.analyze
test
def analyze(self): """ Run complete analysis and return results. """ try: incore_analysis, asm_block = self.kernel.iaca_analysis( micro_architecture=self.machine['micro-architecture'], asm_block=self.asm_block, pointer_incremen...
python
{ "resource": "" }
q273675
strip_and_uncomment
test
def strip_and_uncomment(asm_lines): """Strip whitespaces and comments from asm lines.""" asm_stripped = [] for line in asm_lines: # Strip comments and whitespaces asm_stripped.append(line.split('#')[0].strip()) return asm_stripped
python
{ "resource": "" }
q273676
strip_unreferenced_labels
test
def strip_unreferenced_labels(asm_lines): """Strip all labels, which are never referenced.""" asm_stripped = [] for line in asm_lines: if re.match(r'^\S+:', line): # Found label label = line[0:line.find(':')] # Search for references to current label if...
python
{ "resource": "" }
q273677
select_best_block
test
def select_best_block(blocks): """Return best block selected based on simple heuristic.""" # TODO make this cleverer with more stats if not blocks: raise ValueError("No suitable blocks were found in assembly.") best_block = max(blocks, key=lambda b: b[1]['packed_instr']) if best_block[1]['pa...
python
{ "resource": "" }
q273678
userselect_increment
test
def userselect_increment(block): """Let user interactively select byte increment.""" print("Selected block:") print('\n ' + ('\n '.join(block['lines']))) print() increment = None while increment is None: increment = input("Choose store pointer increment (number of bytes): ") ...
python
{ "resource": "" }
q273679
userselect_block
test
def userselect_block(blocks, default=None, debug=False): """Let user interactively select block.""" print("Blocks found in assembly file:") print(" block | OPs | pck. | AVX || Registers | ZMM | YMM | XMM | GP ||ptr.inc|\n" "----------------+-----+------+-----++--------...
python
{ "resource": "" }
q273680
insert_markers
test
def insert_markers(asm_lines, start_line, end_line): """Insert IACA marker into list of ASM instructions at given indices.""" asm_lines = (asm_lines[:start_line] + START_MARKER + asm_lines[start_line:end_line + 1] + END_MARKER + asm_lines[end_line + 1:]) return asm_lines
python
{ "resource": "" }
q273681
iaca_instrumentation
test
def iaca_instrumentation(input_file, output_file, block_selection='auto', pointer_increment='auto_with_manual_fallback', debug=False): """ Add IACA markers to an assembly file. If instrumentation fails because loop increment could n...
python
{ "resource": "" }
q273682
main
test
def main(): """Execute command line interface.""" parser = argparse.ArgumentParser( description='Find and analyze basic loop blocks and mark for IACA.', epilog='For help, examples, documentation and bug reports go to:\nhttps://github.com' '/RRZE-HPC/kerncraft\nLicense: AGPLv3') ...
python
{ "resource": "" }
q273683
simulate
test
def simulate(kernel, model, define_dict, blocking_constant, blocking_length): """Setup and execute model with given blocking length""" kernel.clear_state() # Add constants from define arguments for k, v in define_dict.items(): kernel.set_constant(k, v) kernel.set_constant(blocking_constant...
python
{ "resource": "" }
q273684
space
test
def space(start, stop, num, endpoint=True, log=False, base=10): """ Return list of evenly spaced integers over an interval. Numbers can either be evenly distributed in a linear space (if *log* is False) or in a log space (if *log* is True). If *log* is True, base is used to define the log space basis. ...
python
{ "resource": "" }
q273685
get_last_modified_datetime
test
def get_last_modified_datetime(dir_path=os.path.dirname(__file__)): """Return datetime object of latest change in kerncraft module directory.""" max_mtime = 0 for root, dirs, files in os.walk(dir_path): for f in files: p = os.path.join(root, f) try: max_mtime ...
python
{ "resource": "" }
q273686
check_arguments
test
def check_arguments(args, parser): """Check arguments passed by user that are not checked by argparse itself.""" if args.asm_block not in ['auto', 'manual']: try: args.asm_block = int(args.asm_block) except ValueError: parser.error('--asm-block can only be "auto", "manual...
python
{ "resource": "" }
q273687
main
test
def main(): """Initialize and run command line interface.""" # Create and populate parser parser = create_parser() # Parse given arguments args = parser.parse_args() # Checking arguments check_arguments(args, parser) # BUSINESS LOGIC IS FOLLOWING run(parser, args)
python
{ "resource": "" }
q273688
main
test
def main(): """Comand line interface of picklemerge.""" parser = argparse.ArgumentParser( description='Recursively merges two or more pickle files. Only supports pickles consisting ' 'of a single dictionary object.') parser.add_argument('destination', type=argparse.FileType('r+b'), ...
python
{ "resource": "" }
q273689
symbol_pos_int
test
def symbol_pos_int(*args, **kwargs): """Create a sympy.Symbol with positive and integer assumptions.""" kwargs.update({'positive': True, 'integer': True}) return sympy.Symbol(*args, **kwargs)
python
{ "resource": "" }
q273690
transform_multidim_to_1d_decl
test
def transform_multidim_to_1d_decl(decl): """ Transform ast of multidimensional declaration to a single dimension declaration. In-place operation! Returns name and dimensions of array (to be used with transform_multidim_to_1d_ref()) """ dims = [] type_ = decl.type while type(type_) is c...
python
{ "resource": "" }
q273691
transform_multidim_to_1d_ref
test
def transform_multidim_to_1d_ref(aref, dimension_dict): """ Transform ast of multidimensional reference to a single dimension reference. In-place operation! """ dims = [] name = aref while type(name) is c_ast.ArrayRef: dims.append(name.subscript) name = name.name subscr...
python
{ "resource": "" }
q273692
find_node_type
test
def find_node_type(ast, node_type): """Return list of array references in AST.""" if type(ast) is node_type: return [ast] elif type(ast) is list: return reduce(operator.add, list(map(lambda a: find_node_type(a, node_type), ast)), []) elif ast is None: return [] else: ...
python
{ "resource": "" }
q273693
force_iterable
test
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
python
{ "resource": "" }
q273694
Kernel.check
test
def check(self): """Check that information about kernel makes sens and is valid.""" datatypes = [v[0] for v in self.variables.values()] assert len(set(datatypes)) <= 1, 'mixing of datatypes within a kernel is not supported.'
python
{ "resource": "" }
q273695
Kernel.set_constant
test
def set_constant(self, name, value): """ Set constant of name to value. :param name: may be a str or a sympy.Symbol :param value: must be an int """ assert isinstance(name, str) or isinstance(name, sympy.Symbol), \ "constant name needs to be of type str, unic...
python
{ "resource": "" }
q273696
Kernel.subs_consts
test
def subs_consts(self, expr): """Substitute constants in expression unless it is already a number.""" if isinstance(expr, numbers.Number): return expr else: return expr.subs(self.constants)
python
{ "resource": "" }
q273697
Kernel.array_sizes
test
def array_sizes(self, in_bytes=False, subs_consts=False): """ Return a dictionary with all arrays sizes. :param in_bytes: If True, output will be in bytes, not element counts. :param subs_consts: If True, output will be numbers and not symbolic. Scalar variables are ignored. ...
python
{ "resource": "" }
q273698
Kernel._calculate_relative_offset
test
def _calculate_relative_offset(self, name, access_dimensions): """ Return the offset from the iteration center in number of elements. The order of indices used in access is preserved. """ # TODO to be replaced with compile_global_offsets offset = 0 base_dims = se...
python
{ "resource": "" }
q273699
Kernel._remove_duplicate_accesses
test
def _remove_duplicate_accesses(self): """ Remove duplicate source and destination accesses """ self.destinations = {var_name: set(acs) for var_name, acs in self.destinations.items()} self.sources = {var_name: set(acs) for var_name, acs in self.sources.items()}
python
{ "resource": "" }