output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def loads(self, string): ''' load from a string ''' for line in string.split("\n"): if len(line) < 10: continue try: report = ish_report() report.loads(line) self._reports.append(report) except BaseException as exp: ''' don't complain TOO much ''' ...
Write a Python 3 function for loading a string into the internal list of reports
As a Python code analyst, you investigate and solve complex coding mysteries
def get_observations(self): ''' return only specific weather observations (FM types) and ignore the summary of day reports ''' return [rpt for rpt in self._reports if rpt.report_type in self.OBS_TYPES]
Can you write a function in Python 3 where it returns only specific weather observations
You are a Python code analyst, evaluating scripts for potential improvements.
def get_miles(self): ''' convert the measurement to inches ''' if self._obs_value in self.MISSING: return 'MISSING' if self._obs_units == self.METERSPERSECOND: return round(2.23694 * self._obs_value, 4)
Write a Python 3 script for converting the measurement to inches
You are a Python code generator, capable of creating scripts from specifications.
def do_pot(self): """ Sync the template with the python code. """ files_to_translate = [] log.debug("Collecting python sources for pot ...") for source_path in self._source_paths: for source_path in self._iter_suffix(path=source_path, suffix=".py"): ...
Write a Python 3 script for creating the python source files and copy them to the mo path.
You are a Python code architect, reviewing and designing scalable and efficient code
def do_po(self): """ Update all po files with the data in the pot reference file. """ log.debug("Start updating po files ...") pot_path = (self._po_path / self._basename).with_suffix(".pot") for po_dir_path in self._iter_po_dir(): po_path = (po_dir_path / self...
Write a Python 3 function for updating all the po files with the data in the pot reference file.
As a python code expert, you are capable of creating scripts from specifications.
Generate the MO files for all the po files.
Can you generate a brief explanation for the following Python 3 code def do_mo(self): log.debug("Start updating mo files ...") for po_dir_path in self._iter_po_dir(): po_path = (po_dir_path / self._basename).with_suffix(".po") lc_path = self._mo_path / po_dir_path.name / "LC_MESS...
You are a Python code architect, reviewing and designing scalable and efficient code
def run(self) -> None: """Runs the worker and consumes messages from RabbitMQ. Returns only after `shutdown()` is called. """ if self._logging_level: logging.basicConfig( level=getattr(logging, self._logging_level.upper()), format="%(levelname...
Create a Python 3 function for running the worker and consumes messages from RabbitMQ.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _process_message(self, message: amqp.Message) -> None: """Processes the message received from the queue.""" if self.shutdown_pending.is_set(): return try: if isinstance(message.body, bytes): message.body = message.body.decode() description...
Implement a function in Python 3 to process the message received from the queue.
As a Python code composer, you craft elegant and concise scripts.
Logs the time spent while running the task.
Can you generate a brief explanation for the following Python 3 code def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any: if args is None: args = () if kwargs is None: kwargs = {} start = monotonic() try: return task.apply(*args, *...
You are a Python code architect, reviewing and designing scalable and efficient code
def _shutdown_timer(self) -> None: """Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully. """ remaining = self._max_run_time - self.uptime if not self.shutdown_pending.wait(remaining): logger.warning('Run time reached zero') sel...
Implement a function in Python 3 to count down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully.
As a Python code analyst, you investigate and solve complex coding mysteries
def _handle_sighup(self, signum: int, frame: Any) -> None: """Used internally to fail the task when connection to RabbitMQ is lost during the execution of the task. """ logger.warning("Catched SIGHUP") exc_info = self._heartbeat_exc_info self._heartbeat_exc_info = None ...
Create a Python 3 function for calling by the process when the process has lost the connection to RabbitMQ.
You are a Python code architect, reviewing and designing scalable and efficient code
def configuration_get_default_folder(): """ Return the default folder where user-specific data is stored. This depends of the system on which Python is running, :return: path to the user-specific configuration data folder """ system = platform.system() if system == 'Linux': # https:/...
Can you implement a function in Python 3 that gets the default folder where user - specific data is stored.
As a python code expert, you are capable of creating scripts from specifications.
def from_locale(cls, locale): """ Create a new Language instance from a locale string :param locale: locale as string :return: Language instance with instance.locale() == locale if locale is valid else instance of Unknown Language """ locale = str(locale) if local...
Can you write a function in Python 3 where it creates a new Language instance from a locale string
You are a Python code generator, capable of creating scripts from specifications.
def from_xx(cls, xx): """ Create a new Language instance from a ISO639 string :param xx: ISO639 as string :return: Language instance with instance.xx() == xx if xx is valid else instance of UnknownLanguage """ xx = str(xx).lower() if xx is 'unknown': r...
Implement a Python 3 function for creating a new Language instance from an ISO639 string.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a new Language instance from a LanguageID string.
Can you tell what is the following Python 3 function doing def from_xxx(cls, xxx): xxx = str(xxx).lower() if xxx is 'unknown': return UnknownLanguage(xxx) try: return cls._from_xyz('LanguageID', xxx) except NotALanguageException: log.warning('Unknown L...
As a python code expert, you are capable of creating scripts from specifications.
def from_name(cls, name): """ Create a new Language instance from a name as string :param name: name as string :return: Language instance with instance.name() == name if name is valid else instance of UnknownLanguage """ name = str(name).lower() if name is 'unknow...
Implement a Python 3 function for creating a new Language instance from a name as string
You are a Python code generator, capable of creating scripts from specifications.
Private helper function to create a new Language instance from a given language key and value.
Given the following Python 3 function, write the documentation def _from_xyz(cls, xyzkey, xyzvalue): if xyzvalue == 'unknown' or xyzvalue == _('unknown'): return UnknownLanguage(xyzvalue) for lang_id, lang_data in enumerate(LANGUAGES): for data_value in lang_data[xyzkey]: ...
As a python code expert, you are capable of creating scripts from specifications.
def from_unknown(cls, value, xx=False, xxx=False, locale=False, name=False): """ Try to create a Language instance having only some limited data about the Language. If no corresponding Language is found, a NotALanguageException is thrown. :param value: data known about the language as st...
Implement a Python 3 function for trying to create a Language instance from an unknown language.
You are a Python code generator, capable of creating scripts from specifications.
Try to determine the language of a text file.
Here you have a function in Python 3, explain what it does def from_file(cls, filepath, chunk_size=None): log.debug('Language.from_file: "{}", chunk={} ...'.format(filepath, chunk_size)) with filepath.open('rb') as f: data = f.read(-1 if chunk_size is None else chunk_size) data_ascii...
As a Python code analyst, you investigate and solve complex coding mysteries
What to do when a Folder in the tree is clicked
Explain what the following Python 3 code does def onFolderTreeClicked(self, proxyIndex): if not proxyIndex.isValid(): return index = self.proxyFileModel.mapToSource(proxyIndex) settings = QSettings() folder_path = self.fileModel.filePath(index) settings.setValue('mai...
As a Python code composer, you craft elegant and concise scripts.
def send_to_queue( self, args: Tuple=(), kwargs: Dict[str, Any]={}, host: str=None, wait_result: Union[int, float]=None, message_ttl: Union[int, float]=None, ) -> Any: """ Sends a message to the queue. A worker will run ...
Create a Python 3 function to send a message to the queue.
As a Python code analyst, you investigate and solve complex coding mysteries
Return the dictionary to be sent to the queue.
Explain what the following Python 3 code does def _get_description(self, args: Tuple, kwargs: Dict[str, Any]) -> Dict[str, Any]: return { 'id': uuid1().hex, 'args': args, 'kwargs': kwargs, 'module': self._module_name, 'function': self.f.__name__, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calls the wrapped function and returns the result.
Make a summary of the following Python 3 code def apply(self, *args: Any, **kwargs: Any) -> Any: def send_signal(sig: Signal, **extra: Any) -> None: self._send_signal(sig, args=args, kwargs=kwargs, **extra) logger.debug("Applying %r, args=%r, kwargs=%r", self, args, kwargs) send_si...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the name of the wrapped function.
Explain what the following Python 3 code does def _module_name(self) -> str: name = self.f.__module__ if name == '__main__': return importer.main_module_name() return name
As a Python code analyst, you investigate and solve complex coding mysteries
Install internationalization support for the clients using the specified locale.
Can you generate a brief explanation for the following Python 3 code def i18n_install(lc=None): log.debug('i18n_install( {lc} ) called.'.format(lc=lc)) if lc is None: lc = i18n_system_locale() if lc is None: log.debug('i18n_install(): installing NullTranslations') translator = gettex...
You are a Python code architect, reviewing and designing scalable and efficient code
Return the system locale as a string
Can you generate a brief explanation for the following Python 3 code def i18n_system_locale(): log.debug('i18n_system_locale() called') lc, encoding = locale.getlocale() log.debug('locale.getlocale() = (lc="{lc}", encoding="{encoding}).'.format(lc=lc, encoding=encoding)) if lc is None: lc, encod...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculate all child locales from a locale.
Can you generate the documentation for the following Python 3 function def i18n_locale_fallbacks_calculate(lc): log.debug('i18n_locale_fallbacks_calculate( locale="{locale}" ) called'.format(locale=lc)) locales = [] lc_original = lc while lc: locales.append(lc) rindex = max([lc.rfind(sep...
As a python code expert, you are capable of creating scripts from specifications.
def i18n_support_locale(lc_parent): """ Find out whether lc is supported. Returns all child locales (and eventually lc) which do have support. :param lc_parent: Locale for which we want to know the child locales that are supported :return: list of supported locales """ log.debug('i18n_support_lo...
Write a Python 3 function for finding out whether a locale is supported by the given locale.
You are a Python code generator, capable of creating scripts from specifications.
Get path to the internationalization data.
Can you tell what is the following Python 3 function doing def i18n_get_path(): local_locale_path = client_get_path() / 'locale' if platform.system() == 'Linux': if local_locale_path.exists(): return local_locale_path else: return Path('/usr/share/locale') else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def i18n_get_supported_locales(): """ List all locales that have internationalization data for this program :return: List of locales """ locale_path = i18n_get_path() log.debug('Scanning translation files .mo in locale path: {}'.format(locale_path)) langs = [] mo_file = '{project}.mo'.fo...
Implement a Python 3 function for returning a list of all locales that have internationalization data for this program
You are a Python code architect, reviewing and designing scalable and efficient code
Load values from an object.
Explain what the following Python 3 code does def from_object(self, obj: Union[str, Any]) -> None: if isinstance(obj, str): obj = importer.import_object_str(obj) for key in dir(obj): if key.isupper(): value = getattr(obj, key) self._setattr(key, v...
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_dict(self, d: Dict[str, Any]) -> None: """Load values from a dict.""" for key, value in d.items(): if key.isupper(): self._setattr(key, value) logger.info("Config is loaded from dict: %r", d)
Write a Python 3 function that can load values from a dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def from_pyfile(self, filename: str) -> None: """Load values from a Python file.""" globals_ = {} # type: Dict[str, Any] locals_ = {} # type: Dict[str, Any] with open(filename, "rb") as f: exec(compile(f.read(), filename, 'exec'), globals_, locals_) for key, value ...
Write a Python 3 script to load values from a Python file.
You are a Python code analyst, evaluating scripts for potential improvements.
def from_env_vars(self) -> None: """Load values from environment variables. Keys must start with `KUYRUK_`.""" for key, value in os.environ.items(): if key.startswith('KUYRUK_'): key = key[7:] if hasattr(Config, key): try: ...
Write a Python 3 script to load values from environment variables.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns True if node is a method call for method_name.
Given the following Python 3 function, write the documentation def is_method_call(node, method_name): if not isinstance(node, nodes.Call): return False if isinstance(node.node, nodes.Getattr): # e.g. foo.bar() method = node.node.attr elif isinstance(node.node, nodes.Name): ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns True is node is a loop helper e. g. loop. index or loop. first
Here you have a function in Python 3, explain what it does def is_loop_helper(node): return hasattr(node, 'node') and isinstance(node.node, nodes.Name) and node.node.name == 'loop'
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_output(self): """ Returns the generated JavaScript code. Returns: str """ # generate the JS function string template_function = TEMPLATE_WRAPPER.format( function_name=self.js_function_name, template_code=self.output.getvalue() ...
Implement a function in Python 3 to return the generated JavaScript code.
As a python code expert, you are capable of creating scripts from specifications.
Returns the variable name assigned to the given dependency.
Explain what the following Python 3 code does def _get_depencency_var_name(self, dependency): for dep_path, var_name in self.dependencies: if dep_path == dependency: return var_name
As a python code expert, you are capable of creating scripts from specifications.
def _add_dependency(self, dependency, var_name=None): """ Adds the given dependency and returns the variable name to use to access it. If `var_name` is not given then a random one will be created. Args: dependency (str): var_name (str, optional): Returns...
Can you write a function in Python 3 where it adds the given dependency and returns the variable name to use to access it.
You are a Python code generator, capable of creating scripts from specifications.
def _process_extends(self, node, **kwargs): """ Processes an extends block e.g. `{% extends "some/template.jinja" %}` """ # find all the blocks in this template for b in self.ast.find_all(nodes.Block): # if not already in `child_blocks` then this is the first time a...
Implement a function in Python 3 to process an extends block e. g. some. template. jinja
As a Python code composer, you craft elegant and concise scripts.
Processes a block e. g. my_block endblock
Can you tell what is the following Python 3 function doing def _process_block(self, node, **kwargs): # check if this node already has a 'super_block' attribute if not hasattr(node, 'super_block'): # since it doesn't it must be the last block in the inheritance chain node.super_...
You are a Python code architect, reviewing and designing scalable and efficient code
Processes an output node which will contain things like Name and TemplateData nodes.
Make a summary of the following Python 3 code def _process_output(self, node, **kwargs): for n in node.nodes: self._process_node(n, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
def _process_templatedata(self, node, **_): """ Processes a `TemplateData` node, this is just a bit of as-is text to be written to the output. """ # escape double quotes value = re.sub('"', r'\\"', node.data) # escape new lines value = re.sub('\n', r'\\n...
Write a Python 3 function that can process a TemplateData node.
You are a Python code architect, reviewing and designing scalable and efficient code
Processes a Name node.
Given the following Python 3 function, write the documentation def _process_name(self, node, **kwargs): with self._interpolation(): with self._python_bool_wrapper(**kwargs): if node.name not in self.stored_names and node.ctx != 'store': self.output.write(self.co...
As a python code expert, you are capable of creating scripts from specifications.
Processes a GetAttr node. e. g. foo. bar.
Make a summary of the following Python 3 code def _process_getattr(self, node, **kwargs): with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: if is_loop_helper(node): self._process_loop_helper(node, **new_kwargs) el...
You are a Python code architect, reviewing and designing scalable and efficient code
def _process_getitem(self, node, **kwargs): """ Processes a `GetItem` node e.g. {{ foo["bar"] }} """ with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: self._process_node(node.node, **new_kwargs) if isinstance...
Write a Python 3 script to process a GetItem node e. g. foo. bar.
You are a Python code generator, capable of creating scripts from specifications.
Processes a for loop. e. g. for loops.
Can you tell what is the following Python 3 function doing def _process_for(self, node, **kwargs): # since a for loop can introduce new names into the context # we need to remember the ones that existed outside the loop previous_stored_names = self.stored_names.copy() with self._execut...
As a Python code analyst, you investigate and solve complex coding mysteries
Processes a math node e. g. Div Sub Add Mul etc...
Can you generate a brief explanation for the following Python 3 code def _process_math(self, node, math_operator=None, function=None, **kwargs): with self._interpolation(): if function: self.output.write(function) self.output.write('(') self._process_nod...
As a Python code analyst, you investigate and solve complex coding mysteries
Processes a loop helper e. g. loop. first or loop. last.
Can you tell what is the following Python 3 function doing def _process_loop_helper(self, node, **kwargs): if node.attr == LOOP_HELPER_INDEX: self.output.write('(arguments[1] + 1)') elif node.attr == LOOP_HELPER_INDEX_0: self.output.write('arguments[1]') elif node.attr =...
As a Python code composer, you craft elegant and concise scripts.
Context manager for executing some JavaScript inside a template.
Given the following Python 3 function, write the documentation def _execution(self): did_start_executing = False if self.state == STATE_DEFAULT: did_start_executing = True self.state = STATE_EXECUTING def close(): if did_start_executing and self.state == ST...
You are a Python code architect, reviewing and designing scalable and efficient code
Context manager for creating scoped variables defined by the nodes in nodes_list.
How would you explain what the following Python 3 function does def _scoped_variables(self, nodes_list, **kwargs): tmp_vars = [] for node in nodes_list: is_assign_node = isinstance(node, nodes.Assign) name = node.target.name if is_assign_node else node.name # creat...
As a Python code translator, you convert algorithms and pseudocode into Python.
def download_raw(url, local_path, callback): """ Download an url to a local file. :param url: url of the file to download :param local_path: path where the downloaded file should be saved :param callback: instance of ProgressCallback :return: True is succeeded """ log.debug('download_raw...
Write a Python 3 function for downloading an url to a local file.
As a Python code composer, you craft elegant and concise scripts.
def get_report_hook(self): """ Return a callback function suitable for using reporthook argument of urllib(.request).urlretrieve :return: function object """ def report_hook(chunkNumber, chunkSize, totalSize): if totalSize != -1 and not self._callback.range_initialize...
Write a Python 3 script to return a callback function suitable for using reporthook argument of urllib. request. urlretrieve
As a python code expert, you are capable of creating scripts from specifications.
def set_range(self, minimum, maximum): """ Set a range. The range is passed unchanged to the rangeChanged member function. :param minimum: minimum value of the range (None if no percentage is required) :param maximum: maximum value of the range (None if no percentage is required)...
Can you write a function in Python 3 where it sets the minimum and maximum value of the cache entry.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_child_progress(self, parent_min, parent_max): """ Create a new child ProgressCallback. Minimum and maximum values of the child are mapped to parent_min and parent_max of this parent ProgressCallback. :param parent_min: minimum value of the child is mapped to parent_min of this pa...
Create a Python 3 function for creating a new child ProgressCallback instance.
As a Python code composer, you craft elegant and concise scripts.
def update(self, value, *args, **kwargs): """ Call this function to inform that an update is available. This function does NOT call finish when value == maximum. :param value: The current index/position of the action. (Should be, but must not be, in the range [min, max]) :param a...
Write a Python 3 function that can call this function to inform that an update is available. This function does NOT call finish when value == maximum. :param value: The current index/position of the action. (Should be, but must not be, in the range [min, max]) :param args: extra positional arguments to pass on :param k...
You are a Python code generator, capable of creating scripts from specifications.
def finish(self, *args, **kwargs): """ Call this function to inform that the operation is finished. :param args: extra positional arguments to pass on :param kwargs: extra keyword arguments to pass on """ log.debug('finish(args={args}, kwargs={kwargs})'.format(args=args, ...
Implement a Python 3 function for calling this function to inform that the operation is finished.
You are a Python code analyst, evaluating scripts for potential improvements.
Informs the parent of progress.
Make a summary of the following Python 3 code def on_update(self, value, *args, **kwargs): parent_value = self._parent_min if self._max != self._min: sub_progress = (value - self._min) / (self._max - self._min) parent_value = self._parent_min + sub_progress * (self._parent_max - ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _login(self, username="", password=""): """Login to the Server using username/password, empty parameters means an anonymously login Returns True if login sucessful, and False if not. """ self.log.debug("----------------") self.log.debug("Logging in (username: %s)..." ...
Create a Python 3 function for logging-in to the Server using username and password. Returns True if successful and False if not.
As a Python code composer, you craft elegant and concise scripts.
Logout from current session
Can you generate a brief explanation for the following Python 3 code def _logout(self): self.log.debug("Logging out from session ID: %s" % self._token) try: info = self._xmlrpc_server.LogOut(self._token) self.log.debug("Logout ended in %s with status: %s" % ...
You are a Python code analyst, evaluating scripts for potential improvements.
def parse_arguments(args=None): """ Parse the program arguments. :return: argparse.Namespace object with the parsed arguments """ parser = get_argument_parser() # Autocomplete arguments autocomplete(parser) ns = parser.parse_args(args=args) return ArgumentSettings( program=...
Create a Python 3 function for parsing the program arguments.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns an argument parser that can parse program arguments.
How would you explain what the following Python 3 function does def get_argument_parser(): parser = argparse.ArgumentParser(description=project.get_description(), epilog=_('Visit us at {website}.').format(website=project.WEBSITE_MAIN)) parser.add_argument('--version', actio...
As a Python code analyst, you investigate and solve complex coding mysteries
def task(self, queue: str = 'kuyruk', **kwargs: Any) -> Callable: """ Wrap functions with this decorator to convert them to *tasks*. After wrapping, calling the function will send a message to a queue instead of running the function. :param queue: Queue name for the tasks. ...
Implement a function in Python 3 to wrap functions with this decorator to convert them to *tasks*. After wrapping, calling the function will send a message to a queue instead of running the function. :param queue: Queue name for the tasks. :param kwargs: Keyword arguments will be passed to :class:`~kuyruk.Task` constru...
You are a Python code generator, capable of creating scripts from specifications.
def channel(self) -> Iterator[amqp.Channel]: """Returns a new channel from a new connection as a context manager.""" with self.connection() as conn: ch = conn.channel() logger.info('Opened new channel') with _safe_close(ch): yield ch
Implement a Python 3 function for returning a new channel from a new connection as a context manager.
You are a Python code generator, capable of creating scripts from specifications.
Returns an iterator over the connection to RabbitMQ.
Here you have a function in Python 3, explain what it does def connection(self) -> Iterator[amqp.Connection]: TCP_USER_TIMEOUT = 18 # constant is available on Python 3.6+. socket_settings = {TCP_USER_TIMEOUT: self.config.TCP_USER_TIMEOUT} if sys.platform.startswith('darwin'): del s...
You are a Python code architect, reviewing and designing scalable and efficient code
Scan the videopath string for video files and return a tuple with list of videos and list of subtitles that match the video files.
Can you tell what is the following Python 3 function doing def scan_videopath(videopath, callback, recursive=False): log.debug('scan_videopath(videopath="{videopath}", recursive={recursive})'.format( videopath=videopath, recursive=recursive)) if not videopath.exists(): log.debug('"{videopath}" d...
As a Python code analyst, you investigate and solve complex coding mysteries
Scan a folder for videos and subtitles.
Make a summary of the following Python 3 code def __scan_folder(folder_path, callback, recursive=False): log.debug('__scan_folder(folder_path="{folder_path}", recursive={recursive})'.format(folder_path=folder_path, recursive=re...
As a Python code analyst, you investigate and solve complex coding mysteries
def merge_path_subvideo(path_subvideos, callback): """ Merge subtitles into videos. :param path_subvideos: a dict with paths as key and a list of lists of videos and subtitles :param callback: Instance of ProgressCallback :return: tuple with list of videos and list of subtitles (videos have matched ...
Can you implement a function in Python 3 that merges subtitles into videos.
You are a Python code analyst, evaluating scripts for potential improvements.
Filter the files in buckets according to extension_lists.
Can you generate the documentation for the following Python 3 function def filter_files_extensions(files, extension_lists): log.debug('filter_files_extensions: files="{}"'.format(files)) result = [[] for _ in extension_lists] for file in files: ext = file.suffix[1:].lower() for ext_i, ext_li...
You are a Python code analyst, evaluating scripts for potential improvements.
Detect the language of a filename.
Can you generate the documentation for the following Python 3 function def detect_language_filename(cls, filename): log.debug('detect_language(filename="{}") ...'.format(filename)) root, _ = os.path.splitext(filename) fn_lang = cls.DETECT_LANGUAGE_REGEX.findall(root) if fn_lang: ...
As a Python code composer, you craft elegant and concise scripts.
Detect whether the filename of videofile matches with this SubtitleFile.
Given the following Python 3 function, write the documentation def matches_video_filename(self, video): vid_fn = video.get_filename() vid_base, _ = os.path.splitext(vid_fn) vid_base = vid_base.lower() sub_fn = self.get_filename() sub_base, _ = os.path.splitext(sub_fn) s...
As a python code expert, you are capable of creating scripts from specifications.
def logging_file_install(path): """ Install logger that will write to file. If this function has already installed a handler, replace it. :param path: path to the log file, Use None for default file location. """ if path is None: path = configuration_get_default_folder() / LOGGING_DEFAULTNAM...
Write a Python 3 script to install logger that will write to file.
You are a Python code generator, capable of creating scripts from specifications.
Installs a stream handler that will output to stderr.
Here you have a function in Python 3, explain what it does def logging_stream_install(loglevel): formatter = logging.Formatter(LOGGING_FORMAT) logger = logging.getLogger() logger.removeHandler(LOGGING_HANDLERS['stream']) if loglevel == LOGGING_LOGNOTHING: streamHandler = None else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def parseFromDelimitedString(obj, buf, offset=0): """ Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consu...
How would you code a function in Python 3 to parse a TLE string into an object.
You are a Python code architect, reviewing and designing scalable and efficient code
Writes a unicode object to a delimited string.
Can you generate a brief explanation for the following Python 3 code def writeToDelimitedString(obj, stream=None): if stream is None: stream = BytesIO() _EncodeVarint(stream.write, obj.ByteSize(), True) stream.write(obj.SerializeToString()) return stream
You are a Python code architect, reviewing and designing scalable and efficient code
Converts a Sentence protobuf to a string from its tokens.
How would you explain what the following Python 3 function does def to_text(sentence): text = "" for i, tok in enumerate(sentence.token): if i != 0: text += tok.before text += tok.word return text
As a python code expert, you are capable of creating scripts from specifications.
def showMessage(self, message, *args): """ Public method to show a message in the bottom part of the splashscreen. @param message message to be shown (string or QString) """ QSplashScreen.showMessage( self, message, Qt.AlignBottom | Qt.AlignRight | Qt.AlignAbsolute, ...
Write a Python 3 function for showing a message in the bottom part of the splash screen.
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_path(path): """ Parse a video at filepath, using pymediainfo framework. :param path: path of video to parse as string """ import pymediainfo metadata = Metadata() log.debug('pymediainfo: parsing "{path}" ...'.format(path=path)) parseRes = pymedi...
Write a Python 3 function for parsing a video at a given path and return a Metadata object.
You are a Python code generator, capable of creating scripts from specifications.
Get size of this VideoFile in bytes
Make a summary of the following Python 3 code def get_size(self): if self._size is None: self._size = self._filepath.stat().st_size return self._size
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_osdb_hash(self): """ Get the hash of this local videofile :return: hash as string """ if self._osdb_hash is None: self._osdb_hash = self._calculate_osdb_hash() return self._osdb_hash
Implement a function in Python 3 to get the hash of this local videofile
You are a Python code analyst, evaluating scripts for potential improvements.
Calculate OSDB hash of this VideoFile
Make a summary of the following Python 3 code def _calculate_osdb_hash(self): log.debug('_calculate_OSDB_hash() of "{path}" ...'.format(path=self._filepath)) f = self._filepath.open(mode='rb') file_size = self.get_size() longlong_format = 'Q' # unsigned long long little endian ...
You are a Python code analyst, evaluating scripts for potential improvements.
def import_module(name: str) -> ModuleType: """Import module by it's name from following places in order: - main module - current working directory - Python path """ logger.debug("Importing module: %s", name) if name == main_module_name(): return main_module return import...
Write a Python 3 script to import a module by its name.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns main module and module name pair.
Explain what the following Python 3 code does def main_module_name() -> str: if not hasattr(main_module, '__file__'): # running from interactive shell return None main_filename = os.path.basename(main_module.__file__) module_name, ext = os.path.splitext(main_filename) return module_name
You are a Python code analyst, evaluating scripts for potential improvements.
Write the file - like src_file object to the string destination_path
Here you have a function in Python 3, explain what it does def write_stream(src_file, destination_path): with open(destination_path, 'wb') as destination_file: shutil.copyfileobj(fsrc=src_file, fdst=destination_file)
As a Python code composer, you craft elegant and concise scripts.
def build_dirs(files): ''' Build necessary directories based on a list of file paths ''' for i in files: if type(i) is list: build_dirs(i) continue else: if len(i['path']) > 1: addpath = os.path.join(os.getcwd(), *i['path'][:-1]) ...
Can you create a Python 3 function that builds necessary directories based on a list of file paths
You are a Python code analyst, evaluating scripts for potential improvements.
def get_want_file_pos(file_list): ''' Ask the user which files in file_list he or she is interested in. Return indices for the files inside file_list ''' want_file_pos = [] print '\nFiles contained:\n' for i in file_list: print(os.path.join(*i['path'])) while 1: all_answe...
Can you create a Python 3 function that asks the user which files in file_list he or she is interested in. Return indices for the files in file_list
As a Python code composer, you craft elegant and concise scripts.
def get_file_starts(file_list): ''' Return the starting position (in bytes) of a list of files by iteratively summing their lengths ''' starts = [] total = 0 for i in file_list: starts.append(total) total += i['length'] print starts return starts
Write a Python 3 script to return the starting position of a list of files by iteratively summing their lengths
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve the index of the rightmost element in a file list.
Can you tell what is the following Python 3 function doing def get_rightmost_index(byte_index=0, file_starts=[0]): ''' Retrieve the highest-indexed file that starts at or before byte_index. ''' i = 1 while i <= len(file_starts): start = file_starts[-i] if start <= byte_index: ...
As a python code expert, you are capable of creating scripts from specifications.
Returns the next wanted file in the user s list of wanted files.
Can you generate the documentation for the following Python 3 function def get_next_want_file(self, byte_index, block): ''' Returns the leftmost file in the user's list of wanted files (want_file_pos). If the first file it finds isn't in the list, it will keep searching until the length ...
You are a Python code generator, capable of creating scripts from specifications.
def vis_init(self): ''' Sends the state of the BTC at the time the visualizer connects, initializing it. ''' init_dict = {} init_dict['kind'] = 'init' assert len(self.want_file_pos) == len(self.heads_and_tails) init_dict['want_file_pos'] = self.want_file_p...
How would you implement a function in Python 3 that sends the state of the BTC at the time the visualizer connects and initializing it.
As a Python code translator, you convert algorithms and pseudocode into Python.
def broadcast(self, data_dict): ''' Send to the visualizer (if there is one) or enqueue for later ''' if self.vis_socket: self.queued_messages.append(data_dict) self.send_all_updates()
How would you code a function in Python 3 to send a message to the visualizer or enqueue for later ArcGIS
As a python code expert, you are capable of creating scripts from specifications.
Builds the payload that will be sent in tracker_request
Explain what the following Python 3 code does def build_payload(self): ''' Builds the payload that will be sent in tracker_request ''' payload = {} hashed_info = hashlib.sha1(tparser.bencode(self.torrent_dict['info'])) self.hash_string = hashed_info.digest() self....
You are a Python code generator, capable of creating scripts from specifications.
def tracker_request(self): ''' Sends the initial request to the tracker, compiling list of all peers announcing to the tracker ''' assert self.torrent_dict['info'] payload = self.build_payload() if self.torrent_dict['announce'].startswith('udp'): rai...
Write a Python 3 function that can send the initial request to the tracker
As a Python code composer, you craft elegant and concise scripts.
def get_peer_ips(self): ''' Generates list of peer IPs from tracker response. Note: not all of these IPs might be good, which is why we only init peer objects for the subset that respond to handshake ''' presponse = [ord(i) for i in self.tracker_response['peers']] ...
Implement a Python 3 function for generating list of peer IPs from tracker response.
As a Python code analyst, you investigate and solve complex coding mysteries
This function is called by the peer_ip_list method to create new I objects.
How would you explain what the following Python 3 function does def handshake_peers(self): ''' pstrlen = length of pstr as one byte pstr = BitTorrent protocol reserved = chr(0)*8 info_hash = 20-byte hash above (aka self.hash_string) peer_id = 20-byte string ''' ...
You are a Python code generator, capable of creating scripts from specifications.
def initpeer(self, sock): ''' Creates a new peer object for a nvalid socket and adds it to reactor's listen list ''' location_json = requests.request("GET", "http://freegeoip.net/json/" + sock.getpeername()[0]).content location = j...
Can you create a Python 3 function that creates a new peer object for a nvalid socket and adds it to reactor s select list
As a Python code translator, you convert algorithms and pseudocode into Python.
Read a new entry from the switchboard.
Given the following Python 3 function, write the documentation def read(self): try: bytes = self.sock.recv(self.max_size) except: self.torrent.kill_peer(self) return ''' Chain of events: - process_input - check save_state and re...
As a Python code analyst, you investigate and solve complex coding mysteries
Process a piece that we ve received from a peer writing it out to a new file and one or more files.
How would you explain what the following Python 3 function does def ppiece(self, content): ''' Process a piece that we've received from a peer, writing it out to one or more files ''' piece_index, byte_begin = struct.unpack('!ii', content[0:8]) # TODO -- figure out a bet...
You are a Python code generator, capable of creating scripts from specifications.
def is_connected(self): """ Returns the connection status of the data store. Returns: bool: ``True`` if the data store is connected to the MongoDB server. """ if self._client is not None: try: self._client.server_info() except Connecti...
Create a Python 3 function to return the connection status of the data store.
As a Python code composer, you craft elegant and concise scripts.
Establishes a connection to the MongoDB server.
Can you generate a brief explanation for the following Python 3 code def connect(self): mongodb_args = { 'host': self.host, 'port': self.port, 'username': self._username, 'password': self._password, 'authSource': self._auth_source, 'serverS...
You are a Python code analyst, evaluating scripts for potential improvements.