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 imshow_z(data, name): """2D color plot of the quasiparticle weight as a function of interaction and doping"""
zmes = pick_flat_z(data) plt.figure() plt.imshow(zmes.T, origin='lower', \ extent=[data['doping'].min(), data['doping'].max(), \ 0, data['u_int'].max()], aspect=.16) plt.colorbar() plt.xlabel('$n$', fontsize=20) plt.ylabel('$U/D$', fontsize=20) plt.savefig(name+'_imshow.png', dpi=300, format='png', transparent=False, bbox_inches='tight', pad_inches=0.05)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_mean_field_conv(N=1, n=0.5, Uspan=np.arange(0, 3.6, 0.5)): """Generates the plot on the convergenge of the mean field in single site spin hamiltonian under with N degenerate half-filled orbitals """
sl = Spinon(slaves=2*N, orbitals=N, avg_particles=2*n, hopping=[0.5]*2*N, orbital_e=[0]*2*N) hlog = solve_loop(sl, Uspan, [0.])[1] f, (ax1, ax2) = plt.subplots(2, sharex=True) for field in hlog: field = np.asarray(field) ax1.semilogy(abs(field[1:]-field[:-1])) ax2.plot(field)#, label = 'h, U = {}'.format(Uint)) plt.title('Convergence of selfconsintent mean field') ax1.set_ylabel('$\\Delta h$') ax2.set_ylabel('mean field $h$') plt.xlabel('iterations') return hlog
<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): """Returns the model properties as a dict"""
result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Payment, dict): for key, value in self.items(): result[key] = 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 from_config(cls): """Method to return back a loaded instance."""
config = Config() client = cls( email=config.get('email'), api_key=config.get('api_key'), server=config.get('api_server'), http_proxy=config.get('http_proxy'), https_proxy=config.get('https_proxy'), ) return client
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_debug(self, status): """Control the logging state."""
if status: self.logger.setLevel('DEBUG') else: self.logger.setLevel('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 _endpoint(self, endpoint, action, *url_args): """Return the URL for the action. :param str endpoint: The controller :param str action: The action provided by the controller :param url_args: Additional endpoints(for endpoints that take part of the url as option) :return: Full URL for the requested action """
args = (self.api_base, endpoint, action) if action == '': args = (self.api_base, endpoint) api_url = "/".join(args) if url_args: if len(url_args) == 1: api_url += "/" + url_args[0] else: api_url += "/".join(url_args) return api_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 _json(self, response): """JSON response from server. :param response: Response from the server :throws ValueError: from requests' response.json() error :return: response deserialized from JSON """
if response.status_code == 204: return None try: return response.json() except ValueError as e: raise ValueError( 'Exception: %s\n' 'request: %s, response code: %s, response: %s' % ( str(e), response.request.url, response.status_code, response.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 _get(self, endpoint, action, *url_args, **url_params): """Request API Endpoint - for GET methods. :param str endpoint: Endpoint :param str action: Endpoint Action :param url_args: Additional endpoints(for endpoints that take part of the url as option) :param url_params: Parameters to pass to url, typically query string :return: response deserialized from JSON """
api_url = self._endpoint(endpoint, action, *url_args) kwargs = {'headers': self.headers, 'params': url_params, 'timeout': Client.TIMEOUT, 'verify': self.verify} if self.proxies: kwargs['proxies'] = self.proxies self.logger.debug("Requesting: %s, %s" % (api_url, str(kwargs))) response = requests.get(api_url, **kwargs) return self._json(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 _send_data(self, method, endpoint, action, data, *url_args, **url_params): """Submit to API Endpoint - for DELETE, PUT, POST methods. :param str method: Method to use for the request :param str endpoint: Endpoint :param str action: Endpoint Action :param url_args: Additional endpoints(for endpoints that take part of the url as option) :param url_params: Parameters to pass to url, typically query string :return: response deserialized from JSON """
api_url = self._endpoint(endpoint, action, *url_args) data.update({'email': self.email, 'api_key': self.api_key}) data = json.dumps(data) kwargs = {'headers': self.headers, 'params': url_params, 'verify': self.verify, 'data': data} if self.proxies: kwargs['proxies'] = self.proxies self.logger.debug("Requesting: %s %s, %s" % (method, api_url, str(kwargs))) response = requests.request(method, api_url, **kwargs) self.logger.debug("Response: %d, %s" % (response.status_code, response.content)) return self._json(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 process_events(events, source_ip): """Process all the events for logging and S3."""
s3 = boto3.resource('s3') table = boto3.resource("dynamodb").Table(os.environ['database']) with table.batch_writer() as batch: for idx, event in enumerate(events): event = convert_keys_to_string(event) event['sourceIp'] = source_ip event['event'] = hashlib.sha256(str(event)).hexdigest() metadata = event['metadata'] timestamp = str(event['metadata']['timeStamp']) event['metadata']['timeStamp'] = timestamp kwargs = {'match': event['indicatorMatch'], 'type': metadata['type'], 'method': metadata['method'].lower(), 'time': event['analysisTime'], 'ip': source_ip} file_struct = '{match}_{type}_{method}_{ip}_{time}.json' file_name = file_struct.format(**kwargs) key_path = '/tmp/%s' % file_name output = json.dumps(event, indent=4, sort_keys=True) open(key_path, "w").write(output) data = open(key_path, 'rb') s3.Bucket(os.environ['s3_bucket']).put_object(Key=file_name, Body=data) logger.info("EVENT: %s" % str(event)) batch.put_item(Item=event) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cost_type(self, cost_type): """Sets the cost_type of this TableRateShipping. :param cost_type: The cost_type of this TableRateShipping. :type: str """
allowed_values = ["orderSubtotal", "weight"] if cost_type is not None and cost_type not in allowed_values: raise ValueError( "Invalid value for `cost_type` ({0}), must be one of {1}" .format(cost_type, allowed_values) ) self._cost_type = cost_type
<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_source(path): ''' yields all non-empty lines in a file ''' for line in read(path): if 'import' in line or len(line.strip()) == 0 or line.startswith('#'): continue if '__name__' in line and '__main__' in line: break else: 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 authenticate(self, request): """ Authenticate request using HTTP Basic authentication protocl. If the user is successfully identified, the corresponding user object is stored in `request.user`. If the request has already been authenticated (i.e. `request.user` has authenticated user object), this function does nothing. Raises Forbidden or Unauthorized if the user authentication fails. If no exception is thrown, the `request.user` will contain authenticated user object. """
# todo: can we trust that request.user variable is even defined? if request.user and request.user.is_authenticated(): return request.user if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2: if auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).split(':') user = authenticate(username=uname, password=passwd) if user is not None: if user.is_active: request.user = user return user else: raise Forbidden() # either no auth header or using some other auth protocol, # we'll return a challenge for the user anyway raise Unauthorized()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(): """Clean up previous garbage"""
os.chdir(os.path.join(project_root, 'docs')) sh("make clean") os.chdir(project_root) sh("rm -rf pyoauth2.egg-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 average(): """ generator that holds a rolling average """
count = 0 total = total() i=0 while 1: i = yield ((total.send(i)*1.0)/count if count else 0) count += 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 args(self): """Parsed command-line arguments."""
if self._args is None: parser = self._build_parser() self._args = parser.parse_args() return self._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 build_pypackage_basename(self, pytree, base): """Build the string representing the parsed package basename. :param str pytree: The pytree absolute path. :param str pytree: The absolute path of the pytree sub-package of which determine the parsed name. :rtype: str """
dirname = os.path.dirname(pytree) parsed_package_name = base.replace(dirname, '').strip('/') return parsed_package_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 _build_parser(self): """Build the needed command-line parser."""
parser = argparse.ArgumentParser() parser.add_argument('--pytree', required=True, type=self._valid_directory, help='This is the path, absolute or relative, of the Python package ' 'that is to be parsed.') parser.add_argument('--doctree', required=True, type=self._valid_directory, help='This is the path, absolute or relative, of the documentation ' 'package that is to be parsed.') parser.add_argument('--no-fail', action='store_true', help='Using this option will cause this program to return an exit ' 'code of 0 even when the given trees do not match.') parser.add_argument('--doc-ignores', action=AddDocIgnores, help='A comma separated list of additional doc files to ignore') return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_pyfile_path_from_docname(self, docfile): """Build the expected Python file name based on the given documentation file name. :param str docfile: The documentation file name from which to build the Python file name. :rtype: str """
name, ext = os.path.splitext(docfile) expected_py_name = name.replace('.', '/') + '.py' return expected_py_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 calculate_tree_differences(self, pytree, doctree): """Calculate the differences between the given trees. :param dict pytree: The dictionary of the parsed Python tree. :param dict doctree: The dictionary of the parsed documentation tree. :rtype: tuple :returns: A two-tuple of sets, where the first is the missing Python files, and the second is the missing documentation files. """
pykeys = set(pytree.keys()) dockeys = set(doctree.keys()) # Calculate the missing documentation files, if any. missing_doc_keys = pykeys - dockeys missing_docs = {pytree[pyfile] for pyfile in missing_doc_keys} # Calculate the missing Python files, if any. missing_py_keys = dockeys - pykeys missing_pys = {docfile for docfile in missing_py_keys} return missing_pys, missing_docs
<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_trees(self, parsed_pytree, parsed_doctree): """Compare the given parsed trees. :param dict parsed_pytree: A dictionary representing the parsed Python tree where each key is a parsed Python file and its key is its expected rst file name. """
if parsed_pytree == parsed_doctree: return 0 missing_pys, missing_docs = self.calculate_tree_differences(pytree=parsed_pytree, doctree=parsed_doctree) self.pprint_tree_differences(missing_pys=missing_pys, missing_docs=missing_docs) return 0 if self.args.no_fail else 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 parse_doc_tree(self, doctree, pypackages): """Parse the given documentation tree. :param str doctree: The absolute path to the documentation tree which is to be parsed. :param set pypackages: A set of all Python packages found in the pytree. :rtype: dict :returns: A dict where each key is the path of an expected Python module and its value is the parsed rst module name (relative to the documentation tree). """
parsed_doctree = {} for filename in os.listdir(doctree): if self._ignore_docfile(filename): continue expected_pyfile = self.build_pyfile_path_from_docname(filename) parsed_doctree[expected_pyfile] = filename pypackages = {name + '.py' for name in pypackages} return {elem: parsed_doctree[elem] for elem in parsed_doctree if elem not in pypackages}
<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_py_tree(self, pytree): """Parse the given Python package tree. :param str pytree: The absolute path to the Python tree which is to be parsed. :rtype: dict :returns: A two-tuple. The first element is a dict where each key is the path of a parsed Python module (relative to the Python tree) and its value is the expected rst module name. The second element is a set where each element is a Python package or sub-package. :rtype: tuple """
parsed_pytree = {} pypackages = set() for base, dirs, files in os.walk(pytree): if self._ignore_pydir(os.path.basename(base)): continue # TODO(Anthony): If this is being run against a Python 3 package, this needs to be # adapted to account for namespace packages. elif '__init__.py' not in files: continue package_basename = self.build_pypackage_basename(pytree=pytree, base=base) pypackages.add(package_basename) for filename in files: if self._ignore_pyfile(filename): continue parsed_path = os.path.join(package_basename, filename) parsed_pytree[parsed_path] = self.build_rst_name_from_pypath(parsed_path) return parsed_pytree, pypackages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pprint_tree_differences(self, missing_pys, missing_docs): """Pprint the missing files of each given set. :param set missing_pys: The set of missing Python files. :param set missing_docs: The set of missing documentation files. :rtype: None """
if missing_pys: print('The following Python files appear to be missing:') for pyfile in missing_pys: print(pyfile) print('\n') if missing_docs: print('The following documentation files appear to be missing:') for docfiile in missing_docs: print(docfiile) print('\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _valid_directory(self, path): """Ensure that the given path is valid. :param str path: A valid directory path. :raises: :py:class:`argparse.ArgumentTypeError` :returns: An absolute directory path. """
abspath = os.path.abspath(path) if not os.path.isdir(abspath): raise argparse.ArgumentTypeError('Not a valid directory: {}'.format(abspath)) return abspath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(self): """Parse package trees and report on any discrepancies."""
args = self.args parsed_pytree, pypackages = self.parse_py_tree(pytree=args.pytree) parsed_doctree = self.parse_doc_tree(doctree=args.doctree, pypackages=pypackages) return self.compare_trees(parsed_pytree=parsed_pytree, parsed_doctree=parsed_doctree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where_unique(cls, ip, object_id, location): """ Get db model by username """
return cls.query.filter_by( ip=ip, object_id=object_id, location=location).first()
<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_where_unique(cls, ip, object_id, location): """ delete by ip and object id """
result = cls.where_unique(ip, object_id, location) if result is None: return None result.delete() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_req(self, method, url, body=None, headers=None, status=None): """Used internally to send a request to the API, left public so it can be used to talk to the API more directly. """
if body is None: body = '' else: body = json.dumps(body) res = self.backend.dispatch_request(method=method, url=url, body=body, headers=self.get_headers(headers), auth=self.auth) if not isinstance(res, MapiResponse): res = MapiResponse(*res) if status is None: if res.status // 100 != 2: raise MapiError(*res) elif res.status != status: raise MapiError(*res) 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 _depaginate_all(self, url): """GETs the url provided and traverses the 'next' url that's returned while storing the data in a list. Returns a single list of all items. """
items = [] for x in self._depagination_generator(url): items += x return items
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_user(self, user_id, roles=None, netmask=None, secret=None, pubkey=None): u"""Create user for the Merchant given in the X-Mcash-Merchant header. Arguments: user_id: Identifier for the user roles: Role netmask: Limit user connections by netmask, for example 192.168.1.0/24 secret: Secret used when authenticating with mCASH pubkey: RSA key used for authenticating by signing """
arguments = {'id': user_id, 'roles': roles, 'netmask': netmask, 'secret': secret, 'pubkey': pubkey} return self.do_req('POST', self.merchant_api_base_url + '/user/', arguments).json()
<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_user(self, user_id, roles=None, netmask=None, secret=None, pubkey=None): """Update user. Returns the raw response object. Arguments: user_id: User id of user to update roles: Role netmask: Limit user connections by netmask, for example 192.168.1.0/24 secret: Secret used when authenticating with mCASH pubkey: RSA key used for authenticating by signing """
arguments = {'roles': roles, 'netmask': netmask, 'secret': secret, 'pubkey': pubkey} return self.do_req('PUT', self.merchant_api_base_url + '/user/' + user_id + '/', arguments)
<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_pos(self, name, pos_type, pos_id, location=None): """Create POS resource Arguments: name: Human-readable name of the POS, used for displaying payment request origin to end user pos_type: POS type location: Merchant location pos_id: The ID of the POS that is to be created. Has to be unique for the merchant """
arguments = {'name': name, 'type': pos_type, 'id': pos_id, 'location': location} return self.do_req('POST', self.merchant_api_base_url + '/pos/', arguments).json()
<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_pos(self, pos_id, name, pos_type, location=None): """Update POS resource. Returns the raw response object. Arguments: pos_id: POS id as chosen on registration name: Human-readable name of the POS, used for displaying payment request origin to end user pos_type: POS type location: Merchant location """
arguments = {'name': name, 'type': pos_type, 'location': location} return self.do_req('PUT', self.merchant_api_base_url + '/pos/' + pos_id + '/', arguments)
<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_payment_request(self, customer, currency, amount, allow_credit, pos_id, pos_tid, action, ledger=None, display_message_uri=None, callback_uri=None, additional_amount=None, additional_edit=None, text=None, expires_in=None, required_scope=None, required_scope_text=None, links=None, line_items=None): """Post payment request. The call is idempotent; that is, if one posts the same pos_id and pos_tid twice, only one payment request is created. Arguments: ledger: Log entries will be added to the open report on the specified ledger display_message_uri: Messages that can be used to inform the POS operator about the progress of the payment request will be POSTed to this URI if provided callback_uri: If provided, mCASH will POST to this URI when the status of the payment request changes, using the message mechanism described in the introduction. The data in the "object" part of the message is the same as what can be retrieved by calling GET on the "/payment_request/<tid>/outcome/" resource URI. customer: Customer identifiers include msisdn, scan token or access token currency: 3 chars https://en.wikipedia.org/wiki/ISO_4217 amount: The base amount of the payment additional_amount: Typically cash withdrawal or gratuity additional_edit: Whether user is allowed to additional amount for gratuity or similar allow_credit: Whether to allow credit payment for this payment request. Credit incurs interchange pos_id: The POS this payment request originates from, used for informing user about origin pos_tid: Local transaction id for POS. This must be unique for the POS text: Text that is shown to user when asked to pay. This can contain linebreaks and the text has to fit on smartphones screens. action: Action to perform, the main difference is what it looks like in App UI. expires_in: Expiration in seconds from when server received request required_scope: Scopes required to fulfill payment required_scope_text: Text that is shown to user when asked for permission. links: A list of links to be shown in app in various states [{"uri": "http://example.com/uri1", "caption": "This is always shown", "show_on": ["pending", "fail", "ok"]}] line_items: A list of product lines in the payment request. Each item should contain product_id, vat, description (optional), vat_rate, total, item_cost, quantity and optionally tags, which is a list of tag dicts containing tag_id and label. The sum of all line item totals must be equal to the amount argument. [{"product_id": "product-1", vat: "0.50", description: "An optional description", vat_rate: "0.25", total: "5.00", item_cost: "2.50", quantity: "2", "tags": [ {"tag_id": "product-info-5", "label": "Some product info"} ]}] """
arguments = {'customer': customer, 'currency': currency, 'amount': amount, 'allow_credit': allow_credit, 'pos_id': pos_id, 'pos_tid': pos_tid, 'action': action, 'ledger': ledger, 'display_message_uri': display_message_uri, 'callback_uri': callback_uri, 'additional_amount': additional_amount, 'additional_edit': additional_edit, 'text': text, 'expires_in': expires_in} if required_scope: arguments['required_scope'] = required_scope arguments['required_scope_text'] = required_scope_text if links: arguments['links'] = links if line_items: arguments['line_items'] = line_items return self.do_req('POST', self.merchant_api_base_url + '/payment_request/', arguments).json()
<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_payment_request(self, tid, currency=None, amount=None, action=None, ledger=None, callback_uri=None, display_message_uri=None, capture_id=None, additional_amount=None, text=None, refund_id=None, required_scope=None, required_scope_text=None, line_items=None): """Update payment request, reauthorize, capture, release or abort It is possible to update ledger and the callback URIs for a payment request. Changes are always appended to the open report of a ledger, and notifications are sent to the callback registered at the time of notification. Capturing an authorized payment or reauthorizing is done with the action field. The call is idempotent; that is, if one posts the same amount, additional_amount and capture_id twice with action CAPTURE, only one capture is performed. Similarly, if one posts twice with action CAPTURE without any amount stated, to capture the full amount, only one full capture is performed. Arguments: ledger: Log entries will be added to the open report on the specified ledger display_message_uri: Messages that can be used to inform the POS operator about the progress of the payment request will be POSTed to this URI if provided callback_uri: If provided, mCASH will POST to this URI when the status of the payment request changes, using the message mechanism described in the introduction. The data in the "object" part of the message is the same as what can be retrieved by calling GET on the "/payment_request/<tid>/outcome/" resource URI. currency: 3 chars https://en.wikipedia.org/wiki/ISO_4217 amount: The base amount of the payment additional_amount: Typically cash withdrawal or gratuity capture_id: Local id for capture. Must be set if amount is set, otherwise capture_id must be unset. tid: Transaction id assigned by mCASH refund_id: Refund id needed when doing partial refund text: For example reason for refund. action: Action to perform. required_scope: Scopes required to fulfill payment line_items: An updated line_items. Will fail if line_items already set in the payment request or if the sum of the totals is different from the original amount. required_scope_text: Text that is shown to user when asked for permission. """
arguments = {'ledger': ledger, 'display_message_uri': display_message_uri, 'callback_uri': callback_uri, 'currency': currency, 'amount': amount, 'additional_amount': additional_amount, 'capture_id': capture_id, 'action': action, 'text': text, 'refund_id': refund_id} if required_scope: arguments['required_scope'] = required_scope arguments['required_scope_text'] = required_scope_text if line_items: arguments['line_items'] = line_items arguments = {k: v for k, v in arguments.items() if v is not None} return self.do_req('PUT', self.merchant_api_base_url + '/payment_request/' + tid + '/', arguments)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_chat_message(self, merchant_id, channel_id, message): """post a chat message Arguments: channel_id: Scan token """
return self.do_req('POST', self.base_url + '/chat/v1/merchant/%s/channel/%s/message/' % (merchant_id, channel_id), message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_shortlink(self, callback_uri=None, description=None, serial_number=None): """Register new shortlink Arguments: callback_uri: URI called by mCASH when user scans shortlink description: Shortlink description displayed in confirmation dialogs serial_number: Serial number on printed QR codes. This field is only used when registering printed stickers issued by mCASH """
arguments = {'callback_uri': callback_uri, 'description': description, 'serial_number': serial_number} return self.do_req('POST', self.merchant_api_base_url + '/shortlink/', arguments).json()
<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_shortlink(self, shortlink_id, callback_uri=None, description=None): """Update existing shortlink registration Arguments: shortlink_id: Shortlink id assigned by mCASH """
arguments = {'callback_uri': callback_uri, 'description': description} return self.do_req('PUT', self.merchant_api_base_url + '/shortlink/' + shortlink_id + '/', arguments)
<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_shortlink(self, shortlink_id_or_url): """Retrieve registered shortlink info Arguments: shortlink_id_or_url: Shortlink id or url, assigned by mCASH """
if "://" not in shortlink_id_or_url: shortlink_id_or_url = self.merchant_api_base_url + '/shortlink/' + shortlink_id_or_url + '/' return self.do_req('GET', shortlink_id_or_url).json()
<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_ledger(self, currency, description=None): """Create a ledger """
arguments = {'currency': currency, 'description': description} return self.do_req('POST', self.merchant_api_base_url + '/ledger/', arguments).json()
<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_ledger(self, ledger_id, description=None): """Update ledger info Arguments: ledger_id: Ledger id assigned by mCASH description: Description of the Ledger and it's usage """
arguments = {'description': description} return self.do_req('PUT', self.merchant_api_base_url + '/ledger/' + ledger_id + '/', arguments)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_report(self, ledger_id, report_id, callback_uri=None): u"""Close Report When you PUT to a report, it will start the process of closing it. When the closing process is complete (i.e. when report.status == 'closed') mCASH does a POST call to callback_uri, if provided. This call will contain JSON data similar to when GETing the Report. Closing a report automatically open a new one. The contents of a GET /merchant/v1/ledger/<ledger_id>/report/<report_id>/ is included in callback if callback is a secure URI, otherwise the link itself is sent in callback. Arguments: ledger_id: Id for ledger for report report_id: Report id assigned by mCASH callback_uri: Callback URI to be called when Report has finished closing. """
arguments = {'callback_uri': callback_uri} return self.do_req('PUT', self.merchant_api_base_url + '/ledger/' + ledger_id + '/report/' + report_id + '/', arguments)
<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_report(self, ledger_id, report_id): """Get report info Arguments: ledger_id: Id for ledger for report report_id: Report id assigned by mCASH """
return self.do_req('GET', self.merchant_api_base_url + '/ledger/' + ledger_id + '/report/' + report_id + '/').json()
<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_permission_request(self, customer, pos_id, pos_tid, scope, ledger=None, text=None, callback_uri=None, expires_in=None): """Create permission request The call is idempotent; that is, if one posts the same pos_id and pos_tid twice, only one Permission request is created. """
arguments = {'customer': customer, 'pos_id': pos_id, 'pos_tid': pos_tid, 'scope': scope, 'ledger': ledger, 'text': text, 'callback_uri': callback_uri, 'expires_in': expires_in} return self.do_req('POST', self.merchant_api_base_url + '/permission_request/', arguments).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_receipt(self, url, data): """Upload a receipt to the give url :param url: :param data: :return: """
return self.upload_attachment(url=url, data=data, mime_type='application/vnd.mcash.receipt.v1+json')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_twitter_request_handler(twitter_api_func, call_rate_limit, call_counter, time_window_start, max_retries, wait_period, *args, **kw): """ This is a safe function handler for any twitter request. Inputs: - twitter_api_func: The twython function object to be safely called. - call_rate_limit: THe call rate limit for this specific Twitter API function. - call_counter: A counter that keeps track of the number of function calls in the current 15-minute window. - time_window_start: The timestamp of the current 15-minute window. - max_retries: Number of call retries allowed before abandoning the effort. - wait_period: For certain Twitter errors (i.e. server overload), we wait and call again. - *args, **kw: The parameters of the twython function to be called. Outputs: - twitter_api_function_result: The results of the Twitter function. - call_counter: A counter that keeps track of the number of function calls in the current 15-minute window. - time_window_start: The timestamp of the current 15-minute window. Raises: - twython.TwythonError - urllib.error.URLError - http.client.BadStatusLine """
error_count = 0 while True: try: # If we have reached the call rate limit for this function: if call_counter >= call_rate_limit: # Reset counter. call_counter = 0 # Sleep for the appropriate time. elapsed_time = time.perf_counter() - time_window_start sleep_time = 15*60 - elapsed_time if sleep_time < 0.1: sleep_time = 0.1 time.sleep(sleep_time) # Initialize new 15-minute time window. time_window_start = time.perf_counter() else: call_counter += 1 twitter_api_function_result = twitter_api_func(*args, **kw) return twitter_api_function_result, call_counter, time_window_start except twython.TwythonError as e: # If it is a Twitter error, handle it. error_count, call_counter, time_window_start, wait_period = handle_twitter_http_error(e, error_count, call_counter, time_window_start, wait_period) if error_count > max_retries: print("Max error count reached. Abandoning effort.") raise e except URLError as e: error_count += 1 if error_count > max_retries: print("Max error count reached. Abandoning effort.") raise e except BadStatusLine as e: error_count += 1 if error_count > max_retries: print("Max error count reached. Abandoning effort.") raise e
<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_twitter_http_error(e, error_count, call_counter, time_window_start, wait_period): """ This function handles the twitter request in case of an HTTP error. Inputs: - e: A twython.TwythonError instance to be handled. - error_count: Number of failed retries of the call until now. - call_counter: A counter that keeps track of the number of function calls in the current 15-minute window. - time_window_start: The timestamp of the current 15-minute window. - wait_period: For certain Twitter errors (i.e. server overload), we wait and call again. Outputs: - call_counter: A counter that keeps track of the number of function calls in the current 15-minute window. - time_window_start: The timestamp of the current 15-minute window. - wait_period: For certain Twitter errors (i.e. server overload), we wait and call again. Raises: - twython.TwythonError """
if e.error_code == 401: # Encountered 401 Error (Not Authorized) raise e elif e.error_code == 404: # Encountered 404 Error (Not Found) raise e elif e.error_code == 429: # Encountered 429 Error (Rate Limit Exceeded) # Sleep for 15 minutes error_count += 0.5 call_counter = 0 wait_period = 2 time.sleep(60*15 + 5) time_window_start = time.perf_counter() return error_count, call_counter, time_window_start, wait_period elif e.error_code in (500, 502, 503, 504): error_count += 1 time.sleep(wait_period) wait_period *= 1.5 return error_count, call_counter, time_window_start, wait_period else: raise e
<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_bundle(bundle, fixed_version=None): """ Does all of the processing required to create a bundle and write it to disk, returning its hash version """
tmp_output_file_name = '%s.%s.%s' % (os.path.join(bundle.bundle_file_root, bundle.bundle_filename), 'temp', bundle.bundle_type) iter_input = iter_bundle_files(bundle) output_pipeline = processor_pipeline(bundle.processors, iter_input) m = md5() with open(tmp_output_file_name, 'wb') as output_file: for chunk in output_pipeline: m.update(chunk) output_file.write(chunk) hash_version = fixed_version or m.hexdigest() output_file_name = bundle.get_path(hash_version) os.rename(tmp_output_file_name, output_file_name) return hash_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_to_text(html_string): """ returns a plain text string when given a html string text handles a, p, h1 to h6 and br, inserts newline chars to create space in the string @todo handle images """
# create a valid html document from string # beware that it inserts <hmtl> <body> and <p> tags # where needed html_tree = html.document_fromstring(html_string) # handle header tags for h in html_tree.cssselect("h1, h2, h3, h4, h5, h6"): # add two newlines after a header tag h.text = h.text + '\n\n' # handle links # find all a tags starting from the root of the document // # and replace the link with (link) for a in html_tree.xpath("//a"): href = a.attrib['href'] a.text = a.text + " (" + href + ")" # handle paragraphs for p in html_tree.xpath("//p"): # keep the tail if there is one # or add two newlines after the text if there is no tail p.tail = p.tail if p.tail else "\n\n" # handle breaks for br in html_tree.xpath("//br"): # add a newline and then the tail (remaining text after the <br/> tag) # or add a newline only if there is no tail # http://stackoverflow.com/questions/18660382/how-can-i-preserve-br-as-newlines-with-lxml-html-text-content-or-equivalent?rq=1 br.tail = "\n" + br.tail if br.tail else "\n" return html_tree.text_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 random_string(**kwargs): """ By default generates a random string of 10 chars composed of digits and ascii lowercase letters. String length and pool can be override by using kwargs. Pool must be a list of strings """
n = kwargs.get('length', 10) pool = kwargs.get('pool') or string.digits + string.ascii_lowercase return ''.join(random.SystemRandom().choice(pool) for _ in range(n))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_parallel_process_with_profiling(self, start_path, stop_path, queue, filename): """ wrapper for usage of profiling """
runctx('Engine._run_parallel_process(self, start_path, stop_path, queue)', globals(), locals(), filename)
<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_parallel_process(self, start_path, stop_path, queue): """ The function calls _run_process and puts results produced by consumer at observations of top most consumer in to the queue """
process_num = int(current_process().name.split('-', 2)[1]) self._run_process(start_path, stop_path, process_num) queue.put(self.consumer.put())
<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_process(self, start_path, stop_path, process_num=0): """ The function calls _run_path for given set of paths """
# pre processing self.producer.initialize_worker(process_num) self.consumer.initialize_worker(process_num) # processing for path in range(start_path, stop_path): self._run_path(path) # post processing self.consumer.finalize_worker(process_num)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_path(self, path_num): """ standalone function implementing a single loop of Monte Carlo It returns list produced by consumer at observation dates :param int path_num: path number """
# pre processing self.producer.initialize_path(path_num) self.consumer.initialize_path(path_num) # processing for new_date in self.grid: state = self.producer.evolve(new_date) self.consumer.consume(state) # post processing self.consumer.finalize_path(path_num)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_worker(self, process_num=None): """ reinitialize consumer for process in multiprocesing """
self.initialize(self.grid, self.num_of_paths, self.seed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_path(self, path_num=None): """ initialize consumer for next path """
self.state = copy(self.initial_state) return self.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 consume(self, state): """ consume new producer state """
self.state.append(self.func(state)) return self.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 get(self, queue_get): """ to get states from multiprocessing.queue """
if isinstance(queue_get, (tuple, list)): self.result.extend(queue_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 walk_revctrl(dirname='', ff=''): """Return files found by the file-finder 'ff'. """
file_finder = None items = [] if not ff: distutils.log.error('No file-finder passed to walk_revctrl') sys.exit(1) for ep in pkg_resources.iter_entry_points('setuptools.file_finders'): if ff == ep.name: distutils.log.info('using %s file-finder', ep.name) file_finder = ep.load() finder_items = [] with pythonpath_off(): for item in file_finder(dirname): if not basename(item).startswith(('.svn', '.hg', '.git')): finder_items.append(item) distutils.log.info('%d files found', len(finder_items)) items.extend(finder_items) if file_finder is None: distutils.log.error('Failed to load %s file-finder; setuptools-%s extension missing?', ff, 'subversion' if ff == 'svn' else ff) sys.exit(1) # Returning a non-empty list prevents egg_info from reading the # existing SOURCES.txt return items or ['']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup_pycache(): """Remove .pyc files we leave around because of import. """
try: for file in glob.glob('setup.py[co]'): os.remove(file) if isdir('__pycache__'): for file in glob.glob(join('__pycache__', 'setup.*.py[co]')): os.remove(file) if not glob.glob(join('__pycache__', '*')): os.rmdir('__pycache__') except (IOError, OSError): pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(args, ff=''): """Run setup.py with monkey patches applied. """
import setuptools.command.egg_info if ff == 'none': setuptools.command.egg_info.walk_revctrl = no_walk_revctrl else: setuptools.command.egg_info.walk_revctrl = partial(walk_revctrl, ff=ff) sys.argv = ['setup.py'] + args import setup cleanup_pycache()
<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_sorted_iterator(self, iterator): """ Get the iterator over the sorted items. This function decides whether the items can be sorted in memory or on disk. :return: """
lines = list(next(iterator)) if len(lines) < self.max_lines: return iter(sorted(lines, key=self.key)) import tempfile tmp_dir = tempfile.mkdtemp() fnames = self._split(chain([lines], iterator), tmp_dir) return SortedIteratorMerger([unpickle_iter(open(fname, 'rb')) for fname in fnames], 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 _split(self, iterator, tmp_dir): """ Splits the file into several chunks. If the original file is too big to fit in the allocated space, the sorting will be split into several chunks, then merged. :param tmp_dir: Where to put the intermediate sorted results. :param orig_lines: The lines read before running out of space. :return: The names of the intermediate files. """
fnames = [] for i, lines in enumerate(iterator): lines = list(lines) out_fname = os.path.join(tmp_dir, self.TMP_FNAME.format(i + 1)) self._write(lines, out_fname) fnames.append(out_fname) if len(lines) < self.max_lines: break return fnames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write(self, lines, fname): """ Writes a intermediate temporary sorted file :param lines: The lines to write. :param fname: The name of the temporary file. :return: """
with open(fname, 'wb') as out_fhndl: for line in sorted(lines, key=self.key): pickle.dump(line, out_fhndl)
<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_iso_time(date_part, time_part): r"""Combign date and time into an iso datetime."""
str_date = datetime.datetime.strptime( date_part, '%m/%d/%Y').strftime('%Y-%m-%d') str_time = datetime.datetime.strptime( time_part, '%I:%M %p').strftime('%H:%M:%S') return str_date + "T" + str_time + "-7:00"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_list(host_name, client_name, client_pass): """ Pulls the list of users in a client. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. Output: - user_id_list: A python list of user ids. """
# Construct request. request = construct_request(model_type="pers", client_name=client_name, client_pass=client_pass, command="getusrs", values="whr=*") # Make request. request_result = send_request(host_name, request) # Extract a python list from xml object. user_id_list = list() append_user_id = user_id_list.append if request_result is not None: user_list_xml = request_result.text tree = etree.parse(StringIO(user_list_xml)) root = tree.getroot() xml_rows = root.findall("./result/row/usr") for xml_row in xml_rows: append_user_id(xml_row.text) return user_id_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_features(host_name, client_name, client_pass, feature_names): """ Add a number of numerical features in the client. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. - feature_names: A python list of feature names. """
init_feats = ("&".join(["%s=0"]*len(feature_names))) % tuple(feature_names) features_req = construct_request("pers", client_name, client_pass, "addftr", init_feats) send_request(host_name, features_req)
<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_features(host_name, client_name, client_pass, feature_names=None): """ Remove a number of numerical features in the client. If a list is not provided, remove all features. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. - feature_names: A python list of feature names. """
# Get all features. if feature_names is None: feature_names = get_feature_names(host_name, client_name, client_pass) # Remove all features. feature_to_be_removed = ("&".join(["ftr=%s"]*len(feature_names))) % tuple(feature_names) features_req = construct_request("pers", client_name, client_pass, 'remftr', feature_to_be_removed) send_request(host_name, features_req)
<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_feature_names(host_name, client_name, client_pass): """ Get the names of all features in a PServer client. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. Output: - feature_names: A python list of feature names. """
# Construct request. request = construct_request(model_type="pers", client_name=client_name, client_pass=client_pass, command="getftrdef", values="ftr=*") # Send request. request_result = send_request(host_name, request) # Extract a python list from xml object. feature_names = list() append_feature_name = feature_names.append if request_result is not None: feature_names_xml = request_result.text tree = etree.parse(StringIO(feature_names_xml)) root = tree.getroot() xml_rows = root.findall("row/ftr") for xml_row in xml_rows: append_feature_name(xml_row.text) return feature_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_request(model_type, client_name, client_pass, command, values): """ Construct the request url. Inputs: - model_type: PServer usage mode type. - client_name: The PServer client name. - client_pass: The PServer client's password. - command: A PServer command. - values: PServer command arguments. Output: - base_request: The base request string. """
base_request = ("{model_type}?" "clnt={client_name}|{client_pass}&" "com={command}&{values}".format(model_type=model_type, client_name=client_name, client_pass=client_pass, command=command, values=values)) return base_request
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(host_name, request): """ Sends a PServer url request. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - request: The url request. """
request = "%s%s" % (host_name, request) # print(request) try: result = requests.get(request) if result.status_code == 200: return result else: # print(result.status_code) raise Exception except Exception as e: # print(e) raise e
<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_feature_value(host_name, client_name, client_pass, user_twitter_id, feature_name, feature_score): """ Updates a single topic score, for a single user. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. - user_twitter_id: A Twitter user identifier. - feature_name: A specific PServer feature name. - feature_score: The corresponding score. """
username = str(user_twitter_id) feature_value = "{0:.2f}".format(feature_score) joined_ftr_value = "ftr_" + feature_name + "=" + str(feature_value) values = "usr=%s&%s" % (username, joined_ftr_value) # Construct request. request = construct_request(model_type="pers", client_name=client_name, client_pass=client_pass, command="setusr", values=values) # Send request. send_request(host_name, request)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app): """ Initialize the application once the configuration has been loaded there. """
self.app = app self.log = app.logger.getChild('compass') self.log.debug("Initializing compass integration") self.compass_path = self.app.config.get('COMPASS_PATH', 'compass') self.config_files = self.app.config.get('COMPASS_CONFIGS', None) self.requestcheck_debug_only = self.app.config.get( 'COMPASS_REQUESTCHECK_DEBUG_ONLY', True) self.skip_mtime_check = self.app.config.get( 'COMPASS_SKIP_MTIME_CHECK', False) self.debug_only = self.app.config.get( 'COMPASS_DEBUG_ONLY', False) self.disabled = self.app.config.get('COMPASS_DISABLED', False) if not self.debug_only: self.compile() if (not self.debug_only) \ and (not self.requestcheck_debug_only or self.app.debug): self.app.after_request(self.after_request)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self): """ Main entry point that compiles all the specified or found compass projects. """
if self.disabled: return self._check_configs() for _, cfg in self.configs.iteritems(): cfg.parse() if cfg.changes_found() or self.skip_mtime_check: self.log.debug("Changes found for " + cfg.path \ + " or checks disabled. Compiling...") cfg.compile(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 after_request(self, response): """ after_request handler for compiling the compass projects with each request. """
if response is not None and request is not None: # When used as response processor, only run if we are requesting # anything but a static resource. if request.endpoint in [None, "static"]: return response self.compile() 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 _check_configs(self): """ Reloads the configuration files. """
configs = set(self._find_configs()) known_configs = set(self.configs.keys()) new_configs = configs - known_configs for cfg in (known_configs - configs): self.log.debug("Compass configuration has been removed: " + cfg) del self.configs[cfg] for cfg in new_configs: self.log.debug("Found new compass configuration: " + cfg) self.configs[cfg] = CompassConfig(cfg)
<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_configs(self): """ Scans the project directory for config files or returns the explicitly specified list of files. """
if self.config_files is not None: return self.config_files # Walk the whole project tree and look for "config.rb" files result = [] for path, _, files in os.walk(self.app.root_path): if "config.rb" in files: result.append(os.path.join(path, "config.rb")) 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 parse(self, replace=False): """ Parse the given compass config file """
if self.last_parsed is not None \ and self.last_parsed > os.path.getmtime(self.path) \ and not replace: return self.last_parsed = time.time() with open(self.path, 'r') as file_: for line in file_: match = CONFIG_LINE_RE.match(line.rstrip()) if match: if match.group(1) == 'sass_dir': self.src = os.path.join( self.base_dir, match.group(2)[1:-1]) elif match.group(1) == 'css_dir': self.dest = os.path.join( self.base_dir, match.group(2)[1:-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 changes_found(self): """ Returns True if the target folder is older than the source folder. """
if self.dest is None: warnings.warn("dest directory not found!") if self.src is None: warnings.warn("src directory not found!") if self.src is None or self.dest is None: return False dest_mtime = -1 src_mtime = os.path.getmtime(self.src) if os.path.exists(self.dest): dest_mtime = os.path.getmtime(self.dest) if src_mtime >= dest_mtime: return True # changes found for folder, _, files in os.walk(self.src): for filename in fnmatch.filter(files, '*.scss'): src_path = os.path.join(folder, filename) if os.path.getmtime(src_path) >= dest_mtime: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self, compass): """ Calls the compass script specified in the compass extension with the paths provided by the config.rb. """
try: output = subprocess.check_output( [compass.compass_path, 'compile', '-q'], cwd=self.base_dir) os.utime(self.dest, None) compass.log.debug(output) except OSError, e: if e.errno == errno.ENOENT: compass.log.error("Compass could not be found in the PATH " + "and/or in the COMPASS_PATH setting! " + "Disabling compilation.") compass.disabled = True else: raise e
<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_otiose(lst): """lift deeply nested expressions out of redundant parentheses"""
listtype = type([]) while type(lst) == listtype and len(lst) == 1: lst = lst[0] return lst
<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_work_commits(repo_addr, ascending = True, tz = 'US/Eastern', correct_times = True): """Retrives work commits from repo"""
repo = git.Repo(repo_addr) commits = list(repo.iter_commits()) logs = [(c.authored_datetime, c.message.strip('\n'), str(c)) for c in repo.iter_commits()] work = pd.DataFrame.from_records(logs, columns = ['time', 'message', 'hash']) work.time = pd.DatetimeIndex([pd.Timestamp(i).tz_convert(tz) for i in work.time]) work.set_index('time', inplace = True) with warnings.catch_warnings(): warnings.simplefilter("ignore") work = work.sort_index(ascending = ascending) if correct_times: work = adjust_time(work) return work, repo
<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_topic_set(file_path): """ Opens one of the topic set resource files and returns a set of topics. - Input: - file_path: The path pointing to the topic set resource file. - Output: - topic_set: A python set of strings. """
topic_set = set() file_row_gen = get_file_row_generator(file_path, ",") # The separator here is irrelevant. for file_row in file_row_gen: topic_set.add(file_row[0]) return topic_set
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_reveal_set(): """ Returns a set of all the topics that are interesting for REVEAL use-cases. """
file_path = get_package_path() + "/twitter/res/topics/story_set.txt" story_topics = get_topic_set(file_path) file_path = get_package_path() + "/twitter/res/topics/theme_set.txt" theme_topics = get_topic_set(file_path) file_path = get_package_path() + "/twitter/res/topics/attribute_set.txt" attribute_topics = get_topic_set(file_path) file_path = get_package_path() + "/twitter/res/topics/stance_set.txt" stance_topics = get_topic_set(file_path) file_path = get_package_path() + "/twitter/res/topics/geographical_set.txt" geographical_topics = get_topic_set(file_path) topics = story_topics | theme_topics | attribute_topics | stance_topics | geographical_topics return topics
<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_topic_keyword_dictionary(): """ Opens the topic-keyword map resource file and returns the corresponding python dictionary. - Input: - file_path: The path pointing to the topic-keyword map resource file. - Output: - topic_set: A topic to keyword python dictionary. """
topic_keyword_dictionary = dict() file_row_gen = get_file_row_generator(get_package_path() + "/twitter/res/topics/topic_keyword_mapping" + ".txt", ",", "utf-8") for file_row in file_row_gen: topic_keyword_dictionary[file_row[0]] = set([keyword for keyword in file_row[1:]]) return topic_keyword_dictionary
<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_input(self, name, ds): """ Retrieves the content of an input given a DataSource. The input acts like a filter over the outputs of the DataSource. Args: name (str): The name of the input. ds (openflow.DataSource): The DataSource that will feed the data. Returns: pandas.DataFrame: The content of the input. """
columns = self.inputs.get(name) df = ds.get_dataframe() # set defaults for column in columns: if column not in df.columns: df[column] = self.defaults.get(column) return df[columns]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def domain_relationship(self): """ Returns a domain relationship equivalent with this resource relationship. """
if self.__domain_relationship is None: ent = self.relator.get_entity() self.__domain_relationship = \ self.descriptor.make_relationship(ent) return self.__domain_relationship
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit(self): """Fit MCMC AgeDepthModel"""
self._mcmcfit = self.mcmcsetup.run() self._mcmcfit.burnin(self.burnin) dmin = min(self._mcmcfit.depth_segments) dmax = max(self._mcmcfit.depth_segments) self._thick = (dmax - dmin) / len(self.mcmcfit.depth_segments) self._depth = np.arange(dmin, dmax + 0.001) self._age_ensemble = np.array([self.agedepth(d=dx) for dx in self.depth])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def date(self, proxy, how='median', n=500): """Date a proxy record Parameters proxy : ProxyRecord how : str How to perform the dating. 'median' returns the average of the MCMC ensemble. 'ensemble' returns a 'n' randomly selected members of the MCMC ensemble. Default is 'median'. n : int If 'how' is 'ensemble', the function will randomly select 'n' MCMC ensemble members, with replacement. Returns ------- DatedProxyRecord """
assert how in ['median', 'ensemble'] ens_members = self.mcmcfit.n_members() if how == 'ensemble': select_idx = np.random.choice(range(ens_members), size=n, replace=True) out = [] for d in proxy.data.depth.values: age = self.agedepth(d) if how == 'median': age = np.median(age) elif how == 'ensemble': age = age[select_idx] out.append(age) return DatedProxyRecord(proxy.data.copy(), 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 plot(self, agebins=50, p=(2.5, 97.5), ax=None): """Age-depth plot"""
if ax is None: ax = plt.gca() ax.hist2d(np.repeat(self.depth, self.age_ensemble.shape[1]), self.age_ensemble.flatten(), (len(self.depth), agebins), cmin=1) ax.step(self.depth, self.age_median(), where='mid', color='red') ax.step(self.depth, self.age_percentile(p[0]), where='mid', color='red', linestyle=':') ax.step(self.depth, self.age_percentile(p[1]), where='mid', color='red', linestyle=':') ax.set_ylabel('Age (cal yr BP)') ax.set_xlabel('Depth (cm)') ax.grid(True) return ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def agedepth(self, d): """Get calendar age for a depth Parameters d : float Sediment depth (in cm). Returns ------- Numeric giving true age at given depth. """
# TODO(brews): Function cannot handle hiatus # See lines 77 - 100 of hist2.cpp x = self.mcmcfit.sediment_rate theta0 = self.mcmcfit.headage # Age abscissa (in yrs). If array, dimension should be iterations or realizations of the sediment deltac = self.thick c0 = min(self.depth) # Uniform depth segment abscissa (in cm). assert d > c0 or np.isclose(c0, d, atol = 1e-4) out = theta0.astype(float) i = int(np.floor((d - c0) / deltac)) for j in range(i): out += x[j] * deltac ci = c0 + i * deltac assert ci < d or np.isclose(ci, d, atol = 1e-4) try: next_x = x[i] except IndexError: # Extrapolating next_x = x[i - 1] out += next_x * (d - ci) 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 plot_prior_dates(self, dwidth=30, ax=None): """Plot prior chronology dates in age-depth plot"""
if ax is None: ax = plt.gca() depth, probs = self.prior_dates() pat = [] for i, d in enumerate(depth): p = probs[i] z = np.array([p[:, 0], dwidth * p[:, 1] / np.sum(p[:, 1])]) # Normalize z = z[:, z[0].argsort(kind='mergesort')] # np.interp requires `xp` arg to be sorted zy = np.linspace(np.min(z[0]), np.max(z[0]), num=200) zp = np.interp(x=zy, xp=z[0], fp=z[1]) pol = np.vstack([np.concatenate([d + zp, d - zp[::-1]]), np.concatenate([zy, zy[::-1]])]) pat.append(Polygon(pol.T)) p = PatchCollection(pat) p.set_label('Prior dates') ax.add_collection(p) ax.autoscale_view() ax.set_ylabel('Age (cal yr BP)') ax.set_xlabel('Depth (cm)') ax.grid(True) return ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_sediment_rate(self, ax=None): """Plot sediment accumulation rate prior and posterior distributions"""
if ax is None: ax = plt.gca() y_prior, x_prior = self.prior_sediment_rate() ax.plot(x_prior, y_prior, label='Prior') y_posterior = self.mcmcfit.sediment_rate density = scipy.stats.gaussian_kde(y_posterior.flat) density.covariance_factor = lambda: 0.25 density._compute_covariance() ax.plot(x_prior, density(x_prior), label='Posterior') acc_shape = self.mcmcsetup.mcmc_kws['acc_shape'] acc_mean = self.mcmcsetup.mcmc_kws['acc_mean'] annotstr_template = 'acc_shape: {0}\nacc_mean: {1}' annotstr = annotstr_template.format(acc_shape, acc_mean) ax.annotate(annotstr, xy=(0.9, 0.9), xycoords='axes fraction', horizontalalignment='right', verticalalignment='top') ax.set_ylabel('Density') ax.set_xlabel('Acc. rate (yr/cm)') ax.grid(True) return ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_sediment_memory(self, ax=None): """Plot sediment memory prior and posterior distributions"""
if ax is None: ax = plt.gca() y_prior, x_prior = self.prior_sediment_memory() ax.plot(x_prior, y_prior, label='Prior') y_posterior = self.mcmcfit.sediment_memory density = scipy.stats.gaussian_kde(y_posterior ** (1/self.thick)) density.covariance_factor = lambda: 0.25 density._compute_covariance() ax.plot(x_prior, density(x_prior), label='Posterior') mem_mean = self.mcmcsetup.mcmc_kws['mem_mean'] mem_strength = self.mcmcsetup.mcmc_kws['mem_strength'] annotstr_template = 'mem_strength: {0}\nmem_mean: {1}\nthick: {2} cm' annotstr = annotstr_template.format(mem_strength, mem_mean, self.thick) ax.annotate(annotstr, xy=(0.9, 0.9), xycoords='axes fraction', horizontalalignment='right', verticalalignment='top') ax.set_ylabel('Density') ax.set_xlabel('Memory (ratio)') ax.grid(True) return ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qpinfo(): """Print information of a quantitative phase imaging dataset"""
parser = qpinfo_parser() args = parser.parse_args() path = pathlib.Path(args.path).resolve() try: ds = load_data(path) except UnknownFileFormatError: print("Unknown file format: {}".format(path)) return print("{} ({})".format(ds.__class__.__doc__, ds.__class__.__name__)) print("- number of images: {}".format(len(ds))) for key in ds.meta_data: print("- {}: {}".format(key, ds.meta_data[key]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node_meta_type(manager, handle_id): """ Returns the meta type of the supplied node as a string. :param manager: Neo4jDBSessionManager :param handle_id: Unique id :return: string """
node = get_node(manager=manager, handle_id=handle_id, legacy=False) for label in node.labels: if label in META_TYPES: return label raise exceptions.NoMetaLabelFound(handle_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 create_relationship(manager, handle_id, other_handle_id, rel_type): """ Makes a relationship from node to other_node depending on which meta_type the nodes are. Returns the relationship or raises NoRelationshipPossible exception. """
meta_type = get_node_meta_type(manager, handle_id) if meta_type == 'Location': return create_location_relationship(manager, handle_id, other_handle_id, rel_type) elif meta_type == 'Logical': return create_logical_relationship(manager, handle_id, other_handle_id, rel_type) elif meta_type == 'Relation': return create_relation_relationship(manager, handle_id, other_handle_id, rel_type) elif meta_type == 'Physical': return create_physical_relationship(manager, handle_id, other_handle_id, rel_type) other_meta_type = get_node_meta_type(manager, other_handle_id) raise exceptions.NoRelationshipPossible(handle_id, meta_type, other_handle_id, other_meta_type, rel_type)
<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_code(self, url, html): """ Parse the code details and TOC from the given HTML content :type url: str :param url: source URL of the page :type html: unicode :param html: Content of the HTML :return: the code """
soup = BeautifulSoup(html, 'html5lib', from_encoding='utf-8') # -- main text div = (soup .find('div', id='content_false') .find('div', attrs={'class': 'data'})) code = Code(self.id_code, date_pub=self.date_pub, url_code=cleanup_url(url)) # -- Code title/subtitle div_title = div.find('div', id='titreTexte') span_subtitle = div_title.find('span', attrs={'class': 'sousTitreTexte'}) if span_subtitle: code.title = div_title.text.replace(span_subtitle.text, '') code.subtitle = span_subtitle.text.strip() regex = r'Version consolidée au (\d{1,2}(?:er)?\s+[^\s]+\s+\d{4})' m = re.search(regex, code.subtitle) if m: code.date_pub = parse_date(m.group(1)) code.title = code.title.strip() # -- TOC code.children = [self.parse_code_ul(url, child) for child in div.find_all('ul', recursive=False)] return 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 parse_code_ul(self, url, ul): """Fill the toc item"""
li_list = ul.find_all('li', recursive=False) li = li_list[0] span_title = li.find('span', attrs={'class': re.compile(r'TM\d+Code')}, recursive=False) section = Section(span_title.attrs['id'], span_title.text.strip()) div_italic = li.find('div', attrs={'class': 'italic'}, recursive=False) if div_italic: section.content = div_italic.text.strip() span_link = li.find('span', attrs={'class': 'codeLienArt'}, recursive=False) if span_link: a_link = span_link.find('a', recursive=False) if self.with_articles: service = self.section_service section.articles = service.articles(self.id_code, section.id_section, self.date_pub) else: section.articles = a_link.text.strip() section.url_section = cleanup_url( urljoin(url, a_link.attrs['href'])) section.children = [self.parse_code_ul(url, child) for child in li.find_all('ul', recursive=False)] return section