text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_name(self, name): """Writes a domain name to the packet"""
try: # Find existing instance of this name in packet # index = self.names[name] except KeyError: # No record of this name already, so write it # out as normal, recording the location of the name # for future pointers to it. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_question(self, question): """Writes a question to the packet"""
self.write_name(question.name) self.write_short(question.type) self.write_short(question.clazz)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def packet(self): """Returns a string containing the packet's bytes No further parts should be added to the packet once this is done."""
if not self.finished: self.finished = 1 for question in self.questions: self.write_question(question) for answer, time in self.answers: self.write_record(answer, time) for authority in self.authorities: self.write_r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, entry): """Adds an entry"""
if self.get(entry) is not None: return try: list = self.cache[entry.key] except: list = self.cache[entry.key] = [] list.append(entry)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign(self, entry, signer=None): """Adds and sign an entry"""
if (self.get(entry) is not None): return if (entry.rrsig is None) and (self.private is not None): entry.rrsig = DNSSignatureS(entry.name, _TYPE_RRSIG, _CLASS_IN, entry, self.private, signer) self.add(entry) if (self.private is not None): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, entry): """Removes an entry"""
try: list = self.cache[entry.key] list.remove(entry) except: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, entry): """Gets an entry by key. Will return None if there is no matching entry."""
try: list = self.cache[entry.key] return list[list.index(entry)] except: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_details(self, name, type, clazz): """Gets an entry by details. Will return None if there is no matching entry."""
entry = DNSEntry(name, type, clazz) return self.get(entry)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entries(self): """Returns a list of all entries"""
def add(x, y): return x + y try: return reduce(add, list(self.cache.values())) except: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_record(self, zeroconf, now, record): """Callback invoked by Zeroconf when new information arrives. Updates information required by browser in the Zero...
if record.type == _TYPE_PTR and record.name == self.type: expired = record.is_expired(now) try: oldrecord = self.services[record.alias.lower()] if not expired: oldrecord.reset_ttl(record) else: del(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_properties(self, properties): """Sets properties and text of this info from a dictionary"""
if isinstance(properties, dict): self.properties = properties self.sync_properties() else: self.text = properties
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_text(self, text): """Sets properties and text given a text field"""
self.text = text try: self.properties = text_to_dict(text) except: traceback.print_exc() self.properties = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_record(self, zeroconf, now, record): """Updates service information from a DNS record"""
if record is not None and not record.is_expired(now): if record.type == _TYPE_A: if record.name == self.name: if not record.address in self.address: self.address.append(record.address) elif record.type == _TYPE_SRV: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, zeroconf, timeout): """Returns true if the service could be discovered on the network, and updates this object with details discovered. """
now = current_time_millis() delay = _LISTENER_TIME next = now + delay last = now + timeout result = 0 try: zeroconf.add_listener(self, DNSQuestion(self.name, _TYPE_ANY, _CLASS_IN)) while self.server is None or \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, timeout): """Calling thread waits for a given number of milliseconds or until notified."""
self.condition.acquire() self.condition.wait(timeout // 1000) self.condition.release()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify_all(self): """Notifies all waiting threads"""
self.condition.acquire() # python 3.x try: self.condition.notify_all() except: self.condition.notifyAll() self.condition.release()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_service_info(self, type, name, timeout=3000): """Returns network's service information for a particular name and type, or None if no service matches by t...
info = ServiceInfo(type, name) if info.request(self, timeout): return info return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_serviceListener(self, type, listener): """Adds a listener for a particular service type. This object will then have its update_record method called when ...
self.remove_service_listener(listener) self.browsers.append(ServiceBrowser(self, type, listener))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_service_listener(self, listener): """Removes a listener from the set that is currently listening."""
for browser in self.browsers: if browser.listener == listener: browser.cancel() del(browser)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_service(self, info): """Registers service information to the network with a default TTL of 60 seconds. Zeroconf will then respond to requests for in...
self.check_service(info) self.services[info.name.lower()] = info # zone transfer self.transfer_zone(info.type) self.announce_service(info.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister_service(self, info): """Unregister a service."""
try: del(self.services[info.name.lower()]) except: pass now = current_time_millis() next_time = now i = 0 while i < 3: if now < next_time: self.wait(next_time - now) now = current_time_millis() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_service(self, info): """Checks the network for a unique service name, modifying the ServiceInfo passed in if it is not unique."""
now = current_time_millis() next_time = now i = 0 while i < 3: for record in self.cache.entries_with_name(info.type): if record.type == _TYPE_PTR and \ not record.is_expired(now) and \ record.alias == info.name:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_listener(self, listener, question): """Adds a listener for a given question. The listener will have its update_record method called when information is a...
now = current_time_millis() self.listeners.append(listener) if question is not None: for record in self.cache.entries_with_name(question.name): if question.answered_by(record) and not record.is_expired(now): listener.update_record(self, now, recor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_record(self, now, rec): """Used to notify listeners of new information that has updated a record."""
for listener in self.listeners: listener.update_record(self, now, rec) self.notify_all()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_response(self, msg, address): """Deal with incoming response packets. All answers are held in the cache, and listeners are notified."""
now = current_time_millis() sigs = [] precache = [] for record in msg.answers: if isinstance(record, DNSSignature): sigs.append(record) else: precache.append(record) for e in precache: for s in sigs: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT): """Sends an outgoing packet."""
# This is a quick test to see if we can parse the packets we generate #temp = DNSIncoming(out.packet()) for i in self.intf.values(): try: return i.sendto(out.packet(), 0, (addr, port)) except: traceback.print_exc() # Ignore...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Ends the background threads, and prevent this instance from servicing further queries."""
if globals()['_GLOBAL_DONE'] == 0: globals()['_GLOBAL_DONE'] = 1 self.notify_all() self.engine.notify() self.unregister_all_services() for i in self.intf.values(): try: # there are cases, when we start mDNS without ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, identity_records: 'RDD', old_state_rdd: Optional['RDD'] = None) -> 'RDD': """ Executes Blurr BTS with the given records. old_state_rdd can be pr...
identity_records_with_state = identity_records if old_state_rdd: identity_records_with_state = identity_records.fullOuterJoin(old_state_rdd) return identity_records_with_state.map(lambda x: self._execute_per_identity_records(x))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_record_rdd_from_json_files(self, json_files: List[str], data_processor: DataProcessor = SimpleJsonDataProcessor(), spark_session: Optional['SparkSession']...
spark_context = get_spark_session(spark_session).sparkContext raw_records: 'RDD' = spark_context.union( [spark_context.textFile(file) for file in json_files]) return raw_records.mapPartitions( lambda x: self.get_per_identity_records(x, data_processor)).groupByKey().mapVa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_record_rdd_from_rdd( self, rdd: 'RDD', data_processor: DataProcessor = SimpleDictionaryDataProcessor(), ) -> 'RDD': """ Converts a RDD of raw events into ...
return rdd.mapPartitions( lambda x: self.get_per_identity_records(x, data_processor)).groupByKey().mapValues(list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_output_file(self, path: str, per_identity_data: 'RDD', spark_session: Optional['SparkSession'] = None) -> None: """ Basic helper function to persist dat...
_spark_session_ = get_spark_session(spark_session) if not self._window_bts: per_identity_data.flatMap( lambda x: [json.dumps(data, cls=BlurrJSONEncoder) for data in x[1][0].items()] ).saveAsTextFile(path) else: # Convert to a DataFrame first s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_output(self, per_identity_data: 'RDD') -> None: """ Basic helper function to write data to stdout. If window BTS was provided then the window BTS output...
if not self._window_bts: data = per_identity_data.flatMap( lambda x: [json.dumps(data, cls=BlurrJSONEncoder) for data in x[1][0].items()]) else: # Convert to a DataFrame first so that the data can be saved as a CSV data = per_identity_data.map( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_executable(executable, path=None): """ As distutils.spawn.find_executable, but on Windows, look up every extension declared in PATHEXT instead of just `...
if sys.platform != 'win32': return distutils.spawn.find_executable(executable, path) if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) extensions = os.environ.get('PATHEXT', '.exe').split(os.pathsep) base, ext = os.path.splitext(executable) if not os.p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_environment_dict(overrides): """ Create and return a copy of os.environ with the specified overrides """
result = os.environ.copy() result.update(overrides or {}) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, server): """ Retrieve credentials for `server`. If no credentials are found, a `StoreError` will be raised. """
if not isinstance(server, six.binary_type): server = server.encode('utf-8') data = self._execute('get', server) result = json.loads(data.decode('utf-8')) # docker-credential-pass will return an object for inexistent servers # whereas other helpers will exit with ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store(self, server, username, secret): """ Store credentials for `server`. Raises a `StoreError` if an error occurs. """
data_input = json.dumps({ 'ServerURL': server, 'Username': username, 'Secret': secret }).encode('utf-8') return self._execute('store', data_input)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase(self, server): """ Erase credentials for `server`. Raises a `StoreError` if an error occurs. """
if not isinstance(server, six.binary_type): server = server.encode('utf-8') self._execute('erase', server)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend_schema_spec(self) -> None: """ Injects the identity field """
super().extend_schema_spec() identity_field = { 'Name': '_identity', 'Type': BtsType.STRING, 'Value': 'identity', ATTRIBUTE_INTERNAL: True } if self.ATTRIBUTE_FIELDS in self._spec: self._spec[self.ATTRIBUTE_FIELDS].insert(0, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _persist(self) -> None: """ Persists the current data group """
if self._store: self._store.save(self._key, self._snapshot)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None: """ Adds errors to the error store for the schema """
for error in errors: self._error_cache.add(error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def global_add(self, key: str, value: Any) -> None: """ Adds a key and value to the global dictionary """
self.global_context[key] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_files(source, target): """ Copy all the files in source directory to target. Ignores subdirectories. """
source_files = listdir(source) if not exists(target): makedirs(target) for filename in source_files: full_filename = join(source, filename) if isfile(full_filename): shutil.copy(full_filename, target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_copy(self): """ Initialises a temporary directory structure and copy of MAGICC configuration files and binary. """
if self.executable is None or not isfile(self.executable): raise FileNotFoundError( "Could not find MAGICC{} executable: {}".format( self.version, self.executable ) ) if self.is_temp: assert ( self.r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, scenario=None, only=None, **kwargs): """ Run MAGICC and parse the output. As a reminder, putting ``out_parameters=1`` will cause MAGICC to write ou...
if not exists(self.root_dir): raise FileNotFoundError(self.root_dir) if self.executable is None: raise ValueError( "MAGICC executable not found, try setting an environment variable `MAGICC_EXECUTABLE_{}=/path/to/binary`".format( self.version ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_config(self): """Check that our MAGICC ``.CFG`` files are set to safely work with PYMAGICC For further detail about why this is required, please see :r...
cfg_error_msg = ( "PYMAGICC is not the only tuning model that will be used by " "`MAGCFG_USER.CFG`: your run is likely to fail/do odd things" ) emisscen_error_msg = ( "You have more than one `FILE_EMISSCEN_X` flag set. Using more than " "one emiss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, mdata, name): """Write an input file to disk Parameters mdata : :obj:`pymagicc.io.MAGICCData` A MAGICCData instance with the data to write name :...
mdata.write(join(self.run_dir, name), self.version)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_parameters(self): """ Read a parameters.out file Returns ------- dict A dictionary containing all the configuration used by MAGICC """
param_fname = join(self.out_dir, "PARAMETERS.OUT") if not exists(param_fname): raise FileNotFoundError("No PARAMETERS.OUT found") with open(param_fname) as nml_file: parameters = dict(f90nml.read(nml_file)) for group in ["nml_years", "nml_allcfgs", "nml_out...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_temp_copy(self): """ Removes a temporary copy of the MAGICC version shipped with Pymagicc. """
if self.is_temp and self.root_dir is not None: shutil.rmtree(self.root_dir) self.root_dir = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_config( self, filename="MAGTUNE_PYMAGICC.CFG", top_level_key="nml_allcfgs", **kwargs ): """ Create a configuration file for MAGICC. Writes a fortran name...
kwargs = self._format_config(kwargs) fname = join(self.run_dir, filename) conf = {top_level_key: kwargs} f90nml.write(conf, fname, force=True) return conf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_config( self, filename="MAGTUNE_PYMAGICC.CFG", top_level_key="nml_allcfgs", **kwargs ): """Updates a configuration file for MAGICC Updates the content...
kwargs = self._format_config(kwargs) fname = join(self.run_dir, filename) if exists(fname): conf = f90nml.read(fname) else: conf = {top_level_key: {}} conf[top_level_key].update(kwargs) f90nml.write(conf, fname, force=True) return conf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_zero_config(self): """Set config such that radiative forcing and temperature output will be zero This method is intended as a convenience only, it does n...
# zero_emissions is imported from scenarios module zero_emissions.write(join(self.run_dir, self._scen_file_name), self.version) time = zero_emissions.filter(variable="Emissions|CH4", region="World")[ "time" ].values no_timesteps = len(time) # value doesn't a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_years(self, startyear=1765, endyear=2100): """ Set the start and end dates of the simulations. Parameters startyear : int Start year of the simulation en...
# TODO: test altering stepsperyear, I think 1, 2 and 24 should all work return self.set_config( "MAGCFG_NMLYEARS.CFG", "nml_years", endyear=endyear, startyear=startyear, stepsperyear=12, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_output_variables(self, write_ascii=True, write_binary=False, **kwargs): """Set the output configuration, minimising output as much as possible There are ...
assert ( write_ascii or write_binary ), "write_binary and/or write_ascii must be configured" if write_binary and write_ascii: ascii_binary = "BOTH" elif write_ascii: ascii_binary = "ASCII" else: ascii_binary = "BINARY" # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagnose_tcr_ecs(self, **kwargs): """Diagnose TCR and ECS The transient climate response (TCR), is the global-mean temperature response at time at which atmo...
if self.version == 7: raise NotImplementedError("MAGICC7 cannot yet diagnose ECS and TCR") self._diagnose_tcr_ecs_config_setup(**kwargs) timeseries = self.run( scenario=None, only=[ "Atmospheric Concentrations|CO2", "Radiative ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_emission_scenario_setup(self, scenario, config_dict): """Set the emissions flags correctly. Parameters scenario : :obj:`pymagicc.io.MAGICCData` Scenario ...
self.write(scenario, self._scen_file_name) # can be lazy in this line as fix backwards key handles errors for us config_dict["file_emissionscenario"] = self._scen_file_name config_dict = self._fix_any_backwards_emissions_scen_key_in_config(config_dict) return config_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains(value: Union[str, 'Type']) -> bool: """ Checks if a type is defined """
if isinstance(value, str): return any(value.lower() == i.value for i in Type) return any(value == i for i in Type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calcidxs(func): """Return the required indexes based on the given lambda function and the |Timegrids| object handled by module |pub|. Raise a |RuntimeError|...
timegrids = hydpy.pub.get('timegrids') if timegrids is None: raise RuntimeError( 'An Indexer object has been asked for an %s array. Such an ' 'array has neither been determined yet nor can it be ' 'determined automatically at the moment. Ei...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getter_(self, fget) -> 'BaseProperty': """Add the given getter function and its docstring to the property and return it."""
self.fget = fget self.set_doc(fget.__doc__) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isready(self, obj) -> bool: """Return |True| or |False| to indicate if the protected property is ready for the given object. If the object is unknow, |Protect...
return vars(obj).get(self.name, False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allready(self, obj) -> bool: """Return |True| or |False| to indicate whether all protected properties are ready or not."""
for prop in self.__properties: if not prop.isready(obj): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_fget(self, obj) -> Any: """Return the predefined custom value when available, otherwise, the value defined by the getter function."""
custom = vars(obj).get(self.name) if custom is None: return self.fget(obj) return custom
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_fset(self, obj, value) -> None: """Store the given custom value and call the setter function."""
vars(obj)[self.name] = self.fset(obj, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_fdel(self, obj) -> None: """Remove the predefined custom value and call the delete function."""
self.fdel(obj) try: del vars(obj)[self.name] except KeyError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_lines(specification, module): """Return autodoc commands for a basemodels docstring. Note that `collection classes` (e.g. `Model`, `ControlParameters`, ...
caption = _all_spec2capt.get(specification, 'dummy') if caption.split()[-1] in ('parameters', 'sequences', 'Masks'): exists_collectionclass = True name_collectionclass = caption.title().replace(' ', '') else: exists_collectionclass = False lines = [] if specification == 'mod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodoc_basemodel(module): """Add an exhaustive docstring to the given module of a basemodel. Works onlye when all modules of the basemodel are named in the ...
autodoc_tuple2doc(module) namespace = module.__dict__ doc = namespace.get('__doc__') if doc is None: doc = '' basemodulename = namespace['__name__'].split('.')[-1] modules = {key: value for key, value in namespace.items() if (isinstance(value, types.ModuleType) and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodoc_applicationmodel(module): """Improves the docstrings of application models when called at the bottom of the respective module. |autodoc_applicationmo...
autodoc_tuple2doc(module) name_applicationmodel = module.__name__ name_basemodel = name_applicationmodel.split('_')[0] module_basemodel = importlib.import_module(name_basemodel) substituter = Substituter(module_basemodel.substituter) substituter.add_module(module) substituter.update_masters...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _number_of_line(member_tuple): """Try to return the number of the first line of the definition of a member of a module."""
member = member_tuple[1] try: return member.__code__.co_firstlineno except AttributeError: pass try: return inspect.findsource(member)[1] except BaseException: pass for value in vars(member).values(): try: return value.__code__.co_firstlineno ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodoc_module(module): """Add a short summary of all implemented members to a modules docstring. """
doc = getattr(module, '__doc__') if doc is None: doc = '' members = [] for name, member in inspect.getmembers(module): if ((not name.startswith('_')) and (inspect.getmodule(member) is module)): members.append((name, member)) members = sorted(members, key=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodoc_tuple2doc(module): """Include tuples as `CLASSES` of `ControlParameters` and `RUN_METHODS` of `Models` into the respective docstring."""
modulename = module.__name__ for membername, member in inspect.getmembers(module): for tuplename, descr in _name2descr.items(): tuple_ = getattr(member, tuplename, None) if tuple_: logstring = f'{modulename}.{membername}.{tuplename}' if logstring ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consider_member(name_member, member, module, class_=None): """Return |True| if the given member should be added to the substitutions. If not return |False|. ...
if name_member.startswith('_'): return False if inspect.ismodule(member): return False real_module = getattr(member, '__module__', None) if not real_module: return True if real_module != module.__name__: if class_ and hasattr(membe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_role(member, cython=False): """Return the reStructuredText role `func`, `class`, or `const` best describing the given member. Some examples based on the ...
if inspect.isroutine(member) or isinstance(member, numpy.ufunc): return 'func' elif inspect.isclass(member): return 'class' elif cython: return 'func' return 'const'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_substitution(self, short, medium, long, module): """Add the given substitutions both as a `short2long` and a `medium2long` mapping. Assume `variable1` is...
name = module.__name__ if 'builtin' in name: self._short2long[short] = long.split('~')[0] + long.split('.')[-1] else: if ('hydpy' in name) and (short not in self._blacklist): if short in self._short2long: if self._short2long[short] != ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_module(self, module, cython=False): """Add the given module, its members, and their submembers. The first examples are based on the site-package |numpy|:...
name_module = module.__name__.split('.')[-1] short = ('|%s|' % name_module) long = (':mod:`~%s`' % module.__name__) self._short2long[short] = long for (name_member, member) in vars(module).items(): if self.consider_member( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_modules(self, package): """Add the modules of the given package without their members."""
for name in os.listdir(package.__path__[0]): if name.startswith('_'): continue name = name.split('.')[0] short = '|%s|' % name long = ':mod:`~%s.%s`' % (package.__package__, name) self._short2long[short] = long
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_masters(self): """Update all `master` |Substituter| objects. If a |Substituter| object is passed to the constructor of another |Substituter| object, t...
if self.master is not None: self.master._medium2long.update(self._medium2long) self.master.update_masters()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_slaves(self): """Update all `slave` |Substituter| objects. See method |Substituter.update_masters| for further information. """
for slave in self.slaves: slave._medium2long.update(self._medium2long) slave.update_slaves()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_commands(self, source=None): """Return a string containing multiple `reStructuredText` replacements with the substitutions currently defined. Some exampl...
commands = [] for key, value in self: if (source is None) or (key in source): commands.append('.. %s replace:: %s' % (key, value)) return '\n'.join(commands)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(self, text): """Print all substitutions that include the given text string."""
for key, value in self: if (text in key) or (text in value): print(key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_progress(wrapped, _=None, args=None, kwargs=None): """Add print commands time to the given function informing about execution time. To show how the |pr...
global _printprogress_indentation _printprogress_indentation += 4 try: if hydpy.pub.options.printprogress: blanks = ' ' * _printprogress_indentation name = wrapped.__name__ time_ = time.strftime('%H:%M:%S') with PrintStyle(color=34, font=1): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def progressbar(iterable, length=23): """Print a simple progress bar while processing the given iterable. Function |progressbar| does print the progress bar when...
if hydpy.pub.options.printprogress and (len(iterable) > 1): temp_name = os.path.join(tempfile.gettempdir(), 'HydPy_progressbar_stdout') temp_stdout = open(temp_name, 'w') real_stdout = sys.stdout try: sys.stdout = temp_stdout ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_parameteritemtypes(self) -> None: """Get the types of all current exchange items supposed to change the values of |Parameter| objects."""
for item in state.parameteritems: self._outputs[item.name] = self._get_itemtype(item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_conditionitemtypes(self) -> None: """Get the types of all current exchange items supposed to change the values of |StateSequence| or |LogSequence| objects...
for item in state.conditionitems: self._outputs[item.name] = self._get_itemtype(item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_getitemtypes(self) -> None: """Get the types of all current exchange items supposed to return the values of |Parameter| or |Sequence| objects or the time ...
for item in state.getitems: type_ = self._get_itemtype(item) for name, _ in item.yield_name2value(): self._outputs[name] = type_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def POST_timegrid(self) -> None: """Change the current simulation |Timegrid|."""
init = hydpy.pub.timegrids.init sim = hydpy.pub.timegrids.sim sim.firstdate = self._inputs['firstdate'] sim.lastdate = self._inputs['lastdate'] state.idx1 = init[sim.firstdate] state.idx2 = init[sim.lastdate]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_parameteritemvalues(self) -> None: """Get the values of all |ChangeItem| objects handling |Parameter| objects."""
for item in state.parameteritems: self._outputs[item.name] = item.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_conditionitemvalues(self) -> None: """Get the values of all |ChangeItem| objects handling |StateSequence| or |LogSequence| objects."""
for item in state.conditionitems: self._outputs[item.name] = item.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_getitemvalues(self) -> None: """Get the values of all |Variable| objects observed by the current |GetItem| objects. For |GetItem| objects observing time s...
for item in state.getitems: for name, value in item.yield_name2value(state.idx1, state.idx2): self._outputs[name] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_load_conditionvalues(self) -> None: """Assign the |StateSequence| or |LogSequence| object values available for the current simulation start point to the c...
try: state.hp.conditions = state.conditions[self._id][state.idx1] except KeyError: if state.idx1: self._statuscode = 500 raise RuntimeError( f'Conditions for ID `{self._id}` and time point ' f'`{hydpy.pub.ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_save_conditionvalues(self) -> None: """Save the |StateSequence| and |LogSequence| object values of the current |HydPy| instance for the current simulation...
state.conditions[self._id] = state.conditions.get(self._id, {}) state.conditions[self._id][state.idx2] = state.hp.conditions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_save_parameteritemvalues(self) -> None: """Save the values of those |ChangeItem| objects which are handling |Parameter| objects."""
for item in state.parameteritems: state.parameteritemvalues[self._id][item.name] = item.value.copy()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_savedparameteritemvalues(self) -> None: """Get the previously saved values of those |ChangeItem| objects which are handling |Parameter| objects."""
dict_ = state.parameteritemvalues.get(self._id) if dict_ is None: self.GET_parameteritemvalues() else: for name, value in dict_.items(): self._outputs[name] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_save_getitemvalues(self) -> None: """Save the values of all current |GetItem| objects."""
for item in state.getitems: for name, value in item.yield_name2value(state.idx1, state.idx2): state.getitemvalues[self._id][name] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_savedgetitemvalues(self) -> None: """Get the previously saved values of all |GetItem| objects."""
dict_ = state.getitemvalues.get(self._id) if dict_ is None: self.GET_getitemvalues() else: for name, value in dict_.items(): self._outputs[name] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_save_timegrid(self) -> None: """Save the current simulation period."""
state.timegrids[self._id] = copy.deepcopy(hydpy.pub.timegrids.sim)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GET_savedtimegrid(self) -> None: """Get the previously saved simulation period."""
try: self._write_timegrid(state.timegrids[self._id]) except KeyError: self._write_timegrid(hydpy.pub.timegrids.init)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compare_variables_function_generator( method_string, aggregation_func): """Return a function usable as a comparison method for class |Variable|. Pass the sp...
def comparison_function(self, other): """Wrapper for comparison functions for class |Variable|.""" if self is other: return method_string in ('__eq__', '__le__', '__ge__') method = getattr(self.value, method_string) try: if hasattr(type(other), '__hydpy__get_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(self) -> None: """Raises a |RuntimeError| if at least one of the required values of a |Variable| object is |None| or |numpy.nan|. The descriptor `mask`...
nmbnan: int = numpy.sum(numpy.isnan( numpy.array(self.value)[self.mask])) if nmbnan: if nmbnan == 1: text = 'value has' else: text = 'values have' raise RuntimeError( f'For variable {objecttools.devicephrase...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def average_values(self, *args, **kwargs) -> float: """Average the actual values of the |Variable| object. For 0-dimensional |Variable| objects, the result of met...
try: if not self.NDIM: return self.value mask = self.get_submask(*args, **kwargs) if numpy.any(mask): weights = self.refweights[mask] return numpy.sum(weights*self[mask])/numpy.sum(weights) return numpy.nan ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_submask(self, *args, **kwargs) -> masktools.CustomMask: """Get a sub-mask of the mask handled by the actual |Variable| object based on the given arguments...
if args or kwargs: masks = self.availablemasks mask = masktools.CustomMask(numpy.full(self.shape, False)) for arg in args: mask = mask + self._prepare_mask(arg, masks) for key, value in kwargs.items(): mask = mask + self._prepare_m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commentrepr(self) -> List[str]: """A list with comments for making string representations more informative. With option |Options.reprcomments| being disabled,...
if hydpy.pub.options.reprcomments: return [f'# {line}' for line in textwrap.wrap(objecttools.description(self), 72)] return []