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 ready(self): """Auto load Trionyx"""
models_config.auto_load_configs() self.auto_load_app_modules(['layouts', 'signals']) app_menu.auto_load_model_menu() auto_register_search_models() tabs.auto_generate_missing_tabs()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auto_load_app_modules(self, modules): """Auto load app modules"""
for app in apps.get_app_configs(): for module in modules: try: import_module('{}.{}'.format(app.module.__package__, module)) except ImportError: 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 bump(match): """Bumps the version"""
before, old_version, after = match.groups() major, minor, patch = map(int, old_version.split('.')) patch += 1 if patch == 10: patch = 0 minor += 1 if minor == 10: minor = 0 major += 1 new_version = '{0}.{1}.{2}'.format(major, minor, patch) print('{0} => {1}'.format(old_version, new_version)) retur...
<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_raw(self, suffix): """ writes a the suffix prefixed by the CSI to the handle """
if not self.enabled: return self.buffer.write(CSI) self.buffer.write(suffix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_db_tables(db): """Build Seshet's basic database schema. Requires one parameter, `db` as `pydal.DAL` instance. """
if not isinstance(db, DAL) or not db._uri: raise Exception("Need valid DAL object to define tables") # event log - self-explanatory, logs all events db.define_table('event_log', Field('event_type'), Field('event_time', 'datetime'), F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_values(self, *args, **kwargs): """ Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'si...
sample_size = kwargs.get('size', self.size) f = self.instantiate_distribution_function(self.module_name, self.distribution_name) distribution_function = partial(f, *self.random_function_params, size=sample_size) if self.sample_mean_value: sample = np.full(sample_size, 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 add_scenario(self, parameter: 'Parameter', scenario_name: str = default_scenario): """ Add a scenario for this parameter. :param scenario_name: :param parame...
self.scenarios[scenario_name] = parameter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_missing_attributes_from_default_parameter(self, param): """ Empty fields in Parameter definitions in scenarios are populated with default values. E.g. i...
if not self.exists(param.name) or not ParameterScenarioSet.default_scenario in self.parameter_sets[ param.name].scenarios.keys(): logger.warning( f'No default value for param {param.name} found.') return default = self.parameter_sets[param.name][Param...
<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_by_tag(self, tag) -> Dict[str, Set[Parameter]]: """ Get all registered dicts that are registered for a tag :param tag: str - single tag :return: a dict o...
return self.tags[tag]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_parameter_definitions(self, sheet_name: str = None): """ Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets ar...
definitions = self.excel_handler.load_definitions(sheet_name, filename=self.filename) self.definition_version = self.excel_handler.version return definitions
<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, url: str) -> str: """A small wrapper method which makes a quick GET request. Parameters url : str The URL to get. Returns ------- str The raw html ...
resp = self.session.get(url, headers=self.HEADERS) if resp.status_code is 200: return resp.text else: raise RuneConnectionError(resp.status_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sys_call(cmd): """Execute cmd and capture stdout and stderr :param cmd: command to be executed :return: (stdout, stderr) """
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) return p.stdout.readlines(), p.stderr.readlines()
<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_alphanumeric_index(query_string): """ Given an input string of either int or char, returns what index in the alphabet and case it is :param query_string...
# TODO: could probably rework this. it works, but it's ugly as hell. try: return [int(query_string), 'int'] except ValueError: if len(query_string) == 1: if query_string.isupper(): return [string.ascii_uppercase.index(query_string), 'c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_numeric(val): """ Helper function for conversion of various data types into numeric representation. """
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)): return val return float(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_binop_logical(self, operation, left, right, **kwargs): """ Evaluate given logical binary operation with given operands. """
if not operation in self.binops_logical: raise ValueError("Invalid logical binary operation '{}'".format(operation)) result = self.binops_logical[operation](left, right) return bool(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 evaluate_binop_comparison(self, operation, left, right, **kwargs): """ Evaluate given comparison binary operation with given operands. """
if not operation in self.binops_comparison: raise ValueError("Invalid comparison binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_vector(self, operation, left, right): """ Calculate vector result from two list operands with given mathematical operation. """
result = [] if len(right) == 1: right = _to_numeric(right[0]) for iteml in left: iteml = _to_numeric(iteml) result.append(self.binops_math[operation](iteml, right)) elif len(left) == 1: left = _to_numeric(left[0]) f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_binop_math(self, operation, left, right, **kwargs): """ Evaluate given mathematical binary operation with given operands. """
if not operation in self.binops_math: raise ValueError("Invalid math binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (list, ListIP)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_unop(self, operation, right, **kwargs): """ Evaluate given unary operation with given operand. """
if not operation in self.unops: raise ValueError("Invalid unary operation '{}'".format(operation)) if right is None: return None return self.unops[operation](right)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate_function(self, name, decorator): """ Decorate function with given name with given decorator. :param str name: Name of the function. :param callable ...
self.functions[name] = decorator(self.functions[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 render(self, template=None, additional=None): """ Render single model to its html representation. You may set template path in render function argument, or m...
template_path = template or self.get_template_path() template_vars = {'model': self} if additional: template_vars.update(additional) rendered = render_to_string(template_path, template_vars) return mark_safe(rendered)
<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): """Execute a system command."""
if self._decode_output: # Capture and decode system output with Popen(self.command, shell=True, stdout=PIPE) as process: self._output = [i.decode("utf-8").strip() for i in process.stdout] self._success = True else: # Execute without ca...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accepts(exception=TypeError, **types): """ A wrapper of function for checking function parameters type Example 1: @accepts(a=int, b='__iter__', c=str) def te...
def check_param(v, type_or_funcname): if isinstance(type_or_funcname, tuple): results1 = [check_param(v, t) for t in type_or_funcname if t is not None] results2 = [v == t for t in type_or_funcname if t is None] return any(results1) or any(results2) is_type_inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_vimball(fd): """Test for vimball archive format compliance. Simple check to see if the first line of the file starts with standard vimball archive header....
fd.seek(0) try: header = fd.readline() except UnicodeDecodeError: # binary files will raise exceptions when trying to decode raw bytes to # str objects in our readline() wrapper return False if re.match('^" Vimball Archiver', header) is not None: 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 files(self): """Yields archive file information."""
# try new file header format first, then fallback on old for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"): header = re.compile(header) filename = None self.fd.seek(0) line = self.readline() while line: m = header.match(line) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract(self, extractdir=None, verbose=False): """Extract archive files to a directory."""
if extractdir is None: filebase, ext = os.path.splitext(self.path) if ext in ('.gz', '.bz2', '.xz'): filebase, _ext = os.path.splitext(filebase) extractdir = os.path.basename(filebase) if os.path.exists(extractdir): tempdir = tempf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ini_dump_hook(cfg, text: bool=False): """ Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it w...
data = cfg.config.dump() # Load data back into the goddamned ini file. ndict = {} for key, item in data.items(): key = key.replace('_', '.') ndict[key] = item cfg.tmpini = configparser.ConfigParser() cfg.tmpini.read_dict(data) if not text: cfg.tmpini.write(cfg.fd) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exception_message(): """Create a message with details on the exception."""
exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, 'traceback': traceback.format_exception(*exc_info)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def behavior(f): """Decorator for declaring a function as behavior. Use as:: @behavior def fun(x, y, self, msg): And create or become this behavior by passing t...
@wraps(f) def wrapper(*args): message = args[-1] if isinstance(message, MutableMapping): message = Message(message) f(*(args[:-1] + (message,))) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromtimestamp(timestamp): """Because python doesn't support negative timestamp to datetime so we have to implement my own method """
if timestamp >= 0: return datetime.fromtimestamp(timestamp) else: return datetime(1969, 12, 31, 20, 0) + timedelta(seconds=timestamp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rigid_linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis): """A datetime-version that takes datetime object list as x_axis. """
numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return rigid_linear_interpolate( numeric_datetime_axis, y_axis, numeric_datetime_new_axis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exam_reliability_by_datetime( datetime_axis, datetime_new_axis, reliable_distance): """A datetime-version that takes datetime object list as x_axis reliable_...
numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return exam_reliability(numeric_datetime_axis, numeric_datetime_new_axis, rel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_object_by_string(namespace): """Import object by complete namespace"""
segments = namespace.split('.') module = importlib.import_module('.'.join(segments[:-1])) return getattr(module, segments[-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 create_celerybeat_schedule(apps): """Create Celery beat schedule by get schedule from every installed app"""
beat_schedule = {} for app in apps: try: config = import_object_by_string(app) module = importlib.import_module('{}.cron'.format(config.name)) except Exception: try: module = importlib.import_module('{}.cron'.format(app)) except Ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_client( cls, address: Union[str, Tuple[str, int], Path] = 'localhost', port: int = 6379, db: int = 0, password: str = None, ssl: Union[bool, str, SS...
assert check_argument_types() if isinstance(address, str) and not address.startswith('/'): address = (address, port) elif isinstance(address, Path): address = str(address) client_args.update({ 'address': address, 'db': db, 'pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_word_list_mixedcase(word_list): """ Given a list of words, this function returns a new list where the words follow mixed case convention. As a reminde...
to_return, first_word = list(), True for word in word_list: if first_word: to_return.append(word.lower()) first_word = False else: to_return.append(word.capitalize()) return to_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 format_string(string_to_format, wordstyle="lowercase", separator=" "): """ Takes an un-formatted string and returns it in the desired format Acceptable forma...
# first split the string up into its constituent words words = string_to_format.split(" ") # format the individual words function_map = { "lowercase": format_word_list_lowercase, "uppercase": format_word_list_uppercase, "capitalize": format_word_list_capitalize, "mixedc...
<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_random_word(dictionary, starting_letter=None): """ Takes the dictionary to read from and returns a random word optionally accepts a starting letter """
if starting_letter is None: starting_letter = random.choice(list(dictionary.keys())) try: to_return = random.choice(dictionary[starting_letter]) except KeyError: msg = "Dictionary does not contain a word starting with '{}'" raise NoWordForLetter(msg.format(starting_letter))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_dictionary(dictionary): """ Function used to import the dictionary file into memory opened_file should be an already opened dictionary file :raises Di...
def load_into_dictionary(dictionary_file): """create the dictionary to hold the words""" to_return = dict() for line in dictionary_file: try: to_return[line[0].lower()].append(line.strip().lower()) except KeyError: to_return[line[0].lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_for_count(dictionary, count): """Create a random string of N=`count` words"""
string_to_print = "" if count is not None: if count == 0: return "" ranger = count else: ranger = 2 for index in range(ranger): string_to_print += "{} ".format(get_random_word(dictionary)) return string_to_print.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_seed(seed): """Generate seed for random number generator"""
if seed is None: random.seed() seed = random.randint(0, sys.maxsize) random.seed(a=seed) return seed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(dictionary='dictionaries/all_en_US.dict', count=None, initials=None, seed=None, wordstyle='lowercase', separator=' '): """Main processing function for n...
generate_seed(seed) # attempt to read in the given dictionary dictionary = import_dictionary(dictionary) # if count and initials are both set, let the user know what's up if count and initials: msg = "--count and --initials are mutually exclusive, using initials" logging.info(msg)...
<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_parser(): """Creates the Namespace object to be used by the rest of the tool"""
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-d', '--dictionary', nargs='?', default='dictionaries/all_en_US.dict', help='Specify a non-default word dictionary to use.') parser.add_argument('-c', '--count...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_to_db(model_text_id, parsed_values): """save to db and return saved object"""
Model = apps.get_model(model_text_id) # normalise values and separate to m2m, simple simple_fields = {} many2many_fields = {} for field, value in parsed_values.items(): if (Model._meta.get_field( field).get_internal_type() == 'ManyToManyField'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grouper(iterable, n): """ Slice up `iterable` into iterables of `n` items. :param iterable: Iterable to splice. :param n: Number of items per slice. :returns...
it = iter(iterable) while True: chunk = itertools.islice(it, n) try: first = next(chunk) except StopIteration: return yield itertools.chain([first], chunk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, dataframe): """ Takes the already cleaned dataframe, splits it into train and test and returns the train and test as numpy arrays. If the probl...
mapping = DataFrameMapCreator().get_mapping_from_config(self.__config) self.__mapper = DataFrameMapper(mapping) train, test = split_dataframe_train_test(dataframe, self.__config.get_option_parameter("split", "train_percentage")) return self.__get_correct_return_parameters(train, test)
<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_target_data(self, transformed_data, original_data): """ Picks up the target data from the original_data and appends it as a column to the transformed_d...
model = self.__config.get_data_model() target_feature = model.find_target_feature() name = target_feature.get_name() if target_feature.is_categorical(): target_row = original_data[name] target = self.__label_encoder_adapter.transform(target_row) else: ...
<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_params(method, params): """Set params to query limesurvey"""
data = {'method': method, 'params': params, 'id': str(uuid4())} return json.dumps(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_surveys(session): """retrieve a list of surveys from current user"""
params = {'sUser': session['user'], 'sSessionKey': session['token']} data = set_params('list_surveys', params) req = requests.post(session['url'], data=data, headers=headers) return req.text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Send signal to stop the current stream playback"""
self._response['shouldEndSession'] = True self._response['action']['audio']['interface'] = 'stop' self._response['action']['audio']['sources'] = [] 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 sub_path(self, path): """ If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`. """
if not self.regular_expression: return self.new_path return re.sub(self.old_path, self.new_path, path)
<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_formatter(self): """ Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default i...
if hasattr(self._config, "formatter") and self._config.formatter == "json": self._formatter = "json" else: self._formatter = "text"
<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_log_level(self): """ Inspects config and sets the log level as instance attr. If not present in config, default is "INFO". """
# set log level on logger log_level = "INFO" if hasattr(self._config, "level") and self._config.level.upper() in ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]: log_level = self._config.level.upper() self._log_level = log_level
<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_framework_logger(self): """ Creates a logger with default formatting for internal use by the CloeePy framework and its plugins. User may configure custo...
formatter = None if self._formatter == "json": formatter = CustomJsonFormatter(self.default_json_fmt) else: formatter = logging.Formatter(self.default_text_fmt) self._logger = logging.getLogger("CloeePyFramework") logHandler = logging.StreamHandler() ...
<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_application_logger(self): """ Creates a logger intended for use by applications using CloeePy. This logger is fully configurable by the user and can inc...
formatter = None if self._formatter == "json": if hasattr(self._config, "formatString"): formatter = CustomJsonFormatter(self._config.formatString) else: formatter = CustomJsonFormatter(self.default_json_fmt) else: if hasattr(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 lisFichierLexique(self, filepath): """ Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: s...
orig = int(filepath.endswith("ext.la")) lignes = lignesFichier(filepath) for ligne in lignes: self.parse_lemme(ligne, orig)
<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_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """
self.lemmatiseur._modeles[modele.gr()] = modele
<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_lemme(self, lemma): """ Register a lemma into the Lemmatiseur :param lemma: Lemma to register :return: """
if lemma.cle() not in self.lemmatiseur._lemmes: self.ajRadicaux(lemma) self.lemmatiseur._lemmes[lemma.cle()] = lemma
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_irreg(self, l): """ Constructeur de la classe Irreg. :param l: Ligne de chargement des irréguliers :type l: str """
ecl = l.split(':') grq = ecl[0] exclusif = False if grq.endswith("*"): grq = grq[:-1] exclusif = True return Irreg( graphie_accentuee=grq, graphie=atone(grq), exclusif=exclusif, morphos=listeI(ecl[2]), lemme...
<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, event, callback, single=False, priority=1): """ Add a callback to an event list so it will be run at this event's firing. If single is Tru...
event_stack = self._events[event] event_stack.append({ "callback": callback, "single": single, "priority": priority }) event_stack.sort(key=lambda x: x['priority'])
<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_listener(self, event, callback, single=None, priority=None): """ Remove the event listener matching the same signature used for adding it. This will r...
event_stack = self._events[event] for x in event_stack: if x['callback'] == callback and \ (single is None or x['single'] == single) and \ (priority is None or x['priority'] == priority): event_stack.remove(x) break else:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire_event(self, event, *args, **kwargs): """ Execute the listeners for this event passing any arguments along. """
remove = [] event_stack = self._events[event] for x in event_stack: x['callback'](*args, **kwargs) if x['single']: remove.append(x) for x in remove: event_stack.remove(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 stop(self): """Save last elapse time to self.records. """
self.elapse = time.clock() - self.st self.records.append(self.elapse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_all(self): """Print detailed information. """
print( ("total elapse %0.6f seconds, last elapse %0.6f seconds, " "took %s times measurement") % ( self.total_elapse, self.elapse, len(self.records)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_cached(html_dump): """Parse html string from cached html files. Parameters html_dump : string HTML content Returns ------- translations : list Transla...
soup = BeautifulSoup(html_dump, "html.parser") translations = [] for trans in soup.find_all("div", class_="translation"): word = tuple(t.get_text() for t in trans.select("div.word > h2")) trans_list = [] for part in trans.find_all("div", class_="part-of-speech"): pn = pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cache_lookup(word, data_dir, native=False): """Checks if word is in cache. Parameters word : str Word to check in cache. data_dir : pathlib.Path Cache direc...
trans_dir = "translations" if native: trans_dir += "_native" logger.debug("Cache lookup: %s", word) filename = data_dir.joinpath(trans_dir, "{}.html".format(word)) if filename.is_file(): with open(filename, mode="r") as f: logger.debug("Cache found: %s", word) ...
<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_words(data_dir): """Get list of words from history file. Parameters data_dir : pathlib.Path Directory where data is saved. Returns ------- word_list : l...
words_file = data_dir.joinpath("words.txt") word_list = [] if not words_file.is_file(): return word_list with open(words_file, mode="r") as f: for l in f: line = l.rstrip() word_list.append(line) return word_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 _save_to_history(word, data_dir): """Write word to history file. Parameters word : str Word to save to history. data_dir : pathlib.Path Directory where histo...
if not data_dir.exists(): logger.debug("Creating DATA DIR: %s", data_dir.as_posix()) data_dir.mkdir(parents=True) if word not in _get_words(data_dir): with open(data_dir.joinpath("words.txt"), mode="a+") as f: logger.debug("Adding to history: %s", word) f.write(w...
<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_html_file_content(translations): """Create html string out of translation dict. Parameters tralnslations : dict Dictionary of word translations. Retu...
content = [] for i1, t in enumerate(translations): if i1 > 0: content.append("<br>") content.append('<div class="translation">') content.append('<div class="word">') for w in t.word: content.append("<h2>{word}</h2>".format(word=w)) content.append(...
<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_html_file(word, translations, data_dir, native=False): """Create html file of word translations. Parameters word : str Word that was translated. traln...
content_str = _create_html_file_content(translations) html_string = HTML_TEMPLATE.replace("{% word %}", word) html_string = html_string.replace("{% content %}", content_str) trans_dir = "translations" if native: trans_dir += "_native" translations_dir = data_dir.joinpath(trans_dir) ...
<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_index_content(words): """Create html string of index file. Parameters words : list of str List of cached words. Returns ------- str html string. """
content = ["<h1>Index</h1>", "<ul>"] for word in words: content.append( '<li><a href="translations/{word}.html">{word}</a></li>'.format(word=word) ) content.append("</ul>") if not words: content.append("<i>Nothing to see here ...yet!</i>") return "\n".join(cont...
<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_index_file(data_dir): """Create index file of cached translations. Parameters data_dir : pathlib.Path Cache directory location. """
cached_words = [ w for w in _get_words(data_dir) if data_dir.joinpath("translations/{}.html".format(w)).is_file() ] content_str = _create_index_content(cached_words) html_string = HTML_TEMPLATE.replace("{% word %}", "Index") html_string = html_string.replace("{% content %}"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_file(filename, data, mk_parents=True): """Save file to disk. Paramaters filename : pathlib.Path Path to the file. data : str File contents. mk_parents :...
parent = filename.parent if not parent.exists() and mk_parents: logger.debug("Creating directory: %s", parent.as_posix()) parent.mkdir(parents=True) with open(filename, mode="w") as f: logger.debug("Saving file: %s", filename.as_posix()) f.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lookup_online(word): """Look up word on diki.pl. Parameters word : str Word too look up. Returns ------- str website HTML content. """
URL = "https://www.diki.pl/{word}" HEADERS = { "User-Agent": ( "Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; " "Trident/7.0; rv:11.0) like Gecko" ) } logger.debug("Looking up online: %s", word) quoted_word = urllib.parse.quote(word) req = urllib.re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(word, config, use_cache=True, to_eng=False): """Translate a word. Parameters word : str Word to translate. config : Config Configuration settings. ...
translation = None data_dir = Path(config["data dir"]) if use_cache: logger.debug("Checking cache: %s", word) translation = _cache_lookup(word, data_dir, native=to_eng) if translation: return translation html_dump = _lookup_online(word) try: translation = _pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_index(config): """Open index in web browser. Parameters config : Config Configuration settings. Raises ------ FileNotFoundError If index file doesn't...
browser = config["web browser"].lower() data_dir = Path(config["data dir"]) if browser in webbrowser._browsers: b = webbrowser.get(browser) else: if browser != "default": logger.warning( "Couldn't find '%s' browser. Falling back to default.", 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 wrap_text(translations, linewrap=0): """Pretty print translations. If linewrap is set to 0 disble line wrapping. Parameters translations : list List of word ...
# pylint: disable=too-many-locals def wrap(text, width=linewrap, findent=0, sindent=0, bold=False): if width == 0: text = " " * findent + text else: text = textwrap.fill( text, width=width, initial_indent=" " * findent, ...
<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_config(self): """ Read config from a file. Invalid config values will be discarded and defaults used in their place. """
_config = self.config["dikicli"] # TODO: what if file doesn't exist? if self.config_file.is_file(): logger.debug("Reading config file: %s", self.config_file.as_posix()) with open(self.config_file, mode="r") as f: self.config.read_file(f) # DI...
<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_default_config(self): """Write default config file to disk. Backs up existing configuration file. Returns ------- filename : string Path to config fil...
filename = self.config_file.as_posix() logger.info("Creating default config file: %s", filename) config_dir = self.config_file.parent if not config_dir.exists(): config_dir.mkdir(parents=True) if self.config_file.is_file(): backup = filename + ".old" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def arc_length(start_a=[0.0], end_a=[0.0], radius=0.0): '''Return Euclidean length of arc. ''' assert isinstance(start_a, list) assert isinstance(end_a, list) l_angle = len(start_a) assert l_angle > 0 assert l_angle == len(end_a) for i in start_a: assert isinstance(i, float) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_autopaginate(parser, token): """ Splits the arguments to the autopaginate tag and formats them correctly. """
split = token.split_contents() as_index = None context_var = None for i, bit in enumerate(split): if bit == 'as': as_index = i break if as_index is not None: try: context_var = split[as_index + 1] except IndexError: raise templ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linebuffered_stdout(): """ Always line buffer stdout so pipes and redirects are CLI friendly. """
if sys.stdout.line_buffering: return sys.stdout orig = sys.stdout new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors, line_buffering=True) new.mode = orig.mode return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore_broken_pipe(): """ If a shellish program has redirected stdio it is subject to erroneous "ignored" exceptions during the interpretor shutdown. This es...
for f in sys.stdin, sys.stdout, sys.stderr: try: f.close() except BrokenPipeError: 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_last_nonce(app, key, nonce): """ This method is only an example! Replace it with a real nonce database. :param str key: the public key the nonce belongs ...
if not hasattr(app, 'example_nonce_db'): # store nonces as a pair {key: lastnonce} app.example_nonce_db = {} if not key in app.example_nonce_db: app.example_nonce_db[key] = nonce return 0 else: oldnonce = copy.copy(app.example_nonce_db[key]) app.example_nonce...
<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_user_by_key(app, key): """ This method is only an example! Replace it with a real user database. :param str key: the public key the user belongs to """
if not hasattr(app, 'example_user_db'): app.example_user_db = {} if key in app.example_user_db: return app.example_user_db[key] 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 load_jws_from_request(req): """ This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, ...
current_app.logger.info("loading request with headers: %s" % req.headers) if (("content-type" in req.headers and "application/jose" in req.headers['content-type']) or ("Content-Type" in req.headers and "application/jose" in req.headers['Content-Type'])): path = urlparse.urlspl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_user_from_request(req): """ Just like the Flask.login load_user_from_request If you need to customize the user loading from your database, the FlaskBitj...
load_jws_from_request(req) if not hasattr(req, 'jws_header') or req.jws_header is None or not \ 'iat' in req.jws_payload: current_app.logger.info("invalid jws request.") return None ln = current_app.bitjws.get_last_nonce(current_app, 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 dumplist(args): """Dumps lists of files based on your criteria"""
from .query import Database db = Database() r = db.objects( protocol=args.protocol, purposes=args.purpose, model_ids=(args.client,), groups=args.group, classes=args.sclass ) output = sys.stdout if args.selftest: from bob.db.utils import null output = null() for f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkfiles(args): """Checks existence of files based on your criteria"""
from .query import Database db = Database() r = db.objects() # go through all files, check if they are available on the filesystem good = [] bad = [] for f in r: if os.path.exists(f.make_path(args.directory, args.extension)): good.append(f) else: bad.append(f) # report output ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse(args): """Returns a list of file database identifiers given the path stems"""
from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.reverse(args.path) for f in r: output.write('%d\n' % f.id) if not r: return 1 return 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 path(args): """Returns a list of fully formed paths or stems given some file id"""
from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.paths(args.id, prefix=args.directory, suffix=args.extension) for path in r: output.write('%s\n' % path) if not r: return 1 return 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 app_restart(cls): ''' Restart a frozen esky app Can also restart if the program is being run as a script passes restarted as an argument to the restarted app ''' logging.debug('In restarter') executable = sys.executable.split(os.sep)[-1] if os.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 start_client(self, host, port=5001, protocol='TCP', timeout=5, parallel=None, bandwidth=None): """iperf -D -c host -t 60 """
cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)] if not (protocol, 'UDP'): cmd.append('-u') if parallel: cmd.extend(['-P', str(parallel)]) if bandwidth: cmd.extend(['-b', '%sM' % bandwidth]) stdcode, stdout, stderr = utils.exe...
<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_language_database(): ''' Return the language to be used to search the database contents ''' lang = None language = get_language() if language: for x in settings.LANGUAGES_DATABASES: if x.upper() == language.upper(): lang = language brea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def df_string(df, percentage_columns=(), format_map=None, **kwargs): """Return a nicely formatted string for the given dataframe. Arguments --------- df : pandas...
formatters_map = {} for col, dtype in df.dtypes.iteritems(): if col in percentage_columns: formatters_map[col] = '{:,.2f} %'.format elif dtype == 'float64': formatters_map[col] = '{:,.2f}'.format if format_map: for key in format_map: formatters_ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def big_dataframe_setup(): # pragma: no cover """Sets pandas to display really big data frames."""
pd.set_option('display.max_colwidth', sys.maxsize) pd.set_option('max_colwidth', sys.maxsize) # height has been deprecated. # pd.set_option('display.height', sys.maxsize) pd.set_option('display.max_rows', sys.maxsize) pd.set_option('display.width', sys.maxsize) pd.set_option('display.colhea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def df_to_html(df, percentage_columns=None): # pragma: no cover """Return a nicely formatted HTML code string for the given dataframe. Arguments --------- df : p...
big_dataframe_setup() try: res = '<br><h2> {} </h2>'.format(df.name) except AttributeError: res = '' df.style.set_properties(**{'text-align': 'center'}) res += df.to_html(formatters=_formatters_dict( input_df=df, percentage_columns=percentage_columns )) res +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """
@wraps(All) def built(value): for validator in validators: value = validator(value) return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Any(*validators): """ Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given. ""...
@wraps(Any) def built(value): error = None for validator in validators: try: return validator(value) except Error as e: error = e raise error return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Maybe(validator): """ Wraps the given validator callable, only using it for the given value if it is not ``None``. """
@wraps(Maybe) def built(value): if value != None: return validator(value) return built