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 dynacRepresentation(self): """ Return the Dynac representation of this cavity instance. """
return ['CAVMC', [ [self.cavID.val], [self.xesln.val, self.phase.val, self.fieldReduction.val, self.isec.val, 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 from_dynacRepr(cls, pynacRepr): """ Construct a ``AccGap`` instance from the Pynac lattice element """
pynacList = pynacRepr[1][0] L = float(pynacList[3]) TTF = float(pynacList[4]) TTFprime = float(pynacList[5]) TTFprimeprime = float(pynacList[13]) EField = float(pynacList[10]) phase = float(pynacList[11]) F = float(pynacList[14]) atten = float(pynacList[15]) gap = cls(L, TTF, TTFprime, TTFprimeprime, EField, phase, F, atten) gap.gapID = Param(val = int(pynacList[0]), unit = None) gap.energy = Param(val = float(pynacList[1]), unit = 'MeV') gap.beta = Param(val = float(pynacList[2]), unit = None) gap.S = Param(val = float(pynacList[6]), unit = None) gap.SP = Param(val = float(pynacList[7]), unit = None) gap.quadLength = Param(val = float(pynacList[8]), unit = 'cm') gap.quadStrength = Param(val = float(pynacList[9]), unit = 'kG/cm') gap.accumLen = Param(val = float(pynacList[12]), unit = 'cm') return gap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynacRepresentation(self): """ Return the Dynac representation of this accelerating gap instance. """
details = [ self.gapID.val, self.energy.val, self.beta.val, self.L.val, self.TTF.val, self.TTFprime.val, self.S.val, self.SP.val, self.quadLength.val, self.quadStrength.val, self.EField.val, self.phase.val, self.accumLen.val, self.TTFprimeprime.val, self.F.val, self.atten.val, ] return ['CAVSC', [details]]
<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_dynacRepr(cls, pynacRepr): """ Construct a ``Set4DAperture`` instance from the Pynac lattice element """
energyDefnFlag = int(pynacRepr[1][0][0]) energy = float(pynacRepr[1][0][1]) phase = float(pynacRepr[1][0][2]) x = float(pynacRepr[1][0][3]) y = float(pynacRepr[1][0][4]) radius = float(pynacRepr[1][0][5]) return cls(energy, phase, x, y, radius, energyDefnFlag)
<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_dynacRepr(cls, pynacRepr): """ Construct a ``Steerer`` instance from the Pynac lattice element """
f = float(pynacRepr[1][0][0]) p = 'HV'[int(pynacRepr[1][0][1])] return cls(f, p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynacRepresentation(self): """ Return the Dynac representation of this steerer instance. """
if self.plane.val == 'H': p = 0 elif self.plane.val == 'V': p = 1 return ['STEER', [[self.field_strength.val], [p]]]
<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(): """ parse command line opts and run a skeleton file when called from the command line, ligament looks in the current working directory for a file called `skeleton.py`. Tasks specified from the command line are then executed in order, and if the -w flag was specified, ligament then watches the filesystem for changes to prompt task re-execution; """
options = None try: options, args = getopt.gnu_getopt( sys.argv[1:], "whqv", ["watch", "help", "query", "verbose"]) except getopt.GetoptError as e: print e print_helptext() exit(1) should_watch = False query_skeleton = False verbose = False for opt, arg in options: if opt == "--watch" or opt == '-w': should_watch = True elif opt == "--query" or opt == '-q': query_skeleton = True elif opt == "--help" or opt == '-h': print_helptext() exit(0) elif opt == "--verbose" or opt == '-v': verbose = True else: print "option '%s' not recognized" % opt print_helptext() exit(1) if verbose: helpers.set_verbosity(".*") if query_skeleton: print " ".join(ligament.query_skeleton("./skeleton.py")) helpers.set_verbosity() else: helpers.add_verbosity_groups("build_task") ligament.run_skeleton( "./skeleton.py", ["default"] if len(args) == 0 else args, watch=should_watch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getter(self, obj): """Called when the parent element tries to get this property value. :param obj: parent object. """
result = None if self._fget_ is not None: result = self._fget_(obj) if result is None: result = getattr(obj, self._attrname(), self._default_) # notify parent schema about returned value if isinstance(obj, Schema): obj._getvalue(self, 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 _setter(self, obj, value): """Called when the parent element tries to set this property value. :param obj: parent object. :param value: new value to use. If lambda, updated with the lambda result. """
if isinstance(value, DynamicValue): # execute lambda values. fvalue = value() else: fvalue = value self._validate(data=fvalue, owner=obj) if self._fset_ is not None: self._fset_(obj, fvalue) else: setattr(obj, self._attrname(), value) # notify obj about the new value. if isinstance(obj, Schema): obj._setvalue(self, fvalue)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deleter(self, obj): """Called when the parent element tries to delete this property value. :param obj: parent object. """
if self._fdel_ is not None: self._fdel_(obj) else: delattr(obj, self._attrname()) # notify parent schema about value deletion. if isinstance(obj, Schema): obj._delvalue(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate(self, data, owner=None): """Validate input data in returning an empty list if true. :param data: data to validate with this schema. :param Schema owner: schema owner. :raises: Exception if the data is not validated. """
if isinstance(data, DynamicValue): data = data() if data is None and not self.nullable: raise ValueError('Value can not be null') elif data is not None: isdict = isinstance(data, dict) for name, schema in iteritems(self.getschemas()): if name == 'default': continue if name in self.required: if ( (isdict and name not in data) or (not isdict and not hasattr(data, name)) ): part1 = ( 'Mandatory property {0} by {1} is missing in {2}.'. format(name, self, data) ) part2 = '{0} expected.'.format(schema) error = '{0} {1}'.format(part1, part2) raise ValueError(error) elif (isdict and name in data) or hasattr(data, name): value = data[name] if isdict else getattr(data, name) schema._validate(data=value, owner=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getschemas(cls): """Get inner schemas by name. :return: ordered dict by name. :rtype: OrderedDict """
members = getmembers(cls, lambda member: isinstance(member, Schema)) result = OrderedDict() for name, member in members: result[name] = member 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_ability_desc(ability): """Return the description matching the given ability name. Check abilities.json in the same directory."""
srcpath = path.dirname(__file__) try: f = open(path.join(srcpath, 'abilities.json'), 'r') except IOError: get_abilities() f = open(path.join(srcpath, 'abilities.json'), 'r') finally: with f: return json.load(f)[ability].encode('utf-8')
<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_move_data(move): """Return the index number for the given move name. Check moves.json in the same directory."""
srcpath = path.dirname(__file__) try: f = open(path.join(srcpath, 'moves.json'), 'r') except IOError: get_moves() f = open(path.join(srcpath, 'moves.json'), 'r') finally: with f: return json.load(f)[move]
<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): """Registers SSH key with provider."""
log.info('Installing ssh key, %s' % self.name) self.consul.create_ssh_pub_key(self.name, self.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 find_existing(self): """ Searches for existing server instances with matching tags. To match, the existing instances must also be "running". """
instances = self.consul.find_servers(self.tags) maxnames = len(instances) while instances: i = instances.pop(0) server_id = i[A.server.ID] if self.namespace.add_if_unique(server_id): log.info('Found existing server, %s' % server_id) self.server_attrs = i break if len(self.namespace.names) >= maxnames: break instances.append(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 wait_for_running(self): """Waits for found servers to be operational"""
self.server_attrs = self.consul.find_running( self.server_attrs, self.launch_timeout_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 create(self): """Launches a new server instance."""
self.server_attrs = self.consul.create_server( "%s-%s" % (self.stack.name, self.name), self.disk_image_id, self.instance_type, self.ssh_key_name, tags=self.tags, availability_zone=self.availability_zone, timeout_s=self.launch_timeout_s, security_groups=self.security_groups, **self.provider_extras ) log.debug('Post launch delay: %d s' % self.post_launch_delay_s) time.sleep(self.post_launch_delay_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 add_to_inventory(self): """Adds host to stack inventory"""
if not self.server_attrs: return for addy in self.server_attrs[A.server.PUBLIC_IPS]: self.stack.add_host(addy, self.groups, self.hostvars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define(self): """Defines a new server."""
self.server_def = self.consul.define_server( self.name, self.server_tpl, self.server_tpl_rev, self.instance_type, self.ssh_key_name, tags=self.tags, availability_zone=self.availability_zone, security_groups=self.security_groups, **self.provider_extras ) log.debug('Defined server %s' % self.server_def)
<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_existing(self): """ Finds existing rule in secgroup. Populates ``self.create_these_rules`` and ``self.delete_these_rules``. """
sg = self.consul.find_secgroup(self.name) current = sg.rules log.debug('Current rules: %s' % current) log.debug('Intended rules: %s' % self.rules) exp_rules = [] for rule in self.rules: exp = ( rule[A.secgroup.PROTOCOL], rule[A.secgroup.FROM], rule[A.secgroup.TO], rule[A.secgroup.SOURCE], ) exp_rules.append(exp) if exp in current: del current[exp] else: self.create_these_rules.append(exp) self.delete_these_rules.extend(current.itervalues()) log.debug('Create these rules: %s' % self.create_these_rules) log.debug('Delete these rules: %s' % self.delete_these_rules)
<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_rule_changes(self): """ Makes the security group rules match what is defined in the Bang config file. """
# TODO: add error handling for rule in self.delete_these_rules: self.consul.delete_secgroup_rule(rule) log.info("Revoked: %s" % rule) for rule in self.create_these_rules: args = rule + (self.name, ) self.consul.create_secgroup_rule(*args) log.info("Authorized: %s" % str(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 create(self): """Creates a new bucket"""
self.consul.create_bucket("%s-%s" % (self.stack.name, self.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 create(self): """Creates a new database"""
self.db_attrs = self.consul.create_db( self.instance_name, self.instance_type, self.admin_username, self.admin_password, db_name=self.db_name, storage_size_gb=self.storage_size, timeout_s=self.launch_timeout_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 add_to_inventory(self): """Adds db host to stack inventory"""
host = self.db_attrs.pop(A.database.HOST) self.stack.add_host( host, self.groups, self.db_attrs )
<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(self): """Creates a new load balancer"""
required_nodes = self._get_required_nodes() self.lb_attrs = self.consul.create_lb( self.instance_name, protocol=self.protocol, port=self.port, nodes=required_nodes, node_port=str(self.backend_port), algorithm=getattr(self, 'algorithm', 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 configure_nodes(self): """Ensure that the LB's nodes matches the stack"""
# Since load balancing runs after server provisioning, # the servers should already be created regardless of # whether this was a preexisting load balancer or not. # We also have the existing nodes, because add_to_inventory # has been called already required_nodes = self._get_required_nodes() log.debug( "Matching existing lb nodes to required %s (port %s)" % (", ".join(required_nodes), self.backend_port) ) self.consul.match_lb_nodes( self.lb_attrs[A.loadbalancer.ID], self.lb_attrs[A.loadbalancer.NODES_KEY], required_nodes, self.backend_port) self.lb_attrs = self.consul.lb_details( self.lb_attrs[A.loadbalancer.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 add_to_inventory(self): """Adds lb IPs to stack inventory"""
if self.lb_attrs: self.lb_attrs = self.consul.lb_details( self.lb_attrs[A.loadbalancer.ID] ) host = self.lb_attrs['virtualIps'][0]['address'] self.stack.add_lb_secgroup(self.name, [host], self.backend_port) self.stack.add_host( host, [self.name], self.lb_attrs )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_dependencies(self): """ evaluate each of the data dependencies of this build target, returns the resulting dict"""
return dict( [((key, self.data_dependencies[key]) if type(self.data_dependencies[key]) != DeferredDependency else (key, self.data_dependencies[key].resolve())) for key in self.data_dependencies])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_and_build(self): """ resolves the dependencies of this build target and builds it """
pdebug("resolving and building task '%s'" % self.name, groups=["build_task"]) indent_text(indent="++2") toret = self.build(**self.resolve_dependencies()) indent_text(indent="--2") return toret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_response(self, request, response): """ Sets the cache and deals with caching headers if needed """
if not self.should_cache(request, response): # We don't need to update the cache, just return return response response = self.patch_headers(response) self.set_cache(request, response) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keys(self): """Create an ordered dict of the names and values of key fields."""
keys = OrderedDict() def order_key(_): (k, v) = _ cache_key = getattr(type(self), k) return cache_key.order items = [(k, getattr(type(self), k)) for k in dir(type(self)) ] items = [(k, v) for (k, v) in items if isinstance(v, Key) ] for k, v in sorted(items, key=order_key): keys[k] = getattr(self, k) return keys
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self): """Serialize all the fields into one string."""
keys = self._all_keys() serdata = {} for fieldname, value in self._data.items(): serdata[fieldname] = getattr(type(self), fieldname).python_to_cache(value) return json.dumps(serdata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(cls, string): """Reconstruct a previously serialized string back into an instance of a ``CacheModel``."""
data = json.loads(string) for fieldname, value in data.items(): data[fieldname] = getattr(cls, fieldname).cache_to_python(value) return cls(**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 save(self, expires=None): """Save a copy of the object into the cache."""
if expires is None: expires = self.expires s = self.serialize() key = self._key(self._all_keys()) _cache.set(key, s, expires)
<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, **kwargs): """Get a copy of the type from the cache and reconstruct it."""
data = cls._get(**kwargs) if data is None: new = cls() new.from_miss(**kwargs) return new return cls.deserialize(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_or_create(cls, **kwargs): """Get a copy of the type from the cache, or create a new one."""
data = cls._get(**kwargs) if data is None: return cls(**kwargs), True return cls.deserialize(data), 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 from_miss(self, **kwargs): """Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, def from_miss(self, username): user = User.objects.get(username=username) self.email = user.email self.full_name = user.get_full_name() """
raise type(self).Missing(type(self)(**kwargs).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 delete(self): """Deleting any existing copy of this object from the cache."""
key = self._key(self._all_keys()) _cache.delete(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 overlay_config(base, overlay): '''Overlay one configuration over another. This overlays `overlay` on top of `base` as follows: * If either isn't a dictionary, returns `overlay`. * Any key in `base` not present in `overlay` is present in the result with its original value. * Any key in `overlay` with value :const:`None` is not present in the result, unless it also is :const:`None` in `base`. * Any key in `overlay` not present in `base` and not :const:`None` is present in the result with its new value. * Any key in both `overlay` and `base` with a non-:const:`None` value is recursively overlaid. >>> overlay_config({'a': 'b'}, {'a': 'c'}) {'a': 'c'} >>> overlay_config({'a': 'b'}, {'c': 'd'}) {'a': 'b', 'c': 'd'} >>> overlay_config({'a': {'b': 'c'}}, ... {'a': {'b': 'd', 'e': 'f'}}) {'a': {'b': 'd', 'e': 'f'}} >>> overlay_config({'a': 'b', 'c': 'd'}, {'a': None}) {'c': 'd'} :param dict base: original configuration :param dict overlay: overlay configuration :return: new overlaid configuration :returntype dict: ''' if not isinstance(base, collections.Mapping): return overlay if not isinstance(overlay, collections.Mapping): return overlay result = dict() for k in iterkeys(base): if k not in overlay: result[k] = base[k] for k, v in iteritems(overlay): if v is not None or (k in base and base[k] is None): if k in base: v = overlay_config(base[k], v) result[k] = v 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 diff_config(base, target): '''Find the differences between two configurations. This finds a delta configuration from `base` to `target`, such that calling :func:`overlay_config` with `base` and the result of this function yields `target`. This works as follows: * If both are identical (of any type), returns an empty dictionary. * If either isn't a dictionary, returns `target`. * Any key in `target` not present in `base` is included in the output with its value from `target`. * Any key in `base` not present in `target` is included in the output with value :const:`None`. * Any keys present in both dictionaries are recursively merged. >>> diff_config({'a': 'b'}, {}) {'a': None} >>> diff_config({'a': 'b'}, {'a': 'b', 'c': 'd'}) {'c': 'd'} :param dict base: original configuration :param dict target: new configuration :return: overlay configuration :returntype dict: ''' if not isinstance(base, collections.Mapping): if base == target: return {} return target if not isinstance(target, collections.Mapping): return target result = dict() for k in iterkeys(base): if k not in target: result[k] = None for k, v in iteritems(target): if k in base: merged = diff_config(base[k], v) if merged != {}: result[k] = merged else: result[k] = v 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 pformat(tree): """Recursively formats a tree into a nice string representation. Example Input: yahoo = tt.Tree(tt.Node("CEO")) yahoo.root.add(tt.Node("Infra")) yahoo.root[0].add(tt.Node("Boss")) yahoo.root[0][0].add(tt.Node("Me")) yahoo.root.add(tt.Node("Mobile")) yahoo.root.add(tt.Node("Mail")) Example Output: CEO |__Infra | |__Boss | |__Me |__Mobile |__Mail """
if tree.empty(): return '' buf = six.StringIO() for line in _pformat(tree.root, 0): buf.write(line + "\n") return buf.getvalue().strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_iter(self, include_self=True): """Yields back the path from this node to the root node."""
if include_self: node = self else: node = self.parent while node is not None: yield node node = node.parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def child_count(self, only_direct=True): """Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node. """
if not only_direct: count = 0 for _node in self.dfs_iter(): count += 1 return count return len(self._children)
<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, item): """Finds the child index of a given item, searchs in added order."""
index_at = None for (i, child) in enumerate(self._children): if child.item == item: index_at = i break if index_at is None: raise ValueError("%s is not contained in any child" % (item)) return index_at
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish_state(self, state): """Publish thing state to AWS IoT. Args: state (dict): object state. Must be JSON serializable (i.e., not have circular references). """
message = json.dumps({'state': {'reported': state}}) self.client.publish(self.topic, message) self._state = state
<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_kpoint(line): """Is this line the start of a new k-point block"""
# Try to parse the k-point; false otherwise toks = line.split() # k-point header lines have 4 tokens if len(toks) != 4: return False try: # K-points are centered at the origin xs = [float(x) for x in toks[:3]] # Weights are in [0,1] w = float(toks[3]) return all(abs(x) <= 0.5 for x in xs) and w >= 0.0 and w <= 1.0 except ValueError: 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 _parse_kpoint(line, lines): """Parse the k-point and then continue to iterate over the band energies and occupations"""
toks = line.split() kpoint = [float(x) for x in toks[:3]] weight = float(toks[-1]) newline = next(lines) bands_up = [] occ_up = [] bands_down = [] occ_down = [] ispin = None while len(newline.split()) > 0: toks = newline.split() if ispin is None: # there are two spins if there are 5 columns (two spin energies and occupancies) or # very probably if there are 3 columns and the last column's first value isn't 1.0 # (which would be the occupancy of the lowest energy level) ispin = (len(toks) == 5) or (len(toks) == 3 and abs(float(toks[2]) - 1.0) > 1.0e-4) if len(toks) == 2: bands_up.append(float(toks[1])) elif len(toks) == 3 and not ispin: bands_up.append(float(toks[1])) occ_up.append(float(toks[2])) elif len(toks) == 3 and ispin: bands_up.append(float(toks[1])) bands_down.append(float(toks[2])) elif len(toks) == 5 and ispin: bands_up.append(float(toks[1])) bands_down.append(float(toks[2])) occ_up.append(float(toks[3])) occ_down.append(float(toks[4])) else: raise ValueError("Encountered {} when parsing k-point".format(newline)) newline = next(lines) res = {"kpoint": kpoint, "weight": weight} if len(bands_down) > 0: res["energies"] = list(zip(bands_up, bands_down)) else: res["energies"] = list(zip(bands_up)) if len(occ_down) > 0: res["occupancies"] = list(zip(occ_up, occ_down)) elif len(occ_up) > 0: res["occupancies"] = list(zip(occ_up)) return 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 parse(cls, op): """Gets the enum for the op code Args: op: value of the op code (will be casted to int) Returns: The enum that matches the op code """
for event in cls: if event.value == int(op): return event 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 run(self): """Runs the thread This method handles sending the heartbeat to the Discord websocket server, so the connection can remain open and the bot remain online for those commands that require it to be. Args: None """
while self.should_run: try: self.logger.debug('Sending heartbeat, seq ' + last_sequence) self.ws.send(json.dumps({ 'op': 1, 'd': last_sequence })) except Exception as e: self.logger.error(f'Got error in heartbeat: {str(e)}') finally: elapsed = 0.0 while elapsed < self.interval and self.should_run: time.sleep(self.TICK_INTERVAL) elapsed += self.TICK_INTERVAL
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_logger(self, logging_level: int, log_to_console: bool): """Sets up the internal logger Args: logging_level: what logging level to use log_to_console: whether or not to log to the console """
self.logger = logging.getLogger('discord') self.logger.handlers = [] self.logger.setLevel(logging_level) formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S') file_handler = logging.FileHandler('pycord.log') file_handler.setFormatter(formatter) file_handler.setLevel(logging_level) self.logger.addHandler(file_handler) if log_to_console: stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setFormatter(formatter) stream_handler.setLevel(logging_level) self.logger.addHandler(stream_handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \ -> Union[List[Dict[str, Any]], Dict[str, Any], None]: """Make an HTTP request Args: path: the URI path (not including the base url, start with data: the data to send as JSON data expected_status: expected HTTP status; other statuses received will raise an Exception Returns: Data from the endpoint's response """
url = Pycord.url_base + path self.logger.debug(f'Making {method} request to "{url}"') if method == 'GET': r = requests.get(url, headers=self._build_headers()) elif method == 'POST': r = requests.post(url, headers=self._build_headers(), json=data) r = requests.get(url, headers=self._build_headers()) elif method == 'PATCH': r = requests.patch(url, headers=self._build_headers(), json=data) else: raise ValueError(f'Unknown HTTP method {method}') self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"') if r.status_code != expected_status: raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}') if expected_status == 200: return r.json() 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 _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]): """Callback for receiving messages from the websocket connection This method receives ALL events from the websocket connection, some of which are used for the initial authentication flow, some of which are used for maintaining the connection, some of which are for notifying this client of user states, etc. Only a few of the events are really worth listening to by "downstream" clients, mostly chat events (``WebSocketEvent.DISPATCH`` with element ``t`` == 'MESSAGE_CREATE'), and those can be accessed by clients using this library via the command registration, which is handled by this method. Args: ws: websocket connection raw: message received from the connection; either string or bytes, the latter is a zlip-compressed string. Either way, the end result of formatting is JSON """
if isinstance(raw, bytes): decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8') else: decoded = raw data = json.loads(decoded) if data.get('s') is not None: global last_sequence last_sequence = str(data['s']) self.logger.debug('Set last_sequence to ' + last_sequence) event = WebSocketEvent.parse(data['op']) self.logger.debug('Received event {} (op #{})'.format( event.name, data['op'] )) if event == WebSocketEvent.HELLO: interval = float(data['d']['heartbeat_interval']) / 1000 self.logger.debug(f'Starting heartbeat thread at {interval} seconds') self._ws_keep_alive = WebSocketKeepAlive(self.logger, ws, interval) self._ws_keep_alive.start() elif event == WebSocketEvent.DISPATCH: self.logger.debug('Got dispatch ' + data['t']) if data['t'] == PycordCallback.MESSAGE.value: message_content = data['d']['content'] if message_content.startswith(self.command_prefix) and self._commands: cmd_str = message_content[1:].split(' ')[0].lower() self.logger.debug(f'Got new message, checking for callback for command "{cmd_str}"') for command_obj in self._commands: if command_obj[0].lower() == cmd_str: self.logger.debug(f'Found matching command "{command_obj[0]}", invoking callback') command_obj[1](data) for key in self.callbacks: if key.value == data['t']: self.callbacks[key](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 _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception): """Callback for receiving errors from the websocket connection Args: ws: websocket connection error: exception raised """
self.logger.error(f'Got error from websocket connection: {str(error)}')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ws_on_close(self, ws: websocket.WebSocketApp): """Callback for closing the websocket connection Args: ws: websocket connection (now closed) """
self.connected = False self.logger.error('Websocket closed') self._reconnect_websocket()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ws_on_open(self, ws: websocket.WebSocketApp): """Callback for sending the initial authentication data This "payload" contains the required data to authenticate this websocket client as a suitable bot connection to the Discord websocket. Args: ws: websocket connection """
payload = { 'op': WebSocketEvent.IDENTIFY.value, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'Pycord', '$device': 'Pycord', '$referrer': '', '$referring_domain': '' }, 'compress': True, 'large_threshold': 250 } } self.logger.debug('Sending identify payload') ws.send(json.dumps(payload)) self.connected = 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 connect_to_websocket(self): """Call this method to make the connection to the Discord websocket This method is not blocking, so you'll probably want to call it after initializating your Pycord object, and then move on with your code. When you want to block on just maintaining the websocket connection, then call ``keep_running``, and it'll block until your application is interrupted. Args: None """
self.logger.info('Making websocket connection') try: if hasattr(self, '_ws'): self._ws.close() except: self.logger.debug('Couldn\'t terminate previous websocket connection') self._ws = websocket.WebSocketApp( self._get_websocket_address() + '?v=6&encoding=json', on_message=self._ws_on_message, on_error=self._ws_on_error, on_close=self._ws_on_close ) self._ws.on_open = self._ws_on_open self._ws_run_forever_wrapper = WebSocketRunForeverWrapper(self.logger, self._ws) self._ws_run_forever_wrapper.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect_from_websocket(self): """Disconnects from the websocket Args: None """
self.logger.warning('Disconnecting from websocket') self.logger.info('Stopping keep alive thread') self._ws_keep_alive.stop() self._ws_keep_alive.join() self.logger.info('Stopped keep alive thread') try: self.logger.warning('Disconnecting from websocket') self._ws.close() self.logger.info('Closed websocket connection') except: self.logger.debug('Couldn\'t terminate previous websocket connection')
<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_status(self, name: str = None): """Updates the bot's status This is used to get the game that the bot is "playing" or to clear it. If you want to set a game, pass a name; if you want to clear it, either call this method without the optional ``name`` parameter or explicitly pass ``None``. Args: name: the game's name, or None """
game = None if name: game = { 'name': name } payload = { 'op': WebSocketEvent.STATUS_UPDATE.value, 'd': { 'game': game, 'status': 'online', 'afk': False, 'since': 0.0 } } data = json.dumps(payload, indent=2) self.logger.debug(f'Sending status update payload: {data}') self._ws.send(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_guild_info(self, id: str) -> Dict[str, Any]: """Get a guild's information by its id Args: id: snowflake id of the guild Returns: Dictionary data for the guild API object Example: { "id": "41771983423143937", "name": "Discord Developers", "icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh", "splash": null, "owner_id": "80351110224678912", "region": "us-east", "afk_channel_id": "42072017402331136", "afk_timeout": 300, "embed_enabled": true, "embed_channel_id": "41771983444115456", "verification_level": 1, "roles": [], "emojis": [], "features": ["INVITE_SPLASH"], "unavailable": false } """
return self._query(f'guilds/{id}', 'GET')
<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_channels_in(self, guild_id: str) -> List[Dict[str, Any]]: """Get a list of channels in the guild Args: guild_id: id of the guild to fetch channels from Returns: List of dictionary objects of channels in the guild. Note the different types of channels: text, voice, DM, group DM. https://discordapp.com/developers/docs/resources/channel#channel-object Example: [ { "id": "41771983423143937", "guild_id": "41771983423143937", "name": "general", "type": 0, "position": 6, "permission_overwrites": [], "topic": "24/7 chat about how to gank Mike #2", "last_message_id": "155117677105512449" }, { "id": "155101607195836416", "guild_id": "41771983423143937", "name": "ROCKET CHEESE", "type": 2, "position": 5, "permission_overwrites": [], "bitrate": 64000, "user_limit": 0 }, { "last_message_id": "3343820033257021450", "type": 1, "id": "319674150115610528", "recipients": [ { "username": "test", "discriminator": "9999", "id": "82198898841029460", "avatar": "33ecab261d4681afa4d85a04691c4a01" } ] } ] """
return self._query(f'guilds/{guild_id}/channels', 'GET')
<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_channel_info(self, id: str) -> Dict[str, Any]: """Get a chanel's information by its id Args: id: snowflake id of the chanel Returns: Dictionary data for the chanel API object Example: { "id": "41771983423143937", "guild_id": "41771983423143937", "name": "general", "type": 0, "position": 6, "permission_overwrites": [], "topic": "24/7 chat about how to gank Mike #2", "last_message_id": "155117677105512449" } """
return self._query(f'channels/{id}', 'GET')
<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_guild_members(self, guild_id: int) -> List[Dict[str, Any]]: """Get a list of members in the guild Args: guild_id: snowflake id of the guild Returns: List of dictionary objects of users in the guild. Example: [ { "id": "41771983423143937", "name": "Discord Developers", "icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh", "splash": null, "owner_id": "80351110224678912", "region": "us-east", "afk_channel_id": "42072017402331136", "afk_timeout": 300, "embed_enabled": true, "embed_channel_id": "41771983444115456", "verification_level": 1, "roles": [], "emojis": [], "features": ["INVITE_SPLASH"], "unavailable": false }, { "id": "41771983423143937", "name": "Discord Developers", "icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh", "splash": null, "owner_id": "80351110224678912", "region": "us-east", "afk_channel_id": "42072017402331136", "afk_timeout": 300, "embed_enabled": true, "embed_channel_id": "41771983444115456", "verification_level": 1, "roles": [], "emojis": [], "features": ["INVITE_SPLASH"], "unavailable": false } ] """
return self._query(f'guilds/{guild_id}/members', 'GET')
<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_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]: """Get a guild member by their id Args: guild_id: snowflake id of the guild member_id: snowflake id of the member Returns: Dictionary data for the guild member. Example: { "id": "41771983423143937", "name": "Discord Developers", "icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh", "splash": null, "owner_id": "80351110224678912", "region": "us-east", "afk_channel_id": "42072017402331136", "afk_timeout": 300, "embed_enabled": true, "embed_channel_id": "41771983444115456", "verification_level": 1, "roles": [ "41771983423143936", "41771983423143937", "41771983423143938" ], "emojis": [], "features": ["INVITE_SPLASH"], "unavailable": false } """
return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')
<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_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]: """Gets all the roles for the specified guild Args: guild_id: snowflake id of the guild Returns: List of dictionary objects of roles in the guild. Example: [ { "id": "41771983423143936", "name": "WE DEM BOYZZ!!!!!!", "color": 3447003, "hoist": true, "position": 1, "permissions": 66321471, "managed": false, "mentionable": false }, { "hoist": false, "name": "Admin", "mentionable": false, "color": 15158332, "position": 2, "id": "151107620239966208", "managed": false, "permissions": 66583679 }, { "hoist": false, "name": "@everyone", "mentionable": false, "color": 0, "position": 0, "id": "151106790233210882", "managed": false, "permissions": 37215297 } ] """
return self._query(f'guilds/{guild_id}/roles', 'GET')
<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_member_roles(self, guild_id: int, member_id: int, roles: List[int]): """Set the member's roles This method takes a list of **role ids** that you want the user to have. This method will **overwrite** all of the user's current roles with the roles in the passed list of roles. When calling this method, be sure that the list of roles that you're setting for this user is complete, not just the roles that you want to add or remove. For assistance in just adding or just removing roles, set the ``add_member_roles`` and ``remove_member_roles`` methods. Args: guild_id: snowflake id of the guild member_id: snowflake id of the member roles: list of snowflake ids of roles to set """
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204)
<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(self, name: str) -> Callable: """Decorator to wrap methods to register them as commands The argument to this method is the command that you want to trigger your callback. If you want users to send "!hello bob" and your method "command_hello" to get called when someone does, then your setup will look like: @pycord.command('hello') def command_hello(data): # do stuff here The ``data`` argument that your method will receive is the message object. Example: { "t": "MESSAGE_CREATE", "s": 4, "op": 0, "d": { "type": 0, "tts": false, "timestamp": "2017-07-22T04:46:41.366000+00:00", "pinned": false, "nonce": "338180052904574976", "mentions": [], "mention_roles": [], "mention_everyone": false, "id": "338180026363150336", "embeds": [], "edited_timestamp": null, "content": "!source", "channel_id": "151106790233210882", "author": { "username": "Celeo", "id": "110245175636312064", "discriminator": "1453", "avatar": "3118c26ea7e40350212196e1d9d7f5c9" }, "attachments": [] } } Args: name: command name Returns: Method decorator """
def inner(f: Callable): self._commands.append((name, f)) return inner
<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_command(self, name: str, f: Callable): """Registers an existing callable object as a command callback This method can be used instead of the ``@command`` decorator. Both do the same thing, but this method is useful for registering callbacks for methods defined before or outside the scope of your bot object, allowing you to define methods in another file or wherever, import them, and register them. See the documentation for the ``@command`` decorator for more information on what you method will receive. Example: def process_hello(data): # do stuff # later, somewhere else, etc. pycord.register_command('hello', process_hello) Args: name: the command to trigger the callback (see ``@command`` documentation) f: callable that will be triggered on command processing """
self._commands.append((name, f))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_csv_to_dataframe(data_file, config, use_target=True): """ Parses the given data file following the data model of the given configuration. @return: pandas DataFrame """
names, dtypes = [], [] model = config.get_data_model() for feature in model: assert feature.get_name() not in names, "Two features can't have the same name." if not use_target and feature.is_target(): continue names.append(feature.get_name()) data = pd.read_csv(data_file, names=names) transform_categorical_features(config, data, use_target) return 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 mark_for_update(self): ''' Note that a change has been made so all Statuses need update ''' self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE) push_key.delay(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_cookie(self, key, value, domain=None, path='/', secure=False, httponly=True): """Set a cookie. Args: key (:obj:`str`): Cookie name value (:obj:`str`): Cookie value domain (:obj:`str`): Cookie domain path (:obj:`str`): Cookie value secure (:obj:`bool`): True if secure, False otherwise httponly (:obj:`bool`): True if it's a HTTP only cookie, False otherwise """
self._cookies[key] = value if domain: self._cookies[key]['domain'] = domain if path: self._cookies[key]['path'] = path if secure: self._cookies[key]['secure'] = secure if httponly: self._cookies[key]['httponly'] = httponly
<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_content(self, content, content_length=None): """Set content for the response. Args: content (:obj:`str` or :obj:`iterable`): Response content. Can be either unicode or raw bytes. When returning large content, an iterable (or a generator) can be used to avoid loading entire content into the memory. content_length (:obj:`int`, optional): Content length. Length will be determined if not set. If content is an iterable, it's a good practise to set the content length. """
if content_length is not None: self._content_length = content_length self._content = content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bake(self, start_response): """Bakes the response and returns the content. Args: start_response (:obj:`callable`): Callback method that accepts status code and a list of tuples (pairs) containing headers' key and value respectively. """
if isinstance(self._content, six.text_type): self._content = self._content.encode('utf8') if self._content_length is None: self._content_length = len(self._content) self._headers[HttpResponseHeaders.CONTENT_LENGTH] = \ str(self._content_length) headers = list(self._headers.items()) cookies = [(HttpResponseHeaders.SET_COOKIE, v.OutputString()) for _, v in self._cookies.items()] if len(cookies): headers = list(headers) + cookies start_response(self._status_code, headers) if isinstance(self._content, six.binary_type): return [self._content] return self._content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_redirect(self, url, status=HttpStatusCodes.HTTP_303): """Helper method to set a redirect response. Args: url (:obj:`str`): URL to redirect to status (:obj:`str`, optional): Status code of the response """
self.set_status(status) self.set_content('') self.set_header(HttpResponseHeaders.LOCATION, url)
<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_json(self, obj, status=HttpStatusCodes.HTTP_200): """Helper method to set a JSON response. Args: obj (:obj:`object`): JSON serializable object status (:obj:`str`, optional): Status code of the response """
obj = json.dumps(obj, sort_keys=True, default=lambda x: str(x)) self.set_status(status) self.set_header(HttpResponseHeaders.CONTENT_TYPE, 'application/json') self.set_content(obj)
<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_rak(): """ Find our instance of Rak, navigating Local's and possible blueprints. """
if hasattr(current_app, 'rak'): return getattr(current_app, 'rak') else: if hasattr(current_app, 'blueprints'): blueprints = getattr(current_app, 'blueprints') for blueprint_name in blueprints: if hasattr(blueprints[blueprint_name], 'rak'): return getattr(blueprints[blueprint_name], 'rak')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intent(self, intent_name): """Decorator routes an Rogo IntentRequest. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent') def weather(city): return statement('I predict great weather for {}'.format(city)) Arguments: intent_name {str} -- Name of the intent request to be mapped to the decorated function """
def decorator(f): self._intent_view_funcs[intent_name] = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_anchor_id(self): """Return string to use as URL anchor for this comment. """
result = re.sub( '[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp) 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 make_url(self, my_request, anchor_id=None): """Make URL to this comment. :arg my_request: The request object where this comment is seen from. :arg anchor_id=None: Optional anchor id. If None, we use self.make_anchor_id() ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: String URL to this comment. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Be able to create links to this comment. """
if anchor_id is None: anchor_id = self.make_anchor_id() result = '{}?{}#{}'.format( my_request.path, urllib.parse.urlencode(my_request.args), anchor_id) 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 to_dict(self): """Return description of self in dict format. This is useful for serializing to something like json later. """
jdict = { 'user': self.user, 'summary': self.summary, 'body': self.body, 'markup': self.markup, 'url': self.url, 'timestamp': self.timestamp } return jdict
<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_display_mode(self, mytz, fmt): """Set the display mode for self. :arg mytz: A pytz.timezone object. :arg fmt: A format string for strftime. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Modifies self.display_timestamp to first parse self.timestamp and then format according to given timezone and format string. """
my_stamp = dateutil.parser.parse(self.timestamp) tz_stamp = my_stamp.astimezone( mytz) if my_stamp.tzinfo is not None else my_stamp self.display_timestamp = tz_stamp.strftime(fmt)
<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_comment_section(self, force_reload=False, reverse=False): """Get CommentSection instance representing all comments for thread. :arg force_reload=False: Whether to force reloading comments directly or allow using what is cached in self.content if possible. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: CommentSection representing all comments for thread. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: High-level function called by user to get comments. """
if self.content is not None and not force_reload: return self.content if self.thread_id is None: self.thread_id = self.lookup_thread_id() self.content = self.lookup_comments(reverse=reverse) return self.content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_attachment_location(self, location): """Validate a proposed attachment location. :arg location: String representing location to put attachment. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Raises an exception if attachment location is bad. By default, this just forces reasonable characters. Sub-classes can override as desired. """
if not re.compile(self.valid_attachment_loc_re).match(location): raise ValueError( 'Bad chars in attachment location. Must match %s' % ( self.valid_attachment_loc_re))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lookup_thread_id(self): "Lookup the thread id as path to comment file." path = os.path.join(self.realm, self.topic + '.csv') return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lookup_comments(self, reverse=False): "Implement as required by parent to lookup comments in file system." comments = [] if self.thread_id is None: self.thread_id = self.lookup_thread_id() path = self.thread_id with open(self.thread_id, 'r', newline='') as fdesc: reader = csv.reader(fdesc) header = reader.__next__() assert header == self.header for num, line in enumerate(reader): if not line: continue assert len(line) == len(header), ( 'Line %i in path %s misformatted' % (num+1, path)) line_kw = dict(zip(header, line)) comments.append(SingleComment(**line_kw)) if reverse: comments = list(reversed(comments)) return CommentSection(comments)
<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_thread(self, body): """Implement create_thread as required by parent. This basically just calls add_comment with allow_create=True and then builds a response object to indicate everything is fine. """
self.add_comment(body, allow_create=True) the_response = Response() the_response.code = "OK" the_response.status_code = 200
<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_comment(self, body, allow_create=False, allow_hashes=False, summary=None): "Implement as required by parent to store comment in CSV file." if allow_hashes: raise ValueError('allow_hashes not implemented for %s yet' % ( self.__class__.__name__)) if self.thread_id is None: self.thread_id = self.lookup_thread_id() if not os.path.exists(self.thread_id): if not allow_create: raise KeyError(self.topic) with open(self.thread_id, 'a', newline='') as fdesc: csv.writer(fdesc).writerow(self.header) with open(self.thread_id, 'a', newline='') as fdesc: writer = csv.writer(fdesc) writer.writerow([self.user, datetime.datetime.utcnow(), summary, body, ''])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pascal_row(n): """ Returns n-th row of Pascal's triangle """
result = [1] x, numerator = 1, n for denominator in range(1, n // 2 + 1): x *= numerator x /= denominator result.append(x) numerator -= 1 if n & 1 == 0: result.extend(reversed(result[:-1])) else: result.extend(reversed(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 create_salt(length: int=128) -> bytes: """ Create a new salt :param int length: How many bytes should the salt be long? :return: The salt :rtype: bytes """
return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(length))
<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_connection(self) -> redis.Redis: """ Get a Redis connection :return: Redis connection instance :rtype: redis.Redis """
if self.__redis_use_socket: r = redis.from_url( 'unix://{:s}?db={:d}'.format( self.__redis_host, self.__redis_db ) ) else: r = redis.from_url( 'redis://{:s}:{:d}/{:d}'.format( self.__redis_host, self.__redis_port, self.__redis_db ) ) if BlackRed.Settings.REDIS_AUTH is not None: r.execute_command('AUTH {:s}'.format(BlackRed.Settings.REDIS_AUTH)) 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 _encode_item(self, item: str) -> str: """ If anonymization is on, an item gets salted and hashed here. :param str item: :return: Hashed item, if anonymization is on; the unmodified item otherwise :rtype: str """
assert item is not None if not self.__redis_conf['anonymization']: return item connection = self.__get_connection() salt = connection.get(self.__redis_conf['salt_key']) if salt is None: salt = create_salt() connection.set(self.__redis_conf['salt_key'], salt) BlackRed.__release_connection(connection) return sha512(salt + item.encode()).hexdigest()
<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_ttl(self, item: str) -> int: """ Get the amount of time a specific item will remain in the database. :param str item: The item to get the TTL for :return: Time in seconds. Returns None for a non-existing element. :rtype: int """
connection = self.__get_connection() ttl = connection.ttl(item) BlackRed.__release_connection(connection) return ttl
<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_watchlist_ttl(self, item: str) -> int: """ Get the amount of time a specific item will remain on the watchlist. :param str item: The item to get the TTL for on the watchlist :return: Time in seconds. Returns None for a non-existing element :rtype: int """
assert item is not None item = self._encode_item(item) return self.__get_ttl(self.__redis_conf['watchlist_template'].format(item))
<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_not_blocked(self, item: str) -> bool: """ Check if an item is _not_ already on the blacklist :param str item: The item to check :return: True, when the item is _not_ on the blacklist :rtype: bool """
assert item is not None item = self._encode_item(item) connection = self.__get_connection() key = self.__redis_conf['blacklist_template'].format(item) value = connection.get(key) if value is None: BlackRed.__release_connection(connection) return True if self.__redis_conf['blacklist_refresh_ttl']: connection.expire(key, self.__redis_conf['blacklist_ttl']) BlackRed.__release_connection(connection) 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 log_fail(self, item: str) -> None: """ Log a failed action for an item. If the fail count for this item reaches the threshold, the item is moved to the blacklist. :param str item: The item to log """
assert item is not None item = self._encode_item(item) if self.is_blocked(item): return connection = self.__get_connection() key = self.__redis_conf['watchlist_template'].format(item) value = connection.get(key) if value is None: connection.set(key, 1, ex=self.__redis_conf['watchlist_ttl']) BlackRed.__release_connection(connection) return value = int(value) + 1 if value < self.__redis_conf['watchlist_to_blacklist']: connection.set(key, value, ex=self.__redis_conf['watchlist_ttl']) BlackRed.__release_connection(connection) return blacklist_key = self.__redis_conf['blacklist_template'].format(item) connection.set(blacklist_key, time.time(), ex=self.__redis_conf['blacklist_ttl']) connection.delete(key) BlackRed.__release_connection(connection)
<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_task(self, func): """Start up a task"""
task = self.loop.create_task(func(self)) self._started_tasks.append(task) def done_callback(done_task): self._started_tasks.remove(done_task) task.add_done_callback(done_callback) return 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 run(self, loop=None): """Actually run the application :param loop: Custom event loop or None for default """
if loop is None: loop = asyncio.get_event_loop() self.loop = loop loop.run_until_complete(self.startup()) for func in self.tasks: self.start_task(func) try: task = self.start_task(self.main_task) loop.run_until_complete(task) except (KeyboardInterrupt, SystemError): print("Attempting graceful shutdown, press Ctrl-C again to exit", flush=True) def shutdown_exception_handler(_loop, context): if "exception" not in context or not isinstance(context["exception"], asyncio.CancelledError): _loop.default_exception_handler(context) loop.set_exception_handler(shutdown_exception_handler) tasks = asyncio.gather(*self._started_tasks, loop=loop, return_exceptions=True) tasks.add_done_callback(lambda _: loop.stop()) tasks.cancel() while not tasks.done() and not loop.is_closed(): loop.run_forever() finally: loop.run_until_complete(self.shutdown()) loop.run_until_complete(self.cleanup()) loop.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 read_git_blob(commit_ref, path, repo_dir='.'): """Get text from a git blob. Parameters commit_ref : str Any SHA or git tag that can resolve into a commit in the git repository. path : str Path to the document in the git repository, relative to the root of the repository. repo_dir : str Path from current working directory to the root of the git repository. Returns ------- text : unicode The document text. """
repo = git.Repo(repo_dir) tree = repo.tree(commit_ref) dirname, fname = os.path.split(path) text = None if dirname == '': text = _read_blob(tree, fname) else: components = path.split(os.sep) text = _read_blob_in_tree(tree, components) return 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 _read_blob_in_tree(tree, components): """Recursively open trees to ultimately read a blob"""
if len(components) == 1: # Tree is direct parent of blob return _read_blob(tree, components[0]) else: # Still trees to open dirname = components.pop(0) for t in tree.traverse(): if t.name == dirname: return _read_blob_in_tree(t, components)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def absolute_git_root_dir(fpath=""): """Absolute path to the git root directory containing a given file or directory. """
if len(fpath) == 0: dirname_str = os.getcwd() else: dirname_str = os.path.dirname(fpath) dirname_str = os.path.abspath(dirname_str) dirnames = dirname_str.split(os.sep) n = len(dirnames) for i in xrange(n): # is there a .git directory at this level? # FIXME hack basedir = "/" + os.path.join(*dirnames[0:n - i]) gitdir = os.path.join(basedir, ".git") if os.path.exists(gitdir): return basedir