body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
ab2cac1617e5f7db3a7eef308b961a860b3b10fe647606e486a5828d7391bd5b | def Printing_summary(PDB_filename, Output, water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list):
'\n Prints a summary of the processing of the PDB file prior to the PELE\n simulation. It includes the number of water molecules found and the \n unconventional molecules found.\n\n PARAMETERS\n ----------\n PDB_filename : string\n filename of the input PDB file that wants to be processed\n Output : string\n filename of the output PDB file after processing\n water_i : integer\n number of water molecules found in the PDB input file\n Non_aminoacid_dict : dictionary\n dicitonary with the key:item pair being the unconventional AA and the number of instances\n HXT_terminal : boolean\n The HXT atom name is present in the C-terminal residue of the protein chain/s (when True)\n Gly_to_other_residue : boolean / list\n The list of new residues mutated have the HA2 atom name to the HA atom name due to the previous Gly residue (when True)\n ASH_list : boolean / list\n The list of ASH residues (ASP with HD2) in the protein chain/s (when True)\n GLH_list : boolean / list\n The list of GLH residues (GLU with HD2) in the protein chain/s (when True) \n\n RETURNS\n -------\n PDB modified file\n '
Screen_ticks = 10
if (Output != ''):
print(((('\n{} has been succesfully processed and written to {}.pdb\n\n'.format(PDB_filename, Output) + ('-' * Screen_ticks)) + 'SUMMARY') + ('-' * Screen_ticks)))
else:
os.system('rm {}'.format(PDB_filename))
os.system('mv {}_modified.pdb {}'.format(PDB_filename[:(- 4)], PDB_filename))
print(((('\n{} has been succesfully processed and overwritten\n\n'.format(PDB_filename) + ('-' * Screen_ticks)) + 'SUMMARY') + ('-' * Screen_ticks)))
if (water_i == 0):
print('\nNo water molecules were found in the PDB file')
elif (water_i == 1):
print('\n{} water molecule was found in the PDB file'.format(water_i))
else:
print('\n{} water molecules were found in the PDB file'.format(water_i))
if HXT_terminal:
print('\nThe C-terminal residue contained the HXT atom name automatically put by Maestro/Schrödinger. Be aware! (Modified by the code)')
if Gly_to_other_residue:
print('\nThe following residues contained the typical HA2 atom name from a GLY residue but were another residue: {}. (Modified by the code)'.format(Gly_to_other_residue))
if other_residue_to_Gly:
print('\nThe following residues contained the typical HA atom name from any residue, apart from GLY and they are a GLY residue: {}. (Modified by the code)'.format(other_residue_to_Gly))
if ASH_list:
print('\nThe following residues are really ASH residues: {}. (Modified manually by the user)'.format(ASH_list))
if GLH_list:
print('\nThe following residues are really GLH residues: {}. (Modified manually by the user)'.format(GLH_list))
if (Non_aminoacid_dict != {}):
print('\nThe following ligands and cofactors were found in the PDB file\n')
for ligand in Non_aminoacid_dict.keys():
print((((ligand + ': ') + str(Non_aminoacid_dict[ligand])) + ' molecule/s\n')) | Prints a summary of the processing of the PDB file prior to the PELE
simulation. It includes the number of water molecules found and the
unconventional molecules found.
PARAMETERS
----------
PDB_filename : string
filename of the input PDB file that wants to be processed
Output : string
filename of the output PDB file after processing
water_i : integer
number of water molecules found in the PDB input file
Non_aminoacid_dict : dictionary
dicitonary with the key:item pair being the unconventional AA and the number of instances
HXT_terminal : boolean
The HXT atom name is present in the C-terminal residue of the protein chain/s (when True)
Gly_to_other_residue : boolean / list
The list of new residues mutated have the HA2 atom name to the HA atom name due to the previous Gly residue (when True)
ASH_list : boolean / list
The list of ASH residues (ASP with HD2) in the protein chain/s (when True)
GLH_list : boolean / list
The list of GLH residues (GLU with HD2) in the protein chain/s (when True)
RETURNS
-------
PDB modified file | PELEAnalysis-Processing/Preprocessing/PDBProcessor4PELE.py | Printing_summary | SergiR1996/PELEAnalysis-Processing | 3 | python | def Printing_summary(PDB_filename, Output, water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list):
'\n Prints a summary of the processing of the PDB file prior to the PELE\n simulation. It includes the number of water molecules found and the \n unconventional molecules found.\n\n PARAMETERS\n ----------\n PDB_filename : string\n filename of the input PDB file that wants to be processed\n Output : string\n filename of the output PDB file after processing\n water_i : integer\n number of water molecules found in the PDB input file\n Non_aminoacid_dict : dictionary\n dicitonary with the key:item pair being the unconventional AA and the number of instances\n HXT_terminal : boolean\n The HXT atom name is present in the C-terminal residue of the protein chain/s (when True)\n Gly_to_other_residue : boolean / list\n The list of new residues mutated have the HA2 atom name to the HA atom name due to the previous Gly residue (when True)\n ASH_list : boolean / list\n The list of ASH residues (ASP with HD2) in the protein chain/s (when True)\n GLH_list : boolean / list\n The list of GLH residues (GLU with HD2) in the protein chain/s (when True) \n\n RETURNS\n -------\n PDB modified file\n '
Screen_ticks = 10
if (Output != ):
print(((('\n{} has been succesfully processed and written to {}.pdb\n\n'.format(PDB_filename, Output) + ('-' * Screen_ticks)) + 'SUMMARY') + ('-' * Screen_ticks)))
else:
os.system('rm {}'.format(PDB_filename))
os.system('mv {}_modified.pdb {}'.format(PDB_filename[:(- 4)], PDB_filename))
print(((('\n{} has been succesfully processed and overwritten\n\n'.format(PDB_filename) + ('-' * Screen_ticks)) + 'SUMMARY') + ('-' * Screen_ticks)))
if (water_i == 0):
print('\nNo water molecules were found in the PDB file')
elif (water_i == 1):
print('\n{} water molecule was found in the PDB file'.format(water_i))
else:
print('\n{} water molecules were found in the PDB file'.format(water_i))
if HXT_terminal:
print('\nThe C-terminal residue contained the HXT atom name automatically put by Maestro/Schrödinger. Be aware! (Modified by the code)')
if Gly_to_other_residue:
print('\nThe following residues contained the typical HA2 atom name from a GLY residue but were another residue: {}. (Modified by the code)'.format(Gly_to_other_residue))
if other_residue_to_Gly:
print('\nThe following residues contained the typical HA atom name from any residue, apart from GLY and they are a GLY residue: {}. (Modified by the code)'.format(other_residue_to_Gly))
if ASH_list:
print('\nThe following residues are really ASH residues: {}. (Modified manually by the user)'.format(ASH_list))
if GLH_list:
print('\nThe following residues are really GLH residues: {}. (Modified manually by the user)'.format(GLH_list))
if (Non_aminoacid_dict != {}):
print('\nThe following ligands and cofactors were found in the PDB file\n')
for ligand in Non_aminoacid_dict.keys():
print((((ligand + ': ') + str(Non_aminoacid_dict[ligand])) + ' molecule/s\n')) | def Printing_summary(PDB_filename, Output, water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list):
'\n Prints a summary of the processing of the PDB file prior to the PELE\n simulation. It includes the number of water molecules found and the \n unconventional molecules found.\n\n PARAMETERS\n ----------\n PDB_filename : string\n filename of the input PDB file that wants to be processed\n Output : string\n filename of the output PDB file after processing\n water_i : integer\n number of water molecules found in the PDB input file\n Non_aminoacid_dict : dictionary\n dicitonary with the key:item pair being the unconventional AA and the number of instances\n HXT_terminal : boolean\n The HXT atom name is present in the C-terminal residue of the protein chain/s (when True)\n Gly_to_other_residue : boolean / list\n The list of new residues mutated have the HA2 atom name to the HA atom name due to the previous Gly residue (when True)\n ASH_list : boolean / list\n The list of ASH residues (ASP with HD2) in the protein chain/s (when True)\n GLH_list : boolean / list\n The list of GLH residues (GLU with HD2) in the protein chain/s (when True) \n\n RETURNS\n -------\n PDB modified file\n '
Screen_ticks = 10
if (Output != ):
print(((('\n{} has been succesfully processed and written to {}.pdb\n\n'.format(PDB_filename, Output) + ('-' * Screen_ticks)) + 'SUMMARY') + ('-' * Screen_ticks)))
else:
os.system('rm {}'.format(PDB_filename))
os.system('mv {}_modified.pdb {}'.format(PDB_filename[:(- 4)], PDB_filename))
print(((('\n{} has been succesfully processed and overwritten\n\n'.format(PDB_filename) + ('-' * Screen_ticks)) + 'SUMMARY') + ('-' * Screen_ticks)))
if (water_i == 0):
print('\nNo water molecules were found in the PDB file')
elif (water_i == 1):
print('\n{} water molecule was found in the PDB file'.format(water_i))
else:
print('\n{} water molecules were found in the PDB file'.format(water_i))
if HXT_terminal:
print('\nThe C-terminal residue contained the HXT atom name automatically put by Maestro/Schrödinger. Be aware! (Modified by the code)')
if Gly_to_other_residue:
print('\nThe following residues contained the typical HA2 atom name from a GLY residue but were another residue: {}. (Modified by the code)'.format(Gly_to_other_residue))
if other_residue_to_Gly:
print('\nThe following residues contained the typical HA atom name from any residue, apart from GLY and they are a GLY residue: {}. (Modified by the code)'.format(other_residue_to_Gly))
if ASH_list:
print('\nThe following residues are really ASH residues: {}. (Modified manually by the user)'.format(ASH_list))
if GLH_list:
print('\nThe following residues are really GLH residues: {}. (Modified manually by the user)'.format(GLH_list))
if (Non_aminoacid_dict != {}):
print('\nThe following ligands and cofactors were found in the PDB file\n')
for ligand in Non_aminoacid_dict.keys():
print((((ligand + ': ') + str(Non_aminoacid_dict[ligand])) + ' molecule/s\n'))<|docstring|>Prints a summary of the processing of the PDB file prior to the PELE
simulation. It includes the number of water molecules found and the
unconventional molecules found.
PARAMETERS
----------
PDB_filename : string
filename of the input PDB file that wants to be processed
Output : string
filename of the output PDB file after processing
water_i : integer
number of water molecules found in the PDB input file
Non_aminoacid_dict : dictionary
dicitonary with the key:item pair being the unconventional AA and the number of instances
HXT_terminal : boolean
The HXT atom name is present in the C-terminal residue of the protein chain/s (when True)
Gly_to_other_residue : boolean / list
The list of new residues mutated have the HA2 atom name to the HA atom name due to the previous Gly residue (when True)
ASH_list : boolean / list
The list of ASH residues (ASP with HD2) in the protein chain/s (when True)
GLH_list : boolean / list
The list of GLH residues (GLU with HD2) in the protein chain/s (when True)
RETURNS
-------
PDB modified file<|endoftext|> |
73959aaac927f1247301150714d74df8c87c9c2a0a617ff070332148ce11b91c | def main():
'\n Main function\n\n It is called when this script is the main program called by the interpreter\n '
(PDBs, Output, Residue_name) = parseArgs()
for PDB_filename in PDBs:
(water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list) = PDB_processing(PDB_filename, Output, Residue_name)
Printing_summary(PDB_filename, Output, water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list) | Main function
It is called when this script is the main program called by the interpreter | PELEAnalysis-Processing/Preprocessing/PDBProcessor4PELE.py | main | SergiR1996/PELEAnalysis-Processing | 3 | python | def main():
'\n Main function\n\n It is called when this script is the main program called by the interpreter\n '
(PDBs, Output, Residue_name) = parseArgs()
for PDB_filename in PDBs:
(water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list) = PDB_processing(PDB_filename, Output, Residue_name)
Printing_summary(PDB_filename, Output, water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list) | def main():
'\n Main function\n\n It is called when this script is the main program called by the interpreter\n '
(PDBs, Output, Residue_name) = parseArgs()
for PDB_filename in PDBs:
(water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list) = PDB_processing(PDB_filename, Output, Residue_name)
Printing_summary(PDB_filename, Output, water_i, Non_aminoacid_dict, HXT_terminal, Gly_to_other_residue, other_residue_to_Gly, ASH_list, GLH_list)<|docstring|>Main function
It is called when this script is the main program called by the interpreter<|endoftext|> |
e21b2d4e7dc631f0ee67bfa21d84e96c50848f6fbba1088cba75fbcda589290c | def __init__(self, settings):
'creates session connection to XenAPI. Connects using admin login/password from settings\n :param authenticator: authorized authenticator object\n '
if ('debug' in settings):
self.debug = bool(settings['debug'])
self.init_log()
try:
url = settings['url']
username = settings['username']
password = settings['password']
except KeyError as e:
raise XenAdapterArgumentError(self.log, f'Failed to parse settings: {str(e)}')
self.username = username
try:
self.session = XenAPI.Session(url)
self.session.xenapi.login_with_password(username, password)
self.log.info(f'Authentication is successful. XenAdapter object created in thread {threading.get_ident()}')
self.api = self.session.xenapi
self.url = url
except OSError as e:
raise XenAdapterConnectionError(self.log, f'Unable to reach XenServer at {url}: {str(e)}')
except XenAPI.Failure as e:
raise XenAdapterConnectionError(self.log, f'Failed to login: url: "{url}"; username: "{username}"; password: "{password}"; error: {str(e)}')
self.conn = r.connect(settings['host'], settings['port'], db=settings['database']).repl()
if (not (settings['database'] in r.db_list().run())):
r.db_create(settings['database']).run()
self.db = r.db(settings['database']) | creates session connection to XenAPI. Connects using admin login/password from settings
:param authenticator: authorized authenticator object | xenadapter/__init__.py | __init__ | pashazz/vmemperor | 1 | python | def __init__(self, settings):
'creates session connection to XenAPI. Connects using admin login/password from settings\n :param authenticator: authorized authenticator object\n '
if ('debug' in settings):
self.debug = bool(settings['debug'])
self.init_log()
try:
url = settings['url']
username = settings['username']
password = settings['password']
except KeyError as e:
raise XenAdapterArgumentError(self.log, f'Failed to parse settings: {str(e)}')
self.username = username
try:
self.session = XenAPI.Session(url)
self.session.xenapi.login_with_password(username, password)
self.log.info(f'Authentication is successful. XenAdapter object created in thread {threading.get_ident()}')
self.api = self.session.xenapi
self.url = url
except OSError as e:
raise XenAdapterConnectionError(self.log, f'Unable to reach XenServer at {url}: {str(e)}')
except XenAPI.Failure as e:
raise XenAdapterConnectionError(self.log, f'Failed to login: url: "{url}"; username: "{username}"; password: "{password}"; error: {str(e)}')
self.conn = r.connect(settings['host'], settings['port'], db=settings['database']).repl()
if (not (settings['database'] in r.db_list().run())):
r.db_create(settings['database']).run()
self.db = r.db(settings['database']) | def __init__(self, settings):
'creates session connection to XenAPI. Connects using admin login/password from settings\n :param authenticator: authorized authenticator object\n '
if ('debug' in settings):
self.debug = bool(settings['debug'])
self.init_log()
try:
url = settings['url']
username = settings['username']
password = settings['password']
except KeyError as e:
raise XenAdapterArgumentError(self.log, f'Failed to parse settings: {str(e)}')
self.username = username
try:
self.session = XenAPI.Session(url)
self.session.xenapi.login_with_password(username, password)
self.log.info(f'Authentication is successful. XenAdapter object created in thread {threading.get_ident()}')
self.api = self.session.xenapi
self.url = url
except OSError as e:
raise XenAdapterConnectionError(self.log, f'Unable to reach XenServer at {url}: {str(e)}')
except XenAPI.Failure as e:
raise XenAdapterConnectionError(self.log, f'Failed to login: url: "{url}"; username: "{username}"; password: "{password}"; error: {str(e)}')
self.conn = r.connect(settings['host'], settings['port'], db=settings['database']).repl()
if (not (settings['database'] in r.db_list().run())):
r.db_create(settings['database']).run()
self.db = r.db(settings['database'])<|docstring|>creates session connection to XenAPI. Connects using admin login/password from settings
:param authenticator: authorized authenticator object<|endoftext|> |
69b94b205e817d5fae509eaa95d6838c9bdae0d862a179f949154e46d47e4135 | def __init__(self, component: Component, id_: str, chain_id: str):
'\n :param component: A component of which this compin is an instance.\n :param id_: Unique ID of the compin.\n :param chain_id: ID of the client to whose chain this compin belongs. For Unmanaged compins must be equal to id.\n '
self.component: Component = component
self.id: str = id_
self._ip: Optional[str] = None
self._chain_id: str = chain_id
self._dependencies: Dict[(str, 'ManagedCompin')] = {} | :param component: A component of which this compin is an instance.
:param id_: Unique ID of the compin.
:param chain_id: ID of the client to whose chain this compin belongs. For Unmanaged compins must be equal to id. | cloud_controller/knowledge/instance.py | __init__ | smartarch/qoscloud | 2 | python | def __init__(self, component: Component, id_: str, chain_id: str):
'\n :param component: A component of which this compin is an instance.\n :param id_: Unique ID of the compin.\n :param chain_id: ID of the client to whose chain this compin belongs. For Unmanaged compins must be equal to id.\n '
self.component: Component = component
self.id: str = id_
self._ip: Optional[str] = None
self._chain_id: str = chain_id
self._dependencies: Dict[(str, 'ManagedCompin')] = {} | def __init__(self, component: Component, id_: str, chain_id: str):
'\n :param component: A component of which this compin is an instance.\n :param id_: Unique ID of the compin.\n :param chain_id: ID of the client to whose chain this compin belongs. For Unmanaged compins must be equal to id.\n '
self.component: Component = component
self.id: str = id_
self._ip: Optional[str] = None
self._chain_id: str = chain_id
self._dependencies: Dict[(str, 'ManagedCompin')] = {}<|docstring|>:param component: A component of which this compin is an instance.
:param id_: Unique ID of the compin.
:param chain_id: ID of the client to whose chain this compin belongs. For Unmanaged compins must be equal to id.<|endoftext|> |
72c687401a706dd470f78585993972b5b7bd8ac075c86631ab5bf3899ea7256d | @property
def chain_id(self) -> str:
'ID of the client for which this compin was created'
return self._chain_id | ID of the client for which this compin was created | cloud_controller/knowledge/instance.py | chain_id | smartarch/qoscloud | 2 | python | @property
def chain_id(self) -> str:
return self._chain_id | @property
def chain_id(self) -> str:
return self._chain_id<|docstring|>ID of the client for which this compin was created<|endoftext|> |
0f0362a90a923c8193615ff3f9ef12c3587d5fb6d7e96cf6783b7c81e13f42bd | def set_dependency(self, compin: 'ManagedCompin') -> None:
"\n Sets the provided Managed compin as a dependency of this compin. Will raise an exception if this compin does\n not have a dependency on the given managed compin's component.\n "
if (compin.component in self.component.dependencies):
if (compin.component.name in self._dependencies):
self._dependencies[compin.component.name].dependants.remove(self)
self._dependencies[compin.component.name] = compin
compin.dependants.append(self)
else:
raise Exception(f'Component {self.component.name} does not have dependency {compin.component.name}') | Sets the provided Managed compin as a dependency of this compin. Will raise an exception if this compin does
not have a dependency on the given managed compin's component. | cloud_controller/knowledge/instance.py | set_dependency | smartarch/qoscloud | 2 | python | def set_dependency(self, compin: 'ManagedCompin') -> None:
"\n Sets the provided Managed compin as a dependency of this compin. Will raise an exception if this compin does\n not have a dependency on the given managed compin's component.\n "
if (compin.component in self.component.dependencies):
if (compin.component.name in self._dependencies):
self._dependencies[compin.component.name].dependants.remove(self)
self._dependencies[compin.component.name] = compin
compin.dependants.append(self)
else:
raise Exception(f'Component {self.component.name} does not have dependency {compin.component.name}') | def set_dependency(self, compin: 'ManagedCompin') -> None:
"\n Sets the provided Managed compin as a dependency of this compin. Will raise an exception if this compin does\n not have a dependency on the given managed compin's component.\n "
if (compin.component in self.component.dependencies):
if (compin.component.name in self._dependencies):
self._dependencies[compin.component.name].dependants.remove(self)
self._dependencies[compin.component.name] = compin
compin.dependants.append(self)
else:
raise Exception(f'Component {self.component.name} does not have dependency {compin.component.name}')<|docstring|>Sets the provided Managed compin as a dependency of this compin. Will raise an exception if this compin does
not have a dependency on the given managed compin's component.<|endoftext|> |
0431fea14cfb409d34e79c344e6936fd36f362ca213c1ffab32c4c060be5241d | def set_force_keep(self) -> None:
'\n Sets force_keep on this compin as well as on all of its transitive dependencies.\n '
self.force_keep = True
for compin in self.list_dependencies():
compin.set_force_keep() | Sets force_keep on this compin as well as on all of its transitive dependencies. | cloud_controller/knowledge/instance.py | set_force_keep | smartarch/qoscloud | 2 | python | def set_force_keep(self) -> None:
'\n \n '
self.force_keep = True
for compin in self.list_dependencies():
compin.set_force_keep() | def set_force_keep(self) -> None:
'\n \n '
self.force_keep = True
for compin in self.list_dependencies():
compin.set_force_keep()<|docstring|>Sets force_keep on this compin as well as on all of its transitive dependencies.<|endoftext|> |
726ee45e12bfc3b22a6bc780e81173676755f2ea4745768b8d099246657ba7e8 | @property
def is_serving(self) -> bool:
'\n :return: True if this compin has ever been set as a (transitive) dependency for an unmanaged compin, False\n otherwise.\n '
return self._is_serving | :return: True if this compin has ever been set as a (transitive) dependency for an unmanaged compin, False
otherwise. | cloud_controller/knowledge/instance.py | is_serving | smartarch/qoscloud | 2 | python | @property
def is_serving(self) -> bool:
'\n :return: True if this compin has ever been set as a (transitive) dependency for an unmanaged compin, False\n otherwise.\n '
return self._is_serving | @property
def is_serving(self) -> bool:
'\n :return: True if this compin has ever been set as a (transitive) dependency for an unmanaged compin, False\n otherwise.\n '
return self._is_serving<|docstring|>:return: True if this compin has ever been set as a (transitive) dependency for an unmanaged compin, False
otherwise.<|endoftext|> |
f3bbde6e0082dcd4b8ed4a17769853ec120855c874a7b59e156094a2ed49abac | def set_serving(self) -> None:
'\n Sets this compin, as well as all of its transitive dependencies as serving. Resets force_keep.\n '
self.force_keep = False
if (not self._is_serving):
self._is_serving = True
for dependent_compin in self.list_dependencies():
dependent_compin.set_serving() | Sets this compin, as well as all of its transitive dependencies as serving. Resets force_keep. | cloud_controller/knowledge/instance.py | set_serving | smartarch/qoscloud | 2 | python | def set_serving(self) -> None:
'\n \n '
self.force_keep = False
if (not self._is_serving):
self._is_serving = True
for dependent_compin in self.list_dependencies():
dependent_compin.set_serving() | def set_serving(self) -> None:
'\n \n '
self.force_keep = False
if (not self._is_serving):
self._is_serving = True
for dependent_compin in self.list_dependencies():
dependent_compin.set_serving()<|docstring|>Sets this compin, as well as all of its transitive dependencies as serving. Resets force_keep.<|endoftext|> |
d9414cbd8c1e3177229fa92e88cdd3a64f306f0788c726cecd33e5c0f6d1ad55 | def disconnect(self) -> None:
'\n Clears the dependencies and dependants of this compin, sets force_keep and _is_serving to False.\n '
self._is_serving = False
self.force_keep = False
self.dependants.clear()
self._dependencies.clear() | Clears the dependencies and dependants of this compin, sets force_keep and _is_serving to False. | cloud_controller/knowledge/instance.py | disconnect | smartarch/qoscloud | 2 | python | def disconnect(self) -> None:
'\n \n '
self._is_serving = False
self.force_keep = False
self.dependants.clear()
self._dependencies.clear() | def disconnect(self) -> None:
'\n \n '
self._is_serving = False
self.force_keep = False
self.dependants.clear()
self._dependencies.clear()<|docstring|>Clears the dependencies and dependants of this compin, sets force_keep and _is_serving to False.<|endoftext|> |
1f1831fcecaf716eb2a861104d28dda5f11a7fe96db88db50b9e64e090576de4 | def deployment_name(self) -> str:
'\n :return: The name of a Kubernetes deployment corresponding to this compin.\n '
return ((self.component.name + '-') + self.id) | :return: The name of a Kubernetes deployment corresponding to this compin. | cloud_controller/knowledge/instance.py | deployment_name | smartarch/qoscloud | 2 | python | def deployment_name(self) -> str:
'\n \n '
return ((self.component.name + '-') + self.id) | def deployment_name(self) -> str:
'\n \n '
return ((self.component.name + '-') + self.id)<|docstring|>:return: The name of a Kubernetes deployment corresponding to this compin.<|endoftext|> |
acd0ddd8b5469fdbc7eafba1dc0fbd980988affd55db0327d00886c61a9532f1 | def service_name(self) -> str:
'\n :return: The name of a Kubernetes service corresponding to this compin.\n '
return ''.join((ch for ch in self.deployment_name() if (ch.isalnum() or (ch == '-')))) | :return: The name of a Kubernetes service corresponding to this compin. | cloud_controller/knowledge/instance.py | service_name | smartarch/qoscloud | 2 | python | def service_name(self) -> str:
'\n \n '
return .join((ch for ch in self.deployment_name() if (ch.isalnum() or (ch == '-')))) | def service_name(self) -> str:
'\n \n '
return .join((ch for ch in self.deployment_name() if (ch.isalnum() or (ch == '-'))))<|docstring|>:return: The name of a Kubernetes service corresponding to this compin.<|endoftext|> |
ec584553d825991a3616df05c4b902595ca4f2cc5f4ea9802d5b54813da9fcc7 | def get_client(self) -> Optional['UnmanagedCompin']:
'\n Searches through the dependent compins recursively, until finds the unmanaged compin for which this instance was\n created\n :return: The unmanaged compin for which this instance was created. None, if no such compin exists anymore\n '
return self._get_client([]) | Searches through the dependent compins recursively, until finds the unmanaged compin for which this instance was
created
:return: The unmanaged compin for which this instance was created. None, if no such compin exists anymore | cloud_controller/knowledge/instance.py | get_client | smartarch/qoscloud | 2 | python | def get_client(self) -> Optional['UnmanagedCompin']:
'\n Searches through the dependent compins recursively, until finds the unmanaged compin for which this instance was\n created\n :return: The unmanaged compin for which this instance was created. None, if no such compin exists anymore\n '
return self._get_client([]) | def get_client(self) -> Optional['UnmanagedCompin']:
'\n Searches through the dependent compins recursively, until finds the unmanaged compin for which this instance was\n created\n :return: The unmanaged compin for which this instance was created. None, if no such compin exists anymore\n '
return self._get_client([])<|docstring|>Searches through the dependent compins recursively, until finds the unmanaged compin for which this instance was
created
:return: The unmanaged compin for which this instance was created. None, if no such compin exists anymore<|endoftext|> |
3cbfce26a66a368c9ddc7826d5126b33328aa244a87394131031e498c021f1fd | def set_dependency(self, compin: 'ManagedCompin') -> None:
'\n In addition to setting the compin as a current dependency, sets that compin (and all transitively dependent\n compins) as serving.\n :param compin: A new compin to set as dependency.\n '
super().set_dependency(compin)
compin.set_serving() | In addition to setting the compin as a current dependency, sets that compin (and all transitively dependent
compins) as serving.
:param compin: A new compin to set as dependency. | cloud_controller/knowledge/instance.py | set_dependency | smartarch/qoscloud | 2 | python | def set_dependency(self, compin: 'ManagedCompin') -> None:
'\n In addition to setting the compin as a current dependency, sets that compin (and all transitively dependent\n compins) as serving.\n :param compin: A new compin to set as dependency.\n '
super().set_dependency(compin)
compin.set_serving() | def set_dependency(self, compin: 'ManagedCompin') -> None:
'\n In addition to setting the compin as a current dependency, sets that compin (and all transitively dependent\n compins) as serving.\n :param compin: A new compin to set as dependency.\n '
super().set_dependency(compin)
compin.set_serving()<|docstring|>In addition to setting the compin as a current dependency, sets that compin (and all transitively dependent
compins) as serving.
:param compin: A new compin to set as dependency.<|endoftext|> |
82e846cd7b9310e20b50d064581cdb9b726ecbcfe52c1eccc30af36e2e274ef7 | @abc.abstractmethod
def iterate(self) -> Iterator[Class]:
'Create an iterator for the class map values.' | Create an iterator for the class map values. | xsdata/codegen/mixins.py | iterate | neriusmika/xsdata | 0 | python | @abc.abstractmethod
def iterate(self) -> Iterator[Class]:
| @abc.abstractmethod
def iterate(self) -> Iterator[Class]:
<|docstring|>Create an iterator for the class map values.<|endoftext|> |
9809b5e4c7e0531e1c32f633e1fcf2704f4223e84a3131bc3af78d52d245f57f | @abc.abstractmethod
def find(self, qname: str, condition: Callable=return_true) -> Optional[Class]:
'Search by qualified name for a specific class with an optional\n condition callable.' | Search by qualified name for a specific class with an optional
condition callable. | xsdata/codegen/mixins.py | find | neriusmika/xsdata | 0 | python | @abc.abstractmethod
def find(self, qname: str, condition: Callable=return_true) -> Optional[Class]:
'Search by qualified name for a specific class with an optional\n condition callable.' | @abc.abstractmethod
def find(self, qname: str, condition: Callable=return_true) -> Optional[Class]:
'Search by qualified name for a specific class with an optional\n condition callable.'<|docstring|>Search by qualified name for a specific class with an optional
condition callable.<|endoftext|> |
609f2c9e35962b70cfdf370b188e82291c2c0923cd85a267f6a1e50dcb88cfe4 | @abc.abstractmethod
def find_inner(self, source: Class, qname: str) -> Class:
'Search by qualified name for a specific inner class or fail.' | Search by qualified name for a specific inner class or fail. | xsdata/codegen/mixins.py | find_inner | neriusmika/xsdata | 0 | python | @abc.abstractmethod
def find_inner(self, source: Class, qname: str) -> Class:
| @abc.abstractmethod
def find_inner(self, source: Class, qname: str) -> Class:
<|docstring|>Search by qualified name for a specific inner class or fail.<|endoftext|> |
02dc3aeec30623968f1b9cde974364bc29c096f9cf07f2d958f6d07a15b90b95 | @abc.abstractmethod
def add(self, item: Class):
'Add class item to the container.' | Add class item to the container. | xsdata/codegen/mixins.py | add | neriusmika/xsdata | 0 | python | @abc.abstractmethod
def add(self, item: Class):
| @abc.abstractmethod
def add(self, item: Class):
<|docstring|>Add class item to the container.<|endoftext|> |
f5d719bf587d7d0a95c21e5cce8c41ae14e9e9f8115406f73eaacdb365cafa00 | @abc.abstractmethod
def extend(self, items: List[Class]):
'Add a list of classes the container.' | Add a list of classes the container. | xsdata/codegen/mixins.py | extend | neriusmika/xsdata | 0 | python | @abc.abstractmethod
def extend(self, items: List[Class]):
| @abc.abstractmethod
def extend(self, items: List[Class]):
<|docstring|>Add a list of classes the container.<|endoftext|> |
1fcdb87b5d64c5a6055f82d555ea09f910d66ea775d23185f2ee7af7f6dca3f9 | @abc.abstractmethod
def process(self, target: Class):
'Process the given target class.' | Process the given target class. | xsdata/codegen/mixins.py | process | neriusmika/xsdata | 0 | python | @abc.abstractmethod
def process(self, target: Class):
| @abc.abstractmethod
def process(self, target: Class):
<|docstring|>Process the given target class.<|endoftext|> |
7a6b304431dcbc358e608670dde2da39892c87809f603f58dc79fdd1b5fd0d8c | def nodes_edges(num_nodes):
' this function takes number of nodes and returns nodes and edge list'
nodes = list(range(num_nodes))
edges = list(itertools.combinations(nodes, 2))
return (nodes, edges) | this function takes number of nodes and returns nodes and edge list | net_performance_comparison.py | nodes_edges | SandhyaaGopchandani/PythonNetworkLibsComparion | 1 | python | def nodes_edges(num_nodes):
' '
nodes = list(range(num_nodes))
edges = list(itertools.combinations(nodes, 2))
return (nodes, edges) | def nodes_edges(num_nodes):
' '
nodes = list(range(num_nodes))
edges = list(itertools.combinations(nodes, 2))
return (nodes, edges)<|docstring|>this function takes number of nodes and returns nodes and edge list<|endoftext|> |
14d939d388c54fdeaf232085af0c1f6b34edc5d5d6d69812a75b4a9e126fbdaf | def create_graph_graphtool(node_num, edges):
' this function creates graph object of graphtool library'
g = Graph(directed=False)
vlist = g.add_vertex(node_num)
g.add_edge_list(edges)
return g | this function creates graph object of graphtool library | net_performance_comparison.py | create_graph_graphtool | SandhyaaGopchandani/PythonNetworkLibsComparion | 1 | python | def create_graph_graphtool(node_num, edges):
' '
g = Graph(directed=False)
vlist = g.add_vertex(node_num)
g.add_edge_list(edges)
return g | def create_graph_graphtool(node_num, edges):
' '
g = Graph(directed=False)
vlist = g.add_vertex(node_num)
g.add_edge_list(edges)
return g<|docstring|>this function creates graph object of graphtool library<|endoftext|> |
6396a36f5fc8f2a90895878007fc3aed008e2a42112ebdba6d9c4dabb1d8fedc | def create_graph_igraph(nodes, edges):
' this function creates graph object of igraph library'
g = Graph(directed=False)
g.add_vertices(nodes)
g.add_edges(edges)
return g | this function creates graph object of igraph library | net_performance_comparison.py | create_graph_igraph | SandhyaaGopchandani/PythonNetworkLibsComparion | 1 | python | def create_graph_igraph(nodes, edges):
' '
g = Graph(directed=False)
g.add_vertices(nodes)
g.add_edges(edges)
return g | def create_graph_igraph(nodes, edges):
' '
g = Graph(directed=False)
g.add_vertices(nodes)
g.add_edges(edges)
return g<|docstring|>this function creates graph object of igraph library<|endoftext|> |
0c94e02d3838ad0e0b4776c01a87ccc028ef0619ca4a7c91fa342fbdd6eeff64 | def create_graph_networkx(nodes, edges):
' this function creates graph object of networkx library'
g = nx.Graph(directed=False)
g.add_nodes_from(nodes)
g.add_edges_from(edges)
return g | this function creates graph object of networkx library | net_performance_comparison.py | create_graph_networkx | SandhyaaGopchandani/PythonNetworkLibsComparion | 1 | python | def create_graph_networkx(nodes, edges):
' '
g = nx.Graph(directed=False)
g.add_nodes_from(nodes)
g.add_edges_from(edges)
return g | def create_graph_networkx(nodes, edges):
' '
g = nx.Graph(directed=False)
g.add_nodes_from(nodes)
g.add_edges_from(edges)
return g<|docstring|>this function creates graph object of networkx library<|endoftext|> |
80189d5616417b13ad3811cf247c3a93feff4e240ccf548cf7a1617ca0ed2680 | def get_edges(complete_edge_list, threshold=0.5):
' this function randomnly picks the edges in graph based on probability. 0.5 means we want to include only 50% of random \n edges of the total edges in the graph'
edge_list = []
for key in complete_edge_list:
if (np.random.random() < threshold):
edge_list.append(key)
return edge_list | this function randomnly picks the edges in graph based on probability. 0.5 means we want to include only 50% of random
edges of the total edges in the graph | net_performance_comparison.py | get_edges | SandhyaaGopchandani/PythonNetworkLibsComparion | 1 | python | def get_edges(complete_edge_list, threshold=0.5):
' this function randomnly picks the edges in graph based on probability. 0.5 means we want to include only 50% of random \n edges of the total edges in the graph'
edge_list = []
for key in complete_edge_list:
if (np.random.random() < threshold):
edge_list.append(key)
return edge_list | def get_edges(complete_edge_list, threshold=0.5):
' this function randomnly picks the edges in graph based on probability. 0.5 means we want to include only 50% of random \n edges of the total edges in the graph'
edge_list = []
for key in complete_edge_list:
if (np.random.random() < threshold):
edge_list.append(key)
return edge_list<|docstring|>this function randomnly picks the edges in graph based on probability. 0.5 means we want to include only 50% of random
edges of the total edges in the graph<|endoftext|> |
65370c94f8d3ecdc1aa6010e0c98e88dfa4c0e84c87bab23be47bb2cd559b803 | def multiple_graph(complete_edge_list, nodes, probs, netlib='networkx'):
'this function times the various centrality measures calculated using three different network libararies.\n The function computes various graph based on given probability of edges, computes the degree, closeness and betweenness\n centrality measure and time those. At the end, it returns the list of timestamp for each cenrality. '
print('total possible edges:', len(complete_edge_list))
time_deg_central = []
time_closeness_central = []
time_between_central = []
num_edges = []
for prob in probs:
edges = get_edges(complete_edge_list, prob)
if (netlib == 'graph-tool'):
num_nodes = len(nodes)
graph = create_graph_graphtool(num_nodes, edges)
print(prob, len(graph.get_vertices()), len(graph.get_edges()))
num_edges.append(len(graph.get_edges()))
start = timer()
doc_degree_centralities = graph.get_out_degrees(nodes)
end = timer()
time_deg_central.append((end - start))
start = timer()
(vertex_betweenness, edge_betweenness) = graph_tool.centrality.betweenness(graph)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = graph_tool.centrality.closeness(graph)
end = timer()
time_closeness_central.append((end - start))
if (netlib == 'networkx'):
graph = create_graph_networkx(nodes, edges)
print(prob, len(graph.nodes()), len(graph.edges()))
num_edges.append(len(graph.edges()))
start = timer()
doc_degree_centralities = nx.algorithms.centrality.degree_centrality(graph)
end = timer()
time_deg_central.append((end - start))
start = timer()
vertex_betweenness = nx.algorithms.centrality.betweenness_centrality(graph)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = nx.algorithms.centrality.closeness_centrality(graph)
end = timer()
time_closeness_central.append((end - start))
if (netlib == 'igraph'):
graph = create_graph_igraph(nodes, edges)
print(prob, graph.vcount(), graph.ecount())
num_edges.append(graph.ecount())
start = timer()
doc_degree_centralities = (np.array(graph.degree(nodes), dtype='f') / (graph.vcount() - 1))
end = timer()
time_deg_central.append((end - start))
start = timer()
normalization_factor = (2 / (float((graph.vcount() - 1)) * float((graph.vcount() - 2))))
vertex_betweenness = (np.array(graph.betweenness(), dtype='f') * normalization_factor)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = graph.closeness()
end = timer()
time_closeness_central.append((end - start))
return (num_edges, time_deg_central, time_closeness_central, time_between_central) | this function times the various centrality measures calculated using three different network libararies.
The function computes various graph based on given probability of edges, computes the degree, closeness and betweenness
centrality measure and time those. At the end, it returns the list of timestamp for each cenrality. | net_performance_comparison.py | multiple_graph | SandhyaaGopchandani/PythonNetworkLibsComparion | 1 | python | def multiple_graph(complete_edge_list, nodes, probs, netlib='networkx'):
'this function times the various centrality measures calculated using three different network libararies.\n The function computes various graph based on given probability of edges, computes the degree, closeness and betweenness\n centrality measure and time those. At the end, it returns the list of timestamp for each cenrality. '
print('total possible edges:', len(complete_edge_list))
time_deg_central = []
time_closeness_central = []
time_between_central = []
num_edges = []
for prob in probs:
edges = get_edges(complete_edge_list, prob)
if (netlib == 'graph-tool'):
num_nodes = len(nodes)
graph = create_graph_graphtool(num_nodes, edges)
print(prob, len(graph.get_vertices()), len(graph.get_edges()))
num_edges.append(len(graph.get_edges()))
start = timer()
doc_degree_centralities = graph.get_out_degrees(nodes)
end = timer()
time_deg_central.append((end - start))
start = timer()
(vertex_betweenness, edge_betweenness) = graph_tool.centrality.betweenness(graph)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = graph_tool.centrality.closeness(graph)
end = timer()
time_closeness_central.append((end - start))
if (netlib == 'networkx'):
graph = create_graph_networkx(nodes, edges)
print(prob, len(graph.nodes()), len(graph.edges()))
num_edges.append(len(graph.edges()))
start = timer()
doc_degree_centralities = nx.algorithms.centrality.degree_centrality(graph)
end = timer()
time_deg_central.append((end - start))
start = timer()
vertex_betweenness = nx.algorithms.centrality.betweenness_centrality(graph)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = nx.algorithms.centrality.closeness_centrality(graph)
end = timer()
time_closeness_central.append((end - start))
if (netlib == 'igraph'):
graph = create_graph_igraph(nodes, edges)
print(prob, graph.vcount(), graph.ecount())
num_edges.append(graph.ecount())
start = timer()
doc_degree_centralities = (np.array(graph.degree(nodes), dtype='f') / (graph.vcount() - 1))
end = timer()
time_deg_central.append((end - start))
start = timer()
normalization_factor = (2 / (float((graph.vcount() - 1)) * float((graph.vcount() - 2))))
vertex_betweenness = (np.array(graph.betweenness(), dtype='f') * normalization_factor)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = graph.closeness()
end = timer()
time_closeness_central.append((end - start))
return (num_edges, time_deg_central, time_closeness_central, time_between_central) | def multiple_graph(complete_edge_list, nodes, probs, netlib='networkx'):
'this function times the various centrality measures calculated using three different network libararies.\n The function computes various graph based on given probability of edges, computes the degree, closeness and betweenness\n centrality measure and time those. At the end, it returns the list of timestamp for each cenrality. '
print('total possible edges:', len(complete_edge_list))
time_deg_central = []
time_closeness_central = []
time_between_central = []
num_edges = []
for prob in probs:
edges = get_edges(complete_edge_list, prob)
if (netlib == 'graph-tool'):
num_nodes = len(nodes)
graph = create_graph_graphtool(num_nodes, edges)
print(prob, len(graph.get_vertices()), len(graph.get_edges()))
num_edges.append(len(graph.get_edges()))
start = timer()
doc_degree_centralities = graph.get_out_degrees(nodes)
end = timer()
time_deg_central.append((end - start))
start = timer()
(vertex_betweenness, edge_betweenness) = graph_tool.centrality.betweenness(graph)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = graph_tool.centrality.closeness(graph)
end = timer()
time_closeness_central.append((end - start))
if (netlib == 'networkx'):
graph = create_graph_networkx(nodes, edges)
print(prob, len(graph.nodes()), len(graph.edges()))
num_edges.append(len(graph.edges()))
start = timer()
doc_degree_centralities = nx.algorithms.centrality.degree_centrality(graph)
end = timer()
time_deg_central.append((end - start))
start = timer()
vertex_betweenness = nx.algorithms.centrality.betweenness_centrality(graph)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = nx.algorithms.centrality.closeness_centrality(graph)
end = timer()
time_closeness_central.append((end - start))
if (netlib == 'igraph'):
graph = create_graph_igraph(nodes, edges)
print(prob, graph.vcount(), graph.ecount())
num_edges.append(graph.ecount())
start = timer()
doc_degree_centralities = (np.array(graph.degree(nodes), dtype='f') / (graph.vcount() - 1))
end = timer()
time_deg_central.append((end - start))
start = timer()
normalization_factor = (2 / (float((graph.vcount() - 1)) * float((graph.vcount() - 2))))
vertex_betweenness = (np.array(graph.betweenness(), dtype='f') * normalization_factor)
end = timer()
time_between_central.append((end - start))
start = timer()
vertex_closeness = graph.closeness()
end = timer()
time_closeness_central.append((end - start))
return (num_edges, time_deg_central, time_closeness_central, time_between_central)<|docstring|>this function times the various centrality measures calculated using three different network libararies.
The function computes various graph based on given probability of edges, computes the degree, closeness and betweenness
centrality measure and time those. At the end, it returns the list of timestamp for each cenrality.<|endoftext|> |
1848da4a93ddbf01571e608c48bcc7eeab256c7f8d840192050ecaf4894e3ffa | def plot_result(num_nodes, x, y1, y2, y3):
'This function plots the timestamp for three centralities as a function of number of edges.'
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.legend(['degree centrality', 'closeness centrality', 'betweenness centrality'], loc='upper left')
plt.xticks(x)
plt.title(('with network of nodes ' + str(num_nodes)))
plt.xticks(rotation=90)
plt.xlabel('number of edges')
plt.ylabel('time (in seconds)')
plt.show() | This function plots the timestamp for three centralities as a function of number of edges. | net_performance_comparison.py | plot_result | SandhyaaGopchandani/PythonNetworkLibsComparion | 1 | python | def plot_result(num_nodes, x, y1, y2, y3):
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.legend(['degree centrality', 'closeness centrality', 'betweenness centrality'], loc='upper left')
plt.xticks(x)
plt.title(('with network of nodes ' + str(num_nodes)))
plt.xticks(rotation=90)
plt.xlabel('number of edges')
plt.ylabel('time (in seconds)')
plt.show() | def plot_result(num_nodes, x, y1, y2, y3):
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.legend(['degree centrality', 'closeness centrality', 'betweenness centrality'], loc='upper left')
plt.xticks(x)
plt.title(('with network of nodes ' + str(num_nodes)))
plt.xticks(rotation=90)
plt.xlabel('number of edges')
plt.ylabel('time (in seconds)')
plt.show()<|docstring|>This function plots the timestamp for three centralities as a function of number of edges.<|endoftext|> |
4f910ca99c75cc81ad4aba254b3545bb56dd74badcef525bc08e1badd28ae62e | def add(self, h, contains=None):
"Add the given keys. First time a key is added the value is set to 0,\n then it's set to one."
if (not isinstance(h, np.ndarray)):
h = np.array(h, dtype=HASH_TYPE)
if (contains is None):
contains = self.__contains__(h)
self.__setitem__(h, contains)
return contains | Add the given keys. First time a key is added the value is set to 0,
then it's set to one. | kenlm_training/cc_net/flat_hash_set.py | add | abumafrim/data_tooling | 435 | python | def add(self, h, contains=None):
"Add the given keys. First time a key is added the value is set to 0,\n then it's set to one."
if (not isinstance(h, np.ndarray)):
h = np.array(h, dtype=HASH_TYPE)
if (contains is None):
contains = self.__contains__(h)
self.__setitem__(h, contains)
return contains | def add(self, h, contains=None):
"Add the given keys. First time a key is added the value is set to 0,\n then it's set to one."
if (not isinstance(h, np.ndarray)):
h = np.array(h, dtype=HASH_TYPE)
if (contains is None):
contains = self.__contains__(h)
self.__setitem__(h, contains)
return contains<|docstring|>Add the given keys. First time a key is added the value is set to 0,
then it's set to one.<|endoftext|> |
2289ddd84ef628332dd38e5dce0a7708fbf398ce6bc4d790363d45d06acb1e75 | def __contains__(self, values):
'Returns `True` if the object has been added at list once.'
contains_point = super().__contains__
return np.fromiter(map(contains_point, values), count=len(values), dtype=np.uint8) | Returns `True` if the object has been added at list once. | kenlm_training/cc_net/flat_hash_set.py | __contains__ | abumafrim/data_tooling | 435 | python | def __contains__(self, values):
contains_point = super().__contains__
return np.fromiter(map(contains_point, values), count=len(values), dtype=np.uint8) | def __contains__(self, values):
contains_point = super().__contains__
return np.fromiter(map(contains_point, values), count=len(values), dtype=np.uint8)<|docstring|>Returns `True` if the object has been added at list once.<|endoftext|> |
8e144c466dbe3304d9fd09f7167681c1a3d014a92941bc23db54ecba57d4321b | def __getitem__(self, values):
'Returns `True` if the object has been added at list twice.'
get_point = super().get
return np.fromiter(map((lambda x: get_point(x, False)), values), count=len(values), dtype=np.uint8) | Returns `True` if the object has been added at list twice. | kenlm_training/cc_net/flat_hash_set.py | __getitem__ | abumafrim/data_tooling | 435 | python | def __getitem__(self, values):
get_point = super().get
return np.fromiter(map((lambda x: get_point(x, False)), values), count=len(values), dtype=np.uint8) | def __getitem__(self, values):
get_point = super().get
return np.fromiter(map((lambda x: get_point(x, False)), values), count=len(values), dtype=np.uint8)<|docstring|>Returns `True` if the object has been added at list twice.<|endoftext|> |
72d0db161520972061277d0e8aea67b72006887e187af84d00c6fe22a3a9fed8 | def __contains__(self, h):
'Returns `True` if the object has been added at list once.'
if (not isinstance(h, np.ndarray)):
h = np.array(h, dtype=HASH_TYPE)
c = gp.Dict.__contains__(self, h)
c.dtype = np.uint8
return c | Returns `True` if the object has been added at list once. | kenlm_training/cc_net/flat_hash_set.py | __contains__ | abumafrim/data_tooling | 435 | python | def __contains__(self, h):
if (not isinstance(h, np.ndarray)):
h = np.array(h, dtype=HASH_TYPE)
c = gp.Dict.__contains__(self, h)
c.dtype = np.uint8
return c | def __contains__(self, h):
if (not isinstance(h, np.ndarray)):
h = np.array(h, dtype=HASH_TYPE)
c = gp.Dict.__contains__(self, h)
c.dtype = np.uint8
return c<|docstring|>Returns `True` if the object has been added at list once.<|endoftext|> |
1adf3835be825ef3c07e3e570b9277a270d9a2a2652e5fa6cc20bab927077db7 | def load_gp(self, filename):
'Override gp.Dict.load, to correctly merge values instead of overwriting.'
other = gp.Dict(HASH_TYPE, np.uint8, default_value=False)
other.load(str(filename))
n = len(other)
keys = np.fromiter((k for (k, v) in other.items()), dtype=HASH_TYPE, count=n)
values = np.fromiter((v for (k, v) in other.items()), dtype=np.uint8, count=n)
self.merge(keys, values) | Override gp.Dict.load, to correctly merge values instead of overwriting. | kenlm_training/cc_net/flat_hash_set.py | load_gp | abumafrim/data_tooling | 435 | python | def load_gp(self, filename):
other = gp.Dict(HASH_TYPE, np.uint8, default_value=False)
other.load(str(filename))
n = len(other)
keys = np.fromiter((k for (k, v) in other.items()), dtype=HASH_TYPE, count=n)
values = np.fromiter((v for (k, v) in other.items()), dtype=np.uint8, count=n)
self.merge(keys, values) | def load_gp(self, filename):
other = gp.Dict(HASH_TYPE, np.uint8, default_value=False)
other.load(str(filename))
n = len(other)
keys = np.fromiter((k for (k, v) in other.items()), dtype=HASH_TYPE, count=n)
values = np.fromiter((v for (k, v) in other.items()), dtype=np.uint8, count=n)
self.merge(keys, values)<|docstring|>Override gp.Dict.load, to correctly merge values instead of overwriting.<|endoftext|> |
701704c5d4c4d72593d85d2b31bbe22bec0bb911ec68a160215d5419dd52cd7d | def connect(self, client_id):
"Forms a connection to the peer across TCP. Also creates\n an initial handshake message and schedules it for delivery.\n\n The connection for this peer is run on it's own thread. Which will\n hopefully allow this to easily be made concurrent.\n\n Args:\n client_id: String representing the 20 byte client Id that\n is making the connection to the peer.\n Raises:\n A peer exception if the connection has already been made.\n "
self.shake_hands(client_id)
if self._connection_thread:
raise PeerError('This Peer is already connected.')
reactor.connectTCP(self.ip, self.port, PeerConnectionFactory(self))
PeerConnectionFactory.ensure_reactor() | Forms a connection to the peer across TCP. Also creates
an initial handshake message and schedules it for delivery.
The connection for this peer is run on it's own thread. Which will
hopefully allow this to easily be made concurrent.
Args:
client_id: String representing the 20 byte client Id that
is making the connection to the peer.
Raises:
A peer exception if the connection has already been made. | peer.py | connect | dcheno/dripdrop | 0 | python | def connect(self, client_id):
"Forms a connection to the peer across TCP. Also creates\n an initial handshake message and schedules it for delivery.\n\n The connection for this peer is run on it's own thread. Which will\n hopefully allow this to easily be made concurrent.\n\n Args:\n client_id: String representing the 20 byte client Id that\n is making the connection to the peer.\n Raises:\n A peer exception if the connection has already been made.\n "
self.shake_hands(client_id)
if self._connection_thread:
raise PeerError('This Peer is already connected.')
reactor.connectTCP(self.ip, self.port, PeerConnectionFactory(self))
PeerConnectionFactory.ensure_reactor() | def connect(self, client_id):
"Forms a connection to the peer across TCP. Also creates\n an initial handshake message and schedules it for delivery.\n\n The connection for this peer is run on it's own thread. Which will\n hopefully allow this to easily be made concurrent.\n\n Args:\n client_id: String representing the 20 byte client Id that\n is making the connection to the peer.\n Raises:\n A peer exception if the connection has already been made.\n "
self.shake_hands(client_id)
if self._connection_thread:
raise PeerError('This Peer is already connected.')
reactor.connectTCP(self.ip, self.port, PeerConnectionFactory(self))
PeerConnectionFactory.ensure_reactor()<|docstring|>Forms a connection to the peer across TCP. Also creates
an initial handshake message and schedules it for delivery.
The connection for this peer is run on it's own thread. Which will
hopefully allow this to easily be made concurrent.
Args:
client_id: String representing the 20 byte client Id that
is making the connection to the peer.
Raises:
A peer exception if the connection has already been made.<|endoftext|> |
b96cd59db8e39d5f275cce590b33f9cedd786ca1851b06bef35c76f39efad76e | def close_connection(self):
'Tells the protocol to close the connection, then notifies the queues\n that their work is over.'
self.messages_to_peer.put(Message(MessageType.CLOSE))
self.messages_to_peer.close()
self.messages_from_peer.close() | Tells the protocol to close the connection, then notifies the queues
that their work is over. | peer.py | close_connection | dcheno/dripdrop | 0 | python | def close_connection(self):
'Tells the protocol to close the connection, then notifies the queues\n that their work is over.'
self.messages_to_peer.put(Message(MessageType.CLOSE))
self.messages_to_peer.close()
self.messages_from_peer.close() | def close_connection(self):
'Tells the protocol to close the connection, then notifies the queues\n that their work is over.'
self.messages_to_peer.put(Message(MessageType.CLOSE))
self.messages_to_peer.close()
self.messages_from_peer.close()<|docstring|>Tells the protocol to close the connection, then notifies the queues
that their work is over.<|endoftext|> |
8b9f819d6b87f2206d59fd0f7d00166438f0a8700a22437de1bb398b367a9397 | def message_peer(self, message):
'Places a message which will be passed to the peer connection'
self.messages_to_peer.put(message) | Places a message which will be passed to the peer connection | peer.py | message_peer | dcheno/dripdrop | 0 | python | def message_peer(self, message):
self.messages_to_peer.put(message) | def message_peer(self, message):
self.messages_to_peer.put(message)<|docstring|>Places a message which will be passed to the peer connection<|endoftext|> |
40aa378ee340c69196cf53d99cd9f32b06940efdff95d09cba5028461dd3d59d | def handle_messages(self, data):
'Interprets incoming messages and responds or notifies the client\n nas necessary'
if is_handshake(data):
handshake = parse_handshake(data)
if (handshake['peer_id'] != self.peer_id):
raise HandshakeException('Bad Peer Id')
self.hands_shook = True
self.messages_from_peer.put(Message.factory(MessageType.HANDSHAKE, data))
if ('extra' in handshake):
self.handle_messages(handshake['extra'])
else:
messages = self._message_parser(data)
for message in messages:
handler_method = self._message_dispatch(message)
handler_method(message.payload)
self.messages_from_peer.put(message) | Interprets incoming messages and responds or notifies the client
nas necessary | peer.py | handle_messages | dcheno/dripdrop | 0 | python | def handle_messages(self, data):
'Interprets incoming messages and responds or notifies the client\n nas necessary'
if is_handshake(data):
handshake = parse_handshake(data)
if (handshake['peer_id'] != self.peer_id):
raise HandshakeException('Bad Peer Id')
self.hands_shook = True
self.messages_from_peer.put(Message.factory(MessageType.HANDSHAKE, data))
if ('extra' in handshake):
self.handle_messages(handshake['extra'])
else:
messages = self._message_parser(data)
for message in messages:
handler_method = self._message_dispatch(message)
handler_method(message.payload)
self.messages_from_peer.put(message) | def handle_messages(self, data):
'Interprets incoming messages and responds or notifies the client\n nas necessary'
if is_handshake(data):
handshake = parse_handshake(data)
if (handshake['peer_id'] != self.peer_id):
raise HandshakeException('Bad Peer Id')
self.hands_shook = True
self.messages_from_peer.put(Message.factory(MessageType.HANDSHAKE, data))
if ('extra' in handshake):
self.handle_messages(handshake['extra'])
else:
messages = self._message_parser(data)
for message in messages:
handler_method = self._message_dispatch(message)
handler_method(message.payload)
self.messages_from_peer.put(message)<|docstring|>Interprets incoming messages and responds or notifies the client
nas necessary<|endoftext|> |
66f1cc0f3b91f79a508547271d49e394874660f88cf44033557cec73e84fb132 | def subscribe_for_messages_to_peer(self, callback):
'Assigns a callback for all messages that are intended for the peer'
if self._peer_listener_thread:
raise PeerError('This peer already has a connection listening to it.')
thread = Thread(target=message_queue_worker, args=(self.messages_to_peer, callback))
self._peer_listener_thread = thread
thread.start() | Assigns a callback for all messages that are intended for the peer | peer.py | subscribe_for_messages_to_peer | dcheno/dripdrop | 0 | python | def subscribe_for_messages_to_peer(self, callback):
if self._peer_listener_thread:
raise PeerError('This peer already has a connection listening to it.')
thread = Thread(target=message_queue_worker, args=(self.messages_to_peer, callback))
self._peer_listener_thread = thread
thread.start() | def subscribe_for_messages_to_peer(self, callback):
if self._peer_listener_thread:
raise PeerError('This peer already has a connection listening to it.')
thread = Thread(target=message_queue_worker, args=(self.messages_to_peer, callback))
self._peer_listener_thread = thread
thread.start()<|docstring|>Assigns a callback for all messages that are intended for the peer<|endoftext|> |
3633d33e9d7b32d45b2daf64be4b80221fcd95298d5aa12cda4364cbad885a3f | def subscribe_for_messages_to_client(self, callback):
'Assigns a callback for all messages that are intended for the client'
if self._client_listener_thread:
raise PeerError('This peer already has a client listening to it.')
thread = Thread(target=message_queue_worker, args=(self.messages_from_peer, callback))
self._client_listener_thread = thread
thread.start() | Assigns a callback for all messages that are intended for the client | peer.py | subscribe_for_messages_to_client | dcheno/dripdrop | 0 | python | def subscribe_for_messages_to_client(self, callback):
if self._client_listener_thread:
raise PeerError('This peer already has a client listening to it.')
thread = Thread(target=message_queue_worker, args=(self.messages_from_peer, callback))
self._client_listener_thread = thread
thread.start() | def subscribe_for_messages_to_client(self, callback):
if self._client_listener_thread:
raise PeerError('This peer already has a client listening to it.')
thread = Thread(target=message_queue_worker, args=(self.messages_from_peer, callback))
self._client_listener_thread = thread
thread.start()<|docstring|>Assigns a callback for all messages that are intended for the client<|endoftext|> |
619ae93ae27acce7b29675872a7586381a3a3ac688064f14fdb16adb099b61fe | def _handle_bitfield(self, payload):
"Update the peer's pieces based on the bitfield representation.\n\n The bitfield payload is a series of bytes, where each bit in\n each byte represents whether the peer has the piece or not. The leftmost\n bit of the leftmost byte is piece 0.\n\n Assert: (pieces//8) <= len(bitfield payload) <= ((pieces//8) + 1)\n "
if (len(payload) != ceil((self.torrent.num_pieces / 8))):
self.close_connection()
raise PeerError('Peer Bitfield Does not Match Expected Length')
piece_number = 0
for byte in payload:
bits = bin(byte).lstrip('0b')
piece_number += (8 - len(bits))
for bit in bits:
if (bit == '1'):
self.pieces.add(piece_number)
piece_number += 1
if (piece_number >= self.torrent.num_pieces):
break | Update the peer's pieces based on the bitfield representation.
The bitfield payload is a series of bytes, where each bit in
each byte represents whether the peer has the piece or not. The leftmost
bit of the leftmost byte is piece 0.
Assert: (pieces//8) <= len(bitfield payload) <= ((pieces//8) + 1) | peer.py | _handle_bitfield | dcheno/dripdrop | 0 | python | def _handle_bitfield(self, payload):
"Update the peer's pieces based on the bitfield representation.\n\n The bitfield payload is a series of bytes, where each bit in\n each byte represents whether the peer has the piece or not. The leftmost\n bit of the leftmost byte is piece 0.\n\n Assert: (pieces//8) <= len(bitfield payload) <= ((pieces//8) + 1)\n "
if (len(payload) != ceil((self.torrent.num_pieces / 8))):
self.close_connection()
raise PeerError('Peer Bitfield Does not Match Expected Length')
piece_number = 0
for byte in payload:
bits = bin(byte).lstrip('0b')
piece_number += (8 - len(bits))
for bit in bits:
if (bit == '1'):
self.pieces.add(piece_number)
piece_number += 1
if (piece_number >= self.torrent.num_pieces):
break | def _handle_bitfield(self, payload):
"Update the peer's pieces based on the bitfield representation.\n\n The bitfield payload is a series of bytes, where each bit in\n each byte represents whether the peer has the piece or not. The leftmost\n bit of the leftmost byte is piece 0.\n\n Assert: (pieces//8) <= len(bitfield payload) <= ((pieces//8) + 1)\n "
if (len(payload) != ceil((self.torrent.num_pieces / 8))):
self.close_connection()
raise PeerError('Peer Bitfield Does not Match Expected Length')
piece_number = 0
for byte in payload:
bits = bin(byte).lstrip('0b')
piece_number += (8 - len(bits))
for bit in bits:
if (bit == '1'):
self.pieces.add(piece_number)
piece_number += 1
if (piece_number >= self.torrent.num_pieces):
break<|docstring|>Update the peer's pieces based on the bitfield representation.
The bitfield payload is a series of bytes, where each bit in
each byte represents whether the peer has the piece or not. The leftmost
bit of the leftmost byte is piece 0.
Assert: (pieces//8) <= len(bitfield payload) <= ((pieces//8) + 1)<|endoftext|> |
b58714ea608572caaf75a12accaa5662c784c84fb1a0803b84ee9007bdbe2909 | def connectionMade(self):
'Function to be called whenever a connection is established\n for the protocol.'
print('Connection made with: {}'.format(self.peer))
self.peer.subscribe_for_messages_to_peer(self.send_message) | Function to be called whenever a connection is established
for the protocol. | peer.py | connectionMade | dcheno/dripdrop | 0 | python | def connectionMade(self):
'Function to be called whenever a connection is established\n for the protocol.'
print('Connection made with: {}'.format(self.peer))
self.peer.subscribe_for_messages_to_peer(self.send_message) | def connectionMade(self):
'Function to be called whenever a connection is established\n for the protocol.'
print('Connection made with: {}'.format(self.peer))
self.peer.subscribe_for_messages_to_peer(self.send_message)<|docstring|>Function to be called whenever a connection is established
for the protocol.<|endoftext|> |
086e675b6f34073fbe5167729a0bd5b546707ba391481f839314f48a3176c572 | def dataReceived(self, data):
'Function to be called whenever data is received over the connection\n\n Should examine type of message and parse. If initial handshake, should\n examine for authenticity, and prepare for response.\n '
self.peer.handle_messages(data) | Function to be called whenever data is received over the connection
Should examine type of message and parse. If initial handshake, should
examine for authenticity, and prepare for response. | peer.py | dataReceived | dcheno/dripdrop | 0 | python | def dataReceived(self, data):
'Function to be called whenever data is received over the connection\n\n Should examine type of message and parse. If initial handshake, should\n examine for authenticity, and prepare for response.\n '
self.peer.handle_messages(data) | def dataReceived(self, data):
'Function to be called whenever data is received over the connection\n\n Should examine type of message and parse. If initial handshake, should\n examine for authenticity, and prepare for response.\n '
self.peer.handle_messages(data)<|docstring|>Function to be called whenever data is received over the connection
Should examine type of message and parse. If initial handshake, should
examine for authenticity, and prepare for response.<|endoftext|> |
22220ecbd69cbf7d83b8e7c6a7776865fe4756daffeedec8d3c848bbabd02ae4 | def search(self):
'Search a params.'
self.count += 1
params = {}
for (param_key, param_values) in self.hyper_parameters.items():
params[param_key] = random.choice(param_values)
logging.info('params:%s', params)
return (self.count, params) | Search a params. | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/fine_grained_space/sample/random_search.py | search | Huawei-Ascend/modelzoo | 12 | python | def search(self):
self.count += 1
params = {}
for (param_key, param_values) in self.hyper_parameters.items():
params[param_key] = random.choice(param_values)
logging.info('params:%s', params)
return (self.count, params) | def search(self):
self.count += 1
params = {}
for (param_key, param_values) in self.hyper_parameters.items():
params[param_key] = random.choice(param_values)
logging.info('params:%s', params)
return (self.count, params)<|docstring|>Search a params.<|endoftext|> |
0e2634a5bd9ac0f1990324ad5c40e89a43f783a61079b2bbf4eb87664d735430 | def update_params(self, params):
'Update params into search_space.'
return None | Update params into search_space. | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/fine_grained_space/sample/random_search.py | update_params | Huawei-Ascend/modelzoo | 12 | python | def update_params(self, params):
return None | def update_params(self, params):
return None<|docstring|>Update params into search_space.<|endoftext|> |
e3d131dccbc65c143e1780e1bf1b53603ac050a99289dbaedc5da9db92368716 | @property
def is_completed(self):
'Make trail completed.'
return (self.count > 2) | Make trail completed. | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/fine_grained_space/sample/random_search.py | is_completed | Huawei-Ascend/modelzoo | 12 | python | @property
def is_completed(self):
return (self.count > 2) | @property
def is_completed(self):
return (self.count > 2)<|docstring|>Make trail completed.<|endoftext|> |
9d4e9a76e4288e3ae48b9ab08c3e491fef1465e76f460e48b03c91750fba0e7c | def predict(self, X: ArrayLike) -> np.ndarray:
'Predict the primary incident type of the given descriptions.\n\n Params:\n X: 1D array-like of descriptions to classify\n\n Returns:\n 1D array of `IncidentType` predictions for the given descriptions.\n '
predictions = self._model.predict(X)
return np.array([prediction for prediction in predictions]) | Predict the primary incident type of the given descriptions.
Params:
X: 1D array-like of descriptions to classify
Returns:
1D array of `IncidentType` predictions for the given descriptions. | models/svm_model.py | predict | Code-the-Change-YYC/YW-NLP | 1 | python | def predict(self, X: ArrayLike) -> np.ndarray:
'Predict the primary incident type of the given descriptions.\n\n Params:\n X: 1D array-like of descriptions to classify\n\n Returns:\n 1D array of `IncidentType` predictions for the given descriptions.\n '
predictions = self._model.predict(X)
return np.array([prediction for prediction in predictions]) | def predict(self, X: ArrayLike) -> np.ndarray:
'Predict the primary incident type of the given descriptions.\n\n Params:\n X: 1D array-like of descriptions to classify\n\n Returns:\n 1D array of `IncidentType` predictions for the given descriptions.\n '
predictions = self._model.predict(X)
return np.array([prediction for prediction in predictions])<|docstring|>Predict the primary incident type of the given descriptions.
Params:
X: 1D array-like of descriptions to classify
Returns:
1D array of `IncidentType` predictions for the given descriptions.<|endoftext|> |
2f0213716115c36b34c042f62e85c85a8c360159763742e772cbb7717fe77f05 | def __init__(self, path, local):
'\n Initialize the dataset\n :param path: Path to the hdf5 dataset file\n :param local: True if the path is to a local file, False otherwise\n '
self.path = path
self.local = local
if (not local):
with file_io.FileIO(path, mode='rb') as dataset_f:
with open('dataset.h5', 'wb') as local_dataset:
local_dataset.write(dataset_f.read())
path = 'dataset.h5'
hf = h5py.File(path, 'r')
self.x = hf.get('x')[:]
self.y = hf.get('y')[:]
hf.close()
self.x = ((self.x.astype(np.float32) - 127.5) / 127.5)
print('Loaded dataset')
print('X:', self.x.shape)
print('Y:', self.y.shape) | Initialize the dataset
:param path: Path to the hdf5 dataset file
:param local: True if the path is to a local file, False otherwise | trainer/dataset.py | __init__ | jessica-dl/2XB3-ML-Training | 0 | python | def __init__(self, path, local):
'\n Initialize the dataset\n :param path: Path to the hdf5 dataset file\n :param local: True if the path is to a local file, False otherwise\n '
self.path = path
self.local = local
if (not local):
with file_io.FileIO(path, mode='rb') as dataset_f:
with open('dataset.h5', 'wb') as local_dataset:
local_dataset.write(dataset_f.read())
path = 'dataset.h5'
hf = h5py.File(path, 'r')
self.x = hf.get('x')[:]
self.y = hf.get('y')[:]
hf.close()
self.x = ((self.x.astype(np.float32) - 127.5) / 127.5)
print('Loaded dataset')
print('X:', self.x.shape)
print('Y:', self.y.shape) | def __init__(self, path, local):
'\n Initialize the dataset\n :param path: Path to the hdf5 dataset file\n :param local: True if the path is to a local file, False otherwise\n '
self.path = path
self.local = local
if (not local):
with file_io.FileIO(path, mode='rb') as dataset_f:
with open('dataset.h5', 'wb') as local_dataset:
local_dataset.write(dataset_f.read())
path = 'dataset.h5'
hf = h5py.File(path, 'r')
self.x = hf.get('x')[:]
self.y = hf.get('y')[:]
hf.close()
self.x = ((self.x.astype(np.float32) - 127.5) / 127.5)
print('Loaded dataset')
print('X:', self.x.shape)
print('Y:', self.y.shape)<|docstring|>Initialize the dataset
:param path: Path to the hdf5 dataset file
:param local: True if the path is to a local file, False otherwise<|endoftext|> |
4584428157da77cc988ed99c66ea60283fa3b595654a27f80099e564fdeb4a59 | def __make_overfit(self):
'\n Modify dataset for overfitting by only including 3 samples from each class\n :return:\n '
minimal_x = self.x[:1]
minimal_y = self.y[:1]
per_class = 3
i = 1
found = np.array([0 for _ in range(self.y.shape[(- 1)])])
found[np.argmax(minimal_y[0])] += 1
while (sum(found) < (self.y.shape[(- 1)] * per_class)):
for c in range(self.y.shape[(- 1)]):
if (found[np.argmax(self.y[i])] < per_class):
minimal_x = np.concatenate([minimal_x, self.x[i:(i + 1)]])
minimal_y = np.concatenate([minimal_y, self.y[i:(i + 1)]])
found[np.argmax(self.y[i])] += 1
i += 1
self.x = minimal_x
self.y = minimal_y | Modify dataset for overfitting by only including 3 samples from each class
:return: | trainer/dataset.py | __make_overfit | jessica-dl/2XB3-ML-Training | 0 | python | def __make_overfit(self):
'\n Modify dataset for overfitting by only including 3 samples from each class\n :return:\n '
minimal_x = self.x[:1]
minimal_y = self.y[:1]
per_class = 3
i = 1
found = np.array([0 for _ in range(self.y.shape[(- 1)])])
found[np.argmax(minimal_y[0])] += 1
while (sum(found) < (self.y.shape[(- 1)] * per_class)):
for c in range(self.y.shape[(- 1)]):
if (found[np.argmax(self.y[i])] < per_class):
minimal_x = np.concatenate([minimal_x, self.x[i:(i + 1)]])
minimal_y = np.concatenate([minimal_y, self.y[i:(i + 1)]])
found[np.argmax(self.y[i])] += 1
i += 1
self.x = minimal_x
self.y = minimal_y | def __make_overfit(self):
'\n Modify dataset for overfitting by only including 3 samples from each class\n :return:\n '
minimal_x = self.x[:1]
minimal_y = self.y[:1]
per_class = 3
i = 1
found = np.array([0 for _ in range(self.y.shape[(- 1)])])
found[np.argmax(minimal_y[0])] += 1
while (sum(found) < (self.y.shape[(- 1)] * per_class)):
for c in range(self.y.shape[(- 1)]):
if (found[np.argmax(self.y[i])] < per_class):
minimal_x = np.concatenate([minimal_x, self.x[i:(i + 1)]])
minimal_y = np.concatenate([minimal_y, self.y[i:(i + 1)]])
found[np.argmax(self.y[i])] += 1
i += 1
self.x = minimal_x
self.y = minimal_y<|docstring|>Modify dataset for overfitting by only including 3 samples from each class
:return:<|endoftext|> |
d27d460379f6d7cdd05f41b8f1ae44662ca9b4dfb3b86d7f99bbc396e4d8a14f | @Tracking
def __init__(self, finn_code: str):
'\n Constructor / Instantiate the class.\n\n Parameters\n ----------\n finn_code : str\n finn_code to be validated\n\n '
self.name = self.__class__.__name__
Assertor.assert_data_types([finn_code], [str])
super().__init__(name=self.name, desc='rules: {} \\n id: Validate Finn Code'.format(Finn.rules()))
self.finn_code = finn_code | Constructor / Instantiate the class.
Parameters
----------
finn_code : str
finn_code to be validated | source/app/processing/engine/validate_finn_code.py | __init__ | seemir/stressa | 0 | python | @Tracking
def __init__(self, finn_code: str):
'\n Constructor / Instantiate the class.\n\n Parameters\n ----------\n finn_code : str\n finn_code to be validated\n\n '
self.name = self.__class__.__name__
Assertor.assert_data_types([finn_code], [str])
super().__init__(name=self.name, desc='rules: {} \\n id: Validate Finn Code'.format(Finn.rules()))
self.finn_code = finn_code | @Tracking
def __init__(self, finn_code: str):
'\n Constructor / Instantiate the class.\n\n Parameters\n ----------\n finn_code : str\n finn_code to be validated\n\n '
self.name = self.__class__.__name__
Assertor.assert_data_types([finn_code], [str])
super().__init__(name=self.name, desc='rules: {} \\n id: Validate Finn Code'.format(Finn.rules()))
self.finn_code = finn_code<|docstring|>Constructor / Instantiate the class.
Parameters
----------
finn_code : str
finn_code to be validated<|endoftext|> |
91f5d2055288ebb8c0f3fb048e6a8d88ed3a3cd38f7744be22271d341beae790 | @Tracking
def run(self):
'\n method for running the operation\n\n Returns\n -------\n out : str\n validated Finn code str\n\n '
Finn(self.finn_code).validate_finn_code()
return self.finn_code | method for running the operation
Returns
-------
out : str
validated Finn code str | source/app/processing/engine/validate_finn_code.py | run | seemir/stressa | 0 | python | @Tracking
def run(self):
'\n method for running the operation\n\n Returns\n -------\n out : str\n validated Finn code str\n\n '
Finn(self.finn_code).validate_finn_code()
return self.finn_code | @Tracking
def run(self):
'\n method for running the operation\n\n Returns\n -------\n out : str\n validated Finn code str\n\n '
Finn(self.finn_code).validate_finn_code()
return self.finn_code<|docstring|>method for running the operation
Returns
-------
out : str
validated Finn code str<|endoftext|> |
5fd40b6a6e976102ba2a0543dbc770f121d97cc3bacffa0aea330e985761d071 | def __init__(self, title, template, method_config):
'\n This class creates an API Gateway object with one or multiple methods attached.\n AWS Cloud Formation Links:\n RestApi: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html\n Resource: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html\n Method: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html\n Integration:\n https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html\n Troposhere link:\n https://github.com/cloudtools/troposphere/blob/master/troposphere/apigateway.py\n :param title: title of the api gateway and associated resources to be used in cloud formation\n :param template: the troposphere template object to update\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
self.title = title
self.template = template
self.methods = []
self.method_responses = []
self.integration_responses = []
self.method_config = method_config
self.permissions = []
self.api = self.template.add_resource(RestApi(self.title, Name=Join('-', [Ref('AWS::StackName'), title])))
for method in self.method_config:
resource = self.create_resource(method)
self.get_responses(method)
integration = self.create_integration(method, self.get_lambda_reference(method.lambda_unit))
self.add_method(resource, integration, method)
dependencies = []
for method in self.methods:
dependencies.append(method.title)
self.deployment = Deployment('{0}Deployment'.format(self.title), Description=Join('', [Ref('AWS::StackName'), ' Deployment created for APIGW ', self.title]), RestApiId=Ref(self.api), StageName='amz_deploy', DependsOn=dependencies)
self.template.add_resource(self.deployment)
self.template.add_output(Output((self.deployment.title + 'URL'), Description='URL of API deployment: {0}'.format(self.deployment.title), Value=Join('', ['https://', Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com/', self.deployment.StageName]))) | This class creates an API Gateway object with one or multiple methods attached.
AWS Cloud Formation Links:
RestApi: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html
Resource: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html
Method: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html
Integration:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html
Troposhere link:
https://github.com/cloudtools/troposphere/blob/master/troposphere/apigateway.py
:param title: title of the api gateway and associated resources to be used in cloud formation
:param template: the troposphere template object to update
:param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values
values | aws/amazonia/amazonia/classes/amz_api_gateway.py | __init__ | linz/Geodesy-Web-Services | 2 | python | def __init__(self, title, template, method_config):
'\n This class creates an API Gateway object with one or multiple methods attached.\n AWS Cloud Formation Links:\n RestApi: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html\n Resource: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html\n Method: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html\n Integration:\n https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html\n Troposhere link:\n https://github.com/cloudtools/troposphere/blob/master/troposphere/apigateway.py\n :param title: title of the api gateway and associated resources to be used in cloud formation\n :param template: the troposphere template object to update\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
self.title = title
self.template = template
self.methods = []
self.method_responses = []
self.integration_responses = []
self.method_config = method_config
self.permissions = []
self.api = self.template.add_resource(RestApi(self.title, Name=Join('-', [Ref('AWS::StackName'), title])))
for method in self.method_config:
resource = self.create_resource(method)
self.get_responses(method)
integration = self.create_integration(method, self.get_lambda_reference(method.lambda_unit))
self.add_method(resource, integration, method)
dependencies = []
for method in self.methods:
dependencies.append(method.title)
self.deployment = Deployment('{0}Deployment'.format(self.title), Description=Join(, [Ref('AWS::StackName'), ' Deployment created for APIGW ', self.title]), RestApiId=Ref(self.api), StageName='amz_deploy', DependsOn=dependencies)
self.template.add_resource(self.deployment)
self.template.add_output(Output((self.deployment.title + 'URL'), Description='URL of API deployment: {0}'.format(self.deployment.title), Value=Join(, ['https://', Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com/', self.deployment.StageName]))) | def __init__(self, title, template, method_config):
'\n This class creates an API Gateway object with one or multiple methods attached.\n AWS Cloud Formation Links:\n RestApi: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html\n Resource: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html\n Method: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html\n Integration:\n https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html\n Troposhere link:\n https://github.com/cloudtools/troposphere/blob/master/troposphere/apigateway.py\n :param title: title of the api gateway and associated resources to be used in cloud formation\n :param template: the troposphere template object to update\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
self.title = title
self.template = template
self.methods = []
self.method_responses = []
self.integration_responses = []
self.method_config = method_config
self.permissions = []
self.api = self.template.add_resource(RestApi(self.title, Name=Join('-', [Ref('AWS::StackName'), title])))
for method in self.method_config:
resource = self.create_resource(method)
self.get_responses(method)
integration = self.create_integration(method, self.get_lambda_reference(method.lambda_unit))
self.add_method(resource, integration, method)
dependencies = []
for method in self.methods:
dependencies.append(method.title)
self.deployment = Deployment('{0}Deployment'.format(self.title), Description=Join(, [Ref('AWS::StackName'), ' Deployment created for APIGW ', self.title]), RestApiId=Ref(self.api), StageName='amz_deploy', DependsOn=dependencies)
self.template.add_resource(self.deployment)
self.template.add_output(Output((self.deployment.title + 'URL'), Description='URL of API deployment: {0}'.format(self.deployment.title), Value=Join(, ['https://', Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com/', self.deployment.StageName])))<|docstring|>This class creates an API Gateway object with one or multiple methods attached.
AWS Cloud Formation Links:
RestApi: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html
Resource: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html
Method: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html
Integration:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html
Troposhere link:
https://github.com/cloudtools/troposphere/blob/master/troposphere/apigateway.py
:param title: title of the api gateway and associated resources to be used in cloud formation
:param template: the troposphere template object to update
:param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values
values<|endoftext|> |
c5d59a6f0e55e63ab98f94a88dbf01a0c435fdad83a545455b34340c530f0d59 | def create_resource(self, method_config):
'\n Creates a resource using a single provided ApiGatewayMethodConfig object.\n :param method_config: a single ApiGatewayMethodConfig object\n :return: a troposphere Resource object that links the API with the method_config provided\n '
return self.template.add_resource(Resource('{0}{1}'.format(self.api.title, method_config.method_name), ParentId=GetAtt(self.api.title, 'RootResourceId'), RestApiId=Ref(self.api), PathPart=method_config.method_name)) | Creates a resource using a single provided ApiGatewayMethodConfig object.
:param method_config: a single ApiGatewayMethodConfig object
:return: a troposphere Resource object that links the API with the method_config provided | aws/amazonia/amazonia/classes/amz_api_gateway.py | create_resource | linz/Geodesy-Web-Services | 2 | python | def create_resource(self, method_config):
'\n Creates a resource using a single provided ApiGatewayMethodConfig object.\n :param method_config: a single ApiGatewayMethodConfig object\n :return: a troposphere Resource object that links the API with the method_config provided\n '
return self.template.add_resource(Resource('{0}{1}'.format(self.api.title, method_config.method_name), ParentId=GetAtt(self.api.title, 'RootResourceId'), RestApiId=Ref(self.api), PathPart=method_config.method_name)) | def create_resource(self, method_config):
'\n Creates a resource using a single provided ApiGatewayMethodConfig object.\n :param method_config: a single ApiGatewayMethodConfig object\n :return: a troposphere Resource object that links the API with the method_config provided\n '
return self.template.add_resource(Resource('{0}{1}'.format(self.api.title, method_config.method_name), ParentId=GetAtt(self.api.title, 'RootResourceId'), RestApiId=Ref(self.api), PathPart=method_config.method_name))<|docstring|>Creates a resource using a single provided ApiGatewayMethodConfig object.
:param method_config: a single ApiGatewayMethodConfig object
:return: a troposphere Resource object that links the API with the method_config provided<|endoftext|> |
68ed345ff45424ed1a4b67cae076ee914cd95539017a4bef5ca2b8ebd509b7eb | def create_integration(self, method_config, lambda_arn):
'\n Creates an integration object using a single provided ApiGatewayMethodConfig object.\n :param method_config: a single ApiGatewayMethodConfig object\n :param lambda_arn: the ARN of a lambda function to point this integration at.\n :return: a troposphere integration object\n '
integration = Integration('{0}Integration'.format(method_config.method_name), Type='AWS', IntegrationHttpMethod=method_config.httpmethod, IntegrationResponses=self.integration_responses, RequestTemplates=method_config.request.templates, Uri=Join('', ['arn:aws:apigateway:ap-southeast-2:lambda:path/2015-03-31/functions/', lambda_arn, '/invocations']))
perm = self.template.add_resource(Permission('{0}Permission'.format(integration.title), Action='lambda:InvokeFunction', FunctionName=lambda_arn, Principal='apigateway.amazonaws.com'))
self.permissions.append(perm)
integration.resource['PassthroughBehavior'] = 'WHEN_NO_TEMPLATES'
return integration | Creates an integration object using a single provided ApiGatewayMethodConfig object.
:param method_config: a single ApiGatewayMethodConfig object
:param lambda_arn: the ARN of a lambda function to point this integration at.
:return: a troposphere integration object | aws/amazonia/amazonia/classes/amz_api_gateway.py | create_integration | linz/Geodesy-Web-Services | 2 | python | def create_integration(self, method_config, lambda_arn):
'\n Creates an integration object using a single provided ApiGatewayMethodConfig object.\n :param method_config: a single ApiGatewayMethodConfig object\n :param lambda_arn: the ARN of a lambda function to point this integration at.\n :return: a troposphere integration object\n '
integration = Integration('{0}Integration'.format(method_config.method_name), Type='AWS', IntegrationHttpMethod=method_config.httpmethod, IntegrationResponses=self.integration_responses, RequestTemplates=method_config.request.templates, Uri=Join(, ['arn:aws:apigateway:ap-southeast-2:lambda:path/2015-03-31/functions/', lambda_arn, '/invocations']))
perm = self.template.add_resource(Permission('{0}Permission'.format(integration.title), Action='lambda:InvokeFunction', FunctionName=lambda_arn, Principal='apigateway.amazonaws.com'))
self.permissions.append(perm)
integration.resource['PassthroughBehavior'] = 'WHEN_NO_TEMPLATES'
return integration | def create_integration(self, method_config, lambda_arn):
'\n Creates an integration object using a single provided ApiGatewayMethodConfig object.\n :param method_config: a single ApiGatewayMethodConfig object\n :param lambda_arn: the ARN of a lambda function to point this integration at.\n :return: a troposphere integration object\n '
integration = Integration('{0}Integration'.format(method_config.method_name), Type='AWS', IntegrationHttpMethod=method_config.httpmethod, IntegrationResponses=self.integration_responses, RequestTemplates=method_config.request.templates, Uri=Join(, ['arn:aws:apigateway:ap-southeast-2:lambda:path/2015-03-31/functions/', lambda_arn, '/invocations']))
perm = self.template.add_resource(Permission('{0}Permission'.format(integration.title), Action='lambda:InvokeFunction', FunctionName=lambda_arn, Principal='apigateway.amazonaws.com'))
self.permissions.append(perm)
integration.resource['PassthroughBehavior'] = 'WHEN_NO_TEMPLATES'
return integration<|docstring|>Creates an integration object using a single provided ApiGatewayMethodConfig object.
:param method_config: a single ApiGatewayMethodConfig object
:param lambda_arn: the ARN of a lambda function to point this integration at.
:return: a troposphere integration object<|endoftext|> |
72b7b4ec7f5e81c53d3aaa5987301134a41003186574e4f64320612f79ed8347 | def get_responses(self, method_config):
'\n Creates a method and integration response object in troposphere from a provided ApiGatewayMethodConfig object.\n :param method_config: a preconfigured ApiGatewayMethodConfig object\n '
self.method_responses = []
self.integration_responses = []
for (number, response) in enumerate(method_config.responses):
method_response = MethodResponse('{0}Response{1}'.format(method_config.method_name, number), StatusCode=response.statuscode)
if response.models:
method_response.ResponseModels = response.models
integration_response = IntegrationResponse('{0}IntegrationResponse{1}'.format(method_config.method_name, number), StatusCode=response.statuscode, ResponseTemplates=response.templates, SelectionPattern=response.selectionpattern)
if response.parameters:
method_response.ResponseParameters = response.parameters
integration_response.ResponseParameters = response.parameters
self.integration_responses.append(integration_response)
self.method_responses.append(method_response) | Creates a method and integration response object in troposphere from a provided ApiGatewayMethodConfig object.
:param method_config: a preconfigured ApiGatewayMethodConfig object | aws/amazonia/amazonia/classes/amz_api_gateway.py | get_responses | linz/Geodesy-Web-Services | 2 | python | def get_responses(self, method_config):
'\n Creates a method and integration response object in troposphere from a provided ApiGatewayMethodConfig object.\n :param method_config: a preconfigured ApiGatewayMethodConfig object\n '
self.method_responses = []
self.integration_responses = []
for (number, response) in enumerate(method_config.responses):
method_response = MethodResponse('{0}Response{1}'.format(method_config.method_name, number), StatusCode=response.statuscode)
if response.models:
method_response.ResponseModels = response.models
integration_response = IntegrationResponse('{0}IntegrationResponse{1}'.format(method_config.method_name, number), StatusCode=response.statuscode, ResponseTemplates=response.templates, SelectionPattern=response.selectionpattern)
if response.parameters:
method_response.ResponseParameters = response.parameters
integration_response.ResponseParameters = response.parameters
self.integration_responses.append(integration_response)
self.method_responses.append(method_response) | def get_responses(self, method_config):
'\n Creates a method and integration response object in troposphere from a provided ApiGatewayMethodConfig object.\n :param method_config: a preconfigured ApiGatewayMethodConfig object\n '
self.method_responses = []
self.integration_responses = []
for (number, response) in enumerate(method_config.responses):
method_response = MethodResponse('{0}Response{1}'.format(method_config.method_name, number), StatusCode=response.statuscode)
if response.models:
method_response.ResponseModels = response.models
integration_response = IntegrationResponse('{0}IntegrationResponse{1}'.format(method_config.method_name, number), StatusCode=response.statuscode, ResponseTemplates=response.templates, SelectionPattern=response.selectionpattern)
if response.parameters:
method_response.ResponseParameters = response.parameters
integration_response.ResponseParameters = response.parameters
self.integration_responses.append(integration_response)
self.method_responses.append(method_response)<|docstring|>Creates a method and integration response object in troposphere from a provided ApiGatewayMethodConfig object.
:param method_config: a preconfigured ApiGatewayMethodConfig object<|endoftext|> |
49e38abbb146127779f6994049248f001cdd92b9f63ef59df1d47e47a7283518 | def add_method(self, resource, integration, method_config):
'\n Creates a Method as a part of this api and adds it to the template.\n :param resource: The resource that has been created for this api/method pair.\n :param integration: An Integration object for this method.\n :param method_config: The method_config object with details for the method.\n '
method = Method('{0}Method'.format(method_config.method_name), RestApiId=Ref(self.api), AuthorizationType=method_config.authorizationtype, ResourceId=Ref(resource), HttpMethod=method_config.httpmethod, Integration=integration, MethodResponses=self.method_responses)
if method_config.request.parameters:
method.RequestParameters = method_config.request.parameters
self.method_responses = []
self.integration_responses = []
self.methods.append(method)
self.template.add_resource(method) | Creates a Method as a part of this api and adds it to the template.
:param resource: The resource that has been created for this api/method pair.
:param integration: An Integration object for this method.
:param method_config: The method_config object with details for the method. | aws/amazonia/amazonia/classes/amz_api_gateway.py | add_method | linz/Geodesy-Web-Services | 2 | python | def add_method(self, resource, integration, method_config):
'\n Creates a Method as a part of this api and adds it to the template.\n :param resource: The resource that has been created for this api/method pair.\n :param integration: An Integration object for this method.\n :param method_config: The method_config object with details for the method.\n '
method = Method('{0}Method'.format(method_config.method_name), RestApiId=Ref(self.api), AuthorizationType=method_config.authorizationtype, ResourceId=Ref(resource), HttpMethod=method_config.httpmethod, Integration=integration, MethodResponses=self.method_responses)
if method_config.request.parameters:
method.RequestParameters = method_config.request.parameters
self.method_responses = []
self.integration_responses = []
self.methods.append(method)
self.template.add_resource(method) | def add_method(self, resource, integration, method_config):
'\n Creates a Method as a part of this api and adds it to the template.\n :param resource: The resource that has been created for this api/method pair.\n :param integration: An Integration object for this method.\n :param method_config: The method_config object with details for the method.\n '
method = Method('{0}Method'.format(method_config.method_name), RestApiId=Ref(self.api), AuthorizationType=method_config.authorizationtype, ResourceId=Ref(resource), HttpMethod=method_config.httpmethod, Integration=integration, MethodResponses=self.method_responses)
if method_config.request.parameters:
method.RequestParameters = method_config.request.parameters
self.method_responses = []
self.integration_responses = []
self.methods.append(method)
self.template.add_resource(method)<|docstring|>Creates a Method as a part of this api and adds it to the template.
:param resource: The resource that has been created for this api/method pair.
:param integration: An Integration object for this method.
:param method_config: The method_config object with details for the method.<|endoftext|> |
aef2ee301e71929e05474ab1872b4fefeee2274fa74dd31f72d582b8aa38210c | def get_lambda_reference(self, lambda_name):
'\n Define abstract method to be overridden by implementing classes\n :param lambda_name: amazonia name of lamda\n '
raise NotImplementedError('Please Implement this method') | Define abstract method to be overridden by implementing classes
:param lambda_name: amazonia name of lamda | aws/amazonia/amazonia/classes/amz_api_gateway.py | get_lambda_reference | linz/Geodesy-Web-Services | 2 | python | def get_lambda_reference(self, lambda_name):
'\n Define abstract method to be overridden by implementing classes\n :param lambda_name: amazonia name of lamda\n '
raise NotImplementedError('Please Implement this method') | def get_lambda_reference(self, lambda_name):
'\n Define abstract method to be overridden by implementing classes\n :param lambda_name: amazonia name of lamda\n '
raise NotImplementedError('Please Implement this method')<|docstring|>Define abstract method to be overridden by implementing classes
:param lambda_name: amazonia name of lamda<|endoftext|> |
2b1de68f75287feea094d1b13d426d950404fcfe79781cdf15f5b65be2e2f614 | def __init__(self, tree_name, leaf_title, template, method_config):
'\n Create an APi Gateway as a leaf, part of cross referenced stack\n :param leaf_title: title of the API Gateway as part of cross referenced stack\n :param tree_name: name of cross referenced stack\n :param template: troposphere template\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
self.tree_name = tree_name
super(ApiGatewayLeaf, self).__init__(leaf_title, template, method_config)
self.template.add_output(Output((self.deployment.title + 'Endpoint'), Description='Endpoint of API deployment: {0}'.format(self.deployment.title), Value=Join('', [Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com']), Export=Export((((self.tree_name + '-') + self.title) + '-Endpoint')))) | Create an APi Gateway as a leaf, part of cross referenced stack
:param leaf_title: title of the API Gateway as part of cross referenced stack
:param tree_name: name of cross referenced stack
:param template: troposphere template
:param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values
values | aws/amazonia/amazonia/classes/amz_api_gateway.py | __init__ | linz/Geodesy-Web-Services | 2 | python | def __init__(self, tree_name, leaf_title, template, method_config):
'\n Create an APi Gateway as a leaf, part of cross referenced stack\n :param leaf_title: title of the API Gateway as part of cross referenced stack\n :param tree_name: name of cross referenced stack\n :param template: troposphere template\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
self.tree_name = tree_name
super(ApiGatewayLeaf, self).__init__(leaf_title, template, method_config)
self.template.add_output(Output((self.deployment.title + 'Endpoint'), Description='Endpoint of API deployment: {0}'.format(self.deployment.title), Value=Join(, [Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com']), Export=Export((((self.tree_name + '-') + self.title) + '-Endpoint')))) | def __init__(self, tree_name, leaf_title, template, method_config):
'\n Create an APi Gateway as a leaf, part of cross referenced stack\n :param leaf_title: title of the API Gateway as part of cross referenced stack\n :param tree_name: name of cross referenced stack\n :param template: troposphere template\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
self.tree_name = tree_name
super(ApiGatewayLeaf, self).__init__(leaf_title, template, method_config)
self.template.add_output(Output((self.deployment.title + 'Endpoint'), Description='Endpoint of API deployment: {0}'.format(self.deployment.title), Value=Join(, [Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com']), Export=Export((((self.tree_name + '-') + self.title) + '-Endpoint'))))<|docstring|>Create an APi Gateway as a leaf, part of cross referenced stack
:param leaf_title: title of the API Gateway as part of cross referenced stack
:param tree_name: name of cross referenced stack
:param template: troposphere template
:param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values
values<|endoftext|> |
182fc73d5534b24eda6586cf450fe31c15cc03efc3344e32af9ace33fcf5c4ec | def get_lambda_reference(self, lambda_name):
'\n Return the lambda arn from a different stack in the same tree\n :param lambda_name: amazonia name of lamda\n :return: The ARN of the target Lambda\n '
return ImportValue((((self.tree_name + '-') + lambda_name) + '-Arn')) | Return the lambda arn from a different stack in the same tree
:param lambda_name: amazonia name of lamda
:return: The ARN of the target Lambda | aws/amazonia/amazonia/classes/amz_api_gateway.py | get_lambda_reference | linz/Geodesy-Web-Services | 2 | python | def get_lambda_reference(self, lambda_name):
'\n Return the lambda arn from a different stack in the same tree\n :param lambda_name: amazonia name of lamda\n :return: The ARN of the target Lambda\n '
return ImportValue((((self.tree_name + '-') + lambda_name) + '-Arn')) | def get_lambda_reference(self, lambda_name):
'\n Return the lambda arn from a different stack in the same tree\n :param lambda_name: amazonia name of lamda\n :return: The ARN of the target Lambda\n '
return ImportValue((((self.tree_name + '-') + lambda_name) + '-Arn'))<|docstring|>Return the lambda arn from a different stack in the same tree
:param lambda_name: amazonia name of lamda
:return: The ARN of the target Lambda<|endoftext|> |
68ef3164b453e87b2dc1f20bf9231a093f538348cef5d3e5b97b369501cf33c5 | def __init__(self, unit_title, template, method_config, stack_config):
'\n Create an APi Gateway as a unit, part of an integrated stack\n :param unit_title: title of the API Gateway as part of an integrated stack\n :param template: troposphere template\n :param stack_config: shared stack configuration object to store generated API Gateway endpoint\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
super(ApiGatewayUnit, self).__init__(title=unit_title, template=template, method_config=method_config)
self.stack_config = stack_config
self.stack_config.endpoints[unit_title] = Join('', [Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com']) | Create an APi Gateway as a unit, part of an integrated stack
:param unit_title: title of the API Gateway as part of an integrated stack
:param template: troposphere template
:param stack_config: shared stack configuration object to store generated API Gateway endpoint
:param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values
values | aws/amazonia/amazonia/classes/amz_api_gateway.py | __init__ | linz/Geodesy-Web-Services | 2 | python | def __init__(self, unit_title, template, method_config, stack_config):
'\n Create an APi Gateway as a unit, part of an integrated stack\n :param unit_title: title of the API Gateway as part of an integrated stack\n :param template: troposphere template\n :param stack_config: shared stack configuration object to store generated API Gateway endpoint\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
super(ApiGatewayUnit, self).__init__(title=unit_title, template=template, method_config=method_config)
self.stack_config = stack_config
self.stack_config.endpoints[unit_title] = Join(, [Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com']) | def __init__(self, unit_title, template, method_config, stack_config):
'\n Create an APi Gateway as a unit, part of an integrated stack\n :param unit_title: title of the API Gateway as part of an integrated stack\n :param template: troposphere template\n :param stack_config: shared stack configuration object to store generated API Gateway endpoint\n :param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values\n values\n '
super(ApiGatewayUnit, self).__init__(title=unit_title, template=template, method_config=method_config)
self.stack_config = stack_config
self.stack_config.endpoints[unit_title] = Join(, [Ref(self.api), '.execute-api.', Ref('AWS::Region'), '.amazonaws.com'])<|docstring|>Create an APi Gateway as a unit, part of an integrated stack
:param unit_title: title of the API Gateway as part of an integrated stack
:param template: troposphere template
:param stack_config: shared stack configuration object to store generated API Gateway endpoint
:param method_config: a list of one or many ApiGatewayMethodConfig objects with data prefilled from yaml values
values<|endoftext|> |
507fe658e148b7f02c1df86d41b4562d11ba91dd1897a9bf7e307a4e9d9b5133 | def get_lambda_reference(self, lambda_name):
'\n Return the lambda arn from a lambda unit\n :param lambda_name: amazonia name of lamda\n :return: The ARN of the target Lambda\n '
return GetAtt(lambda_name, 'Arn') | Return the lambda arn from a lambda unit
:param lambda_name: amazonia name of lamda
:return: The ARN of the target Lambda | aws/amazonia/amazonia/classes/amz_api_gateway.py | get_lambda_reference | linz/Geodesy-Web-Services | 2 | python | def get_lambda_reference(self, lambda_name):
'\n Return the lambda arn from a lambda unit\n :param lambda_name: amazonia name of lamda\n :return: The ARN of the target Lambda\n '
return GetAtt(lambda_name, 'Arn') | def get_lambda_reference(self, lambda_name):
'\n Return the lambda arn from a lambda unit\n :param lambda_name: amazonia name of lamda\n :return: The ARN of the target Lambda\n '
return GetAtt(lambda_name, 'Arn')<|docstring|>Return the lambda arn from a lambda unit
:param lambda_name: amazonia name of lamda
:return: The ARN of the target Lambda<|endoftext|> |
6bebf2b5110a4df24d82736dfbac20675fa83e924c18e2d47939b6cc33ad6942 | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.CreateResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/CreateResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.CreateResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.CreateResourceResponse.FromString)
self.AlterResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/AlterResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AlterResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AlterResourceResponse.FromString)
self.DropResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/DropResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DropResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DropResourceResponse.FromString)
self.ListResources = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/ListResources', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.ListResourcesRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.ListResourcesResponse.FromString)
self.DescribeResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/DescribeResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DescribeResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DescribeResourceResponse.FromString)
self.AcquireResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/AcquireResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AcquireResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AcquireResourceResponse.FromString) | Constructor.
Args:
channel: A grpc.Channel. | kikimr/public/api/grpc/ydb_rate_limiter_v1_pb2_grpc.py | __init__ | clumpytuna/ydb-python-sdk | 19 | python | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.CreateResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/CreateResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.CreateResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.CreateResourceResponse.FromString)
self.AlterResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/AlterResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AlterResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AlterResourceResponse.FromString)
self.DropResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/DropResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DropResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DropResourceResponse.FromString)
self.ListResources = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/ListResources', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.ListResourcesRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.ListResourcesResponse.FromString)
self.DescribeResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/DescribeResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DescribeResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DescribeResourceResponse.FromString)
self.AcquireResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/AcquireResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AcquireResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AcquireResourceResponse.FromString) | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.CreateResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/CreateResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.CreateResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.CreateResourceResponse.FromString)
self.AlterResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/AlterResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AlterResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AlterResourceResponse.FromString)
self.DropResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/DropResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DropResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DropResourceResponse.FromString)
self.ListResources = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/ListResources', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.ListResourcesRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.ListResourcesResponse.FromString)
self.DescribeResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/DescribeResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DescribeResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.DescribeResourceResponse.FromString)
self.AcquireResource = channel.unary_unary('/Ydb.RateLimiter.V1.RateLimiterService/AcquireResource', request_serializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AcquireResourceRequest.SerializeToString, response_deserializer=kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2.AcquireResourceResponse.FromString)<|docstring|>Constructor.
Args:
channel: A grpc.Channel.<|endoftext|> |
3c841f685f1284e9a64449304c0de4c4dba9d1eb4d49c2d0b81fb24fa42c4ab5 | def CreateResource(self, request, context):
'Create a new resource in existing coordination node.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Create a new resource in existing coordination node. | kikimr/public/api/grpc/ydb_rate_limiter_v1_pb2_grpc.py | CreateResource | clumpytuna/ydb-python-sdk | 19 | python | def CreateResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | def CreateResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')<|docstring|>Create a new resource in existing coordination node.<|endoftext|> |
ef913decebdf75e01657a4fae27f1ac128243a126e915d6f22bff1350f2ea23b | def AlterResource(self, request, context):
'Update a resource in coordination node.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Update a resource in coordination node. | kikimr/public/api/grpc/ydb_rate_limiter_v1_pb2_grpc.py | AlterResource | clumpytuna/ydb-python-sdk | 19 | python | def AlterResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | def AlterResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')<|docstring|>Update a resource in coordination node.<|endoftext|> |
fd325c573168c34b9f9e5795b882628118c04f1059b2cf2dc4364f78581beedc | def DropResource(self, request, context):
'Delete a resource from coordination node.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Delete a resource from coordination node. | kikimr/public/api/grpc/ydb_rate_limiter_v1_pb2_grpc.py | DropResource | clumpytuna/ydb-python-sdk | 19 | python | def DropResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | def DropResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')<|docstring|>Delete a resource from coordination node.<|endoftext|> |
f1d1eb13a7e9dd37617fc46e35e2c1651a4a0d18a26167dc2089398bf5849fd6 | def ListResources(self, request, context):
'List resources in given coordination node.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | List resources in given coordination node. | kikimr/public/api/grpc/ydb_rate_limiter_v1_pb2_grpc.py | ListResources | clumpytuna/ydb-python-sdk | 19 | python | def ListResources(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | def ListResources(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')<|docstring|>List resources in given coordination node.<|endoftext|> |
e94a0078baeca4523cb55765db61e5575b82a7791c87fa693c6af6655150ee9c | def DescribeResource(self, request, context):
'Describe properties of resource in coordination node.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Describe properties of resource in coordination node. | kikimr/public/api/grpc/ydb_rate_limiter_v1_pb2_grpc.py | DescribeResource | clumpytuna/ydb-python-sdk | 19 | python | def DescribeResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | def DescribeResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')<|docstring|>Describe properties of resource in coordination node.<|endoftext|> |
30961cc7a1b0ba8e4728851ee23ed36eb0c84aa57ce63caf74ea1f136cbe21fe | def AcquireResource(self, request, context):
'Take units for usage of a resource in coordination node.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Take units for usage of a resource in coordination node. | kikimr/public/api/grpc/ydb_rate_limiter_v1_pb2_grpc.py | AcquireResource | clumpytuna/ydb-python-sdk | 19 | python | def AcquireResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | def AcquireResource(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')<|docstring|>Take units for usage of a resource in coordination node.<|endoftext|> |
40ec0d29ab3152db88fc3f0ca1a6d8a26d0162b1e1cef1d0b53096332517de7d | def get_current_timestamp():
'\n Returns the current timestamp, used to set ``timestamp`` for new\n :py:class:`ProposedTransaction` objects.\n\n Split out into a separate function so that it can be mocked during\n unit tests.\n '
return unix_timestamp(datetime.utcnow().timetuple()) | Returns the current timestamp, used to set ``timestamp`` for new
:py:class:`ProposedTransaction` objects.
Split out into a separate function so that it can be mocked during
unit tests. | src/cornode/transaction.py | get_current_timestamp | Cornode/cornode.lib.py | 0 | python | def get_current_timestamp():
'\n Returns the current timestamp, used to set ``timestamp`` for new\n :py:class:`ProposedTransaction` objects.\n\n Split out into a separate function so that it can be mocked during\n unit tests.\n '
return unix_timestamp(datetime.utcnow().timetuple()) | def get_current_timestamp():
'\n Returns the current timestamp, used to set ``timestamp`` for new\n :py:class:`ProposedTransaction` objects.\n\n Split out into a separate function so that it can be mocked during\n unit tests.\n '
return unix_timestamp(datetime.utcnow().timetuple())<|docstring|>Returns the current timestamp, used to set ``timestamp`` for new
:py:class:`ProposedTransaction` objects.
Split out into a separate function so that it can be mocked during
unit tests.<|endoftext|> |
c3b085863f02799a5eb213b0d8f181b74bcf987dddb1e0b4917680e71b9062af | @classmethod
def from_tryte_string(cls, trytes):
'\n Creates a Transaction object from a sequence of trytes.\n '
tryte_string = TransactionTrytes(trytes)
hash_ = ([0] * HASH_LENGTH)
sponge = Curl()
sponge.absorb(tryte_string.as_trits())
sponge.squeeze(hash_)
return cls(hash_=TransactionHash.from_trits(hash_), signature_message_fragment=Fragment(tryte_string[0:2187]), address=Address(tryte_string[2187:2268]), value=int_from_trits(tryte_string[2268:2295].as_trits()), tag=Tag(tryte_string[2295:2322]), timestamp=int_from_trits(tryte_string[2322:2331].as_trits()), current_index=int_from_trits(tryte_string[2331:2340].as_trits()), last_index=int_from_trits(tryte_string[2340:2349].as_trits()), bundle_hash=BundleHash(tryte_string[2349:2430]), trunk_transaction_hash=TransactionHash(tryte_string[2430:2511]), branch_transaction_hash=TransactionHash(tryte_string[2511:2592]), nonce=Hash(tryte_string[2592:2673])) | Creates a Transaction object from a sequence of trytes. | src/cornode/transaction.py | from_tryte_string | Cornode/cornode.lib.py | 0 | python | @classmethod
def from_tryte_string(cls, trytes):
'\n \n '
tryte_string = TransactionTrytes(trytes)
hash_ = ([0] * HASH_LENGTH)
sponge = Curl()
sponge.absorb(tryte_string.as_trits())
sponge.squeeze(hash_)
return cls(hash_=TransactionHash.from_trits(hash_), signature_message_fragment=Fragment(tryte_string[0:2187]), address=Address(tryte_string[2187:2268]), value=int_from_trits(tryte_string[2268:2295].as_trits()), tag=Tag(tryte_string[2295:2322]), timestamp=int_from_trits(tryte_string[2322:2331].as_trits()), current_index=int_from_trits(tryte_string[2331:2340].as_trits()), last_index=int_from_trits(tryte_string[2340:2349].as_trits()), bundle_hash=BundleHash(tryte_string[2349:2430]), trunk_transaction_hash=TransactionHash(tryte_string[2430:2511]), branch_transaction_hash=TransactionHash(tryte_string[2511:2592]), nonce=Hash(tryte_string[2592:2673])) | @classmethod
def from_tryte_string(cls, trytes):
'\n \n '
tryte_string = TransactionTrytes(trytes)
hash_ = ([0] * HASH_LENGTH)
sponge = Curl()
sponge.absorb(tryte_string.as_trits())
sponge.squeeze(hash_)
return cls(hash_=TransactionHash.from_trits(hash_), signature_message_fragment=Fragment(tryte_string[0:2187]), address=Address(tryte_string[2187:2268]), value=int_from_trits(tryte_string[2268:2295].as_trits()), tag=Tag(tryte_string[2295:2322]), timestamp=int_from_trits(tryte_string[2322:2331].as_trits()), current_index=int_from_trits(tryte_string[2331:2340].as_trits()), last_index=int_from_trits(tryte_string[2340:2349].as_trits()), bundle_hash=BundleHash(tryte_string[2349:2430]), trunk_transaction_hash=TransactionHash(tryte_string[2430:2511]), branch_transaction_hash=TransactionHash(tryte_string[2511:2592]), nonce=Hash(tryte_string[2592:2673]))<|docstring|>Creates a Transaction object from a sequence of trytes.<|endoftext|> |
2e47b4d92c2c486a165145674414f101a9eff22f00b738f56ec01e91058a515d | @property
def is_tail(self):
'\n Returns whether this transaction is a tail.\n '
return (self.current_index == 0) | Returns whether this transaction is a tail. | src/cornode/transaction.py | is_tail | Cornode/cornode.lib.py | 0 | python | @property
def is_tail(self):
'\n \n '
return (self.current_index == 0) | @property
def is_tail(self):
'\n \n '
return (self.current_index == 0)<|docstring|>Returns whether this transaction is a tail.<|endoftext|> |
293682630ff17849819b7ed77cca9a528f3405fd3b649c45261dc27a2092dd86 | @property
def value_as_trytes(self):
"\n Returns a TryteString representation of the transaction's value.\n "
return TryteString.from_trits(trits_from_int(self.value, pad=81)) | Returns a TryteString representation of the transaction's value. | src/cornode/transaction.py | value_as_trytes | Cornode/cornode.lib.py | 0 | python | @property
def value_as_trytes(self):
"\n \n "
return TryteString.from_trits(trits_from_int(self.value, pad=81)) | @property
def value_as_trytes(self):
"\n \n "
return TryteString.from_trits(trits_from_int(self.value, pad=81))<|docstring|>Returns a TryteString representation of the transaction's value.<|endoftext|> |
a6169a09b9a713fee3b828c6e6bfcb130e9f72fd42f94fac5a82406ed8240e34 | @property
def timestamp_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n timestamp.\n "
return TryteString.from_trits(trits_from_int(self.timestamp, pad=27)) | Returns a TryteString representation of the transaction's
timestamp. | src/cornode/transaction.py | timestamp_as_trytes | Cornode/cornode.lib.py | 0 | python | @property
def timestamp_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n timestamp.\n "
return TryteString.from_trits(trits_from_int(self.timestamp, pad=27)) | @property
def timestamp_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n timestamp.\n "
return TryteString.from_trits(trits_from_int(self.timestamp, pad=27))<|docstring|>Returns a TryteString representation of the transaction's
timestamp.<|endoftext|> |
7b5e4d0240ea32468fdb51dd34ba39af40f2ed2a218f40b98909d280eae962fb | @property
def current_index_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n ``current_index`` value.\n "
return TryteString.from_trits(trits_from_int(self.current_index, pad=27)) | Returns a TryteString representation of the transaction's
``current_index`` value. | src/cornode/transaction.py | current_index_as_trytes | Cornode/cornode.lib.py | 0 | python | @property
def current_index_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n ``current_index`` value.\n "
return TryteString.from_trits(trits_from_int(self.current_index, pad=27)) | @property
def current_index_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n ``current_index`` value.\n "
return TryteString.from_trits(trits_from_int(self.current_index, pad=27))<|docstring|>Returns a TryteString representation of the transaction's
``current_index`` value.<|endoftext|> |
a3abf5b3b0e82742d2cfc7b51ec8e84e69296cca4b9cd3f5e7a4aac3eb468407 | @property
def last_index_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n ``last_index`` value.\n "
return TryteString.from_trits(trits_from_int(self.last_index, pad=27)) | Returns a TryteString representation of the transaction's
``last_index`` value. | src/cornode/transaction.py | last_index_as_trytes | Cornode/cornode.lib.py | 0 | python | @property
def last_index_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n ``last_index`` value.\n "
return TryteString.from_trits(trits_from_int(self.last_index, pad=27)) | @property
def last_index_as_trytes(self):
"\n Returns a TryteString representation of the transaction's\n ``last_index`` value.\n "
return TryteString.from_trits(trits_from_int(self.last_index, pad=27))<|docstring|>Returns a TryteString representation of the transaction's
``last_index`` value.<|endoftext|> |
c9c665613a4792778cbb53537aed6a4143948dcf0a20219f7e193c9ebdfb365f | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return {'hash': self.hash, 'signature_message_fragment': self.signature_message_fragment, 'address': self.address, 'value': self.value, 'tag': self.tag, 'timestamp': self.timestamp, 'current_index': self.current_index, 'last_index': self.last_index, 'bundle_hash': self.bundle_hash, 'trunk_transaction_hash': self.trunk_transaction_hash, 'branch_transaction_hash': self.branch_transaction_hash, 'nonce': self.nonce} | Returns a JSON-compatible representation of the object.
References:
- :py:class:`cornode.json.JsonEncoder`. | src/cornode/transaction.py | as_json_compatible | Cornode/cornode.lib.py | 0 | python | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return {'hash': self.hash, 'signature_message_fragment': self.signature_message_fragment, 'address': self.address, 'value': self.value, 'tag': self.tag, 'timestamp': self.timestamp, 'current_index': self.current_index, 'last_index': self.last_index, 'bundle_hash': self.bundle_hash, 'trunk_transaction_hash': self.trunk_transaction_hash, 'branch_transaction_hash': self.branch_transaction_hash, 'nonce': self.nonce} | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return {'hash': self.hash, 'signature_message_fragment': self.signature_message_fragment, 'address': self.address, 'value': self.value, 'tag': self.tag, 'timestamp': self.timestamp, 'current_index': self.current_index, 'last_index': self.last_index, 'bundle_hash': self.bundle_hash, 'trunk_transaction_hash': self.trunk_transaction_hash, 'branch_transaction_hash': self.branch_transaction_hash, 'nonce': self.nonce}<|docstring|>Returns a JSON-compatible representation of the object.
References:
- :py:class:`cornode.json.JsonEncoder`.<|endoftext|> |
afb2b376f7acc3db35fada9d827dcac40fc247085d2b008c0a894f99edf2da73 | def as_tryte_string(self):
'\n Returns a TryteString representation of the transaction.\n '
return TransactionTrytes(((((((((((self.signature_message_fragment + self.address.address) + self.value_as_trytes) + self.tag) + self.timestamp_as_trytes) + self.current_index_as_trytes) + self.last_index_as_trytes) + self.bundle_hash) + self.trunk_transaction_hash) + self.branch_transaction_hash) + self.nonce)) | Returns a TryteString representation of the transaction. | src/cornode/transaction.py | as_tryte_string | Cornode/cornode.lib.py | 0 | python | def as_tryte_string(self):
'\n \n '
return TransactionTrytes(((((((((((self.signature_message_fragment + self.address.address) + self.value_as_trytes) + self.tag) + self.timestamp_as_trytes) + self.current_index_as_trytes) + self.last_index_as_trytes) + self.bundle_hash) + self.trunk_transaction_hash) + self.branch_transaction_hash) + self.nonce)) | def as_tryte_string(self):
'\n \n '
return TransactionTrytes(((((((((((self.signature_message_fragment + self.address.address) + self.value_as_trytes) + self.tag) + self.timestamp_as_trytes) + self.current_index_as_trytes) + self.last_index_as_trytes) + self.bundle_hash) + self.trunk_transaction_hash) + self.branch_transaction_hash) + self.nonce))<|docstring|>Returns a TryteString representation of the transaction.<|endoftext|> |
c358e3a70319949920e7c99c30cc9a09408aba84b70b1862d99a467707969cb3 | def get_signature_validation_trytes(self):
"\n Returns the values needed to validate the transaction's\n ``signature_message_fragment`` value.\n "
return (((((self.address.address + self.value_as_trytes) + self.tag) + self.timestamp_as_trytes) + self.current_index_as_trytes) + self.last_index_as_trytes) | Returns the values needed to validate the transaction's
``signature_message_fragment`` value. | src/cornode/transaction.py | get_signature_validation_trytes | Cornode/cornode.lib.py | 0 | python | def get_signature_validation_trytes(self):
"\n Returns the values needed to validate the transaction's\n ``signature_message_fragment`` value.\n "
return (((((self.address.address + self.value_as_trytes) + self.tag) + self.timestamp_as_trytes) + self.current_index_as_trytes) + self.last_index_as_trytes) | def get_signature_validation_trytes(self):
"\n Returns the values needed to validate the transaction's\n ``signature_message_fragment`` value.\n "
return (((((self.address.address + self.value_as_trytes) + self.tag) + self.timestamp_as_trytes) + self.current_index_as_trytes) + self.last_index_as_trytes)<|docstring|>Returns the values needed to validate the transaction's
``signature_message_fragment`` value.<|endoftext|> |
8e45460fe80ed1feff626bdea9f7495b9784eb6e51239f9a02d571f10e84a5c0 | def as_tryte_string(self):
'\n Returns a TryteString representation of the transaction.\n '
if (not self.bundle_hash):
raise with_context(exc=RuntimeError('Cannot get TryteString representation of {cls} instance without a bundle hash; call ``bundle.finalize()`` first (``exc.context`` has more info).'.format(cls=type(self).__name__)), context={'transaction': self})
return super(ProposedTransaction, self).as_tryte_string() | Returns a TryteString representation of the transaction. | src/cornode/transaction.py | as_tryte_string | Cornode/cornode.lib.py | 0 | python | def as_tryte_string(self):
'\n \n '
if (not self.bundle_hash):
raise with_context(exc=RuntimeError('Cannot get TryteString representation of {cls} instance without a bundle hash; call ``bundle.finalize()`` first (``exc.context`` has more info).'.format(cls=type(self).__name__)), context={'transaction': self})
return super(ProposedTransaction, self).as_tryte_string() | def as_tryte_string(self):
'\n \n '
if (not self.bundle_hash):
raise with_context(exc=RuntimeError('Cannot get TryteString representation of {cls} instance without a bundle hash; call ``bundle.finalize()`` first (``exc.context`` has more info).'.format(cls=type(self).__name__)), context={'transaction': self})
return super(ProposedTransaction, self).as_tryte_string()<|docstring|>Returns a TryteString representation of the transaction.<|endoftext|> |
afa998845ed65e304d2aeb596c653c399e904097b17940bf2d0d071f498fd668 | @classmethod
def from_tryte_strings(cls, trytes):
'\n Creates a Bundle object from a list of tryte values.\n '
return cls(map(Transaction.from_tryte_string, trytes)) | Creates a Bundle object from a list of tryte values. | src/cornode/transaction.py | from_tryte_strings | Cornode/cornode.lib.py | 0 | python | @classmethod
def from_tryte_strings(cls, trytes):
'\n \n '
return cls(map(Transaction.from_tryte_string, trytes)) | @classmethod
def from_tryte_strings(cls, trytes):
'\n \n '
return cls(map(Transaction.from_tryte_string, trytes))<|docstring|>Creates a Bundle object from a list of tryte values.<|endoftext|> |
874a6eccb7c13cb957ddcc9ba4878f2c1ae47e5852663a649d764ff84c9c0e21 | @property
def is_confirmed(self):
'\n Returns whether this bundle has been confirmed by neighbor nodes.\n\n This attribute must be set manually.\n\n References:\n - :py:class:`cornode.commands.extended.get_transfers.GetTransfersCommand`\n '
return self._is_confirmed | Returns whether this bundle has been confirmed by neighbor nodes.
This attribute must be set manually.
References:
- :py:class:`cornode.commands.extended.get_transfers.GetTransfersCommand` | src/cornode/transaction.py | is_confirmed | Cornode/cornode.lib.py | 0 | python | @property
def is_confirmed(self):
'\n Returns whether this bundle has been confirmed by neighbor nodes.\n\n This attribute must be set manually.\n\n References:\n - :py:class:`cornode.commands.extended.get_transfers.GetTransfersCommand`\n '
return self._is_confirmed | @property
def is_confirmed(self):
'\n Returns whether this bundle has been confirmed by neighbor nodes.\n\n This attribute must be set manually.\n\n References:\n - :py:class:`cornode.commands.extended.get_transfers.GetTransfersCommand`\n '
return self._is_confirmed<|docstring|>Returns whether this bundle has been confirmed by neighbor nodes.
This attribute must be set manually.
References:
- :py:class:`cornode.commands.extended.get_transfers.GetTransfersCommand`<|endoftext|> |
bd0eeb588bb8e312b26cbab66b9c776a1858881680d267b4f54b3254574da96c | @is_confirmed.setter
def is_confirmed(self, new_is_confirmed):
'\n Sets the ``is_confirmed`` for the bundle.\n '
self._is_confirmed = new_is_confirmed
for txn in self:
txn.is_confirmed = new_is_confirmed | Sets the ``is_confirmed`` for the bundle. | src/cornode/transaction.py | is_confirmed | Cornode/cornode.lib.py | 0 | python | @is_confirmed.setter
def is_confirmed(self, new_is_confirmed):
'\n \n '
self._is_confirmed = new_is_confirmed
for txn in self:
txn.is_confirmed = new_is_confirmed | @is_confirmed.setter
def is_confirmed(self, new_is_confirmed):
'\n \n '
self._is_confirmed = new_is_confirmed
for txn in self:
txn.is_confirmed = new_is_confirmed<|docstring|>Sets the ``is_confirmed`` for the bundle.<|endoftext|> |
b091caf9d7e5c473e9941eb4657240447e1b63cfd7e61098b400aa4d3f2749a0 | @property
def hash(self):
"\n Returns the hash of the bundle.\n\n This value is determined by inspecting the bundle's tail\n transaction, so in a few edge cases, it may be incorrect.\n\n If the bundle has no transactions, this method returns `None`.\n "
try:
return self.tail_transaction.bundle_hash
except IndexError:
return None | Returns the hash of the bundle.
This value is determined by inspecting the bundle's tail
transaction, so in a few edge cases, it may be incorrect.
If the bundle has no transactions, this method returns `None`. | src/cornode/transaction.py | hash | Cornode/cornode.lib.py | 0 | python | @property
def hash(self):
"\n Returns the hash of the bundle.\n\n This value is determined by inspecting the bundle's tail\n transaction, so in a few edge cases, it may be incorrect.\n\n If the bundle has no transactions, this method returns `None`.\n "
try:
return self.tail_transaction.bundle_hash
except IndexError:
return None | @property
def hash(self):
"\n Returns the hash of the bundle.\n\n This value is determined by inspecting the bundle's tail\n transaction, so in a few edge cases, it may be incorrect.\n\n If the bundle has no transactions, this method returns `None`.\n "
try:
return self.tail_transaction.bundle_hash
except IndexError:
return None<|docstring|>Returns the hash of the bundle.
This value is determined by inspecting the bundle's tail
transaction, so in a few edge cases, it may be incorrect.
If the bundle has no transactions, this method returns `None`.<|endoftext|> |
e40eb34e121d4d0540d2eaf4251835db995df1ff5d89fcb6b2d438f008ef5c4b | @property
def tail_transaction(self):
'\n Returns the tail transaction of the bundle.\n '
return self[0] | Returns the tail transaction of the bundle. | src/cornode/transaction.py | tail_transaction | Cornode/cornode.lib.py | 0 | python | @property
def tail_transaction(self):
'\n \n '
return self[0] | @property
def tail_transaction(self):
'\n \n '
return self[0]<|docstring|>Returns the tail transaction of the bundle.<|endoftext|> |
bcc0323d28e8e83b6f0ad5a875550d0cfda91d3a091129779557ce9bb6654e0a | def get_messages(self, errors='drop'):
"\n Attempts to decipher encoded messages from the transactions in the\n bundle.\n\n :param errors:\n How to handle trytes that can't be converted, or bytes that can't\n be decoded using UTF-8:\n - 'drop': drop the trytes from the result.\n - 'strict': raise an exception.\n - 'replace': replace with a placeholder character.\n - 'ignore': omit the invalid tryte/byte sequence.\n "
decode_errors = ('strict' if (errors == 'drop') else errors)
messages = []
i = 0
while (i < len(self)):
txn = self[i]
if (txn.value < 0):
i += AddressGenerator.DIGEST_ITERATIONS
continue
message_trytes = TryteString(txn.signature_message_fragment)
for j in range((i + 1), len(self)):
aux_txn = self[j]
if ((aux_txn.address == txn.address) and (aux_txn.value == 0)):
message_trytes += aux_txn.signature_message_fragment
i += 1
else:
break
if message_trytes:
try:
messages.append(message_trytes.as_string(decode_errors))
except (TrytesDecodeError, UnicodeDecodeError):
if (errors != 'drop'):
raise
i += 1
return messages | Attempts to decipher encoded messages from the transactions in the
bundle.
:param errors:
How to handle trytes that can't be converted, or bytes that can't
be decoded using UTF-8:
- 'drop': drop the trytes from the result.
- 'strict': raise an exception.
- 'replace': replace with a placeholder character.
- 'ignore': omit the invalid tryte/byte sequence. | src/cornode/transaction.py | get_messages | Cornode/cornode.lib.py | 0 | python | def get_messages(self, errors='drop'):
"\n Attempts to decipher encoded messages from the transactions in the\n bundle.\n\n :param errors:\n How to handle trytes that can't be converted, or bytes that can't\n be decoded using UTF-8:\n - 'drop': drop the trytes from the result.\n - 'strict': raise an exception.\n - 'replace': replace with a placeholder character.\n - 'ignore': omit the invalid tryte/byte sequence.\n "
decode_errors = ('strict' if (errors == 'drop') else errors)
messages = []
i = 0
while (i < len(self)):
txn = self[i]
if (txn.value < 0):
i += AddressGenerator.DIGEST_ITERATIONS
continue
message_trytes = TryteString(txn.signature_message_fragment)
for j in range((i + 1), len(self)):
aux_txn = self[j]
if ((aux_txn.address == txn.address) and (aux_txn.value == 0)):
message_trytes += aux_txn.signature_message_fragment
i += 1
else:
break
if message_trytes:
try:
messages.append(message_trytes.as_string(decode_errors))
except (TrytesDecodeError, UnicodeDecodeError):
if (errors != 'drop'):
raise
i += 1
return messages | def get_messages(self, errors='drop'):
"\n Attempts to decipher encoded messages from the transactions in the\n bundle.\n\n :param errors:\n How to handle trytes that can't be converted, or bytes that can't\n be decoded using UTF-8:\n - 'drop': drop the trytes from the result.\n - 'strict': raise an exception.\n - 'replace': replace with a placeholder character.\n - 'ignore': omit the invalid tryte/byte sequence.\n "
decode_errors = ('strict' if (errors == 'drop') else errors)
messages = []
i = 0
while (i < len(self)):
txn = self[i]
if (txn.value < 0):
i += AddressGenerator.DIGEST_ITERATIONS
continue
message_trytes = TryteString(txn.signature_message_fragment)
for j in range((i + 1), len(self)):
aux_txn = self[j]
if ((aux_txn.address == txn.address) and (aux_txn.value == 0)):
message_trytes += aux_txn.signature_message_fragment
i += 1
else:
break
if message_trytes:
try:
messages.append(message_trytes.as_string(decode_errors))
except (TrytesDecodeError, UnicodeDecodeError):
if (errors != 'drop'):
raise
i += 1
return messages<|docstring|>Attempts to decipher encoded messages from the transactions in the
bundle.
:param errors:
How to handle trytes that can't be converted, or bytes that can't
be decoded using UTF-8:
- 'drop': drop the trytes from the result.
- 'strict': raise an exception.
- 'replace': replace with a placeholder character.
- 'ignore': omit the invalid tryte/byte sequence.<|endoftext|> |
6987b762cef85546c5103b8691f9f5b41fa3afbd3cc1c8bc877d1402459c30d1 | def as_tryte_strings(self, head_to_tail=True):
'\n Returns TryteString representations of the transactions in this\n bundle.\n\n :param head_to_tail:\n Determines the order of the transactions:\n\n - ``True`` (default): head txn first, tail txn last.\n - ``False``: tail txn first, head txn last.\n '
transactions = (reversed(self) if head_to_tail else self)
return [t.as_tryte_string() for t in transactions] | Returns TryteString representations of the transactions in this
bundle.
:param head_to_tail:
Determines the order of the transactions:
- ``True`` (default): head txn first, tail txn last.
- ``False``: tail txn first, head txn last. | src/cornode/transaction.py | as_tryte_strings | Cornode/cornode.lib.py | 0 | python | def as_tryte_strings(self, head_to_tail=True):
'\n Returns TryteString representations of the transactions in this\n bundle.\n\n :param head_to_tail:\n Determines the order of the transactions:\n\n - ``True`` (default): head txn first, tail txn last.\n - ``False``: tail txn first, head txn last.\n '
transactions = (reversed(self) if head_to_tail else self)
return [t.as_tryte_string() for t in transactions] | def as_tryte_strings(self, head_to_tail=True):
'\n Returns TryteString representations of the transactions in this\n bundle.\n\n :param head_to_tail:\n Determines the order of the transactions:\n\n - ``True`` (default): head txn first, tail txn last.\n - ``False``: tail txn first, head txn last.\n '
transactions = (reversed(self) if head_to_tail else self)
return [t.as_tryte_string() for t in transactions]<|docstring|>Returns TryteString representations of the transactions in this
bundle.
:param head_to_tail:
Determines the order of the transactions:
- ``True`` (default): head txn first, tail txn last.
- ``False``: tail txn first, head txn last.<|endoftext|> |
d4c637515b7bd428ea3523a34f17fe46e48069688b7ee839cb164c68eeaafbbb | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return [txn.as_json_compatible() for txn in self] | Returns a JSON-compatible representation of the object.
References:
- :py:class:`cornode.json.JsonEncoder`. | src/cornode/transaction.py | as_json_compatible | Cornode/cornode.lib.py | 0 | python | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return [txn.as_json_compatible() for txn in self] | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return [txn.as_json_compatible() for txn in self]<|docstring|>Returns a JSON-compatible representation of the object.
References:
- :py:class:`cornode.json.JsonEncoder`.<|endoftext|> |
f1c52ec1678c612a2993d4fbedf5399cd5844161fa9f8ca11275b90a915f6ac9 | @property
def errors(self):
'\n Returns all errors found with the bundle.\n '
try:
self._errors.extend(self._validator)
except StopIteration:
pass
return self._errors | Returns all errors found with the bundle. | src/cornode/transaction.py | errors | Cornode/cornode.lib.py | 0 | python | @property
def errors(self):
'\n \n '
try:
self._errors.extend(self._validator)
except StopIteration:
pass
return self._errors | @property
def errors(self):
'\n \n '
try:
self._errors.extend(self._validator)
except StopIteration:
pass
return self._errors<|docstring|>Returns all errors found with the bundle.<|endoftext|> |
2b008938da1d83e94b2f07c33ee7e5af3f90b93e56db9ed5aa556edd836e85e7 | def is_valid(self):
'\n Returns whether the bundle is valid.\n '
if (not self._errors):
try:
self._errors.append(next(self._validator))
except StopIteration:
pass
return (not self._errors) | Returns whether the bundle is valid. | src/cornode/transaction.py | is_valid | Cornode/cornode.lib.py | 0 | python | def is_valid(self):
'\n \n '
if (not self._errors):
try:
self._errors.append(next(self._validator))
except StopIteration:
pass
return (not self._errors) | def is_valid(self):
'\n \n '
if (not self._errors):
try:
self._errors.append(next(self._validator))
except StopIteration:
pass
return (not self._errors)<|docstring|>Returns whether the bundle is valid.<|endoftext|> |
b76bd9c637a80b5db7bd01ad32cab0d7defa6a2b36cfbc2e873b56bb1c56c6a1 | def _create_validator(self):
'\n Creates a generator that does all the work.\n '
bundle_hash = self.bundle.hash
last_index = (len(self.bundle) - 1)
balance = 0
for (i, txn) in enumerate(self.bundle):
balance += txn.value
if (txn.bundle_hash != bundle_hash):
(yield 'Transaction {i} has invalid bundle hash.'.format(i=i))
if (txn.current_index != i):
(yield 'Transaction {i} has invalid current index value (expected {i}, actual {actual}).'.format(actual=txn.current_index, i=i))
if (txn.last_index != last_index):
(yield 'Transaction {i} has invalid last index value (expected {expected}, actual {actual}).'.format(actual=txn.last_index, expected=last_index, i=i))
if (balance != 0):
(yield 'Bundle has invalid balance (expected 0, actual {actual}).'.format(actual=balance))
if (not self._errors):
i = 0
while (i <= last_index):
txn = self.bundle[i]
if (txn.value < 0):
signature_fragments = [txn.signature_message_fragment]
fragments_valid = True
j = 0
for j in range(1, AddressGenerator.DIGEST_ITERATIONS):
i += 1
try:
next_txn = self.bundle[i]
except IndexError:
(yield 'Reached end of bundle while looking for signature fragment {j} for transaction {i}.'.format(i=txn.current_index, j=(j + 1)))
fragments_valid = False
break
if (next_txn.address != txn.address):
(yield 'Unable to find signature fragment {j} for transaction {i}.'.format(i=txn.current_index, j=(j + 1)))
fragments_valid = False
break
if (next_txn.value != 0):
(yield 'Transaction {i} has invalid amount (expected 0, actual {actual}).'.format(actual=next_txn.value, i=next_txn.current_index))
fragments_valid = False
continue
signature_fragments.append(next_txn.signature_message_fragment)
if fragments_valid:
signature_valid = validate_signature_fragments(fragments=signature_fragments, hash_=txn.bundle_hash, public_key=txn.address)
if (not signature_valid):
(yield 'Transaction {i} has invalid signature (using {fragments} fragments).'.format(fragments=len(signature_fragments), i=txn.current_index))
i += j
else:
i += 1 | Creates a generator that does all the work. | src/cornode/transaction.py | _create_validator | Cornode/cornode.lib.py | 0 | python | def _create_validator(self):
'\n \n '
bundle_hash = self.bundle.hash
last_index = (len(self.bundle) - 1)
balance = 0
for (i, txn) in enumerate(self.bundle):
balance += txn.value
if (txn.bundle_hash != bundle_hash):
(yield 'Transaction {i} has invalid bundle hash.'.format(i=i))
if (txn.current_index != i):
(yield 'Transaction {i} has invalid current index value (expected {i}, actual {actual}).'.format(actual=txn.current_index, i=i))
if (txn.last_index != last_index):
(yield 'Transaction {i} has invalid last index value (expected {expected}, actual {actual}).'.format(actual=txn.last_index, expected=last_index, i=i))
if (balance != 0):
(yield 'Bundle has invalid balance (expected 0, actual {actual}).'.format(actual=balance))
if (not self._errors):
i = 0
while (i <= last_index):
txn = self.bundle[i]
if (txn.value < 0):
signature_fragments = [txn.signature_message_fragment]
fragments_valid = True
j = 0
for j in range(1, AddressGenerator.DIGEST_ITERATIONS):
i += 1
try:
next_txn = self.bundle[i]
except IndexError:
(yield 'Reached end of bundle while looking for signature fragment {j} for transaction {i}.'.format(i=txn.current_index, j=(j + 1)))
fragments_valid = False
break
if (next_txn.address != txn.address):
(yield 'Unable to find signature fragment {j} for transaction {i}.'.format(i=txn.current_index, j=(j + 1)))
fragments_valid = False
break
if (next_txn.value != 0):
(yield 'Transaction {i} has invalid amount (expected 0, actual {actual}).'.format(actual=next_txn.value, i=next_txn.current_index))
fragments_valid = False
continue
signature_fragments.append(next_txn.signature_message_fragment)
if fragments_valid:
signature_valid = validate_signature_fragments(fragments=signature_fragments, hash_=txn.bundle_hash, public_key=txn.address)
if (not signature_valid):
(yield 'Transaction {i} has invalid signature (using {fragments} fragments).'.format(fragments=len(signature_fragments), i=txn.current_index))
i += j
else:
i += 1 | def _create_validator(self):
'\n \n '
bundle_hash = self.bundle.hash
last_index = (len(self.bundle) - 1)
balance = 0
for (i, txn) in enumerate(self.bundle):
balance += txn.value
if (txn.bundle_hash != bundle_hash):
(yield 'Transaction {i} has invalid bundle hash.'.format(i=i))
if (txn.current_index != i):
(yield 'Transaction {i} has invalid current index value (expected {i}, actual {actual}).'.format(actual=txn.current_index, i=i))
if (txn.last_index != last_index):
(yield 'Transaction {i} has invalid last index value (expected {expected}, actual {actual}).'.format(actual=txn.last_index, expected=last_index, i=i))
if (balance != 0):
(yield 'Bundle has invalid balance (expected 0, actual {actual}).'.format(actual=balance))
if (not self._errors):
i = 0
while (i <= last_index):
txn = self.bundle[i]
if (txn.value < 0):
signature_fragments = [txn.signature_message_fragment]
fragments_valid = True
j = 0
for j in range(1, AddressGenerator.DIGEST_ITERATIONS):
i += 1
try:
next_txn = self.bundle[i]
except IndexError:
(yield 'Reached end of bundle while looking for signature fragment {j} for transaction {i}.'.format(i=txn.current_index, j=(j + 1)))
fragments_valid = False
break
if (next_txn.address != txn.address):
(yield 'Unable to find signature fragment {j} for transaction {i}.'.format(i=txn.current_index, j=(j + 1)))
fragments_valid = False
break
if (next_txn.value != 0):
(yield 'Transaction {i} has invalid amount (expected 0, actual {actual}).'.format(actual=next_txn.value, i=next_txn.current_index))
fragments_valid = False
continue
signature_fragments.append(next_txn.signature_message_fragment)
if fragments_valid:
signature_valid = validate_signature_fragments(fragments=signature_fragments, hash_=txn.bundle_hash, public_key=txn.address)
if (not signature_valid):
(yield 'Transaction {i} has invalid signature (using {fragments} fragments).'.format(fragments=len(signature_fragments), i=txn.current_index))
i += j
else:
i += 1<|docstring|>Creates a generator that does all the work.<|endoftext|> |
88c1d55bd15871acaae9e64551c5a2c0c094749ae30b772101d2baf29d61ce38 | def __bool__(self):
'\n Returns whether this bundle has any transactions.\n '
return bool(self._transactions) | Returns whether this bundle has any transactions. | src/cornode/transaction.py | __bool__ | Cornode/cornode.lib.py | 0 | python | def __bool__(self):
'\n \n '
return bool(self._transactions) | def __bool__(self):
'\n \n '
return bool(self._transactions)<|docstring|>Returns whether this bundle has any transactions.<|endoftext|> |
d1efbccb8122345c00349c29c8a944ce3f3e90fd857c356481b0c2b7ccf7015e | def __getitem__(self, index):
'\n Returns the transaction at the specified index.\n '
return self._transactions[index] | Returns the transaction at the specified index. | src/cornode/transaction.py | __getitem__ | Cornode/cornode.lib.py | 0 | python | def __getitem__(self, index):
'\n \n '
return self._transactions[index] | def __getitem__(self, index):
'\n \n '
return self._transactions[index]<|docstring|>Returns the transaction at the specified index.<|endoftext|> |
5cae85c7470dbb8dc55f14fbacb749d36ce35b41b0a1e2165d476fe16b49419c | def __iter__(self):
'\n Iterates over transactions in the bundle.\n '
return iter(self._transactions) | Iterates over transactions in the bundle. | src/cornode/transaction.py | __iter__ | Cornode/cornode.lib.py | 0 | python | def __iter__(self):
'\n \n '
return iter(self._transactions) | def __iter__(self):
'\n \n '
return iter(self._transactions)<|docstring|>Iterates over transactions in the bundle.<|endoftext|> |
48df585856e28110a1806f727e5c5d3f3a77696d16e3b07f7d4cab8bb3446052 | def __len__(self):
'\n Returns te number of transactions in the bundle.\n '
return len(self._transactions) | Returns te number of transactions in the bundle. | src/cornode/transaction.py | __len__ | Cornode/cornode.lib.py | 0 | python | def __len__(self):
'\n \n '
return len(self._transactions) | def __len__(self):
'\n \n '
return len(self._transactions)<|docstring|>Returns te number of transactions in the bundle.<|endoftext|> |
6fac939e72bd1eca4ec44df3c61c8ed6fb05507b1337a1bec0628fdec0872bb1 | @property
def balance(self):
'\n Returns the bundle balance.\n In order for a bundle to be valid, its balance must be 0:\n\n - A positive balance means that there aren\'t enough inputs to\n cover the spent amount.\n Add more inputs using :py:meth:`add_inputs`.\n - A negative balance means that there are unspent inputs.\n Use :py:meth:`send_unspent_inputs_to` to send the unspent\n inputs to a "change" address.\n '
return sum((t.value for t in self._transactions)) | Returns the bundle balance.
In order for a bundle to be valid, its balance must be 0:
- A positive balance means that there aren't enough inputs to
cover the spent amount.
Add more inputs using :py:meth:`add_inputs`.
- A negative balance means that there are unspent inputs.
Use :py:meth:`send_unspent_inputs_to` to send the unspent
inputs to a "change" address. | src/cornode/transaction.py | balance | Cornode/cornode.lib.py | 0 | python | @property
def balance(self):
'\n Returns the bundle balance.\n In order for a bundle to be valid, its balance must be 0:\n\n - A positive balance means that there aren\'t enough inputs to\n cover the spent amount.\n Add more inputs using :py:meth:`add_inputs`.\n - A negative balance means that there are unspent inputs.\n Use :py:meth:`send_unspent_inputs_to` to send the unspent\n inputs to a "change" address.\n '
return sum((t.value for t in self._transactions)) | @property
def balance(self):
'\n Returns the bundle balance.\n In order for a bundle to be valid, its balance must be 0:\n\n - A positive balance means that there aren\'t enough inputs to\n cover the spent amount.\n Add more inputs using :py:meth:`add_inputs`.\n - A negative balance means that there are unspent inputs.\n Use :py:meth:`send_unspent_inputs_to` to send the unspent\n inputs to a "change" address.\n '
return sum((t.value for t in self._transactions))<|docstring|>Returns the bundle balance.
In order for a bundle to be valid, its balance must be 0:
- A positive balance means that there aren't enough inputs to
cover the spent amount.
Add more inputs using :py:meth:`add_inputs`.
- A negative balance means that there are unspent inputs.
Use :py:meth:`send_unspent_inputs_to` to send the unspent
inputs to a "change" address.<|endoftext|> |
d140c32405407111c3e04c12734c6bca9146d8bbfd0429fc4f533d3327800295 | @property
def tag(self):
'\n Determines the most relevant tag for the bundle.\n '
for txn in reversed(self):
if txn.tag:
return txn.tag
return Tag(b'') | Determines the most relevant tag for the bundle. | src/cornode/transaction.py | tag | Cornode/cornode.lib.py | 0 | python | @property
def tag(self):
'\n \n '
for txn in reversed(self):
if txn.tag:
return txn.tag
return Tag(b) | @property
def tag(self):
'\n \n '
for txn in reversed(self):
if txn.tag:
return txn.tag
return Tag(b)<|docstring|>Determines the most relevant tag for the bundle.<|endoftext|> |
d4c637515b7bd428ea3523a34f17fe46e48069688b7ee839cb164c68eeaafbbb | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return [txn.as_json_compatible() for txn in self] | Returns a JSON-compatible representation of the object.
References:
- :py:class:`cornode.json.JsonEncoder`. | src/cornode/transaction.py | as_json_compatible | Cornode/cornode.lib.py | 0 | python | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return [txn.as_json_compatible() for txn in self] | def as_json_compatible(self):
'\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`cornode.json.JsonEncoder`.\n '
return [txn.as_json_compatible() for txn in self]<|docstring|>Returns a JSON-compatible representation of the object.
References:
- :py:class:`cornode.json.JsonEncoder`.<|endoftext|> |
235a732b079300ee046444fc70c3865251540c95f2c6a074c8e4d5eb85bfe0d4 | def as_tryte_strings(self):
'\n Returns the bundle as a list of TryteStrings, suitable as inputs\n for :py:meth:`cornode.api.cornode.send_trytes`.\n '
return [t.as_tryte_string() for t in reversed(self)] | Returns the bundle as a list of TryteStrings, suitable as inputs
for :py:meth:`cornode.api.cornode.send_trytes`. | src/cornode/transaction.py | as_tryte_strings | Cornode/cornode.lib.py | 0 | python | def as_tryte_strings(self):
'\n Returns the bundle as a list of TryteStrings, suitable as inputs\n for :py:meth:`cornode.api.cornode.send_trytes`.\n '
return [t.as_tryte_string() for t in reversed(self)] | def as_tryte_strings(self):
'\n Returns the bundle as a list of TryteStrings, suitable as inputs\n for :py:meth:`cornode.api.cornode.send_trytes`.\n '
return [t.as_tryte_string() for t in reversed(self)]<|docstring|>Returns the bundle as a list of TryteStrings, suitable as inputs
for :py:meth:`cornode.api.cornode.send_trytes`.<|endoftext|> |
86bf285c6daf503fef3b1c5ee88416be7c0417755d15c94048e12974f245ee63 | def add_transaction(self, transaction):
'\n Adds a transaction to the bundle.\n\n If the transaction message is too long, it will be split\n automatically into multiple transactions.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if (transaction.value < 0):
raise ValueError('Use ``add_inputs`` to add inputs to the bundle.')
self._transactions.append(ProposedTransaction(address=transaction.address, value=transaction.value, tag=transaction.tag, message=transaction.message[:Fragment.LEN], timestamp=transaction.timestamp))
fragment = transaction.message[Fragment.LEN:]
while fragment:
self._transactions.append(ProposedTransaction(address=transaction.address, value=0, tag=transaction.tag, message=fragment[:Fragment.LEN], timestamp=transaction.timestamp))
fragment = fragment[Fragment.LEN:] | Adds a transaction to the bundle.
If the transaction message is too long, it will be split
automatically into multiple transactions. | src/cornode/transaction.py | add_transaction | Cornode/cornode.lib.py | 0 | python | def add_transaction(self, transaction):
'\n Adds a transaction to the bundle.\n\n If the transaction message is too long, it will be split\n automatically into multiple transactions.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if (transaction.value < 0):
raise ValueError('Use ``add_inputs`` to add inputs to the bundle.')
self._transactions.append(ProposedTransaction(address=transaction.address, value=transaction.value, tag=transaction.tag, message=transaction.message[:Fragment.LEN], timestamp=transaction.timestamp))
fragment = transaction.message[Fragment.LEN:]
while fragment:
self._transactions.append(ProposedTransaction(address=transaction.address, value=0, tag=transaction.tag, message=fragment[:Fragment.LEN], timestamp=transaction.timestamp))
fragment = fragment[Fragment.LEN:] | def add_transaction(self, transaction):
'\n Adds a transaction to the bundle.\n\n If the transaction message is too long, it will be split\n automatically into multiple transactions.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if (transaction.value < 0):
raise ValueError('Use ``add_inputs`` to add inputs to the bundle.')
self._transactions.append(ProposedTransaction(address=transaction.address, value=transaction.value, tag=transaction.tag, message=transaction.message[:Fragment.LEN], timestamp=transaction.timestamp))
fragment = transaction.message[Fragment.LEN:]
while fragment:
self._transactions.append(ProposedTransaction(address=transaction.address, value=0, tag=transaction.tag, message=fragment[:Fragment.LEN], timestamp=transaction.timestamp))
fragment = fragment[Fragment.LEN:]<|docstring|>Adds a transaction to the bundle.
If the transaction message is too long, it will be split
automatically into multiple transactions.<|endoftext|> |
f519e309d2c48883a4b1e4e9c58a94a4da4187f114405b792a8c4c4ac85604a7 | def add_inputs(self, inputs):
'\n Adds inputs to spend in the bundle.\n\n Note that each input requires two transactions, in order to\n hold the entire signature.\n\n :param inputs:\n Addresses to use as the inputs for this bundle.\n\n IMPORTANT: Must have ``balance`` and ``key_index`` attributes!\n Use :py:meth:`cornode.api.get_inputs` to prepare inputs.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
for addy in inputs:
if (addy.balance is None):
raise with_context(exc=ValueError('Address {address} has null ``balance`` (``exc.context`` has more info).'.format(address=addy)), context={'address': addy})
if (addy.key_index is None):
raise with_context(exc=ValueError('Address {address} has null ``key_index`` (``exc.context`` has more info).'.format(address=addy)), context={'address': addy})
self._transactions.append(ProposedTransaction(address=addy, tag=self.tag, value=(- addy.balance)))
for _ in range((AddressGenerator.DIGEST_ITERATIONS - 1)):
self._transactions.append(ProposedTransaction(address=addy, tag=self.tag, value=0)) | Adds inputs to spend in the bundle.
Note that each input requires two transactions, in order to
hold the entire signature.
:param inputs:
Addresses to use as the inputs for this bundle.
IMPORTANT: Must have ``balance`` and ``key_index`` attributes!
Use :py:meth:`cornode.api.get_inputs` to prepare inputs. | src/cornode/transaction.py | add_inputs | Cornode/cornode.lib.py | 0 | python | def add_inputs(self, inputs):
'\n Adds inputs to spend in the bundle.\n\n Note that each input requires two transactions, in order to\n hold the entire signature.\n\n :param inputs:\n Addresses to use as the inputs for this bundle.\n\n IMPORTANT: Must have ``balance`` and ``key_index`` attributes!\n Use :py:meth:`cornode.api.get_inputs` to prepare inputs.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
for addy in inputs:
if (addy.balance is None):
raise with_context(exc=ValueError('Address {address} has null ``balance`` (``exc.context`` has more info).'.format(address=addy)), context={'address': addy})
if (addy.key_index is None):
raise with_context(exc=ValueError('Address {address} has null ``key_index`` (``exc.context`` has more info).'.format(address=addy)), context={'address': addy})
self._transactions.append(ProposedTransaction(address=addy, tag=self.tag, value=(- addy.balance)))
for _ in range((AddressGenerator.DIGEST_ITERATIONS - 1)):
self._transactions.append(ProposedTransaction(address=addy, tag=self.tag, value=0)) | def add_inputs(self, inputs):
'\n Adds inputs to spend in the bundle.\n\n Note that each input requires two transactions, in order to\n hold the entire signature.\n\n :param inputs:\n Addresses to use as the inputs for this bundle.\n\n IMPORTANT: Must have ``balance`` and ``key_index`` attributes!\n Use :py:meth:`cornode.api.get_inputs` to prepare inputs.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
for addy in inputs:
if (addy.balance is None):
raise with_context(exc=ValueError('Address {address} has null ``balance`` (``exc.context`` has more info).'.format(address=addy)), context={'address': addy})
if (addy.key_index is None):
raise with_context(exc=ValueError('Address {address} has null ``key_index`` (``exc.context`` has more info).'.format(address=addy)), context={'address': addy})
self._transactions.append(ProposedTransaction(address=addy, tag=self.tag, value=(- addy.balance)))
for _ in range((AddressGenerator.DIGEST_ITERATIONS - 1)):
self._transactions.append(ProposedTransaction(address=addy, tag=self.tag, value=0))<|docstring|>Adds inputs to spend in the bundle.
Note that each input requires two transactions, in order to
hold the entire signature.
:param inputs:
Addresses to use as the inputs for this bundle.
IMPORTANT: Must have ``balance`` and ``key_index`` attributes!
Use :py:meth:`cornode.api.get_inputs` to prepare inputs.<|endoftext|> |
59574640f0a09f74476e759b63f4b45fbb844085817f09b53791cf31355b8d95 | def send_unspent_inputs_to(self, address):
'\n Adds a transaction to send "change" (unspent inputs) to the\n specified address.\n\n If the bundle has no unspent inputs, this method does nothing.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
self.change_address = address | Adds a transaction to send "change" (unspent inputs) to the
specified address.
If the bundle has no unspent inputs, this method does nothing. | src/cornode/transaction.py | send_unspent_inputs_to | Cornode/cornode.lib.py | 0 | python | def send_unspent_inputs_to(self, address):
'\n Adds a transaction to send "change" (unspent inputs) to the\n specified address.\n\n If the bundle has no unspent inputs, this method does nothing.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
self.change_address = address | def send_unspent_inputs_to(self, address):
'\n Adds a transaction to send "change" (unspent inputs) to the\n specified address.\n\n If the bundle has no unspent inputs, this method does nothing.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
self.change_address = address<|docstring|>Adds a transaction to send "change" (unspent inputs) to the
specified address.
If the bundle has no unspent inputs, this method does nothing.<|endoftext|> |
d4b571d4f65933d16459f73e75b2990b24e5528a54001916972238db2ac7354f | def finalize(self):
'\n Finalizes the bundle, preparing it to be attached to the Tangle.\n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if (not self):
raise ValueError('Bundle has no transactions.')
balance = self.balance
if (balance < 0):
if self.change_address:
self.add_transaction(ProposedTransaction(address=self.change_address, value=(- balance), tag=self.tag))
else:
raise ValueError('Bundle has unspent inputs (balance: {balance}); use ``send_unspent_inputs_to`` to create change transaction.'.format(balance=balance))
elif (balance > 0):
raise ValueError('Inputs are insufficient to cover bundle spend (balance: {balance}).'.format(balance=balance))
sponge = Curl()
last_index = (len(self) - 1)
for (i, txn) in enumerate(self):
txn.current_index = i
txn.last_index = last_index
sponge.absorb(txn.get_signature_validation_trytes().as_trits())
bundle_hash = ([0] * HASH_LENGTH)
sponge.squeeze(bundle_hash)
self.hash = Hash.from_trits(bundle_hash)
for txn in self:
txn.bundle_hash = self.hash
txn.signature_message_fragment = Fragment((txn.message or b'')) | Finalizes the bundle, preparing it to be attached to the Tangle. | src/cornode/transaction.py | finalize | Cornode/cornode.lib.py | 0 | python | def finalize(self):
'\n \n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if (not self):
raise ValueError('Bundle has no transactions.')
balance = self.balance
if (balance < 0):
if self.change_address:
self.add_transaction(ProposedTransaction(address=self.change_address, value=(- balance), tag=self.tag))
else:
raise ValueError('Bundle has unspent inputs (balance: {balance}); use ``send_unspent_inputs_to`` to create change transaction.'.format(balance=balance))
elif (balance > 0):
raise ValueError('Inputs are insufficient to cover bundle spend (balance: {balance}).'.format(balance=balance))
sponge = Curl()
last_index = (len(self) - 1)
for (i, txn) in enumerate(self):
txn.current_index = i
txn.last_index = last_index
sponge.absorb(txn.get_signature_validation_trytes().as_trits())
bundle_hash = ([0] * HASH_LENGTH)
sponge.squeeze(bundle_hash)
self.hash = Hash.from_trits(bundle_hash)
for txn in self:
txn.bundle_hash = self.hash
txn.signature_message_fragment = Fragment((txn.message or b)) | def finalize(self):
'\n \n '
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if (not self):
raise ValueError('Bundle has no transactions.')
balance = self.balance
if (balance < 0):
if self.change_address:
self.add_transaction(ProposedTransaction(address=self.change_address, value=(- balance), tag=self.tag))
else:
raise ValueError('Bundle has unspent inputs (balance: {balance}); use ``send_unspent_inputs_to`` to create change transaction.'.format(balance=balance))
elif (balance > 0):
raise ValueError('Inputs are insufficient to cover bundle spend (balance: {balance}).'.format(balance=balance))
sponge = Curl()
last_index = (len(self) - 1)
for (i, txn) in enumerate(self):
txn.current_index = i
txn.last_index = last_index
sponge.absorb(txn.get_signature_validation_trytes().as_trits())
bundle_hash = ([0] * HASH_LENGTH)
sponge.squeeze(bundle_hash)
self.hash = Hash.from_trits(bundle_hash)
for txn in self:
txn.bundle_hash = self.hash
txn.signature_message_fragment = Fragment((txn.message or b))<|docstring|>Finalizes the bundle, preparing it to be attached to the Tangle.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.