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 to_properties(cls, config, compact=False, indent=2, key_stack=[]): """Convert HOCON input into a .properties output :return: .properties string representation :type return: basestring :return: """
def escape_value(value): return value.replace('=', '\\=').replace('!', '\\!').replace('#', '\\#').replace('\n', '\\\n') stripped_key_stack = [key.strip('"') for key in key_stack] lines = [] if isinstance(config, ConfigTree): for key, item in config.items(): if item is not None: lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [key])) elif isinstance(config, list): for index, item in enumerate(config): if item is not None: lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [str(index)])) elif isinstance(config, basestring): lines.append('.'.join(stripped_key_stack) + ' = ' + escape_value(config)) elif config is True: lines.append('.'.join(stripped_key_stack) + ' = true') elif config is False: lines.append('.'.join(stripped_key_stack) + ' = false') elif config is None or isinstance(config, NoneValue): pass else: lines.append('.'.join(stripped_key_stack) + ' = ' + str(config)) return '\n'.join([line for line in lines if len(line) > 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 convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False): """Convert to json, properties or yaml :param input_file: input file, if not specified stdin :param output_file: output file, if not specified stdout :param output_format: json, properties or yaml :return: json, properties or yaml string representation """
if input_file is None: content = sys.stdin.read() config = ConfigFactory.parse_string(content) else: config = ConfigFactory.parse_file(input_file) res = cls.convert(config, output_format, indent, compact) if output_file is None: print(res) else: with open(output_file, "w") as fd: fd.write(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 postParse(self, instring, loc, token_list): """Create a list from the tokens :param instring: :param loc: :param token_list: :return: """
cleaned_token_list = [token for tokens in (token.tokens if isinstance(token, ConfigInclude) else [token] for token in token_list if token != '') for token in tokens] config_list = ConfigList(cleaned_token_list) return [config_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 postParse(self, instring, loc, token_list): """Create ConfigTree from tokens :param instring: :param loc: :param token_list: :return: """
config_tree = ConfigTree(root=self.root) for element in token_list: expanded_tokens = element.tokens if isinstance(element, ConfigInclude) else [element] for tokens in expanded_tokens: # key, value1 (optional), ... key = tokens[0].strip() operator = '=' if len(tokens) == 3 and tokens[1].strip() in [':', '=', '+=']: operator = tokens[1].strip() values = tokens[2:] elif len(tokens) == 2: values = tokens[1:] else: raise ParseSyntaxException("Unknown tokens {tokens} received".format(tokens=tokens)) # empty string if len(values) == 0: config_tree.put(key, '') else: value = values[0] if isinstance(value, list) and operator == "+=": value = ConfigValues([ConfigSubstitution(key, True, '', False, loc), value], False, loc) config_tree.put(key, value, False) elif isinstance(value, unicode) and operator == "+=": value = ConfigValues([ConfigSubstitution(key, True, '', True, loc), ' ' + value], True, loc) config_tree.put(key, value, False) elif isinstance(value, list): config_tree.put(key, value, False) else: existing_value = config_tree.get(key, None) if isinstance(value, ConfigTree) and not isinstance(existing_value, list): # Only Tree has to be merged with tree config_tree.put(key, value, True) elif isinstance(value, ConfigValues): conf_value = value value.parent = config_tree value.key = key if isinstance(existing_value, list) or isinstance(existing_value, ConfigTree): config_tree.put(key, conf_value, True) else: config_tree.put(key, conf_value, False) else: config_tree.put(key, value, False) return config_tree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_configs(a, b, copy_trees=False): """Merge config b into a :param a: target config :type a: ConfigTree :param b: source config :type b: ConfigTree :return: merged config a """
for key, value in b.items(): # if key is in both a and b and both values are dictionary then merge it otherwise override it if key in a and isinstance(a[key], ConfigTree) and isinstance(b[key], ConfigTree): if copy_trees: a[key] = a[key].copy() ConfigTree.merge_configs(a[key], b[key], copy_trees=copy_trees) else: if isinstance(value, ConfigValues): value.parent = a value.key = key if key in a: value.overriden_value = a[key] a[key] = value if a.root: if b.root: a.history[key] = a.history.get(key, []) + b.history.get(key, [value]) else: a.history[key] = a.history.get(key, []) + [value] return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, default=UndefinedKey): """Get a value from the tree :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: object :return: value in the tree located at key """
return self._get(ConfigTree.parse_key(key), 0, default)
<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_string(self, key, default=UndefinedKey): """Return string representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: basestring :return: string value :type return: basestring """
value = self.get(key, default) if value is None: return None string_value = unicode(value) if isinstance(value, bool): string_value = string_value.lower() return string_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 pop(self, key, default=UndefinedKey): """Remove specified key and return the corresponding value. If key is not found, default is returned if given, otherwise ConfigMissingException is raised This method assumes the user wants to remove the last value in the chain so it parses via parse_key and pops the last value out of the dict. :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: object :param default: default value if key not found :return: value in the tree located at key """
if default != UndefinedKey and key not in self: return default value = self.get(key, UndefinedKey) lst = ConfigTree.parse_key(key) parent = self.KEY_SEP.join(lst[0:-1]) child = lst[-1] if parent: self.get(parent).__delitem__(child) else: self.__delitem__(child) 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 get_int(self, key, default=UndefinedKey): """Return int representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: int :return: int value :type return: int """
value = self.get(key, default) try: return int(value) if value is not None else None except (TypeError, ValueError): raise ConfigException( u"{key} has type '{type}' rather than 'int'".format(key=key, type=type(value).__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 get_float(self, key, default=UndefinedKey): """Return float representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: float :return: float value :type return: float """
value = self.get(key, default) try: return float(value) if value is not None else None except (TypeError, ValueError): raise ConfigException( u"{key} has type '{type}' rather than 'float'".format(key=key, type=type(value).__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 get_bool(self, key, default=UndefinedKey): """Return boolean representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: bool :return: boolean value :type return: bool """
# String conversions as per API-recommendations: # https://github.com/typesafehub/config/blob/master/HOCON.md#automatic-type-conversions bool_conversions = { None: None, 'true': True, 'yes': True, 'on': True, 'false': False, 'no': False, 'off': False } string_value = self.get_string(key, default) if string_value is not None: string_value = string_value.lower() try: return bool_conversions[string_value] except KeyError: raise ConfigException( u"{key} does not translate to a Boolean value".format(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 get_list(self, key, default=UndefinedKey): """Return list representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: list :return: list value :type return: list """
value = self.get(key, default) if isinstance(value, list): return value elif isinstance(value, ConfigTree): lst = [] for k, v in sorted(value.items(), key=lambda kv: kv[0]): if re.match('^[1-9][0-9]*$|0', k): lst.append(v) else: raise ConfigException(u"{key} does not translate to a list".format(key=key)) return lst elif value is None: return None else: raise ConfigException( u"{key} has type '{type}' rather than 'list'".format(key=key, type=type(value).__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 get_config(self, key, default=UndefinedKey): """Return tree config representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: config :return: config value :type return: ConfigTree """
value = self.get(key, default) if isinstance(value, dict): return value elif value is None: return None else: raise ConfigException( u"{key} has type '{type}' rather than 'config'".format(key=key, type=type(value).__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 as_plain_ordered_dict(self): """return a deep copy of this config as a plain OrderedDict The config tree should be fully resolved. This is useful to get an object with no special semantics such as path expansion for the keys. In particular this means that keys that contain dots are not surrounded with '"' in the plain OrderedDict. :return: this config as an OrderedDict :type return: OrderedDict """
def plain_value(v): if isinstance(v, list): return [plain_value(e) for e in v] elif isinstance(v, ConfigTree): return v.as_plain_ordered_dict() else: if isinstance(v, ConfigValues): raise ConfigException("The config tree contains unresolved elements") return v return OrderedDict((key.strip('"'), plain_value(value)) for key, value in self.items())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def labelLine(line, x, label=None, align=True, **kwargs): '''Label a single matplotlib line at position x Parameters ---------- line : matplotlib.lines.Line The line holding the label x : number The location in data unit of the label label : string, optional The label to set. This is inferred from the line by default kwargs : dict, optional Optional arguments passed to ax.text ''' ax = line.axes xdata = line.get_xdata() ydata = line.get_ydata() order = np.argsort(xdata) xdata = xdata[order] ydata = ydata[order] # Convert datetime objects to floats if isinstance(x, datetime): x = date2num(x) xmin, xmax = xdata[0], xdata[-1] if (x < xmin) or (x > xmax): raise Exception('x label location is outside data range!') # Find corresponding y co-ordinate and angle of the ip = 1 for i in range(len(xdata)): if x < xdata[i]: ip = i break y = ydata[ip-1] + (ydata[ip]-ydata[ip-1]) * \ (x-xdata[ip-1])/(xdata[ip]-xdata[ip-1]) if not label: label = line.get_label() if align: # Compute the slope dx = xdata[ip] - xdata[ip-1] dy = ydata[ip] - ydata[ip-1] ang = degrees(atan2(dy, dx)) # Transform to screen co-ordinates pt = np.array([x, y]).reshape((1, 2)) trans_angle = ax.transData.transform_angles(np.array((ang, )), pt)[0] else: trans_angle = 0 # Set a bunch of keyword arguments if 'color' not in kwargs: kwargs['color'] = line.get_color() if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs): kwargs['ha'] = 'center' if ('verticalalignment' not in kwargs) and ('va' not in kwargs): kwargs['va'] = 'center' if 'backgroundcolor' not in kwargs: kwargs['backgroundcolor'] = ax.get_facecolor() if 'clip_on' not in kwargs: kwargs['clip_on'] = True if 'zorder' not in kwargs: kwargs['zorder'] = 2.5 ax.text(x, y, label, rotation=trans_angle, **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 labelLines(lines, align=True, xvals=None, **kwargs): '''Label all lines with their respective legends. Parameters ---------- lines : list of matplotlib lines The lines to label align : boolean, optional If True, the label will be aligned with the slope of the line at the location of the label. If False, they will be horizontal. xvals : (xfirst, xlast) or array of float, optional The location of the labels. If a tuple, the labels will be evenly spaced between xfirst and xlast (in the axis units). kwargs : dict, optional Optional arguments passed to ax.text ''' ax = lines[0].axes labLines = [] labels = [] # Take only the lines which have labels other than the default ones for line in lines: label = line.get_label() if "_line" not in label: labLines.append(line) labels.append(label) if xvals is None: xvals = ax.get_xlim() # set axis limits as annotation limits, xvals now a tuple if type(xvals) == tuple: xmin, xmax = xvals xscale = ax.get_xscale() if xscale == "log": xvals = np.logspace(np.log10(xmin), np.log10(xmax), len(labLines)+2)[1:-1] else: xvals = np.linspace(xmin, xmax, len(labLines)+2)[1:-1] for line, x, label in zip(labLines, xvals, labels): labelLine(line, x, label, align, **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 new_as_dict(self, raw=True, vars=None): """Convert an INI file to a dictionary"""
# Load INI file into a dict result = {} for section in self.sections(): if section not in result: result[section] = {} for option in self.options(section): value = self.get(section, option, raw=raw, vars=vars) try: value = cherrypy.lib.reprconf.unrepr(value) except Exception: x = sys.exc_info()[1] msg = ("Config error in section: %r, option: %r, " "value: %r. Config values must be valid Python." % (section, option, value)) raise ValueError(msg, x.__class__.__name__, x.args) result[section][option] = value 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 auth(self, username, password): """ Check authentication against the backend :param username: 'key' attribute of the user :type username: string :param password: password of the user :type password: string :rtype: boolean (True is authentication success, False otherwise) """
if username not in self.users: return False elif self.users[username][self.pwd_attr] == password: return True return 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 add_user(self, attrs): """ Add a user to the backend :param attrs: attributes of the user :type attrs: dict ({<attr>: <value>}) .. warning:: raise UserAlreadyExists if user already exists """
username = attrs[self.key] if username in self.users: raise UserAlreadyExists(username, self.backend_name) self.users[username] = attrs self.users[username]['groups'] = 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 del_user(self, username): """ Delete a user from the backend :param username: 'key' attribute of the user :type username: string """
self._check_fix_users(username) try: del self.users[username] except Exception as e: raise UserDoesntExist(username, self.backend_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 set_attrs(self, username, attrs): """ set a list of attributes for a given user :param username: 'key' attribute of the user :type username: string :param attrs: attributes of the user :type attrs: dict ({<attr>: <value>}) """
self._check_fix_users(username) for attr in attrs: self.users[username][attr] = attrs[attr]
<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_to_groups(self, username, groups): """ Add a user to a list of groups :param username: 'key' attribute of the user :type username: string :param groups: list of groups :type groups: list of strings """
self._check_fix_users(username) current_groups = self.users[username]['groups'] new_groups = current_groups | set(groups) self.users[username]['groups'] = new_groups
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, searchstring): """ Search backend for users :param searchstring: the search string :type searchstring: string :rtype: dict of dict ( {<user attr key>: {<attr>: <value>}} ) """
ret = {} for user in self.users: match = False for attr in self.search_attrs: if attr not in self.users[user]: pass elif re.search(searchstring + '.*', self.users[user][attr]): match = True if match: ret[user] = self.users[user] return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(self, username): """ Get a user's attributes :param username: 'key' attribute of the user :type username: string :rtype: dict ( {<attr>: <value>} ) .. warning:: raise UserDoesntExist if user doesn't exist """
try: return self.users[username] except Exception as e: raise UserDoesntExist(username, self.backend_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 get_groups(self, username): """ Get a user's groups :param username: 'key' attribute of the user :type username: string :rtype: list of groups """
try: return self.users[username]['groups'] except Exception as e: raise UserDoesntExist(username, self.backend_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 get_loglevel(level): """ return logging level object corresponding to a given level passed as a string @str level: name of a syslog log level @rtype: logging, logging level from logging module """
if level == 'debug': return logging.DEBUG elif level == 'notice': return logging.INFO elif level == 'info': return logging.INFO elif level == 'warning' or level == 'warn': return logging.WARNING elif level == 'error' or level == 'err': return logging.ERROR elif level == 'critical' or level == 'crit': return logging.CRITICAL elif level == 'alert': return logging.CRITICAL elif level == 'emergency' or level == 'emerg': return logging.CRITICAL else: return logging.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 _normalize_group_attrs(self, attrs): """Normalize the attributes used to set groups If it's a list of one element, it just become this element. It raises an error if the attribute doesn't exist or if it's multivaluated. """
for key in self.group_attrs_keys: if key not in attrs: raise MissingGroupAttr(key) if type(attrs[key]) is list and len(attrs[key]) == 1: attrs[key] = attrs[key][0] if type(attrs[key]) is list and len(attrs[key]) != 1: raise MultivaluedGroupAttr(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 _connect(self): """Initialize an ldap client"""
ldap_client = ldap.initialize(self.uri) ldap.set_option(ldap.OPT_REFERRALS, 0) ldap.set_option(ldap.OPT_TIMEOUT, self.timeout) if self.starttls == 'on': ldap.set_option(ldap.OPT_X_TLS_DEMAND, True) else: ldap.set_option(ldap.OPT_X_TLS_DEMAND, False) # set the CA file if declared and if necessary if self.ca and self.checkcert == 'on': # check if the CA file actually exists if os.path.isfile(self.ca): ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.ca) else: raise CaFileDontExist(self.ca) if self.checkcert == 'off': # this is dark magic # remove any of these two lines and it doesn't work ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) ldap_client.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER ) else: # this is even darker magic ldap_client.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND ) # it doesn't make sense to set it to never # (== don't check certifate) # but it only works with this option... # ... and it checks the certificat # (I've lost my sanity over this) ldap.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER ) if self.starttls == 'on': try: ldap_client.start_tls_s() except Exception as e: self._exception_handler(e) return ldap_client
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bind(self): """bind to the ldap with the technical account"""
ldap_client = self._connect() try: ldap_client.simple_bind_s(self.binddn, self.bindpassword) except Exception as e: ldap_client.unbind_s() self._exception_handler(e) return ldap_client
<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(self, username, attrs=ALL_ATTRS): """Get a user from the ldap"""
username = ldap.filter.escape_filter_chars(username) user_filter = self.user_filter_tmpl % { 'username': self._uni(username) } r = self._search(self._byte_p2(user_filter), attrs, self.userdn) if len(r) == 0: return None # if NO_ATTR, only return the DN if attrs == NO_ATTR: dn_entry = r[0][0] # in other cases, return everything (dn + attributes) else: dn_entry = r[0] return dn_entry
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth(self, username, password): """Authentication of a user"""
binddn = self._get_user(self._byte_p2(username), NO_ATTR) if binddn is not None: ldap_client = self._connect() try: ldap_client.simple_bind_s( self._byte_p2(binddn), self._byte_p2(password) ) except ldap.INVALID_CREDENTIALS: ldap_client.unbind_s() return False ldap_client.unbind_s() return True else: return 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 add_user(self, attrs): """add a user"""
ldap_client = self._bind() # encoding crap attrs_srt = self.attrs_pretreatment(attrs) attrs_srt[self._byte_p2('objectClass')] = self.objectclasses # construct is DN dn = \ self._byte_p2(self.dn_user_attr) + \ self._byte_p2('=') + \ self._byte_p2(ldap.dn.escape_dn_chars( attrs[self.dn_user_attr] ) ) + \ self._byte_p2(',') + \ self._byte_p2(self.userdn) # gen the ldif first add_s and add the user ldif = modlist.addModlist(attrs_srt) try: ldap_client.add_s(dn, ldif) except ldap.ALREADY_EXISTS as e: raise UserAlreadyExists(attrs[self.key], self.backend_name) except Exception as e: ldap_client.unbind_s() self._exception_handler(e) ldap_client.unbind_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 del_user(self, username): """delete a user"""
ldap_client = self._bind() # recover the user dn dn = self._byte_p2(self._get_user(self._byte_p2(username), NO_ATTR)) # delete if dn is not None: ldap_client.delete_s(dn) else: ldap_client.unbind_s() raise UserDoesntExist(username, self.backend_name) ldap_client.unbind_s()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attrs(self, username, attrs): """ set user attributes"""
ldap_client = self._bind() tmp = self._get_user(self._byte_p2(username), ALL_ATTRS) if tmp is None: raise UserDoesntExist(username, self.backend_name) dn = self._byte_p2(tmp[0]) old_attrs = tmp[1] for attr in attrs: bcontent = self._byte_p2(attrs[attr]) battr = self._byte_p2(attr) new = {battr: self._modlist(self._byte_p3(bcontent))} # if attr is dn entry, use rename if attr.lower() == self.dn_user_attr.lower(): ldap_client.rename_s( dn, ldap.dn.dn2str([[(battr, bcontent, 1)]]) ) dn = ldap.dn.dn2str( [[(battr, bcontent, 1)]] + ldap.dn.str2dn(dn)[1:] ) else: # if attr is already set, replace the value # (see dict old passed to modifyModlist) if attr in old_attrs: if type(old_attrs[attr]) is list: tmp = [] for value in old_attrs[attr]: tmp.append(self._byte_p2(value)) bold_value = tmp else: bold_value = self._modlist( self._byte_p3(old_attrs[attr]) ) old = {battr: bold_value} # attribute is not set, just add it else: old = {} ldif = modlist.modifyModlist(old, new) if ldif: try: ldap_client.modify_s(dn, ldif) except Exception as e: ldap_client.unbind_s() self._exception_handler(e) ldap_client.unbind_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 del_from_groups(self, username, groups): """Delete user from groups"""
# it follows the same logic than add_to_groups # but with MOD_DELETE ldap_client = self._bind() tmp = self._get_user(self._byte_p2(username), ALL_ATTRS) if tmp is None: raise UserDoesntExist(username, self.backend_name) dn = tmp[0] attrs = tmp[1] attrs['dn'] = dn self._normalize_group_attrs(attrs) dn = self._byte_p2(tmp[0]) for group in groups: group = self._byte_p2(group) for attr in self.group_attrs: content = self._byte_p2(self.group_attrs[attr] % attrs) ldif = [(ldap.MOD_DELETE, attr, self._byte_p3(content))] try: ldap_client.modify_s(group, ldif) except ldap.NO_SUCH_ATTRIBUTE as e: self._logger( severity=logging.INFO, msg="%(backend)s: user '%(user)s'" " wasn't member of group '%(group)s'" " (attribute '%(attr)s')" % { 'user': username, 'group': self._uni(group), 'attr': attr, 'backend': self.backend_name } ) except Exception as e: ldap_client.unbind_s() self._exception_handler(e) ldap_client.unbind_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 get_user(self, username): """Gest a specific user"""
ret = {} tmp = self._get_user(self._byte_p2(username), ALL_ATTRS) if tmp is None: raise UserDoesntExist(username, self.backend_name) attrs_tmp = tmp[1] for attr in attrs_tmp: value_tmp = attrs_tmp[attr] if len(value_tmp) == 1: ret[attr] = value_tmp[0] else: ret[attr] = value_tmp return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_groups(self, username): """Get all groups of a user"""
username = ldap.filter.escape_filter_chars(self._byte_p2(username)) userdn = self._get_user(username, NO_ATTR) searchfilter = self.group_filter_tmpl % { 'userdn': userdn, 'username': username } groups = self._search(searchfilter, NO_ATTR, self.groupdn) ret = [] for entry in groups: ret.append(self._uni(entry[0])) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_groups(self, backends_list): """ merge a list backends_groups"""
ret = {} for backends in backends_list: for b in backends: if b not in ret: ret[b] = set([]) for group in backends[b]: ret[b].add(group) for b in ret: ret[b] = list(ret[b]) ret[b].sort() return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_parent(self, roleid1, roleid2): """Test if roleid1 is contained inside roleid2"""
role2 = copy.deepcopy(self.flatten[roleid2]) role1 = copy.deepcopy(self.flatten[roleid1]) if role1 == role2: return False # Check if role1 is contained by role2 for b1 in role1['backends_groups']: if b1 not in role2['backends_groups']: return False for group in role1['backends_groups'][b1]: if group not in role2['backends_groups'][b1]: return False # If role2 is inside role1, roles are equal, throw exception for b2 in role2['backends_groups']: if b2 not in role1['backends_groups']: return True for group in role2['backends_groups'][b2]: if group not in role1['backends_groups'][b2]: return True raise DumplicateRoleContent(roleid1, roleid2)
<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_groups_to_remove(self, current_roles, roles_to_remove): """get groups to remove from list of roles to remove and current roles """
current_roles = set(current_roles) ret = {} roles_to_remove = set(roles_to_remove) tmp = set([]) # get sub roles of the role to remove that the user belongs to # if we remove a role, there is no reason to keep the sub roles for r in roles_to_remove: for sr in self._get_subroles(r): if sr not in roles_to_remove and sr in current_roles: tmp.add(sr) roles_to_remove = roles_to_remove.union(tmp) roles = current_roles.difference(set(roles_to_remove)) groups_roles = self._get_groups(roles) groups_roles_to_remove = self._get_groups(roles_to_remove) # if groups belongs to roles the user keeps, don't remove it for b in groups_roles_to_remove: if b in groups_roles: groups_roles_to_remove[b] = \ groups_roles_to_remove[b].difference(groups_roles[b]) return groups_roles_to_remove
<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_roles(self, groups): """get list of roles and list of standalone groups"""
roles = set([]) parentroles = set([]) notroles = set([]) tmp = set([]) usedgroups = {} unusedgroups = {} ret = {} # determine roles membership for role in self.roles: if self._check_member( role, groups, notroles, tmp, parentroles, usedgroups): roles.add(role) # determine standalone groups not matching any roles for b in groups: for g in groups[b]: if b not in usedgroups or g not in usedgroups[b]: if b not in unusedgroups: unusedgroups[b] = set([]) unusedgroups[b].add(g) ret['roles'] = roles ret['unusedgroups'] = unusedgroups return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_display_name(self, role): """get the display name of a role"""
if role not in self.flatten: raise MissingRole(role) return self.flatten[role]['display_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 get_groups(self, roles): """get the list of groups from role"""
ret = {} for role in roles: if role not in self.flatten: raise MissingRole(role) for b in self.flatten[role]['backends_groups']: if b not in ret: ret[b] = [] ret[b] = ret[b] + self.flatten[role]['backends_groups'][b] return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_admin(self, roles): """determine from a list of roles if is ldapcherry administrator"""
for r in roles: if r in self.admin_roles: return True return 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 _get_param(self, section, key, config, default=None): """ Get configuration parameter "key" from config @str section: the section of the config file @str key: the key to get @dict config: the configuration (dictionnary) @str default: the default value if parameter "key" is not present @rtype: str (value of config['key'] if present default otherwith """
if section in config and key in config[section]: return config[section][key] if default is not None: return default else: raise MissingParameter(section, 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 _get_groups(self, username): """ Get groups of a user @str username: name of the user @rtype: dict, format { '<backend>': [<list of groups>] } """
ret = {} for b in self.backends: ret[b] = self.backends[b].get_groups(username) cherrypy.log.error( msg="user '" + username + "' groups: " + str(ret), severity=logging.DEBUG, ) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_roles(self, username): """ Get roles of a user @str username: name of the user @rtype: dict, format { 'roles': [<list of roles>], 'unusedgroups': [<list of groups not matching roles>] } """
groups = self._get_groups(username) user_roles = self.roles.get_roles(groups) cherrypy.log.error( msg="user '" + username + "' roles: " + str(user_roles), severity=logging.DEBUG, ) return user_roles
<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_admin(self, username): """ Check if a user is an ldapcherry administrator @str username: name of the user @rtype: bool, True if administrator, False otherwise """
roles = self._get_roles(username) return self.roles.is_admin(roles['roles'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_backends(self): """ Check that every backend in roles and attributes is declared in main configuration """
backends = self.backends_params.keys() for b in self.roles.get_backends(): if b not in backends: raise MissingBackend(b, 'role') for b in self.attributes.get_backends(): if b not in backends: raise MissingBackend(b, 'attribute')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_backends(self, config): """ Init all backends @dict: configuration of ldapcherry """
self.backends_params = {} self.backends = {} self.backends_display_names = {} for entry in config['backends']: # split at the first dot backend, sep, param = entry.partition('.') value = config['backends'][entry] if backend not in self.backends_params: self.backends_params[backend] = {} self.backends_params[backend][param] = value for backend in self.backends_params: # get the backend display_name try: self.backends_display_names[backend] = \ self.backends_params[backend]['display_name'] except Exception as e: self.backends_display_names[backend] = backend self.backends_params[backend]['display_name'] = backend params = self.backends_params[backend] # Loading the backend module try: module = params['module'] except Exception as e: raise MissingParameter('backends', backend + '.module') try: bc = __import__(module, globals(), locals(), ['Backend'], 0) except Exception as e: self._handle_exception(e) raise BackendModuleLoadingFail(module) try: attrslist = self.attributes.get_backend_attributes(backend) key = self.attributes.get_backend_key(backend) self.backends[backend] = bc.Backend( params, cherrypy.log.error, backend, attrslist, key, ) except MissingParameter as e: raise except Exception as e: self._handle_exception(e) raise BackendModuleInitFail(module)
<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_access_log(self, config, level): """ Configure access logs """
access_handler = self._get_param( 'global', 'log.access_handler', config, 'syslog', ) # log format for syslog syslog_formatter = logging.Formatter( "ldapcherry[%(process)d]: %(message)s" ) # replace access log handler by a syslog handler if access_handler == 'syslog': cherrypy.log.access_log.handlers = [] handler = logging.handlers.SysLogHandler( address='/dev/log', facility='user', ) handler.setFormatter(syslog_formatter) cherrypy.log.access_log.addHandler(handler) # if stdout, open a logger on stdout elif access_handler == 'stdout': cherrypy.log.access_log.handlers = [] handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( 'ldapcherry.access - %(levelname)s - %(message)s' ) handler.setFormatter(formatter) cherrypy.log.access_log.addHandler(handler) # if file, we keep the default elif access_handler == 'file': pass # replace access log handler by a null handler elif access_handler == 'none': cherrypy.log.access_log.handlers = [] handler = logging.NullHandler() cherrypy.log.access_log.addHandler(handler) # set log level cherrypy.log.access_log.setLevel(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_error_log(self, config, level, debug=False): """ Configure error logs """
error_handler = self._get_param( 'global', 'log.error_handler', config, 'syslog' ) # log format for syslog syslog_formatter = logging.Formatter( "ldapcherry[%(process)d]: %(message)s", ) # replacing the error handler by a syslog handler if error_handler == 'syslog': cherrypy.log.error_log.handlers = [] # redefining log.error method because cherrypy does weird # things like adding the date inside the message # or adding space even if context is empty # (by the way, what's the use of "context"?) cherrypy.log.error = syslog_error handler = logging.handlers.SysLogHandler( address='/dev/log', facility='user', ) handler.setFormatter(syslog_formatter) cherrypy.log.error_log.addHandler(handler) # if stdout, open a logger on stdout elif error_handler == 'stdout': cherrypy.log.error_log.handlers = [] handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( 'ldapcherry.app - %(levelname)s - %(message)s' ) handler.setFormatter(formatter) cherrypy.log.error_log.addHandler(handler) # if file, we keep the default elif error_handler == 'file': pass # replacing the error handler by a null handler elif error_handler == 'none': cherrypy.log.error_log.handlers = [] handler = logging.NullHandler() cherrypy.log.error_log.addHandler(handler) # set log level cherrypy.log.error_log.setLevel(level) if debug: cherrypy.log.error_log.handlers = [] handler = logging.StreamHandler(sys.stderr) handler.setLevel(logging.DEBUG) cherrypy.log.error_log.addHandler(handler) cherrypy.log.error_log.setLevel(logging.DEBUG)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _auth(self, user, password): """ authenticate a user @str user: login of the user @str password: password of the user @rtype: dict, {'connected': <boolean, True if connection succeded>, 'isadmin': <True if user is ldapcherry administrator>} """
if self.auth_mode == 'none': return {'connected': True, 'isadmin': True} elif self.auth_mode == 'and': ret1 = True for b in self.backends: ret1 = self.backends[b].auth(user, password) and ret1 elif self.auth_mode == 'or': ret1 = False for b in self.backends: ret1 = self.backends[b].auth(user, password) or ret1 elif self.auth_mode == 'custom': ret1 = self.auth.auth(user, password) else: raise Exception() if not ret1: return {'connected': False, 'isadmin': False} else: isadmin = self._is_admin(user) return {'connected': True, 'isadmin': isadmin}
<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_notification(self, message): """ add a notification in the notification queue of a user """
sess = cherrypy.session username = sess.get(SESSION_KEY, None) if username not in self.notifications: self.notifications[username] = [] self.notifications[username].append(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 _empty_notification(self): """ empty and return list of message notification """
sess = cherrypy.session username = sess.get(SESSION_KEY, None) if username in self.notifications: ret = self.notifications[username] else: ret = [] self.notifications[username] = [] return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_user_attrs(self, attrs_backend, attrs_out, backend_name): """ merge attributes from one backend search to the attributes dict output """
for attr in attrs_backend: if attr in self.attributes.backend_attributes[backend_name]: attrid = self.attributes.backend_attributes[backend_name][attr] if attrid not in attrs_out: attrs_out[attrid] = attrs_backend[attr]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(self): """main page rendering """
self._check_auth(must_admin=False) is_admin = self._check_admin() sess = cherrypy.session user = sess.get(SESSION_KEY, None) if self.auth_mode == 'none': user_attrs = None else: user_attrs = self._get_user(user) attrs_list = self.attributes.get_search_attributes() return self.temp['index.tmpl'].render( is_admin=is_admin, attrs_list=attrs_list, searchresult=user_attrs, notifications=self._empty_notification(), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adduser(self, **params): """ add user page """
self._check_auth(must_admin=True) is_admin = self._check_admin() if cherrypy.request.method.upper() == 'POST': params = self._parse_params(params) self._adduser(params) self._add_notification("User added") graph = {} for r in self.roles.graph: s = list(self.roles.graph[r]['sub_roles']) p = list(self.roles.graph[r]['parent_roles']) graph[r] = {'sub_roles': s, 'parent_roles': p} graph_js = json.dumps(graph, separators=(',', ':')) display_names = {} for r in self.roles.flatten: display_names[r] = self.roles.flatten[r]['display_name'] roles_js = json.dumps(display_names, separators=(',', ':')) try: form = self.temp['form.tmpl'].render( attributes=self.attributes.attributes, values=None, modify=False, autofill=True ) roles = self.temp['roles.tmpl'].render( roles=self.roles.flatten, graph=self.roles.graph, graph_js=graph_js, roles_js=roles_js, current_roles=None, ) return self.temp['adduser.tmpl'].render( form=form, roles=roles, is_admin=is_admin, custom_js=self.custom_js, notifications=self._empty_notification(), ) except NameError: raise TemplateRenderError( exceptions.text_error_template().render() )
<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, user): """ remove user page """
self._check_auth(must_admin=True) is_admin = self._check_admin() try: referer = cherrypy.request.headers['Referer'] except Exception as e: referer = '/' self._deleteuser(user) self._add_notification('User Deleted') raise cherrypy.HTTPRedirect(referer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(self, user=None, **params): """ modify user page """
self._check_auth(must_admin=True) is_admin = self._check_admin() if cherrypy.request.method.upper() == 'POST': params = self._parse_params(params) self._modify(params) self._add_notification("User modified") try: referer = cherrypy.request.headers['Referer'] except Exception as e: referer = '/' raise cherrypy.HTTPRedirect(referer) graph = {} for r in self.roles.graph: s = list(self.roles.graph[r]['sub_roles']) p = list(self.roles.graph[r]['parent_roles']) graph[r] = {'sub_roles': s, 'parent_roles': p} graph_js = json.dumps(graph, separators=(',', ':')) display_names = {} for r in self.roles.flatten: display_names[r] = self.roles.flatten[r]['display_name'] if user is None: cherrypy.response.status = 400 return self.temp['error.tmpl'].render( is_admin=is_admin, alert='warning', message="No user requested" ) user_attrs = self._get_user(user) if user_attrs == {}: cherrypy.response.status = 400 return self.temp['error.tmpl'].render( is_admin=is_admin, alert='warning', message="User '" + user + "' does not exist" ) tmp = self._get_roles(user) user_roles = tmp['roles'] standalone_groups = tmp['unusedgroups'] roles_js = json.dumps(display_names, separators=(',', ':')) key = self.attributes.get_key() try: form = self.temp['form.tmpl'].render( attributes=self.attributes.attributes, values=user_attrs, modify=True, keyattr=key, autofill=False ) roles = self.temp['roles.tmpl'].render( roles=self.roles.flatten, graph=self.roles.graph, graph_js=graph_js, roles_js=roles_js, current_roles=user_roles, ) glued_template = self.temp['modify.tmpl'].render( form=form, roles=roles, is_admin=is_admin, standalone_groups=standalone_groups, backends_display_names=self.backends_display_names, custom_js=self.custom_js, notifications=self._empty_notification(), ) except NameError: raise TemplateRenderError( exceptions.text_error_template().render() ) return glued_template
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selfmodify(self, **params): """ self modify user page """
self._check_auth(must_admin=False) is_admin = self._check_admin() sess = cherrypy.session user = sess.get(SESSION_KEY, None) if self.auth_mode == 'none': return self.temp['error.tmpl'].render( is_admin=is_admin, alert='warning', message="Not accessible with authentication disabled." ) if cherrypy.request.method.upper() == 'POST': params = self._parse_params(params) self._selfmodify(params) self._add_notification( "Self modification done" ) user_attrs = self._get_user(user) try: if user_attrs == {}: return self.temp['error.tmpl'].render( is_admin=is_admin, alert='warning', message="User doesn't exist" ) form = self.temp['form.tmpl'].render( attributes=self.attributes.get_selfattributes(), values=user_attrs, modify=True, autofill=False ) return self.temp['selfmodify.tmpl'].render( form=form, is_admin=is_admin, notifications=self._empty_notification(), ) except NameError: raise TemplateRenderError( exceptions.text_error_template().render() )
<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_to_response(self, context, *args, **kwargs): """ Build dictionary of content """
preview_outputs = [] file_outputs = [] bast_ctx = context added = set() for output_group, output_files in context['job_info']['file_groups'].items(): for output_file_content in output_files: if output_group: bast_ctx.update({ 'job_info': context['job_info'], 'output_group': output_group, 'output_file_content': output_file_content, }) preview = render_to_string('wooey/preview/%s.html' % output_group, bast_ctx) preview_outputs.append(preview) for file_info in context['job_info']['all_files']: if file_info and file_info.get('name') not in added: row_ctx = dict( file=file_info, **context ) table_row = render_to_string('wooey/jobs/results/table_row.html', row_ctx) file_outputs.append(table_row) added.add(file_info.get('name')) return JsonResponse({ 'status': context['job_info']['status'].lower(), 'command': context['job_info']['job'].command, 'stdout': context['job_info']['job'].get_stdout(), 'stderr': context['job_info']['job'].get_stderr(), 'preview_outputs_html': preview_outputs, 'file_outputs_html': file_outputs, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup_dead_jobs(): """ This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant to cleanup jobs that have been lost due to a server crash or some other reason a job is in limbo. """
from .models import WooeyJob # Get active tasks from Celery inspect = celery_app.control.inspect() active_tasks = {task['id'] for worker, tasks in six.iteritems(inspect.active()) for task in tasks} # find jobs that are marked as running but not present in celery's active tasks active_jobs = WooeyJob.objects.filter(status=WooeyJob.RUNNING) to_disable = set() for job in active_jobs: if job.celery_id not in active_tasks: to_disable.add(job.pk) WooeyJob.objects.filter(pk__in=to_disable).update(status=WooeyJob.FAILED)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_query(query_string, findterms=re.compile(r'"([^"]+)"|(\S+)').findall, normspace=re.compile(r'\s{2,}').sub): """ Split the query string into individual keywords, discarding spaces and grouping quoted words together. ['some', 'random', 'words', 'with quotes', 'and', 'spaces'] """
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_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 save(self, *args, **kwargs): """ Saves model and set initial state. """
super(ModelDiffMixin, self).save(*args, **kwargs) self.__initial = self._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 _load_text_assets(self, text_image_file, text_file): """ Internal. Builds a character indexed dictionary of pixels used by the show_message function below """
text_pixels = self.load_image(text_image_file, False) with open(text_file, 'r') as f: loaded_text = f.read() self._text_dict = {} for index, s in enumerate(loaded_text): start = index * 40 end = start + 40 char = text_pixels[start:end] self._text_dict[s] = char
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _trim_whitespace(self, char): # For loading text assets only """ Internal. Trims white space pixels from the front and back of loaded text characters """
psum = lambda x: sum(sum(x, [])) if psum(char) > 0: is_empty = True while is_empty: # From front row = char[0:8] is_empty = psum(row) == 0 if is_empty: del char[0:8] is_empty = True while is_empty: # From back row = char[-8:] is_empty = psum(row) == 0 if is_empty: del char[-8:] return char
<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_settings_file(self, imu_settings_file): """ Internal. Logic to check for a system wide RTIMU ini file. This is copied to the home folder if one is not already found there. """
ini_file = '%s.ini' % imu_settings_file home_dir = pwd.getpwuid(os.getuid())[5] home_path = os.path.join(home_dir, self.SETTINGS_HOME_PATH) if not os.path.exists(home_path): os.makedirs(home_path) home_file = os.path.join(home_path, ini_file) home_exists = os.path.isfile(home_file) system_file = os.path.join('/etc', ini_file) system_exists = os.path.isfile(system_file) if system_exists and not home_exists: shutil.copyfile(system_file, home_file) return RTIMU.Settings(os.path.join(home_path, imu_settings_file))
<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_rotation(self, r=0, redraw=True): """ Sets the LED matrix rotation for viewing, adjust if the Pi is upside down or sideways. 0 is with the Pi HDMI port facing downwards """
if r in self._pix_map.keys(): if redraw: pixel_list = self.get_pixels() self._rotation = r if redraw: self.set_pixels(pixel_list) else: raise ValueError('Rotation must be 0, 90, 180 or 270 degrees')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flip_h(self, redraw=True): """ Flip LED matrix horizontal """
pixel_list = self.get_pixels() flipped = [] for i in range(8): offset = i * 8 flipped.extend(reversed(pixel_list[offset:offset + 8])) if redraw: self.set_pixels(flipped) return flipped
<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_image(self, file_path, redraw=True): """ Accepts a path to an 8 x 8 image file and updates the LED matrix with the image """
if not os.path.exists(file_path): raise IOError('%s not found' % file_path) img = Image.open(file_path).convert('RGB') pixel_list = list(map(list, img.getdata())) if redraw: self.set_pixels(pixel_list) return pixel_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 _get_char_pixels(self, s): """ Internal. Safeguards the character indexed dictionary for the show_message function below """
if len(s) == 1 and s in self._text_dict.keys(): return list(self._text_dict[s]) else: return list(self._text_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 show_message( self, text_string, scroll_speed=.1, text_colour=[255, 255, 255], back_colour=[0, 0, 0] ): """ Scrolls a string of text across the LED matrix using the specified speed and colours """
# We must rotate the pixel map left through 90 degrees when drawing # text, see _load_text_assets previous_rotation = self._rotation self._rotation -= 90 if self._rotation < 0: self._rotation = 270 dummy_colour = [None, None, None] string_padding = [dummy_colour] * 64 letter_padding = [dummy_colour] * 8 # Build pixels from dictionary scroll_pixels = [] scroll_pixels.extend(string_padding) for s in text_string: scroll_pixels.extend(self._trim_whitespace(self._get_char_pixels(s))) scroll_pixels.extend(letter_padding) scroll_pixels.extend(string_padding) # Recolour pixels as necessary coloured_pixels = [ text_colour if pixel == [255, 255, 255] else back_colour for pixel in scroll_pixels ] # Shift right by 8 pixels per frame to scroll scroll_length = len(coloured_pixels) // 8 for i in range(scroll_length - 8): start = i * 8 end = start + 64 self.set_pixels(coloured_pixels[start:end]) time.sleep(scroll_speed) self._rotation = previous_rotation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_letter( self, s, text_colour=[255, 255, 255], back_colour=[0, 0, 0] ): """ Displays a single text character on the LED matrix using the specified colours """
if len(s) > 1: raise ValueError('Only one character may be passed into this method') # We must rotate the pixel map left through 90 degrees when drawing # text, see _load_text_assets previous_rotation = self._rotation self._rotation -= 90 if self._rotation < 0: self._rotation = 270 dummy_colour = [None, None, None] pixel_list = [dummy_colour] * 8 pixel_list.extend(self._get_char_pixels(s)) pixel_list.extend([dummy_colour] * 16) coloured_pixels = [ text_colour if pixel == [255, 255, 255] else back_colour for pixel in pixel_list ] self.set_pixels(coloured_pixels) self._rotation = previous_rotation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gamma_reset(self): """ Resets the LED matrix gamma correction to default """
with open(self._fb_device) as f: fcntl.ioctl(f, self.SENSE_HAT_FB_FBIORESET_GAMMA, self.SENSE_HAT_FB_GAMMA_DEFAULT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_humidity(self): """ Internal. Initialises the humidity sensor via RTIMU """
if not self._humidity_init: self._humidity_init = self._humidity.humidityInit() if not self._humidity_init: raise OSError('Humidity Init Failed')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_pressure(self): """ Internal. Initialises the pressure sensor via RTIMU """
if not self._pressure_init: self._pressure_init = self._pressure.pressureInit() if not self._pressure_init: raise OSError('Pressure Init Failed')
<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_humidity(self): """ Returns the percentage of relative humidity """
self._init_humidity() # Ensure humidity sensor is initialised humidity = 0 data = self._humidity.humidityRead() if (data[0]): # Humidity valid humidity = data[1] return humidity
<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_temperature_from_humidity(self): """ Returns the temperature in Celsius from the humidity sensor """
self._init_humidity() # Ensure humidity sensor is initialised temp = 0 data = self._humidity.humidityRead() if (data[2]): # Temp valid temp = data[3] return temp
<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_temperature_from_pressure(self): """ Returns the temperature in Celsius from the pressure sensor """
self._init_pressure() # Ensure pressure sensor is initialised temp = 0 data = self._pressure.pressureRead() if (data[2]): # Temp valid temp = data[3] return temp
<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_pressure(self): """ Returns the pressure in Millibars """
self._init_pressure() # Ensure pressure sensor is initialised pressure = 0 data = self._pressure.pressureRead() if (data[0]): # Pressure valid pressure = data[1] return pressure
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_imu(self): """ Internal. Initialises the IMU sensor via RTIMU """
if not self._imu_init: self._imu_init = self._imu.IMUInit() if self._imu_init: self._imu_poll_interval = self._imu.IMUGetPollInterval() * 0.001 # Enable everything on IMU self.set_imu_config(True, True, True) else: raise OSError('IMU Init Failed')
<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_imu(self): """ Internal. Tries to read the IMU sensor three times before giving up """
self._init_imu() # Ensure imu is initialised attempts = 0 success = False while not success and attempts < 3: success = self._imu.IMURead() attempts += 1 time.sleep(self._imu_poll_interval) return success
<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_raw_data(self, is_valid_key, data_key): """ Internal. Returns the specified raw data from the IMU when valid """
result = None if self._read_imu(): data = self._imu.getIMUData() if data[is_valid_key]: raw = data[data_key] result = { 'x': raw[0], 'y': raw[1], 'z': raw[2] } return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_orientation_radians(self): """ Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch, roll and yaw """
raw = self._get_raw_data('fusionPoseValid', 'fusionPose') if raw is not None: raw['roll'] = raw.pop('x') raw['pitch'] = raw.pop('y') raw['yaw'] = raw.pop('z') self._last_orientation = raw return deepcopy(self._last_orientation)
<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_orientation_degrees(self): """ Returns a dictionary object to represent the current orientation in degrees, 0 to 360, using the aircraft principal axes of pitch, roll and yaw """
orientation = self.get_orientation_radians() for key, val in orientation.items(): deg = math.degrees(val) # Result is -180 to +180 orientation[key] = deg + 360 if deg < 0 else deg return orientation
<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_compass(self): """ Gets the direction of North from the magnetometer in degrees """
self.set_imu_config(True, False, False) orientation = self.get_orientation_degrees() if type(orientation) is dict and 'yaw' in orientation.keys(): return orientation['yaw'] else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_gyroscope_raw(self): """ Gyroscope x y z raw data in radians per second """
raw = self._get_raw_data('gyroValid', 'gyro') if raw is not None: self._last_gyro_raw = raw return deepcopy(self._last_gyro_raw)
<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_accelerometer_raw(self): """ Accelerometer x y z raw data in Gs """
raw = self._get_raw_data('accelValid', 'accel') if raw is not None: self._last_accel_raw = raw return deepcopy(self._last_accel_raw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stick_device(self): """ Discovers the filename of the evdev device that represents the Sense HAT's joystick. """
for evdev in glob.glob('/sys/class/input/event*'): try: with io.open(os.path.join(evdev, 'device', 'name'), 'r') as f: if f.read().strip() == self.SENSE_HAT_EVDEV_NAME: return os.path.join('/dev', 'input', os.path.basename(evdev)) except IOError as e: if e.errno != errno.ENOENT: raise raise RuntimeError('unable to locate SenseHAT joystick device')
<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(self): """ Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise. """
event = self._stick_file.read(self.EVENT_SIZE) (tv_sec, tv_usec, type, code, value) = struct.unpack(self.EVENT_FORMAT, event) if type == self.EV_KEY: return InputEvent( timestamp=tv_sec + (tv_usec / 1000000), direction={ self.KEY_UP: DIRECTION_UP, self.KEY_DOWN: DIRECTION_DOWN, self.KEY_LEFT: DIRECTION_LEFT, self.KEY_RIGHT: DIRECTION_RIGHT, self.KEY_ENTER: DIRECTION_MIDDLE, }[code], action={ self.STATE_PRESS: ACTION_PRESSED, self.STATE_RELEASE: ACTION_RELEASED, self.STATE_HOLD: ACTION_HELD, }[value]) else: 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 wait_for_event(self, emptybuffer=False): """ Waits until a joystick event becomes available. Returns the event, as an `InputEvent` tuple. If *emptybuffer* is `True` (it defaults to `False`), any pending events will be thrown away first. This is most useful if you are only interested in "pressed" events. """
if emptybuffer: while self._wait(0): self._read() while self._wait(): event = self._read() if event: return event
<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_events(self): """ Returns a list of all joystick events that have occurred since the last call to `get_events`. The list contains events in the order that they occurred. If no events have occurred in the intervening time, the result is an empty list. """
result = [] while self._wait(0): event = self._read() if event: result.append(event) 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 signal_handler(sig, frame): """SIGINT handler. Disconnect all active clients and then invoke the original signal handler. """
for client in connected_clients[:]: if client.is_asyncio_based(): client.start_background_task(client.disconnect, abort=True) else: client.disconnect(abort=True) return original_signal_handler(sig, frame)
<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_background_task(self, target, *args, **kwargs): """Start a background task. This is a utility function that applications can use to start a background task. :param target: the target function to execute. :param args: arguments to pass to the function. :param kwargs: keyword arguments to pass to the function. This function returns an object compatible with the `Thread` class in the Python standard library. The `start()` method on this object is already called by this function. """
th = threading.Thread(target=target, args=args, kwargs=kwargs) th.start() return th
<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_engineio_url(self, url, engineio_path, transport): """Generate the Engine.IO connection URL."""
engineio_path = engineio_path.strip('/') parsed_url = urllib.parse.urlparse(url) if transport == 'polling': scheme = 'http' elif transport == 'websocket': scheme = 'ws' else: # pragma: no cover raise ValueError('invalid transport') if parsed_url.scheme in ['https', 'wss']: scheme += 's' return ('{scheme}://{netloc}/{path}/?{query}' '{sep}transport={transport}&EIO=3').format( scheme=scheme, netloc=parsed_url.netloc, path=engineio_path, query=parsed_url.query, sep='&' if parsed_url.query else '', transport=transport)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ping_loop(self): """This background task sends a PING to the server at the requested interval. """
self.pong_received = True self.ping_loop_event.clear() while self.state == 'connected': if not self.pong_received: self.logger.info( 'PONG response has not been received, aborting') if self.ws: self.ws.close() self.queue.put(None) break self.pong_received = False self._send_packet(packet.Packet(packet.PING)) self.ping_loop_event.wait(timeout=self.ping_interval) self.logger.info('Exiting ping task')
<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_loop_polling(self): """Read packets by polling the Engine.IO server."""
while self.state == 'connected': self.logger.info( 'Sending polling GET request to ' + self.base_url) r = self._send_request( 'GET', self.base_url + self._get_url_timestamp()) if r is None: self.logger.warning( 'Connection refused by the server, aborting') self.queue.put(None) break if r.status_code != 200: self.logger.warning('Unexpected status code %s in server ' 'response, aborting', r.status_code) self.queue.put(None) break try: p = payload.Payload(encoded_payload=r.content) except ValueError: self.logger.warning( 'Unexpected packet from server, aborting') self.queue.put(None) break for pkt in p.packets: self._receive_packet(pkt) self.logger.info('Waiting for write loop task to end') self.write_loop_task.join() self.logger.info('Waiting for ping loop task to end') self.ping_loop_event.set() self.ping_loop_task.join() if self.state == 'connected': self._trigger_event('disconnect', run_async=False) try: connected_clients.remove(self) except ValueError: # pragma: no cover pass self._reset() self.logger.info('Exiting read loop task')
<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_loop_websocket(self): """Read packets from the Engine.IO WebSocket connection."""
while self.state == 'connected': p = None try: p = self.ws.recv() except websocket.WebSocketConnectionClosedException: self.logger.warning( 'WebSocket connection was closed, aborting') self.queue.put(None) break except Exception as e: self.logger.info( 'Unexpected error "%s", aborting', str(e)) self.queue.put(None) break if isinstance(p, six.text_type): # pragma: no cover p = p.encode('utf-8') pkt = packet.Packet(encoded_packet=p) self._receive_packet(pkt) self.logger.info('Waiting for write loop task to end') self.write_loop_task.join() self.logger.info('Waiting for ping loop task to end') self.ping_loop_event.set() self.ping_loop_task.join() if self.state == 'connected': self._trigger_event('disconnect', run_async=False) try: connected_clients.remove(self) except ValueError: # pragma: no cover pass self._reset() self.logger.info('Exiting read loop task')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _upgrades(self, sid, transport): """Return the list of possible upgrades for a client connection."""
if not self.allow_upgrades or self._get_socket(sid).upgraded or \ self._async['websocket'] is None or transport == 'websocket': return [] return ['websocket']