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 fromexcel(cls, path, sheet_name_or_num=0, headers=None): """ Constructs a new DataTable from an Excel file. Specify sheet_name_or_number to load that specific sheet. Headers will be inferred automatically, but if you'd prefer to load only a subset of all the headers, pass in a list of the headers you'd like as `headers`. --- Alternatively, it's quite simple to: reader = ExcelReader('myfile.xls') reader.change_sheet('default') data = DataTable(reader) """
reader = ExcelRW.UnicodeDictReader(path, sheet_name_or_num) return cls(reader, headers=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __print_table(self, row_delim, header_delim=None, header_pad=u"", pad=u""): """ row_delim default delimiter inserted between columns of every row in the table. header_delim delimiter inserted within the headers. by default takes the value of `row_delim` header_pad put on the sides of the row of headers. pad put on the sides of every row. """
if header_delim is None: header_delim = row_delim num_cols = len(self.fields) accumulator = ((u"%s" + header_delim) * num_cols)[:-len(header_delim)] accumulator = ((header_pad + accumulator + header_pad + u"\n") % tuple(self.fields)) for datarow in self: rowstring = ((u"%s" + row_delim) * num_cols)[:-len(row_delim)] rowstring = (pad + rowstring + pad + u"\n") % tuple(datarow) accumulator += rowstring return accumulator[:-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 apply(self, func, *fields): """ Applies the function, `func`, to every row in the DataTable. If no fields are supplied, the entire row is passed to `func`. If fields are supplied, the values at all of those fields are passed into func in that order. --- data['diff'] = data.apply(short_diff, 'old_count', 'new_count') """
results = [] for row in self: if not fields: results.append(func(row)) else: if any(field not in self for field in fields): for field in fields: if field not in self: raise Exception("Column `%s` does not exist " "in DataTable" % field) results.append(func(*[row[field] for field in fields])) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def col(self, col_name_or_num): """ Returns the col at index `colnum` or name `colnum`. """
if isinstance(col_name_or_num, basestring): return self[col_name_or_num] elif isinstance(col_name_or_num, (int, long)): if col_name_or_num > len(self.fields): raise IndexError("Invalid column index `%s` for DataTable" % col_name_or_num) return self.__data[self.fields[col_name_or_num]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distinct(self, fieldname, key=None): """ Returns the unique values seen at `fieldname`. """
return tuple(unique_everseen(self[fieldname], key=key))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mask(self, masklist): """ `masklist` is an array of Bools or equivalent. This returns a new DataTable using only the rows that were True (or equivalent) in the mask. """
if not hasattr(masklist, '__len__'): masklist = tuple(masklist) if len(masklist) != len(self): raise Exception("Masklist length (%s) must match length " "of DataTable (%s)" % (len(masklist), len(self))) new_datatable = DataTable() for field in self.fields: new_datatable[field] = list(compress(self[field], masklist)) return new_datatable
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutapply(self, function, fieldname): """ Applies `function` in-place to the field name specified. In other words, `mutapply` overwrites column `fieldname` ith the results of applying `function` to each element of that column. """
self[fieldname] = self.apply(function, fieldname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(self, old_fieldname, new_fieldname): """ Renames a specific field, and preserves the underlying order. """
if old_fieldname not in self: raise Exception("DataTable does not have field `%s`" % old_fieldname) if not isinstance(new_fieldname, basestring): raise ValueError("DataTable fields must be strings, not `%s`" % type(new_fieldname)) if old_fieldname == new_fieldname: return new_names = self.fields location = new_names.index(old_fieldname) del new_names[location] new_names.insert(location, new_fieldname) self.fields = new_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reorder(self, fields_in_new_order): """ Pass in field names in the order you wish them to be swapped. """
if not len(fields_in_new_order) == len(self.fields): raise Exception("Fields to reorder with are not the same length " "(%s) as the original fields (%s)" % (len(fields_in_new_order), len(self.fields))) if not set(fields_in_new_order) == set(self.fields): raise Exception("Fields to reorder with should be the same " "as the original fields") new = OrderedDict() for field in fields_in_new_order: new[field] = self.__data[field] self.__data = 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 sample(self, num): """ Returns a new table with rows randomly sampled. We create a mask with `num` True bools, and fill it with False bools until it is the length of the table. We shuffle it, and apply that mask to the table. """
if num > len(self): return self.copy() elif num < 0: raise IndexError("Cannot sample a negative number of rows " "from a DataTable") random_row_mask = ([True] * num) + ([False] * (len(self) - num)) shuffle(random_row_mask) sampled_table = self.mask(random_row_mask) random_col_name = 'random_sorting_column' while random_col_name in sampled_table: random_col_name = '%030x' % randrange(16**30) sampled_table[random_col_name] = [random() for _ in xrange(len(sampled_table))] sampled_table.sort(random_col_name, inplace=True) del sampled_table[random_col_name] return sampled_table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, *cols): """ Returns DataTable with a subset of columns in this table """
return DataTable([cols] + zip(*[self[col] for col in cols]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self, fieldname, key=lambda x: x, desc=False, inplace=False): """ This matches Python's built-in sorting signature closely. By default, a new DataTable will be returned and the original will not be mutated. If preferred, specify `inplace=True` in order to mutate the original table. Either way, a reference to the relevant table will be returned. """
try: field_index = tuple(self.fields).index(fieldname) except ValueError: raise ValueError("Sorting on a field that doesn't exist: `%s`" % fieldname) data_cols = izip(*sorted(izip(*[self.__data[field] for field in self.fields]), key=lambda row: key(row[field_index]), reverse=desc)) target_table = self if inplace else DataTable() for field, data_col in izip(self.fields, data_cols): target_table[field] = list(data_col) # Note that sorting in-place still returns a reference # to the table being sorted, for convenience. return target_table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where(self, fieldname, value, negate=False): """ Returns a new DataTable with rows only where the value at `fieldname` == `value`. """
if negate: return self.mask([elem != value for elem in self[fieldname]]) else: return self.mask([elem == value for elem in self[fieldname]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wheregreater(self, fieldname, value): """ Returns a new DataTable with rows only where the value at `fieldname` > `value`. """
return self.mask([elem > value for elem in self[fieldname]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def whereless(self, fieldname, value): """ Returns a new DataTable with rows only where the value at `fieldname` < `value`. """
return self.mask([elem < value for elem in self[fieldname]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wherenot(self, fieldname, value): """ Logical opposite of `where`. """
return self.where(fieldname, value, negate=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 wherenotin(self, fieldname, value): """ Logical opposite of `wherein`. """
return self.wherein(fieldname, value, negate=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 writexlsx(self, path, sheetname="default"): """ Writes this table to an .xlsx file at the specified path. If you'd like to specify a sheetname, you may do so. If you'd like to write one workbook with different DataTables for each sheet, import the `excel` function from acrylic. You can see that code in `utils.py`. Note that the outgoing file is an .xlsx file, so it'd make sense to name that way. """
writer = ExcelRW.UnicodeWriter(path) writer.set_active_sheet(sheetname) writer.writerow(self.fields) writer.writerows(self) writer.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pyuri_formatter(namespace, value): """ Formats a namespace and ending value into a python friendly format args: namespace: RdfNamespace or tuple in the format of (prefix, uri,) value: end value to attach to the namespace """
if namespace[0]: return "%s_%s" %(namespace[0], value) else: return "pyuri_%s_%s" % (base64.b64encode(bytes(namespace[1], "utf-8")).decode(), value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def robots(self): """Return values for robots html meta key"""
r = 'noindex' if self.is_noindex else 'index' r += ',' r += 'nofollow' if self.is_nofollow else 'follow' return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_common_args(parser, is_create=True): """If is_create is True, protocol and action become mandatory arguments. CreateCommand = is_create : True UpdateCommand = is_create : False """
parser.add_argument( '--name', help=_('Name for the firewall rule.')) parser.add_argument( '--description', help=_('Description for the firewall rule.')) parser.add_argument( '--source-ip-address', help=_('Source IP address or subnet.')) parser.add_argument( '--destination-ip-address', help=_('Destination IP address or subnet.')) parser.add_argument( '--source-port', help=_('Source port (integer in [1, 65535] or range in a:b).')) parser.add_argument( '--destination-port', help=_('Destination port (integer in [1, 65535] or range in ' 'a:b).')) utils.add_boolean_argument( parser, '--enabled', dest='enabled', help=_('Whether to enable or disable this rule.')) parser.add_argument( '--protocol', choices=['tcp', 'udp', 'icmp', 'any'], required=is_create, type=utils.convert_to_lowercase, help=_('Protocol for the firewall rule.')) parser.add_argument( '--action', required=is_create, type=utils.convert_to_lowercase, choices=['allow', 'deny', 'reject'], help=_('Action for the firewall rule.'))
<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_relation_by_type_list(parser, token): """Gets list of relations from object identified by a content type. Syntax:: {% get_relation_list [content_type_app_label.content_type_model] for [object] as [varname] [direction] %} """
tokens = token.contents.split() if len(tokens) not in (6, 7): raise template.TemplateSyntaxError( "%r tag requires 6 arguments" % tokens[0] ) if tokens[2] != 'for': raise template.TemplateSyntaxError( "Third argument in %r tag must be 'for'" % tokens[0] ) if tokens[4] != 'as': raise template.TemplateSyntaxError( "Fifth argument in %r tag must be 'as'" % tokens[0] ) direction = 'forward' if len(tokens) == 7: direction = tokens[6] return RelationByTypeListNode( name=tokens[1], obj=tokens[3], as_var=tokens[5], direction=direction )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter(cls, **items): ''' Returns multiple Union objects with search params ''' client = cls._new_api_client(subpath='/search') items_dict = dict((k, v) for k, v in list(items.items())) json_data = json.dumps(items_dict, sort_keys=True, indent=4) return client.make_request(cls, 'post', post_data=json_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 get(cls, id): ''' Look up one Union object ''' client = cls._new_api_client() return client.make_request(cls, 'get', url_params={'id': id})
<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(self): ''' Save an instance of a Union object ''' client = self._new_api_client() params = {'id': self.id} if hasattr(self, 'id') else {} action = 'patch' if hasattr(self, 'id') else 'post' saved_model = client.make_request(self, action, url_params=params, post_data=self._to_json) self.__init__(**saved_model._to_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete(cls, id): ''' Destroy a Union object ''' client = cls._new_api_client() return client.make_request(cls, 'delete', url_params={'id': id})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def applyconfiguration(targets, conf=None, *args, **kwargs): """Apply configuration on input targets. If targets are not annotated by a Configurable, a new one is instanciated. :param Iterable targets: targets to configurate. :param tuple args: applyconfiguration var args. :param dict kwargs: applyconfiguration keywords. :return: configured targets. :rtype: list """
result = [] for target in targets: configurables = Configurable.get_annotations(target) if not configurables: configurables = [Configurable()] for configurable in configurables: configuredtargets = configurable.applyconfiguration( targets=[target], conf=conf, *args, **kwargs ) result += configuredtargets return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getcallparams( self, target, conf=None, args=None, kwargs=None, exec_ctx=None ): """Get target call parameters. :param list args: target call arguments. :param dict kwargs: target call keywords. :return: args, kwargs :rtype: tuple"""
if args is None: args = [] if kwargs is None: kwargs = {} if conf is None: conf = self.conf params = conf.params try: argspec = getargspec(target) except TypeError as tex: argspec = None callargs = {} else: try: callargs = getcallargs(target, *args, **kwargs) except TypeError as tex: if tex.args[0].endswith('\'{0}\''.format(argspec.args[0])): args = [None] else: raise try: callargs = getcallargs(target, *args, **kwargs) except TypeError as tex: if tex.args[0].endswith('\'{0}\''.format(argspec.args[0])): args = [] else: raise callargs = getcallargs(target, *args, **kwargs) args = [] pnames = set(params) for pname in pnames: if argspec and pname in argspec.args and ( (exec_ctx is not None and pname in exec_ctx) or callargs.get(pname) is None ): kwargs[pname] = params[pname].value if exec_ctx is not None: exec_ctx |= pnames return args, kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modules(self, value): """Change required modules. Reload modules given in the value. :param list value: new modules to use."""
modules = [module.__name__ for module in self.loadmodules(value)] self._modules = [ module for module in self._modules + modules if module not in self._modules ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conf(self, value): """Change of configuration. :param value: new configuration to use. :type value: Category or Configuration """
self._conf = self._toconf(value) if self.autoconf: self.applyconfiguration()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _toconf(self, conf): """Convert input parameter to a Configuration. :param conf: configuration to convert to a Configuration object. :type conf: Configuration, Category or Parameter. :rtype: Configuration"""
result = conf if result is None: result = Configuration() elif isinstance(result, Category): result = configuration(result) elif isinstance(result, Parameter): result = configuration(category('', result)) elif isinstance(result, list): result = configuration(category('', *result)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paths(self, value): """Change of paths in adding it in watching list."""
if value is None: value = () elif isinstance(value, string_types): value = (value, ) self._paths = tuple(value) if self.autoconf: self.applyconfiguration()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getconf( self, conf=None, paths=None, drivers=None, logger=None, modules=None ): """Get a configuration from paths. :param conf: conf to update. Default this conf. :type conf: Configuration, Category or Parameter :param str(s) paths: list of conf files. Default this paths. :param Logger logger: logger to use for logging info/error messages. :param list drivers: ConfDriver to use. Default this drivers. :param list modules: modules to reload before. :return: not resolved configuration. :rtype: Configuration """
result = None self.loadmodules(modules=modules) modules = [] conf = self._toconf(conf) # start to initialize input params if conf is None: conf = self.conf.copy() else: selfconf = self.conf.copy() selfconf.update(conf) conf = selfconf if paths is None: paths = self.paths if isinstance(paths, string_types): paths = [paths] if drivers is None: drivers = self.drivers if logger is None: logger = self.logger # iterate on all paths for path in paths: rscconf = None for driver in drivers: # find the best driver rscconf = driver.getconf(path=path, conf=conf, logger=logger) if rscconf is None: continue conf.update(rscconf) if rscconf is None: # if no conf found, display a warning log message if logger is not None: logger.warning( 'No driver found among {0} for processing {1}'.format( drivers, path ) ) result = conf return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure( self, conf=None, targets=None, logger=None, callconf=False, keepstate=None, modules=None ): """Apply input conf on targets objects. Specialization of this method is done in the _configure method. :param conf: configuration model to configure. Default is this conf. :type conf: Configuration, Category or Parameter :param Iterable targets: objects to configure. self targets by default. :param Logger logger: specific logger to use. :param bool callconf: if True (False by default), the configuration is used in the callable target parameters while calling it. :param bool keepstate: if True (default), do not instanciate sub objects if they already exist. :param list modules: modules to reload before. :return: configured targets. :rtype: list :raises: Parameter.Error for any raised exception. """
result = [] self.loadmodules(modules=modules) modules = [] conf = self._toconf(conf) if conf is None: conf = self.conf if targets is None: targets = self.targets if logger is None: logger = self.logger if keepstate is None: keepstate = self.keepstate for target in targets: try: configured = self._configure( conf=conf, logger=logger, target=target, callconf=callconf, keepstate=keepstate, modules=modules ) except Exception: if logger is not None: logger.error( 'Error {0} raised while configuring {1}/{2}'.format( format_exc(), self, targets ) ) else: result.append(configured) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure( self, target, conf=None, logger=None, callconf=None, keepstate=None, modules=None ): """Configure this class with input conf only if auto_conf or configure is true. This method should be overriden for specific conf :param target: object to configure. self targets by default. :param Configuration conf: configuration model to configure. Default is this conf. :param Logger logger: logger to use. :param bool callconf: if True, use conf in target __call__ parameters. :param bool keepstate: if True recreate sub objects if they already exist. :param list modules: modules to reload before. :return: configured target. """
result = target self.loadmodules(modules=modules) modules = [] if conf is None: conf = self.conf if logger is None: logger = self.logger if callconf is None: callconf = self.callparams if keepstate is None: keepstate = self.keepstate subcats = {} # store sub configurable categories params = [] # self parameters sub_conf_prefix = Configurable.SUB_CONF_PREFIX for cat in conf.values(): # separate sub params and params cname = cat.name if cname.startswith(sub_conf_prefix): subcnames = cname.split(sub_conf_prefix) pname = subcnames[1] fcname = cname[1 + len(pname):] if not fcname: fcname = str(random()) fcat = cat.copy(name=fcname) if pname in subcats: subcats[pname].append(fcat) else: subcats[pname] = [fcat] else: cparams = cat.params params += cparams.values() if callconf and callable(target): conf = self._toconf(params) args, kwargs = self.getcallparams(conf=conf, target=target) result = target = target(*args, **kwargs) for param in params: value, pname = param.value, param.name if pname in subcats: # if sub param subcallconf = True if keepstate and hasattr(target, pname): subcallconf = False value = getattr(target, pname) cats = subcats[pname] subconf = configuration(*cats) targets = applyconfiguration( targets=[value], conf=subconf, callconf=subcallconf, keepstate=keepstate, modules=modules ) value = targets[0] if param.error: continue elif self.foreigns or param.local: try: setattr(target, pname, value) except Exception: if logger is not None: logger.error( 'Error while setting {0}({1}) on {2}: {3}'.format( pname, value, target, format_exc() ) ) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_matches(self, text): """Return candidates matching the text."""
if self.use_main_ns: self.namespace = __main__.__dict__ if "." in text: return self.attr_matches(text) else: return self.global_matches(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 dict_camel_to_snake_case(camel_dict, convert_keys=True, convert_subkeys=False): """ Recursively convert camelCased keys for a camelCased dict into snake_cased keys :param camel_dict: Dictionary to convert :param convert_keys: Whether the key should be converted :param convert_subkeys: Whether to also convert the subkeys, in case they are named properties of the dict :return: """
converted = {} for key, value in camel_dict.items(): if isinstance(value, dict): new_value = dict_camel_to_snake_case(value, convert_keys=convert_subkeys, convert_subkeys=True) elif isinstance(value, list): new_value = [] for subvalue in value: new_subvalue = dict_camel_to_snake_case(subvalue, convert_keys=convert_subkeys, convert_subkeys=True) \ if isinstance(subvalue, dict) else subvalue new_value.append(new_subvalue) else: new_value = value new_key = to_snake_case(key) if convert_keys else key converted[new_key] = new_value return converted
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_snake_to_camel_case(snake_dict, convert_keys=True, convert_subkeys=False): """ Recursively convert a snake_cased dict into a camelCased dict :param snake_dict: Dictionary to convert :param convert_keys: Whether the key should be converted :param convert_subkeys: Whether to also convert the subkeys, in case they are named properties of the dict :return: """
converted = {} for key, value in snake_dict.items(): if isinstance(value, dict): new_value = dict_snake_to_camel_case(value, convert_keys=convert_subkeys, convert_subkeys=True) elif isinstance(value, list): new_value = [] for subvalue in value: new_subvalue = dict_snake_to_camel_case(subvalue, convert_keys=convert_subkeys, convert_subkeys=True) \ if isinstance(subvalue, dict) else subvalue new_value.append(new_subvalue) else: new_value = value new_key = to_camel_case(key) if convert_keys else key converted[new_key] = new_value return converted
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dubstep(client, channel, nick, message, matches): """ Dubstep can be described as a rapid succession of wub wubs, wow wows, and yep yep yep yeps """
now = time.time() if dubstep._last and (now - dubstep._last) > WUB_TIMEOUT: dubstep._counts[channel] = 0 dubstep._last = now if dubstep._counts[channel] >= MAX_WUBS: dubstep._counts[channel] = 0 return u'STOP! MY HEAD IS VIBRATING' else: dubstep._counts[channel] += 1 return u'wubwub' * dubstep._counts[channel] * random.randint(1, 4)
<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_tree(profile, sha, recursive=True): """Fetch a tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. sha The SHA of the tree to fetch. recursive If ``True``, traverse all subtrees and their subtrees, all the way down. That will return a list of all objects in the tree, all levels deep. Returns: A dict with data about the tree. """
resource = "/trees/" + sha if recursive: resource += "?recursive=1" data = api.get_request(profile, resource) return prepare(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 create_tree(profile, tree): """Create a new tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. tree A list of blob objects (each with a path, mode, type, and content or sha) to put in the tree. Returns: A dict with data about the tree. """
resource = "/trees" payload = {"tree": tree} data = api.post_request(profile, resource, payload) return prepare(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 validate(self): """Ensure that all fields' values are valid and that non-nullable fields are present. """
for field_name, field_obj in self._fields.items(): value = field_obj.__get__(self, self.__class__) if value is None and field_obj.null is False: raise ValidationError('Non-nullable field {0} is set to None'.format(field_name)) elif value is None and field_obj.null is True: # no further validations are possible on NoneType field continue if isinstance(field_obj, NestedDocumentField): value.validate() else: field_obj.validate(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self): """Converts given document to JSON dict. """
json_data = dict() for field_name, field_obj in self._fields.items(): if isinstance(field_obj, NestedDocumentField): nested_document = field_obj.__get__(self, self.__class__) value = None if nested_document is None else nested_document.to_json() elif isinstance(field_obj, BaseField): value = field_obj.__get__(self, self.__class__) value = field_obj.to_json(value) else: # ignore fields not derived from BaseField or NestedDocument continue if value is None: # skip fields with None value continue json_data[field_name] = value return json_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 from_json(cls, json_data): """ Converts json data to a new document instance"""
new_instance = cls() for field_name, field_obj in cls._get_fields().items(): if isinstance(field_obj, NestedDocumentField): if field_name in json_data: nested_field = field_obj.__get__(new_instance, new_instance.__class__) if not nested_field: # here, we have to create an instance of the nested document, # since we have a JSON object for it nested_field = field_obj.nested_klass() nested_document = nested_field.from_json(json_data[field_name]) field_obj.__set__(new_instance, nested_document) elif isinstance(field_obj, BaseField): if field_name in json_data: value = field_obj.from_json(json_data[field_name]) field_obj.__set__(new_instance, value) else: continue return new_instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, conn, tmp, module_name, module_args, inject): ''' handler for template operations ''' if not self.runner.is_playbook: raise errors.AnsibleError("in current versions of ansible, templates are only usable in playbooks") # load up options options = utils.parse_kv(module_args) source = options.get('src', None) dest = options.get('dest', None) if (source is None and 'first_available_file' not in inject) or dest is None: result = dict(failed=True, msg="src and dest are required") return ReturnData(conn=conn, comm_ok=False, result=result) # if we have first_available_file in our vars # look up the files and use the first one we find as src if 'first_available_file' in inject: found = False for fn in self.runner.module_vars.get('first_available_file'): fnt = utils.template(self.runner.basedir, fn, inject) fnd = utils.path_dwim(self.runner.basedir, fnt) if os.path.exists(fnd): source = fnt found = True break if not found: result = dict(failed=True, msg="could not find src in first_available_file list") return ReturnData(conn=conn, comm_ok=False, result=result) else: source = utils.template(self.runner.basedir, source, inject) if dest.endswith("/"): base = os.path.basename(source) dest = os.path.join(dest, base) # template the source data locally & transfer try: resultant = utils.template_from_file(self.runner.basedir, source, inject) except Exception, e: result = dict(failed=True, msg=str(e)) return ReturnData(conn=conn, comm_ok=False, result=result) xfered = self.runner._transfer_str(conn, tmp, 'source', resultant) # fix file permissions when the copy is done as a different user if self.runner.sudo and self.runner.sudo_user != 'root': self.runner._low_level_exec_command(conn, "chmod a+r %s" % xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s" % (module_args, xfered, dest) return self.runner._execute_module(conn, tmp, 'copy', module_args, inject=inject)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decompose_dateint(dateint): """Decomposes the given dateint into its year, month and day components. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. Returns ------- year : int The year component of the given dateint. month : int The month component of the given dateint. day : int The day component of the given dateint. """
year = int(dateint / 10000) leftover = dateint - year * 10000 month = int(leftover / 100) day = leftover - month * 100 return year, month, day
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_to_datetime(dateint): """Converts the given dateint to a datetime object, in local timezone. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. Returns ------- datetime.datetime A timezone-unaware datetime object representing the start of the given """
if len(str(dateint)) != 8: raise ValueError( 'Dateints must have exactly 8 digits; the first four representing ' 'the year, the next two the months, and the last two the days.') year, month, day = decompose_dateint(dateint) return datetime(year=year, month=month, day=day)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_to_weekday(dateint, first_day='Monday'): """Returns the weekday of the given dateint. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. first_day : str, default 'Monday' The first day of the week. Returns ------- int The weekday of the given dateint, when first day of the week = 0, last day of the week = 6. Example ------- 0 6 1 0 2 """
weekday_ix = dateint_to_datetime(dateint).weekday() return (weekday_ix - WEEKDAYS.index(first_day)) % 7
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_dateint(dateint, day_shift): """Shifts the given dateint by the given amount of days. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. days : int The number of days to shift the given dateint by. A negative number shifts the dateint backwards. Returns ------- int A dateint corresponding to the given date shifted by the given amount of days. Example ------- 20170301 20170228 20170225 """
dtime = dateint_to_datetime(dateint) delta = timedelta(days=abs(day_shift)) if day_shift > 0: dtime = dtime + delta else: dtime = dtime - delta return datetime_to_dateint(dtime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_range(first_dateint, last_dateint): """Returns all dateints in the given dateint range. Arguments --------- first_dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. last_dateint : int An integer object decipting a specific calendaric day; e.g. 20170108. Returns ------- iterable An iterable of ints representing all days in the given dateint range. Example ------- [20170228, 20170301] [20170225, 20170226, 20170227, 20170228, 20170301] """
first_datetime = dateint_to_datetime(first_dateint) last_datetime = dateint_to_datetime(last_dateint) delta = last_datetime - first_datetime delta_in_hours = math.ceil(delta.total_seconds() / 3600) delta_in_days = math.ceil(delta_in_hours / 24) + 1 dateint_set = set() for delta_i in range(0, delta_in_days * 24, 24): datetime_i = first_datetime + timedelta(hours=delta_i) dateint_i = datetime_to_dateint(datetime_i) if dateint_i <= last_dateint: dateint_set.add(dateint_i) return sorted(dateint_set)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_week_by_dateint(dateint, first_day='Monday'): """Return a dateint range of the week the given dateint belongs to. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. first_day : str, default 'Monday' The first day of the week. Returns ------- iterable An iterable of dateint representing all days of the week the given dateint belongs to. """
weekday_ix = dateint_to_weekday(dateint, first_day) first_day_dateint = shift_dateint(dateint, -weekday_ix) last_day_dateint = shift_dateint(first_day_dateint, 6) return dateint_range(first_day_dateint, last_day_dateint)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_difference(dateint1, dateint2): """Return the difference between two dateints in days. Arguments --------- dateint1 : int An integer object decipting a specific calendaric day; e.g. 20161225. dateint2 : int An integer object decipting a specific calendaric day; e.g. 20161225. Returns ------- int The difference between the two given dateints in days. """
dt1 = dateint_to_datetime(dateint1) dt2 = dateint_to_datetime(dateint2) delta = dt1 - dt2 return abs(delta.days)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyFile(src, dest): """Copies a source file to a destination whose path may not yet exist. Keyword arguments: src -- Source path to a file (string) dest -- Path for destination file (also a string) """
#Src Exists? try: if os.path.isfile(src): dpath, dfile = os.path.split(dest) if not os.path.isdir(dpath): os.makedirs(dpath) if not os.path.exists(dest): touch(dest) try: shutil.copy2(src, dest) # eg. src and dest are the same file except shutil.Error as e: logging.exception('Error: %s' % e) # eg. source or destination doesn't exist except IOError as e: logging.exception('Error: %s' % e.strerror) except: logging.exception('Error: src to copy does not exist.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _terminal_notifier(title, message): """ Shows user notification message via `terminal-notifier` command. `title` Notification title. `message` Notification message. """
try: paths = common.extract_app_paths(['terminal-notifier']) except ValueError: pass common.shell_process([paths[0], '-title', title, '-message', message])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _growlnotify(title, message): """ Shows growl notification message via `growlnotify` command. `title` Notification title. `message` Notification message. """
try: paths = common.extract_app_paths(['growlnotify']) except ValueError: return common.shell_process([paths[0], '-t', title, '-m', message])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dbus_notify(title, message): """ Shows system notification message via dbus. `title` Notification title. `message` Notification message. """
try: # fetch main account manager interface bus = dbus.SessionBus() obj = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications') if obj: iface = dbus.Interface(obj, 'org.freedesktop.Notifications') if iface: # dispatch notification message iface.Notify('Focus', 0, '', title, message, [], {}, 5) except dbus.exceptions.DBusException: 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 _notify(self, task, message): """ Shows system notification message according to system requirements. `message` Status message. """
if self.notify_func: message = common.to_utf8(message.strip()) title = common.to_utf8(u'Focus ({0})'.format(task.name)) self.notify_func(title, message)
<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_option(self, option, block_name, message): """ Parse show, end_show, and timer_show options. """
if option == 'show': option = 'start_' + option key = option.split('_', 1)[0] self.messages[key] = message
<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_value(value): """ Convert a list into a comma separated string, for displaying select multiple values in emails. """
if isinstance(value, list): value = ", ".join([v.strip() for v in value]) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form_processor(request, page): """ Display a built form and handle submission. """
form = FormForForm(page.form, RequestContext(request), request.POST or None, request.FILES or None) if form.is_valid(): url = page.get_absolute_url() + "?sent=1" if is_spam(request, form, url): return redirect(url) attachments = [] for f in form.files.values(): f.seek(0) attachments.append((f.name, f.read())) entry = form.save() subject = page.form.email_subject if not subject: subject = "%s - %s" % (page.form.title, entry.entry_time) fields = [(v.label, format_value(form.cleaned_data[k])) for (k, v) in form.fields.items()] context = { "fields": fields, "message": page.form.email_message, "request": request, } email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL email_to = form.email_to() if email_to and page.form.send_email: send_mail_template(subject, "email/form_response", email_from, email_to, context) headers = None if email_to: # Add the email entered as a Reply-To header headers = {'Reply-To': email_to} email_copies = split_addresses(page.form.email_copies) if email_copies: send_mail_template(subject, "email/form_response_copies", email_from, email_copies, context, attachments=attachments, headers=headers) form_valid.send(sender=request, form=form, entry=entry) return redirect(url) form_invalid.send(sender=request, form=form) return {"form": form}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visible(self): """ Only shown on the sharing view """
context_state = api.content.get_view(context=self.context, request=self.request, name="plone_context_state") url = context_state.current_base_url() return url.endswith('@@sharing')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def active_participant_policy(self): """ Get the title of the current participation policy """
key = self.context.participant_policy policy = PARTICIPANT_POLICY.get(key) return policy['title']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_integrity_multilevel(d1, d2): """ still under development """
keys = [x for x in d2] for key in keys: d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]} same = set(o for o in intersect_keys if d1[o] == d2[o]) if added == removed == set(): d1_values = [x for x in d1.values()][0] print('d1_values: ' + str(d1_values)) d2_values = [x for x in d2.values()][0] print('d2_values: ' + str(d2_values)) length = len(d2_values) print('length = %d' % length) pdb.set_trace() if length > 1: d1 = d1_values.items() d2 = d2_values.items() else: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_local_config(cfg): """ Parses local config file for override values Args: :local_file (str): filename of local config file Returns: dict object of values contained in local config file """
try: if os.path.exists(cfg): config = import_file_object(cfg) return config else: logger.warning( '%s: local config file (%s) not found, cannot be read' % (inspect.stack()[0][3], str(cfg))) except IOError as e: logger.warning( 'import_file_object: %s error opening %s' % (str(e), str(cfg)) ) 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 formfield_for_dbfield(self, db_field, **kwargs): """ Adds the "Send to Twitter" checkbox after the "status" field, provided by any ``Displayable`` models. The approach here is quite a hack, however the sane approach of using a custom form with a boolean field defined, and then adding it to the formssets attribute of the admin class fell apart quite horrifically. """
formfield = super(TweetableAdminMixin, self).formfield_for_dbfield(db_field, **kwargs) if Api and db_field.name == "status" and get_auth_settings(): def wrapper(render): def wrapped(*args, **kwargs): rendered = render(*args, **kwargs) label = _("Send to Twitter") return mark_safe(rendered + FORMFIELD_HTML % label) return wrapped formfield.widget.render = wrapper(formfield.widget.render) return formfield
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command(cmd): """Execute command and raise an exception upon an error. True Traceback (most recent call last): SdistCreationError """
status, out = commands.getstatusoutput(cmd) if status is not 0: logger.error("Something went wrong:") logger.error(out) raise SdistCreationError() return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize_number(val, line): """Parse val correctly into int or float."""
try: num = int(val) typ = TokenType.int except ValueError: num = float(val) typ = TokenType.float return {'type': typ, 'value': num, 'line': 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 loadHistory(self): """ Loads the shop sale history Raises parseException """
pg = self.usr.getPage("http://www.neopets.com/market.phtml?type=sales")\ try: rows = pg.find("b", text = "Date").parent.parent.parent.find_all("tr") # First and last row do not contain entries rows.pop(0) rows.pop(-1) self.history = [] for row in rows: parts = row.find_all("td") dets = {} dets['date'] = parts[0].text dets['item'] = parts[1].text dets['buyer'] = parts[2].text dets['price'] = parts[3].text self.history.append(dets) # Reverse the list to put it in order by date self.history.reverse() except Exception: logging.getLogger("neolib.shop").exception("Could not parse sales history.", {'pg': pg}) raise parseException
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_entry(self, id_, **kwargs): """ Edits a time entry by ID. Takes the same data as `create_entry`, but requires an ID to work. It also takes a `force` parameter that, when set to True, allows administrators to edit locked entries. """
data = self._wrap_dict("time_entry", kwargs) return self.patch("/time_entries/{}.json".format(id_), 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 start_tracker(self, id_, **kwargs): """ Starts a tracker for the time entry identified by `id_`. """
data = None if kwargs: data = self._wrap_dict("tracker", self._wrap_dict("tracking_time_entry", kwargs)) return self.patch("/tracker/{}.json".format(id_), data=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 edit_customer(self, id_, **kwargs): """ Edits a customer by ID. All fields available at creation can be updated as well. If you want to update hourly rates retroactively, set the argument `update_hourly_rate_on_time_entries` to True. """
data = self._wrap_dict("customer", kwargs) return self.patch("/customers/{}.json".format(id_), data=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 edit_project(self, id_, **kwargs): """ Edits a project by ID. All fields available at creation can be updated as well. If you want to update hourly rates retroactively, set the argument `update_hourly_rate_on_time_entries` to True. """
data = self._wrap_dict("project", kwargs) return self.patch("/projects/{}.json".format(id_), data=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 edit_service(self, id_, **kwargs): """ Edits a service by ID. All fields available at creation can be updated as well. If you want to update hourly rates retroactively, set the argument `update_hourly_rate_on_time_entries` to True. """
data = self._wrap_dict("service", kwargs) return self.patch("/services/{}.json".format(id_), data=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 get_committed_signatures(vcs): """Get the list of committed signatures Args: vcs (easyci.vcs.base.Vcs) Returns: list(basestring) - list of signatures """
committed_path = _get_committed_history_path(vcs) known_signatures = [] if os.path.exists(committed_path): with open(committed_path, 'r') as f: known_signatures = f.read().split() return known_signatures
<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_staged_signatures(vcs): """Get the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) Returns: list(basestring) - list of signatures """
staged_path = _get_staged_history_path(vcs) known_signatures = [] if os.path.exists(staged_path): with open(staged_path, 'r') as f: known_signatures = f.read().split() return known_signatures
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit_signature(vcs, user_config, signature): """Add `signature` to the list of committed signatures The signature must already be staged Args: vcs (easyci.vcs.base.Vcs) user_config (dict) signature (basestring) Raises: NotStagedError AlreadyCommittedError """
if signature not in get_staged_signatures(vcs): raise NotStagedError evidence_path = _get_committed_history_path(vcs) committed_signatures = get_committed_signatures(vcs) if signature in committed_signatures: raise AlreadyCommittedError committed_signatures.append(signature) string = '\n'.join(committed_signatures[-user_config['history_limit']:]) with open(evidence_path, 'w') as f: f.write(string) unstage_signature(vcs, signature)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stage_signature(vcs, signature): """Add `signature` to the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) signature (basestring) Raises: AlreadyStagedError """
evidence_path = _get_staged_history_path(vcs) staged = get_staged_signatures(vcs) if signature in staged: raise AlreadyStagedError staged.append(signature) string = '\n'.join(staged) with open(evidence_path, 'w') as f: f.write(string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unstage_signature(vcs, signature): """Remove `signature` from the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) signature (basestring) Raises: NotStagedError """
evidence_path = _get_staged_history_path(vcs) staged = get_staged_signatures(vcs) if signature not in staged: raise NotStagedError staged.remove(signature) string = '\n'.join(staged) with open(evidence_path, 'w') as f: f.write(string)
<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_decrpyted_path(encrypted_path, surfix=default_surfix): """ Find the original path of encrypted file or dir. Example: - file: ``${home}/test-encrypted.txt`` -> ``${home}/test.txt`` - dir: ``${home}/Documents-encrypted`` -> ``${home}/Documents`` """
surfix_reversed = surfix[::-1] p = Path(encrypted_path).absolute() fname = p.fname fname_reversed = fname[::-1] new_fname = fname_reversed.replace(surfix_reversed, "", 1)[::-1] decrypted_p = p.change(new_fname=new_fname) return decrypted_p.abspath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(src, dst, converter, overwrite=False, stream=True, chunksize=1024**2, **kwargs): """ A file stream transform IO utility function. :param src: original file path :param dst: destination file path :param converter: binary content converter function :param overwrite: default False, :param stream: default True, if True, use stream IO mode, chunksize has to be specified. :param chunksize: default 1MB """
if not overwrite: # pragma: no cover if Path(dst).exists(): raise EnvironmentError("'%s' already exists!" % dst) with open(src, "rb") as f_input: with open(dst, "wb") as f_output: if stream: # fix chunksize to a reasonable range if chunksize > 1024 ** 2 * 10: chunksize = 1024 ** 2 * 10 elif chunksize < 1024 ** 2: chunksize = 1024 ** 2 # write file while 1: content = f_input.read(chunksize) if content: f_output.write(converter(content, **kwargs)) else: break else: # pragma: no cover f_output.write(converter(f_input.read(), **kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, tweet): """Add a tweet to the end of the list."""
c = self.connection.cursor() last_tweet = c.execute("SELECT tweet from tweetlist where label='last_tweet'").next()[0] c.execute("INSERT INTO tweets(message, previous_tweet, next_tweet) VALUES (?,?,NULL)", (tweet, last_tweet)) tweet_id = c.lastrowid # Set the current tweet as the last tweet c.execute("UPDATE tweetlist SET tweet=? WHERE label='last_tweet'", (tweet_id,)) # If there was no last_tweet, there was no first_tweet # so make this the first tweet if last_tweet is None: c.execute("UPDATE tweetlist SET tweet=? WHERE label='first_tweet'", (tweet_id,)) else: # Update the last tweets reference to this one c.execute("UPDATE tweets SET next_tweet = ? WHERE id= ? ", (tweet_id, last_tweet)) self.connection.commit() c.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self): """Return first tweet in the list."""
c = self.connection.cursor() first_tweet_id = c.execute("SELECT tweet from tweetlist where label='first_tweet'").next()[0] if first_tweet_id is None: # No tweets are in the list, so return None return None tweet = c.execute("SELECT id, message, previous_tweet, next_tweet from tweets WHERE id=?", (first_tweet_id,)).next() # Update the first tweet reference c.execute("UPDATE tweetlist SET tweet=? WHERE label='first_tweet'", (tweet[3],)) # Update the "next tweet" if it exists if tweet[3] is not None: c.execute("UPDATE tweets SET previous_tweet=NULL WHERE id=?", (tweet[3],)) else: #This was the last tweet so NULL the last tweet reference. c.execute("UPDATE tweetlist SET tweet=NULL WHERE label=?", ('last_tweet',)) # Now remove the tweet from the list c.execute("DELETE FROM tweets WHERE id=?", (first_tweet_id,)) self.connection.commit() c.close() return tweet[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 peek(self): """Peeks at the first of the list without removing it."""
c = self.connection.cursor() first_tweet_id = c.execute("SELECT tweet from tweetlist where label='first_tweet'").next()[0] if first_tweet_id is None: # No tweets are in the list, so return None return None tweet = c.execute("SELECT message from tweets WHERE id=?", (first_tweet_id,)).next()[0] c.close() return tweet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, tweet_id): """Deletes a tweet from the list with the given id"""
c = self.connection.cursor() try: tweet = c.execute("SELECT id, message, previous_tweet, next_tweet from tweets WHERE id=?", (tweet_id,)).next() except StopIteration: raise ValueError("No tweets were found with that ID") # Update linked list references c.execute("UPDATE tweets set next_tweet=? WHERE id=?", (tweet[3], tweet[2])) c.execute("UPDATE tweets set previous_tweet=? WHERE id=?", (tweet[2], tweet[3])) if tweet[3] is None: c.execute("UPDATE tweetlist SET tweet=? WHERE label='last_tweet'", (tweet[2],)) if tweet[2] is None: c.execute("UPDATE tweetlist SET tweet=? WHERE label='first_tweet'", (tweet[3],)) c.execute("DELETE from tweets WHERE id=?", (tweet_id,)) self.connection.commit() c.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def usetz_now(): """Determine current time depending on USE_TZ setting. Affects Django 1.4 and above only. if `USE_TZ = True`, then returns current time according to timezone, else returns current UTC time. """
USE_TZ = getattr(settings, 'USE_TZ', False) if USE_TZ and DJANGO_VERSION >= '1.4': return now() else: return datetime.utcnow()
<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_delta(self, now, then): """ Internal helper which will return a ``datetime.timedelta`` representing the time between ``now`` and ``then``. Assumes ``now`` is a ``datetime.date`` or ``datetime.datetime`` later than ``then``. If ``now`` and ``then`` are not of the same type due to one of them being a ``datetime.date`` and the other being a ``datetime.datetime``, both will be coerced to ``datetime.date`` before calculating the delta. """
if now.__class__ is not then.__class__: now = datetime.date(now.year, now.month, now.day) then = datetime.date(then.year, then.month, then.day) if now < then: raise ValueError("Cannot determine moderation rules because date field is set to a value in the future") return now - then
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Hook up the moderation methods to pre- and post-save signals from the comment models. """
signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model())
<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(self, model_or_iterable, moderation_class): """ Register a model or a list of models for comment moderation, using a particular moderation class. Raise ``AlreadyModerated`` if any of the models are already registered. """
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model in self._registry: raise AlreadyModerated( "The model '%s' is already being moderated" % model._meta.verbose_name ) self._registry[model] = moderation_class(model)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, model_or_iterable): """ Remove a model or a list of models from the list of models whose comments will be moderated. Raise ``NotModerated`` if any of the models are not currently registered for moderation. """
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotModerated("The model '%s' is not currently being moderated" % model._meta.module_name) del self._registry[model]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary pre-save moderation steps to new comments. """
model = comment.content_type.model_class() if model not in self._registry: return content_object = comment.content_object moderation_class = self._registry[model] # Comment will be disallowed outright (HTTP 403 response) if not moderation_class.allow(comment, content_object, request): return False if moderation_class.moderate(comment, content_object, request): comment.is_public = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary post-save moderation steps to new comments. """
model = comment.content_type.model_class() if model not in self._registry: return self._registry[model].email(comment, comment.content_object, request)
<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(args): """ main entry point for the FDR script. :param args: the arguments for this script, as a list of string. Should already have had things like the script name stripped. That is, if there are no args provided, this should be an empty list. """
# get options and arguments ui = getUI(args) if ui.optionIsSet("test"): # just run unit tests unittest.main(argv=[sys.argv[0]]) elif ui.optionIsSet("help"): # just show help ui.usage() else: verbose = (ui.optionIsSet("verbose") is True) or DEFAULT_VERBOSITY # header? header = ui.optionIsSet("header") # get field value field = ui.getValue("field") - 1 # get output handle out_fh = sys.stdout if ui.optionIsSet("output"): out_fh = open(ui.getValue("output"), "w") # get input file-handle in_fh = sys.stdin if ui.hasArgument(0): in_fh = open(ui.getArgument(0)) delim = DEFAULT_DELIM # load data, do conversion, write out results. data_table = DataTable() data_table.load(in_fh, header, delim, verbose) data_table.frame[field] =\ correct_pvals(data_table.frame[field], verbose=verbose) data_table.write(out_fh, delim, verbose)
<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(self, in_fh, header=False, delimit=None, verbose=False): """ Load this data_table from a stream or file. Blank lines in the file are skipped. Any existing values in this dataTable object are cleared before loading the new ones. :param in_fh: load from this stream. Can also be a string, in which case we treat it as a filename and attempt to load from that file. :param header: if True, the first row is considered a header :param delimit: delimiter for splitting columns; set to None (default) to split around any whitespace. :param verbose: if True, output progress messages to stderr. """
self.clear() if verbose: sys.stderr.write("getting input...\n") # figure out whether we need to open a file or not in_strm = in_fh if isinstance(in_strm, basestring): in_strm = open(in_strm) for line in in_strm: line = line.strip() if line == "": continue if header and self.header is None: self.header = line.split(delimit) continue parts = line.split(delimit) if self.frame != [] and len(parts) != len(self.frame): raise IOError("Cannot handle ragged data frames") while len(self.frame) < len(parts): self.frame.append([]) for i in range(0, len(parts)): self.frame[i].append(parts[i])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, strm, delim, verbose=False): """ Write this data frame to a stream or file. :param strm: stream to write to; can also be a string, in which case we treat it as a filename and to open that file for writing to. :param delim: delimiter to use between columns. :param verbose: if True, output progress messages to stderr. """
if verbose: sys.stderr.write("outputing...\n") # figure out whether we need to open a file or not out_strm = strm if isinstance(out_strm, basestring): out_strm = open(out_strm) if self.header is not None: out_strm.write(delim.join(self.header)) max_col_len = len(max(self.frame, key=len)) for i in range(0, max_col_len): for j in range(0, len(self.frame)): if j != 0: out_strm.write(delim) out_strm.write(str(self.frame[j][i])) out_strm.write("\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_core_filters(cls): """ Attach core filters to filterset """
opts = cls._meta base_filters = cls.base_filters.copy() cls.base_filters.clear() for name, filter_ in six.iteritems(base_filters): if isinstance(filter_, AutoFilters): field = filterset.get_model_field(opts.model, filter_.name) filter_exclusion = filter_.extra.pop('drop', []) for lookup_expr in utils.lookups_for_field(field): if lookup_expr not in filter_exclusion: new_filter = cls.filter_for_field(field, filter_.name, lookup_expr) # by convention use field name for filters with exact lookup_expr if lookup_expr != 'exact': filter_name = LOOKUP_SEP.join([name, lookup_expr]) else: filter_name = name cls.base_filters[filter_name] = new_filter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def only_for(theme, redirect_to='/', raise_error=None): """ Decorator for restrict access to views according by list of themes. Params: * ``theme`` - string or list of themes where decorated view must be * ``redirect_to`` - url or name of url pattern for redirect if CURRENT_THEME not in themes * ``raise_error`` - error class for raising Example: .. code:: python # views.py from django_vest import only_for @only_for('black_theme') def my_view(request): """
def check_theme(*args, **kwargs): if isinstance(theme, six.string_types): themes = (theme,) else: themes = theme if settings.CURRENT_THEME is None: return True result = settings.CURRENT_THEME in themes if not result and raise_error is not None: raise raise_error return result return user_passes_test(check_theme, login_url=redirect_to)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(self, document): """Create experiment object from JSON document retrieved from database. Parameters document : JSON Json document in database Returns ------- ExperimentHandle Handle for experiment object """
identifier = str(document['_id']) active = document['active'] timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f') properties = document['properties'] subject_id = document['subject'] image_group_id = document['images'] fmri_data_id = document['fmri'] if 'fmri' in document else None return ExperimentHandle( identifier, properties, subject_id, image_group_id, fmri_data_id=fmri_data_id, timestamp=timestamp, is_active=active )
<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_objects(self, query=None, limit=-1, offset=-1): """List of all experiments in the database. Overrides the super class method to allow the returned object's property lists to be extended with the run count. Parameters query : Dictionary Filter objects by property-value pairs defined by dictionary. limit : int Limit number of items in the result set offset : int Set offset in list (order as defined by object store) Returns ------- ObjectListing """
# Call super class method to get the object listing result = super(DefaultExperimentManager, self).list_objects( query=query, limit=limit, offset=offset ) # Run aggregate count on predictions if collection was given if not self.coll_predictions is None: # Get model run counts for active experiments. Experiments without # runs will not be in the result counts = {} pipeline = [ { '$match': {'active': True}}, { '$group': { '_id': "$experiment", 'count': { '$sum': 1 } } } ] for doc in self.coll_predictions.aggregate(pipeline): counts[doc['_id']] = doc['count'] # Set run count property for all experiments in the result set for item in result.items: if item.identifier in counts: item.properties[PROPERTY_RUN_COUNT] = counts[item.identifier] else: item.properties[PROPERTY_RUN_COUNT] = 0 return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_fmri_data(self, identifier, fmri_data_id): """Associate the fMRI object with the identified experiment. Parameters identifier : string Unique experiment object identifier fmri_data_id : string Unique fMRI data object identifier Returns ------- ExperimentHandle Returns modified experiment object or None if no experiment with the given identifier exists. """
# Get experiment to ensure that it exists experiment = self.get_object(identifier) if experiment is None: return None # Update fmri_data property and replace existing object with updated one experiment.fmri_data_id = fmri_data_id self.replace_object(experiment) # Return modified experiment return experiment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(): """ Load system configuration @rtype: ConfigParser """
cfg = ConfigParser() cfg.read(os.path.join(os.path.dirname(os.path.realpath(ips_vagrant.__file__)), 'config/ipsv.conf')) return cfg