output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Maps the vars_list into a list of axis indices corresponding to the fluent scope.
Given the following Python 3 function, write the documentation def _varslist2axis(cls, fluent: 'TensorFluent', vars_list: List[str]) -> List[int]: '''Maps the `vars_list` into a list of axis indices corresponding to the `fluent` scope. Args: x: The fluent. vars_list: The...
As a Python code composer, you craft elegant and concise scripts.
def cast(self, dtype: tf.DType) -> 'TensorFluent': '''Returns a TensorFluent for the cast operation with given `dtype`. Args: dtype: The output's data type. Returns: A TensorFluent wrapping the cast operation. ''' if self.dtype == dtype: retu...
Create a Python 3 function for returning a TensorFluent for the cast operation with given dtype.
As a Python code analyst, you investigate and solve complex coding mysteries
def reshape(self, shape: tf.TensorShape) -> 'TensorFluent': '''Returns a TensorFluent for the reshape operation with given `shape`. Args: shape: The output's shape. Returns: A TensorFluent wrapping the reshape operation. ''' t = tf.reshape(self.tensor, s...
Create a Python 3 function for returning a TensorFluent for the reshape operation with given shape.
You are a Python code generator, capable of creating scripts from specifications.
def transpose(self, permutation: Optional[List[int]] = None) -> 'TensorFluent': '''Returns a TensorFluent for the transpose operation with given `permutation`. Args: permutation: The output's shape permutation. Returns: A TensorFluent wrapping the transpose operation. ...
Write a Python 3 function that can return a TensorFluent for the transpose operation with given permutation.
As a Python code composer, you craft elegant and concise scripts.
Returns the TensorFluent for the sum aggregation function.
Can you generate the documentation for the following Python 3 function def sum(self, vars_list: List[str]) -> 'TensorFluent': '''Returns the TensorFluent for the sum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFlu...
As a Python code composer, you craft elegant and concise scripts.
Returns the TensorFluent for the avg aggregation function.
Make a summary of the following Python 3 code def avg(self, vars_list: List[str]) -> 'TensorFluent': '''Returns the TensorFluent for the avg aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the avg aggr...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the TensorFluent for the prod aggregation function.
Make a summary of the following Python 3 code def prod(self, vars_list: List[str]) -> 'TensorFluent': '''Returns the TensorFluent for the prod aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the prod a...
You are a Python code architect, reviewing and designing scalable and efficient code
def maximum(self, vars_list: List[str]) -> 'TensorFluent': '''Returns the TensorFluent for the maximum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the maximum aggregation function. ''' ...
Write a Python 3 script for returning the TensorFluent for the maximum aggregation function.
As a Python code analyst, you investigate and solve complex coding mysteries
def minimum(self, vars_list: List[str]) -> 'TensorFluent': '''Returns the TensorFluent for the minimum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the minimum aggregation function. ''' ...
Can you write a function in Python 3 where it returns the TensorFluent for the minimum aggregation function.
As a Python code analyst, you investigate and solve complex coding mysteries
def forall(self, vars_list: List[str]) -> 'TensorFluent': '''Returns the TensorFluent for the forall aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the forall aggregation function. ''' ...
Write a Python 3 script to return the TensorFluent for the forall aggregation function.
As a Python code translator, you convert algorithms and pseudocode into Python.
def exists(self, vars_list: List[str]) -> 'TensorFluent': '''Returns the TensorFluent for the exists aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the exists aggregation function. ''' ...
How would you implement a function in Python 3 that returns the TensorFluent for the exists aggregation function.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a narrower list of sources.
Can you generate a brief explanation for the following Python 3 code def exclude_sources(exclude, section=False): newlist = sources.copy() if not isinstance(exclude, list): exclude = [exclude] for source in exclude: if not section: newlist.remove(source) else: ...
You are a Python code generator, capable of creating scripts from specifications.
def get_lyrics(song, l_sources=None): """ Searches for lyrics of a single song and returns a Result object with the various stats collected in the process. The optional parameter 'sources' specifies an alternative list of sources. If not present, the main list will be used. """ if l_sources...
Can you write a function in Python 3 where it searches for lyrics of a single song and returns a Result object with the lyrics and various stats collected in the process.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a list of all the lyrics of a single song in a single thread.
Make a summary of the following Python 3 code def get_lyrics_threaded(song, l_sources=None): if l_sources is None: l_sources = sources if song.lyrics and not CONFIG['overwrite']: logger.debug('%s already has embedded lyrics', song) return None runtimes = {} queue = Queue() ...
You are a Python code architect, reviewing and designing scalable and efficient code
Process a result object by finding the lyrics and saving them to the corresponding file.
Can you tell what is the following Python 3 function doing def process_result(result): found = result.source is not None if found: if hasattr(result.song, 'filename'): audiofile = eyed3.load(result.song.filename) audiofile.tag.lyrics.set(result.song.lyrics) audiofile....
As a Python code translator, you convert algorithms and pseudocode into Python.
def run(songs): """ Calls get_lyrics_threaded for a song or list of songs. """ if not hasattr(songs, '__iter__'): result = get_lyrics_threaded(songs) process_result(result) else: start = time.time() stats = run_mp(songs) end = time.time() if CONFIG['pr...
How would you code a function in Python 3 to call get_lyrics_threaded for a song or list of songs.
As a python code expert, you are capable of creating scripts from specifications.
Convert potentially a list of commands into a single string.
Here you have a function in Python 3, explain what it does def parse_setup(options: Union[List, str]) -> str: if isinstance(options, str): return options return "\n".join(options)
As a Python code composer, you craft elegant and concise scripts.
def create_scheduler_file(scheduler: str, job: Job) -> str: """Substitute values into a template scheduler file.""" logger.debug("Create Scheduler File Function") if job.scheduler_options is None: scheduler_options: Dict[str, Any] = {} else: scheduler_options = deepcopy(job.scheduler_op...
Write a Python 3 script for creating a scheduler file from a job.
You are a Python code generator, capable of creating scripts from specifications.
def initialize_state(self): """ Call this to initialize the state of the UI after everything has been connected. """ if self.__hardware_source: self.__data_item_states_changed_event_listener = self.__hardware_source.data_item_states_changed_event.listen(self.__data_item_states_changed) ...
How would you code a function in Python 3 to initialize the state of the UI.
As a python code expert, you are capable of creating scripts from specifications.
def handle_play_clicked(self): """ Call this when the user clicks the play/pause button. """ if self.__hardware_source: if self.is_playing: self.__hardware_source.stop_playing() else: self.__hardware_source.start_playing()
Create a Python 3 function for calling this when the user clicks the play button.
As a python code expert, you are capable of creating scripts from specifications.
Maps RDDL range types to TensorFlow dtypes.
Explain what the following Python 3 code does def range_type_to_dtype(range_type: str) -> Optional[tf.DType]: '''Maps RDDL range types to TensorFlow dtypes.''' range2dtype = { 'real': tf.float32, 'int': tf.int32, 'bool': tf.bool } return range2dtype[range_type]
You are a Python code generator, capable of creating scripts from specifications.
Maps python types to TensorFlow dtypes.
Explain what the following Python 3 code does def python_type_to_dtype(python_type: type) -> Optional[tf.DType]: '''Maps python types to TensorFlow dtypes.''' dtype = None if python_type == float: dtype = tf.float32 elif python_type == int: dtype = tf.int32 elif python_type == bool: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the string for the dependency type for SlurmPrinter.
Make a summary of the following Python 3 code def get_dependency_type(_type): if _type == DependencyTypes.AFTER: return 'after' elif _type == DependencyTypes.AFTER_ANY: return 'afterany' elif _type == DependencyTypes.AFTER_CORR: return 'aftercorr' elif...
As a Python code composer, you craft elegant and concise scripts.
Makes the header section for the scripts
Explain what the following Python 3 code does def get_header(): username, userid, uname = get_user_information() header = '''\ # This Slurm batch script was generated # By user: %s (%s) # On host: %s # At date: %s # Using: Pyqueue v%s ''' % (username, userid, uname, datetime.now().strftime('%a. %B %w...
As a Python code analyst, you investigate and solve complex coding mysteries
def generate(self, job): """ Generates a job submission script from a job object :param job: An instance of JobInterface :type job: pyqueue.job.JobInterface """ options = job.get_options().copy() job_name = options.pop('name', None) job_account = options...
Implement a function in Python 3 to generate a job submission script from a job object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def submit(self, job): """ Submits a given job :param job: The job to submit :type job: pyqueue.job.JobInterface """ from subprocess import Popen, PIPE script = self._printer.generate(job) process = Popen('sbatch', stdout=PIPE, stdin=PIPE, stderr=PIPE) ...
Write a Python 3 function that can submit a given job to the cluster.
As a Python code analyst, you investigate and solve complex coding mysteries
def submit(self, job): """ Submits a given job :param job: The job to submit :type job: pyqueue.job.JobInterface """ script = self._printer.generate(job) stdin, stdout, stderr = self._ssh.exec_command('sbatch') stdin.write(script) stdin.flush() ...
Create a Python 3 function to submit a given job to the remote host.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the current playing song from an mpris2 compliant player.
Here you have a function in Python 3, explain what it does def get_info_mpris2(name): # qdbus org.mpris.MediaPlayer2.<name> /org/mpris/MediaPlayer2\ # org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadat bus_name = 'org.mpris.MediaPlayer2.' + name path = '/org/mpris/MediaPlayer2' ...
You are a Python code generator, capable of creating scripts from specifications.
Get the current song from clementine.
Make a summary of the following Python 3 code def get_current_clementine(): # mpris_version 2 try: return get_info_mpris2('clementine') except DBusErrorResponse: bus_name = 'org.mpris.clementine' path = '/Player' interface = 'org.freedesktop.MediaPlayer' return dbus_g...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the current song from cmus.
Can you tell what is the following Python 3 function doing def get_current_cmus(): result = subprocess.run('cmus-remote -Q'.split(' '), check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) info = {} for line in result.stdout.decode().split('\n'): line = line.spl...
You are a Python code analyst, evaluating scripts for potential improvements.
def from_filename(cls, filename): """ Class constructor using the path to the corresponding mp3 file. The metadata will be read from this file to create the song object, so it must at least contain valid ID3 tags for artist and title. """ if not filename: logg...
Write a Python 3 script for creating a new Song object from a file.
You are a Python code analyst, evaluating scripts for potential improvements.
This method is used to construct a new Song object from a string with the artist and title.
Can you generate a brief explanation for the following Python 3 code def from_string(cls, name, separator='-', reverse=False): recv = [t.strip() for t in name.split(separator)] if len(recv) < 2: logger.error('Wrong format!') return None if reverse: title = re...
You are a Python code architect, reviewing and designing scalable and efficient code
Fetch the name of the album from lastfm.
Can you tell what is the following Python 3 function doing def fetch_album_name(self): response = get_lastfm('track.getInfo', artist=self.artist, track=self.title) if response: try: self.album = response['track']['album']['title'] ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_closest_week(self, metric_date): """ Gets the closest monday to the date provided. """ #find the offset to the closest monday days_after_monday = metric_date.isoweekday() - 1 return metric_date - datetime.timedelta(days=days_after_monday)
How would you code a function in Python 3 to get the closest monday to the provided date.
As a Python code composer, you craft elegant and concise scripts.
Get the range of days that we need to scan redis.
Make a summary of the following Python 3 code def _get_daily_date_range(self, metric_date, delta): dates = [metric_date] start_date = metric_date end_date = metric_date + delta while start_date.month < end_date.month or start_date.year < end_date.year: days_in_month = calend...
You are a Python code generator, capable of creating scripts from specifications.
def _get_weekly_date_range(self, metric_date, delta): """ Gets the range of years that we need to use as keys to get metrics from redis. """ dates = [metric_date] end_date = metric_date + delta #Figure out how many years our metric range spans spanning_years = end...
Implement a Python 3 function for getting the range of years that we need to get metrics from redis.
As a python code expert, you are capable of creating scripts from specifications.
def clear_all(self): """ Deletes all ``sandsnake`` related data from redis. .. warning:: Very expensive and destructive operation. Use with causion """ keys = self._analytics_backend.keys() for key in itertools.chain(*keys): with self._analytics...
Implement a function in Python 3 to delete all sandsnake related data from redis.
As a Python code translator, you convert algorithms and pseudocode into Python.
def track_count(self, unique_identifier, metric, inc_amt=1, **kwargs): """ Tracks a metric just by count. If you track a metric this way, you won't be able to query the metric by day, week or month. :param unique_identifier: Unique string indetifying the object this metric is for ...
Write a Python 3 function that can track a count of the object with the given unique identifier.
You are a Python code generator, capable of creating scripts from specifications.
Track a metric for a specific unique identifier for a specific date.
Can you generate the documentation for the following Python 3 function def track_metric(self, unique_identifier, metric, date=None, inc_amt=1, **kwargs): metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.Li...
As a python code expert, you are capable of creating scripts from specifications.
Get the metric for the unique_identifier segmented by day from from_date.
Can you generate the documentation for the following Python 3 function def get_metric_by_day(self, unique_identifier, metric, from_date, limit=30, **kwargs): conn = kwargs.get("connection", None) date_generator = (from_date + datetime.timedelta(days=i) for i in itertools.count()) metric_key_date...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_metric_by_week(self, unique_identifier, metric, from_date, limit=10, **kwargs): """ Returns the ``metric`` for ``unique_identifier`` segmented by week starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metr...
Can you create a Python 3 function that returns the metric for the unique_identifier segmented by week starting from from_date.
As a Python code analyst, you investigate and solve complex coding mysteries
This method returns the metric for the unique_identifier segmented by month from_date. It will retrieve the metrics for the unique_identifier starting from from_date.
Explain what the following Python 3 code does def get_metric_by_month(self, unique_identifier, metric, from_date, limit=10, **kwargs): conn = kwargs.get("connection", None) first_of_month = datetime.date(year=from_date.year, month=from_date.month, day=1) metric_key_date_range = self._get_weekly_...
As a Python code composer, you craft elegant and concise scripts.
Retrieves multiple metrics as efficiently as possible.
Can you generate the documentation for the following Python 3 function def get_metrics(self, metric_identifiers, from_date, limit=10, group_by="week", **kwargs): results = [] #validation of types: allowed_types = { "day": self.get_metric_by_day, "week": self.get_metric_by...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_count(self, unique_identifier, metric, start_date=None, end_date=None, **kwargs): """ Gets the count for the ``metric`` for ``unique_identifier``. You can specify a ``start_date`` and an ``end_date``, to only get metrics within that time range. :param unique_identifier: Unique s...
Write a Python 3 script to get the count for the metric for the unique_identifier.
As a python code expert, you are capable of creating scripts from specifications.
def get_counts(self, metric_identifiers, **kwargs): """ Retrieves a multiple metrics as efficiently as possible. :param metric_identifiers: a list of tuples of the form `(unique_identifier, metric_name`) identifying which metrics to retrieve. For example [('user:1', 'people_invited',), ...
Can you write a function in Python 3 where it retrieves a multiple metrics as efficiently as possible.
You are a Python code analyst, evaluating scripts for potential improvements.
def set_metric_by_day(self, unique_identifier, metric, date, count, sync_agg=True, update_counter=True): """ Sets the count for the ``metric`` for ``unique_identifier``. You must specify a ``date`` for the ``count`` to be set on. Useful for resetting a metric count to 0 or decrementing a metric....
Can you implement a function in Python 3 that sets the count for the metric for the unique_identifier for the given date.
You are a Python code architect, reviewing and designing scalable and efficient code
Synchronizes the metric for the given unique_identifier with the given start and end dates.
Can you generate the documentation for the following Python 3 function def sync_agg_metric(self, unique_identifier, metric, start_date, end_date): self.sync_week_metric(unique_identifier, metric, start_date, end_date) self.sync_month_metric(unique_identifier, metric, start_date, end_date)
You are a Python code analyst, evaluating scripts for potential improvements.
Synchronizes the metric for the given unique_identifier for the given start and end date.
Can you generate the documentation for the following Python 3 function def sync_week_metric(self, unique_identifier, metric, start_date, end_date): metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType...
As a Python code translator, you convert algorithms and pseudocode into Python.
Synchronizes the given metric for the given unique identifier for the given start and end date.
Make a summary of the following Python 3 code def sync_month_metric(self, unique_identifier, metric, start_date, end_date): metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types...
As a python code expert, you are capable of creating scripts from specifications.
Returns True if a string is a valid mxid.
Can you tell what is the following Python 3 function doing def is_full_mxid(user_string): if not user_string[0] == "@": return False parts = user_string[1:].split(":") localpart_chars = ascii_lowercase + digits + "._-=" if not (len(parts) == 2 and all([i in localpart_chars for i in parts[0]])): ...
You are a Python code architect, reviewing and designing scalable and efficient code
def intent(method): """Helps object methods handle MatrixRequestError. Args: method(function): Object method to be wrapped Method's object must have _handle_request_exception method that deals with specific status codes and errcodes. """ def wrapper(self, *args, **kwargs): try...
Can you write a function in Python 3 where it helps object methods handle MatrixRequestError. Args: method(function): Object method to be wrapped Method's object must have _handle_request_exception method that deals with specific status codes and errcodes.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_variables(self) -> Set[str]: """Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces. """ variables = set() for cmd in self._cmd: ...
Create a Python 3 function to find all the variables specified in a format string. This returns a list of all the variables that are not in the format string.
As a python code expert, you are capable of creating scripts from specifications.
Return a representation of the job as a bash array.
Explain what the following Python 3 code does def as_bash_array(self) -> str: return_string = "( \\\n" for command in self: return_string += '"' + str(command) + '" \\\n' return_string += ")" return return_string
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_doc(doc): """ Parse docstrings to dict, it should look like: key: value """ if not doc: return {} out = {} for s in doc.split('\n'): s = s.strip().split(':', maxsplit=1) if len(s) == 2: out[s[0]] = s[1] return out
Can you implement a function in Python 3 that parses a docstring into a dict
You are a Python code analyst, evaluating scripts for potential improvements.
Combine a list of dictionaries into a single dictionary.
Can you generate the documentation for the following Python 3 function def combine_dictionaries(dicts: List[Dict[str, Any]]) -> Dict[str, Any]: return dict(ChainMap(*dicts))
You are a Python code architect, reviewing and designing scalable and efficient code
Returns an iterator over the set of variables.
Make a summary of the following Python 3 code def iterator_zip(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: logger.debug("Yielding from zip iterator") if isinstance(variables, list): for item in variables: yield list(variable_matrix(item, parent, "zip")) else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def iterator_product(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: """Apply the product operator to a set of variables. This uses the python itertools.product iterator to combine multiple variables such that all possible combinations are generated. This is the default iterator however...
Can you create a Python 3 function that returns an iterator over the product of the given set of variables.
You are a Python code architect, reviewing and designing scalable and efficient code
This function returns an iterator over the values generated for each element of an array and puts all the values generated for each element in the list into a single list of values.
Can you generate a brief explanation for the following Python 3 code def iterator_chain(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: logger.debug("Yielding from append iterator") if not isinstance(variables, list): raise ValueError( f"Append keyword only takes a list of ar...
You are a Python code analyst, evaluating scripts for potential improvements.
Create a list of values using the numpy. arange function.
Make a summary of the following Python 3 code def iterator_arange(variables: VarType, parent: str) -> Iterable[VarMatrix]: assert parent is not None if isinstance(variables, (int, float)): yield [{parent: i} for i in np.arange(variables)] elif isinstance(variables, dict): if variables.get("...
As a Python code analyst, you investigate and solve complex coding mysteries
Cycle through a list of values a specified number of times.
Can you generate the documentation for the following Python 3 function def iterator_cycle(variables: VarType, parent: str) -> Iterable[VarMatrix]: if isinstance(variables, dict): if variables.get("times"): times = int(variables["times"]) del variables["times"] yield list...
As a Python code translator, you convert algorithms and pseudocode into Python.
def variable_matrix( variables: VarType, parent: str = None, iterator: str = "product" ) -> Iterable[Dict[str, YamlValue]]: """Process the variables into a list of the appropriate combinations. This function performs recursive processing of the input variables, creating an iterator which has all the co...
Can you write a function in Python 3 where it generates a list of the appropriate combinations of variables in the base tree tree.
As a python code expert, you are capable of creating scripts from specifications.
def uniqueify(my_list: Any) -> List[Any]: """Remove duplicate entries in a list retaining order.""" if sys.version_info >= (3, 6): # An implementation specific detail of py3.6 is the retention of order # within a dictionary. In py3.7 this becomes the documented behaviour. return list(dic...
Write a Python 3 function that can remove duplicate entries in a list retaining order.
You are a Python code architect, reviewing and designing scalable and efficient code
Generates all combinations of commands given a variable matrix.
Make a summary of the following Python 3 code def process_command(command: CommandInput, matrix: VarMatrix) -> List[Command]: assert command is not None if isinstance(command, str): command_list = [Command(command, variables=variables) for variables in matrix] elif isinstance(command, list): ...
As a python code expert, you are capable of creating scripts from specifications.
Read and parse yaml file.
Make a summary of the following Python 3 code def read_file(filename: PathLike = "experiment.yml") -> Dict[str, Any]: logger.debug("Input file: %s", filename) with open(filename, "r") as stream: structure = yaml.safe_load(stream) return structure
You are a Python code analyst, evaluating scripts for potential improvements.
Submit commands to the bash shell.
Explain what the following Python 3 code does def run_bash_jobs( jobs: Iterator[Job], directory: PathLike = Path.cwd(), dry_run: bool = False ) -> None: """Submit commands to the bash shell. This function runs the commands iteratively but handles errors in the same way as with the pbs_commands function...
As a Python code composer, you craft elegant and concise scripts.
Submit a series of jobs to a batch scheduler.
Given the following Python 3 function, write the documentation def run_scheduler_jobs( scheduler: str, jobs: Iterator[Job], directory: PathLike = Path.cwd(), basename: str = "experi", dry_run: bool = False, ) -> None: """Submit a series of commands to a batch scheduler. This takes a list of...
As a Python code translator, you convert algorithms and pseudocode into Python.
def determine_scheduler( scheduler: Optional[str], experiment_definition: Dict[str, YamlValue] ) -> str: """Determine the scheduler to use to run the jobs.""" # Scheduler value from command line has first priority if scheduler is not None: if scheduler in ["shell", "pbs", "slurm"]: ...
Implement a Python 3 function for determining the scheduler to use to run the jobs.
As a Python code translator, you convert algorithms and pseudocode into Python.
def safe_type(self, data, tree): """ Make sure that the incoming data complies with the class type we are expecting it to be. In this case, classes that inherit from this base class expect data to be of type ``list``. """ if not isinstance(data, list): name = ...
Implement a Python 3 function for making sure that the incoming data complies with the class type we expect.
As a Python code composer, you craft elegant and concise scripts.
An internal context generator.
Make a summary of the following Python 3 code def get_context(context): new_context = { 'model': context['model'], 'session': context['session'], 'user': context.get('user'), 'ignore_auth': context.get('ignore_auth', False), 'use_cache': context.get('use_cache', False), }...
You are a Python code analyst, evaluating scripts for potential improvements.
def request_uniq(func): """ return unique dict for each uwsgi request. note: won't work on non-uwsgi cases """ def _wrapped(*args, **kwargs): data = _get_request_unique_cache() return func(data, *args, **kwargs) return _wrapped
How would you implement a function in Python 3 that returns unique dict for each uwsgi request. note: won't work on non-uwsgi cases
As a python code expert, you are capable of creating scripts from specifications.
def safe_repr(obj): """ Try to get ``__name__`` first, ``__class__.__name__`` second and finally, if we can't get anything acceptable, fallback to user a ``repr()`` call. """ name = getattr(obj, '__name__', getattr(obj.__class__, '__name__')) if name == 'ndict': name = 'dict' ret...
Write a Python 3 script to return a string representation of the object.
As a python code expert, you are capable of creating scripts from specifications.
def sift(data, required_items=None): """ Receive a ``data`` object that will be in the form of a normalized structure (e.g. ``{0: {'a': 0}}``) and filter out keys that match the ``required_items``. """ required_items = required_items or [] new_data = {} for k, v in data.items(): ...
How would you implement a function in Python 3 that receives a data object that will be in the form and filter out keys that match the required_items.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a string representation of an unexpected data item.
Given the following Python 3 function, write the documentation def data_item(data): if isinstance(data, ndict): # OK, we have something that looks like {0: ('a', 'b')} # or something that is a regular dictionary # so try to return 'a' regardless of the length for item in data: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Checks an assertion argument for truth -ness. Will return True or explicitly raise AssertionError.
Make a summary of the following Python 3 code def ensure(assertion, message=None): message = message or assertion if not assertion: raise AssertionError(message) return True
As a python code expert, you are capable of creating scripts from specifications.
def fluent_shape(self) -> Sequence[int]: '''Returns a copy of the fluent shape, ignoring batch size if in batch mode.''' return tuple(self._shape.as_list()[1:] if self._batch else self._shape.as_list()[:])
Write a Python 3 script to return a copy of the fluent shape ignoring batch size if in batch mode.
As a python code expert, you are capable of creating scripts from specifications.
This function broadcasts the fluent shapes if any input is in batch mode. It broadcasts the fluent shapes if any input is in batch mode and expanding its dimensions if necessary. It outputs a tuple with new shapes.
Given the following Python 3 function, write the documentation def broadcast(cls, shape1: 'TensorFluentShape', shape2: 'TensorFluentShape') -> Tuple[Reshaping, Reshaping]: '''It broadcasts the fluent shapes if any input is in batch mode. It handles input shapes in different mode...
As a Python code composer, you craft elegant and concise scripts.
Run mpileup on given chrom and pos
Explain what the following Python 3 code does def run(bam, chrom, pos1, pos2, reffa, chr_reffa, parameters): # check for chr ref is_chr_query = chrom.startswith('chr') if is_chr_query and chr_reffa is None: chr_reffa = reffa # check bam ref type bam_header = subprocess.check_output("samtoo...
As a Python code composer, you craft elegant and concise scripts.
def execfile(fname, _globals, _locals): """ Usage: execfile('path/to/file.py', globals(), locals()) """ if os.path.exists(fname): with open(fname) as f: code = compile(f.read(), os.path.basename(fname), 'exec') exec(code, _globals, _locals) return True els...
Write a Python 3 script for executing a file and return True if it exists False otherwise
As a Python code composer, you craft elegant and concise scripts.
Create a directory with the given name.
How would you explain what the following Python 3 function does def auto_directory(rel_name): dir_name = rel_path(rel_name, check=False) if not os.path.exists(dir_name): os.makedirs(dir_name, exist_ok=True) return dir_name
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_iso8601_date(string): """ Parse an ISO 8601 date string """ # Match ISO 8601? match = _RE_ISO8601_DATE.search(string) if not match: raise ValueError('Expected ISO 8601 date') # Extract ISO 8601 components year = int(match.group('year')) month = int(match.group('mo...
How would you code a function in Python 3 to parse an ISO 8601 date string into a date object.
You are a Python code generator, capable of creating scripts from specifications.
def parse_iso8601_datetime(string): """ Parse an ISO 8601 date/time string """ # Match ISO 8601? match = _RE_ISO8601_DATETIME.search(string) if not match: raise ValueError('Expected ISO 8601 date/time') # Extract ISO 8601 components year = int(match.group('year')) month = i...
How would you implement a function in Python 3 that parses an ISO 8601 date or time string into a datetime object.
As a python code expert, you are capable of creating scripts from specifications.
def compile_initial_state(self, batch_size: Optional[int] = None) -> Sequence[tf.Tensor]: '''Returns a tuple of tensors representing the initial state fluents. Args: batch_size (Optional[int]): The batch size. Returns: Sequence[tf.Tensor]: A tuple of tensors. ''...
Create a Python 3 function for returning a tuple of tensors representing the initial state fluents.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a tuple of tensors representing the default action fluents.
Make a summary of the following Python 3 code def compile_default_action(self, batch_size: Optional[int] = None) -> Sequence[tf.Tensor]: '''Returns a tuple of tensors representing the default action fluents. Args: batch_size (int): The batch size. Returns: Sequence[tf.T...
As a python code expert, you are capable of creating scripts from specifications.
Compiles the intermediate and next state fluent CPFs given the current state and action.
Explain what the following Python 3 code does def cpfs(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], noise: Optional[Noise] = None) -> Tuple[List[TensorFluent], List[TensorFluent]]: '''Compiles the intermediate and next state fluent CPFs given the ...
You are a Python code generator, capable of creating scripts from specifications.
Compiles the reward function given the current state action and next_state.
Given the following Python 3 function, write the documentation def reward(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], next_state: Sequence[tf.Tensor]) -> tf.Tensor: '''Compiles the reward function given the current `state`, `action` and `ne...
You are a Python code analyst, evaluating scripts for potential improvements.
def compile_cpfs(self, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[Noise] = None) -> Tuple[List[CPFPair], List[CPFPair]]: '''Compiles the intermediate and next state fluent CPFs given the current `state` and `ac...
Can you implement a function in Python 3 that compiles the intermediate and next state fluent CPFs given the current state and action scope.
As a python code expert, you are capable of creating scripts from specifications.
def compile_intermediate_cpfs(self, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[Noise] = None) -> List[CPFPair]: '''Compiles the intermediate fluent CPFs given the current ...
Write a Python 3 script for compiling the intermediate fluent CPFs given the current state and action scope.
As a Python code analyst, you investigate and solve complex coding mysteries
Compiles the next state fluent CPFs given the current state and action scope.
Here you have a function in Python 3, explain what it does def compile_state_cpfs(self, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[Noise] = None) -> List[CPFPair]: '''Compiles the next state f...
You are a Python code analyst, evaluating scripts for potential improvements.
def compile_reward(self, scope: Dict[str, TensorFluent]) -> TensorFluent: '''Compiles the reward function given the fluent `scope`. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for reward evaluation. Returns: A :obj:`rddl2tf.fluent.Tenso...
Create a Python 3 function for compiling the reward function given the fluent scope.
As a Python code analyst, you investigate and solve complex coding mysteries
Compiles the state - action constraints given current state and action fluents.
Make a summary of the following Python 3 code def compile_state_action_constraints(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> List[TensorFluent]: '''Compiles the state-action constraints given current `state` and `action` fluents. Args: state (...
As a python code expert, you are capable of creating scripts from specifications.
Compiles the action preconditions given current state and action fluents.
Here you have a function in Python 3, explain what it does def compile_action_preconditions(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> List[TensorFluent]: '''Compiles the action preconditions given current `state` and `action` fluents. Args: st...
You are a Python code architect, reviewing and designing scalable and efficient code
def compile_state_invariants(self, state: Sequence[tf.Tensor]) -> List[TensorFluent]: '''Compiles the state invarints given current `state` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorF...
Write a Python 3 function that can compile the state invarints given current state fluents.
You are a Python code generator, capable of creating scripts from specifications.
Combines the action preconditions into an applicability checking op.
Given the following Python 3 function, write the documentation def compile_action_preconditions_checking(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> tf.Tensor: '''Combines the action preconditions into an applicability checking op. Args: state (...
You are a Python code analyst, evaluating scripts for potential improvements.
def compile_action_bound_constraints(self, state: Sequence[tf.Tensor]) -> Dict[str, Bounds]: '''Compiles all actions bounds for the given `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from action names to a pair of...
Can you create a Python 3 function that compiles all actions bounds for the given state.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a partial scope with non - fluents.
Explain what the following Python 3 code does def non_fluents_scope(self) -> Dict[str, TensorFluent]: '''Returns a partial scope with non-fluents. Returns: A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`. ''' if self.__dict__.get('non_fluents') is None:...
As a Python code translator, you convert algorithms and pseudocode into Python.
def state_scope(self, state_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: '''Returns a partial scope with current state-fluents. Args: state_fluents (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from state fluent names to :obj:`rddl2tf...
Write a Python 3 script for returning a partial scope with current state - fluents.
As a Python code composer, you craft elegant and concise scripts.
def action_scope(self, action_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: '''Returns a partial scope with current action-fluents. Args: action_fluents (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from action fluent names to :obj:`rddl2tf.f...
Can you create a Python 3 function that returns a partial scope with current action - fluents.
As a python code expert, you are capable of creating scripts from specifications.
Returns a partial scope with current next state - fluents.
Given the following Python 3 function, write the documentation def next_state_scope(self, next_state_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: '''Returns a partial scope with current next state-fluents. Args: next_state_fluents (Sequence[tf.Tensor]): The next state fluents. ...
As a Python code composer, you craft elegant and concise scripts.
def transition_scope(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: '''Returns the complete transition fluent scope for the current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents....
Create a Python 3 function to return the complete transition fluent scope for the current state and action fluents.
You are a Python code analyst, evaluating scripts for potential improvements.
def reward_scope(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], next_state: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: '''Returns the complete reward fluent scope for the current `state`, `action` fluents, and `next_sta...
Can you create a Python 3 function that returns the complete reward fluent scope for the current state action and next_state fluents.
You are a Python code architect, reviewing and designing scalable and efficient code