code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
obj = {} cls.add_if_not_none(obj, cls._FIELD_LATITUDE, geolocation.latitude) cls.add_if_not_none(obj, cls._FIELD_LONGITUDE, geolocation.longitude) cls.add_if_not_none(obj, cls._FIELD_ALTITUDE, geolocation.altitude) cls.add_if_not_none(obj, cls._FIELD_RADIUS, geolocatio...
def serialize(cls, geolocation)
:type geolocation: object_.Geolocation :rtype: dict
1.859212
1.898491
0.97931
if value is not None: dict_[key] = str(value)
def add_if_not_none(cls, dict_, key, value)
:type dict_: dict[str, str] :type key: str :type value: float :rtype: None
5.845136
3.423464
1.707375
label_monetary_account = converter.deserialize( object_.LabelMonetaryAccount, obj ) return target_class.create_from_label_monetary_account( label_monetary_account )
def deserialize(cls, target_class, obj)
:type target_class: object_.MonetaryAccountReference|type :type obj: dict :rtype: object_.MonetaryAccountReference
8.406882
6.071608
1.384622
share_detail = target_class.__new__(target_class) share_detail.__dict__ = { cls._ATTRIBUTE_PAYMENT: converter.deserialize( object_.ShareDetailPayment, cls._get_field_or_none(cls._FIELD_DRAFT_PAYMENT, obj) ), cls._ATTRIBUTE_REA...
def deserialize(cls, target_class, obj)
:type target_class: object_.ShareDetail|type :type obj: dict :rtype: object_.ShareDetail
3.048108
2.784739
1.094576
return { cls._FIELD_PAYMENT: converter.serialize( share_detail._payment_field_for_request), cls._FIELD_READ_ONLY: converter.serialize( share_detail._read_only_field_for_request), cls._FIELD_DRAFT_PAYMENT: converter.serialize( ...
def serialize(cls, share_detail)
:type share_detail: object_.ShareDetail :rtype: dict
4.656015
5.037582
0.924256
pagination = client.Pagination() pagination.__dict__.update( cls.parse_pagination_dict(pagination_response) ) return pagination
def deserialize(cls, target_class, pagination_response)
:type target_class: client.Pagination|type :type pagination_response: dict :rtype: client.Pagination
7.403392
6.101883
1.213296
pagination_dict = {} cls.update_dict_id_field_from_response_field( pagination_dict, cls._FIELD_OLDER_ID, response_obj, cls._FIELD_OLDER_URL, client.Pagination.PARAM_OLDER_ID ) cls.update_dict_id_field_from_response_fi...
def parse_pagination_dict(cls, response_obj)
:type response_obj: dict :rtype: dict
2.232042
2.229979
1.000925
url = response_obj[response_field] if url is not None: url_parsed = urlparse.urlparse(url) parameters = urlparse.parse_qs(url_parsed.query) dict_[dict_id_field] = int( parameters[response_param][cls._INDEX_FIRST] ) i...
def update_dict_id_field_from_response_field(cls, dict_, dict_id_field, response_obj, response_field, response_param)
:type dict_: dict :type dict_id_field: str :type response_obj: dict :type response_field: str :type response_param: str
3.237003
3.233055
1.001221
self._initialize_installation() self._register_device(device_description, permitted_ips) self._initialize_session()
def _initialize(self, device_description, permitted_ips)
:type device_description: str :type permitted_ips: list[str] :rtype: None
6.359007
6.311564
1.007517
private_key_client = security.generate_rsa_private_key() installation = core.Installation.create( self, security.public_key_to_string(private_key_client.publickey()) ).value token = installation.token.token public_key_server_string = \ ...
def _initialize_installation(self)
:rtype: None
4.489009
4.243366
1.057889
from bunq.sdk.model.device_server_internal import DeviceServerInternal DeviceServerInternal.create( device_description, self.api_key, permitted_ips, api_context=self )
def _register_device(self, device_description, permitted_ips)
:type device_description: str :type permitted_ips: list[] :rtype: None
7.586243
7.719211
0.982774
session_server = core.SessionServer.create(self).value token = session_server.token.token expiry_time = self._get_expiry_timestamp(session_server) user_id = session_server.get_referenced_user().id_ self._session_context = SessionContext(token, expiry_time, user_id)
def _initialize_session(self)
:rtype: None
7.075973
6.555167
1.07945
timeout_seconds = cls._get_session_timeout_seconds(session_server) time_now = datetime.datetime.now() return time_now + datetime.timedelta(seconds=timeout_seconds)
def _get_expiry_timestamp(cls, session_server)
:type session_server: core.SessionServer :rtype: datetime.datetime
3.173339
2.828446
1.121937
if session_server.user_company is not None: return session_server.user_company.session_timeout elif session_server.user_person is not None: return session_server.user_person.session_timeout elif session_server.user_api_key is not None: return session...
def _get_session_timeout_seconds(cls, session_server)
:type session_server: core.SessionServer :rtype: int
3.679429
3.484228
1.056024
if self.session_context is None: return False time_now = datetime.datetime.now() time_to_expiry = self.session_context.expiry_time - time_now time_to_expiry_minimum = datetime.timedelta( seconds=self._TIME_TO_SESSION_EXPIRY_MINIMUM_SECONDS ) ...
def is_session_active(self)
:rtype: bool
3.250199
2.946623
1.103025
if self._session_context is not None: return self.session_context.token elif self._installation_context is not None: return self.installation_context.token else: return None
def token(self)
:rtype: str
4.117177
3.431427
1.199844
if path is None: path = self._PATH_API_CONTEXT_DEFAULT with open(path, self._FILE_MODE_WRITE) as file_: file_.write(self.to_json())
def save(self, path=None)
:type path: str :rtype: None
6.018171
5.734375
1.04949
if path is None: path = cls._PATH_API_CONTEXT_DEFAULT with open(path, cls._FILE_MODE_READ) as file_: return cls.from_json(file_.read())
def restore(cls, path=None)
:type path: str :rtype: ApiContext
5.561227
4.09183
1.359105
cls._api_context = api_context cls._user_context = UserContext(api_context.session_context.user_id) cls._user_context.init_main_monetary_account()
def load_api_context(cls, api_context)
:type api_context: ApiContext
6.350336
5.712643
1.111628
import datetime import inspect from bunq.sdk import client from bunq.sdk import context from bunq.sdk.model import core from bunq.sdk.json import adapters from bunq.sdk.json import converter from bunq.sdk.model.generated import object_ from bunq.sdk.model.generated import endp...
def initialize_converter()
:rtype: None
2.360734
2.338269
1.009607
head_bytes = _generate_request_head_bytes(method, endpoint, headers) bytes_to_sign = head_bytes + body_bytes signer = PKCS1_v1_5.new(private_key) digest = SHA256.new() digest.update(bytes_to_sign) sign = signer.sign(digest) return b64encode(sign)
def sign_request(private_key, method, endpoint, body_bytes, headers)
:type private_key: RSA.RsaKey :type method: str :type endpoint: str :type body_bytes: bytes :type headers: dict[str, str] :rtype: str
2.392539
2.398876
0.997358
head_string = _FORMAT_METHOD_AND_ENDPOINT.format(method, endpoint) header_tuples = sorted((k, headers[k]) for k in headers) for name, value in header_tuples: if _should_sign_request_header(name): head_string += _FORMAT_HEADER_STRING.format(name, value) return (head_string + _...
def _generate_request_head_bytes(method, endpoint, headers)
:type method: str :type endpoint: str :type headers: dict[str, str] :rtype: bytes
3.753132
3.516824
1.067193
if header_name in {_HEADER_USER_AGENT, _HEADER_CACHE_CONTROL}: return True if re.match(_PATTERN_HEADER_PREFIX_BUNQ, header_name): return True return False
def _should_sign_request_header(header_name)
:type header_name: str :rtype: bool
6.817773
5.647274
1.207268
key = Random.get_random_bytes(_AES_KEY_SIZE) iv = Random.get_random_bytes(_BLOCK_SIZE) _add_header_client_encryption_key(api_context, key, custom_headers) _add_header_client_encryption_iv(iv, custom_headers) request_bytes = _encrypt_request_bytes(request_bytes, key, iv) _add_header_client_...
def encrypt(api_context, request_bytes, custom_headers)
:type api_context: bunq.sdk.context.ApiContext :type request_bytes: bytes :type custom_headers: dict[str, str] :rtype: bytes
2.918036
3.085069
0.945857
public_key_server = api_context.installation_context.public_key_server key_cipher = PKCS1_v1_5_Cipher.new(public_key_server) key_encrypted = key_cipher.encrypt(key) key_encrypted_base64 = base64.b64encode(key_encrypted).decode() custom_headers[_HEADER_CLIENT_ENCRYPTION_KEY] = key_encrypted_bas...
def _add_header_client_encryption_key(api_context, key, custom_headers)
:type api_context: bunq.sdk.context.ApiContext :type key: bytes :type custom_headers: dict[str, str] :rtype: None
2.969169
2.862663
1.037205
cipher = Cipher.AES.new(key, Cipher.AES.MODE_CBC, iv) request_bytes_padded = _pad_bytes(request_bytes) return cipher.encrypt(request_bytes_padded)
def _encrypt_request_bytes(request_bytes, key, iv)
:type request_bytes: bytes :type key: bytes :type iv: bytes :rtype: bytes
3.214006
3.131128
1.026469
padding_length = (_BLOCK_SIZE - len(request_bytes) % _BLOCK_SIZE) padding_character = bytes(bytearray([padding_length])) return request_bytes + padding_character * padding_length
def _pad_bytes(request_bytes)
:type request_bytes: bytes :rtype: bytes
3.196691
3.394854
0.941628
hashed = hmac.new(key, iv + request_bytes, sha1) hashed_base64 = base64.b64encode(hashed.digest()).decode() custom_headers[_HEADER_CLIENT_ENCRYPTION_HMAC] = hashed_base64
def _add_header_client_encryption_hmac(request_bytes, key, iv, custom_headers)
:type request_bytes: bytes :type key: bytes :type iv: bytes :type custom_headers: dict[str, str] :rtype: None
2.831303
2.998839
0.944133
head_bytes = _generate_response_head_bytes(status_code, headers) bytes_signed = head_bytes + body_bytes signer = PKCS1_v1_5.pkcs1_15.new(public_key_server) digest = SHA256.new() digest.update(bytes_signed) signer.verify(digest, base64.b64decode(headers[_HEADER_SERVER_SIGNATURE]))
def validate_response(public_key_server, status_code, body_bytes, headers)
:type public_key_server: RSA.RsaKey :type status_code: int :type body_bytes: bytes :type headers: dict[str, str] :rtype: None
3.464255
3.302855
1.048867
head_string = str(status_code) + _DELIMITER_NEWLINE header_tuples = sorted((k, headers[k]) for k in headers) for name, value in header_tuples: name = _get_header_correctly_cased(name) if _should_sign_response_header(name): head_string += _FORMAT_HEADER_STRING.format(name,...
def _generate_response_head_bytes(status_code, headers)
:type status_code: int :type headers: dict[str, str] :rtype: bytes
4.021459
3.905701
1.029638
header_name = header_name.capitalize() matches = re.findall(_REGEX_FOR_LOWERCASE_HEADERS, header_name) for match in matches: header_name = (re.sub(match, match.upper(), header_name)) return header_name
def _get_header_correctly_cased(header_name)
:type header_name: str :rtype: str
3.567371
3.352292
1.064159
if header_name == _HEADER_SERVER_SIGNATURE: return False if re.match(_PATTERN_HEADER_PREFIX_BUNQ, header_name): return True return False
def _should_sign_response_header(header_name)
:type header_name: str :rtype: bool
8.082378
6.548315
1.234268
sandbox_user = __generate_new_sandbox_user() return ApiContext( ApiEnvironmentType.SANDBOX, sandbox_user.api_key, socket.gethostname() )
def automatic_sandbox_install()
:rtype: ApiContext
10.136911
6.32549
1.60255
url = ApiEnvironmentType.SANDBOX.uri_base + __ENDPOINT_SANDBOX_USER headers = { ApiClient.HEADER_REQUEST_ID: __UNIQUE_REQUEST_ID, ApiClient.HEADER_CACHE_CONTROL: ApiClient._CACHE_CONTROL_NONE, ApiClient.HEADER_GEOLOCATION: ApiClient._GEOLOCATION_ZERO, ApiClient.HEADER_LANG...
def __generate_new_sandbox_user()
:rtype: endpoint.SandboxUser
4.322207
3.795435
1.138791
json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) value = converter.deserialize(cls, obj[cls._FIELD_RESPONSE]) return client.BunqResponse(value, response_raw.headers)
def _from_json_array_nested(cls, response_raw)
:type response_raw: client.BunqResponseRaw :rtype: bunq.sdk.client.BunqResponse[cls]
10.022992
7.79495
1.285831
json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) value = converter.deserialize( cls, cls._unwrap_response_single(obj, wrapper) ) return client.BunqResponse(value, response_raw.headers)
def _from_json(cls, response_raw, wrapper=None)
:type response_raw: client.BunqResponseRaw :type wrapper: str|None :rtype: client.BunqResponse[cls]
8.296427
7.228936
1.147669
if wrapper is not None: return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST][wrapper] return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST]
def _unwrap_response_single(cls, obj, wrapper=None)
:type obj: dict :type wrapper: str|None :rtype: dict
4.863892
4.475292
1.086832
json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) id_ = converter.deserialize( Id, cls._unwrap_response_single(obj, cls._FIELD_ID) ) return client.BunqResponse(id_.id_, response_raw.headers)
def _process_for_id(cls, response_raw)
:type response_raw: client.BunqResponseRaw :rtype: client.BunqResponse[int]
10.231139
8.837927
1.15764
json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) uuid = converter.deserialize( Uuid, cls._unwrap_response_single(obj, cls._FIELD_UUID) ) return client.BunqResponse(uuid.uuid, response_raw.headers)
def _process_for_uuid(cls, response_raw)
:type response_raw: client.BunqResponseRaw :rtype: client.BunqResponse[str]
9.739377
8.359808
1.165024
json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) array = obj[cls._FIELD_RESPONSE] array_deserialized = [] for item in array: item_unwrapped = item if wrapper is None else item[wrapper] item_deserialized = convert...
def _from_json_list(cls, response_raw, wrapper=None)
:type response_raw: client.BunqResponseRaw :type wrapper: str|None :rtype: client.BunqResponse[list[cls]]
4.394794
3.803921
1.155332
if monetary_account_id is None: return context.BunqContext.user_context().primary_monetary_account.id_ return monetary_account_id
def _determine_monetary_account_id(cls, monetary_account_id=None)
:type monetary_account_id: int :rtype: int
5.991033
6.204513
0.965593
api_client = client.ApiClient(api_context) body_bytes = cls.generate_request_body_bytes( public_key_string ) response_raw = api_client.post(cls._ENDPOINT_URL_POST, body_bytes, {}) return cls._from_json_array_nested(response_raw)
def create(cls, api_context, public_key_string)
:type api_context: bunq.sdk.context.ApiContext :type public_key_string: str :rtype: client.BunqResponse[Installation]
5.47397
5.261506
1.040381
if self._user_person is not None: return self._user_person if self._user_company is not None: return self._user_company if self._user_api_key is not None: return self._user_api_key raise BunqException(self._ERROR_ALL_FIELD_IS_NULL)
def get_referenced_user(self)
:rtype: BunqModel
3.574015
2.836959
1.259805
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
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/...
4.137726
4.083937
1.013171
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 res...
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 ...
3.033103
2.922444
1.037865
transform = None try: transform = load_object(transform_py_name)() if os.name == 'posix' and transform.superuser and os.geteuid(): rc = sudo(sys.argv) if rc == 1: message_writer(MaltegoTransformResponseMessage() + UIMessage('User cancelled transform...
def local_transform_runner(transform_py_name, value, fields, params, config, message_writer=message)
Internal API: The local transform runner is responsible for executing the local transform. Parameters: transform - The name or module of the transform to execute (i.e sploitego.transforms.whatismyip). value - The input entity value. fields - A dict of the field names and their re...
4.530871
4.264593
1.062439
tab += 1 if isinstance(msg, Model): msg = fromstring(msg.render(encoding='utf-8')) print('%s`- %s: %s %s' % ( ' ' * tab, click.style(msg.tag, bold=True), click.style(msg.text, fg='red') if msg.text is not None else '', click.style(repr(msg.attrib), fg='green',...
def console_writer(msg, tab=-1)
Internal API: Returns a prettified tree-based output of an XML message for debugging purposes. This helper function is used by the debug-transform command.
2.328649
2.250115
1.034902
return boolbox(msg, title, choices, image=image)
def ynbox(msg="Shall I continue?" , title=" " , choices=("Yes", "No") , image=None )
Display a msgbox with choices of Yes and No. The default is "Yes". The returned value is calculated this way:: if the first choice ("Yes") is chosen, or if the dialog is cancelled: return 1 else: return 0 If invoked without a msg argument, displays a generic reques...
5.305628
27.891972
0.190221
return boolbox(msg, title, choices, image=image)
def ccbox(msg="Shall I continue?" , title=" " , choices=("Continue", "Cancel") , image=None )
Display a msgbox with choices of Continue and Cancel. The default is "Continue". The returned value is calculated this way:: if the first choice ("Continue") is chosen, or if the dialog is cancelled: return 1 else: return 0 If invoked without a msg argument, displa...
5.088627
27.262482
0.186653
reply = buttonbox(msg=msg, choices=choices, title=title, image=image) if reply == choices[0]: return 1 else: return 0
def boolbox(msg="Shall I continue?" , title=" " , choices=("Yes","No") , image=None )
Display a boolean msgbox. The default is the first choice. The returned value is calculated this way:: if the first choice is chosen, or if the dialog is cancelled: returns 1 else: returns 0
2.648368
3.873197
0.683768
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.")
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.
5.509401
5.871893
0.938267
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)
def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None)
Display a messagebox
3.633652
3.710203
0.979367
if sys.platform == 'darwin': _bring_to_front() global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame # Initialize __replyButtonText to the first choice. # This is what will be used if the window is closed by the close button. __replyButtonText = choices[0] if root: ...
def buttonbox(msg="",title=" " ,choices=("Button1", "Button2", "Button3") , image=None , root=None )
Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg to be displayed. @arg title: the window title @arg choices: a list or tuple of the choices to be displayed
3.144359
3.247599
0.968211
if sys.platform == 'darwin': _bring_to_front() if "argLowerBound" in invalidKeywordArguments: raise AssertionError( "\nintegerbox no longer supports the 'argLowerBound' argument.\n" + "Use 'lowerbound' instead.\n\n") if "argUpperBound" in invalidKeywordArguments:...
def integerbox(msg="" , title=" " , default="" , lowerbound=0 , upperbound=99 , image = None , root = None , **invalidKeywordArguments )
Show a box in which a user can enter an integer. In addition to arguments for msg and title, this function accepts integer arguments for "default", "lowerbound", and "upperbound". The default argument may be None. When the user enters some text, the text is checked to verify that it can be conver...
2.3258
2.273727
1.022902
r return __multfillablebox(msg,title,fields,values,"*")
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 accept...
20.91123
53.264751
0.39259
result = __fillablebox(msg, title, default=default, mask=None,image=image,root=root) if result and strip: result = result.strip() return result
def enterbox(msg="Enter something." , title=" " , default="" , strip=True , image=None , root=None )
Show a box in which a user can enter some text. You may optionally specify some default text, which will appear in the enterbox when it is displayed. Returns the text that the user entered, or None if he cancels the operation. By default, enterbox strips its result (i.e. removes leading and trailing ...
5.489161
9.383274
0.584994
return __fillablebox(msg, title, default, mask="*",image=image,root=root)
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.
11.256577
12.103391
0.930035
if len(choices) == 0: choices = ["Program logic error - no choices were specified."] global __choiceboxMultipleSelect __choiceboxMultipleSelect = 1 return __choicebox(msg, title, choices)
def multchoicebox(msg="Pick as many items as you like." , title=" " , choices=() , **kwargs )
Present the user with a list of choices. allow him to select multiple items and return them in a list. if the user doesn't choose anything from the list, return the empty list. return None if he cancelled selection. @arg msg: the msg to be displayed. @arg title: the window title @arg choices: a...
9.459044
13.191953
0.717031
if len(choices) == 0: choices = ["Program logic error - no choices were specified."] global __choiceboxMultipleSelect __choiceboxMultipleSelect = 0 return __choicebox(msg,title,choices)
def choicebox(msg="Pick something." , title=" " , choices=() )
Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection. @arg msg: the msg to be displayed. @arg title: the window title @arg choices: a list or tuple of the choices to be displayed
7.911793
13.162625
0.60108
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...
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.
3.952541
4.692076
0.842386
if sys.platform == 'darwin': _bring_to_front() localRoot = Tk() localRoot.withdraw() initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes) #------------------------------------------------------------ # if initialfile contains no wildcards; we don't wan...
def fileopenbox(msg=None , title=None , default="*" , filetypes=None )
A dialog to get a file name. About the "default" argument ============================ The "default" argument specifies a filepath that (normally) contains one or more wildcards. fileopenbox will display only files that match the default filepath. If omitted, defaults to "*" (al...
4.720273
5.166422
0.913644
global boxRoot, __widgetTexts, __replyButtonText __replyButtonText = __widgetTexts[event.widget] boxRoot.quit()
def __buttonEvent(event)
Handle an event that is generated by a person clicking a button.
23.664099
23.763927
0.995799
v = MaltegoMessage(message=msg).render(encoding='utf-8') return Response(v, status=200, mimetype='text/xml')
def message(msg)
Write a MaltegoMessage to stdout and exit successfully
12.172861
7.943179
1.532492
def exit_function(*args): func() exit(0) signal.signal(signal.SIGTERM, exit_function)
def on_terminate(func)
Register a signal handler to execute when Maltego forcibly terminates the transform.
3.605646
3.597311
1.002317
if sys.platform == 'win32': decoding = sys.stdout.encoding if sys.version_info[0] > 2 else 'cp1252' click.echo(MaltegoMessage(message=m).render(fragment=True, encoding='utf-8').decode(decoding), file=fd) else: click.echo(MaltegoMessage(message=m).render(encoding='utf-8', fragment=T...
def message(m, fd=sys.stdout)
Write a MaltegoMessage to stdout and exit successfully
3.454584
3.103293
1.113199
if isinstance(error, MaltegoException): message_writer(MaltegoTransformExceptionMessage(exceptions=[error])) else: message_writer(MaltegoTransformExceptionMessage(exceptions=[MaltegoException(error)]))
def croak(error, message_writer=message)
Throw an exception in the Maltego GUI containing error_msg.
4.54015
3.04332
1.491841
e = entity_type(value) for k, v in fields.items(): e.fields[k] = Field(k, v) return e
def to_entity(entity_type, value, fields)
Internal API: Returns an instance of an entity of type entity_type with the specified value and fields (stored in dict). This is only used by the local transform runner as a helper function.
3.550197
3.508225
1.011964
if sys.version_info[0] > 3: spec = inspect.getfullargspec(transform) else: spec = inspect.getargspec(transform) if spec.varargs: return 3 n = len(spec.args) if 2 <= n <= 3: return n raise Exception('Could not determine transform version.')
def get_transform_version(transform)
Internal API: Returns the version of the transform function based on the transform function's signature. Currently, only two versions are supported (2 and 3). This is what version 2 transform functions look like: def transform(request, response): ... Version 3 transforms have the additional config...
3.256932
2.748345
1.185052
for i in args: click.echo('D:%s' % str(i), err=True)
def debug(*args)
Send debug messages to the Maltego console.
7.345047
7.064711
1.039681
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)
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.
3.241109
2.982564
1.086686
from canari.commands.create_package import create_package create_package(package, author, email, description, create_example)
def create_package(package, author, email, description, create_example)
Creates a Canari transform package skeleton.
4.761158
2.979909
1.597753
from canari.commands.create_profile import create_profile create_profile(ctx.config_dir, ctx.project, package)
def create_profile(ctx, package)
Creates an importable Maltego profile (*.mtz) file.
9.39035
9.652221
0.972869
from canari.commands.create_transform import create_transform create_transform(ctx.project, transform)
def create_transform(ctx, transform)
Creates a new transform in the specified directory and auto-updates dependencies.
13.146358
9.961802
1.319677
from canari.commands.debug_transform import debug_transform debug_transform(transform, value, fields, params, ctx.project, ctx.config)
def debug_transform(ctx, transform, params, value, fields)
Runs Canari local transforms in a terminal-friendly fashion.
9.695469
7.637939
1.269383
from canari.commands.dockerize_package import dockerize_package dockerize_package(ctx.project, os, host)
def dockerize_package(ctx, os, host)
Creates a Docker build file pre-configured with Plume.
9.181887
8.798799
1.043539
from canari.commands.generate_entities import generate_entities generate_entities( ctx.project, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity)
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.
4.088519
3.706028
1.103208
from canari.commands.generate_entities_doc import generate_entities_doc generate_entities_doc(ctx.project, out_path, package)
def generate_entities_doc(ctx, out_path, package)
Create entities documentation from Canari python classes file.
5.290452
3.426171
1.54413
from canari.commands.load_plume_package import load_plume_package load_plume_package(package, plume_dir, accept_defaults)
def load_plume_package(package, plume_dir, accept_defaults)
Loads a canari package into Plume.
3.978723
2.507107
1.586977
from canari.commands.remote_transform import remote_transform remote_transform(host, transform, input, entity_field, transform_parameter, raw_output, ssl, base_path, soft_limit, hard_limit, verbose)
def remote_transform(host, transform, input, entity_field, transform_parameter, raw_output, ssl, base_path, soft_limit, hard_limit, verbose)
Runs Canari local transforms in a terminal-friendly fashion.
2.600729
2.255694
1.152962
ctx.mode = CanariMode.LocalShellDebug from canari.commands.shell import shell shell(package, working_dir, sudo)
def shell(ctx, package, working_dir, sudo)
Runs a Canari interactive python shell
18.245296
11.354026
1.606945
from canari.commands.unload_plume_package import unload_plume_package unload_plume_package(package, plume_dir)
def unload_plume_package(package, plume_dir)
Unloads a canari package from Plume.
4.204894
2.816002
1.493214
global canari_mode old_mode = canari_mode canari_mode = mode return old_mode
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.
3.362943
4.158606
0.808671
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 ...
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,...
2.680572
2.572993
1.041811
@wraps(fun) def measure_time(*args, **kwargs): t1 = timer() result = fun(*args, **kwargs) t2 = timer() print("@timefun:" + fun.__name__ + " took " + str(t2 - t1) + " seconds") return result return measure_time
def timefun(fun)
Timing decorator Timers require you to do some digging. Start wrapping a few of the higher level functions and confirm where the bottleneck is, then drill down into that function, repeating as you go. When you find the disproportionately slow bit of code, fix it, and work your way back out confirming t...
2.155505
2.879753
0.748504
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
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 ...
1.646042
2.48379
0.662714
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)
def convolve(sequence, rule, **kwds)
Wrapper around scipy.ndimage.convolve1d that allows complex input.
2.428655
2.158247
1.125291
def linfun(i): return np.linspace(0, np.pi / 2., 2**i + 1) dea = EpsAlg(limexp=15) print('NO. PANELS TRAP. APPROX APPROX W/EA abserr') txt = '{0:5d} {1:20.8f} {2:20.8f} {3:20.8f}' for k in np.arange(10): x = linfun(k) val = np.trapz(np.sin(x), x...
def epsalg_demo()
>>> epsalg_demo() NO. PANELS TRAP. APPROX APPROX W/EA abserr 1 0.78539816 0.78539816 0.21460184 2 0.94805945 0.94805945 0.05194055 4 0.98711580 0.99945672 0.00054328 ...
5.72242
3.544278
1.614552
def linfun(i): return np.linspace(0, np.pi / 2., 2**i + 1) dea = Dea(limexp=6) print('NO. PANELS TRAP. APPROX APPROX W/EA abserr') txt = '{0:5d} {1:20.8f} {2:20.8f} {3:20.8f}' for k in np.arange(12): x = linfun(k) val = np.trapz(np.sin(x), x) ...
def dea_demo()
>>> dea_demo() NO. PANELS TRAP. APPROX APPROX W/EA abserr 1 0.78539816 0.78539816 0.78539816 2 0.94805945 0.94805945 0.97596771 4 0.98711580 0.99945672 0.21405856 ...
6.286397
3.571503
1.760155
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) *...
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 a...
3.441959
3.467069
0.992758
_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 = c...
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 (onl...
3.203941
3.362466
0.952855
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' ...
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
5.820941
6.01152
0.968298
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]...
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
2.905005
2.723455
1.066662
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] ...
def _multicomplex2(f, fx, x, h)
Calculate Hessian with Bicomplex-step derivative approximation
4.229984
3.76339
1.123982
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 +...
def _central_even(f, fx, x, h)
Eq 9.
2.003179
1.971873
1.015877
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, ...
def _central2(f, fx, x, h)
Eq. 8
2.274419
2.235142
1.017573
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)
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: ar...
3.178294
3.938895
0.8069
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
def valarray(shape, value=np.NaN, typecode=None)
Return an array of all value.
2.865672
2.767511
1.035469
if x is None: return 1.0 return np.log1p(np.abs(x)).clip(min=1.0)
def nominal_step(x=None)
Return nominal step
4.6502
4.285447
1.085115
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_ste...
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 me...
4.58046
4.259216
1.075423
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 = convol...
def apply(self, f_del, h)
Apply finite difference rule along the first axis.
6.883742
6.192999
1.111536