_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q242400
JsonFile.write_file
train
def write_file(self, content, filepath=None, filename=None, indent=None, keys_to_write=None): ''' Write a Python dictionary as JSON to a file. :param content: Dictionary of key-value pairs to save to a file :param filepath: Path where the file is to be created :param filename: N...
python
{ "resource": "" }
q242401
JsonFile.read_file
train
def read_file(self, filepath=None, filename=None): """ Tries to read JSON content from filename and convert it to a dict. :param filepath: Path where the file is :param filename: File name :return: Dictionary read from the file :raises EnvironmentError, ValueError ...
python
{ "resource": "" }
q242402
JsonFile.read_value
train
def read_value(self, key, filepath=None, filename=None): """ Tries to read the value of given key from JSON file filename. :param filepath: Path to file :param filename: Name of file :param key: Key to search for :return: Value corresponding to given key :raises ...
python
{ "resource": "" }
q242403
JsonFile.write_values
train
def write_values(self, data, filepath=None, filename=None, indent=None, keys_to_write=None): """ Tries to write extra content to a JSON file. Creates filename.temp with updated content, removes the old file and finally renames the .temp to match the old file. This is in effort t...
python
{ "resource": "" }
q242404
JsonFile._write_json
train
def _write_json(self, filepath, filename, writemode, content, indent): """ Helper for writing content to a file. :param filepath: path to file :param filename: name of file :param writemode: writemode used :param content: content to write :param indent: value for...
python
{ "resource": "" }
q242405
JsonFile._read_json
train
def _read_json(self, path, name): """ Load a json into a dictionary from a file. :param path: path to file :param name: name of file :return: dict """ with open(os.path.join(path, name), 'r') as fil: output = json.load(fil) self.logger.inf...
python
{ "resource": "" }
q242406
JsonFile._ends_with
train
def _ends_with(self, string_to_edit, end): # pylint: disable=no-self-use """ Check if string ends with characters in end, if not merge end to string. :param string_to_edit: string to check and edit. :param end: str :return: string_to_edit or string_to_edit + end """ ...
python
{ "resource": "" }
q242407
ParserManager.parse
train
def parse(self, *args, **kwargs): # pylint: disable=unused-argument """ Parse response. :param args: List. 2 first items used as parser name and response to parse :param kwargs: dict, not used :return: dictionary or return value of called callable from parser. """ ...
python
{ "resource": "" }
q242408
ResultList.append
train
def append(self, result): """ Append a new Result to the list. :param result: Result to append :return: Nothing :raises: TypeError if result is not Result or ResultList """ if isinstance(result, Result): self.data.append(result) elif isinstanc...
python
{ "resource": "" }
q242409
ResultList.save
train
def save(self, heads, console=True): """ Create reports in different formats. :param heads: html table extra values in title rows :param console: Boolean, default is True. If set, also print out the console log. """ # Junit self._save_junit() # HTML ...
python
{ "resource": "" }
q242410
ResultList._save_junit
train
def _save_junit(self): """ Save Junit report. :return: Nothing """ report = ReportJunit(self) file_name = report.get_latest_filename("result.junit.xml", "") report.generate(file_name) file_name = report.get_latest_filename("junit.xml", "../") rep...
python
{ "resource": "" }
q242411
ResultList._save_html_report
train
def _save_html_report(self, heads=None, refresh=None): """ Save html report. :param heads: headers as dict :param refresh: Boolean, if True will add a reload-tag to the report :return: Nothing """ report = ReportHtml(self) heads = heads if heads else {} ...
python
{ "resource": "" }
q242412
ResultList.success_count
train
def success_count(self): """ Amount of passed test cases in this list. :return: integer """ return len([i for i, result in enumerate(self.data) if result.success])
python
{ "resource": "" }
q242413
ResultList.failure_count
train
def failure_count(self): """ Amount of failed test cases in this list. :return: integer """ return len([i for i, result in enumerate(self.data) if result.failure])
python
{ "resource": "" }
q242414
ResultList.inconclusive_count
train
def inconclusive_count(self): """ Amount of inconclusive test cases in this list. :return: integer """ inconc_count = len([i for i, result in enumerate(self.data) if result.inconclusive]) unknown_count = len([i for i, result in enumerate(self.data) if result.get_verdict(...
python
{ "resource": "" }
q242415
ResultList.retry_count
train
def retry_count(self): """ Amount of retried test cases in this list. :return: integer """ retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0]) return retries
python
{ "resource": "" }
q242416
ResultList.skip_count
train
def skip_count(self): """ Amount of skipped test cases in this list. :return: integer """ return len([i for i, result in enumerate(self.data) if result.skip])
python
{ "resource": "" }
q242417
ResultList.clean_fails
train
def clean_fails(self): """ Check if there are any fails that were not subsequently retried. :return: Boolean """ for item in self.data: if item.failure and not item.retries_left > 0: return True return False
python
{ "resource": "" }
q242418
ResultList.clean_inconcs
train
def clean_inconcs(self): """ Check if there are any inconclusives or uknowns that were not subsequently retried. :return: Boolean """ for item in self.data: if (item.inconclusive or item.get_verdict() == "unknown") and not item.retries_left > 0: retur...
python
{ "resource": "" }
q242419
ResultList.total_duration
train
def total_duration(self): """ Sum of the durations of the tests in this list. :return: integer """ durations = [result.duration for result in self.data] return sum(durations)
python
{ "resource": "" }
q242420
ResultList.pass_rate
train
def pass_rate(self, include_skips=False, include_inconclusive=False, include_retries=True): """ Calculate pass rate for tests in this list. :param include_skips: Boolean, if True skipped tc:s will be included. Default is False :param include_inconclusive: Boolean, if True inconclusive t...
python
{ "resource": "" }
q242421
ResultList.get_summary
train
def get_summary(self): """ Get a summary of this ResultLists contents as dictionary. :return: dictionary """ return { "count": self.count(), "pass": self.success_count(), "fail": self.failure_count(), "skip": self.skip_count(), ...
python
{ "resource": "" }
q242422
ResultList.next
train
def next(self): """ Implementation of next method from Iterator. :return: Result :raises: StopIteration if IndexError occurs. """ try: result = self.data[self.index] except IndexError: self.index = 0 raise StopIteration ...
python
{ "resource": "" }
q242423
deprecated
train
def deprecated(message=""): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used first time and filter is set for show DeprecationWarning. """ def decorator_wrapper(func): """ Generate decor...
python
{ "resource": "" }
q242424
remove_file
train
def remove_file(filename, path=None): """ Remove file filename from path. :param filename: Name of file to remove :param path: Path where file is located :return: True if successfull :raises OSError if chdir or remove fails. """ cwd = os.getcwd() try: if path: os...
python
{ "resource": "" }
q242425
CliResponse.verify_message
train
def verify_message(self, expected_response, break_in_fail=True): """ Verifies that expected_response is found in self.lines. :param expected_response: response or responses to look for. Must be list or str. :param break_in_fail: If set to True, re-raises exceptions caught or if ...
python
{ "resource": "" }
q242426
CliResponse.verify_trace
train
def verify_trace(self, expected_traces, break_in_fail=True): """ Verifies that expectedResponse is found in self.traces :param expected_traces: response or responses to look for. Must be list or str. :param break_in_fail: If set to True, re-raises exceptions caught or if message was ...
python
{ "resource": "" }
q242427
CliResponse.verify_response_duration
train
def verify_response_duration(self, expected=None, zero=0, threshold_percent=0, break_in_fail=True): """ Verify that response duration is in bounds. :param expected: seconds what is expected duration :param zero: seconds if one to normalize duration befor...
python
{ "resource": "" }
q242428
ResourceConfig._hardware_count
train
def _hardware_count(self): """ Amount of hardware resources. :return: integer """ return self._counts.get("hardware") + self._counts.get("serial") + self._counts.get("mbed")
python
{ "resource": "" }
q242429
ResourceConfig._resolve_requirements
train
def _resolve_requirements(self, requirements): """ Internal method for resolving requirements into resource configurations. :param requirements: Resource requirements from test case configuration as dictionary. :return: Empty list if dut_count cannot be resolved, or nothing """ ...
python
{ "resource": "" }
q242430
ResourceConfig._solve_location
train
def _solve_location(self, req, dut_req_len, idx): """ Helper function for resolving the location for a resource. :param req: Requirements dictionary :param dut_req_len: Amount of required resources :param idx: index, integer :return: Nothing, modifies req object ...
python
{ "resource": "" }
q242431
ResourceConfig.__replace_base_variables
train
def __replace_base_variables(text, req_len, idx): """ Replace i and n in text with index+1 and req_len. :param text: base text to modify :param req_len: amount of required resources :param idx: index of resource we are working on :return: modified string """ ...
python
{ "resource": "" }
q242432
ResourceConfig.__replace_coord_variables
train
def __replace_coord_variables(text, x_and_y, req_len, idx): """ Replace x and y with their coordinates and replace pi with value of pi. :param text: text: base text to modify :param x_and_y: location x and y :param req_len: amount of required resources :param idx: index ...
python
{ "resource": "" }
q242433
ResourceConfig.__generate_indexed_requirements
train
def __generate_indexed_requirements(dut_count, basekeys, requirements): """ Generate indexed requirements from general requirements. :param dut_count: Amount of duts :param basekeys: base keys as dict :param requirements: requirements :return: Indexed requirements as dic...
python
{ "resource": "" }
q242434
ResourceConfig._resolve_hardware_count
train
def _resolve_hardware_count(self): """ Calculate amount of hardware resources. :return: Nothing, adds results to self._hardware_count """ length = len([d for d in self._dut_requirements if d.get("type") in ["hardware", ...
python
{ "resource": "" }
q242435
ResourceConfig._resolve_process_count
train
def _resolve_process_count(self): """ Calculate amount of process resources. :return: Nothing, adds results to self._process_count """ length = len([d for d in self._dut_requirements if d.get("type") == "process"]) self._process_count = length
python
{ "resource": "" }
q242436
ResourceConfig._resolve_dut_count
train
def _resolve_dut_count(self): """ Calculates total amount of resources required and their types. :return: Nothing, modifies _dut_count, _hardware_count and _process_count :raises: ValueError if total count does not match counts of types separately. """ self._dut_...
python
{ "resource": "" }
q242437
ResourceConfig.set_dut_configuration
train
def set_dut_configuration(self, ident, config): """ Set requirements for dut ident. :param ident: Identity of dut. :param config: If ResourceRequirements object, add object as requirements for resource ident. If dictionary, create new ResourceRequirements object from dictionary....
python
{ "resource": "" }
q242438
DutMbed.flash
train
def flash(self, binary_location=None, forceflash=None): """ Flash a binary to the target device using mbed-flasher. :param binary_location: Binary to flash to device. :param forceflash: Not used. :return: False if an unknown error was encountered during flashing. True if...
python
{ "resource": "" }
q242439
DutMbed._flash_needed
train
def _flash_needed(self, **kwargs): """ Check if flashing is needed. Flashing can be skipped if resource binary_sha1 attribute matches build sha1 and forceflash is not True. :param kwargs: Keyword arguments (forceflash: Boolean) :return: Boolean """ forceflash = k...
python
{ "resource": "" }
q242440
SerialParams.get_params
train
def get_params(self): """ Get parameters as a tuple. :return: timeout, xonxoff, rtscts, baudrate """ return self.timeout, self.xonxoff, self.rtscts, self.baudrate
python
{ "resource": "" }
q242441
DutSerial.open_connection
train
def open_connection(self): """ Open serial port connection. :return: Nothing :raises: DutConnectionError if serial port was already open or a SerialException occurs. ValueError if EnhancedSerial __init__ or value setters raise ValueError """ if self.readthread is...
python
{ "resource": "" }
q242442
DutSerial.close_connection
train
def close_connection(self): # pylint: disable=C0103 """ Closes serial port connection. :return: Nothing """ if self.port: self.stop() self.logger.debug("Close port '%s'" % self.comport, extra={'type': '<->'}) sel...
python
{ "resource": "" }
q242443
DutSerial.__send_break
train
def __send_break(self): """ Sends break to device. :return: result of EnhancedSerial safe_sendBreak() """ if self.port: self.logger.debug("sendBreak to device to reboot", extra={'type': '<->'}) result = self.port.safe_sendBreak() time.sleep(1)...
python
{ "resource": "" }
q242444
DutSerial.writeline
train
def writeline(self, data): """ Writes data to serial port. :param data: Data to write :return: Nothing :raises: IOError if SerialException occurs. """ try: if self.ch_mode: data += "\n" parts = split_by_n(data, self.ch_...
python
{ "resource": "" }
q242445
DutSerial._readline
train
def _readline(self, timeout=1): """ Read line from serial port. :param timeout: timeout, default is 1 :return: stripped line or None """ line = self.port.readline(timeout=timeout) return strip_escape(line.strip()) if line is not None else line
python
{ "resource": "" }
q242446
DutSerial.run
train
def run(self): """ Read lines while keep_reading is True. Calls process_dut for each received line. :return: Nothing """ self.keep_reading = True while self.keep_reading: line = self._readline() if line: self.input_queue.appendleft...
python
{ "resource": "" }
q242447
DutSerial.stop
train
def stop(self): """ Stops and joins readthread. :return: Nothing """ self.keep_reading = False if self.readthread is not None: self.readthread.join() self.readthread = None
python
{ "resource": "" }
q242448
DutSerial.print_info
train
def print_info(self): """ Prints Dut information nicely formatted into a table. """ table = PrettyTable() start_string = "DutSerial {} \n".format(self.name) row = [] info_string = "" if self.config: info_string = info_string + "Configuration fo...
python
{ "resource": "" }
q242449
Data.append
train
def append(self, data): """Append a Data instance to self""" for k in self._entries.keys(): self._entries[k].append(data._entries[k])
python
{ "resource": "" }
q242450
Data.init_group
train
def init_group(self, group, chunk_size, compression=None, compression_opts=None): """Initializes a HDF5 group compliant with the stored data. This method creates the datasets 'items', 'labels', 'features' and 'index' and leaves them empty. :param h5py.Group group: Th...
python
{ "resource": "" }
q242451
Data.is_appendable_to
train
def is_appendable_to(self, group): """Returns True if the data can be appended in a given group.""" # First check only the names if not all([k in group for k in self._entries.keys()]): return False # If names are matching, check the contents for k in self._entries.ke...
python
{ "resource": "" }
q242452
Data.write_to
train
def write_to(self, group, append=False): """Write the data to the given group. :param h5py.Group group: The group to write the data on. It is assumed that the group is already existing or initialized to store h5features data (i.e. the method ``Data.init_group`` have ...
python
{ "resource": "" }
q242453
Labels.check
train
def check(labels): """Raise IOError if labels are not correct `labels` must be a list of sorted numpy arrays of equal dimensions (must be 1D or 2D). In the case of 2D labels, the second axis must have the same shape for all labels. """ # type checking ...
python
{ "resource": "" }
q242454
Converter._write
train
def _write(self, item, labels, features): """ Writes the given item to the owned file.""" data = Data([item], [labels], [features]) self._writer.write(data, self.groupname, append=True)
python
{ "resource": "" }
q242455
Converter.convert
train
def convert(self, infile, item=None): """Convert an input file to h5features based on its extension. :raise IOError: if `infile` is not a valid file. :raise IOError: if `infile` extension is not supported. """ if not os.path.isfile(infile): raise IOError('{} is not ...
python
{ "resource": "" }
q242456
Converter.npz_convert
train
def npz_convert(self, infile, item): """Convert a numpy NPZ file to h5features.""" data = np.load(infile) labels = self._labels(data) features = data['features'] self._write(item, labels, features)
python
{ "resource": "" }
q242457
Converter.h5features_convert
train
def h5features_convert(self, infile): """Convert a h5features file to the latest h5features version.""" with h5py.File(infile, 'r') as f: groups = list(f.keys()) for group in groups: self._writer.write( Reader(infile, group).read(), self.gr...
python
{ "resource": "" }
q242458
read
train
def read(filename, groupname=None, from_item=None, to_item=None, from_time=None, to_time=None, index=None): """Reads in a h5features file. :param str filename: Path to a hdf5 file potentially serving as a container for many small files :param str groupname: HDF5 group to read the data fro...
python
{ "resource": "" }
q242459
write
train
def write(filename, groupname, items, times, features, properties=None, dformat='dense', chunk_size='auto', sparsity=0.1, mode='a'): """Write h5features data in a HDF5 file. This function is a wrapper to the Writer class. It has three purposes: * Check parameters for errors (see details below), ...
python
{ "resource": "" }
q242460
contains_empty
train
def contains_empty(features): """Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else. """ if not features: return True for feature in features: if featur...
python
{ "resource": "" }
q242461
parse_dformat
train
def parse_dformat(dformat, check=True): """Return `dformat` or raise if it is not 'dense' or 'sparse'""" if check and dformat not in ['dense', 'sparse']: raise IOError( "{} is a bad features format, please choose 'dense' or 'sparse'" .format(dformat)) return dformat
python
{ "resource": "" }
q242462
parse_dtype
train
def parse_dtype(features, check=True): """Return the features scalar type, raise if error Raise IOError if all features have not the same data type. Return dtype, the features scalar type. """ dtype = features[0].dtype if check: types = [x.dtype for x in features] if not all([t...
python
{ "resource": "" }
q242463
parse_dim
train
def parse_dim(features, check=True): """Return the features dimension, raise if error Raise IOError if features have not all the same positive dimension. Return dim (int), the features dimension. """ # try: dim = features[0].shape[1] # except IndexError: # dim = 1 if check an...
python
{ "resource": "" }
q242464
Features.is_appendable_to
train
def is_appendable_to(self, group): """Return True if features are appendable to a HDF5 group""" return (group.attrs['format'] == self.dformat and group[self.name].dtype == self.dtype and # We use a method because dim differs in dense and sparse. self._grou...
python
{ "resource": "" }
q242465
Features.create_dataset
train
def create_dataset( self, group, chunk_size, compression=None, compression_opts=None): """Initialize the features subgoup""" group.attrs['format'] = self.dformat super(Features, self)._create_dataset( group, chunk_size, compression, compression_opts) # TODO attri...
python
{ "resource": "" }
q242466
Features.write_to
train
def write_to(self, group, append=False): """Write stored features to a given group""" if self.sparsetodense: self.data = [x.todense() if sp.issparse(x) else x for x in self.data] nframes = sum([d.shape[0] for d in self.data]) dim = self._group_dim(gr...
python
{ "resource": "" }
q242467
SparseFeatures.create_dataset
train
def create_dataset(self, group, chunk_size): """Initializes sparse specific datasets""" group.attrs['format'] = self.dformat group.attrs['dim'] = self.dim if chunk_size == 'auto': group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, ...
python
{ "resource": "" }
q242468
read_properties
train
def read_properties(group): """Returns properties loaded from a group""" if 'properties' not in group: raise IOError('no properties in group') data = group['properties'][...][0].replace(b'__NULL__', b'\x00') return pickle.loads(data)
python
{ "resource": "" }
q242469
Properties._eq_dicts
train
def _eq_dicts(d1, d2): """Returns True if d1 == d2, False otherwise""" if not d1.keys() == d2.keys(): return False for k, v1 in d1.items(): v2 = d2[k] if not type(v1) == type(v2): return False if isinstance(v1, np.ndarray): ...
python
{ "resource": "" }
q242470
Properties.write_to
train
def write_to(self, group, append=False): """Writes the properties to a `group`, or append it""" data = self.data if append is True: try: # concatenate original and new properties in a single list original = read_properties(group) data =...
python
{ "resource": "" }
q242471
generate_data
train
def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'): """Returns a randomly generated h5f.Data instance. - nitem is the number of items to generate. - nfeat is the number of features to generate for each item. - dim is the dimension of the features vectors. - base is the items basenam...
python
{ "resource": "" }
q242472
create_index
train
def create_index(group, chunk_size, compression=None, compression_opts=None): """Create an empty index dataset in the given group.""" dtype = np.int64 if chunk_size == 'auto': chunks = True else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) group.create_dataset(...
python
{ "resource": "" }
q242473
write_index
train
def write_index(data, group, append): """Write the data index to the given group. :param h5features.Data data: The that is being indexed. :param h5py.Group group: The group where to write the index. :param bool append: If True, append the created index to the existing one in the `group`. Delete...
python
{ "resource": "" }
q242474
read_index
train
def read_index(group, version='1.1'): """Return the index stored in a h5features group. :param h5py.Group group: The group to read the index from. :param str version: The h5features version of the `group`. :return: a 1D numpy array of features indices. """ if version == '0.1': return np...
python
{ "resource": "" }
q242475
nb_per_chunk
train
def nb_per_chunk(item_size, item_dim, chunk_size): """Return the number of items that can be stored in one chunk. :param int item_size: Size of an item's scalar componant in Bytes (e.g. for np.float64 this is 8) :param int item_dim: Items dimension (length of the second axis) :param float chu...
python
{ "resource": "" }
q242476
Entry.is_appendable
train
def is_appendable(self, entry): """Return True if entry can be appended to self""" try: if ( self.name == entry.name and self.dtype == entry.dtype and self.dim == entry.dim ): return True except A...
python
{ "resource": "" }
q242477
Entry.append
train
def append(self, entry): """Append an entry to self""" if not self.is_appendable(entry): raise ValueError('entry not appendable') self.data += entry.data
python
{ "resource": "" }
q242478
Writer.write
train
def write(self, data, groupname='h5features', append=False): """Write h5features data in a specified group of the file. :param dict data: A `h5features.Data` instance to be writed on disk. :param str groupname: Optional. The name of the group in which to write the data. :p...
python
{ "resource": "" }
q242479
Writer._prepare
train
def _prepare(self, data, groupname): """Clear the group if existing and initialize empty datasets.""" if groupname in self.h5file: del self.h5file[groupname] group = self.h5file.create_group(groupname) group.attrs['version'] = self.version data.init_group( ...
python
{ "resource": "" }
q242480
read_items
train
def read_items(group, version='1.1', check=False): """Return an Items instance initialized from a h5features group.""" if version == '0.1': # parse unicode to strings return ''.join( [unichr(int(c)) for c in group['files'][...]] ).replace('/-', '/').split('/\\') elif vers...
python
{ "resource": "" }
q242481
Items.write_to
train
def write_to(self, group): """Write stored items to the given HDF5 group. We assume that self.create() has been called. """ # The HDF5 group where to write data items_group = group[self.name] nitems = items_group.shape[0] items_group.resize((nitems + len(self.d...
python
{ "resource": "" }
q242482
Items._create_dataset
train
def _create_dataset( self, group, chunk_size, compression, compression_opts): """Create an empty dataset in a group.""" if chunk_size == 'auto': chunks = True else: # if dtype is a variable str, guess representative size is 20 bytes per_chunk = ( ...
python
{ "resource": "" }
q242483
read_version
train
def read_version(group): """Return the h5features version of a given HDF5 `group`. Look for a 'version' attribute in the `group` and return its value. Return '0.1' if the version is not found. Raises an IOError if it is not supported. """ version = ('0.1' if 'version' not in group.attrs ...
python
{ "resource": "" }
q242484
Reader.read
train
def read(self, from_item=None, to_item=None, from_time=None, to_time=None): """Retrieve requested data coordinates from the h5features index. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: ...
python
{ "resource": "" }
q242485
GTP_game.writesgf
train
def writesgf(self, sgffilename): "Write the game to an SGF file after a game" size = self.size outfile = open(sgffilename, "w") if not outfile: print "Couldn't create " + sgffilename return black_name = self.blackplayer.get_program_name() white_na...
python
{ "resource": "" }
q242486
_escapeText
train
def _escapeText(text): """ Adds backslash-escapes to property value characters that need them.""" output = "" index = 0 match = reCharsToEscape.search(text, index) while match: output = output + text[index:match.start()] + '\\' + text[match.start()] index = match.end() match = reCharsToEscape.search(text, in...
python
{ "resource": "" }
q242487
SGFParser.parse
train
def parse(self): """ Parses the SGF data stored in 'self.data', and returns a 'Collection'.""" c = Collection() while self.index < self.datalen: g = self.parseOneGame() if g: c.append(g) else: break return c
python
{ "resource": "" }
q242488
SGFParser.parseOneGame
train
def parseOneGame(self): """ Parses one game from 'self.data'. Returns a 'GameTree' containing one game, or 'None' if the end of 'self.data' has been reached.""" if self.index < self.datalen: match = self.reGameTreeStart.match(self.data, self.index) if match: self.index = match.end() return self.par...
python
{ "resource": "" }
q242489
Cursor.reset
train
def reset(self): """ Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'.""" self.gametree = self.game self.nodenum = 0 self.index = 0 self.stack = [] self.node = self.gametree[self.index] self._setChildren() self._setFlags()
python
{ "resource": "" }
q242490
Cursor.previous
train
def previous(self): """ Moves the 'Cursor' to & returns the previous 'Node'. Raises 'GameTreeEndError' if the start of a branch is exceeded.""" if self.index - 1 >= 0: # more main line? self.index = self.index - 1 elif self.stack: # were we in a variation? self.gametree = self.stack.pop() sel...
python
{ "resource": "" }
q242491
Cursor._setChildren
train
def _setChildren(self): """ Sets up 'self.children'.""" if self.index + 1 < len(self.gametree): self.children = [self.gametree[self.index+1]] else: self.children = map(lambda list: list[0], self.gametree.variations)
python
{ "resource": "" }
q242492
Cursor._setFlags
train
def _setFlags(self): """ Sets up the flags 'self.atEnd' and 'self.atStart'.""" self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree)) self.atStart = not self.stack and (self.index == 0)
python
{ "resource": "" }
q242493
ripple_carry_add
train
def ripple_carry_add(A, B, cin=0): """Return symbolic logic for an N-bit ripple carry adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") ss, cs = list(), list() for i, a in enumerate(A): c = (cin if i == 0 else cs[i-1]) ss.append(a ^ B[i] ^ c) ...
python
{ "resource": "" }
q242494
kogge_stone_add
train
def kogge_stone_add(A, B, cin=0): """Return symbolic logic for an N-bit Kogge-Stone adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] f...
python
{ "resource": "" }
q242495
brent_kung_add
train
def brent_kung_add(A, B, cin=0): """Return symbolic logic for an N-bit Brent-Kung adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] # c...
python
{ "resource": "" }
q242496
_expect_token
train
def _expect_token(lexer, types): """Return the next token, or raise an exception.""" tok = next(lexer) if any(isinstance(tok, t) for t in types): return tok else: raise Error("unexpected token: " + str(tok))
python
{ "resource": "" }
q242497
parse_cnf
train
def parse_cnf(s, varname='x'): """ Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults...
python
{ "resource": "" }
q242498
_cnf
train
def _cnf(lexer, varname): """Return a DIMACS CNF.""" _expect_token(lexer, {KW_p}) _expect_token(lexer, {KW_cnf}) nvars = _expect_token(lexer, {IntegerToken}).value nclauses = _expect_token(lexer, {IntegerToken}).value return _cnf_formula(lexer, varname, nvars, nclauses)
python
{ "resource": "" }
q242499
_cnf_formula
train
def _cnf_formula(lexer, varname, nvars, nclauses): """Return a DIMACS CNF formula.""" clauses = _clauses(lexer, varname, nvars) if len(clauses) < nclauses: fstr = "formula has fewer than {} clauses" raise Error(fstr.format(nclauses)) if len(clauses) > nclauses: fstr = "formula h...
python
{ "resource": "" }