body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def refresh_data(self, force_refresh=False, data_refresh_time_seconds=None): ' Read and stores crea blockchain parameters\n If the last data refresh is older than data_refresh_time_seconds, data will be refreshed\n\n :param bool force_refresh: if True, a refresh of the data is enforced\n :param float data_refresh_time_seconds: set a new minimal refresh time in seconds\n\n ' if self.offline: return if (data_refresh_time_seconds is not None): self.data_refresh_time_seconds = data_refresh_time_seconds if ((self.data['last_refresh'] is not None) and (not force_refresh) and (self.data['last_node'] == self.rpc.url)): if ((datetime.utcnow() - self.data['last_refresh']).total_seconds() < self.data_refresh_time_seconds): return self.data['last_refresh'] = datetime.utcnow() self.data['last_node'] = self.rpc.url self.data['dynamic_global_properties'] = self.get_dynamic_global_properties(False) try: self.data['feed_history'] = self.get_feed_history(False) self.data['get_feed_history'] = self.get_feed_history(False) except: self.data['feed_history'] = None self.data['get_feed_history'] = None try: self.data['hardfork_properties'] = self.get_hardfork_properties(False) except: self.data['hardfork_properties'] = None self.data['network'] = self.get_network(False) self.data['witness_schedule'] = self.get_witness_schedule(False) self.data['config'] = self.get_config(False) self.data['reward_funds'] = self.get_reward_funds(False)
7,819,743,639,589,063,000
Read and stores crea blockchain parameters If the last data refresh is older than data_refresh_time_seconds, data will be refreshed :param bool force_refresh: if True, a refresh of the data is enforced :param float data_refresh_time_seconds: set a new minimal refresh time in seconds
crea/crea.py
refresh_data
creativechain/crea-python-lib
python
def refresh_data(self, force_refresh=False, data_refresh_time_seconds=None): ' Read and stores crea blockchain parameters\n If the last data refresh is older than data_refresh_time_seconds, data will be refreshed\n\n :param bool force_refresh: if True, a refresh of the data is enforced\n :param float data_refresh_time_seconds: set a new minimal refresh time in seconds\n\n ' if self.offline: return if (data_refresh_time_seconds is not None): self.data_refresh_time_seconds = data_refresh_time_seconds if ((self.data['last_refresh'] is not None) and (not force_refresh) and (self.data['last_node'] == self.rpc.url)): if ((datetime.utcnow() - self.data['last_refresh']).total_seconds() < self.data_refresh_time_seconds): return self.data['last_refresh'] = datetime.utcnow() self.data['last_node'] = self.rpc.url self.data['dynamic_global_properties'] = self.get_dynamic_global_properties(False) try: self.data['feed_history'] = self.get_feed_history(False) self.data['get_feed_history'] = self.get_feed_history(False) except: self.data['feed_history'] = None self.data['get_feed_history'] = None try: self.data['hardfork_properties'] = self.get_hardfork_properties(False) except: self.data['hardfork_properties'] = None self.data['network'] = self.get_network(False) self.data['witness_schedule'] = self.get_witness_schedule(False) self.data['config'] = self.get_config(False) self.data['reward_funds'] = self.get_reward_funds(False)
def get_dynamic_global_properties(self, use_stored_data=True): ' This call returns the *dynamic global properties*\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n ' if use_stored_data: self.refresh_data() return self.data['dynamic_global_properties'] if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) return self.rpc.get_dynamic_global_properties(api='database')
-3,508,538,338,149,902,000
This call returns the *dynamic global properties* :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used.
crea/crea.py
get_dynamic_global_properties
creativechain/crea-python-lib
python
def get_dynamic_global_properties(self, use_stored_data=True): ' This call returns the *dynamic global properties*\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n ' if use_stored_data: self.refresh_data() return self.data['dynamic_global_properties'] if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) return self.rpc.get_dynamic_global_properties(api='database')
def get_reserve_ratio(self): ' This call returns the *reserve ratio*\n ' if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): return self.rpc.get_reserve_ratio(api='witness') else: props = self.get_dynamic_global_properties() reserve_ratio = {'id': 0, 'average_block_size': props['average_block_size'], 'current_reserve_ratio': props['current_reserve_ratio'], 'max_virtual_bandwidth': props['max_virtual_bandwidth']} return reserve_ratio
5,242,808,978,048,539,000
This call returns the *reserve ratio*
crea/crea.py
get_reserve_ratio
creativechain/crea-python-lib
python
def get_reserve_ratio(self): ' \n ' if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): return self.rpc.get_reserve_ratio(api='witness') else: props = self.get_dynamic_global_properties() reserve_ratio = {'id': 0, 'average_block_size': props['average_block_size'], 'current_reserve_ratio': props['current_reserve_ratio'], 'max_virtual_bandwidth': props['max_virtual_bandwidth']} return reserve_ratio
def get_feed_history(self, use_stored_data=True): ' Returns the feed_history\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n ' if use_stored_data: self.refresh_data() return self.data['feed_history'] if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) return self.rpc.get_feed_history(api='database')
206,164,912,570,837,760
Returns the feed_history :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used.
crea/crea.py
get_feed_history
creativechain/crea-python-lib
python
def get_feed_history(self, use_stored_data=True): ' Returns the feed_history\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n ' if use_stored_data: self.refresh_data() return self.data['feed_history'] if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) return self.rpc.get_feed_history(api='database')
def get_reward_funds(self, use_stored_data=True): ' Get details for a reward fund.\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n ' if use_stored_data: self.refresh_data() return self.data['reward_funds'] if (self.rpc is None): return None ret = None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): funds = self.rpc.get_reward_funds(api='database') if (funds is not None): funds = funds['funds'] else: return None if (len(funds) > 0): funds = funds[0] ret = funds else: ret = self.rpc.get_reward_fund('post', api='database') return ret
-760,045,488,233,925,500
Get details for a reward fund. :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used.
crea/crea.py
get_reward_funds
creativechain/crea-python-lib
python
def get_reward_funds(self, use_stored_data=True): ' Get details for a reward fund.\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n ' if use_stored_data: self.refresh_data() return self.data['reward_funds'] if (self.rpc is None): return None ret = None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): funds = self.rpc.get_reward_funds(api='database') if (funds is not None): funds = funds['funds'] else: return None if (len(funds) > 0): funds = funds[0] ret = funds else: ret = self.rpc.get_reward_fund('post', api='database') return ret
def get_current_median_history(self, use_stored_data=True): ' Returns the current median price\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n ' if use_stored_data: self.refresh_data() if self.data['get_feed_history']: return self.data['get_feed_history']['current_median_history'] else: return None if (self.rpc is None): return None ret = None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): ret = self.rpc.get_feed_history(api='database')['current_median_history'] else: ret = self.rpc.get_current_median_history_price(api='database') return ret
283,038,694,342,067,040
Returns the current median price :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used.
crea/crea.py
get_current_median_history
creativechain/crea-python-lib
python
def get_current_median_history(self, use_stored_data=True): ' Returns the current median price\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n ' if use_stored_data: self.refresh_data() if self.data['get_feed_history']: return self.data['get_feed_history']['current_median_history'] else: return None if (self.rpc is None): return None ret = None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): ret = self.rpc.get_feed_history(api='database')['current_median_history'] else: ret = self.rpc.get_current_median_history_price(api='database') return ret
def get_hardfork_properties(self, use_stored_data=True): ' Returns Hardfork and live_time of the hardfork\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n ' if use_stored_data: self.refresh_data() return self.data['hardfork_properties'] if (self.rpc is None): return None ret = None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): ret = self.rpc.get_hardfork_properties(api='database') else: ret = self.rpc.get_next_scheduled_hardfork(api='database') return ret
3,865,267,989,304,429,000
Returns Hardfork and live_time of the hardfork :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used.
crea/crea.py
get_hardfork_properties
creativechain/crea-python-lib
python
def get_hardfork_properties(self, use_stored_data=True): ' Returns Hardfork and live_time of the hardfork\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n ' if use_stored_data: self.refresh_data() return self.data['hardfork_properties'] if (self.rpc is None): return None ret = None self.rpc.set_next_node_on_empty_reply(True) if self.rpc.get_use_appbase(): ret = self.rpc.get_hardfork_properties(api='database') else: ret = self.rpc.get_next_scheduled_hardfork(api='database') return ret
def get_network(self, use_stored_data=True): ' Identify the network\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n :returns: Network parameters\n :rtype: dictionary\n ' if use_stored_data: self.refresh_data() return self.data['network'] if (self.rpc is None): return None try: return self.rpc.get_network() except: return known_chains['CREA']
5,438,952,769,049,470,000
Identify the network :param bool use_stored_data: if True, stored data will be returned. If stored data are empty or old, refresh_data() is used. :returns: Network parameters :rtype: dictionary
crea/crea.py
get_network
creativechain/crea-python-lib
python
def get_network(self, use_stored_data=True): ' Identify the network\n\n :param bool use_stored_data: if True, stored data will be returned. If stored data are\n empty or old, refresh_data() is used.\n\n :returns: Network parameters\n :rtype: dictionary\n ' if use_stored_data: self.refresh_data() return self.data['network'] if (self.rpc is None): return None try: return self.rpc.get_network() except: return known_chains['CREA']
def get_median_price(self, use_stored_data=True): ' Returns the current median history price as Price\n ' median_price = self.get_current_median_history(use_stored_data=use_stored_data) if (median_price is None): return None a = Price(None, base=Amount(median_price['base'], crea_instance=self), quote=Amount(median_price['quote'], crea_instance=self), crea_instance=self) return a.as_base(self.sbd_symbol)
7,293,544,818,523,480,000
Returns the current median history price as Price
crea/crea.py
get_median_price
creativechain/crea-python-lib
python
def get_median_price(self, use_stored_data=True): ' \n ' median_price = self.get_current_median_history(use_stored_data=use_stored_data) if (median_price is None): return None a = Price(None, base=Amount(median_price['base'], crea_instance=self), quote=Amount(median_price['quote'], crea_instance=self), crea_instance=self) return a.as_base(self.sbd_symbol)
def get_block_interval(self, use_stored_data=True): 'Returns the block interval in seconds' props = self.get_config(use_stored_data=use_stored_data) block_interval = 3 if (props is None): return block_interval for key in props: if (key[(- 14):] == 'BLOCK_INTERVAL'): block_interval = props[key] return block_interval
4,398,964,587,922,790,000
Returns the block interval in seconds
crea/crea.py
get_block_interval
creativechain/crea-python-lib
python
def get_block_interval(self, use_stored_data=True): props = self.get_config(use_stored_data=use_stored_data) block_interval = 3 if (props is None): return block_interval for key in props: if (key[(- 14):] == 'BLOCK_INTERVAL'): block_interval = props[key] return block_interval
def get_blockchain_version(self, use_stored_data=True): 'Returns the blockchain version' props = self.get_config(use_stored_data=use_stored_data) blockchain_version = '0.0.0' if (props is None): return blockchain_version for key in props: if (key[(- 18):] == 'BLOCKCHAIN_VERSION'): blockchain_version = props[key] return blockchain_version
6,491,688,609,673,718,000
Returns the blockchain version
crea/crea.py
get_blockchain_version
creativechain/crea-python-lib
python
def get_blockchain_version(self, use_stored_data=True): props = self.get_config(use_stored_data=use_stored_data) blockchain_version = '0.0.0' if (props is None): return blockchain_version for key in props: if (key[(- 18):] == 'BLOCKCHAIN_VERSION'): blockchain_version = props[key] return blockchain_version
def get_dust_threshold(self, use_stored_data=True): 'Returns the vote dust threshold' props = self.get_config(use_stored_data=use_stored_data) dust_threshold = 0 if (props is None): return dust_threshold for key in props: if (key[(- 20):] == 'VOTE_DUST_THRESHOLD'): dust_threshold = props[key] return dust_threshold
-8,331,495,759,918,413,000
Returns the vote dust threshold
crea/crea.py
get_dust_threshold
creativechain/crea-python-lib
python
def get_dust_threshold(self, use_stored_data=True): props = self.get_config(use_stored_data=use_stored_data) dust_threshold = 0 if (props is None): return dust_threshold for key in props: if (key[(- 20):] == 'VOTE_DUST_THRESHOLD'): dust_threshold = props[key] return dust_threshold
def get_resource_params(self): 'Returns the resource parameter' return self.rpc.get_resource_params(api='rc')['resource_params']
5,245,043,488,725,302,000
Returns the resource parameter
crea/crea.py
get_resource_params
creativechain/crea-python-lib
python
def get_resource_params(self): return self.rpc.get_resource_params(api='rc')['resource_params']
def get_resource_pool(self): 'Returns the resource pool' return self.rpc.get_resource_pool(api='rc')['resource_pool']
9,023,864,460,098,035,000
Returns the resource pool
crea/crea.py
get_resource_pool
creativechain/crea-python-lib
python
def get_resource_pool(self): return self.rpc.get_resource_pool(api='rc')['resource_pool']
def get_rc_cost(self, resource_count): 'Returns the RC costs based on the resource_count' pools = self.get_resource_pool() params = self.get_resource_params() config = self.get_config() dyn_param = self.get_dynamic_global_properties() rc_regen = (int(Amount(dyn_param['total_vesting_shares'], crea_instance=self)) / (CREA_RC_REGEN_TIME / config['CREA_BLOCK_INTERVAL'])) total_cost = 0 if (rc_regen == 0): return total_cost for resource_type in resource_count: curve_params = params[resource_type]['price_curve_params'] current_pool = int(pools[resource_type]['pool']) count = resource_count[resource_type] count *= params[resource_type]['resource_dynamics_params']['resource_unit'] cost = self._compute_rc_cost(curve_params, current_pool, count, rc_regen) total_cost += cost return total_cost
1,370,687,015,575,499,300
Returns the RC costs based on the resource_count
crea/crea.py
get_rc_cost
creativechain/crea-python-lib
python
def get_rc_cost(self, resource_count): pools = self.get_resource_pool() params = self.get_resource_params() config = self.get_config() dyn_param = self.get_dynamic_global_properties() rc_regen = (int(Amount(dyn_param['total_vesting_shares'], crea_instance=self)) / (CREA_RC_REGEN_TIME / config['CREA_BLOCK_INTERVAL'])) total_cost = 0 if (rc_regen == 0): return total_cost for resource_type in resource_count: curve_params = params[resource_type]['price_curve_params'] current_pool = int(pools[resource_type]['pool']) count = resource_count[resource_type] count *= params[resource_type]['resource_dynamics_params']['resource_unit'] cost = self._compute_rc_cost(curve_params, current_pool, count, rc_regen) total_cost += cost return total_cost
def _compute_rc_cost(self, curve_params, current_pool, resource_count, rc_regen): 'Helper function for computing the RC costs' num = int(rc_regen) num *= int(curve_params['coeff_a']) num = (int(num) >> int(curve_params['shift'])) num += 1 num *= int(resource_count) denom = int(curve_params['coeff_b']) if (int(current_pool) > 0): denom += int(current_pool) num_denom = (num / denom) return (int(num_denom) + 1)
4,214,059,006,486,920,700
Helper function for computing the RC costs
crea/crea.py
_compute_rc_cost
creativechain/crea-python-lib
python
def _compute_rc_cost(self, curve_params, current_pool, resource_count, rc_regen): num = int(rc_regen) num *= int(curve_params['coeff_a']) num = (int(num) >> int(curve_params['shift'])) num += 1 num *= int(resource_count) denom = int(curve_params['coeff_b']) if (int(current_pool) > 0): denom += int(current_pool) num_denom = (num / denom) return (int(num_denom) + 1)
def rshares_to_sbd(self, rshares, not_broadcasted_vote=False, use_stored_data=True): ' Calculates the current CBD value of a vote\n ' payout = (float(rshares) * self.get_sbd_per_rshares(use_stored_data=use_stored_data, not_broadcasted_vote_rshares=(rshares if not_broadcasted_vote else 0))) return payout
-4,718,203,261,994,518,000
Calculates the current CBD value of a vote
crea/crea.py
rshares_to_sbd
creativechain/crea-python-lib
python
def rshares_to_sbd(self, rshares, not_broadcasted_vote=False, use_stored_data=True): ' \n ' payout = (float(rshares) * self.get_sbd_per_rshares(use_stored_data=use_stored_data, not_broadcasted_vote_rshares=(rshares if not_broadcasted_vote else 0))) return payout
def get_sbd_per_rshares(self, not_broadcasted_vote_rshares=0, use_stored_data=True): ' Returns the current rshares to CBD ratio\n ' reward_fund = self.get_reward_funds(use_stored_data=use_stored_data) reward_balance = Amount(reward_fund['reward_balance'], crea_instance=self).amount recent_claims = (float(reward_fund['recent_claims']) + not_broadcasted_vote_rshares) fund_per_share = (reward_balance / recent_claims) median_price = self.get_median_price(use_stored_data=use_stored_data) if (median_price is None): return 0 CBD_price = (median_price * Amount(1, self.crea_symbol, crea_instance=self)).amount return (fund_per_share * CBD_price)
1,823,671,415,033,162,200
Returns the current rshares to CBD ratio
crea/crea.py
get_sbd_per_rshares
creativechain/crea-python-lib
python
def get_sbd_per_rshares(self, not_broadcasted_vote_rshares=0, use_stored_data=True): ' \n ' reward_fund = self.get_reward_funds(use_stored_data=use_stored_data) reward_balance = Amount(reward_fund['reward_balance'], crea_instance=self).amount recent_claims = (float(reward_fund['recent_claims']) + not_broadcasted_vote_rshares) fund_per_share = (reward_balance / recent_claims) median_price = self.get_median_price(use_stored_data=use_stored_data) if (median_price is None): return 0 CBD_price = (median_price * Amount(1, self.crea_symbol, crea_instance=self)).amount return (fund_per_share * CBD_price)
def get_crea_per_mvest(self, time_stamp=None, use_stored_data=True): ' Returns the MVEST to CREA ratio\n\n :param int time_stamp: (optional) if set, return an estimated\n CREA per MVEST ratio for the given time stamp. If unset the\n current ratio is returned (default). (can also be a datetime object)\n ' if (time_stamp is not None): if isinstance(time_stamp, (datetime, date)): time_stamp = formatToTimeStamp(time_stamp) a = 2.1325476281078992e-05 b = (- 31099.685481490847) a2 = 2.901922773947368e-07 b2 = 48.41432402074669 if (time_stamp < ((b2 - b) / (a - a2))): return ((a * time_stamp) + b) else: return ((a2 * time_stamp) + b2) global_properties = self.get_dynamic_global_properties(use_stored_data=use_stored_data) return (Amount(global_properties['total_vesting_fund_crea'], crea_instance=self).amount / (Amount(global_properties['total_vesting_shares'], crea_instance=self).amount / 1000000.0))
-4,148,933,468,931,298,300
Returns the MVEST to CREA ratio :param int time_stamp: (optional) if set, return an estimated CREA per MVEST ratio for the given time stamp. If unset the current ratio is returned (default). (can also be a datetime object)
crea/crea.py
get_crea_per_mvest
creativechain/crea-python-lib
python
def get_crea_per_mvest(self, time_stamp=None, use_stored_data=True): ' Returns the MVEST to CREA ratio\n\n :param int time_stamp: (optional) if set, return an estimated\n CREA per MVEST ratio for the given time stamp. If unset the\n current ratio is returned (default). (can also be a datetime object)\n ' if (time_stamp is not None): if isinstance(time_stamp, (datetime, date)): time_stamp = formatToTimeStamp(time_stamp) a = 2.1325476281078992e-05 b = (- 31099.685481490847) a2 = 2.901922773947368e-07 b2 = 48.41432402074669 if (time_stamp < ((b2 - b) / (a - a2))): return ((a * time_stamp) + b) else: return ((a2 * time_stamp) + b2) global_properties = self.get_dynamic_global_properties(use_stored_data=use_stored_data) return (Amount(global_properties['total_vesting_fund_crea'], crea_instance=self).amount / (Amount(global_properties['total_vesting_shares'], crea_instance=self).amount / 1000000.0))
def vests_to_sp(self, vests, timestamp=None, use_stored_data=True): ' Converts vests to SP\n\n :param amount.Amount vests/float vests: Vests to convert\n :param int timestamp: (Optional) Can be used to calculate\n the conversion rate from the past\n\n ' if isinstance(vests, Amount): vests = vests.amount return ((vests / 1000000.0) * self.get_crea_per_mvest(timestamp, use_stored_data=use_stored_data))
-2,568,794,267,450,538,500
Converts vests to SP :param amount.Amount vests/float vests: Vests to convert :param int timestamp: (Optional) Can be used to calculate the conversion rate from the past
crea/crea.py
vests_to_sp
creativechain/crea-python-lib
python
def vests_to_sp(self, vests, timestamp=None, use_stored_data=True): ' Converts vests to SP\n\n :param amount.Amount vests/float vests: Vests to convert\n :param int timestamp: (Optional) Can be used to calculate\n the conversion rate from the past\n\n ' if isinstance(vests, Amount): vests = vests.amount return ((vests / 1000000.0) * self.get_crea_per_mvest(timestamp, use_stored_data=use_stored_data))
def sp_to_vests(self, sp, timestamp=None, use_stored_data=True): ' Converts SP to vests\n\n :param float sp: Crea power to convert\n :param datetime timestamp: (Optional) Can be used to calculate\n the conversion rate from the past\n ' return ((sp * 1000000.0) / self.get_crea_per_mvest(timestamp, use_stored_data=use_stored_data))
-4,849,199,026,127,953,000
Converts SP to vests :param float sp: Crea power to convert :param datetime timestamp: (Optional) Can be used to calculate the conversion rate from the past
crea/crea.py
sp_to_vests
creativechain/crea-python-lib
python
def sp_to_vests(self, sp, timestamp=None, use_stored_data=True): ' Converts SP to vests\n\n :param float sp: Crea power to convert\n :param datetime timestamp: (Optional) Can be used to calculate\n the conversion rate from the past\n ' return ((sp * 1000000.0) / self.get_crea_per_mvest(timestamp, use_stored_data=use_stored_data))
def sp_to_sbd(self, sp, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, not_broadcasted_vote=True, use_stored_data=True): ' Obtain the resulting CBD vote value from Crea power\n\n :param number crea_power: Crea Power\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n\n Only impactful for very big votes. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n ' vesting_shares = int(self.sp_to_vests(sp, use_stored_data=use_stored_data)) return self.vests_to_sbd(vesting_shares, voting_power=voting_power, vote_pct=vote_pct, not_broadcasted_vote=not_broadcasted_vote, use_stored_data=use_stored_data)
5,978,847,911,755,759,000
Obtain the resulting CBD vote value from Crea power :param number crea_power: Crea Power :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting percentage (100% = 10000) :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote). Only impactful for very big votes. Slight modification to the value calculation, as the not_broadcasted vote rshares decreases the reward pool.
crea/crea.py
sp_to_sbd
creativechain/crea-python-lib
python
def sp_to_sbd(self, sp, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, not_broadcasted_vote=True, use_stored_data=True): ' Obtain the resulting CBD vote value from Crea power\n\n :param number crea_power: Crea Power\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n\n Only impactful for very big votes. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n ' vesting_shares = int(self.sp_to_vests(sp, use_stored_data=use_stored_data)) return self.vests_to_sbd(vesting_shares, voting_power=voting_power, vote_pct=vote_pct, not_broadcasted_vote=not_broadcasted_vote, use_stored_data=use_stored_data)
def vests_to_sbd(self, vests, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, not_broadcasted_vote=True, use_stored_data=True): ' Obtain the resulting CBD vote value from vests\n\n :param number vests: vesting shares\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n\n Only impactful for very big votes. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n ' vote_rshares = self.vests_to_rshares(vests, voting_power=voting_power, vote_pct=vote_pct) return self.rshares_to_sbd(vote_rshares, not_broadcasted_vote=not_broadcasted_vote, use_stored_data=use_stored_data)
-7,475,987,706,363,184,000
Obtain the resulting CBD vote value from vests :param number vests: vesting shares :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting percentage (100% = 10000) :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote). Only impactful for very big votes. Slight modification to the value calculation, as the not_broadcasted vote rshares decreases the reward pool.
crea/crea.py
vests_to_sbd
creativechain/crea-python-lib
python
def vests_to_sbd(self, vests, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, not_broadcasted_vote=True, use_stored_data=True): ' Obtain the resulting CBD vote value from vests\n\n :param number vests: vesting shares\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n\n Only impactful for very big votes. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n ' vote_rshares = self.vests_to_rshares(vests, voting_power=voting_power, vote_pct=vote_pct) return self.rshares_to_sbd(vote_rshares, not_broadcasted_vote=not_broadcasted_vote, use_stored_data=use_stored_data)
def sp_to_rshares(self, crea_power, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, use_stored_data=True): ' Obtain the r-shares from Crea power\n\n :param number crea_power: Crea Power\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n\n ' vesting_shares = int(self.sp_to_vests(crea_power, use_stored_data=use_stored_data)) return self.vests_to_rshares(vesting_shares, voting_power=voting_power, vote_pct=vote_pct, use_stored_data=use_stored_data)
-7,830,901,295,728,305,000
Obtain the r-shares from Crea power :param number crea_power: Crea Power :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting percentage (100% = 10000)
crea/crea.py
sp_to_rshares
creativechain/crea-python-lib
python
def sp_to_rshares(self, crea_power, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, use_stored_data=True): ' Obtain the r-shares from Crea power\n\n :param number crea_power: Crea Power\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n\n ' vesting_shares = int(self.sp_to_vests(crea_power, use_stored_data=use_stored_data)) return self.vests_to_rshares(vesting_shares, voting_power=voting_power, vote_pct=vote_pct, use_stored_data=use_stored_data)
def vests_to_rshares(self, vests, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, subtract_dust_threshold=True, use_stored_data=True): ' Obtain the r-shares from vests\n\n :param number vests: vesting shares\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n\n ' used_power = self._calc_resulting_vote(voting_power=voting_power, vote_pct=vote_pct, use_stored_data=use_stored_data) rshares = int(math.copysign((((vests * 1000000.0) * used_power) / CREA_100_PERCENT), vote_pct)) if subtract_dust_threshold: if (abs(rshares) <= self.get_dust_threshold(use_stored_data=use_stored_data)): return 0 rshares -= math.copysign(self.get_dust_threshold(use_stored_data=use_stored_data), vote_pct) return rshares
8,090,407,536,710,920,000
Obtain the r-shares from vests :param number vests: vesting shares :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting percentage (100% = 10000)
crea/crea.py
vests_to_rshares
creativechain/crea-python-lib
python
def vests_to_rshares(self, vests, voting_power=CREA_100_PERCENT, vote_pct=CREA_100_PERCENT, subtract_dust_threshold=True, use_stored_data=True): ' Obtain the r-shares from vests\n\n :param number vests: vesting shares\n :param int voting_power: voting power (100% = 10000)\n :param int vote_pct: voting percentage (100% = 10000)\n\n ' used_power = self._calc_resulting_vote(voting_power=voting_power, vote_pct=vote_pct, use_stored_data=use_stored_data) rshares = int(math.copysign((((vests * 1000000.0) * used_power) / CREA_100_PERCENT), vote_pct)) if subtract_dust_threshold: if (abs(rshares) <= self.get_dust_threshold(use_stored_data=use_stored_data)): return 0 rshares -= math.copysign(self.get_dust_threshold(use_stored_data=use_stored_data), vote_pct) return rshares
def sbd_to_rshares(self, sbd, not_broadcasted_vote=False, use_stored_data=True): ' Obtain the r-shares from CBD\n\n :param sbd: CBD\n :type sbd: str, int, amount.Amount\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n Only impactful for very high amounts of CBD. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n\n ' if isinstance(sbd, Amount): sbd = Amount(sbd, crea_instance=self) elif isinstance(sbd, string_types): sbd = Amount(sbd, crea_instance=self) else: sbd = Amount(sbd, self.sbd_symbol, crea_instance=self) if (sbd['symbol'] != self.sbd_symbol): raise AssertionError('Should input CBD, not any other asset!') if (not not_broadcasted_vote): return int((sbd.amount / self.get_sbd_per_rshares(use_stored_data=use_stored_data))) reward_fund = self.get_reward_funds(use_stored_data=use_stored_data) median_price = self.get_median_price(use_stored_data=use_stored_data) recent_claims = int(reward_fund['recent_claims']) reward_balance = Amount(reward_fund['reward_balance'], crea_instance=self) reward_pool_sbd = (median_price * reward_balance) if (sbd > reward_pool_sbd): raise ValueError('Provided more CBD than available in the reward pool.') rshares = ((recent_claims * sbd.amount) / ((reward_balance.amount * float(median_price)) - sbd.amount)) return int(rshares)
-82,920,561,340,008,460
Obtain the r-shares from CBD :param sbd: CBD :type sbd: str, int, amount.Amount :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote). Only impactful for very high amounts of CBD. Slight modification to the value calculation, as the not_broadcasted vote rshares decreases the reward pool.
crea/crea.py
sbd_to_rshares
creativechain/crea-python-lib
python
def sbd_to_rshares(self, sbd, not_broadcasted_vote=False, use_stored_data=True): ' Obtain the r-shares from CBD\n\n :param sbd: CBD\n :type sbd: str, int, amount.Amount\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n Only impactful for very high amounts of CBD. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n\n ' if isinstance(sbd, Amount): sbd = Amount(sbd, crea_instance=self) elif isinstance(sbd, string_types): sbd = Amount(sbd, crea_instance=self) else: sbd = Amount(sbd, self.sbd_symbol, crea_instance=self) if (sbd['symbol'] != self.sbd_symbol): raise AssertionError('Should input CBD, not any other asset!') if (not not_broadcasted_vote): return int((sbd.amount / self.get_sbd_per_rshares(use_stored_data=use_stored_data))) reward_fund = self.get_reward_funds(use_stored_data=use_stored_data) median_price = self.get_median_price(use_stored_data=use_stored_data) recent_claims = int(reward_fund['recent_claims']) reward_balance = Amount(reward_fund['reward_balance'], crea_instance=self) reward_pool_sbd = (median_price * reward_balance) if (sbd > reward_pool_sbd): raise ValueError('Provided more CBD than available in the reward pool.') rshares = ((recent_claims * sbd.amount) / ((reward_balance.amount * float(median_price)) - sbd.amount)) return int(rshares)
def rshares_to_vote_pct(self, rshares, crea_power=None, vests=None, voting_power=CREA_100_PERCENT, use_stored_data=True): ' Obtain the voting percentage for a desired rshares value\n for a given Crea Power or vesting shares and voting_power\n Give either crea_power or vests, not both.\n When the output is greater than 10000 or less than -10000,\n the given absolute rshares are too high\n\n Returns the required voting percentage (100% = 10000)\n\n :param number rshares: desired rshares value\n :param number crea_power: Crea Power\n :param number vests: vesting shares\n :param int voting_power: voting power (100% = 10000)\n\n ' if ((crea_power is None) and (vests is None)): raise ValueError('Either crea_power or vests has to be set!') if ((crea_power is not None) and (vests is not None)): raise ValueError('Either crea_power or vests has to be set. Not both!') if (crea_power is not None): vests = int((self.sp_to_vests(crea_power, use_stored_data=use_stored_data) * 1000000.0)) if (self.hardfork >= 20): rshares += math.copysign(self.get_dust_threshold(use_stored_data=use_stored_data), rshares) max_vote_denom = self._max_vote_denom(use_stored_data=use_stored_data) used_power = int(math.ceil(((abs(rshares) * CREA_100_PERCENT) / vests))) used_power = (used_power * max_vote_denom) vote_pct = (((used_power * CREA_100_PERCENT) / ((60 * 60) * 24)) / voting_power) return int(math.copysign(vote_pct, rshares))
-4,879,210,701,771,130,000
Obtain the voting percentage for a desired rshares value for a given Crea Power or vesting shares and voting_power Give either crea_power or vests, not both. When the output is greater than 10000 or less than -10000, the given absolute rshares are too high Returns the required voting percentage (100% = 10000) :param number rshares: desired rshares value :param number crea_power: Crea Power :param number vests: vesting shares :param int voting_power: voting power (100% = 10000)
crea/crea.py
rshares_to_vote_pct
creativechain/crea-python-lib
python
def rshares_to_vote_pct(self, rshares, crea_power=None, vests=None, voting_power=CREA_100_PERCENT, use_stored_data=True): ' Obtain the voting percentage for a desired rshares value\n for a given Crea Power or vesting shares and voting_power\n Give either crea_power or vests, not both.\n When the output is greater than 10000 or less than -10000,\n the given absolute rshares are too high\n\n Returns the required voting percentage (100% = 10000)\n\n :param number rshares: desired rshares value\n :param number crea_power: Crea Power\n :param number vests: vesting shares\n :param int voting_power: voting power (100% = 10000)\n\n ' if ((crea_power is None) and (vests is None)): raise ValueError('Either crea_power or vests has to be set!') if ((crea_power is not None) and (vests is not None)): raise ValueError('Either crea_power or vests has to be set. Not both!') if (crea_power is not None): vests = int((self.sp_to_vests(crea_power, use_stored_data=use_stored_data) * 1000000.0)) if (self.hardfork >= 20): rshares += math.copysign(self.get_dust_threshold(use_stored_data=use_stored_data), rshares) max_vote_denom = self._max_vote_denom(use_stored_data=use_stored_data) used_power = int(math.ceil(((abs(rshares) * CREA_100_PERCENT) / vests))) used_power = (used_power * max_vote_denom) vote_pct = (((used_power * CREA_100_PERCENT) / ((60 * 60) * 24)) / voting_power) return int(math.copysign(vote_pct, rshares))
def sbd_to_vote_pct(self, sbd, crea_power=None, vests=None, voting_power=CREA_100_PERCENT, not_broadcasted_vote=True, use_stored_data=True): ' Obtain the voting percentage for a desired CBD value\n for a given Crea Power or vesting shares and voting power\n Give either Crea Power or vests, not both.\n When the output is greater than 10000 or smaller than -10000,\n the CBD value is too high.\n\n Returns the required voting percentage (100% = 10000)\n\n :param sbd: desired CBD value\n :type sbd: str, int, amount.Amount\n :param number crea_power: Crea Power\n :param number vests: vesting shares\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n Only impactful for very high amounts of CBD. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n\n ' if isinstance(sbd, Amount): sbd = Amount(sbd, crea_instance=self) elif isinstance(sbd, string_types): sbd = Amount(sbd, crea_instance=self) else: sbd = Amount(sbd, self.sbd_symbol, crea_instance=self) if (sbd['symbol'] != self.sbd_symbol): raise AssertionError() rshares = self.sbd_to_rshares(sbd, not_broadcasted_vote=not_broadcasted_vote, use_stored_data=use_stored_data) return self.rshares_to_vote_pct(rshares, crea_power=crea_power, vests=vests, voting_power=voting_power, use_stored_data=use_stored_data)
1,368,237,473,710,176,000
Obtain the voting percentage for a desired CBD value for a given Crea Power or vesting shares and voting power Give either Crea Power or vests, not both. When the output is greater than 10000 or smaller than -10000, the CBD value is too high. Returns the required voting percentage (100% = 10000) :param sbd: desired CBD value :type sbd: str, int, amount.Amount :param number crea_power: Crea Power :param number vests: vesting shares :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote). Only impactful for very high amounts of CBD. Slight modification to the value calculation, as the not_broadcasted vote rshares decreases the reward pool.
crea/crea.py
sbd_to_vote_pct
creativechain/crea-python-lib
python
def sbd_to_vote_pct(self, sbd, crea_power=None, vests=None, voting_power=CREA_100_PERCENT, not_broadcasted_vote=True, use_stored_data=True): ' Obtain the voting percentage for a desired CBD value\n for a given Crea Power or vesting shares and voting power\n Give either Crea Power or vests, not both.\n When the output is greater than 10000 or smaller than -10000,\n the CBD value is too high.\n\n Returns the required voting percentage (100% = 10000)\n\n :param sbd: desired CBD value\n :type sbd: str, int, amount.Amount\n :param number crea_power: Crea Power\n :param number vests: vesting shares\n :param bool not_broadcasted_vote: not_broadcasted or already broadcasted vote (True = not_broadcasted vote).\n Only impactful for very high amounts of CBD. Slight modification to the value calculation, as the not_broadcasted\n vote rshares decreases the reward pool.\n\n ' if isinstance(sbd, Amount): sbd = Amount(sbd, crea_instance=self) elif isinstance(sbd, string_types): sbd = Amount(sbd, crea_instance=self) else: sbd = Amount(sbd, self.sbd_symbol, crea_instance=self) if (sbd['symbol'] != self.sbd_symbol): raise AssertionError() rshares = self.sbd_to_rshares(sbd, not_broadcasted_vote=not_broadcasted_vote, use_stored_data=use_stored_data) return self.rshares_to_vote_pct(rshares, crea_power=crea_power, vests=vests, voting_power=voting_power, use_stored_data=use_stored_data)
def get_chain_properties(self, use_stored_data=True): " Return witness elected chain properties\n\n Properties:::\n\n {\n 'account_creation_fee': '30.000 CREA',\n 'maximum_block_size': 65536,\n 'sbd_interest_rate': 250\n }\n\n " if use_stored_data: self.refresh_data() return self.data['witness_schedule']['median_props'] else: return self.get_witness_schedule(use_stored_data)['median_props']
900,415,650,330,882,200
Return witness elected chain properties Properties::: { 'account_creation_fee': '30.000 CREA', 'maximum_block_size': 65536, 'sbd_interest_rate': 250 }
crea/crea.py
get_chain_properties
creativechain/crea-python-lib
python
def get_chain_properties(self, use_stored_data=True): " Return witness elected chain properties\n\n Properties:::\n\n {\n 'account_creation_fee': '30.000 CREA',\n 'maximum_block_size': 65536,\n 'sbd_interest_rate': 250\n }\n\n " if use_stored_data: self.refresh_data() return self.data['witness_schedule']['median_props'] else: return self.get_witness_schedule(use_stored_data)['median_props']
def get_witness_schedule(self, use_stored_data=True): ' Return witness elected chain properties\n\n ' if use_stored_data: self.refresh_data() return self.data['witness_schedule'] if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) return self.rpc.get_witness_schedule(api='database')
-4,272,107,932,345,133,600
Return witness elected chain properties
crea/crea.py
get_witness_schedule
creativechain/crea-python-lib
python
def get_witness_schedule(self, use_stored_data=True): ' \n\n ' if use_stored_data: self.refresh_data() return self.data['witness_schedule'] if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) return self.rpc.get_witness_schedule(api='database')
def get_config(self, use_stored_data=True): ' Returns internal chain configuration.\n\n :param bool use_stored_data: If True, the cached value is returned\n ' if use_stored_data: self.refresh_data() config = self.data['config'] else: if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) config = self.rpc.get_config(api='database') return config
7,234,055,566,862,977,000
Returns internal chain configuration. :param bool use_stored_data: If True, the cached value is returned
crea/crea.py
get_config
creativechain/crea-python-lib
python
def get_config(self, use_stored_data=True): ' Returns internal chain configuration.\n\n :param bool use_stored_data: If True, the cached value is returned\n ' if use_stored_data: self.refresh_data() config = self.data['config'] else: if (self.rpc is None): return None self.rpc.set_next_node_on_empty_reply(True) config = self.rpc.get_config(api='database') return config
def set_default_account(self, account): ' Set the default account to be used\n ' Account(account, crea_instance=self) config['default_account'] = account
2,919,257,918,958,075,400
Set the default account to be used
crea/crea.py
set_default_account
creativechain/crea-python-lib
python
def set_default_account(self, account): ' \n ' Account(account, crea_instance=self) config['default_account'] = account
def set_password_storage(self, password_storage): ' Set the password storage mode.\n\n When set to "no", the password has to be provided each time.\n When set to "environment" the password is taken from the\n UNLOCK variable\n\n When set to "keyring" the password is taken from the\n python keyring module. A wallet password can be stored with\n python -m keyring set crea wallet password\n\n :param str password_storage: can be "no",\n "keyring" or "environment"\n\n ' config['password_storage'] = password_storage
-388,675,954,485,607,360
Set the password storage mode. When set to "no", the password has to be provided each time. When set to "environment" the password is taken from the UNLOCK variable When set to "keyring" the password is taken from the python keyring module. A wallet password can be stored with python -m keyring set crea wallet password :param str password_storage: can be "no", "keyring" or "environment"
crea/crea.py
set_password_storage
creativechain/crea-python-lib
python
def set_password_storage(self, password_storage): ' Set the password storage mode.\n\n When set to "no", the password has to be provided each time.\n When set to "environment" the password is taken from the\n UNLOCK variable\n\n When set to "keyring" the password is taken from the\n python keyring module. A wallet password can be stored with\n python -m keyring set crea wallet password\n\n :param str password_storage: can be "no",\n "keyring" or "environment"\n\n ' config['password_storage'] = password_storage
def set_default_nodes(self, nodes): ' Set the default nodes to be used\n ' if bool(nodes): if isinstance(nodes, list): nodes = str(nodes) config['node'] = nodes else: config.delete('node')
-685,676,945,500,974,800
Set the default nodes to be used
crea/crea.py
set_default_nodes
creativechain/crea-python-lib
python
def set_default_nodes(self, nodes): ' \n ' if bool(nodes): if isinstance(nodes, list): nodes = str(nodes) config['node'] = nodes else: config.delete('node')
def get_default_nodes(self): 'Returns the default nodes' if ('node' in config): nodes = config['node'] elif ('nodes' in config): nodes = config['nodes'] elif (('default_nodes' in config) and bool(config['default_nodes'])): nodes = config['default_nodes'] else: nodes = [] if (isinstance(nodes, str) and (nodes[0] == '[') and (nodes[(- 1)] == ']')): nodes = ast.literal_eval(nodes) return nodes
-1,576,660,519,120,907,800
Returns the default nodes
crea/crea.py
get_default_nodes
creativechain/crea-python-lib
python
def get_default_nodes(self): if ('node' in config): nodes = config['node'] elif ('nodes' in config): nodes = config['nodes'] elif (('default_nodes' in config) and bool(config['default_nodes'])): nodes = config['default_nodes'] else: nodes = [] if (isinstance(nodes, str) and (nodes[0] == '[') and (nodes[(- 1)] == ']')): nodes = ast.literal_eval(nodes) return nodes
def move_current_node_to_front(self): 'Returns the default node list, until the first entry\n is equal to the current working node url\n ' node = self.get_default_nodes() if (len(node) < 2): return offline = self.offline while ((not offline) and (node[0] != self.rpc.url) and (len(node) > 1)): node = (node[1:] + [node[0]]) self.set_default_nodes(node)
-5,797,824,108,166,384,000
Returns the default node list, until the first entry is equal to the current working node url
crea/crea.py
move_current_node_to_front
creativechain/crea-python-lib
python
def move_current_node_to_front(self): 'Returns the default node list, until the first entry\n is equal to the current working node url\n ' node = self.get_default_nodes() if (len(node) < 2): return offline = self.offline while ((not offline) and (node[0] != self.rpc.url) and (len(node) > 1)): node = (node[1:] + [node[0]]) self.set_default_nodes(node)
def set_default_vote_weight(self, vote_weight): ' Set the default vote weight to be used\n ' config['default_vote_weight'] = vote_weight
-6,378,185,273,434,452,000
Set the default vote weight to be used
crea/crea.py
set_default_vote_weight
creativechain/crea-python-lib
python
def set_default_vote_weight(self, vote_weight): ' \n ' config['default_vote_weight'] = vote_weight
def finalizeOp(self, ops, account, permission, **kwargs): ' This method obtains the required private keys if present in\n the wallet, finalizes the transaction, signs it and\n broadacasts it\n\n :param ops: The operation (or list of operations) to\n broadcast\n :type ops: list, GrapheneObject\n :param Account account: The account that authorizes the\n operation\n :param string permission: The required permission for\n signing (active, owner, posting)\n :param TransactionBuilder append_to: This allows to provide an instance of\n TransactionBuilder (see :func:`Crea.new_tx()`) to specify\n where to put a specific operation.\n\n .. note:: ``append_to`` is exposed to every method used in the\n Crea class\n\n .. note:: If ``ops`` is a list of operation, they all need to be\n signable by the same key! Thus, you cannot combine ops\n that require active permission with ops that require\n posting permission. Neither can you use different\n accounts for different operations!\n\n .. note:: This uses :func:`Crea.txbuffer` as instance of\n :class:`crea.transactionbuilder.TransactionBuilder`.\n You may want to use your own txbuffer\n ' if self.offline: return {} if (('append_to' in kwargs) and kwargs['append_to']): append_to = kwargs['append_to'] parent = append_to.get_parent() if (not isinstance(append_to, TransactionBuilder)): raise AssertionError() append_to.appendOps(ops) parent.appendSigner(account, permission) return append_to.get_parent() else: self.txbuffer.appendOps(ops) if self.unsigned: self.txbuffer.addSigningInformation(account, permission) return self.txbuffer elif self.bundle: self.txbuffer.appendSigner(account, permission) return self.txbuffer.json() else: self.txbuffer.appendSigner(account, permission) self.txbuffer.sign() return self.txbuffer.broadcast()
-6,611,208,480,797,089,000
This method obtains the required private keys if present in the wallet, finalizes the transaction, signs it and broadacasts it :param ops: The operation (or list of operations) to broadcast :type ops: list, GrapheneObject :param Account account: The account that authorizes the operation :param string permission: The required permission for signing (active, owner, posting) :param TransactionBuilder append_to: This allows to provide an instance of TransactionBuilder (see :func:`Crea.new_tx()`) to specify where to put a specific operation. .. note:: ``append_to`` is exposed to every method used in the Crea class .. note:: If ``ops`` is a list of operation, they all need to be signable by the same key! Thus, you cannot combine ops that require active permission with ops that require posting permission. Neither can you use different accounts for different operations! .. note:: This uses :func:`Crea.txbuffer` as instance of :class:`crea.transactionbuilder.TransactionBuilder`. You may want to use your own txbuffer
crea/crea.py
finalizeOp
creativechain/crea-python-lib
python
def finalizeOp(self, ops, account, permission, **kwargs): ' This method obtains the required private keys if present in\n the wallet, finalizes the transaction, signs it and\n broadacasts it\n\n :param ops: The operation (or list of operations) to\n broadcast\n :type ops: list, GrapheneObject\n :param Account account: The account that authorizes the\n operation\n :param string permission: The required permission for\n signing (active, owner, posting)\n :param TransactionBuilder append_to: This allows to provide an instance of\n TransactionBuilder (see :func:`Crea.new_tx()`) to specify\n where to put a specific operation.\n\n .. note:: ``append_to`` is exposed to every method used in the\n Crea class\n\n .. note:: If ``ops`` is a list of operation, they all need to be\n signable by the same key! Thus, you cannot combine ops\n that require active permission with ops that require\n posting permission. Neither can you use different\n accounts for different operations!\n\n .. note:: This uses :func:`Crea.txbuffer` as instance of\n :class:`crea.transactionbuilder.TransactionBuilder`.\n You may want to use your own txbuffer\n ' if self.offline: return {} if (('append_to' in kwargs) and kwargs['append_to']): append_to = kwargs['append_to'] parent = append_to.get_parent() if (not isinstance(append_to, TransactionBuilder)): raise AssertionError() append_to.appendOps(ops) parent.appendSigner(account, permission) return append_to.get_parent() else: self.txbuffer.appendOps(ops) if self.unsigned: self.txbuffer.addSigningInformation(account, permission) return self.txbuffer elif self.bundle: self.txbuffer.appendSigner(account, permission) return self.txbuffer.json() else: self.txbuffer.appendSigner(account, permission) self.txbuffer.sign() return self.txbuffer.broadcast()
def sign(self, tx=None, wifs=[], reconstruct_tx=True): ' Sign a provided transaction with the provided key(s)\n\n :param dict tx: The transaction to be signed and returned\n :param string wifs: One or many wif keys to use for signing\n a transaction. If not present, the keys will be loaded\n from the wallet as defined in "missing_signatures" key\n of the transactions.\n :param bool reconstruct_tx: when set to False and tx\n is already contructed, it will not reconstructed\n and already added signatures remain\n\n ' if tx: txbuffer = TransactionBuilder(tx, crea_instance=self) else: txbuffer = self.txbuffer txbuffer.appendWif(wifs) txbuffer.appendMissingSignatures() txbuffer.sign(reconstruct_tx=reconstruct_tx) return txbuffer.json()
8,778,294,486,211,037,000
Sign a provided transaction with the provided key(s) :param dict tx: The transaction to be signed and returned :param string wifs: One or many wif keys to use for signing a transaction. If not present, the keys will be loaded from the wallet as defined in "missing_signatures" key of the transactions. :param bool reconstruct_tx: when set to False and tx is already contructed, it will not reconstructed and already added signatures remain
crea/crea.py
sign
creativechain/crea-python-lib
python
def sign(self, tx=None, wifs=[], reconstruct_tx=True): ' Sign a provided transaction with the provided key(s)\n\n :param dict tx: The transaction to be signed and returned\n :param string wifs: One or many wif keys to use for signing\n a transaction. If not present, the keys will be loaded\n from the wallet as defined in "missing_signatures" key\n of the transactions.\n :param bool reconstruct_tx: when set to False and tx\n is already contructed, it will not reconstructed\n and already added signatures remain\n\n ' if tx: txbuffer = TransactionBuilder(tx, crea_instance=self) else: txbuffer = self.txbuffer txbuffer.appendWif(wifs) txbuffer.appendMissingSignatures() txbuffer.sign(reconstruct_tx=reconstruct_tx) return txbuffer.json()
def broadcast(self, tx=None): ' Broadcast a transaction to the Crea network\n\n :param tx tx: Signed transaction to broadcast\n\n ' if tx: return TransactionBuilder(tx, crea_instance=self).broadcast() else: return self.txbuffer.broadcast()
-6,851,223,572,119,729,000
Broadcast a transaction to the Crea network :param tx tx: Signed transaction to broadcast
crea/crea.py
broadcast
creativechain/crea-python-lib
python
def broadcast(self, tx=None): ' Broadcast a transaction to the Crea network\n\n :param tx tx: Signed transaction to broadcast\n\n ' if tx: return TransactionBuilder(tx, crea_instance=self).broadcast() else: return self.txbuffer.broadcast()
def info(self, use_stored_data=True): ' Returns the global properties\n ' return self.get_dynamic_global_properties(use_stored_data=use_stored_data)
-818,533,252,388,624,900
Returns the global properties
crea/crea.py
info
creativechain/crea-python-lib
python
def info(self, use_stored_data=True): ' \n ' return self.get_dynamic_global_properties(use_stored_data=use_stored_data)
def newWallet(self, pwd): ' Create a new wallet. This method is basically only calls\n :func:`crea.wallet.Wallet.create`.\n\n :param str pwd: Password to use for the new wallet\n\n :raises WalletExists: if there is already a\n wallet created\n\n ' return self.wallet.create(pwd)
3,670,030,472,949,375,000
Create a new wallet. This method is basically only calls :func:`crea.wallet.Wallet.create`. :param str pwd: Password to use for the new wallet :raises WalletExists: if there is already a wallet created
crea/crea.py
newWallet
creativechain/crea-python-lib
python
def newWallet(self, pwd): ' Create a new wallet. This method is basically only calls\n :func:`crea.wallet.Wallet.create`.\n\n :param str pwd: Password to use for the new wallet\n\n :raises WalletExists: if there is already a\n wallet created\n\n ' return self.wallet.create(pwd)
def unlock(self, *args, **kwargs): ' Unlock the internal wallet\n ' return self.wallet.unlock(*args, **kwargs)
-8,737,820,938,272,326,000
Unlock the internal wallet
crea/crea.py
unlock
creativechain/crea-python-lib
python
def unlock(self, *args, **kwargs): ' \n ' return self.wallet.unlock(*args, **kwargs)
@property def txbuffer(self): ' Returns the currently active tx buffer\n ' return self.tx()
3,077,081,393,798,707,700
Returns the currently active tx buffer
crea/crea.py
txbuffer
creativechain/crea-python-lib
python
@property def txbuffer(self): ' \n ' return self.tx()
def tx(self): ' Returns the default transaction buffer\n ' return self._txbuffers[0]
5,966,482,822,398,606,000
Returns the default transaction buffer
crea/crea.py
tx
creativechain/crea-python-lib
python
def tx(self): ' \n ' return self._txbuffers[0]
def new_tx(self, *args, **kwargs): " Let's obtain a new txbuffer\n\n :returns: id of the new txbuffer\n :rtype: int\n " builder = TransactionBuilder(*args, crea_instance=self, **kwargs) self._txbuffers.append(builder) return builder
-812,935,130,183,155,200
Let's obtain a new txbuffer :returns: id of the new txbuffer :rtype: int
crea/crea.py
new_tx
creativechain/crea-python-lib
python
def new_tx(self, *args, **kwargs): " Let's obtain a new txbuffer\n\n :returns: id of the new txbuffer\n :rtype: int\n " builder = TransactionBuilder(*args, crea_instance=self, **kwargs) self._txbuffers.append(builder) return builder
def claim_account(self, creator, fee=None, **kwargs): ' Claim account for claimed account creation.\n\n When fee is 0 CREA a subsidized account is claimed and can be created\n later with create_claimed_account.\n The number of subsidized account is limited.\n\n :param str creator: which account should pay the registration fee (RC or CREA)\n (defaults to ``default_account``)\n :param str fee: when set to 0 CREA (default), claim account is paid by RC\n ' fee = (fee if (fee is not None) else ('0 %s' % self.crea_symbol)) if ((not creator) and config['default_account']): creator = config['default_account'] if (not creator): raise ValueError(('Not creator account given. Define it with ' + 'creator=x, or set the default_account using creapy')) creator = Account(creator, crea_instance=self) op = {'fee': Amount(fee, crea_instance=self), 'creator': creator['name'], 'prefix': self.prefix} op = operations.Claim_account(**op) return self.finalizeOp(op, creator, 'active', **kwargs)
4,870,016,310,296,848,000
Claim account for claimed account creation. When fee is 0 CREA a subsidized account is claimed and can be created later with create_claimed_account. The number of subsidized account is limited. :param str creator: which account should pay the registration fee (RC or CREA) (defaults to ``default_account``) :param str fee: when set to 0 CREA (default), claim account is paid by RC
crea/crea.py
claim_account
creativechain/crea-python-lib
python
def claim_account(self, creator, fee=None, **kwargs): ' Claim account for claimed account creation.\n\n When fee is 0 CREA a subsidized account is claimed and can be created\n later with create_claimed_account.\n The number of subsidized account is limited.\n\n :param str creator: which account should pay the registration fee (RC or CREA)\n (defaults to ``default_account``)\n :param str fee: when set to 0 CREA (default), claim account is paid by RC\n ' fee = (fee if (fee is not None) else ('0 %s' % self.crea_symbol)) if ((not creator) and config['default_account']): creator = config['default_account'] if (not creator): raise ValueError(('Not creator account given. Define it with ' + 'creator=x, or set the default_account using creapy')) creator = Account(creator, crea_instance=self) op = {'fee': Amount(fee, crea_instance=self), 'creator': creator['name'], 'prefix': self.prefix} op = operations.Claim_account(**op) return self.finalizeOp(op, creator, 'active', **kwargs)
def create_claimed_account(self, account_name, creator=None, owner_key=None, active_key=None, memo_key=None, posting_key=None, password=None, additional_owner_keys=[], additional_active_keys=[], additional_posting_keys=[], additional_owner_accounts=[], additional_active_accounts=[], additional_posting_accounts=[], storekeys=True, store_owner_key=False, json_meta=None, combine_with_claim_account=False, fee=None, **kwargs): " Create new claimed account on Crea\n\n The brainkey/password can be used to recover all generated keys\n (see :class:`creagraphenebase.account` for more details.\n\n By default, this call will use ``default_account`` to\n register a new name ``account_name`` with all keys being\n derived from a new brain key that will be returned. The\n corresponding keys will automatically be installed in the\n wallet.\n\n .. warning:: Don't call this method unless you know what\n you are doing! Be sure to understand what this\n method does and where to find the private keys\n for your account.\n\n .. note:: Please note that this imports private keys\n (if password is present) into the wallet by\n default when nobroadcast is set to False.\n However, it **does not import the owner\n key** for security reasons by default.\n If you set store_owner_key to True, the\n owner key is stored.\n Do NOT expect to be able to recover it from\n the wallet if you lose your password!\n\n .. note:: Account creations cost a fee that is defined by\n the network. If you create an account, you will\n need to pay for that fee!\n\n :param str account_name: (**required**) new account name\n :param str json_meta: Optional meta data for the account\n :param str owner_key: Main owner key\n :param str active_key: Main active key\n :param str posting_key: Main posting key\n :param str memo_key: Main memo_key\n :param str password: Alternatively to providing keys, one\n can provide a password from which the\n keys will be derived\n :param array additional_owner_keys: Additional owner public keys\n :param array additional_active_keys: Additional active public keys\n :param array additional_posting_keys: Additional posting public keys\n :param array additional_owner_accounts: Additional owner account\n names\n :param array additional_active_accounts: Additional acctive account\n names\n :param bool storekeys: Store new keys in the wallet (default:\n ``True``)\n :param bool combine_with_claim_account: When set to True, a\n claim_account operation is additionally broadcasted\n :param str fee: When combine_with_claim_account is set to True,\n this parameter is used for the claim_account operation\n\n :param str creator: which account should pay the registration fee\n (defaults to ``default_account``)\n :raises AccountExistsException: if the account already exists on\n the blockchain\n\n " fee = (fee if (fee is not None) else ('0 %s' % self.crea_symbol)) if ((not creator) and config['default_account']): creator = config['default_account'] if (not creator): raise ValueError(('Not creator account given. Define it with ' + 'creator=x, or set the default_account using creapy')) if (password and (owner_key or active_key or memo_key)): raise ValueError("You cannot use 'password' AND provide keys!") try: Account(account_name, crea_instance=self) raise AccountExistsException except AccountDoesNotExistsException: pass creator = Account(creator, crea_instance=self) ' Generate new keys from password' from creagraphenebase.account import PasswordKey if password: active_key = PasswordKey(account_name, password, role='active', prefix=self.prefix) owner_key = PasswordKey(account_name, password, role='owner', prefix=self.prefix) posting_key = PasswordKey(account_name, password, role='posting', prefix=self.prefix) memo_key = PasswordKey(account_name, password, role='memo', prefix=self.prefix) active_pubkey = active_key.get_public_key() owner_pubkey = owner_key.get_public_key() posting_pubkey = posting_key.get_public_key() memo_pubkey = memo_key.get_public_key() active_privkey = active_key.get_private_key() posting_privkey = posting_key.get_private_key() owner_privkey = owner_key.get_private_key() memo_privkey = memo_key.get_private_key() try: if (storekeys and (not self.nobroadcast)): if store_owner_key: self.wallet.addPrivateKey(str(owner_privkey)) self.wallet.addPrivateKey(str(active_privkey)) self.wallet.addPrivateKey(str(memo_privkey)) self.wallet.addPrivateKey(str(posting_privkey)) except ValueError as e: log.info(str(e)) elif (owner_key and active_key and memo_key and posting_key): active_pubkey = PublicKey(active_key, prefix=self.prefix) owner_pubkey = PublicKey(owner_key, prefix=self.prefix) posting_pubkey = PublicKey(posting_key, prefix=self.prefix) memo_pubkey = PublicKey(memo_key, prefix=self.prefix) else: raise ValueError('Call incomplete! Provide either a password or public keys!') owner = format(owner_pubkey, self.prefix) active = format(active_pubkey, self.prefix) posting = format(posting_pubkey, self.prefix) memo = format(memo_pubkey, self.prefix) owner_key_authority = [[owner, 1]] active_key_authority = [[active, 1]] posting_key_authority = [[posting, 1]] owner_accounts_authority = [] active_accounts_authority = [] posting_accounts_authority = [] for k in additional_owner_keys: owner_key_authority.append([k, 1]) for k in additional_active_keys: active_key_authority.append([k, 1]) for k in additional_posting_keys: posting_key_authority.append([k, 1]) for k in additional_owner_accounts: addaccount = Account(k, crea_instance=self) owner_accounts_authority.append([addaccount['name'], 1]) for k in additional_active_accounts: addaccount = Account(k, crea_instance=self) active_accounts_authority.append([addaccount['name'], 1]) for k in additional_posting_accounts: addaccount = Account(k, crea_instance=self) posting_accounts_authority.append([addaccount['name'], 1]) if combine_with_claim_account: op = {'fee': Amount(fee, crea_instance=self), 'creator': creator['name'], 'prefix': self.prefix} op = operations.Claim_account(**op) ops = [op] op = {'creator': creator['name'], 'new_account_name': account_name, 'owner': {'account_auths': owner_accounts_authority, 'key_auths': owner_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'active': {'account_auths': active_accounts_authority, 'key_auths': active_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'posting': {'account_auths': active_accounts_authority, 'key_auths': posting_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'memo_key': memo, 'json_metadata': (json_meta or {}), 'prefix': self.prefix} op = operations.Create_claimed_account(**op) if combine_with_claim_account: ops.append(op) return self.finalizeOp(ops, creator, 'active', **kwargs) else: return self.finalizeOp(op, creator, 'active', **kwargs)
1,773,387,453,791,773,400
Create new claimed account on Crea The brainkey/password can be used to recover all generated keys (see :class:`creagraphenebase.account` for more details. By default, this call will use ``default_account`` to register a new name ``account_name`` with all keys being derived from a new brain key that will be returned. The corresponding keys will automatically be installed in the wallet. .. warning:: Don't call this method unless you know what you are doing! Be sure to understand what this method does and where to find the private keys for your account. .. note:: Please note that this imports private keys (if password is present) into the wallet by default when nobroadcast is set to False. However, it **does not import the owner key** for security reasons by default. If you set store_owner_key to True, the owner key is stored. Do NOT expect to be able to recover it from the wallet if you lose your password! .. note:: Account creations cost a fee that is defined by the network. If you create an account, you will need to pay for that fee! :param str account_name: (**required**) new account name :param str json_meta: Optional meta data for the account :param str owner_key: Main owner key :param str active_key: Main active key :param str posting_key: Main posting key :param str memo_key: Main memo_key :param str password: Alternatively to providing keys, one can provide a password from which the keys will be derived :param array additional_owner_keys: Additional owner public keys :param array additional_active_keys: Additional active public keys :param array additional_posting_keys: Additional posting public keys :param array additional_owner_accounts: Additional owner account names :param array additional_active_accounts: Additional acctive account names :param bool storekeys: Store new keys in the wallet (default: ``True``) :param bool combine_with_claim_account: When set to True, a claim_account operation is additionally broadcasted :param str fee: When combine_with_claim_account is set to True, this parameter is used for the claim_account operation :param str creator: which account should pay the registration fee (defaults to ``default_account``) :raises AccountExistsException: if the account already exists on the blockchain
crea/crea.py
create_claimed_account
creativechain/crea-python-lib
python
def create_claimed_account(self, account_name, creator=None, owner_key=None, active_key=None, memo_key=None, posting_key=None, password=None, additional_owner_keys=[], additional_active_keys=[], additional_posting_keys=[], additional_owner_accounts=[], additional_active_accounts=[], additional_posting_accounts=[], storekeys=True, store_owner_key=False, json_meta=None, combine_with_claim_account=False, fee=None, **kwargs): " Create new claimed account on Crea\n\n The brainkey/password can be used to recover all generated keys\n (see :class:`creagraphenebase.account` for more details.\n\n By default, this call will use ``default_account`` to\n register a new name ``account_name`` with all keys being\n derived from a new brain key that will be returned. The\n corresponding keys will automatically be installed in the\n wallet.\n\n .. warning:: Don't call this method unless you know what\n you are doing! Be sure to understand what this\n method does and where to find the private keys\n for your account.\n\n .. note:: Please note that this imports private keys\n (if password is present) into the wallet by\n default when nobroadcast is set to False.\n However, it **does not import the owner\n key** for security reasons by default.\n If you set store_owner_key to True, the\n owner key is stored.\n Do NOT expect to be able to recover it from\n the wallet if you lose your password!\n\n .. note:: Account creations cost a fee that is defined by\n the network. If you create an account, you will\n need to pay for that fee!\n\n :param str account_name: (**required**) new account name\n :param str json_meta: Optional meta data for the account\n :param str owner_key: Main owner key\n :param str active_key: Main active key\n :param str posting_key: Main posting key\n :param str memo_key: Main memo_key\n :param str password: Alternatively to providing keys, one\n can provide a password from which the\n keys will be derived\n :param array additional_owner_keys: Additional owner public keys\n :param array additional_active_keys: Additional active public keys\n :param array additional_posting_keys: Additional posting public keys\n :param array additional_owner_accounts: Additional owner account\n names\n :param array additional_active_accounts: Additional acctive account\n names\n :param bool storekeys: Store new keys in the wallet (default:\n ``True``)\n :param bool combine_with_claim_account: When set to True, a\n claim_account operation is additionally broadcasted\n :param str fee: When combine_with_claim_account is set to True,\n this parameter is used for the claim_account operation\n\n :param str creator: which account should pay the registration fee\n (defaults to ``default_account``)\n :raises AccountExistsException: if the account already exists on\n the blockchain\n\n " fee = (fee if (fee is not None) else ('0 %s' % self.crea_symbol)) if ((not creator) and config['default_account']): creator = config['default_account'] if (not creator): raise ValueError(('Not creator account given. Define it with ' + 'creator=x, or set the default_account using creapy')) if (password and (owner_key or active_key or memo_key)): raise ValueError("You cannot use 'password' AND provide keys!") try: Account(account_name, crea_instance=self) raise AccountExistsException except AccountDoesNotExistsException: pass creator = Account(creator, crea_instance=self) ' Generate new keys from password' from creagraphenebase.account import PasswordKey if password: active_key = PasswordKey(account_name, password, role='active', prefix=self.prefix) owner_key = PasswordKey(account_name, password, role='owner', prefix=self.prefix) posting_key = PasswordKey(account_name, password, role='posting', prefix=self.prefix) memo_key = PasswordKey(account_name, password, role='memo', prefix=self.prefix) active_pubkey = active_key.get_public_key() owner_pubkey = owner_key.get_public_key() posting_pubkey = posting_key.get_public_key() memo_pubkey = memo_key.get_public_key() active_privkey = active_key.get_private_key() posting_privkey = posting_key.get_private_key() owner_privkey = owner_key.get_private_key() memo_privkey = memo_key.get_private_key() try: if (storekeys and (not self.nobroadcast)): if store_owner_key: self.wallet.addPrivateKey(str(owner_privkey)) self.wallet.addPrivateKey(str(active_privkey)) self.wallet.addPrivateKey(str(memo_privkey)) self.wallet.addPrivateKey(str(posting_privkey)) except ValueError as e: log.info(str(e)) elif (owner_key and active_key and memo_key and posting_key): active_pubkey = PublicKey(active_key, prefix=self.prefix) owner_pubkey = PublicKey(owner_key, prefix=self.prefix) posting_pubkey = PublicKey(posting_key, prefix=self.prefix) memo_pubkey = PublicKey(memo_key, prefix=self.prefix) else: raise ValueError('Call incomplete! Provide either a password or public keys!') owner = format(owner_pubkey, self.prefix) active = format(active_pubkey, self.prefix) posting = format(posting_pubkey, self.prefix) memo = format(memo_pubkey, self.prefix) owner_key_authority = [[owner, 1]] active_key_authority = [[active, 1]] posting_key_authority = [[posting, 1]] owner_accounts_authority = [] active_accounts_authority = [] posting_accounts_authority = [] for k in additional_owner_keys: owner_key_authority.append([k, 1]) for k in additional_active_keys: active_key_authority.append([k, 1]) for k in additional_posting_keys: posting_key_authority.append([k, 1]) for k in additional_owner_accounts: addaccount = Account(k, crea_instance=self) owner_accounts_authority.append([addaccount['name'], 1]) for k in additional_active_accounts: addaccount = Account(k, crea_instance=self) active_accounts_authority.append([addaccount['name'], 1]) for k in additional_posting_accounts: addaccount = Account(k, crea_instance=self) posting_accounts_authority.append([addaccount['name'], 1]) if combine_with_claim_account: op = {'fee': Amount(fee, crea_instance=self), 'creator': creator['name'], 'prefix': self.prefix} op = operations.Claim_account(**op) ops = [op] op = {'creator': creator['name'], 'new_account_name': account_name, 'owner': {'account_auths': owner_accounts_authority, 'key_auths': owner_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'active': {'account_auths': active_accounts_authority, 'key_auths': active_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'posting': {'account_auths': active_accounts_authority, 'key_auths': posting_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'memo_key': memo, 'json_metadata': (json_meta or {}), 'prefix': self.prefix} op = operations.Create_claimed_account(**op) if combine_with_claim_account: ops.append(op) return self.finalizeOp(ops, creator, 'active', **kwargs) else: return self.finalizeOp(op, creator, 'active', **kwargs)
def create_account(self, account_name, creator=None, owner_key=None, active_key=None, memo_key=None, posting_key=None, password=None, additional_owner_keys=[], additional_active_keys=[], additional_posting_keys=[], additional_owner_accounts=[], additional_active_accounts=[], additional_posting_accounts=[], storekeys=True, store_owner_key=False, json_meta=None, **kwargs): " Create new account on Crea\n\n The brainkey/password can be used to recover all generated keys\n (see :class:`creagraphenebase.account` for more details.\n\n By default, this call will use ``default_account`` to\n register a new name ``account_name`` with all keys being\n derived from a new brain key that will be returned. The\n corresponding keys will automatically be installed in the\n wallet.\n\n .. warning:: Don't call this method unless you know what\n you are doing! Be sure to understand what this\n method does and where to find the private keys\n for your account.\n\n .. note:: Please note that this imports private keys\n (if password is present) into the wallet by\n default when nobroadcast is set to False.\n However, it **does not import the owner\n key** for security reasons by default.\n If you set store_owner_key to True, the\n owner key is stored.\n Do NOT expect to be able to recover it from\n the wallet if you lose your password!\n\n .. note:: Account creations cost a fee that is defined by\n the network. If you create an account, you will\n need to pay for that fee!\n\n :param str account_name: (**required**) new account name\n :param str json_meta: Optional meta data for the account\n :param str owner_key: Main owner key\n :param str active_key: Main active key\n :param str posting_key: Main posting key\n :param str memo_key: Main memo_key\n :param str password: Alternatively to providing keys, one\n can provide a password from which the\n keys will be derived\n :param array additional_owner_keys: Additional owner public keys\n :param array additional_active_keys: Additional active public keys\n :param array additional_posting_keys: Additional posting public keys\n :param array additional_owner_accounts: Additional owner account\n names\n :param array additional_active_accounts: Additional acctive account\n names\n :param bool storekeys: Store new keys in the wallet (default:\n ``True``)\n\n :param str creator: which account should pay the registration fee\n (defaults to ``default_account``)\n :raises AccountExistsException: if the account already exists on\n the blockchain\n\n " if ((not creator) and config['default_account']): creator = config['default_account'] if (not creator): raise ValueError(('Not creator account given. Define it with ' + 'creator=x, or set the default_account using creapy')) if (password and (owner_key or active_key or memo_key)): raise ValueError("You cannot use 'password' AND provide keys!") try: Account(account_name, crea_instance=self) raise AccountExistsException except AccountDoesNotExistsException: pass creator = Account(creator, crea_instance=self) ' Generate new keys from password' from creagraphenebase.account import PasswordKey if password: active_key = PasswordKey(account_name, password, role='active', prefix=self.prefix) owner_key = PasswordKey(account_name, password, role='owner', prefix=self.prefix) posting_key = PasswordKey(account_name, password, role='posting', prefix=self.prefix) memo_key = PasswordKey(account_name, password, role='memo', prefix=self.prefix) active_pubkey = active_key.get_public_key() owner_pubkey = owner_key.get_public_key() posting_pubkey = posting_key.get_public_key() memo_pubkey = memo_key.get_public_key() active_privkey = active_key.get_private_key() posting_privkey = posting_key.get_private_key() owner_privkey = owner_key.get_private_key() memo_privkey = memo_key.get_private_key() try: if (storekeys and (not self.nobroadcast)): if store_owner_key: self.wallet.addPrivateKey(str(owner_privkey)) self.wallet.addPrivateKey(str(active_privkey)) self.wallet.addPrivateKey(str(memo_privkey)) self.wallet.addPrivateKey(str(posting_privkey)) except ValueError as e: log.info(str(e)) elif (owner_key and active_key and memo_key and posting_key): active_pubkey = PublicKey(active_key, prefix=self.prefix) owner_pubkey = PublicKey(owner_key, prefix=self.prefix) posting_pubkey = PublicKey(posting_key, prefix=self.prefix) memo_pubkey = PublicKey(memo_key, prefix=self.prefix) else: raise ValueError('Call incomplete! Provide either a password or public keys!') owner = format(owner_pubkey, self.prefix) active = format(active_pubkey, self.prefix) posting = format(posting_pubkey, self.prefix) memo = format(memo_pubkey, self.prefix) owner_key_authority = [[owner, 1]] active_key_authority = [[active, 1]] posting_key_authority = [[posting, 1]] owner_accounts_authority = [] active_accounts_authority = [] posting_accounts_authority = [] for k in additional_owner_keys: owner_key_authority.append([k, 1]) for k in additional_active_keys: active_key_authority.append([k, 1]) for k in additional_posting_keys: posting_key_authority.append([k, 1]) for k in additional_owner_accounts: addaccount = Account(k, crea_instance=self) owner_accounts_authority.append([addaccount['name'], 1]) for k in additional_active_accounts: addaccount = Account(k, crea_instance=self) active_accounts_authority.append([addaccount['name'], 1]) for k in additional_posting_accounts: addaccount = Account(k, crea_instance=self) posting_accounts_authority.append([addaccount['name'], 1]) props = self.get_chain_properties() if (self.hardfork >= 20): required_fee_crea = Amount(props['account_creation_fee'], crea_instance=self) else: required_fee_crea = (Amount(props['account_creation_fee'], crea_instance=self) * 30) op = {'fee': required_fee_crea, 'creator': creator['name'], 'new_account_name': account_name, 'owner': {'account_auths': owner_accounts_authority, 'key_auths': owner_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'active': {'account_auths': active_accounts_authority, 'key_auths': active_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'posting': {'account_auths': posting_accounts_authority, 'key_auths': posting_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'memo_key': memo, 'json_metadata': (json_meta or {}), 'prefix': self.prefix} op = operations.Account_create(**op) return self.finalizeOp(op, creator, 'active', **kwargs)
7,496,495,228,049,349,000
Create new account on Crea The brainkey/password can be used to recover all generated keys (see :class:`creagraphenebase.account` for more details. By default, this call will use ``default_account`` to register a new name ``account_name`` with all keys being derived from a new brain key that will be returned. The corresponding keys will automatically be installed in the wallet. .. warning:: Don't call this method unless you know what you are doing! Be sure to understand what this method does and where to find the private keys for your account. .. note:: Please note that this imports private keys (if password is present) into the wallet by default when nobroadcast is set to False. However, it **does not import the owner key** for security reasons by default. If you set store_owner_key to True, the owner key is stored. Do NOT expect to be able to recover it from the wallet if you lose your password! .. note:: Account creations cost a fee that is defined by the network. If you create an account, you will need to pay for that fee! :param str account_name: (**required**) new account name :param str json_meta: Optional meta data for the account :param str owner_key: Main owner key :param str active_key: Main active key :param str posting_key: Main posting key :param str memo_key: Main memo_key :param str password: Alternatively to providing keys, one can provide a password from which the keys will be derived :param array additional_owner_keys: Additional owner public keys :param array additional_active_keys: Additional active public keys :param array additional_posting_keys: Additional posting public keys :param array additional_owner_accounts: Additional owner account names :param array additional_active_accounts: Additional acctive account names :param bool storekeys: Store new keys in the wallet (default: ``True``) :param str creator: which account should pay the registration fee (defaults to ``default_account``) :raises AccountExistsException: if the account already exists on the blockchain
crea/crea.py
create_account
creativechain/crea-python-lib
python
def create_account(self, account_name, creator=None, owner_key=None, active_key=None, memo_key=None, posting_key=None, password=None, additional_owner_keys=[], additional_active_keys=[], additional_posting_keys=[], additional_owner_accounts=[], additional_active_accounts=[], additional_posting_accounts=[], storekeys=True, store_owner_key=False, json_meta=None, **kwargs): " Create new account on Crea\n\n The brainkey/password can be used to recover all generated keys\n (see :class:`creagraphenebase.account` for more details.\n\n By default, this call will use ``default_account`` to\n register a new name ``account_name`` with all keys being\n derived from a new brain key that will be returned. The\n corresponding keys will automatically be installed in the\n wallet.\n\n .. warning:: Don't call this method unless you know what\n you are doing! Be sure to understand what this\n method does and where to find the private keys\n for your account.\n\n .. note:: Please note that this imports private keys\n (if password is present) into the wallet by\n default when nobroadcast is set to False.\n However, it **does not import the owner\n key** for security reasons by default.\n If you set store_owner_key to True, the\n owner key is stored.\n Do NOT expect to be able to recover it from\n the wallet if you lose your password!\n\n .. note:: Account creations cost a fee that is defined by\n the network. If you create an account, you will\n need to pay for that fee!\n\n :param str account_name: (**required**) new account name\n :param str json_meta: Optional meta data for the account\n :param str owner_key: Main owner key\n :param str active_key: Main active key\n :param str posting_key: Main posting key\n :param str memo_key: Main memo_key\n :param str password: Alternatively to providing keys, one\n can provide a password from which the\n keys will be derived\n :param array additional_owner_keys: Additional owner public keys\n :param array additional_active_keys: Additional active public keys\n :param array additional_posting_keys: Additional posting public keys\n :param array additional_owner_accounts: Additional owner account\n names\n :param array additional_active_accounts: Additional acctive account\n names\n :param bool storekeys: Store new keys in the wallet (default:\n ``True``)\n\n :param str creator: which account should pay the registration fee\n (defaults to ``default_account``)\n :raises AccountExistsException: if the account already exists on\n the blockchain\n\n " if ((not creator) and config['default_account']): creator = config['default_account'] if (not creator): raise ValueError(('Not creator account given. Define it with ' + 'creator=x, or set the default_account using creapy')) if (password and (owner_key or active_key or memo_key)): raise ValueError("You cannot use 'password' AND provide keys!") try: Account(account_name, crea_instance=self) raise AccountExistsException except AccountDoesNotExistsException: pass creator = Account(creator, crea_instance=self) ' Generate new keys from password' from creagraphenebase.account import PasswordKey if password: active_key = PasswordKey(account_name, password, role='active', prefix=self.prefix) owner_key = PasswordKey(account_name, password, role='owner', prefix=self.prefix) posting_key = PasswordKey(account_name, password, role='posting', prefix=self.prefix) memo_key = PasswordKey(account_name, password, role='memo', prefix=self.prefix) active_pubkey = active_key.get_public_key() owner_pubkey = owner_key.get_public_key() posting_pubkey = posting_key.get_public_key() memo_pubkey = memo_key.get_public_key() active_privkey = active_key.get_private_key() posting_privkey = posting_key.get_private_key() owner_privkey = owner_key.get_private_key() memo_privkey = memo_key.get_private_key() try: if (storekeys and (not self.nobroadcast)): if store_owner_key: self.wallet.addPrivateKey(str(owner_privkey)) self.wallet.addPrivateKey(str(active_privkey)) self.wallet.addPrivateKey(str(memo_privkey)) self.wallet.addPrivateKey(str(posting_privkey)) except ValueError as e: log.info(str(e)) elif (owner_key and active_key and memo_key and posting_key): active_pubkey = PublicKey(active_key, prefix=self.prefix) owner_pubkey = PublicKey(owner_key, prefix=self.prefix) posting_pubkey = PublicKey(posting_key, prefix=self.prefix) memo_pubkey = PublicKey(memo_key, prefix=self.prefix) else: raise ValueError('Call incomplete! Provide either a password or public keys!') owner = format(owner_pubkey, self.prefix) active = format(active_pubkey, self.prefix) posting = format(posting_pubkey, self.prefix) memo = format(memo_pubkey, self.prefix) owner_key_authority = [[owner, 1]] active_key_authority = [[active, 1]] posting_key_authority = [[posting, 1]] owner_accounts_authority = [] active_accounts_authority = [] posting_accounts_authority = [] for k in additional_owner_keys: owner_key_authority.append([k, 1]) for k in additional_active_keys: active_key_authority.append([k, 1]) for k in additional_posting_keys: posting_key_authority.append([k, 1]) for k in additional_owner_accounts: addaccount = Account(k, crea_instance=self) owner_accounts_authority.append([addaccount['name'], 1]) for k in additional_active_accounts: addaccount = Account(k, crea_instance=self) active_accounts_authority.append([addaccount['name'], 1]) for k in additional_posting_accounts: addaccount = Account(k, crea_instance=self) posting_accounts_authority.append([addaccount['name'], 1]) props = self.get_chain_properties() if (self.hardfork >= 20): required_fee_crea = Amount(props['account_creation_fee'], crea_instance=self) else: required_fee_crea = (Amount(props['account_creation_fee'], crea_instance=self) * 30) op = {'fee': required_fee_crea, 'creator': creator['name'], 'new_account_name': account_name, 'owner': {'account_auths': owner_accounts_authority, 'key_auths': owner_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'active': {'account_auths': active_accounts_authority, 'key_auths': active_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'posting': {'account_auths': posting_accounts_authority, 'key_auths': posting_key_authority, 'address_auths': [], 'weight_threshold': 1}, 'memo_key': memo, 'json_metadata': (json_meta or {}), 'prefix': self.prefix} op = operations.Account_create(**op) return self.finalizeOp(op, creator, 'active', **kwargs)
def witness_set_properties(self, wif, owner, props, use_condenser_api=True): ' Set witness properties\n\n :param str wif: Private signing key\n :param dict props: Properties\n :param str owner: witness account name\n\n Properties:::\n\n {\n "account_creation_fee": x,\n "account_subsidy_budget": x,\n "account_subsidy_decay": x,\n "maximum_block_size": x,\n "url": x,\n "sbd_exchange_rate": x,\n "sbd_interest_rate": x,\n "new_signing_key": x\n }\n\n ' owner = Account(owner, crea_instance=self) try: PrivateKey(wif, prefix=self.prefix) except Exception as e: raise e props_list = [['key', repr(PrivateKey(wif, prefix=self.prefix).pubkey)]] for k in props: props_list.append([k, props[k]]) op = operations.Witness_set_properties({'owner': owner['name'], 'props': props_list, 'prefix': self.prefix}) tb = TransactionBuilder(use_condenser_api=use_condenser_api, crea_instance=self) tb.appendOps([op]) tb.appendWif(wif) tb.sign() return tb.broadcast()
-335,836,913,302,357,600
Set witness properties :param str wif: Private signing key :param dict props: Properties :param str owner: witness account name Properties::: { "account_creation_fee": x, "account_subsidy_budget": x, "account_subsidy_decay": x, "maximum_block_size": x, "url": x, "sbd_exchange_rate": x, "sbd_interest_rate": x, "new_signing_key": x }
crea/crea.py
witness_set_properties
creativechain/crea-python-lib
python
def witness_set_properties(self, wif, owner, props, use_condenser_api=True): ' Set witness properties\n\n :param str wif: Private signing key\n :param dict props: Properties\n :param str owner: witness account name\n\n Properties:::\n\n {\n "account_creation_fee": x,\n "account_subsidy_budget": x,\n "account_subsidy_decay": x,\n "maximum_block_size": x,\n "url": x,\n "sbd_exchange_rate": x,\n "sbd_interest_rate": x,\n "new_signing_key": x\n }\n\n ' owner = Account(owner, crea_instance=self) try: PrivateKey(wif, prefix=self.prefix) except Exception as e: raise e props_list = [['key', repr(PrivateKey(wif, prefix=self.prefix).pubkey)]] for k in props: props_list.append([k, props[k]]) op = operations.Witness_set_properties({'owner': owner['name'], 'props': props_list, 'prefix': self.prefix}) tb = TransactionBuilder(use_condenser_api=use_condenser_api, crea_instance=self) tb.appendOps([op]) tb.appendWif(wif) tb.sign() return tb.broadcast()
def witness_update(self, signing_key, url, props, account=None, **kwargs): ' Creates/updates a witness\n\n :param str signing_key: Public signing key\n :param str url: URL\n :param dict props: Properties\n :param str account: (optional) witness account name\n\n Properties:::\n\n {\n "account_creation_fee": "3.000 CREA",\n "maximum_block_size": 65536,\n "sbd_interest_rate": 0,\n }\n\n ' if ((not account) and config['default_account']): account = config['default_account'] if (not account): raise ValueError('You need to provide an account') account = Account(account, crea_instance=self) try: PublicKey(signing_key, prefix=self.prefix) except Exception as e: raise e if ('account_creation_fee' in props): props['account_creation_fee'] = Amount(props['account_creation_fee'], crea_instance=self) op = operations.Witness_update(**{'owner': account['name'], 'url': url, 'block_signing_key': signing_key, 'props': props, 'fee': Amount(0, self.crea_symbol, crea_instance=self), 'prefix': self.prefix}) return self.finalizeOp(op, account, 'active', **kwargs)
7,657,583,815,086,333,000
Creates/updates a witness :param str signing_key: Public signing key :param str url: URL :param dict props: Properties :param str account: (optional) witness account name Properties::: { "account_creation_fee": "3.000 CREA", "maximum_block_size": 65536, "sbd_interest_rate": 0, }
crea/crea.py
witness_update
creativechain/crea-python-lib
python
def witness_update(self, signing_key, url, props, account=None, **kwargs): ' Creates/updates a witness\n\n :param str signing_key: Public signing key\n :param str url: URL\n :param dict props: Properties\n :param str account: (optional) witness account name\n\n Properties:::\n\n {\n "account_creation_fee": "3.000 CREA",\n "maximum_block_size": 65536,\n "sbd_interest_rate": 0,\n }\n\n ' if ((not account) and config['default_account']): account = config['default_account'] if (not account): raise ValueError('You need to provide an account') account = Account(account, crea_instance=self) try: PublicKey(signing_key, prefix=self.prefix) except Exception as e: raise e if ('account_creation_fee' in props): props['account_creation_fee'] = Amount(props['account_creation_fee'], crea_instance=self) op = operations.Witness_update(**{'owner': account['name'], 'url': url, 'block_signing_key': signing_key, 'props': props, 'fee': Amount(0, self.crea_symbol, crea_instance=self), 'prefix': self.prefix}) return self.finalizeOp(op, account, 'active', **kwargs)
def _test_weights_treshold(self, authority): ' This method raises an error if the threshold of an authority cannot\n be reached by the weights.\n\n :param dict authority: An authority of an account\n :raises ValueError: if the threshold is set too high\n ' weights = 0 for a in authority['account_auths']: weights += int(a[1]) for a in authority['key_auths']: weights += int(a[1]) if (authority['weight_threshold'] > weights): raise ValueError('Threshold too restrictive!') if (authority['weight_threshold'] == 0): raise ValueError('Cannot have threshold of 0')
3,737,531,144,419,280,400
This method raises an error if the threshold of an authority cannot be reached by the weights. :param dict authority: An authority of an account :raises ValueError: if the threshold is set too high
crea/crea.py
_test_weights_treshold
creativechain/crea-python-lib
python
def _test_weights_treshold(self, authority): ' This method raises an error if the threshold of an authority cannot\n be reached by the weights.\n\n :param dict authority: An authority of an account\n :raises ValueError: if the threshold is set too high\n ' weights = 0 for a in authority['account_auths']: weights += int(a[1]) for a in authority['key_auths']: weights += int(a[1]) if (authority['weight_threshold'] > weights): raise ValueError('Threshold too restrictive!') if (authority['weight_threshold'] == 0): raise ValueError('Cannot have threshold of 0')
def custom_json(self, id, json_data, required_auths=[], required_posting_auths=[], **kwargs): ' Create a custom json operation\n\n :param str id: identifier for the custom json (max length 32 bytes)\n :param json json_data: the json data to put into the custom_json\n operation\n :param list required_auths: (optional) required auths\n :param list required_posting_auths: (optional) posting auths\n\n .. note:: While reqired auths and required_posting_auths are both\n optional, one of the two are needed in order to send the custom\n json.\n\n .. code-block:: python\n\n crea.custom_json("id", "json_data",\n required_posting_auths=[\'account\'])\n\n ' account = None if len(required_auths): account = required_auths[0] elif len(required_posting_auths): account = required_posting_auths[0] else: raise Exception('At least one account needs to be specified') account = Account(account, full=False, crea_instance=self) op = operations.Custom_json(**{'json': json_data, 'required_auths': required_auths, 'required_posting_auths': required_posting_auths, 'id': id, 'prefix': self.prefix}) return self.finalizeOp(op, account, 'posting', **kwargs)
-7,896,908,938,538,909,000
Create a custom json operation :param str id: identifier for the custom json (max length 32 bytes) :param json json_data: the json data to put into the custom_json operation :param list required_auths: (optional) required auths :param list required_posting_auths: (optional) posting auths .. note:: While reqired auths and required_posting_auths are both optional, one of the two are needed in order to send the custom json. .. code-block:: python crea.custom_json("id", "json_data", required_posting_auths=['account'])
crea/crea.py
custom_json
creativechain/crea-python-lib
python
def custom_json(self, id, json_data, required_auths=[], required_posting_auths=[], **kwargs): ' Create a custom json operation\n\n :param str id: identifier for the custom json (max length 32 bytes)\n :param json json_data: the json data to put into the custom_json\n operation\n :param list required_auths: (optional) required auths\n :param list required_posting_auths: (optional) posting auths\n\n .. note:: While reqired auths and required_posting_auths are both\n optional, one of the two are needed in order to send the custom\n json.\n\n .. code-block:: python\n\n crea.custom_json("id", "json_data",\n required_posting_auths=[\'account\'])\n\n ' account = None if len(required_auths): account = required_auths[0] elif len(required_posting_auths): account = required_posting_auths[0] else: raise Exception('At least one account needs to be specified') account = Account(account, full=False, crea_instance=self) op = operations.Custom_json(**{'json': json_data, 'required_auths': required_auths, 'required_posting_auths': required_posting_auths, 'id': id, 'prefix': self.prefix}) return self.finalizeOp(op, account, 'posting', **kwargs)
def post(self, title, body, author=None, permlink=None, reply_identifier=None, json_metadata=None, comment_options=None, community=None, app=None, tags=None, beneficiaries=None, self_vote=False, parse_body=False, **kwargs): " Create a new post.\n If this post is intended as a reply/comment, `reply_identifier` needs\n to be set with the identifier of the parent post/comment (eg.\n `@author/permlink`).\n Optionally you can also set json_metadata, comment_options and upvote\n the newly created post as an author.\n Setting category, tags or community will override the values provided\n in json_metadata and/or comment_options where appropriate.\n\n :param str title: Title of the post\n :param str body: Body of the post/comment\n :param str author: Account are you posting from\n :param str permlink: Manually set the permlink (defaults to None).\n If left empty, it will be derived from title automatically.\n :param str reply_identifier: Identifier of the parent post/comment (only\n if this post is a reply/comment).\n :param json_metadata: JSON meta object that can be attached to\n the post.\n :type json_metadata: str, dict\n :param dict comment_options: JSON options object that can be\n attached to the post.\n\n Example::\n\n comment_options = {\n 'max_accepted_payout': '1000000.000 CBD',\n 'percent_crea_dollars': 10000,\n 'allow_votes': True,\n 'allow_curation_rewards': True,\n 'extensions': [[0, {\n 'beneficiaries': [\n {'account': 'account1', 'weight': 5000},\n {'account': 'account2', 'weight': 5000},\n ]}\n ]]\n }\n\n :param str community: (Optional) Name of the community we are posting\n into. This will also override the community specified in\n `json_metadata`.\n :param str app: (Optional) Name of the app which are used for posting\n when not set, crea/<version> is used\n :param tags: (Optional) A list of tags to go with the\n post. This will also override the tags specified in\n `json_metadata`. The first tag will be used as a 'category'. If\n provided as a string, it should be space separated.\n :type tags: str, list\n :param list beneficiaries: (Optional) A list of beneficiaries\n for posting reward distribution. This argument overrides\n beneficiaries as specified in `comment_options`.\n\n For example, if we would like to split rewards between account1 and\n account2::\n\n beneficiaries = [\n {'account': 'account1', 'weight': 5000},\n {'account': 'account2', 'weight': 5000}\n ]\n\n :param bool self_vote: (Optional) Upvote the post as author, right after\n posting.\n :param bool parse_body: (Optional) When set to True, all mentioned users,\n used links and images are put into users, links and images array inside\n json_metadata. This will override provided links, images and users inside\n json_metadata. Hashtags will added to tags until its length is below five entries.\n\n " json_metadata = (json_metadata or {}) if isinstance(json_metadata, str): json_metadata = json.loads(json_metadata) if community: json_metadata.update({'community': community}) if app: json_metadata.update({'app': app}) elif ('app' not in json_metadata): json_metadata.update({'app': ('crea/%s' % crea_version)}) if ((not author) and config['default_account']): author = config['default_account'] if (not author): raise ValueError('You need to provide an account') account = Account(author, crea_instance=self) if isinstance(tags, str): tags = list(set([_f for _f in re.split('[\\W_]', tags) if _f])) category = None tags = (tags or json_metadata.get('tags', [])) if parse_body: def get_urls(mdstring): return list(set(re.findall('http[s]*://[^\\s"><\\)\\(]+', mdstring))) def get_users(mdstring): users = [] for u in re.findall('(^|[^a-zA-Z0-9_!#$%&*@@\\/]|(^|[^a-zA-Z0-9_+~.-\\/#]))[@@]([a-z][-\\.a-z\\d]+[a-z\\d])', mdstring): users.append(list(u)[(- 1)]) return users def get_hashtags(mdstring): hashtags = [] for t in re.findall('(^|\\s)(#[-a-z\\d]+)', mdstring): hashtags.append(list(t)[(- 1)]) return hashtags users = [] image = [] links = [] for url in get_urls(body): img_exts = ['.jpg', '.png', '.gif', '.svg', '.jpeg'] if (os.path.splitext(url)[1].lower() in img_exts): image.append(url) else: links.append(url) users = get_users(body) hashtags = get_hashtags(body) users = list(set(users).difference(set([author]))) if (len(users) > 0): json_metadata.update({'users': users}) if (len(image) > 0): json_metadata.update({'image': image}) if (len(links) > 0): json_metadata.update({'links': links}) if (len(tags) < 5): for i in range((5 - len(tags))): if (len(hashtags) > i): tags.append(hashtags[i]) if tags: category = tags[0] json_metadata.update({'tags': tags}) if (reply_identifier and category): category = None if reply_identifier: (parent_author, parent_permlink) = resolve_authorperm(reply_identifier) if (not permlink): permlink = derive_permlink(title, parent_permlink) elif category: parent_permlink = derive_permlink(category) parent_author = '' if (not permlink): permlink = derive_permlink(title) else: parent_author = '' parent_permlink = '' if (not permlink): permlink = derive_permlink(title) post_op = operations.Comment(**{'parent_author': parent_author, 'parent_permlink': parent_permlink, 'author': account['name'], 'permlink': permlink, 'title': title, 'body': body, 'json_metadata': json_metadata}) ops = [post_op] if (comment_options or beneficiaries): comment_op = self._build_comment_options_op(account['name'], permlink, comment_options, beneficiaries) ops.append(comment_op) if self_vote: vote_op = operations.Vote(**{'voter': account['name'], 'author': account['name'], 'permlink': permlink, 'weight': CREA_100_PERCENT}) ops.append(vote_op) return self.finalizeOp(ops, account, 'posting', **kwargs)
-7,500,273,544,721,181,000
Create a new post. If this post is intended as a reply/comment, `reply_identifier` needs to be set with the identifier of the parent post/comment (eg. `@author/permlink`). Optionally you can also set json_metadata, comment_options and upvote the newly created post as an author. Setting category, tags or community will override the values provided in json_metadata and/or comment_options where appropriate. :param str title: Title of the post :param str body: Body of the post/comment :param str author: Account are you posting from :param str permlink: Manually set the permlink (defaults to None). If left empty, it will be derived from title automatically. :param str reply_identifier: Identifier of the parent post/comment (only if this post is a reply/comment). :param json_metadata: JSON meta object that can be attached to the post. :type json_metadata: str, dict :param dict comment_options: JSON options object that can be attached to the post. Example:: comment_options = { 'max_accepted_payout': '1000000.000 CBD', 'percent_crea_dollars': 10000, 'allow_votes': True, 'allow_curation_rewards': True, 'extensions': [[0, { 'beneficiaries': [ {'account': 'account1', 'weight': 5000}, {'account': 'account2', 'weight': 5000}, ]} ]] } :param str community: (Optional) Name of the community we are posting into. This will also override the community specified in `json_metadata`. :param str app: (Optional) Name of the app which are used for posting when not set, crea/<version> is used :param tags: (Optional) A list of tags to go with the post. This will also override the tags specified in `json_metadata`. The first tag will be used as a 'category'. If provided as a string, it should be space separated. :type tags: str, list :param list beneficiaries: (Optional) A list of beneficiaries for posting reward distribution. This argument overrides beneficiaries as specified in `comment_options`. For example, if we would like to split rewards between account1 and account2:: beneficiaries = [ {'account': 'account1', 'weight': 5000}, {'account': 'account2', 'weight': 5000} ] :param bool self_vote: (Optional) Upvote the post as author, right after posting. :param bool parse_body: (Optional) When set to True, all mentioned users, used links and images are put into users, links and images array inside json_metadata. This will override provided links, images and users inside json_metadata. Hashtags will added to tags until its length is below five entries.
crea/crea.py
post
creativechain/crea-python-lib
python
def post(self, title, body, author=None, permlink=None, reply_identifier=None, json_metadata=None, comment_options=None, community=None, app=None, tags=None, beneficiaries=None, self_vote=False, parse_body=False, **kwargs): " Create a new post.\n If this post is intended as a reply/comment, `reply_identifier` needs\n to be set with the identifier of the parent post/comment (eg.\n `@author/permlink`).\n Optionally you can also set json_metadata, comment_options and upvote\n the newly created post as an author.\n Setting category, tags or community will override the values provided\n in json_metadata and/or comment_options where appropriate.\n\n :param str title: Title of the post\n :param str body: Body of the post/comment\n :param str author: Account are you posting from\n :param str permlink: Manually set the permlink (defaults to None).\n If left empty, it will be derived from title automatically.\n :param str reply_identifier: Identifier of the parent post/comment (only\n if this post is a reply/comment).\n :param json_metadata: JSON meta object that can be attached to\n the post.\n :type json_metadata: str, dict\n :param dict comment_options: JSON options object that can be\n attached to the post.\n\n Example::\n\n comment_options = {\n 'max_accepted_payout': '1000000.000 CBD',\n 'percent_crea_dollars': 10000,\n 'allow_votes': True,\n 'allow_curation_rewards': True,\n 'extensions': [[0, {\n 'beneficiaries': [\n {'account': 'account1', 'weight': 5000},\n {'account': 'account2', 'weight': 5000},\n ]}\n ]]\n }\n\n :param str community: (Optional) Name of the community we are posting\n into. This will also override the community specified in\n `json_metadata`.\n :param str app: (Optional) Name of the app which are used for posting\n when not set, crea/<version> is used\n :param tags: (Optional) A list of tags to go with the\n post. This will also override the tags specified in\n `json_metadata`. The first tag will be used as a 'category'. If\n provided as a string, it should be space separated.\n :type tags: str, list\n :param list beneficiaries: (Optional) A list of beneficiaries\n for posting reward distribution. This argument overrides\n beneficiaries as specified in `comment_options`.\n\n For example, if we would like to split rewards between account1 and\n account2::\n\n beneficiaries = [\n {'account': 'account1', 'weight': 5000},\n {'account': 'account2', 'weight': 5000}\n ]\n\n :param bool self_vote: (Optional) Upvote the post as author, right after\n posting.\n :param bool parse_body: (Optional) When set to True, all mentioned users,\n used links and images are put into users, links and images array inside\n json_metadata. This will override provided links, images and users inside\n json_metadata. Hashtags will added to tags until its length is below five entries.\n\n " json_metadata = (json_metadata or {}) if isinstance(json_metadata, str): json_metadata = json.loads(json_metadata) if community: json_metadata.update({'community': community}) if app: json_metadata.update({'app': app}) elif ('app' not in json_metadata): json_metadata.update({'app': ('crea/%s' % crea_version)}) if ((not author) and config['default_account']): author = config['default_account'] if (not author): raise ValueError('You need to provide an account') account = Account(author, crea_instance=self) if isinstance(tags, str): tags = list(set([_f for _f in re.split('[\\W_]', tags) if _f])) category = None tags = (tags or json_metadata.get('tags', [])) if parse_body: def get_urls(mdstring): return list(set(re.findall('http[s]*://[^\\s"><\\)\\(]+', mdstring))) def get_users(mdstring): users = [] for u in re.findall('(^|[^a-zA-Z0-9_!#$%&*@@\\/]|(^|[^a-zA-Z0-9_+~.-\\/#]))[@@]([a-z][-\\.a-z\\d]+[a-z\\d])', mdstring): users.append(list(u)[(- 1)]) return users def get_hashtags(mdstring): hashtags = [] for t in re.findall('(^|\\s)(#[-a-z\\d]+)', mdstring): hashtags.append(list(t)[(- 1)]) return hashtags users = [] image = [] links = [] for url in get_urls(body): img_exts = ['.jpg', '.png', '.gif', '.svg', '.jpeg'] if (os.path.splitext(url)[1].lower() in img_exts): image.append(url) else: links.append(url) users = get_users(body) hashtags = get_hashtags(body) users = list(set(users).difference(set([author]))) if (len(users) > 0): json_metadata.update({'users': users}) if (len(image) > 0): json_metadata.update({'image': image}) if (len(links) > 0): json_metadata.update({'links': links}) if (len(tags) < 5): for i in range((5 - len(tags))): if (len(hashtags) > i): tags.append(hashtags[i]) if tags: category = tags[0] json_metadata.update({'tags': tags}) if (reply_identifier and category): category = None if reply_identifier: (parent_author, parent_permlink) = resolve_authorperm(reply_identifier) if (not permlink): permlink = derive_permlink(title, parent_permlink) elif category: parent_permlink = derive_permlink(category) parent_author = if (not permlink): permlink = derive_permlink(title) else: parent_author = parent_permlink = if (not permlink): permlink = derive_permlink(title) post_op = operations.Comment(**{'parent_author': parent_author, 'parent_permlink': parent_permlink, 'author': account['name'], 'permlink': permlink, 'title': title, 'body': body, 'json_metadata': json_metadata}) ops = [post_op] if (comment_options or beneficiaries): comment_op = self._build_comment_options_op(account['name'], permlink, comment_options, beneficiaries) ops.append(comment_op) if self_vote: vote_op = operations.Vote(**{'voter': account['name'], 'author': account['name'], 'permlink': permlink, 'weight': CREA_100_PERCENT}) ops.append(vote_op) return self.finalizeOp(ops, account, 'posting', **kwargs)
def comment_options(self, options, identifier, beneficiaries=[], account=None, **kwargs): ' Set the comment options\n\n :param dict options: The options to define.\n :param str identifier: Post identifier\n :param list beneficiaries: (optional) list of beneficiaries\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n\n For the options, you have these defaults:::\n\n {\n "author": "",\n "permlink": "",\n "max_accepted_payout": "1000000.000 CBD",\n "percent_crea_dollars": 10000,\n "allow_votes": True,\n "allow_curation_rewards": True,\n }\n\n ' if ((not account) and config['default_account']): account = config['default_account'] if (not account): raise ValueError('You need to provide an account') account = Account(account, crea_instance=self) (author, permlink) = resolve_authorperm(identifier) op = self._build_comment_options_op(author, permlink, options, beneficiaries) return self.finalizeOp(op, account, 'posting', **kwargs)
-6,666,822,546,965,145,000
Set the comment options :param dict options: The options to define. :param str identifier: Post identifier :param list beneficiaries: (optional) list of beneficiaries :param str account: (optional) the account to allow access to (defaults to ``default_account``) For the options, you have these defaults::: { "author": "", "permlink": "", "max_accepted_payout": "1000000.000 CBD", "percent_crea_dollars": 10000, "allow_votes": True, "allow_curation_rewards": True, }
crea/crea.py
comment_options
creativechain/crea-python-lib
python
def comment_options(self, options, identifier, beneficiaries=[], account=None, **kwargs): ' Set the comment options\n\n :param dict options: The options to define.\n :param str identifier: Post identifier\n :param list beneficiaries: (optional) list of beneficiaries\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n\n For the options, you have these defaults:::\n\n {\n "author": ,\n "permlink": ,\n "max_accepted_payout": "1000000.000 CBD",\n "percent_crea_dollars": 10000,\n "allow_votes": True,\n "allow_curation_rewards": True,\n }\n\n ' if ((not account) and config['default_account']): account = config['default_account'] if (not account): raise ValueError('You need to provide an account') account = Account(account, crea_instance=self) (author, permlink) = resolve_authorperm(identifier) op = self._build_comment_options_op(author, permlink, options, beneficiaries) return self.finalizeOp(op, account, 'posting', **kwargs)
def get_api_methods(self): 'Returns all supported api methods' return self.rpc.get_methods(api='jsonrpc')
-1,289,893,449,848,988,200
Returns all supported api methods
crea/crea.py
get_api_methods
creativechain/crea-python-lib
python
def get_api_methods(self): return self.rpc.get_methods(api='jsonrpc')
def get_apis(self): 'Returns all enabled apis' api_methods = self.get_api_methods() api_list = [] for a in api_methods: api = a.split('.')[0] if (api not in api_list): api_list.append(api) return api_list
-5,086,419,132,837,562,000
Returns all enabled apis
crea/crea.py
get_apis
creativechain/crea-python-lib
python
def get_apis(self): api_methods = self.get_api_methods() api_list = [] for a in api_methods: api = a.split('.')[0] if (api not in api_list): api_list.append(api) return api_list
def _get_asset_symbol(self, asset_id): ' get the asset symbol from an asset id\n\n :@param int asset_id: 0 -> CBD, 1 -> CREA, 2 -> VESTS\n\n ' for asset in self.chain_params['chain_assets']: if (asset['id'] == asset_id): return asset['symbol'] raise KeyError('asset ID not found in chain assets')
-2,621,830,467,201,586,700
get the asset symbol from an asset id :@param int asset_id: 0 -> CBD, 1 -> CREA, 2 -> VESTS
crea/crea.py
_get_asset_symbol
creativechain/crea-python-lib
python
def _get_asset_symbol(self, asset_id): ' get the asset symbol from an asset id\n\n :@param int asset_id: 0 -> CBD, 1 -> CREA, 2 -> VESTS\n\n ' for asset in self.chain_params['chain_assets']: if (asset['id'] == asset_id): return asset['symbol'] raise KeyError('asset ID not found in chain assets')
@property def sbd_symbol(self): ' get the current chains symbol for CBD (e.g. "TBD" on testnet) ' try: symbol = self._get_asset_symbol(0) except KeyError: symbol = self._get_asset_symbol(1) return symbol
258,778,943,592,325,400
get the current chains symbol for CBD (e.g. "TBD" on testnet)
crea/crea.py
sbd_symbol
creativechain/crea-python-lib
python
@property def sbd_symbol(self): ' ' try: symbol = self._get_asset_symbol(0) except KeyError: symbol = self._get_asset_symbol(1) return symbol
@property def crea_symbol(self): ' get the current chains symbol for CREA (e.g. "TESTS" on testnet) ' return self._get_asset_symbol(1)
7,066,429,717,625,459,000
get the current chains symbol for CREA (e.g. "TESTS" on testnet)
crea/crea.py
crea_symbol
creativechain/crea-python-lib
python
@property def crea_symbol(self): ' ' return self._get_asset_symbol(1)
@property def vests_symbol(self): ' get the current chains symbol for VESTS ' return self._get_asset_symbol(2)
-7,246,487,139,812,229,000
get the current chains symbol for VESTS
crea/crea.py
vests_symbol
creativechain/crea-python-lib
python
@property def vests_symbol(self): ' ' return self._get_asset_symbol(2)
def edge_1_to_2(in_string): 'A Test function for an edge for a Graph' return in_string.splitlines()
-869,047,839,222,694,000
A Test function for an edge for a Graph
Code/DataHandlers/GraphModels.py
edge_1_to_2
aricsanders/pyMez3
python
def edge_1_to_2(in_string): return in_string.splitlines()
def edge_2_to_1(string_list): 'A test function for an edge in a Graph' return string_list_collapse(string_list)
4,905,795,175,625,708,000
A test function for an edge in a Graph
Code/DataHandlers/GraphModels.py
edge_2_to_1
aricsanders/pyMez3
python
def edge_2_to_1(string_list): return string_list_collapse(string_list)
def visit_all_nodes(graph): 'Visit all nodes visits each node on a graph' nodes = graph.node_names for node in nodes: graph.move_to_node(node)
-8,874,546,696,860,967,000
Visit all nodes visits each node on a graph
Code/DataHandlers/GraphModels.py
visit_all_nodes
aricsanders/pyMez3
python
def visit_all_nodes(graph): nodes = graph.node_names for node in nodes: graph.move_to_node(node)
def visit_and_print_all_nodes(graph): 'Visits all the nodes in graph and prints graph.data after each move' nodes = graph.node_names for node in nodes: graph.move_to_node(node) print(graph.data)
5,210,747,465,776,017,000
Visits all the nodes in graph and prints graph.data after each move
Code/DataHandlers/GraphModels.py
visit_and_print_all_nodes
aricsanders/pyMez3
python
def visit_and_print_all_nodes(graph): nodes = graph.node_names for node in nodes: graph.move_to_node(node) print(graph.data)
def to_node_name(node_data): 'Creates a node name given an input object, does a bit of silly type selecting and name rearranging. This matches for 75%\n of the cases. There are a lot of user defined nodes without a clear path to generate a name. For instance the DataTableGraph\n node HpFile, does not save with a .hp extension so it would be auto named TxtFile if was only selected by the path name.\n If it is auto selected it returns StringList because it is of the format ["file_path","schema_path"] ' class_name = node_data.__class__.__name__ node_name = class_name if re.match('list', class_name): node_name = 'List' try: element_class_name = node_data[0].__class__.__name__ node_name = (element_class_name + node_name) except: pass elif re.match('dict', class_name): node_name = 'Dictionary' try: element_class_name = list(node_data.values())[0].__class__.__name__ node_name = (element_class_name + node_name) except: pass elif re.match('str', class_name): node_name = 'String' if os.path.isfile(node_data): node_name = 'File' extension = '' try: if re.search('\\.', node_data): extension = node_data.split('.')[(- 1)] node_name = (extension.title() + node_name) except: pass elif fnmatch.fnmatch(node_data, '*.*'): node_name = 'File' try: if re.search('\\.', node_data): extension = node_data.split('.')[(- 1)] node_name = (extension.title() + node_name) except: pass node_name = node_name.replace('str', 'String').replace('dict', 'Dictionary') return node_name
3,272,076,638,068,714,000
Creates a node name given an input object, does a bit of silly type selecting and name rearranging. This matches for 75% of the cases. There are a lot of user defined nodes without a clear path to generate a name. For instance the DataTableGraph node HpFile, does not save with a .hp extension so it would be auto named TxtFile if was only selected by the path name. If it is auto selected it returns StringList because it is of the format ["file_path","schema_path"]
Code/DataHandlers/GraphModels.py
to_node_name
aricsanders/pyMez3
python
def to_node_name(node_data): 'Creates a node name given an input object, does a bit of silly type selecting and name rearranging. This matches for 75%\n of the cases. There are a lot of user defined nodes without a clear path to generate a name. For instance the DataTableGraph\n node HpFile, does not save with a .hp extension so it would be auto named TxtFile if was only selected by the path name.\n If it is auto selected it returns StringList because it is of the format ["file_path","schema_path"] ' class_name = node_data.__class__.__name__ node_name = class_name if re.match('list', class_name): node_name = 'List' try: element_class_name = node_data[0].__class__.__name__ node_name = (element_class_name + node_name) except: pass elif re.match('dict', class_name): node_name = 'Dictionary' try: element_class_name = list(node_data.values())[0].__class__.__name__ node_name = (element_class_name + node_name) except: pass elif re.match('str', class_name): node_name = 'String' if os.path.isfile(node_data): node_name = 'File' extension = try: if re.search('\\.', node_data): extension = node_data.split('.')[(- 1)] node_name = (extension.title() + node_name) except: pass elif fnmatch.fnmatch(node_data, '*.*'): node_name = 'File' try: if re.search('\\.', node_data): extension = node_data.split('.')[(- 1)] node_name = (extension.title() + node_name) except: pass node_name = node_name.replace('str', 'String').replace('dict', 'Dictionary') return node_name
def TableGraph_to_Links(table_graph, **options): 'Converts a table graph to a set of download links with embedded data in them' defaults = {'base_name': None, 'nodes': ['XmlFile', 'CsvFile', 'ExcelFile', 'OdsFile', 'MatFile', 'HtmlFile', 'JsonFile'], 'extensions': ['xml', 'csv', 'xlsx', 'ods', 'mat', 'html', 'json'], 'mime_types': ['application/xml', 'text/plain', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.oasis.opendocument.spreadsheet', 'application/x-matlab-data', 'text/html', 'application/json']} conversion_options = {} for (key, value) in defaults.items(): conversion_options[key] = value for (key, value) in options.items(): conversion_options[key] = value if (conversion_options['base_name'] is None): base_name = 'test.txt' else: base_name = conversion_options['base_name'] nodes = conversion_options['nodes'] extensions = conversion_options['extensions'] mime_types = conversion_options['mime_types'] out_links = '' for (node_index, node) in enumerate(nodes): table_graph.move_to_node(node) file_path = table_graph.data in_file = open(file_path, 'rb') content_string = in_file.read() link = String_to_DownloadLink(content_string, suggested_name=change_extension(base_name, extensions[node_index]), mime_type=mime_types[node_index], text=extensions[node_index]) if (node_index == (len(nodes) - 1)): out_links = (out_links + link) else: out_links = ((out_links + link) + ' | ') return out_links
7,363,370,345,560,202,000
Converts a table graph to a set of download links with embedded data in them
Code/DataHandlers/GraphModels.py
TableGraph_to_Links
aricsanders/pyMez3
python
def TableGraph_to_Links(table_graph, **options): defaults = {'base_name': None, 'nodes': ['XmlFile', 'CsvFile', 'ExcelFile', 'OdsFile', 'MatFile', 'HtmlFile', 'JsonFile'], 'extensions': ['xml', 'csv', 'xlsx', 'ods', 'mat', 'html', 'json'], 'mime_types': ['application/xml', 'text/plain', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.oasis.opendocument.spreadsheet', 'application/x-matlab-data', 'text/html', 'application/json']} conversion_options = {} for (key, value) in defaults.items(): conversion_options[key] = value for (key, value) in options.items(): conversion_options[key] = value if (conversion_options['base_name'] is None): base_name = 'test.txt' else: base_name = conversion_options['base_name'] nodes = conversion_options['nodes'] extensions = conversion_options['extensions'] mime_types = conversion_options['mime_types'] out_links = for (node_index, node) in enumerate(nodes): table_graph.move_to_node(node) file_path = table_graph.data in_file = open(file_path, 'rb') content_string = in_file.read() link = String_to_DownloadLink(content_string, suggested_name=change_extension(base_name, extensions[node_index]), mime_type=mime_types[node_index], text=extensions[node_index]) if (node_index == (len(nodes) - 1)): out_links = (out_links + link) else: out_links = ((out_links + link) + ' | ') return out_links
def remove_circular_paths(path): 'Removes pieces of the path that just end on the same node' edge_pattern = re.compile('edge_(?P<begin_node>\\w+)_(?P<end_node>\\w+)_(?P<iterator>\\w+)') past_locations = [] for (index, edge) in enumerate(path): match = re.match(edge_pattern, edge) begin_node = match.groupdict()['begin_node'] end_node = match.groupdict()['end_node'] past_locations.append(begin_node) new_path = [] node_index = 0 between_list = [False for item in past_locations] while (node_index < len(past_locations)): node = past_locations[node_index] old_path = new_path new_path = [] number_of_visits = past_locations.count(node) if (number_of_visits > 1): equality_list = [(x == node) for x in past_locations] print('{0} is {1}'.format('equality_list', equality_list)) between = False visit_number = 0 for (index, equality) in enumerate(equality_list): if equality: visit_number += 1 if ((visit_number == 1) or (visit_number == number_of_visits)): between = (not between) between_list[index] = (between or between_list[index]) else: between_list[index] = (between or between_list[index]) else: between_list[index] = (between or between_list[index]) for (index, item) in enumerate(between_list): if (not item): new_path.append(path[index]) node_index += 1 if (new_path in [[]]): new_path = path return new_path
-6,199,381,688,604,721,000
Removes pieces of the path that just end on the same node
Code/DataHandlers/GraphModels.py
remove_circular_paths
aricsanders/pyMez3
python
def remove_circular_paths(path): edge_pattern = re.compile('edge_(?P<begin_node>\\w+)_(?P<end_node>\\w+)_(?P<iterator>\\w+)') past_locations = [] for (index, edge) in enumerate(path): match = re.match(edge_pattern, edge) begin_node = match.groupdict()['begin_node'] end_node = match.groupdict()['end_node'] past_locations.append(begin_node) new_path = [] node_index = 0 between_list = [False for item in past_locations] while (node_index < len(past_locations)): node = past_locations[node_index] old_path = new_path new_path = [] number_of_visits = past_locations.count(node) if (number_of_visits > 1): equality_list = [(x == node) for x in past_locations] print('{0} is {1}'.format('equality_list', equality_list)) between = False visit_number = 0 for (index, equality) in enumerate(equality_list): if equality: visit_number += 1 if ((visit_number == 1) or (visit_number == number_of_visits)): between = (not between) between_list[index] = (between or between_list[index]) else: between_list[index] = (between or between_list[index]) else: between_list[index] = (between or between_list[index]) for (index, item) in enumerate(between_list): if (not item): new_path.append(path[index]) node_index += 1 if (new_path in [[]]): new_path = path return new_path
def __init__(self, **options): 'Initializes the graph. The first 2 nodes and two edges forming a bijection between them are required' defaults = {'graph_name': 'Graph', 'node_names': ['n1', 'n2'], 'node_descriptions': ['A plain string', 'A list of strings with no \\n, created with string.splitlines()'], 'current_node': 'n1', 'state': [1, 0], 'data': 'This is a test string\n it has to have multiple lines \n and many characters 34%6\n^', 'edge_2_to_1': edge_2_to_1, 'edge_1_to_2': edge_1_to_2} self.options = {} for (key, value) in defaults.items(): self.options[key] = value for (key, value) in options.items(): self.options[key] = value self.elements = ['graph_name', 'node_names', 'node_descriptions', 'current_node', 'state', 'data'] for element in self.elements: self.__dict__[element] = self.options[element] self.edges = [] self.edge_matrices = [] self.state_matrix = np.matrix(self.state).T self.display_graph = networkx.DiGraph() self.add_edge(self.node_names[0], self.node_names[1], self.options['edge_1_to_2']) self.add_edge(self.node_names[1], self.node_names[0], self.options['edge_2_to_1']) self.jumps = [] self.external_node_names = [] self.external_node_descriptions = [] self.display_layout = networkx.spring_layout(self.display_graph)
680,835,897,459,036,800
Initializes the graph. The first 2 nodes and two edges forming a bijection between them are required
Code/DataHandlers/GraphModels.py
__init__
aricsanders/pyMez3
python
def __init__(self, **options): defaults = {'graph_name': 'Graph', 'node_names': ['n1', 'n2'], 'node_descriptions': ['A plain string', 'A list of strings with no \\n, created with string.splitlines()'], 'current_node': 'n1', 'state': [1, 0], 'data': 'This is a test string\n it has to have multiple lines \n and many characters 34%6\n^', 'edge_2_to_1': edge_2_to_1, 'edge_1_to_2': edge_1_to_2} self.options = {} for (key, value) in defaults.items(): self.options[key] = value for (key, value) in options.items(): self.options[key] = value self.elements = ['graph_name', 'node_names', 'node_descriptions', 'current_node', 'state', 'data'] for element in self.elements: self.__dict__[element] = self.options[element] self.edges = [] self.edge_matrices = [] self.state_matrix = np.matrix(self.state).T self.display_graph = networkx.DiGraph() self.add_edge(self.node_names[0], self.node_names[1], self.options['edge_1_to_2']) self.add_edge(self.node_names[1], self.node_names[0], self.options['edge_2_to_1']) self.jumps = [] self.external_node_names = [] self.external_node_descriptions = [] self.display_layout = networkx.spring_layout(self.display_graph)
def get_description_dictionary(self): 'returns a dictionary of the form {NodeName:Node Description for all of the current nodes' dictionary = {node_name: self.node_descriptions[index] for (index, node_name) in enumerate(self.node_names)} return dictionary
2,856,175,162,624,585,000
returns a dictionary of the form {NodeName:Node Description for all of the current nodes
Code/DataHandlers/GraphModels.py
get_description_dictionary
aricsanders/pyMez3
python
def get_description_dictionary(self): dictionary = {node_name: self.node_descriptions[index] for (index, node_name) in enumerate(self.node_names)} return dictionary
def set_state(self, node_name, node_data): 'Sets the graph state to be the state specified by node_name, and node_data' try: current_node_state_position = self.node_names.index(node_name) self.current_node = node_name self.data = node_data self.state = [0 for i in range(len(self.node_names))] self.state[current_node_state_position] = 1 self.state_matrix = np.matrix(self.state).T except: print('Could not set the state of graph: {0}'.format(self.graph_name)) raise
-2,547,455,262,427,283,500
Sets the graph state to be the state specified by node_name, and node_data
Code/DataHandlers/GraphModels.py
set_state
aricsanders/pyMez3
python
def set_state(self, node_name, node_data): try: current_node_state_position = self.node_names.index(node_name) self.current_node = node_name self.data = node_data self.state = [0 for i in range(len(self.node_names))] self.state[current_node_state_position] = 1 self.state_matrix = np.matrix(self.state).T except: print('Could not set the state of graph: {0}'.format(self.graph_name)) raise
def add_edge(self, begin_node=None, end_node=None, edge_function=None): "Adds an edge mapping one node to another, required input is begin_node (it's name)\n end_node, and the edge function" edge_match = re.compile('edge_{0}_{1}'.format(begin_node, end_node)) keys = list(self.__dict__.keys()) iterator = 0 for key in keys: if re.match(edge_match, key): iterator += 1 edge_name = 'edge_{0}_{1}_{2:0>3d}'.format(begin_node, end_node, iterator) self.__dict__[edge_name] = edge_function self.edges.append(edge_name) edge_matrix = np.zeros((len(self.state), len(self.state))) begin_position = self.node_names.index(begin_node) end_position = self.node_names.index(end_node) edge_matrix[end_position][begin_position] = 1 edge_matrix = np.matrix(edge_matrix) self.edge_matrices.append(edge_matrix) self.display_graph.add_edge(begin_node, end_node) self.display_layout = networkx.spring_layout(self.display_graph)
-377,289,024,457,575,600
Adds an edge mapping one node to another, required input is begin_node (it's name) end_node, and the edge function
Code/DataHandlers/GraphModels.py
add_edge
aricsanders/pyMez3
python
def add_edge(self, begin_node=None, end_node=None, edge_function=None): "Adds an edge mapping one node to another, required input is begin_node (it's name)\n end_node, and the edge function" edge_match = re.compile('edge_{0}_{1}'.format(begin_node, end_node)) keys = list(self.__dict__.keys()) iterator = 0 for key in keys: if re.match(edge_match, key): iterator += 1 edge_name = 'edge_{0}_{1}_{2:0>3d}'.format(begin_node, end_node, iterator) self.__dict__[edge_name] = edge_function self.edges.append(edge_name) edge_matrix = np.zeros((len(self.state), len(self.state))) begin_position = self.node_names.index(begin_node) end_position = self.node_names.index(end_node) edge_matrix[end_position][begin_position] = 1 edge_matrix = np.matrix(edge_matrix) self.edge_matrices.append(edge_matrix) self.display_graph.add_edge(begin_node, end_node) self.display_layout = networkx.spring_layout(self.display_graph)
def add_jump(self, begin_node=None, end_node=None, jump_function=None): "Adds a jump mapping one internal node to an external node, required input is begin_node (it's name)\n end_node, and the edge function" jump_match = re.compile('jump_{0}_{1}'.format(begin_node, end_node)) keys = list(self.__dict__.keys()) iterator = 0 for key in keys: if re.match(jump_match, key): iterator += 1 jump_name = 'jump_{0}_{1}_{2:0>3d}'.format(begin_node, end_node, iterator) self.__dict__[jump_name] = jump_function self.jumps.append(jump_name) self.display_graph.add_edge(begin_node, end_node) self.display_layout = networkx.spring_layout(self.display_graph)
9,149,446,158,159,192,000
Adds a jump mapping one internal node to an external node, required input is begin_node (it's name) end_node, and the edge function
Code/DataHandlers/GraphModels.py
add_jump
aricsanders/pyMez3
python
def add_jump(self, begin_node=None, end_node=None, jump_function=None): "Adds a jump mapping one internal node to an external node, required input is begin_node (it's name)\n end_node, and the edge function" jump_match = re.compile('jump_{0}_{1}'.format(begin_node, end_node)) keys = list(self.__dict__.keys()) iterator = 0 for key in keys: if re.match(jump_match, key): iterator += 1 jump_name = 'jump_{0}_{1}_{2:0>3d}'.format(begin_node, end_node, iterator) self.__dict__[jump_name] = jump_function self.jumps.append(jump_name) self.display_graph.add_edge(begin_node, end_node) self.display_layout = networkx.spring_layout(self.display_graph)
def move_to(self, path, **options): 'Changes the state of the graph by moving along the path specified' defaults = {'debug': False, 'verbose': False} move_options = {} for (key, value) in defaults.items(): move_options[key] = value for (key, value) in options.items(): move_options[key] = value if move_options['debug']: print(path) for (index, edge) in enumerate(path): edge_pattern = 'edge_(?P<begin_node>\\w+)_(?P<end_node>\\w+)_(?P<iterator>\\w+)' match = re.match(edge_pattern, edge) begin_node = match.groupdict()['begin_node'] end_node = match.groupdict()['end_node'] if move_options['verbose']: print('moving {0} -> {1}'.format(begin_node, end_node)) self.data = self.__dict__[edge](self.data) self.current_node = match.groupdict()['end_node'] self.state = [0 for i in range(len(self.node_names))] position = self.node_names.index(self.current_node) self.state[position] = 1 self.state_matrix = np.matrix(self.state).T
1,822,351,231,675,839,500
Changes the state of the graph by moving along the path specified
Code/DataHandlers/GraphModels.py
move_to
aricsanders/pyMez3
python
def move_to(self, path, **options): defaults = {'debug': False, 'verbose': False} move_options = {} for (key, value) in defaults.items(): move_options[key] = value for (key, value) in options.items(): move_options[key] = value if move_options['debug']: print(path) for (index, edge) in enumerate(path): edge_pattern = 'edge_(?P<begin_node>\\w+)_(?P<end_node>\\w+)_(?P<iterator>\\w+)' match = re.match(edge_pattern, edge) begin_node = match.groupdict()['begin_node'] end_node = match.groupdict()['end_node'] if move_options['verbose']: print('moving {0} -> {1}'.format(begin_node, end_node)) self.data = self.__dict__[edge](self.data) self.current_node = match.groupdict()['end_node'] self.state = [0 for i in range(len(self.node_names))] position = self.node_names.index(self.current_node) self.state[position] = 1 self.state_matrix = np.matrix(self.state).T
def virtual_move_to(self, path): 'virtual_move_to simulates moving but does not change the state of the graph' temp_state = self.state temp_data = self.data temp_current_node = self.current_node temp_node_names = self.node_names for (index, edge) in enumerate(path): edge_pattern = 'edge_(?P<begin_node>\\w+)_(?P<end_node>\\w+)_(?P<iterator>\\w+)' match = re.match(edge_pattern, edge) begin_node = match.groupdict()['begin_node'] end_node = match.groupdict()['end_node'] temp_data = self.__dict__[edge](temp_data) temp_current_node = match.groupdict()['end_node'] temp_state = [0 for i in range(len(temp_node_names))] position = temp_node_names.index(temp_current_node) temp_state[position] = 1
-7,026,627,548,040,439,000
virtual_move_to simulates moving but does not change the state of the graph
Code/DataHandlers/GraphModels.py
virtual_move_to
aricsanders/pyMez3
python
def virtual_move_to(self, path): temp_state = self.state temp_data = self.data temp_current_node = self.current_node temp_node_names = self.node_names for (index, edge) in enumerate(path): edge_pattern = 'edge_(?P<begin_node>\\w+)_(?P<end_node>\\w+)_(?P<iterator>\\w+)' match = re.match(edge_pattern, edge) begin_node = match.groupdict()['begin_node'] end_node = match.groupdict()['end_node'] temp_data = self.__dict__[edge](temp_data) temp_current_node = match.groupdict()['end_node'] temp_state = [0 for i in range(len(temp_node_names))] position = temp_node_names.index(temp_current_node) temp_state[position] = 1
def add_node(self, node_name, edge_into_node_begin, edge_into_node_function, edge_out_node_end, edge_out_node_function, node_description=None): 'Adds a node to the graph. Required input is node_name (a string with no spaces),\n a reference to an entering node,the function mapping the entering node to the new node,\n a reference to an exiting node and the function mapping the\n new node to the exiting node.' self.node_names.append(node_name) self.state.append(0) self.state_matrix = np.matrix(self.state).T for (index, matrix) in enumerate(self.edge_matrices): pad_row = np.zeros((1, len(matrix))) new_matrix = np.concatenate((matrix, pad_row), axis=0) pad_column = np.zeros((1, len(self.node_names))) new_matrix = np.concatenate((new_matrix, pad_column.T), axis=1) self.edge_matrices[index] = new_matrix self.add_edge(begin_node=node_name, end_node=edge_out_node_end, edge_function=edge_out_node_function) self.add_edge(begin_node=edge_into_node_begin, end_node=node_name, edge_function=edge_into_node_function) if node_description: self.node_descriptions.append(node_description) self.display_graph.add_node(node_name) self.display_graph.add_edge(node_name, edge_out_node_end) self.display_graph.add_edge(edge_into_node_begin, node_name) self.display_layout = networkx.spring_layout(self.display_graph)
-7,575,784,914,703,229,000
Adds a node to the graph. Required input is node_name (a string with no spaces), a reference to an entering node,the function mapping the entering node to the new node, a reference to an exiting node and the function mapping the new node to the exiting node.
Code/DataHandlers/GraphModels.py
add_node
aricsanders/pyMez3
python
def add_node(self, node_name, edge_into_node_begin, edge_into_node_function, edge_out_node_end, edge_out_node_function, node_description=None): 'Adds a node to the graph. Required input is node_name (a string with no spaces),\n a reference to an entering node,the function mapping the entering node to the new node,\n a reference to an exiting node and the function mapping the\n new node to the exiting node.' self.node_names.append(node_name) self.state.append(0) self.state_matrix = np.matrix(self.state).T for (index, matrix) in enumerate(self.edge_matrices): pad_row = np.zeros((1, len(matrix))) new_matrix = np.concatenate((matrix, pad_row), axis=0) pad_column = np.zeros((1, len(self.node_names))) new_matrix = np.concatenate((new_matrix, pad_column.T), axis=1) self.edge_matrices[index] = new_matrix self.add_edge(begin_node=node_name, end_node=edge_out_node_end, edge_function=edge_out_node_function) self.add_edge(begin_node=edge_into_node_begin, end_node=node_name, edge_function=edge_into_node_function) if node_description: self.node_descriptions.append(node_description) self.display_graph.add_node(node_name) self.display_graph.add_edge(node_name, edge_out_node_end) self.display_graph.add_edge(edge_into_node_begin, node_name) self.display_layout = networkx.spring_layout(self.display_graph)
def add_external_node(self, external_node_name, jump_into_node_begin, jump_into_node_function, external_node_description=None): 'Adds an external node to the graph. Required input is node_name (a string with no spaces),\n a reference to an entering node,the function mapping the entering node to the new external node' self.external_node_names.append(external_node_name) self.add_jump(begin_node=jump_into_node_begin, end_node=external_node_name, jump_function=jump_into_node_function) if external_node_description: self.external_node_descriptions.append(external_node_description) self.display_graph.add_node(external_node_name) self.display_graph.add_edge(jump_into_node_begin, external_node_name) self.display_layout = networkx.spring_layout(self.display_graph)
9,169,020,437,954,371,000
Adds an external node to the graph. Required input is node_name (a string with no spaces), a reference to an entering node,the function mapping the entering node to the new external node
Code/DataHandlers/GraphModels.py
add_external_node
aricsanders/pyMez3
python
def add_external_node(self, external_node_name, jump_into_node_begin, jump_into_node_function, external_node_description=None): 'Adds an external node to the graph. Required input is node_name (a string with no spaces),\n a reference to an entering node,the function mapping the entering node to the new external node' self.external_node_names.append(external_node_name) self.add_jump(begin_node=jump_into_node_begin, end_node=external_node_name, jump_function=jump_into_node_function) if external_node_description: self.external_node_descriptions.append(external_node_description) self.display_graph.add_node(external_node_name) self.display_graph.add_edge(jump_into_node_begin, external_node_name) self.display_layout = networkx.spring_layout(self.display_graph)
def jump_to_external_node(self, external_node_name, **options): 'Returns the result of the jump, the graph is left in the node that is the begining of the jump' end_node = external_node_name jump_pattern = 'jump_(?P<begin_node>\\w+)_{0}_(?P<iterator>\\w+)'.format(end_node) for jump in self.jumps[:]: jump_match = re.match(jump_pattern, jump, re.IGNORECASE) if jump_match: jump_to_use = jump begin_node = jump_match.groupdict()['begin_node'] self.move_to_node(begin_node) return self.__dict__[jump_to_use](self.data, **options)
-9,191,175,292,956,245,000
Returns the result of the jump, the graph is left in the node that is the begining of the jump
Code/DataHandlers/GraphModels.py
jump_to_external_node
aricsanders/pyMez3
python
def jump_to_external_node(self, external_node_name, **options): end_node = external_node_name jump_pattern = 'jump_(?P<begin_node>\\w+)_{0}_(?P<iterator>\\w+)'.format(end_node) for jump in self.jumps[:]: jump_match = re.match(jump_pattern, jump, re.IGNORECASE) if jump_match: jump_to_use = jump begin_node = jump_match.groupdict()['begin_node'] self.move_to_node(begin_node) return self.__dict__[jump_to_use](self.data, **options)
def path_length(self, path, num_repeats=10): 'Determines the length of a given path, currently the metric is based on the time to move to.' begin_time = datetime.datetime.now() for i in range(num_repeats): self.virtual_move_to(path) end_time = datetime.datetime.now() delta_t = (end_time - begin_time) path_length = (delta_t.total_seconds() / float(num_repeats)) if (path_length == 0.0): print('Warning the path length is less than 1 microsecond,make sure num_repeats is high enough to measure it.') return path_length
-6,202,180,433,333,419,000
Determines the length of a given path, currently the metric is based on the time to move to.
Code/DataHandlers/GraphModels.py
path_length
aricsanders/pyMez3
python
def path_length(self, path, num_repeats=10): begin_time = datetime.datetime.now() for i in range(num_repeats): self.virtual_move_to(path) end_time = datetime.datetime.now() delta_t = (end_time - begin_time) path_length = (delta_t.total_seconds() / float(num_repeats)) if (path_length == 0.0): print('Warning the path length is less than 1 microsecond,make sure num_repeats is high enough to measure it.') return path_length
def is_path_valid(self, path): 'Returns True if the path is valid from the current node position or False otherwise' null_state = [0 for i in range(len(self.node_names))] null_state_matrix = np.matrix(null_state).T new_state = np.matrix(self.state).T for (index, edge) in enumerate(path): edge_position = self.edges.index(edge) move_matrix = self.edge_matrices[edge_position] new_state = (move_matrix * new_state) if (new_state.any() == null_state_matrix.any()): return False return True
5,951,362,793,279,655,000
Returns True if the path is valid from the current node position or False otherwise
Code/DataHandlers/GraphModels.py
is_path_valid
aricsanders/pyMez3
python
def is_path_valid(self, path): null_state = [0 for i in range(len(self.node_names))] null_state_matrix = np.matrix(null_state).T new_state = np.matrix(self.state).T for (index, edge) in enumerate(path): edge_position = self.edges.index(edge) move_matrix = self.edge_matrices[edge_position] new_state = (move_matrix * new_state) if (new_state.any() == null_state_matrix.any()): return False return True
def get_entering_nodes(self, node): 'Returns all nodes that have an edge that enter the specificed node' enter_edge_pattern = re.compile('edge_(?P<begin_node>\\w+)_{0}_(?P<iterator>\\w+)'.format(node)) enter_nodes = [] for (index, edge) in enumerate(self.edges): enter_match = re.match(enter_edge_pattern, edge) if enter_match: enter_node = enter_match.groupdict()['begin_node'] enter_nodes.append(enter_node) return enter_nodes
-7,463,785,023,597,199,000
Returns all nodes that have an edge that enter the specificed node
Code/DataHandlers/GraphModels.py
get_entering_nodes
aricsanders/pyMez3
python
def get_entering_nodes(self, node): enter_edge_pattern = re.compile('edge_(?P<begin_node>\\w+)_{0}_(?P<iterator>\\w+)'.format(node)) enter_nodes = [] for (index, edge) in enumerate(self.edges): enter_match = re.match(enter_edge_pattern, edge) if enter_match: enter_node = enter_match.groupdict()['begin_node'] enter_nodes.append(enter_node) return enter_nodes
def get_entering_edges(self, node): 'Returns all edges that enter the specificed node' enter_edge_pattern = re.compile('edge_(?P<begin_node>\\w+)_{0}_(?P<iterator>\\w+)'.format(node)) enter_edges = [] for (index, edge) in enumerate(self.edges): if re.match(enter_edge_pattern, edge): enter_edges.append(edge) return enter_edges
-624,790,509,428,448,400
Returns all edges that enter the specificed node
Code/DataHandlers/GraphModels.py
get_entering_edges
aricsanders/pyMez3
python
def get_entering_edges(self, node): enter_edge_pattern = re.compile('edge_(?P<begin_node>\\w+)_{0}_(?P<iterator>\\w+)'.format(node)) enter_edges = [] for (index, edge) in enumerate(self.edges): if re.match(enter_edge_pattern, edge): enter_edges.append(edge) return enter_edges
def get_exiting_edges(self, node): 'Returns all edges that exit the specificed node' exit_edge_pattern = re.compile('edge_{0}_(?P<end_node>\\w+)_(?P<iterator>\\w+)'.format(node)) exit_edges = [] for (index, edge) in enumerate(self.edges): if re.match(exit_edge_pattern, edge): exit_edges.append(edge) return exit_edges
5,830,406,898,505,011,000
Returns all edges that exit the specificed node
Code/DataHandlers/GraphModels.py
get_exiting_edges
aricsanders/pyMez3
python
def get_exiting_edges(self, node): exit_edge_pattern = re.compile('edge_{0}_(?P<end_node>\\w+)_(?P<iterator>\\w+)'.format(node)) exit_edges = [] for (index, edge) in enumerate(self.edges): if re.match(exit_edge_pattern, edge): exit_edges.append(edge) return exit_edges
def get_exiting_nodes(self, node): 'Returns all nodes that have an edge leaving the specificed node' exit_edge_pattern = re.compile('edge_{0}_(?P<end_node>\\w+)_(?P<iterator>\\w+)'.format(node)) exit_nodes = [] for (index, edge) in enumerate(self.edges): exit_match = re.match(exit_edge_pattern, edge) if exit_match: exit_node = exit_match.groupdict()['end_node'] exit_nodes.append(exit_node) return exit_nodes
-8,701,546,965,773,499,000
Returns all nodes that have an edge leaving the specificed node
Code/DataHandlers/GraphModels.py
get_exiting_nodes
aricsanders/pyMez3
python
def get_exiting_nodes(self, node): exit_edge_pattern = re.compile('edge_{0}_(?P<end_node>\\w+)_(?P<iterator>\\w+)'.format(node)) exit_nodes = [] for (index, edge) in enumerate(self.edges): exit_match = re.match(exit_edge_pattern, edge) if exit_match: exit_node = exit_match.groupdict()['end_node'] exit_nodes.append(exit_node) return exit_nodes
def get_path(self, first_node, last_node, **options): 'Returns the first path found between first node and last node, uses a breadth first search algorithm' defaults = {'debug': False, 'method': 'BreathFirst'} self.get_path_options = {} for (key, value) in defaults.items(): self.get_path_options[key] = value for (key, value) in options.items(): self.get_path_options[key] = value unvisited_nodes = self.node_names[:] unvisited_nodes.remove(first_node) visited_nodes = [first_node] node_history = [] edge_history = [] path_queue = [] possible_paths = [] queue = [] current_edge = [] queue.append(first_node) path = {first_node: []} while queue: current_node = queue.pop(0) if (path_queue != []): current_edge = path_queue.pop(0) edge_history.append(current_edge) node_history.append(current_node) if self.get_path_options['debug']: print('current_node is {0}'.format(current_node)) print('current_edge is {0}'.format(current_edge)) if (current_node == last_node): if self.get_path_options['debug']: print('Node path was found to be {0}'.format(node_path)) print('path was found to be {0}'.format(edge_path)) print('{0} is {1}'.format('path', path)) return path[last_node][::(- 1)] adjacent_nodes = self.get_exiting_nodes(current_node) adjacent_paths = self.get_exiting_edges(current_node) if self.get_path_options['debug']: print('{0} are {1}'.format('adjacent_nodes', adjacent_nodes)) print('{0} are {1}'.format('adjacent_paths', adjacent_paths)) current_history = edge_history for (node_index, node) in enumerate(adjacent_nodes): if (node not in visited_nodes): queue.append(node) path_queue.append(adjacent_paths[node_index]) visited_nodes.append(node) path[node] = ([adjacent_paths[node_index]] + path[current_node]) path[node] if self.get_path_options['debug']: print('{0} is {1}'.format('path_queue', path_queue))
-9,194,866,650,367,668,000
Returns the first path found between first node and last node, uses a breadth first search algorithm
Code/DataHandlers/GraphModels.py
get_path
aricsanders/pyMez3
python
def get_path(self, first_node, last_node, **options): defaults = {'debug': False, 'method': 'BreathFirst'} self.get_path_options = {} for (key, value) in defaults.items(): self.get_path_options[key] = value for (key, value) in options.items(): self.get_path_options[key] = value unvisited_nodes = self.node_names[:] unvisited_nodes.remove(first_node) visited_nodes = [first_node] node_history = [] edge_history = [] path_queue = [] possible_paths = [] queue = [] current_edge = [] queue.append(first_node) path = {first_node: []} while queue: current_node = queue.pop(0) if (path_queue != []): current_edge = path_queue.pop(0) edge_history.append(current_edge) node_history.append(current_node) if self.get_path_options['debug']: print('current_node is {0}'.format(current_node)) print('current_edge is {0}'.format(current_edge)) if (current_node == last_node): if self.get_path_options['debug']: print('Node path was found to be {0}'.format(node_path)) print('path was found to be {0}'.format(edge_path)) print('{0} is {1}'.format('path', path)) return path[last_node][::(- 1)] adjacent_nodes = self.get_exiting_nodes(current_node) adjacent_paths = self.get_exiting_edges(current_node) if self.get_path_options['debug']: print('{0} are {1}'.format('adjacent_nodes', adjacent_nodes)) print('{0} are {1}'.format('adjacent_paths', adjacent_paths)) current_history = edge_history for (node_index, node) in enumerate(adjacent_nodes): if (node not in visited_nodes): queue.append(node) path_queue.append(adjacent_paths[node_index]) visited_nodes.append(node) path[node] = ([adjacent_paths[node_index]] + path[current_node]) path[node] if self.get_path_options['debug']: print('{0} is {1}'.format('path_queue', path_queue))
def move_to_node(self, node): 'Moves from current_node to the specified node' path = self.get_path(self.current_node, node) self.move_to(path)
2,212,070,975,144,242,000
Moves from current_node to the specified node
Code/DataHandlers/GraphModels.py
move_to_node
aricsanders/pyMez3
python
def move_to_node(self, node): path = self.get_path(self.current_node, node) self.move_to(path)
def check_closed_path(self): 'Checks that data is not changed for the first closed path found. Returns True if data==data after\n moving around the closed path, False otherwise. Starting point is current_node ' temp_data = self.data path = self.get_path(self.current_node, self.current_node) if self.is_path_valid(path): pass else: print('Path is not valid, graph definition is broken') raise out = (temp_data == self.data) out_list = [self.current_node, path, out] print('The assertion that the data remains unchanged,\nfor node {0} following path {1} is {2}'.format(*out_list)) return out
6,040,080,610,919,660,000
Checks that data is not changed for the first closed path found. Returns True if data==data after moving around the closed path, False otherwise. Starting point is current_node
Code/DataHandlers/GraphModels.py
check_closed_path
aricsanders/pyMez3
python
def check_closed_path(self): 'Checks that data is not changed for the first closed path found. Returns True if data==data after\n moving around the closed path, False otherwise. Starting point is current_node ' temp_data = self.data path = self.get_path(self.current_node, self.current_node) if self.is_path_valid(path): pass else: print('Path is not valid, graph definition is broken') raise out = (temp_data == self.data) out_list = [self.current_node, path, out] print('The assertion that the data remains unchanged,\nfor node {0} following path {1} is {2}'.format(*out_list)) return out
def is_graph_isomorphic(self): 'Returns True if all nodes have closed paths that preserve the data, False otherwise' out = True for node in self.node_names: self.move_to_node(node) if (not self.check_closed_path): out = False return out
-5,432,437,518,856,279,000
Returns True if all nodes have closed paths that preserve the data, False otherwise
Code/DataHandlers/GraphModels.py
is_graph_isomorphic
aricsanders/pyMez3
python
def is_graph_isomorphic(self): out = True for node in self.node_names: self.move_to_node(node) if (not self.check_closed_path): out = False return out
def show(self, **options): 'Shows the graph using matplotlib and networkx' defaults = {'descriptions': False, 'edge_descriptions': False, 'save_plot': False, 'path': None, 'active_node': True, 'directory': None, 'specific_descriptor': self.graph_name.replace(' ', '_'), 'general_descriptor': 'plot', 'file_name': None, 'arrows': True, 'node_size': 1000, 'font_size': 10, 'fix_layout': True} show_options = {} for (key, value) in defaults.items(): show_options[key] = value for (key, value) in options.items(): show_options[key] = value if (show_options['directory'] is None): show_options['directory'] = os.getcwd() if show_options['active_node']: node_colors = [] for node in self.display_graph.nodes(): if (node == self.current_node): node_colors.append('b') elif (node in self.node_names): node_colors.append('r') elif (node in self.external_node_names): node_colors.append('g') else: node_colors = (['r' for node in self.node_names] + ['g' for node in self.node_names]) if show_options['descriptions']: node_labels = {node: self.node_descriptions[index] for (index, node) in enumerate(self.node_names)} if self.external_node_names: for (index, node) in enumerate(self.external_node_names): node_labels[node] = self.external_node_descriptions[index] networkx.draw_networkx(self.display_graph, arrows=show_options['arrows'], labels=node_labels, node_color=node_colors, node_size=show_options['node_size'], font_size=show_options['font_size'], pos=self.display_layout) else: networkx.draw_networkx(self.display_graph, arrows=show_options['arrows'], node_color=node_colors, node_size=show_options['node_size'], font_size=show_options['font_size'], pos=self.display_layout) plt.axis('off') plt.suptitle(self.options['graph_name']) if (show_options['file_name'] is None): file_name = auto_name(specific_descriptor=show_options['specific_descriptor'], general_descriptor=show_options['general_descriptor'], directory=show_options['directory'], extension='png', padding=3) else: file_name = show_options['file_name'] if show_options['save_plot']: if show_options['path']: plt.savefig(show_options['path']) else: plt.savefig(os.path.join(show_options['directory'], file_name)) else: plt.show() fig = plt.gcf() return fig
3,518,758,878,185,004,000
Shows the graph using matplotlib and networkx
Code/DataHandlers/GraphModels.py
show
aricsanders/pyMez3
python
def show(self, **options): defaults = {'descriptions': False, 'edge_descriptions': False, 'save_plot': False, 'path': None, 'active_node': True, 'directory': None, 'specific_descriptor': self.graph_name.replace(' ', '_'), 'general_descriptor': 'plot', 'file_name': None, 'arrows': True, 'node_size': 1000, 'font_size': 10, 'fix_layout': True} show_options = {} for (key, value) in defaults.items(): show_options[key] = value for (key, value) in options.items(): show_options[key] = value if (show_options['directory'] is None): show_options['directory'] = os.getcwd() if show_options['active_node']: node_colors = [] for node in self.display_graph.nodes(): if (node == self.current_node): node_colors.append('b') elif (node in self.node_names): node_colors.append('r') elif (node in self.external_node_names): node_colors.append('g') else: node_colors = (['r' for node in self.node_names] + ['g' for node in self.node_names]) if show_options['descriptions']: node_labels = {node: self.node_descriptions[index] for (index, node) in enumerate(self.node_names)} if self.external_node_names: for (index, node) in enumerate(self.external_node_names): node_labels[node] = self.external_node_descriptions[index] networkx.draw_networkx(self.display_graph, arrows=show_options['arrows'], labels=node_labels, node_color=node_colors, node_size=show_options['node_size'], font_size=show_options['font_size'], pos=self.display_layout) else: networkx.draw_networkx(self.display_graph, arrows=show_options['arrows'], node_color=node_colors, node_size=show_options['node_size'], font_size=show_options['font_size'], pos=self.display_layout) plt.axis('off') plt.suptitle(self.options['graph_name']) if (show_options['file_name'] is None): file_name = auto_name(specific_descriptor=show_options['specific_descriptor'], general_descriptor=show_options['general_descriptor'], directory=show_options['directory'], extension='png', padding=3) else: file_name = show_options['file_name'] if show_options['save_plot']: if show_options['path']: plt.savefig(show_options['path']) else: plt.savefig(os.path.join(show_options['directory'], file_name)) else: plt.show() fig = plt.gcf() return fig
def __init__(self, **options): 'Intializes the StringGraph Class by defining nodes and edges' defaults = {'graph_name': 'StringGraph', 'node_names': ['String', 'StringList'], 'node_descriptions': ['A plain string', 'A list of strings with no \\n, created with string.splitlines()'], 'current_node': 'String', 'state': [1, 0], 'data': 'This is a test string\n it has to have multiple lines \n and many characters 34%6\n^', 'edge_2_to_1': edge_2_to_1, 'edge_1_to_2': edge_1_to_2} self.options = {} for (key, value) in defaults.items(): self.options[key] = value for (key, value) in options.items(): self.options[key] = value Graph.__init__(self, **self.options) self.add_node('File', 'String', String_to_File, 'String', File_to_String, node_description='Plain File') self.add_node('CStringIo', 'String', String_to_CStringIo, 'String', CStringIo_to_String, node_description='C File Like Object') self.add_node('StringIo', 'String', String_to_StringIo, 'String', StringIo_to_String, node_description='File Like Object') self.add_edge(begin_node='StringList', end_node='File', edge_function=StringList_to_File)
-2,571,014,828,930,411,500
Intializes the StringGraph Class by defining nodes and edges
Code/DataHandlers/GraphModels.py
__init__
aricsanders/pyMez3
python
def __init__(self, **options): defaults = {'graph_name': 'StringGraph', 'node_names': ['String', 'StringList'], 'node_descriptions': ['A plain string', 'A list of strings with no \\n, created with string.splitlines()'], 'current_node': 'String', 'state': [1, 0], 'data': 'This is a test string\n it has to have multiple lines \n and many characters 34%6\n^', 'edge_2_to_1': edge_2_to_1, 'edge_1_to_2': edge_1_to_2} self.options = {} for (key, value) in defaults.items(): self.options[key] = value for (key, value) in options.items(): self.options[key] = value Graph.__init__(self, **self.options) self.add_node('File', 'String', String_to_File, 'String', File_to_String, node_description='Plain File') self.add_node('CStringIo', 'String', String_to_CStringIo, 'String', CStringIo_to_String, node_description='C File Like Object') self.add_node('StringIo', 'String', String_to_StringIo, 'String', StringIo_to_String, node_description='File Like Object') self.add_edge(begin_node='StringList', end_node='File', edge_function=StringList_to_File)
def __init__(self, **options): 'Intializes the metadata graph class' defaults = {'graph_name': 'Metadata Graph', 'node_names': ['Dictionary', 'JsonString'], 'node_descriptions': ['Python Dictionary', 'Json string'], 'current_node': 'Dictionary', 'state': [1, 0], 'data': {'a': 'First', 'b': 'Second'}, 'edge_2_to_1': JsonString_to_Dictionary, 'edge_1_to_2': Dictionary_to_JsonString} self.options = {} for (key, value) in defaults.items(): self.options[key] = value for (key, value) in options.items(): self.options[key] = value Graph.__init__(self, **self.options) self.add_node('JsonFile', 'JsonString', JsonString_to_JsonFile, 'JsonString', JsonFile_to_JsonString, node_description='JSON File') self.add_node('XmlString', 'Dictionary', Dictionary_to_XmlString, 'Dictionary', XmlString_to_Dictionary, node_description='XML string') self.add_node('HtmlMetaString', 'Dictionary', Dictionary_to_HtmlMetaString, 'Dictionary', HtmlMetaString_to_Dictionary, node_description='HTML meta tags') self.add_node('XmlTupleString', 'Dictionary', Dictionary_to_XmlTupleString, 'Dictionary', XmlTupleString_to_Dictionary, node_description='Tuple Line') self.add_node('PickleFile', 'Dictionary', Dictionary_to_PickleFile, 'Dictionary', PickleFile_to_Dictionary, node_description='Pickled File') self.add_node('ListList', 'Dictionary', Dictionary_to_ListList, 'Dictionary', ListList_to_Dictionary, node_description='List of lists') self.add_node('HeaderList', 'Dictionary', Dictionary_to_HeaderList, 'Dictionary', HeaderList_to_Dictionary, node_description='Header List') self.add_node('DataFrame', 'Dictionary', Dictionary_to_DataFrame, 'Dictionary', DataFrame_to_Dictionary, node_description='Pandas DataFrame') self.add_node('AsciiDataTable', 'DataFrame', DataFrame_to_AsciiDataTable, 'DataFrame', AsciiDataTable_to_DataFrame, node_description='AsciiDataTable') self.add_node('MatFile', 'AsciiDataTable', AsciiTable_to_MatFile, 'AsciiDataTable', MatFile_to_AsciiDataTableKeyValue, node_description='Matlab') self.add_node('ExcelFile', 'DataFrame', DataFrame_to_ExcelFile, 'DataFrame', ExcelFile_to_DataFrame, node_description='excel') self.add_node('HdfFile', 'DataFrame', DataFrame_to_HdfFile, 'DataFrame', HdfFile_to_DataFrame, node_description='hdf file') self.add_node('CsvFile', 'DataFrame', DataFrame_to_CsvFile, 'DataFrame', CsvFile_to_DataFrame, node_description='CSV File') self.add_node('HtmlFile', 'DataFrame', DataFrame_to_HtmlFile, 'DataFrame', HtmlFile_to_DataFrame, node_description='HTML Table File') self.add_node('HtmlTableString', 'HtmlFile', HtmlFile_to_HtmlString, 'HtmlFile', HtmlString_to_HtmlFile, node_description='HTML Table String')
5,817,421,687,380,620,000
Intializes the metadata graph class
Code/DataHandlers/GraphModels.py
__init__
aricsanders/pyMez3
python
def __init__(self, **options): defaults = {'graph_name': 'Metadata Graph', 'node_names': ['Dictionary', 'JsonString'], 'node_descriptions': ['Python Dictionary', 'Json string'], 'current_node': 'Dictionary', 'state': [1, 0], 'data': {'a': 'First', 'b': 'Second'}, 'edge_2_to_1': JsonString_to_Dictionary, 'edge_1_to_2': Dictionary_to_JsonString} self.options = {} for (key, value) in defaults.items(): self.options[key] = value for (key, value) in options.items(): self.options[key] = value Graph.__init__(self, **self.options) self.add_node('JsonFile', 'JsonString', JsonString_to_JsonFile, 'JsonString', JsonFile_to_JsonString, node_description='JSON File') self.add_node('XmlString', 'Dictionary', Dictionary_to_XmlString, 'Dictionary', XmlString_to_Dictionary, node_description='XML string') self.add_node('HtmlMetaString', 'Dictionary', Dictionary_to_HtmlMetaString, 'Dictionary', HtmlMetaString_to_Dictionary, node_description='HTML meta tags') self.add_node('XmlTupleString', 'Dictionary', Dictionary_to_XmlTupleString, 'Dictionary', XmlTupleString_to_Dictionary, node_description='Tuple Line') self.add_node('PickleFile', 'Dictionary', Dictionary_to_PickleFile, 'Dictionary', PickleFile_to_Dictionary, node_description='Pickled File') self.add_node('ListList', 'Dictionary', Dictionary_to_ListList, 'Dictionary', ListList_to_Dictionary, node_description='List of lists') self.add_node('HeaderList', 'Dictionary', Dictionary_to_HeaderList, 'Dictionary', HeaderList_to_Dictionary, node_description='Header List') self.add_node('DataFrame', 'Dictionary', Dictionary_to_DataFrame, 'Dictionary', DataFrame_to_Dictionary, node_description='Pandas DataFrame') self.add_node('AsciiDataTable', 'DataFrame', DataFrame_to_AsciiDataTable, 'DataFrame', AsciiDataTable_to_DataFrame, node_description='AsciiDataTable') self.add_node('MatFile', 'AsciiDataTable', AsciiTable_to_MatFile, 'AsciiDataTable', MatFile_to_AsciiDataTableKeyValue, node_description='Matlab') self.add_node('ExcelFile', 'DataFrame', DataFrame_to_ExcelFile, 'DataFrame', ExcelFile_to_DataFrame, node_description='excel') self.add_node('HdfFile', 'DataFrame', DataFrame_to_HdfFile, 'DataFrame', HdfFile_to_DataFrame, node_description='hdf file') self.add_node('CsvFile', 'DataFrame', DataFrame_to_CsvFile, 'DataFrame', CsvFile_to_DataFrame, node_description='CSV File') self.add_node('HtmlFile', 'DataFrame', DataFrame_to_HtmlFile, 'DataFrame', HtmlFile_to_DataFrame, node_description='HTML Table File') self.add_node('HtmlTableString', 'HtmlFile', HtmlFile_to_HtmlString, 'HtmlFile', HtmlString_to_HtmlFile, node_description='HTML Table String')
def update_setting(self, setting: dict): '\n Update strategy parameter wtih value in setting dict.\n ' for name in self.parameters: if (name in setting): setattr(self, name, setting[name])
6,207,766,873,134,563,000
Update strategy parameter wtih value in setting dict.
vnpy/app/cta_strategy_pro/template.py
update_setting
UtorYeung/vnpy
python
def update_setting(self, setting: dict): '\n \n ' for name in self.parameters: if (name in setting): setattr(self, name, setting[name])
@classmethod def get_class_parameters(cls): '\n Get default parameters dict of strategy class.\n ' class_parameters = {} for name in cls.parameters: class_parameters[name] = getattr(cls, name) return class_parameters
2,000,523,763,530,372,900
Get default parameters dict of strategy class.
vnpy/app/cta_strategy_pro/template.py
get_class_parameters
UtorYeung/vnpy
python
@classmethod def get_class_parameters(cls): '\n \n ' class_parameters = {} for name in cls.parameters: class_parameters[name] = getattr(cls, name) return class_parameters
def get_parameters(self): '\n Get strategy parameters dict.\n ' strategy_parameters = {} for name in self.parameters: strategy_parameters[name] = getattr(self, name) return strategy_parameters
-8,479,214,757,587,884,000
Get strategy parameters dict.
vnpy/app/cta_strategy_pro/template.py
get_parameters
UtorYeung/vnpy
python
def get_parameters(self): '\n \n ' strategy_parameters = {} for name in self.parameters: strategy_parameters[name] = getattr(self, name) return strategy_parameters
def get_variables(self): '\n Get strategy variables dict.\n ' strategy_variables = {} for name in self.variables: strategy_variables[name] = getattr(self, name) return strategy_variables
3,869,490,173,995,033,000
Get strategy variables dict.
vnpy/app/cta_strategy_pro/template.py
get_variables
UtorYeung/vnpy
python
def get_variables(self): '\n \n ' strategy_variables = {} for name in self.variables: strategy_variables[name] = getattr(self, name) return strategy_variables
def get_data(self): '\n Get strategy data.\n ' strategy_data = {'strategy_name': self.strategy_name, 'vt_symbol': self.vt_symbol, 'class_name': self.__class__.__name__, 'author': self.author, 'parameters': self.get_parameters(), 'variables': self.get_variables()} return strategy_data
2,946,753,334,977,945,000
Get strategy data.
vnpy/app/cta_strategy_pro/template.py
get_data
UtorYeung/vnpy
python
def get_data(self): '\n \n ' strategy_data = {'strategy_name': self.strategy_name, 'vt_symbol': self.vt_symbol, 'class_name': self.__class__.__name__, 'author': self.author, 'parameters': self.get_parameters(), 'variables': self.get_variables()} return strategy_data
def get_positions(self): ' 返回持仓数量' pos_list = [] if (self.pos > 0): pos_list.append({'vt_symbol': self.vt_symbol, 'direction': 'long', 'volume': self.pos}) elif (self.pos < 0): pos_list.append({'vt_symbol': self.vt_symbol, 'direction': 'short', 'volume': abs(self.pos)}) return pos_list
-827,901,046,592,274,400
返回持仓数量
vnpy/app/cta_strategy_pro/template.py
get_positions
UtorYeung/vnpy
python
def get_positions(self): ' ' pos_list = [] if (self.pos > 0): pos_list.append({'vt_symbol': self.vt_symbol, 'direction': 'long', 'volume': self.pos}) elif (self.pos < 0): pos_list.append({'vt_symbol': self.vt_symbol, 'direction': 'short', 'volume': abs(self.pos)}) return pos_list
@virtual def on_init(self): '\n Callback when strategy is inited.\n ' pass
-6,602,614,612,649,703,000
Callback when strategy is inited.
vnpy/app/cta_strategy_pro/template.py
on_init
UtorYeung/vnpy
python
@virtual def on_init(self): '\n \n ' pass
@virtual def on_start(self): '\n Callback when strategy is started.\n ' pass
5,431,041,852,391,603,000
Callback when strategy is started.
vnpy/app/cta_strategy_pro/template.py
on_start
UtorYeung/vnpy
python
@virtual def on_start(self): '\n \n ' pass
@virtual def on_stop(self): '\n Callback when strategy is stopped.\n ' pass
807,889,883,735,305,900
Callback when strategy is stopped.
vnpy/app/cta_strategy_pro/template.py
on_stop
UtorYeung/vnpy
python
@virtual def on_stop(self): '\n \n ' pass