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 load_site_config(name): """Load and return site configuration as a dict."""
return _load_config_json( os.path.join( CONFIG_PATH, CONFIG_SITES_PATH, name + CONFIG_EXT ) )
<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_charsets(self): """ Overridden function for Phylip dataset as the content is different and goes into a separate file. """
count_start = 1 out = '' for gene_code, lengths in self.data.gene_codes_and_lengths.items(): count_end = lengths[0] + count_start - 1 formatted_line = self.format_charset_line(gene_code, count_start, count_end) converted_line = formatted_line.replace(' charset', 'DNA,').replace(';', '') out += converted_line count_start = count_end + 1 return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_date(cls, date): """ Returns a Month instance from the given datetime.date or datetime.datetime object """
try: date = date.date() except AttributeError: pass return cls(date.year, date.month)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rebuild(self, **kwargs): '''Repopulate the node-tracking data structures. Shouldn't really ever be needed. ''' self.nodes = [] self.node_types = [] self.id_dict = {} self.type_dict = {} self.add_node(self.root)
<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_search_kwarg_types(self, kwargs): '''Checks that every element of kwargs is a valid type in this tree.''' for key in kwargs: if key not in self.node_types: raise TypeError("Invalid search type: {}".format(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 average(x): """ Return a numpy array of column average. It does not affect if the array is one dimension Parameters x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance of column average Examples -------- True True """
if x.ndim > 1 and len(x[0]) > 1: return np.average(x, axis=1) return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean(x): """ Return a numpy array of column mean. It does not affect if the array is one dimension Parameters x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance of column mean Examples -------- True True """
if x.ndim > 1 and len(x[0]) > 1: return np.mean(x, axis=1) return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def median(x): """ Return a numpy array of column median. It does not affect if the array is one dimension Parameters x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance of column median Examples -------- True True """
if x.ndim > 1 and len(x[0]) > 1: return np.median(x, axis=1) return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variance(x): """ Return a numpy array of column variance Parameters x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance of column variance Examples -------- """
if x.ndim > 1 and len(x[0]) > 1: return np.var(x, axis=1) return np.var(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def standard_deviation(x): """ Return a numpy array of column standard deviation Parameters x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance of column standard deviation Examples -------- """
if x.ndim > 1 and len(x[0]) > 1: return np.std(x, axis=1) return np.std(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confidential_interval(x, alpha=0.98): """ Return a numpy array of column confidential interval Parameters x : ndarray A numpy array instance alpha : float Alpha value of confidential interval Returns ------- ndarray A 1 x n numpy array which indicate the each difference from sample average point to confidential interval point """
from scipy.stats import t if x.ndim == 1: df = len(x) - 1 # calculate positive critical value of student's T distribution cv = t.interval(alpha, df) # calculate sample standard distribution std = np.std(x) else: # calculate degree of freedom df = len(x[0]) - 1 # calculate positive critical value of student's T distribution cv = t.interval(alpha, df)[1] # calculate sample standard distribution std = np.std(x, axis=1) # calculate positive difference from # sample average to confidential interval return std * cv / np.sqrt(df)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_moving_matrix(x, n=10): """ Create simple moving matrix. Parameters x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A n x n numpy array which will be useful for calculating confidentail interval of simple moving average """
if x.ndim > 1 and len(x[0]) > 1: x = np.average(x, axis=1) h = n / 2 o = 0 if h * 2 == n else 1 xx = [] for i in range(h, len(x) - h): xx.append(x[i-h:i+h+o]) return np.array(xx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_moving_average(x, n=10): """ Calculate simple moving average Parameters x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A 1 x n numpy array instance """
if x.ndim > 1 and len(x[0]) > 1: x = np.average(x, axis=1) a = np.ones(n) / float(n) return np.convolve(x, a, 'valid')
<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_available_port(): """Find an available port. Simple trick: open a socket to localhost, see what port was allocated. Could fail in highly concurrent setups, though. """
s = socket.socket() s.bind(('localhost', 0)) _address, port = s.getsockname() s.close() return port
<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_file(self, needle, candidates): """Find the first directory containing a given candidate file."""
for candidate in candidates: fullpath = os.path.join(candidate, needle) if os.path.isfile(fullpath): return fullpath raise PathError("Unable to locate file %s; tried %s" % (needle, candidates))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _poll_slapd(self, timeout=DEFAULT_STARTUP_DELAY): """Poll slapd port until available."""
begin = time.time() time.sleep(0.5) while time.time() < begin + timeout: if self._process.poll() is not None: raise RuntimeError("LDAP server has exited before starting listen.") s = socket.socket() try: s.connect(('localhost', self.port)) except socket.error: # Not ready yet, sleep time.sleep(0.5) else: return finally: s.close() raise RuntimeError("LDAP server not responding within %s seconds." % timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def list_users(self): ''' a method to list all the user ids of all users in the bucket ''' # construct url url = self.bucket_url + '/_user/' # send request and unwrap response response = requests.get(url) response = response.json() 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 create(self, doc_details): ''' a method to create a new document in the collection :param doc_details: dictionary with document details and user id value :return: dictionary with document details and _id and _rev values ''' # https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/document/post__db___doc_ title = '%s.create' % self.__class__.__name__ # validate input if self.model: doc_details = self.model.validate(doc_details, path_to_root='', object_title='%s(doc_details={...}' % title) # define request fields from copy import deepcopy new_record = deepcopy(doc_details) url = self.bucket_url + '/' # send request and construct output response = requests.post(url, json=new_record) if response.status_code not in (200, 201): response = response.json() raise Exception('%s() error: %s' % (title, response)) response = response.json() new_record['_id'] = response['id'] new_record['_rev'] = response['rev'] return new_record
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def remove(self): ''' a method to remove the entire bucket from the database :return: string with confirmation message ''' # https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/database/delete__db__ title = '%s.remove' % self.__class__.__name__ # validate admin access if not self.admin_access: raise Exception('%s requires admin access.' % title) # flush files on server if self.configs['server'].find('http:') > -1: flush_url = self.configs['server'] + '/pools/%s/buckets/%s/controller/doFlush' % (self.configs['pool'], self.bucket_name) response = requests.post(flush_url) try: print(response.json()) except: print(response.status_code) # else (in dev) iterate over files and users and purge elif self.configs['server'].find('walrus') > -1: for doc in self.list(purge_deleted=True): self.purge(doc['_id']) user_list = self.list_users() for uid in user_list: self.delete_user(uid) self.delete_view() # delete bucket from configs delete_url = self.bucket_url + '/' requests.delete(delete_url) # report outcome exit_msg = 'Bucket "%s" removed from database.' % self.bucket_name self.printer(exit_msg) return exit_msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_chart(self): """Write color palette to Altair Chart. """
encoding, properties = {}, {} if self.orientation == "horizontal": # Set the axis encoding["x"] = alt.X( "hex", axis=None, scale=alt.Scale(zero=False, padding=0) ) # Set the rectangle size. properties["width"] = len(self.df)*self.square_size properties["height"] = self.square_size elif self.orientation == "vertical": # Set the axis encoding["y"] = alt.Y( "hex", axis=None, scale=alt.Scale(zero=False, padding=0) ) # Set the rectangle size. properties["height"] = len(self.df)*self.square_size properties["width"] = self.square_size # Build a chart. tooltip = list(self.df.columns) chart = alt.Chart(self.df).mark_rect().encode( color=alt.Color("hex", legend=None, scale=alt.Scale(range=self.colors)), tooltip=tooltip, **encoding ).properties( **properties ) return chart
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repr_mimebundle_(self, *args, **kwargs): """Return a MIME bundle for display in Jupyter frontends."""
chart = self.to_chart() dct = chart.to_dict() return alt.renderers.get()(dct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _enter_newline(self): """ Remove the trailing spaces in the current line, and then mark that the leading spaces of the next line need to be removed. .. seealso:: `CSS Text Module Level 3 - The White Space Processing Rules <http://www.w3.org/TR/css3-text/#white-space-phase-2>`_ """
last_text_idx = self._last_text_idx if last_text_idx >= 0: buf = self._buffer buf[last_text_idx] = buf[last_text_idx].rstrip() self._remove_begining_ws = 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 handle_comment(self, comment): """ Remove comment except IE conditional comment. .. seealso:: `About conditional comments <http://msdn.microsoft.com/en-us/library/ms537512.ASPX>`_ """
match = _COND_COMMENT_PATTERN.match(comment) if match is not None: cond = match.group(1) content = match.group(2) self._buffer.append(_COND_COMMENT_START_FORMAT % cond) self._push_status() self.feed(content) self._pop_status() self._buffer.append(_COND_COMMENT_END_FORMAT) elif not self.remove_comments: self._buffer.append(_COMMENT_FORMAT % comment)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_data(self, data): """ Any space immediately following another collapsible space will be collapsed. .. seealso:: `CSS Text Module Level 3 - The White Space Processing Rules <http://www.w3.org/TR/css3-text/#egbidiwscollapse>`_ """
tag_stack = self._tag_stack if tag_stack and tag_stack[-1] in _RM_WS_ELEMENTS: # just ignore the content of this element assert data.strip() == '' return if self._preserve == 0: if self._remove_begining_ws: data = data.lstrip() if not data: return self._remove_begining_ws = False self._last_text_idx = len(self._buffer) data = _WS_PATTERN.sub(' ', data) if data and data[-1] == ' ': # immediately followed spaces will be collapsed self._remove_begining_ws = True else: # the content cannot be stripped self._reset_newline_status() self._buffer.append(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 twilio_SMS(self, from_, to, body): """ Send an SMS message from your `twilio`_ account. .. _twilio: https://www.twilio.com/ Login will be performed using stored credentials. * *stored credential name: TWILIO_ACCOUNT_SID* * *stored credential name: TWILIO_AUTH_TOKEN* :param string from_: The phone number in your twilio account to send the SMS message from. Full international format. :param string to: The phone number to send the SMS message to. Full international format. :param string body: The content of the SMS message. """
logging.debug('Texting from Twilio') client = TwilioRestClient(self._credentials['TWILIO_ACCOUNT_SID'], self._credentials['TWILIO_AUTH_TOKEN']) response = client.messages.create( to=to, from_=from_, body=body, ) logging.debug('Response from Twilio: {0}'.format(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 special_get_field(self, value, args, kwargs, format_spec=None): """Also take the spec into account"""
if value in self.chain: raise BadOptionFormat("Recursive option", chain=self.chain + [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_page_from_path(self, path): """ Fetches the FeinCMS Page object that the path points to. Override this to deal with different types of object from Page. """
from feincms.module.page.models import Page try: return Page.objects.best_match_for_path(path) except Page.DoesNotExist: 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_resource_access_state(self, request): """ Returns the FeinCMS resource's access_state, following any INHERITed values. Will return None if the resource has an access state that should never be protected. It should not be possible to protect a resource with an access_state of STATE_ALL_ALLOWED, or an access_state of STATE_INHERIT and no parent. Will also return None if the accessed URL doesn't contain a Page. """
feincms_page = self._get_page_from_path(request.path_info.lstrip('/')) if not feincms_page: return None # Chase inherited values up the tree of inheritance. INHERIT = AccessState.STATE_INHERIT while feincms_page.access_state == INHERIT and feincms_page.parent: feincms_page = feincms_page.parent # Resources with STATE_ALL_ALLOWED or STATE_INHERIT and no parent should never be # access-restricted. This code is here rather than in is_resource_protected to # emphasise its importance and help avoid accidentally overriding it. never_restricted = (INHERIT, AccessState.STATE_ALL_ALLOWED) if feincms_page.access_state in never_restricted: return None # Return the found value. return feincms_page.access_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_resource_protected(self, request, **kwargs): """ Determines if a resource should be protected. Returns true if and only if the resource's access_state matches an entry in the return value of get_protected_states(). """
access_state = self._get_resource_access_state(request) protected_states = self.get_protected_states() return access_state in protected_states
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_two_documents(kls, doc1, doc2): """Compare two documents by converting them into json objects and back to strings and compare"""
first = doc1 if isinstance(doc1, string_types): try: first = json.loads(doc1) except (ValueError, TypeError) as error: log.warning("Failed to convert doc into a json object\terror=%s", error) yield error.args[0] return second = doc2 if isinstance(doc2, string_types): try: second = json.loads(doc2) except (ValueError, TypeError) as error: log.warning("Failed to convert doc into a json object\terror=%s", error) yield error.args[0] return # Ordering the principals because the ordering amazon gives me hates me def sort_statement(statement): for principal in (statement.get("Principal", None), statement.get("NotPrincipal", None)): if principal: for principal_type in ("AWS", "Federated", "Service"): if principal_type in principal and type(principal[principal_type]) is list: principal[principal_type] = sorted(principal[principal_type]) def sort_key(statement, key): if key in statement and type(statement[key]) is list: statement[key] = sorted(statement[key]) for document in (first, second): if "Statement" in document: if type(document["Statement"]) is dict: sort_statement(document["Statement"]) sort_key(document["Statement"], "Action") sort_key(document["Statement"], "NotAction") sort_key(document["Statement"], "Resource") sort_key(document["Statement"], "NotResource") else: for statement in document["Statement"]: sort_statement(statement) sort_key(statement, "Action") sort_key(statement, "NotAction") sort_key(statement, "Resource") sort_key(statement, "NotResource") difference = diff(first, second, fromfile="current", tofile="new").stringify() if difference: lines = difference.split('\n') if not first or not second or first != second: for line in lines: yield line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def facter_info(): """Returns data from facter. """
with suppress(FileNotFoundError): # facter may not be installed proc = subprocess.Popen(['facter', '--yaml'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if not proc.returncode: data = serializer.load(stdout) return {'facter': 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_color(index): """Dips the brush in paint. Arguments: index - an integer between 0 and 7, inclusive. Tells the bot which color you want. """
if index in range(0, 8): # Send the turtle to the top-left corner of the window to imitate the position of the WCB's brush. state['turtle'].goto(-WCB_WIDTH / 2, -WCB_HEIGHT / 2) _make_cnc_request("tool.color./" + str(index)) # This is the order of the colors in the palette in our classroom's bot; yours may vary! colors = ["black", "red", "orange", "yellow", "green", "blue", "purple", "brown"] state['turtle'].color(colors[index]) state['distance_traveled'] = 0 else: print("Color indexes must be between 0 and 7, but you gave me: " + index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to(x, y): """Moves the brush to a particular position. Arguments: x - a number between -250 and 250. y - a number between -180 and 180. """
_make_cnc_request("coord/{0}/{1}".format(x, y)) state['turtle'].goto(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def turn_left(relative_angle): """Turns the brush's "turtle" to the left. Arguments: relative_angle - a number like 10. A bigger number makes the turtle turn farther to the left. """
assert int(relative_angle) == relative_angle, "turn_left() only accepts integers, but you gave it " + str(relative_angle) _make_cnc_request("move.left./" + str(relative_angle)) state['turtle'].left(relative_angle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def turn_right(relative_angle): """Turns the brush's "turtle" to the right. Arguments: relative_angle - a number like 10. A bigger number makes the turtle turn farther to the right. """
assert int(relative_angle) == relative_angle, "turn_right() only accepts integers, but you gave it " + str(relative_angle) _make_cnc_request("move.right./" + str(relative_angle)) state['turtle'].right(relative_angle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe(o): """Describes the object using developer-specified attributes specific to each main object type. Returns: dict: keys are specific attributes tailored to the specific object type, though `fqdn` is common to all descriptions; values are the corresponding attribute values which are *simple* types that can easily be serialized to JSON. """
#First, we need to determine the fqdn, so that we can lookup the format for #this object in the config file for the package. from inspect import getmodule from acorn.logging.decoration import _fqdn fqdn = _fqdn(o, False) if fqdn is None: #This should not have happened; if the FQDN couldn't be determined, then #we should have never logged it. return json_describe(o, str(type(o))) package = fqdn.split('.')[0] global _package_desc if package not in _package_desc: from acorn.config import descriptors spack = descriptors(package) if spack is None: _package_desc[package] = None return json_describe(o, fqdn) else: _package_desc[package] = spack if _package_desc[package] is None: return json_describe(o, fqdn) elif fqdn in _package_desc[package]: return json_describe(o, fqdn, _package_desc[package][fqdn]) else: return json_describe(o, fqdn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _obj_getattr(obj, fqdn, start=1): """Returns the attribute specified by the fqdn list from obj. """
node = obj for chain in fqdn.split('.')[start:]: if hasattr(node, chain): node = getattr(node, chain) else: node = None break return node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _package_transform(package, fqdn, start=1, *args, **kwargs): """Applies the specified package transform with `fqdn` to the package. Args: package: imported package object. fqdn (str): fully-qualified domain name of function in the package. If it does not include the package name, then set `start=0`. start (int): in the '.'-split list of identifiers in `fqdn`, where to start looking in the package. E.g., `numpy.linalg.norm` has `start=1` since `package=numpy`; however, `linalg.norm` would have `start=0`. """
#Our only difficulty here is that package names can be chained. We ignore #the first item since that was already checked for us by the calling #method. node = _obj_getattr(package, fqdn, start) #By the time this loop is finished, we should have a function to apply if #the developer setting up the config did a good job. if node is not None and hasattr(node, "__call__"): return node(*args, **kwargs) else: return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _instance_transform(fqdn, o, *args, **kwargs): """Applies an instance method with name `fqdn` to `o`. Args: fqdn (str): fully-qualified domain name of the object. o: object to apply instance method to. """
return _package_transform(o, fqdn, start=0, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_describe(o, fqdn, descriptor=None): """Describes the specified object using the directives in the JSON `descriptor`, if available. Args: o: object to describe. fqdn (str): fully-qualified domain name of the object. descriptor (dict): keys are attributes of `o`; values are transform functions to apply to the attribute so that only a single value is returned. Returns: dict: keys are specific attributes tailored to the specific object type, though `fqdn` is common to all descriptions; values are the corresponding attribute values which are *simple* types that can easily be serialized to JSON. """
if descriptor is None or not isinstance(descriptor, dict): return {"fqdn": fqdn} else: result = {"fqdn": fqdn} for attr, desc in descriptor.items(): if attr == "instance": #For instance methods, we repeatedly call instance methods on #`value`, assuming that the methods belong to `value`. value = o else: if '.' in attr: #We get the chain of attribute values. value = o for cattr in attr.split('.'): if hasattr(value, cattr): value = getattr(value, cattr, "") else: break else: #There is just a one-level getattr. value = getattr(o, attr, "") if "transform" in desc: for transform in desc["transform"]: if "numpy" == transform[0:len("numpy")]: value = _numpy_transform(transform, value) elif "scipy" == transform[0:len("scipy")]: value = _scipy_transform(transform, value) elif "math" == transform[0:len("math")]: value = _math_transform(transform, value) elif "self" in transform: args = desc["args"] if "args" in desc else [] kwds = desc["kwargs"] if "kwargs" in desc else {} method = transform[len("self."):] value = _instance_transform(method, value, *args,**kwds) if "slice" in desc: for si, sl in enumerate(desc["slice"]): if ':' in sl: name, slice = sl.split(':') else: name, slice = str(si), sl slvalue = value for i in map(int, slice.split(',')): slvalue = slvalue[i] result[name] = _array_convert(slvalue) else: if "rename" in desc: result[desc["rename"]] = _array_convert(value) else: result[attr] = _array_convert(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 get_database_name(self): """ extract database from connection string """
uri_dict = uri_parser.parse_uri(self.host) database = uri_dict.get('database', None) if not database: raise "database name is missing" return database
<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(self, start, end, limit=50, *args, **kwargs): """ find by creation date, using start and end dates as range """
# check if spec has been specified, build on top of it fc = kwargs.get('spec', dict()) # filter _id on start and end dates fc['_id'] = {'$gte': ObjectId.from_datetime(start), '$lte': ObjectId.from_datetime(end)} if not self.collection: collection_name = kwargs.get('collection_name', MONGODB_DEFAULT_COLLECTION) self.set_collection(collection_name) return self.collection.find(fc, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_exc(exc): """ Given a database exception determine how to fail Attempt to lookup a known error & abort on a meaningful error. Otherwise issue a generic DatabaseUnavailable exception. :param exc: psycopg2 exception """
err = ERRORS_TABLE.get(exc.pgcode) if err: abort(exceptions.InvalidQueryParams(**{ 'detail': err, 'parameter': 'filter', })) abort(exceptions.DatabaseUnavailable)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirty_vals(model): """ Get the models dirty values in a friendly SQL format This will be a string of comma separated field names in a format for psycopg to substitute with parameterized inputs. An example, if the `rid` & `created` fields are dirty then they'll be converted into: '%(rid)s, %(created)s' :return: str or None """
vals = [] for field in model.dirty_fields: vals.append('%({0})s'.format(field)) vals = ', '.join(vals) return vals or 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 field_cols(model): """ Get the models columns in a friendly SQL format This will be a string of comma separated field names prefixed by the models resource type. TIP: to_manys are not located on the table in Postgres & are instead application references, so any reference to there column names should be pruned! :return: str """
to_many = model.to_many cols = [f for f in model.all_fields if f not in to_many] cols = ', '.join(cols) return cols or 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 sorts_query(sortables): """ Turn the Sortables into a SQL ORDER BY query """
stmts = [] for sortable in sortables: if sortable.desc: stmts.append('{} DESC'.format(sortable.field)) else: stmts.append('{} ASC'.format(sortable.field)) return ' ORDER BY {}'.format(', '.join(stmts))
<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, model): """ Given a model object instance create it """
signals.pre_create.send(model.__class__, model=model) signals.pre_save.send(model.__class__, model=model) param = self.to_pg(model) query = """ INSERT INTO {table} ({dirty_cols}) VALUES ({dirty_vals}) RETURNING {cols}; """ query = query.format( cols=self.field_cols(model), dirty_cols=self.dirty_cols(model), dirty_vals=self.dirty_vals(model), table=model.rtype, ) result = self.query(query, param=param) signals.post_create.send(model.__class__, model=model) signals.post_save.send(model.__class__, model=model) return model.merge(result[0], clean=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 delete(self, model): """ Given a model object instance delete it """
signals.pre_delete.send(model.__class__, model=model) param = {'rid_value': self.to_pg(model)[model.rid_field]} query = """ DELETE FROM {table} WHERE {rid_field} = %(rid_value)s RETURNING {cols}; """ query = query.format( cols=self.field_cols(model), rid_field=model.rid_field, table=model.rtype, ) result = self.query(query, param=param) signals.post_delete.send(model.__class__, model=model) 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 query(self, query, param=None): """ Perform a SQL based query This will abort on a failure to communicate with the database. :query: string query :params: parameters for the query :return: RecordList from psycopg2 """
with self.conn.cursor() as curs: print 'XXX QUERY', curs.mogrify(query, param) try: curs.execute(query, param) except BaseException as exc: msg = 'query: {}, param: {}, exc: {}'.format(query, param, exc) if hasattr(exc, 'pgcode'): msg = '{}, exc code: {}'.format(msg, exc.pgcode) print msg handle_exc(exc) result = curs.fetchall() 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 search(self, rtype, **kwargs): """ Search for the model by assorted criteria Quite a bit needs to happen for a search processing! The breakdown is we need to apply the query parameters where applicable. These include pagination, sorting, & filtering. Additionally, models can declare there own static filters or static query that should be applied. For static filters a model can opt-in with a `search_filters` property & for a static query to append a `search_query` property must be present. """
model = rtype_to_model(rtype) param = {} pages = self.pages_query(kwargs.get('pages')) sorts = self.sorts_query(kwargs.get( 'sorts', [Sortable(goldman.config.SORT)] )) query = """ SELECT {cols}, count(*) OVER() as _count FROM {table} """ query = query.format( cols=self.field_cols(model), table=rtype, ) filters = kwargs.get('filters', []) filters += getattr(model, 'search_filters', []) or [] if filters: where, param = self.filters_query(filters) query += where model_query = getattr(model, 'search_query', '') or '' if filters and model_query: model_query = ' AND ' + model_query elif model_query: model_query = ' WHERE ' + model_query query += model_query query += sorts query += pages signals.pre_search.send(model.__class__, model=model) result = self.query(query, param=param) models = [model(res) for res in result] if models: signals.post_search.send(model.__class__, models=result) pages = kwargs.get('pages') if pages and result: pages.total = result[0]['_count'] return models
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, model): """ Given a model object instance update it """
signals.pre_update.send(model.__class__, model=model) signals.pre_save.send(model.__class__, model=model) param = self.to_pg(model) param['rid_value'] = param[model.rid_field] query = """ UPDATE {table} SET ({dirty_cols}) = ({dirty_vals}) WHERE {rid_field} = %(rid_value)s RETURNING {cols}; """ query = query.format( cols=self.field_cols(model), dirty_cols=self.dirty_cols(model), dirty_vals=self.dirty_vals(model), rid_field=model.rid_field, table=model.rtype, ) result = self.query(query, param=param) signals.post_update.send(model.__class__, model=model) signals.post_save.send(model.__class__, model=model) return model.merge(result[0], clean=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 get_path(environ): """ Get the path """
from wsgiref import util request_uri = environ.get('REQUEST_URI', environ.get('RAW_URI', '')) if request_uri == '': uri = util.request_uri(environ) host = environ.get('HTTP_HOST', '') scheme = util.guess_scheme(environ) prefix = "{scheme}://{host}".format(scheme=scheme, host=host) request_uri = uri.replace(prefix, '') return request_uri
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_purge(environ, start_response): """ Handle a PURGE request. """
from utils import is_valid_security, get_cached_files from settings import DEBUG server = environ['SERVER_NAME'] try: request_uri = get_path(environ) path_and_query = request_uri.lstrip("/") query_string = environ.get('QUERY_STRING', '') if is_valid_security('PURGE', query_string): cached_files = get_cached_files(path_and_query, server) for i in cached_files: try: os.remove(i) except OSError as e: return do_500(environ, start_response, e.message) start_response("204 No Content", []) return [] else: return do_405(environ, start_response) except Http404 as e: return do_404(environ, start_response, e.message, 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 get_instance(page_to_crawl): """Return an instance of CrawlModel."""
global _instances if isinstance(page_to_crawl, basestring): uri = page_to_crawl page_to_crawl = crawlpage.get_instance(uri) elif isinstance(page_to_crawl, crawlpage.CrawlPage): uri = page_to_crawl.uri else: raise TypeError( "get_instance() expects a parker.CrawlPage " "or basestring derivative." ) try: instance = _instances[uri] except KeyError: instance = CrawlModel(page_to_crawl) _instances[uri] = instance return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_exists(original_file): """ Validate the original file is in the S3 bucket """
s3 = boto3.resource('s3') bucket_name, object_key = _parse_s3_file(original_file) bucket = s3.Bucket(bucket_name) bucket_iterator = bucket.objects.filter(Prefix=object_key) bucket_list = [x for x in bucket_iterator] logger.debug("Bucket List: {0}".format(", ".join([x.key for x in bucket_list]))) logger.debug("bucket_list length: {0}".format(len(bucket_list))) return len(bucket_list) == 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 put_file(buffer, modified_file): """ write the buffer to modified_file. modified_file should be in the format 's3://bucketname/path/to/file.txt' """
import mimetypes import boto3 file_type, _ = mimetypes.guess_type(modified_file) s3 = boto3.resource('s3') bucket_name, object_key = _parse_s3_file(modified_file) extra_args = { 'ACL': 'public-read', 'ContentType': file_type } bucket = s3.Bucket(bucket_name) logger.info("Uploading {0} to {1}".format(object_key, bucket_name)) bucket.upload_fileobj(buffer, object_key, ExtraArgs=extra_args)
<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_data_files(*include_dirs): 'called from setup.py in skeleton projects' data_files = [] for include_dir in include_dirs: for root, directories, filenames in os.walk(include_dir): include_files = [] for filename in filenames: # do not bring along certain files if filename.endswith('.local'): continue include_files.append(os.path.join(root, filename)) if include_files: data_files.append((root, include_files)) return data_files
<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_html_dict(dictionary, prefix=''): """ Used to support dictionary values in HTML forms. { 'profile.username': 'example', 'profile.email': 'example@example.com', } --> { 'profile': { 'username': 'example', 'email': 'example@example.com' } } """
ret = MultiValueDict() regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix)) for field, value in dictionary.items(): match = regex.match(field) if not match: continue key = match.groups()[0] ret[key] = value 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 meta(self): """Data for loading later"""
mount_points = [] for overlay in self.overlays: mount_points.append(overlay.mount_point) return [self.end_dir, self.start_dir, mount_points]
<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_level_fmt(self, level): """Get format for log level."""
key = None if level == logging.DEBUG: key = 'debug' elif level == logging.INFO: key = 'info' elif level == logging.WARNING: key = 'warning' elif level == logging.ERROR: key = 'error' elif level == logging.CRITICAL: key = 'critical' return self.overwrites.get(key, self.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 format(self, record): """Format log record."""
format_orig = self._fmt self._fmt = self.get_level_fmt(record.levelno) record.prefix = self.prefix record.plugin_id = self.plugin_id result = logging.Formatter.format(self, record) self._fmt = format_orig 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 start_simple_server(): "A simple mail server that sends a simple response" args = _get_args() addr = ('', args.port) DebuggingServer(addr, None) asyncore.loop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_post(self, req, resp): """ Validate the token revocation request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder. """
token = req.get_param('token') token_type_hint = req.get_param('token_type_hint') # errors or not, disable client caching along the way # per the spec resp.disable_caching() if not token: resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'invalid_request', 'error_description': 'A token parameter is required during ' 'revocation according to RFC 7009.', 'error_uri': 'tools.ietf.org/html/rfc7009#section-2.1', }) elif token_type_hint == 'refresh_token': resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'unsupported_token_type', 'error_description': 'Currently only access_token types can ' 'be revoked, NOT refresh_token types.', 'error_uri': 'tools.ietf.org/html/rfc7009#section-2.2.1', }) else: # ignore return code per section 2.2 self.revoke_token(token) resp.status = falcon.HTTP_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 emulate_seek(fd, offset, chunk=CHUNK): """ Emulates a seek on an object that does not support it The seek is emulated by reading and discarding bytes until specified offset is reached. The ``offset`` argument is in bytes from start of file. The ``chunk`` argument can be used to adjust the size of the chunks in which read operation is performed. Larger chunks will reach the offset in less reads and cost less CPU but use more memory. Conversely, smaller chunks will be more memory efficient, but cause more read operations and more CPU usage. If chunk is set to None, then the ``offset`` amount of bytes is read at once. This is fastest but depending on the offset size, may use a lot of memory. Default chunk size is controlled by the ``fsend.rangewrapper.CHUNK`` constant, which is 8KB by default. This function has no return value. """
while chunk and offset > CHUNK: fd.read(chunk) offset -= chunk fd.read(offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_seek(fd, offset, chunk=CHUNK): """ Force adjustment of read cursort to specified offset This function takes a file descriptor ``fd`` and tries to seek to position specified by ``offset`` argument. If the descriptor does not support the ``seek()`` method, it will fall back to ``emulate_seek()``. The optional ``chunk`` argument can be used to adjust the chunk size for ``emulate_seek()``. """
try: fd.seek(offset) except (AttributeError, io.UnsupportedOperation): # This file handle probably has no seek() emulate_seek(fd, offset, chunk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def range_iter(fd, offset, length, chunk=CHUNK): """ Iterator generator that iterates over chunks in specified range This generator is meant to be used when returning file descriptor as a response to Range request (byte serving). It limits the reads to the region specified by ``offset`` (in bytes form start of the file) and ``limit`` (number of bytes to read), and returns the file contents in chunks of ``chunk`` bytes. The read offset is set either by using the file descriptor's ``seek()`` method, or by using ``emulate_seek()`` function if file descriptor does not implement ``seek()``. The file descriptor is automatically closed when iteration is finished. """
force_seek(fd, offset, chunk) while length > 0: ret = fd.read(chunk) if not ret: return length -= chunk yield ret fd.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(self, size=None): """ Read a specified number of bytes from the file descriptor This method emulates the normal file descriptor's ``read()`` method and restricts the total number of bytes readable. If file descriptor is not present (e.g., ``close()`` method had been called), ``ValueError`` is raised. If ``size`` is omitted, or ``None``, or any other falsy value, read will be done up to the remaining length (constructor's ``length`` argument minus the bytes that have been read previously). This method internally invokes the file descriptor's ``read()`` method, and the method must accept a single integer positional argument. """
if not self.fd: raise ValueError('I/O on closed file') if not size: size = self.remaining size = min([self.remaining, size]) if not size: return '' data = self.fd.read(size) self.remaining -= size 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 placeholdit( width, height, background_color="cccccc", text_color="969696", text=None, random_background_color=False ): """ Creates a placeholder image using placehold.it Usage format: {% placeholdit [width] [height] [background_color] [text_color] [text] %} Example usage: Default image at 250 square {% placeholdit 250 %} 100 wide and 200 high {% placeholdit 100 200 %} Custom background and text colors {% placeholdit 100 200 background_color='fff' text_color=000' %} Custom text {% placeholdit 100 200 text='Hello LA' %} """
url = get_placeholdit_url( width, height, background_color=background_color, text_color=text_color, text=text, ) return format_html('<img src="{}"/>', 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 pangram(language='en'): """ Prints a pangram in the specified language. A pangram is a phrase that includes every letter of an alphabet. Default is English. For a full list of available languages, refer to pangrams.py Usage format:: {% pangram [language] %} ``language`` is the two-letter abbreviation the desired language. Examples: * ``{% pangram %}`` will output the default English pangram. * ``{% pangram 'fr' %}`` will output a French pangram. """
try: pangram = get_pangram(language) except KeyError: raise template.TemplateSyntaxError( "Could not find a pangram for %r abbreviation" % language ) return get_pangram_html(pangram)
<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_result(self): """ get the result """
info = {} self.options2attr = { 'email': self._email, 'telephone': self._telephone, 'QQ' : self._QQ, 'wechat': self._wechat, 'url': self._url, 'emoji': self._emoji, 'tex': self._tex, 'blur': self._blur, 'message': self.m, } for item in self.option: info[item] = self.options2attr[item] return 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 extract(self, m): """ extract info specified in option """
self._clear() self.m = m # self._preprocess() if self.option != []: self._url_filter() self._email_filter() if 'tex' in self.option: self._tex_filter() # if 'email' in self.option: # self._email_filter() if 'telephone' in self.option: self._telephone_filter() if 'QQ' in self.option: self._QQ_filter() if 'emoji' in self.option: self._emoji_filter() if 'wechat' in self.option: self._wechat_filter() self._filter() if 'blur' in self.option: self._blur = get_number(self.m, self._limit) return self._get_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 _filter(self): """ delete the punctuation """
pattern = u"[\s+\.\!\-\/_,$%^*(+\"\']+|[+——!】【,。??:、:~@#¥%……&*“”()]+" self.m = re.sub(pattern, "", self.m)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_log_level(self, log_level): '''Configures class log level Arguments: log_level (:obj:`str`): log level ('NOTSET','DEBUG','INFO' 'WARNING', 'ERROR', 'CRITICAL') ''' if log_level == 'DEBUG': self.log.setLevel(logging.DEBUG) self.log.debug("Changing log level to "+log_level) elif log_level == 'INFO': self.log.setLevel(logging.INFO) self.log.info("Changing log level to "+log_level) elif log_level == 'WARNING': self.log.setLevel(logging.WARNING) self.log.warning("Changing log level to "+log_level) elif log_level == 'ERROR': self.log.setLevel(logging.ERROR) self.log.error("Changing log level to "+log_level) elif log_level == 'CRITICAL': self.log.setLevel(logging.CRITICAL) self.log.critical("Changing log level to "+log_level) elif log_level == 'NOTSET': self.log.setLevel(logging.NOTSET) else: raise NotImplementedError('Not implemented log level '+str(log_level))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_log_format(self, log_type, log_format): '''Configures log format Arguments: log_type (:obj:`str`): log type (error, debug or stream) log_format (:obj:`str`): log format (ex:"Log: %(message)s | Log level:%(levelname)s | Date:%(asctime)s',datefmt='%m/%d/%Y %I:%M:%S") ''' if not (log_type == 'error' or log_type == 'stream' or log_type == 'debug'): self.log.debug('Log type must be error, stream, or debug') else: self.default_formatter = logging.Formatter(log_format) if log_type == 'error': self.error_handler.setFormatter(self.default_formatter) elif log_type == 'debug': self.debug_handler.setFormatter(self.default_formatter) elif log_type == 'stream': self.stream_handler.setFormatter(self.default_formatter)
<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_document(self, question, answer): """Add question answer set to DB. :param question: A question to an answer :type question: :class:`str` :param answer: An answer to a question :type answer: :class:`str` """
question = question.strip() answer = answer.strip() session = self.Session() if session.query(Document) \ .filter_by(text=question, answer=answer).count(): logger.info('Already here: {0} -> {1}'.format(question, answer)) return logger.info('add document: {0} -> {1}'.format(question, answer)) grams = self._get_grams(session, question, make=True) doc = Document(question, answer) doc.grams = list(grams) self._recalc_idfs(session, grams) session.add(doc) session.commit()
<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_best_answer(self, query): """Get best answer to a question. :param query: A question to get an answer :type query: :class:`str` :returns: An answer to a question :rtype: :class:`str` :raises: :class:`NoAnswerError` when can not found answer to a question """
query = to_unicode(query) session = self.Session() grams = self._get_grams(session, query) if not grams: raise NoAnswerError('Can not found answer') documents = set([doc for gram in grams for doc in gram.documents]) self._recalc_idfs(session, grams) idfs = dict((gram.gram, gram.idf) for gram in grams) docs = dict( (doc.answer, _cosine_measure(idfs, self._get_tf_idfs(doc))) for doc in documents) docs = dict((key, val) for (key, val) in docs.items() if val) session.commit() try: max_ratio = max(docs.values()) answers = [answer for answer in docs.keys() if docs.get(answer) == max_ratio] answer = random.choice(answers) logger.debug('{0} -> {1} ({2})'.format(query, answer, max_ratio)) return (answer, max_ratio) except ValueError: raise NoAnswerError('Can not found answer') finally: session.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recreate_grams(self): """Re-create grams for database. In normal situations, you never need to call this method. But after migrate DB, this method is useful. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` """
session = self.Session() for document in session.query(Document).all(): logger.info(document.text) grams = self._get_grams(session, document.text, make=True) document.grams = list(grams) broken_links = session.query(Gram) \ .filter(~Gram.documents.any()).all() for gram in broken_links: session.delete(gram) session.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recalc_idfs(self, session, grams=None): """Re-calculate idfs for database. calculating idfs for gram is taking long time. So I made it calculates idfs for some grams. If you want make accuracy higher, use this with grams=None. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` :param grams: grams that you want to re-calculating idfs :type grams: A set of :class:`Gram` """
if not grams: grams = session.query(Gram) for gram in grams: orig_idf = gram.idf gram.idf = self._get_idf(session, gram) logger.debug('Recalculating {} {} -> {}'.format( gram.gram, orig_idf, gram.idf))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def throw(self, type, value=None, traceback=None): # pylint: disable=redefined-builtin """Raise an exception in this element"""
return self.__wrapped__.throw(type, value, traceback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enumeratelet(iterable=None, start=0): r""" Enumerate chunks of data from an iterable or a chain :param iterable: object supporting iteration, or an index :type iterable: iterable, None or int :param start: an index to start counting from :type start: int :raises TypeError: if both parameters are set and ``iterable`` does not support iteration In pull mode, :py:func:`~.enumeratelet` works similar to the builtin :py:func:`~.enumerate` but is chainable: .. code:: chain = enumeratelet(['Paul', 'Thomas', 'Brian']) >> printlet(sep=':\t') for value in chain: pass # prints `0: Paul`, `1: Thomas`, `2: Brian` By default, :py:func:`~.enumeratelet` enumerates chunks passed in from a pipeline. To use a different starting index, *either* set the ``start`` keyword parameter *or* set the first positional parameter. .. code:: chain = iteratelet(['Paul', 'Thomas', 'Brian']) >> enumeratelet() >> printlet(sep=':\t') for value in chain: pass # prints `0: Paul`, `1: Thomas`, `2: Brian` """
# shortcut directly to chain enumeration if iterable is None: return _enumeratelet(start=start) try: iterator = iter(iterable) except TypeError: if start != 0: raise # first arg is not iterable but start is explicitly set return _enumeratelet(start=iterable) # first arg is not iterable, try short notation else: return iterlet(enumerate(iterator, start=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 filterlet(function=bool, iterable=None): """ Filter chunks of data from an iterable or a chain :param function: callable selecting valid elements :type function: callable :param iterable: object providing chunks via iteration :type iterable: iterable or None For any chunk in ``iterable`` or the chain, it is passed on only if ``function(chunk)`` returns true. .. code:: chain = iterlet(range(10)) >> filterlet(lambda chunk: chunk % 2 == 0) for value in chain: print(value) # prints 0, 2, 4, 6, 8 """
if iterable is None: return _filterlet(function=function) else: return iterlet(elem for elem in iterable if function(elem))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printlet(flatten=False, **kwargs): """ Print chunks of data from a chain :param flatten: whether to flatten data chunks :param kwargs: keyword arguments as for :py:func:`print` If ``flatten`` is :py:const:`True`, every chunk received is unpacked. This is useful when passing around connected data, e.g. from :py:func:`~.enumeratelet`. Keyword arguments via ``kwargs`` are equivalent to those of :py:func:`print`. For example, passing ``file=sys.stderr`` is a simple way of creating a debugging element in a chain: .. code:: debug_chain = chain[:i] >> printlet(file=sys.stderr) >> chain[i:] """
chunk = yield if flatten: while True: print(*chunk, **kwargs) chunk = yield chunk else: while True: print(chunk, **kwargs) chunk = yield chunk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_one(self, aws_syncr, amazon, function): """Make sure this function exists and has only attributes we want it to have"""
function_info = amazon.lambdas.function_info(function.name, function.location) if not function_info: amazon.lambdas.create_function(function.name, function.description, function.location, function.runtime, function.role, function.handler, function.timeout, function.memory_size, function.code) else: amazon.lambdas.modify_function(function_info, function.name, function.description, function.location, function.runtime, function.role, function.handler, function.timeout, function.memory_size, function.code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self, *args, **kwargs): '''Preserves order if given an assoc list. ''' arg = dict_arg(*args, **kwargs) if isinstance(arg, list): for key, val in arg: self[key] = val else: super(AssocDict, self).update(arg)
<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_url_path(list_name): """ Live Dao requires RESTCLIENTS_MAILMAN_KEY in the settings.py """
access_key = getattr(settings, "RESTCLIENTS_MAILMAN_KEY", "__mock_key__") return URL.format(key=access_key, uwnetid=list_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 operations(*operations): '''Decorator for marking Resource methods as HTTP operations. This decorator does a number of different things: - It transfer onto itself docstring and annotations from the decorated method, so as to be "transparent" with regards to introspection. - It tranform the method so as to make it a classmethod. - It invokes the method within a try-except condition, so as to intercept and populate the Fail(<code>) conditions.''' def decorator(method): def wrapper(cls, request, start_response, **kwargs): result_cache = [] try: yield from method(cls, request, **kwargs) except Respond as e: # Inject messages as taken from signature status = e.status msg = utils.parse_return_annotation(method)[status]['message'] if status / 100 == 2: # All 2xx HTTP codes e.description = msg raise e else: # HTTP Errors --> use werkzeug exceptions raise CODES_TO_EXCEPTIONS[status](msg) # Add operation-specific attributes to the method. method.swagger_ops = operations method.signature = inspect.signature(method) method.source = inspect.getsource(method) method.path_vars = utils.extract_pathvars(method) # "Backport" the method introspective attributes to the wrapper. wrapper.__name__ = method.__name__ wrapper.__doc__ = method.__doc__ wrapper.__annotations__ = method.__annotations__ wrapper.swagger_ops = method.swagger_ops wrapper.signature = method.signature wrapper.source = method.source wrapper.path_vars = method.path_vars return classmethod(wrapper) 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 parse_signature(cls, function): '''Parses the signature of a method and its annotations to swagger. Return a dictionary {arg_name: info}. ''' annotations = function.__annotations__.copy() del annotations['return'] result = [] for param_name, (param_type, param_obj) in annotations.items(): sig_param = function.signature.parameters[param_name] param_description = { 'paramType': param_type, 'name': param_name, 'required': sig_param.default is inspect.Parameter.empty} param_description.update(param_obj.describe()) result.append(param_description) 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_swagger_fragment(cls): '''Return the swagger-formatted fragment for the Resource Listing.''' if cls.__swagger_fragment: return cls.__swagger_fragment cls.__swagger_fragment = { 'path': cls.endpoint_path.replace('<', '{').replace('>', '}'), 'description': cls.description, 'operations': cls.get_resource_operations(), } return cls.__swagger_fragment
<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_resource_operations(cls): '''Return the swagger-formatted method descriptions''' operations = [] for http, callback in cls.implemented_methods.items(): # Parse docstring summary, notes = utils.parse_docstring(callback) # Parse return annotations responses = utils.parse_return_annotation(callback) ok_result_model = responses[200]['responseModel'] operations.append({ 'method': http, 'nickname': callback.__name__, 'type': ok_result_model, 'parameters': cls.parse_signature(callback), 'summary': summary.strip(), 'notes': notes.strip(), 'responseMessages': list(responses.values()) }) return operations
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def callbacks(cls): '''Return all the methods that are actually a request callback.''' if cls.__callbacks is not None: return cls.__callbacks cls.__callbacks = [] for mname in dir(cls): # Avoid recursion by excluding all methods of this prototype class if mname in dir(Resource): continue callback = getattr(cls, mname) if not hasattr(callback, 'swagger_ops'): continue cls.__callbacks.append(callback) return cls.__callbacks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def implemented_methods(cls): '''Return a mapping of implemented HTTP methods vs. their callbacks.''' if cls.__implemented_methods: return cls.__implemented_methods cls.__implemented_methods = {} for method in cls.callbacks: for op in getattr(method, 'swagger_ops'): cls.__implemented_methods[op] = method return cls.__implemented_methods
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit2dArrayToFn(arr, fn, mask=None, down_scale_factor=None, output_shape=None, guess=None, outgrid=None): """Fit a 2d array to a 2d function USE ONLY MASKED VALUES * [down_scale_factor] map to speed up fitting procedure, set value smaller than 1 * [output_shape] shape of the output array * [guess] must be scaled using [scale_factor] Returns: Fitted map, fitting params (scaled), error """
if mask is None: #assert outgrid is not None mask = np.ones(shape=arr.shape, dtype=bool) if down_scale_factor is None: if mask.sum() > 1000: down_scale_factor = 0.3 else: down_scale_factor = 1 if down_scale_factor != 1: # SCALE TO DECREASE AMOUNT OF POINTS TO FIT: arr2 = zoom(arr, down_scale_factor) mask = zoom(mask, down_scale_factor, output=bool) else: arr2 = arr # USE ONLY VALID POINTS: x, y = np.where(mask) z = arr2[mask] # FIT: parameters, cov_matrix = curve_fit(fn, (x, y), z, p0=guess) # ERROR: perr = np.sqrt(np.diag(cov_matrix)) if outgrid is not None: yy,xx = outgrid rebuilt = fn((yy,xx), *parameters) else: if output_shape is None: output_shape = arr.shape fx = arr2.shape[0] / output_shape[0] fy = arr2.shape[1] / output_shape[1] rebuilt = np.fromfunction(lambda x, y: fn((x * fx, y * fy), *parameters), output_shape) return rebuilt, parameters, perr
<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_auth_scheme(self, req): """ Check if the request has auth & the proper scheme Remember NOT to include the error related info in the WWW-Authenticate header for these conditions. :raise: AuthRequired """
if not req.auth: raise AuthRequired(**{ 'detail': 'You must first login to access the requested ' 'resource(s). Please retry your request using ' 'OAuth 2.0 Bearer Token Authentication as ' 'documented in RFC 6750. If you do not have an ' 'access_token then request one at the token ' 'endpdoint of: %s' % self.token_endpoint, 'headers': self._error_headers, 'links': 'tools.ietf.org/html/rfc6750#section-2.1', }) elif req.auth_scheme != 'bearer': raise AuthRequired(**{ 'detail': 'Your Authorization header is using an unsupported ' 'authentication scheme. Please modify your scheme ' 'to be a string of: "Bearer".', 'headers': self._error_headers, 'links': 'tools.ietf.org/html/rfc6750#section-2.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 _get_token(self, req): """ Get the token from the Authorization header If the header is actually malformed where Bearer Auth was indicated by the request then an InvalidAuthSyntax exception is raised. Otherwise an AuthRequired exception since it's unclear in this scenario if the requestor was even aware Authentication was required & if so which "scheme". Calls _validate_auth_scheme first & bubbles up it's exceptions. :return: string token :raise: AuthRequired, InvalidAuthSyntax """
self._validate_auth_scheme(req) try: return naked(req.auth.split(' ')[1]) except IndexError: desc = 'You are using the Bearer Authentication scheme as ' \ 'required to login but your Authorization header is ' \ 'completely missing the access_token.' raise InvalidAuthSyntax(**{ 'detail': desc, 'headers': self._get_invalid_token_headers(desc), 'links': 'tools.ietf.org/html/rfc6750#section-2.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 start(self): """Starts the delayed execution"""
if self._timer: self._timer.cancel() self._timer = Timer(self._timeout, self._fire) self._timer.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 tmpfile(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX): ''' For use in a with statement, this function returns a context manager that yields a path directly under root guaranteed to be unique by using the uuid module. This path is not created. However if the path is an existing file when the with statement is exited, the file will be removed. This function is useful if you want to use a file temporarily but do not want to write boilerplate to make sure it is removed when you are done with it. Example: with temps.tmpfile() as path: do_stuff(path) ''' path = tmppath(root, prefix, suffix) try: yield path finally: if os.path.isfile(path): # try to delete the file os.unlink(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 tmppath(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX): ''' Returns a path directly under root that is guaranteed to be unique by using the uuid module. ''' return os.path.join(root, prefix + uuid.uuid4().hex + suffix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getComplexFileData(self, fileInfo, data): """Function to initialize the slightly more complicated data for file info"""
result = fileInfo[fileInfo.find(data + "</td>") + len(data + "</td>"):] result = result[:result.find("</td>")] result = result[result.rfind(">") + 1:] 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 getFileDescription(self, fileInfo): """Function to get the description of a file."""
data = 'Description' result = fileInfo[fileInfo.find(data + "</td>") + len(data + "</td>"):] result.lstrip() result = result[:result.find("</td>")] result = result[result.rfind("<"):] if "<td" in result: result = result[result.find(">") + 1:] 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 two_numbers( cls, request, operation: (Ptypes.path, String('One of the 4 arithmetic operations.', enum=['add', 'sub', 'mul', 'div'])), first: (Ptypes.path, Float('The first operand.')), second: (Ptypes.path, Float('The second operand.'))) -> [ (200, 'Ok', Float), (400, 'Wrong number format or invalid operation'), (422, 'NaN')]: '''Any of the four arithmetic operation on two numbers.''' log.info('Performing {} on {} and {}'.format(operation, first, second)) try: first = float(first) second = float(second) except ValueError: Respond(400) if operation == 'add': Respond(200, first + second) elif operation == 'sub': Respond(200, first - second) elif operation == 'mul': Respond(200, first * second) elif operation == 'div': if second == 0: Respond(422) Respond(200, first / second) else: Respond(400)