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 list(cls, params=None, custom_headers=None): """ Get a collection of all available users. :type params: dict[str, str]|None :type custom_headers: dict[str, str]|None :rtype: BunqResponseUserList """
if params is None: params = {} if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_LISTING response_raw = api_client.get(endpoint_url, params, custom_headers) return BunqResponseUserList.cast_from_bunq_response( cls._from_json_list(response_raw) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(cls, first_name=None, middle_name=None, last_name=None, public_nick_name=None, address_main=None, address_postal=None, avatar_uuid=None, tax_resident=None, document_type=None, document_number=None, document_country_of_issuance=None, document_front_attachment_id=None, document_back_attachment_id=None, date_of_birth=None, place_of_birth=None, country_of_birth=None, nationality=None, language=None, region=None, gender=None, status=None, sub_status=None, legal_guardian_alias=None, session_timeout=None, card_ids=None, card_limits=None, daily_limit_without_confirmation_login=None, notification_filters=None, display_name=None, custom_headers=None): """ Modify a specific person object's data. :type user_person_id: int :param first_name: The person's first name. :type first_name: str :param middle_name: The person's middle name. :type middle_name: str :param last_name: The person's last name. :type last_name: str :param public_nick_name: The person's public nick name. :type public_nick_name: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The person's postal address. :type address_postal: object_.Address :param avatar_uuid: The public UUID of the user's avatar. :type avatar_uuid: str :param tax_resident: The user's tax residence numbers for different countries. :type tax_resident: list[object_.TaxResident] :param document_type: The type of identification document the person registered with. :type document_type: str :param document_number: The identification document number the person registered with. :type document_number: str :param document_country_of_issuance: The country which issued the identification document the person registered with. :type document_country_of_issuance: str :param document_front_attachment_id: The reference to the uploaded picture/scan of the front side of the identification document. :type document_front_attachment_id: int :param document_back_attachment_id: The reference to the uploaded picture/scan of the back side of the identification document. :type document_back_attachment_id: int :param date_of_birth: The person's date of birth. Accepts ISO8601 date formats. :type date_of_birth: str :param place_of_birth: The person's place of birth. :type place_of_birth: str :param country_of_birth: The person's country of birth. Formatted as a SO 3166-1 alpha-2 country code. :type country_of_birth: str :param nationality: The person's nationality. Formatted as a SO 3166-1 alpha-2 country code. :type nationality: str :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param gender: The person's gender. Can be: MALE, FEMALE and UNKNOWN. :type gender: str :param status: The user status. You are not allowed to update the status via PUT. :type status: str :param sub_status: The user sub-status. Can be updated to SUBMIT if status is RECOVERY. :type sub_status: str :param legal_guardian_alias: The legal guardian of the user. Required for minors. :type legal_guardian_alias: object_.Pointer :param session_timeout: The setting for the session timeout of the user in seconds. :type session_timeout: int :param card_ids: Card ids used for centralized card limits. :type card_ids: list[object_.BunqId] :param card_limits: The centralized limits for user's cards. :type card_limits: list[object_.CardLimit] :param daily_limit_without_confirmation_login: The amount the user can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserPerson. :type notification_filters: list[object_.NotificationFilter] :param display_name: The person's legal name. Available legal names can be listed via the 'user/{user_id}/legal-name' endpoint. :type display_name: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """
if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_FIRST_NAME: first_name, cls.FIELD_MIDDLE_NAME: middle_name, cls.FIELD_LAST_NAME: last_name, cls.FIELD_PUBLIC_NICK_NAME: public_nick_name, cls.FIELD_ADDRESS_MAIN: address_main, cls.FIELD_ADDRESS_POSTAL: address_postal, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_TAX_RESIDENT: tax_resident, cls.FIELD_DOCUMENT_TYPE: document_type, cls.FIELD_DOCUMENT_NUMBER: document_number, cls.FIELD_DOCUMENT_COUNTRY_OF_ISSUANCE: document_country_of_issuance, cls.FIELD_DOCUMENT_FRONT_ATTACHMENT_ID: document_front_attachment_id, cls.FIELD_DOCUMENT_BACK_ATTACHMENT_ID: document_back_attachment_id, cls.FIELD_DATE_OF_BIRTH: date_of_birth, cls.FIELD_PLACE_OF_BIRTH: place_of_birth, cls.FIELD_COUNTRY_OF_BIRTH: country_of_birth, cls.FIELD_NATIONALITY: nationality, cls.FIELD_LANGUAGE: language, cls.FIELD_REGION: region, cls.FIELD_GENDER: gender, cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_LEGAL_GUARDIAN_ALIAS: legal_guardian_alias, cls.FIELD_SESSION_TIMEOUT: session_timeout, cls.FIELD_CARD_IDS: card_ids, cls.FIELD_CARD_LIMITS: card_limits, cls.FIELD_DAILY_LIMIT_WITHOUT_CONFIRMATION_LOGIN: daily_limit_without_confirmation_login, cls.FIELD_NOTIFICATION_FILTERS: notification_filters, cls.FIELD_DISPLAY_NAME: display_name } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id()) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(cls, name=None, public_nick_name=None, avatar_uuid=None, address_main=None, address_postal=None, language=None, region=None, country=None, ubo=None, chamber_of_commerce_number=None, legal_form=None, status=None, sub_status=None, session_timeout=None, daily_limit_without_confirmation_login=None, notification_filters=None, custom_headers=None): """ Modify a specific company's data. :type user_company_id: int :param name: The company name. :type name: str :param public_nick_name: The company's nick name. :type public_nick_name: str :param avatar_uuid: The public UUID of the company's avatar. :type avatar_uuid: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The company's postal address. :type address_postal: object_.Address :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param country: The country where the company is registered. :type country: str :param ubo: The names and birth dates of the company's ultimate beneficiary owners. Minimum zero, maximum four. :type ubo: list[object_.Ubo] :param chamber_of_commerce_number: The company's chamber of commerce number. :type chamber_of_commerce_number: str :param legal_form: The company's legal form. :type legal_form: str :param status: The user status. Can be: ACTIVE, SIGNUP, RECOVERY. :type status: str :param sub_status: The user sub-status. Can be: NONE, FACE_RESET, APPROVAL, APPROVAL_DIRECTOR, APPROVAL_PARENT, APPROVAL_SUPPORT, COUNTER_IBAN, IDEAL or SUBMIT. :type sub_status: str :param session_timeout: The setting for the session timeout of the company in seconds. :type session_timeout: int :param daily_limit_without_confirmation_login: The amount the company can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserCompany. :type notification_filters: list[object_.NotificationFilter] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """
if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_NAME: name, cls.FIELD_PUBLIC_NICK_NAME: public_nick_name, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_ADDRESS_MAIN: address_main, cls.FIELD_ADDRESS_POSTAL: address_postal, cls.FIELD_LANGUAGE: language, cls.FIELD_REGION: region, cls.FIELD_COUNTRY: country, cls.FIELD_UBO: ubo, cls.FIELD_CHAMBER_OF_COMMERCE_NUMBER: chamber_of_commerce_number, cls.FIELD_LEGAL_FORM: legal_form, cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_SESSION_TIMEOUT: session_timeout, cls.FIELD_DAILY_LIMIT_WITHOUT_CONFIRMATION_LOGIN: daily_limit_without_confirmation_login, cls.FIELD_NOTIFICATION_FILTERS: notification_filters } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id()) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, cash_register_id, tab_uuid, description, monetary_account_id=None, ean_code=None, avatar_attachment_uuid=None, tab_attachment=None, quantity=None, amount=None, custom_headers=None): """ Create a new TabItem for a given Tab. :type user_id: int :type monetary_account_id: int :type cash_register_id: int :type tab_uuid: str :param description: The TabItem's brief description. Can't be empty and must be no longer than 100 characters :type description: str :param ean_code: The TabItem's EAN code. :type ean_code: str :param avatar_attachment_uuid: An AttachmentPublic UUID that used as an avatar for the TabItem. :type avatar_attachment_uuid: str :param tab_attachment: A list of AttachmentTab attached to the TabItem. :type tab_attachment: list[int] :param quantity: The quantity of the TabItem. Formatted as a number containing up to 15 digits, up to 15 decimals and using a dot. :type quantity: str :param amount: The money amount of the TabItem. Will not change the value of the corresponding Tab. :type amount: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """
if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_DESCRIPTION: description, cls.FIELD_EAN_CODE: ean_code, cls.FIELD_AVATAR_ATTACHMENT_UUID: avatar_attachment_uuid, cls.FIELD_TAB_ATTACHMENT: tab_attachment, cls.FIELD_QUANTITY: quantity, cls.FIELD_AMOUNT: amount } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), cash_register_id, tab_uuid) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, token, custom_headers=None): """ Create a request from an ideal transaction. :type user_id: int :param token: The token passed from a site or read from a QR code. :type token: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseTokenQrRequestIdeal """
if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_TOKEN: token } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseTokenQrRequestIdeal.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_POST) )
<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(cls, monetary_account_paying_id, request_id, maximum_amount_per_month, custom_headers=None): """ Create a new SDD whitelist entry. :type user_id: int :param monetary_account_paying_id: ID of the monetary account of which you want to pay from. :type monetary_account_paying_id: int :param request_id: ID of the request for which you want to whitelist the originating SDD. :type request_id: int :param maximum_amount_per_month: The maximum amount of money that is allowed to be deducted based on the whitelist. :type maximum_amount_per_month: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """
if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_MONETARY_ACCOUNT_PAYING_ID: monetary_account_paying_id, cls.FIELD_REQUEST_ID: request_id, cls.FIELD_MAXIMUM_AMOUNT_PER_MONTH: maximum_amount_per_month } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def icon_resource(name, package=None): """ Returns the absolute URI path to an image. If a package is not explicitly specified then the calling package name is used. :param name: path relative to package path of the image resource. :param package: package name in dotted format. :return: the file URI path to the image resource (i.e. file:///foo/bar/image.png). """
if not package: package = '%s.resources.images' % calling_package() name = resource_filename(package, name) if not name.startswith('/'): return 'file://%s' % abspath(name) return 'file://%s' % 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 image_resources(package=None, directory='resources'): """ Returns all images under the directory relative to a package path. If no directory or package is specified then the resources module of the calling package will be used. Images are recursively discovered. :param package: package name in dotted format. :param directory: path relative to package path of the resources directory. :return: a list of images under the specified resources path. """
if not package: package = calling_package() package_dir = '.'.join([package, directory]) images = [] for i in resource_listdir(package, directory): if i.startswith('__') or i.endswith('.egg-info'): continue fname = resource_filename(package_dir, i) if resource_isdir(package_dir, i): images.extend(image_resources(package_dir, i)) elif what(fname): images.append(fname) return images
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def indexbox(msg="Shall I continue?" , title=" " , choices=("Yes","No") , image=None ): """ Display a buttonbox with the specified choices. Return the index of the choice selected. """
reply = buttonbox(msg=msg, choices=choices, title=title, image=image) index = -1 for choice in choices: index = index + 1 if reply == choice: return index raise AssertionError( "There is a program logic error in the EasyGui code for indexbox.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None): """ Display a messagebox """
if type(ok_button) != type("OK"): raise AssertionError("The 'ok_button' argument to msgbox must be a string.") return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=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 multpasswordbox(msg="Fill in values for the fields." , title=" " , fields=tuple() ,values=tuple() ): r""" Same interface as multenterbox. But in multpassword box, the last of the fields is assumed to be a password, and is masked with asterisks. Example ======= Here is some example code, that shows how values returned from multpasswordbox can be checked for validity before they are accepted:: msg = "Enter logon information" title = "Demo of multpasswordbox" fieldNames = ["Server ID", "User ID", "Password"] fieldValues = [] # we start with blanks for the values fieldValues = multpasswordbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) writeln("Reply was: %s" % str(fieldValues)) """
return __multfillablebox(msg,title,fields,values,"*")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def passwordbox(msg="Enter your password." , title=" " , default="" , image=None , root=None ): """ Show a box in which a user can enter a password. The text is masked with asterisks, so the password is not displayed. Returns the text that the user entered, or None if he cancels the operation. """
return __fillablebox(msg, title, default, mask="*",image=image,root=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 diropenbox(msg=None , title=None , default=None ): """ A dialog to get a directory name. Note that the msg argument, if specified, is ignored. Returns the name of a directory, or None if user chose to cancel. If the "default" argument specifies a directory name, and that directory exists, then the dialog box will start with that directory. """
if sys.platform == 'darwin': _bring_to_front() title=getFileDialogTitle(msg,title) localRoot = Tk() localRoot.withdraw() if not default: default = None f = tk_FileDialog.askdirectory( parent=localRoot , title=title , initialdir=default , initialfile=None ) localRoot.destroy() if not f: return None return os.path.normpath(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __buttonEvent(event): """ Handle an event that is generated by a person clicking a button. """
global boxRoot, __widgetTexts, __replyButtonText __replyButtonText = __widgetTexts[event.widget] boxRoot.quit()
<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_terminate(func): """Register a signal handler to execute when Maltego forcibly terminates the transform."""
def exit_function(*args): func() exit(0) signal.signal(signal.SIGTERM, exit_function)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def croak(error, message_writer=message): """Throw an exception in the Maltego GUI containing error_msg."""
if isinstance(error, MaltegoException): message_writer(MaltegoTransformExceptionMessage(exceptions=[error])) else: message_writer(MaltegoTransformExceptionMessage(exceptions=[MaltegoException(error)]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debug(*args): """Send debug messages to the Maltego console."""
for i in args: click.echo('D:%s' % str(i), err=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 create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key): """Creates an AWS Chalice project for deployment to AWS Lambda."""
from canari.commands.create_aws_lambda import create_aws_lambda create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_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 create_package(package, author, email, description, create_example): """Creates a Canari transform package skeleton."""
from canari.commands.create_package import create_package create_package(package, author, email, description, create_example)
<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_transform(ctx, transform): """Creates a new transform in the specified directory and auto-updates dependencies."""
from canari.commands.create_transform import create_transform create_transform(ctx.project, transform)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dockerize_package(ctx, os, host): """Creates a Docker build file pre-configured with Plume."""
from canari.commands.dockerize_package import dockerize_package dockerize_package(ctx.project, os, host)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_entities(ctx, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity): """Converts Maltego entity definition files to Canari python classes. Excludes Maltego built-in entities by default."""
from canari.commands.generate_entities import generate_entities generate_entities( ctx.project, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_entities_doc(ctx, out_path, package): """Create entities documentation from Canari python classes file."""
from canari.commands.generate_entities_doc import generate_entities_doc generate_entities_doc(ctx.project, out_path, package)
<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_plume_package(package, plume_dir, accept_defaults): """Loads a canari package into Plume."""
from canari.commands.load_plume_package import load_plume_package load_plume_package(package, plume_dir, accept_defaults)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell(ctx, package, working_dir, sudo): """Runs a Canari interactive python shell"""
ctx.mode = CanariMode.LocalShellDebug from canari.commands.shell import shell shell(package, working_dir, sudo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unload_plume_package(package, plume_dir): """Unloads a canari package from Plume."""
from canari.commands.unload_plume_package import unload_plume_package unload_plume_package(package, plume_dir)
<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_canari_mode(mode=CanariMode.Unknown): """ Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the CanariConfigParser. :param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.). :return: previous operating mode. """
global canari_mode old_mode = canari_mode canari_mode = mode return old_mode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def approx_fprime(x, f, epsilon=None, args=(), kwargs=None, centered=True): """ Gradient of function, or Jacobian if function fun returns 1d array Parameters x : array parameters at which the derivative is evaluated fun : function `fun(*((x,)+args), **kwargs)` returning either one value or 1d array epsilon : float, optional Stepsize, if None, optimal stepsize is used. This is _EPS**(1/2)*x for `centered` == False and _EPS**(1/3)*x for `centered` == True. args : tuple Tuple of additional arguments for function `fun`. kwargs : dict Dictionary of additional keyword arguments for function `fun`. centered : bool Whether central difference should be returned. If not, does forward differencing. Returns ------- grad : array gradient or Jacobian Notes ----- If fun returns a 1d array, it returns a Jacobian. If a 2d array is returned by fun (e.g., with a value for each observation), it returns a 3d array with the Jacobian of each observation with shape xk x nobs x xk. I.e., the Jacobian of the first observation would be [:, 0, :] """
kwargs = {} if kwargs is None else kwargs n = len(x) f0 = f(*(x,) + args, **kwargs) dim = np.atleast_1d(f0).shape # it could be a scalar grad = np.zeros((n,) + dim, float) ei = np.zeros(np.shape(x), float) if not centered: epsilon = _get_epsilon(x, 2, epsilon, n) for k in range(n): ei[k] = epsilon[k] grad[k, :] = (f(*(x + ei,) + args, **kwargs) - f0) / epsilon[k] ei[k] = 0.0 else: epsilon = _get_epsilon(x, 3, epsilon, n) / 2. for k in range(n): ei[k] = epsilon[k] grad[k, :] = (f(*(x + ei,) + args, **kwargs) - f(*(x - ei,) + args, **kwargs)) / (2 * epsilon[k]) ei[k] = 0.0 grad = grad.squeeze() axes = [0, 1, 2][:grad.ndim] axes[:2] = axes[1::-1] return np.transpose(grad, axes=axes).squeeze()
<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_cprofile(func): """ Decorator to profile a function It gives good numbers on various function calls but it omits a vital piece of information: what is it about a function that makes it so slow? However, it is a great start to basic profiling. Sometimes it can even point you to the solution with very little fuss. I often use it as a gut check to start the debugging process before I dig deeper into the specific functions that are either slow are called way too often. Pros: No external dependencies and quite fast. Useful for quick high-level checks. Cons: Rather limited information that usually requires deeper debugging; reports are a bit unintuitive, especially for complex codebases. See also -------- do_profile, test_do_profile """
def profiled_func(*args, **kwargs): profile = cProfile.Profile() try: profile.enable() result = func(*args, **kwargs) profile.disable() return result finally: profile.print_stats() return profiled_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convolve(sequence, rule, **kwds): """Wrapper around scipy.ndimage.convolve1d that allows complex input."""
dtype = np.result_type(float, np.ravel(sequence)[0]) seq = np.asarray(sequence, dtype=dtype) if np.iscomplexobj(seq): return (convolve1d(seq.real, rule, **kwds) + 1j * convolve1d(seq.imag, rule, **kwds)) return convolve1d(seq, rule, **kwds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dea3(v0, v1, v2, symmetric=False): """ Extrapolate a slowly convergent sequence Parameters v0, v1, v2 : array-like 3 values of a convergent sequence to extrapolate Returns ------- result : array-like extrapolated value abserr : array-like absolute error estimate Notes ----- DEA3 attempts to extrapolate nonlinearly to a better estimate of the sequence's limiting value, thus improving the rate of convergence. The routine is based on the epsilon algorithm of P. Wynn, see [1]_. Examples -------- # integrate sin(x) from 0 to pi/2 True True True See also -------- dea References .. [1] C. Brezinski and M. Redivo Zaglia (1991) "Extrapolation Methods. Theory and Practice", North-Holland. .. [2] C. Brezinski (1977) "Acceleration de la convergence en analyse numerique", "Lecture Notes in Math.", vol. 584, Springer-Verlag, New York, 1977. .. [3] E. J. Weniger (1989) "Nonlinear sequence transformations for the acceleration of convergence and the summation of divergent series" Computer Physics Reports Vol. 10, 189 - 371 http://arxiv.org/abs/math/0306302v1 """
e0, e1, e2 = np.atleast_1d(v0, v1, v2) with warnings.catch_warnings(): warnings.simplefilter("ignore") # ignore division by zero and overflow delta2, delta1 = e2 - e1, e1 - e0 err2, err1 = np.abs(delta2), np.abs(delta1) tol2, tol1 = max_abs(e2, e1) * _EPS, max_abs(e1, e0) * _EPS delta1[err1 < _TINY] = _TINY delta2[err2 < _TINY] = _TINY # avoid division by zero and overflow ss = 1.0 / delta2 - 1.0 / delta1 + _TINY smalle2 = abs(ss * e1) <= 1.0e-3 converged = (err1 <= tol1) & (err2 <= tol2) | smalle2 result = np.where(converged, e2 * 1.0, e1 + 1.0 / ss) abserr = err1 + err2 + np.where(converged, tol2 * 10, np.abs(result - e2)) if symmetric and len(result) > 1: return result[:-1], abserr[1:] return result, abserr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fd_matrix(step_ratio, parity, nterms): """ Return matrix for finite difference and complex step derivation. Parameters step_ratio : real scalar ratio between steps in unequally spaced difference rule. parity : scalar, integer 0 (one sided, all terms included but zeroth order) 1 (only odd terms included) 2 (only even terms included) 3 (only every 4'th order terms included starting from order 2) 4 (only every 4'th order terms included starting from order 4) 5 (only every 4'th order terms included starting from order 1) 6 (only every 4'th order terms included starting from order 3) nterms : scalar, integer number of terms """
_assert(0 <= parity <= 6, 'Parity must be 0, 1, 2, 3, 4, 5 or 6! ({0:d})'.format(parity)) step = [1, 2, 2, 4, 4, 4, 4][parity] inv_sr = 1.0 / step_ratio offset = [1, 1, 2, 2, 4, 1, 3][parity] c0 = [1.0, 1.0, 1.0, 2.0, 24.0, 1.0, 6.0][parity] c = c0 / \ special.factorial(np.arange(offset, step * nterms + offset, step)) [i, j] = np.ogrid[0:nterms, 0:nterms] return np.atleast_2d(c[j] * inv_sr ** (i * (step * j + 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 _apply_fd_rule(self, step_ratio, sequence, steps): """ Return derivative estimates of fun at x0 for a sequence of stepsizes h Member variables used n """
f_del, h, original_shape = self._vstack(sequence, steps) fd_rule = self._get_finite_difference_rule(step_ratio) ne = h.shape[0] nr = fd_rule.size - 1 _assert(nr < ne, 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method)) f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2) der_init = f_diff / (h ** self.n) ne = max(ne - nr, 1) return der_init[:ne], h[:ne], original_shape
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _complex_even(f, fx, x, h): """ Calculate Hessian with complex-step derivative approximation The stepsize is the same for the complex and the finite difference part """
n = len(x) ee = np.diag(h) hess = 2. * np.outer(h, h) for i in range(n): for j in range(i, n): hess[i, j] = (f(x + 1j * ee[i] + ee[j]) - f(x + 1j * ee[i] - ee[j])).imag / hess[j, i] hess[j, i] = hess[i, j] return hess
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _multicomplex2(f, fx, x, h): """Calculate Hessian with Bicomplex-step derivative approximation"""
n = len(x) ee = np.diag(h) hess = np.outer(h, h) cmplx_wrap = Bicomplex.__array_wrap__ for i in range(n): for j in range(i, n): zph = Bicomplex(x + 1j * ee[i, :], ee[j, :]) hess[i, j] = cmplx_wrap(f(zph)).imag12 / hess[j, i] hess[j, i] = hess[i, j] return hess
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _central_even(f, fx, x, h): """Eq 9."""
n = len(x) ee = np.diag(h) dtype = np.result_type(fx) hess = np.empty((n, n), dtype=dtype) np.outer(h, h, out=hess) for i in range(n): hess[i, i] = (f(x + 2 * ee[i, :]) - 2 * fx + f(x - 2 * ee[i, :])) / (4. * hess[i, i]) for j in range(i + 1, n): hess[i, j] = (f(x + ee[i, :] + ee[j, :]) - f(x + ee[i, :] - ee[j, :]) - f(x - ee[i, :] + ee[j, :]) + f(x - ee[i, :] - ee[j, :])) / (4. * hess[j, i]) hess[j, i] = hess[i, j] return hess
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _central2(f, fx, x, h): """Eq. 8"""
n = len(x) ee = np.diag(h) dtype = np.result_type(fx) g = np.empty(n, dtype=dtype) gg = np.empty(n, dtype=dtype) for i in range(n): g[i] = f(x + ee[i]) gg[i] = f(x - ee[i]) hess = np.empty((n, n), dtype=dtype) np.outer(h, h, out=hess) for i in range(n): for j in range(i, n): hess[i, j] = (f(x + ee[i, :] + ee[j, :]) + f(x - ee[i, :] - ee[j, :]) - g[i] - g[j] + fx - gg[i] - gg[j] + fx) / (2 * hess[j, i]) hess[j, i] = hess[i, j] return hess
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def directionaldiff(f, x0, vec, **options): """ Return directional derivative of a function of n variables Parameters fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun is assumed to be a function of n*m variables. vec: array vector defining the line along which to take the derivative. It should be the same size as x0, but need not be a vector of unit length. **options: optional arguments to pass on to Derivative. Returns ------- dder: scalar estimate of the first derivative of fun in the specified direction. Examples -------- At the global minimizer (1,1) of the Rosenbrock function, compute the directional derivative in the direction [1 2] True True See also -------- Derivative, Gradient """
x0 = np.asarray(x0) vec = np.asarray(vec) if x0.size != vec.size: raise ValueError('vec and x0 must be the same shapes') vec = np.reshape(vec/np.linalg.norm(vec.ravel()), x0.shape) return Derivative(lambda t: f(x0+t*vec), **options)(0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valarray(shape, value=np.NaN, typecode=None): """Return an array of all value."""
if typecode is None: typecode = bool out = np.ones(shape, dtype=typecode) * value if not isinstance(out, np.ndarray): out = np.asarray(out) 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 nominal_step(x=None): """Return nominal step"""
if x is None: return 1.0 return np.log1p(np.abs(x)).clip(min=1.0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rule(self): """ Return finite differencing rule. The rule is for a nominal unit step size, and must be scaled later to reflect the local step size. Member methods used _fd_matrix Member variables used n order method """
step_ratio = self.step_ratio method = self.method if method in ('multicomplex', ) or self.n == 0: return np.ones((1,)) order, method_order = self.n - 1, self._method_order parity = self._parity(method, order, method_order) step = self._richardson_step() num_terms, ix = (order + method_order) // step, order // step fd_rules = FD_RULES.get((step_ratio, parity, num_terms)) if fd_rules is None: fd_mat = self._fd_matrix(step_ratio, parity, num_terms) fd_rules = linalg.pinv(fd_mat) FD_RULES[(step_ratio, parity, num_terms)] = fd_rules if self._flip_fd_rule: return -fd_rules[ix] return fd_rules[ix]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, f_del, h): """ Apply finite difference rule along the first axis. """
fd_rule = self.rule ne = h.shape[0] nr = fd_rule.size - 1 _assert(nr < ne, 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method)) f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2) der_init = f_diff / (h ** self.n) ne = max(ne - nr, 1) return der_init[:ne], h[:ne]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fd_weights_all(x, x0=0, n=1): """ Return finite difference weights for derivatives of all orders up to n. Parameters x : vector, length m x-coordinates for grid points x0 : scalar location where approximations are to be accurate n : scalar integer highest derivative that we want to find weights for Returns ------- weights : array, shape n+1 x m contains coefficients for the j'th derivative in row j (0 <= j <= n) Notes ----- The x values can be arbitrarily spaced but must be distinct and len(x) > n. The Fornberg algorithm is much more stable numerically than regular vandermonde systems for large values of n. See also -------- fd_weights References B. Fornberg (1998) "Calculation of weights_and_points in finite difference formulas", SIAM Review 40, pp. 685-691. http://www.scholarpedia.org/article/Finite_difference_method """
m = len(x) _assert(n < m, 'len(x) must be larger than n') weights = np.zeros((m, n + 1)) _fd_weights_all(weights, x, x0, n) return weights.T
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fd_derivative(fx, x, n=1, m=2): """ Return the n'th derivative for all points using Finite Difference method. Parameters fx : vector function values which are evaluated on x i.e. fx[i] = f(x[i]) x : vector abscissas on which fx is evaluated. The x values can be arbitrarily spaced but must be distinct and len(x) > n. n : scalar integer order of derivative. m : scalar integer defines the stencil size. The stencil size is of 2 * mm + 1 points in the interior, and 2 * mm + 2 points for each of the 2 * mm boundary points where mm = n // 2 + m. fd_derivative evaluates an approximation for the n'th derivative of the vector function f(x) using the Fornberg finite difference method. Restrictions: 0 < n < len(x) and 2*mm+2 <= len(x) Examples -------- True See also -------- fd_weights """
num_x = len(x) _assert(n < num_x, 'len(x) must be larger than n') _assert(num_x == len(fx), 'len(x) must be equal len(fx)') du = np.zeros_like(fx) mm = n // 2 + m size = 2 * mm + 2 # stencil size at boundary # 2 * mm boundary points for i in range(mm): du[i] = np.dot(fd_weights(x[:size], x0=x[i], n=n), fx[:size]) du[-i-1] = np.dot(fd_weights(x[-size:], x0=x[-i-1], n=n), fx[-size:]) # interior points for i in range(mm, num_x-mm): du[i] = np.dot(fd_weights(x[i-mm:i+mm+1], x0=x[i], n=n), fx[i-mm:i+mm+1]) return du
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _poor_convergence(z, r, f, bn, mvec): """ Test for poor convergence based on three function evaluations. This test evaluates the function at the three points and returns false if the relative error is greater than 1e-3. """
check_points = (-0.4 + 0.3j, 0.7 + 0.2j, 0.02 - 0.06j) diffs = [] ftests = [] for check_point in check_points: rtest = r * check_point ztest = z + rtest ftest = f(ztest) # Evaluate powerseries: comp = np.sum(bn * np.power(check_point, mvec)) ftests.append(ftest) diffs.append(comp - ftest) max_abs_error = np.max(np.abs(diffs)) max_f_value = np.max(np.abs(ftests)) return max_abs_error > 1e-3 * max_f_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 _num_taylor_coefficients(n): """ Return number of taylor coefficients Parameters n : scalar integer Wanted number of taylor coefficients Returns ------- m : scalar integer Number of taylor coefficients calculated 8 if n <= 6 16 if 6 < n <= 12 32 if 12 < n <= 25 64 if 25 < n <= 51 128 if 51 < n <= 103 256 if 103 < n <= 192 """
_assert(n < 193, 'Number of derivatives too large. Must be less than 193') correction = np.array([0, 0, 1, 3, 4, 7])[_get_logn(n)] log2n = _get_logn(n - correction) m = 2 ** (log2n + 3) return 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 richardson(vals, k, c=None): """Richardson extrapolation with parameter estimation"""
if c is None: c = richardson_parameter(vals, k) return vals[k] - (vals[k] - vals[k - 1]) / c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def taylor(fun, z0=0, n=1, r=0.0061, num_extrap=3, step_ratio=1.6, **kwds): """ Return Taylor coefficients of complex analytic function using FFT Parameters fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of taylor coefficents to compute. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. full_output : bool, optional If `full_output` is False, only the coefficents is returned (default). If `full_output` is True, then (coefs, status) is returned Returns ------- coefs : ndarray array of taylor coefficents status: Optional object into which output information is written: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. Notes ----- This module uses the method of Fornberg to compute the Taylor series coefficents of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients and uses Richardson Extrapolation to improve and bound the estimate. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- Compute the first 6 taylor coefficients 1 / (1 - z) expanded round z0 = 0: True True True References [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979 """
return Taylor(fun, n=n, r=r, num_extrap=num_extrap, step_ratio=step_ratio, **kwds)(z0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derivative(fun, z0, n=1, **kwds): """ Calculate n-th derivative of complex analytic function using FFT Parameters fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of derivatives to compute where 0 represents the value of the function and n represents the nth derivative. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation full_output : bool, optional If `full_output` is False, only the derivative is returned (default). If `full_output` is True, then (der, status) is returned `der` is the derivative, and `status` is a Results object. Returns ------- der : ndarray array of derivatives status: Optional object into which output information is written. Fields: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. This module uses the method of Fornberg to compute the derivatives of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients, uses Richardson Extrapolation to improve and bound the estimate, then multiplies by a factorial to compute the derivatives. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- To compute the first five derivatives of 1 / (1 - z) at z = 0: Compute the first 6 taylor derivatives of 1 / (1 - z) at z0 = 0: True True True References [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979 """
result = taylor(fun, z0, n=n, **kwds) # convert taylor series --> actual derivatives. m = _num_taylor_coefficients(n) fact = factorial(np.arange(m)) if kwds.get('full_output'): coefs, info_ = result info = _INFO(info_.error_estimate * fact, *info_[1:]) return coefs * fact, info return result * fact
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_char(self): """An empty character with default foreground and background colors."""
reverse = mo.DECSCNM in self.mode return Char(data=" ", fg="default", bg="default", reverse=reverse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset the terminal to its initial state. * Scrolling margins are reset to screen boundaries. * Cursor is moved to home location -- ``(0, 0)`` and its attributes are set to defaults (see :attr:`default_char`). * Screen is cleared -- each character is reset to :attr:`default_char`. * Tabstops are reset to "every eight columns". * All lines are marked as :attr:`dirty`. .. note:: Neither VT220 nor VT102 manuals mention that terminal modes and tabstops should be reset as well, thanks to :manpage:`xterm` -- we now know that. """
self.dirty.update(range(self.lines)) self.buffer.clear() self.margins = None self.mode = set([mo.DECAWM, mo.DECTCEM]) self.title = "" self.icon_name = "" self.charset = 0 self.g0_charset = cs.LAT1_MAP self.g1_charset = cs.VT100_MAP # From ``man terminfo`` -- "... hardware tabs are initially # set every `n` spaces when the terminal is powered up. Since # we aim to support VT102 / VT220 and linux -- we use n = 8. self.tabstops = set(range(8, self.columns, 8)) self.cursor = Cursor(0, 0) self.cursor_position() self.saved_columns = 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 resize(self, lines=None, columns=None): """Resize the screen to the given size. If the requested screen size has more lines than the existing screen, lines will be added at the bottom. If the requested size has less lines than the existing screen lines will be clipped at the top of the screen. Similarly, if the existing screen has less columns than the requested screen, columns will be added at the right, and if it has more -- columns will be clipped at the right. :param int lines: number of lines in the new screen. :param int columns: number of columns in the new screen. .. versionchanged:: 0.7.0 If the requested screen size is identical to the current screen size, the method does nothing. """
lines = lines or self.lines columns = columns or self.columns if lines == self.lines and columns == self.columns: return # No changes. self.dirty.update(range(lines)) if lines < self.lines: self.save_cursor() self.cursor_position(0, 0) self.delete_lines(self.lines - lines) # Drop from the top. self.restore_cursor() if columns < self.columns: for line in self.buffer.values(): for x in range(columns, self.columns): line.pop(x, None) self.lines, self.columns = lines, columns self.set_margins()
<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_margins(self, top=None, bottom=None): """Select top and bottom margins for the scrolling region. :param int top: the smallest line number that is scrolled. :param int bottom: the biggest line number that is scrolled. """
# XXX 0 corresponds to the CSI with no parameters. if (top is None or top == 0) and bottom is None: self.margins = None return margins = self.margins or Margins(0, self.lines - 1) # Arguments are 1-based, while :attr:`margins` are zero # based -- so we have to decrement them by one. We also # make sure that both of them is bounded by [0, lines - 1]. if top is None: top = margins.top else: top = max(0, min(top - 1, self.lines - 1)) if bottom is None: bottom = margins.bottom else: bottom = max(0, min(bottom - 1, self.lines - 1)) # Even though VT102 and VT220 require DECSTBM to ignore # regions of width less than 2, some programs (like aptitude # for example) rely on it. Practicality beats purity. if bottom - top >= 1: self.margins = Margins(top, bottom) # The cursor moves to the home position when the top and # bottom margins of the scrolling region (DECSTBM) changes. self.cursor_position()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_charset(self, code, mode): """Define ``G0`` or ``G1`` charset. :param str code: character set code, should be a character from ``"B0UK"``, otherwise ignored. :param str mode: if ``"("`` ``G0`` charset is defined, if ``")"`` -- we operate on ``G1``. .. warning:: User-defined charsets are currently not supported. """
if code in cs.MAPS: if mode == "(": self.g0_charset = cs.MAPS[code] elif mode == ")": self.g1_charset = cs.MAPS[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 index(self): """Move the cursor down one line in the same column. If the cursor is at the last line, create a new line at the bottom. """
top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == bottom: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(top, bottom): self.buffer[y] = self.buffer[y + 1] self.buffer.pop(bottom, None) else: self.cursor_down()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse_index(self): """Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top. """
top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == top: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(bottom, top, -1): self.buffer[y] = self.buffer[y - 1] self.buffer.pop(top, None) else: self.cursor_up()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tab(self): """Move to the next tab space, or the end of the screen if there aren't anymore left. """
for stop in sorted(self.tabstops): if self.cursor.x < stop: column = stop break else: column = self.columns - 1 self.cursor.x = column
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_cursor(self): """Push the current cursor position onto the stack."""
self.savepoints.append(Savepoint(copy.copy(self.cursor), self.g0_charset, self.g1_charset, self.charset, mo.DECOM in self.mode, mo.DECAWM in self.mode))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_in_line(self, how=0, private=False): """Erase a line in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of line, including cursor position. * ``1`` -- Erases from beginning of line to cursor, including cursor position. * ``2`` -- Erases complete line. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. """
self.dirty.add(self.cursor.y) if how == 0: interval = range(self.cursor.x, self.columns) elif how == 1: interval = range(self.cursor.x + 1) elif how == 2: interval = range(self.columns) line = self.buffer[self.cursor.y] for x in interval: line[x] = self.cursor.attrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_in_display(self, how=0, *args, **kwargs): """Erases display in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor position. * ``1`` -- Erases from beginning of screen to cursor, including cursor position. * ``2`` and ``3`` -- Erases complete display. All lines are erased and changed to single-width. Cursor does not move. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. .. versionchanged:: 0.8.1 The method accepts any number of positional arguments as some ``clear`` implementations include a ``;`` after the first parameter causing the stream to assume a ``0`` second parameter. """
if how == 0: interval = range(self.cursor.y + 1, self.lines) elif how == 1: interval = range(self.cursor.y) elif how == 2 or how == 3: interval = range(self.lines) self.dirty.update(interval) for y in interval: line = self.buffer[y] for x in line: line[x] = self.cursor.attrs if how == 0 or how == 1: self.erase_in_line(how)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_tab_stop(self, how=0): """Clear a horizontal tab stop. :param int how: defines a way the tab stop should be cleared: * ``0`` or nothing -- Clears a horizontal tab stop at cursor position. * ``3`` -- Clears all horizontal tab stops. """
if how == 0: # Clears a horizontal tab stop at cursor position, if it's # present, or silently fails if otherwise. self.tabstops.discard(self.cursor.x) elif how == 3: self.tabstops = 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 ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds."""
self.cursor.x = min(max(0, self.cursor.x), self.columns - 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 ensure_vbounds(self, use_margins=None): """Ensure the cursor is within vertical screen bounds. :param bool use_margins: when ``True`` or when :data:`~pyte.modes.DECOM` is set, cursor is bounded by top and and bottom margins, instead of ``[0; lines - 1]``. """
if (use_margins or mo.DECOM in self.mode) and self.margins is not None: top, bottom = self.margins else: top, bottom = 0, self.lines - 1 self.cursor.y = min(max(top, self.cursor.y), bottom)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cursor_position(self, line=None, column=None): """Set the cursor to a specific `line` and `column`. Cursor is allowed to move out of the scrolling region only when :data:`~pyte.modes.DECOM` is reset, otherwise -- the position doesn't change. :param int line: line number to move the cursor to. :param int column: column number to move the cursor to. """
column = (column or 1) - 1 line = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if self.margins is not None and mo.DECOM in self.mode: line += self.margins.top # Cursor is not allowed to move out of the scrolling region. if not self.margins.top <= line <= self.margins.bottom: return self.cursor.x = column self.cursor.y = line self.ensure_hbounds() self.ensure_vbounds()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cursor_to_line(self, line=None): """Move cursor to a specific line in the current column. :param int line: line number to move the cursor to. """
self.cursor.y = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if mo.DECOM in self.mode: self.cursor.y += self.margins.top # FIXME: should we also restrict the cursor to the scrolling # region? self.ensure_vbounds()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignment_display(self): """Fills screen with uppercase E's for screen focus and alignment."""
self.dirty.update(range(self.lines)) for y in range(self.lines): for x in range(self.columns): self.buffer[y][x] = self.buffer[y][x]._replace(data="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 select_graphic_rendition(self, *attrs): """Set display attributes. :param list attrs: a list of display attributes to set. """
replace = {} # Fast path for resetting all attributes. if not attrs or attrs == (0, ): self.cursor.attrs = self.default_char return else: attrs = list(reversed(attrs)) while attrs: attr = attrs.pop() if attr == 0: # Reset all attributes. replace.update(self.default_char._asdict()) elif attr in g.FG_ANSI: replace["fg"] = g.FG_ANSI[attr] elif attr in g.BG: replace["bg"] = g.BG_ANSI[attr] elif attr in g.TEXT: attr = g.TEXT[attr] replace[attr[1:]] = attr.startswith("+") elif attr in g.FG_AIXTERM: replace.update(fg=g.FG_AIXTERM[attr], bold=True) elif attr in g.BG_AIXTERM: replace.update(bg=g.BG_AIXTERM[attr], bold=True) elif attr in (g.FG_256, g.BG_256): key = "fg" if attr == g.FG_256 else "bg" try: n = attrs.pop() if n == 5: # 256. m = attrs.pop() replace[key] = g.FG_BG_256[m] elif n == 2: # 24bit. # This is somewhat non-standard but is nonetheless # supported in quite a few terminals. See discussion # here https://gist.github.com/XVilka/8346728. replace[key] = "{0:02x}{1:02x}{2:02x}".format( attrs.pop(), attrs.pop(), attrs.pop()) except IndexError: pass self.cursor.attrs = self.cursor.attrs._replace(**replace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report_device_attributes(self, mode=0, **kwargs): """Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual. """
# We only implement "primary" DA which is the only DA request # VT102 understood, see ``VT102ID`` in ``linux/drivers/tty/vt.c``. if mode == 0 and not kwargs.get("private"): self.write_process_input(ctrl.CSI + "?6c")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report_device_status(self, mode): """Report terminal status or cursor position. :param int mode: if 5 -- terminal status, 6 -- cursor position, otherwise a noop. .. versionadded:: 0.5.0 """
if mode == 5: # Request for terminal status. self.write_process_input(ctrl.CSI + "0n") elif mode == 6: # Request for cursor position. x = self.cursor.x + 1 y = self.cursor.y + 1 # "Origin mode (DECOM) selects line numbering." if mo.DECOM in self.mode: y -= self.margins.top self.write_process_input(ctrl.CSI + "{0};{1}R".format(y, 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 before_event(self, event): """Ensure a screen is at the bottom of the history buffer. :param str event: event name, for example ``"linefeed"``. """
if event not in ["prev_page", "next_page"]: while self.history.position < self.history.size: self.next_page()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_in_display(self, how=0, *args, **kwargs): """Overloaded to reset history state."""
super(HistoryScreen, self).erase_in_display(how, *args, **kwargs) if how == 3: self._reset_history()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(self): """Overloaded to update top history with the removed lines."""
top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == bottom: self.history.top.append(self.buffer[top]) super(HistoryScreen, self).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 prev_page(self): """Move the screen page up through the history buffer. Page size is defined by ``history.ratio``, so for instance ``ratio = .5`` means that half the screen is restored from history on page switch. """
if self.history.position > self.lines and self.history.top: mid = min(len(self.history.top), int(math.ceil(self.lines * self.history.ratio))) self.history.bottom.extendleft( self.buffer[y] for y in range(self.lines - 1, self.lines - mid - 1, -1)) self.history = self.history \ ._replace(position=self.history.position - mid) for y in range(self.lines - 1, mid - 1, -1): self.buffer[y] = self.buffer[y - mid] for y in range(mid - 1, -1, -1): self.buffer[y] = self.history.top.pop() self.dirty = set(range(self.lines))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_page(self): """Move the screen page down through the history buffer."""
if self.history.position < self.history.size and self.history.bottom: mid = min(len(self.history.bottom), int(math.ceil(self.lines * self.history.ratio))) self.history.top.extend(self.buffer[y] for y in range(mid)) self.history = self.history \ ._replace(position=self.history.position + mid) for y in range(self.lines - mid): self.buffer[y] = self.buffer[y + mid] for y in range(self.lines - mid, self.lines): self.buffer[y] = self.history.bottom.popleft() self.dirty = set(range(self.lines))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach(self, screen): """Adds a given screen to the listener queue. :param pyte.screens.Screen screen: a screen to attach to. """
if self.listener is not None: warnings.warn("As of version 0.6.0 the listener queue is " "restricted to a single element. Existing " "listener {0} will be replaced." .format(self.listener), DeprecationWarning) if self.strict: for event in self.events: if not hasattr(screen, event): raise TypeError("{0} is missing {1}".format(screen, event)) self.listener = screen self._parser = None self._initialize_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 feed(self, data): """Consume some data and advances the state as necessary. :param str data: a blob of data to feed from. """
send = self._send_to_parser draw = self.listener.draw match_text = self._text_pattern.match taking_plain_text = self._taking_plain_text length = len(data) offset = 0 while offset < length: if taking_plain_text: match = match_text(data, offset) if match: start, offset = match.span() draw(data[start:offset]) else: taking_plain_text = False else: taking_plain_text = send(data[offset:offset + 1]) offset += 1 self._taking_plain_text = taking_plain_text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def on_shutdown(app): """Closes all WS connections on shutdown."""
global is_shutting_down is_shutting_down = True for task in app["websockets"]: task.cancel() try: await task except asyncio.CancelledError: 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 rmsd(V, W): """ Calculate Root-mean-square deviation from two sets of vectors V and W. Parameters V : array (N,D) matrix, where N is points and D is dimension. W : array (N,D) matrix, where N is points and D is dimension. Returns ------- rmsd : float Root-mean-square deviation between the two vectors """
D = len(V[0]) N = len(V) result = 0.0 for v, w in zip(V, W): result += sum([(v[i] - w[i])**2.0 for i in range(D)]) return np.sqrt(result/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 kabsch_rmsd(P, Q, translate=False): """ Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD. Parameters P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. translate : bool Use centroids to translate vector P and Q unto each other. Returns ------- rmsd : float root-mean squared deviation """
if translate: Q = Q - centroid(Q) P = P - centroid(P) P = kabsch_rotate(P, Q) return rmsd(P, Q)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kabsch_rotate(P, Q): """ Rotate matrix P unto matrix Q using Kabsch algorithm. Parameters P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. Returns ------- P : array (N,D) matrix, where N is points and D is dimension, rotated """
U = kabsch(P, Q) # Rotate P P = np.dot(P, U) return P
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kabsch(P, Q): """ Using the Kabsch algorithm with two sets of paired point P and Q, centered around the centroid. Each vector set is represented as an NxD matrix, where D is the the dimension of the space. The algorithm works in three steps: - a centroid translation of P and Q (assumed done before this function call) - the computation of a covariance matrix C - computation of the optimal rotation matrix U For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm Parameters P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. Returns ------- U : matrix Rotation matrix (D,D) """
# Computation of the covariance matrix C = np.dot(np.transpose(P), Q) # Computation of the optimal rotation matrix # This can be done using singular value decomposition (SVD) # Getting the sign of the det(V)*(W) to decide # whether we need to correct our rotation matrix to ensure a # right-handed coordinate system. # And finally calculating the optimal rotation matrix U # see http://en.wikipedia.org/wiki/Kabsch_algorithm V, S, W = np.linalg.svd(C) d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0 if d: S[-1] = -S[-1] V[:, -1] = -V[:, -1] # Create Rotation matrix U U = np.dot(V, W) return U
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quaternion_rotate(X, Y): """ Calculate the rotation Parameters X : array (N,D) matrix, where N is points and D is dimension. Y: array (N,D) matrix, where N is points and D is dimension. Returns ------- rot : matrix Rotation matrix (D,D) """
N = X.shape[0] W = np.asarray([makeW(*Y[k]) for k in range(N)]) Q = np.asarray([makeQ(*X[k]) for k in range(N)]) Qt_dot_W = np.asarray([np.dot(Q[k].T, W[k]) for k in range(N)]) W_minus_Q = np.asarray([W[k] - Q[k] for k in range(N)]) A = np.sum(Qt_dot_W, axis=0) eigen = np.linalg.eigh(A) r = eigen[1][:, eigen[0].argmax()] rot = quaternion_transform(r) return rot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reorder_distance(p_atoms, q_atoms, p_coord, q_coord): """ Re-orders the input atom list and xyz coordinates by atom type and then by distance of each atom from the centroid. Parameters atoms : array (N,1) matrix, where N is points holding the atoms' names coord : array (N,D) matrix, where N is points and D is dimension Returns ------- atoms_reordered : array (N,1) matrix, where N is points holding the ordered atoms' names coords_reordered : array (N,D) matrix, where N is points and D is dimension (rows re-ordered) """
# Find unique atoms unique_atoms = np.unique(p_atoms) # generate full view from q shape to fill in atom view on the fly view_reorder = np.zeros(q_atoms.shape, dtype=int) for atom in unique_atoms: p_atom_idx, = np.where(p_atoms == atom) q_atom_idx, = np.where(q_atoms == atom) A_coord = p_coord[p_atom_idx] B_coord = q_coord[q_atom_idx] # Calculate distance from each atom to centroid A_norms = np.linalg.norm(A_coord, axis=1) B_norms = np.linalg.norm(B_coord, axis=1) reorder_indices_A = np.argsort(A_norms) reorder_indices_B = np.argsort(B_norms) # Project the order of P onto Q translator = np.argsort(reorder_indices_A) view = reorder_indices_B[translator] view_reorder[p_atom_idx] = q_atom_idx[view] return view_reorder
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hungarian(A, B): """ Hungarian reordering. Assume A and B are coordinates for atoms of SAME type only """
# should be kabasch here i think distances = cdist(A, B, 'euclidean') # Perform Hungarian analysis on distance matrix between atoms of 1st # structure and trial structure indices_a, indices_b = linear_sum_assignment(distances) return indices_b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def brute_permutation(A, B): """ Re-orders the input atom list and xyz coordinates using the brute force method of permuting all rows of the input coordinates Parameters A : array (N,D) matrix, where N is points and D is dimension B : array (N,D) matrix, where N is points and D is dimension Returns ------- view : array (N,1) matrix, reordered view of B projected to A """
rmsd_min = np.inf view_min = None # Sets initial ordering for row indices to [0, 1, 2, ..., len(A)], used in # brute-force method num_atoms = A.shape[0] initial_order = list(range(num_atoms)) for reorder_indices in generate_permutations(initial_order, num_atoms): # Re-order the atom array and coordinate matrix coords_ordered = B[reorder_indices] # Calculate the RMSD between structure 1 and the Hungarian re-ordered # structure 2 rmsd_temp = kabsch_rmsd(A, coords_ordered) # Replaces the atoms and coordinates with the current structure if the # RMSD is lower if rmsd_temp < rmsd_min: rmsd_min = rmsd_temp view_min = copy.deepcopy(reorder_indices) return view_min
<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_reflections(p_atoms, q_atoms, p_coord, q_coord, reorder_method=reorder_hungarian, rotation_method=kabsch_rmsd, keep_stereo=False): """ Minimize RMSD using reflection planes for molecule P and Q Warning: This will affect stereo-chemistry Parameters p_atoms : array (N,1) matrix, where N is points holding the atoms' names q_atoms : array (N,1) matrix, where N is points holding the atoms' names p_coord : array (N,D) matrix, where N is points and D is dimension q_coord : array (N,D) matrix, where N is points and D is dimension Returns ------- min_rmsd min_swap min_reflection min_review """
min_rmsd = np.inf min_swap = None min_reflection = None min_review = None tmp_review = None swap_mask = [1,-1,-1,1,-1,1] reflection_mask = [1,-1,-1,-1,1,1,1,-1] for swap, i in zip(AXIS_SWAPS, swap_mask): for reflection, j in zip(AXIS_REFLECTIONS, reflection_mask): if keep_stereo and i * j == -1: continue # skip enantiomers tmp_atoms = copy.copy(q_atoms) tmp_coord = copy.deepcopy(q_coord) tmp_coord = tmp_coord[:, swap] tmp_coord = np.dot(tmp_coord, np.diag(reflection)) tmp_coord -= centroid(tmp_coord) # Reorder if reorder_method is not None: tmp_review = reorder_method(p_atoms, tmp_atoms, p_coord, tmp_coord) tmp_coord = tmp_coord[tmp_review] tmp_atoms = tmp_atoms[tmp_review] # Rotation if rotation_method is None: this_rmsd = rmsd(p_coord, tmp_coord) else: this_rmsd = rotation_method(p_coord, tmp_coord) if this_rmsd < min_rmsd: min_rmsd = this_rmsd min_swap = swap min_reflection = reflection min_review = tmp_review if not (p_atoms == q_atoms[min_review]).all(): print("error: Not aligned") quit() return min_rmsd, min_swap, min_reflection, min_review
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_coordinates(atoms, V, title=""): """ Print coordinates V with corresponding atoms to stdout in XYZ format. Parameters atoms : list List of element types V : array (N,3) matrix of atomic coordinates title : string (optional) Title of molecule """
print(set_coordinates(atoms, V, title=title)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_coordinates_pdb(filename): """ Get coordinates from the first chain in a pdb file and return a vectorset with all the coordinates. Parameters filename : string Filename to read Returns ------- atoms : list List of atomic types V : array (N,3) where N is number of atoms """
# PDB files tend to be a bit of a mess. The x, y and z coordinates # are supposed to be in column 31-38, 39-46 and 47-54, but this is # not always the case. # Because of this the three first columns containing a decimal is used. # Since the format doesn't require a space between columns, we use the # above column indices as a fallback. x_column = None V = list() # Same with atoms and atom naming. # The most robust way to do this is probably # to assume that the atomtype is given in column 3. atoms = list() with open(filename, 'r') as f: lines = f.readlines() for line in lines: if line.startswith("TER") or line.startswith("END"): break if line.startswith("ATOM"): tokens = line.split() # Try to get the atomtype try: atom = tokens[2][0] if atom in ("H", "C", "N", "O", "S", "P"): atoms.append(atom) else: # e.g. 1HD1 atom = tokens[2][1] if atom == "H": atoms.append(atom) else: raise Exception except: exit("error: Parsing atomtype for the following line: \n{0:s}".format(line)) if x_column == None: try: # look for x column for i, x in enumerate(tokens): if "." in x and "." in tokens[i + 1] and "." in tokens[i + 2]: x_column = i break except IndexError: exit("error: Parsing coordinates for the following line: \n{0:s}".format(line)) # Try to read the coordinates try: V.append(np.asarray(tokens[x_column:x_column + 3], dtype=float)) except: # If that doesn't work, use hardcoded indices try: x = line[30:38] y = line[38:46] z = line[46:54] V.append(np.asarray([x, y ,z], dtype=float)) except: exit("error: Parsing input for the following line: \n{0:s}".format(line)) V = np.asarray(V) atoms = np.asarray(atoms) assert V.shape[0] == atoms.size return atoms, V
<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_coordinates_xyz(filename): """ Get coordinates from filename and return a vectorset with all the coordinates, in XYZ format. Parameters filename : string Filename to read Returns ------- atoms : list List of atomic types V : array (N,3) where N is number of atoms """
f = open(filename, 'r') V = list() atoms = list() n_atoms = 0 # Read the first line to obtain the number of atoms to read try: n_atoms = int(f.readline()) except ValueError: exit("error: Could not obtain the number of atoms in the .xyz file.") # Skip the title line f.readline() # Use the number of atoms to not read beyond the end of a file for lines_read, line in enumerate(f): if lines_read == n_atoms: break atom = re.findall(r'[a-zA-Z]+', line)[0] atom = atom.upper() numbers = re.findall(r'[-]?\d+\.\d*(?:[Ee][-\+]\d+)?', line) numbers = [float(number) for number in numbers] # The numbers are not valid unless we obtain exacly three if len(numbers) >= 3: V.append(np.array(numbers)[:3]) atoms.append(atom) else: exit("Reading the .xyz file failed in line {0}. Please check the format.".format(lines_read + 2)) f.close() atoms = np.array(atoms) V = np.array(V) return atoms, V
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetZipInfo(self): """Retrieves the ZIP info object. Returns: zipfile.ZipInfo: a ZIP info object or None if not available. Raises: PathSpecError: if the path specification is incorrect. """
if not self._zip_info: location = getattr(self.path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self._file_system.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) == 1: return None zip_file = self._file_system.GetZipFile() try: self._zip_info = zip_file.getinfo(location[1:]) except KeyError: pass return self._zip_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 _NormalizedVolumeIdentifiers( self, volume_system, volume_identifiers, prefix='v'): """Normalizes volume identifiers. Args: volume_system (VolumeSystem): volume system. volume_identifiers (list[int|str]): allowed volume identifiers, formatted as an integer or string with prefix. prefix (Optional[str]): volume identifier prefix. Returns: list[str]: volume identifiers with prefix. Raises: ScannerError: if the volume identifier is not supported or no volume could be found that corresponds with the identifier. """
normalized_volume_identifiers = [] for volume_identifier in volume_identifiers: if isinstance(volume_identifier, int): volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier) elif not volume_identifier.startswith(prefix): try: volume_identifier = int(volume_identifier, 10) volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier) except (TypeError, ValueError): pass try: volume = volume_system.GetVolumeByIdentifier(volume_identifier) except KeyError: volume = None if not volume: raise errors.ScannerError( 'Volume missing for identifier: {0:s}.'.format(volume_identifier)) normalized_volume_identifiers.append(volume_identifier) return normalized_volume_identifiers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ScanVolume(self, scan_context, scan_node, base_path_specs): """Scans a volume scan node for volume and file systems. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): volume scan node. base_path_specs (list[PathSpec]): file system base path specifications. Raises: ScannerError: if the format of or within the source is not supported or the scan node is invalid. """
if not scan_node or not scan_node.path_spec: raise errors.ScannerError('Invalid or missing scan node.') if scan_context.IsLockedScanNode(scan_node.path_spec): # The source scanner found a locked volume and we need a credential to # unlock it. self._ScanEncryptedVolume(scan_context, scan_node) if scan_context.IsLockedScanNode(scan_node.path_spec): return if scan_node.IsVolumeSystemRoot(): self._ScanVolumeSystemRoot(scan_context, scan_node, base_path_specs) elif scan_node.IsFileSystem(): self._ScanFileSystem(scan_node, base_path_specs) elif scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: # TODO: look into building VSS store on demand. # We "optimize" here for user experience, alternatively we could scan for # a file system instead of hard coding a TSK child path specification. path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_TSK, location='/', parent=scan_node.path_spec) base_path_specs.append(path_spec) else: for sub_scan_node in scan_node.sub_nodes: self._ScanVolume(scan_context, sub_scan_node, base_path_specs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ScanVolumeSystemRoot(self, scan_context, scan_node, base_path_specs): """Scans a volume system root scan node for volume and file systems. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): volume system root scan node. base_path_specs (list[PathSpec]): file system base path specifications. Raises: ScannerError: if the scan node is invalid, the scan node type is not supported or if a sub scan node cannot be retrieved. """
if not scan_node or not scan_node.path_spec: raise errors.ScannerError('Invalid scan node.') if scan_node.type_indicator == definitions.TYPE_INDICATOR_APFS_CONTAINER: volume_identifiers = self._GetAPFSVolumeIdentifiers(scan_node) elif scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: volume_identifiers = self._GetVSSStoreIdentifiers(scan_node) # Process VSS stores (snapshots) starting with the most recent one. volume_identifiers.reverse() else: raise errors.ScannerError( 'Unsupported volume system type: {0:s}.'.format( scan_node.type_indicator)) for volume_identifier in volume_identifiers: location = '/{0:s}'.format(volume_identifier) sub_scan_node = scan_node.GetSubNodeByLocation(location) if not sub_scan_node: raise errors.ScannerError( 'Scan node missing for volume identifier: {0:s}.'.format( volume_identifier)) self._ScanVolume(scan_context, sub_scan_node, base_path_specs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetBasePathSpecs(self, source_path): """Determines the base path specifications. Args: source_path (str): source path. Returns: list[PathSpec]: path specifications. Raises: ScannerError: if the source path does not exists, or if the source path is not a file or directory, or if the format of or within the source file is not supported. """
if not source_path: raise errors.ScannerError('Invalid source path.') # Note that os.path.exists() does not support Windows device paths. if (not source_path.startswith('\\\\.\\') and not os.path.exists(source_path)): raise errors.ScannerError( 'No such device, file or directory: {0:s}.'.format(source_path)) scan_context = source_scanner.SourceScannerContext() scan_context.OpenSourcePath(source_path) try: self._source_scanner.Scan(scan_context) except (ValueError, errors.BackEndError) as exception: raise errors.ScannerError( 'Unable to scan source with error: {0!s}'.format(exception)) self._source_path = source_path self._source_type = scan_context.source_type if self._source_type not in [ definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE, definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE]: scan_node = scan_context.GetRootScanNode() return [scan_node.path_spec] # Get the first node where where we need to decide what to process. scan_node = scan_context.GetRootScanNode() while len(scan_node.sub_nodes) == 1: scan_node = scan_node.sub_nodes[0] base_path_specs = [] if scan_node.type_indicator != definitions.TYPE_INDICATOR_TSK_PARTITION: self._ScanVolume(scan_context, scan_node, base_path_specs) else: # Determine which partition needs to be processed. partition_identifiers = self._GetTSKPartitionIdentifiers(scan_node) for partition_identifier in partition_identifiers: location = '/{0:s}'.format(partition_identifier) sub_scan_node = scan_node.GetSubNodeByLocation(location) self._ScanVolume(scan_context, sub_scan_node, base_path_specs) return base_path_specs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ScanFileSystemForWindowsDirectory(self, path_resolver): """Scans a file system for a known Windows directory. Args: path_resolver (WindowsPathResolver): Windows path resolver. Returns: bool: True if a known Windows directory was found. """
result = False for windows_path in self._WINDOWS_DIRECTORIES: windows_path_spec = path_resolver.ResolvePath(windows_path) result = windows_path_spec is not None if result: self._windows_directory = windows_path break 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 OpenFile(self, windows_path): """Opens the file specificed by the Windows path. Args: windows_path (str): Windows path to the file. Returns: FileIO: file-like object or None if the file does not exist. """
path_spec = self._path_resolver.ResolvePath(windows_path) if path_spec is None: return None return self._file_system.GetFileObjectByPathSpec(path_spec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ScanForWindowsVolume(self, source_path): """Scans for a Windows volume. Args: source_path (str): source path. Returns: bool: True if a Windows volume was found. Raises: ScannerError: if the source path does not exists, or if the source path is not a file or directory, or if the format of or within the source file is not supported. """
windows_path_specs = self.GetBasePathSpecs(source_path) if (not windows_path_specs or self._source_type == definitions.SOURCE_TYPE_FILE): return False file_system_path_spec = windows_path_specs[0] self._file_system = resolver.Resolver.OpenFileSystem(file_system_path_spec) if file_system_path_spec.type_indicator == definitions.TYPE_INDICATOR_OS: mount_point = file_system_path_spec else: mount_point = file_system_path_spec.parent self._path_resolver = windows_path_resolver.WindowsPathResolver( self._file_system, mount_point) # The source is a directory or single volume storage media image. if not self._windows_directory: self._ScanFileSystemForWindowsDirectory(self._path_resolver) if not self._windows_directory: return False self._path_resolver.SetEnvironmentVariable( 'SystemRoot', self._windows_directory) self._path_resolver.SetEnvironmentVariable( 'WinDir', self._windows_directory) 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 _FlushCache(cls, format_categories): """Flushes the cached objects for the specified format categories. Args: format_categories (set[str]): format categories. """
if definitions.FORMAT_CATEGORY_ARCHIVE in format_categories: cls._archive_remainder_list = None cls._archive_scanner = None cls._archive_store = None if definitions.FORMAT_CATEGORY_COMPRESSED_STREAM in format_categories: cls._compressed_stream_remainder_list = None cls._compressed_stream_scanner = None cls._compressed_stream_store = None if definitions.FORMAT_CATEGORY_FILE_SYSTEM in format_categories: cls._file_system_remainder_list = None cls._file_system_scanner = None cls._file_system_store = None if definitions.FORMAT_CATEGORY_STORAGE_MEDIA_IMAGE in format_categories: cls._storage_media_image_remainder_list = None cls._storage_media_image_scanner = None cls._storage_media_image_store = None if definitions.FORMAT_CATEGORY_VOLUME_SYSTEM in format_categories: cls._volume_system_remainder_list = None cls._volume_system_scanner = None cls._volume_system_store = 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 _GetSignatureScanner(cls, specification_store): """Initializes a signature scanner based on a specification store. Args: specification_store (FormatSpecificationStore): specification store. Returns: pysigscan.scanner: signature scanner. """
signature_scanner = pysigscan.scanner() signature_scanner.set_scan_buffer_size(cls._SCAN_BUFFER_SIZE) for format_specification in specification_store.specifications: for signature in format_specification.signatures: pattern_offset = signature.offset if pattern_offset is None: signature_flags = pysigscan.signature_flags.NO_OFFSET elif pattern_offset < 0: pattern_offset *= -1 signature_flags = pysigscan.signature_flags.RELATIVE_FROM_END else: signature_flags = pysigscan.signature_flags.RELATIVE_FROM_START signature_scanner.add_signature( signature.identifier, pattern_offset, signature.pattern, signature_flags) return signature_scanner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GetSpecificationStore(cls, format_category): """Retrieves the specification store for specified format category. Args: format_category (str): format category. Returns: tuple[FormatSpecificationStore, list[AnalyzerHelper]]: a format specification store and remaining analyzer helpers that do not have a format specification. """
specification_store = specification.FormatSpecificationStore() remainder_list = [] for analyzer_helper in iter(cls._analyzer_helpers.values()): if not analyzer_helper.IsEnabled(): continue if format_category in analyzer_helper.format_categories: format_specification = analyzer_helper.GetFormatSpecification() if format_specification is not None: specification_store.AddSpecification(format_specification) else: remainder_list.append(analyzer_helper) return specification_store, remainder_list