body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
37e4241ef5e1d75a83a85214586ef962a86642ef73a001481e9ccd87f49b64c8 | def log_proba_density(self, x, y, alpha):
'\n computes log p(x | y, alpha)\n '
proba_density = self.proba_density(x, y, alpha)
logproba_density = np.log(proba_density)
return logproba_density | computes log p(x | y, alpha) | explore/minitoy_systematics.py | log_proba_density | victor-estrade/SystGradDescent | 2 | python | def log_proba_density(self, x, y, alpha):
'\n \n '
proba_density = self.proba_density(x, y, alpha)
logproba_density = np.log(proba_density)
return logproba_density | def log_proba_density(self, x, y, alpha):
'\n \n '
proba_density = self.proba_density(x, y, alpha)
logproba_density = np.log(proba_density)
return logproba_density<|docstring|>computes log p(x | y, alpha)<|endoftext|> |
bb97881316e0f1acdd2fb4422116bfe5d5e6aa2d3e47cf41f2221ea0b562c888 | def nll(self, data, y, alpha):
'\n Computes the negative log likelihood of teh data given y and alpha.\n '
nll = (- self.log_proba_density(data, y, alpha).sum())
return nll | Computes the negative log likelihood of teh data given y and alpha. | explore/minitoy_systematics.py | nll | victor-estrade/SystGradDescent | 2 | python | def nll(self, data, y, alpha):
'\n \n '
nll = (- self.log_proba_density(data, y, alpha).sum())
return nll | def nll(self, data, y, alpha):
'\n \n '
nll = (- self.log_proba_density(data, y, alpha).sum())
return nll<|docstring|>Computes the negative log likelihood of teh data given y and alpha.<|endoftext|> |
d18383bd704fca330dbaad75f38be9da7a09486c5fdc20bb0e725ac94e4ac9e0 | def listing_all_sleep_duration_analysis(self, user_id: str, all_days: List[str]):
"\n Produce and save the list of sleep duration acoording to day in one stream and marked\n each day's staying_time as Usual_sleep_duration or More_than_usual or Less_than_usual.\n Sleep duration is saved in hour. For each day's sleep duration the deviation from usual\n sleep duration is saved. All measure are in hour\n\n :param str user_id: UUID of the stream owner\n :param List(str) all_days: All days of the user in the format 'YYYYMMDD'\n :return:\n "
self.CC.logging.log(('%s started processing for user_id %s' % (self.__class__.__name__, str(user_id))))
stream_ids = self.get_latest_stream_id(user_id, Sleep_Durations_STREAM)
sleep_duration_data = []
sleep_durations = list()
for stream_id in stream_ids:
for day in all_days:
sleep_duration_stream = self.CC.get_stream(stream_id['identifier'], user_id, day)
for data in sleep_duration_stream.data:
sleep_duration = data.sample
sleep_durations.append(sleep_duration)
sample = []
sample.append(sleep_duration)
temp = DataPoint(data.start_time, data.end_time, data.offset, sample)
sleep_duration_data.append(temp)
if (not len(sleep_durations)):
return
median = np.median(sleep_durations)
mad_sleep_durations = []
for sleep_duration in sleep_durations:
mad_sleep_durations.append(abs((sleep_duration - median)))
median2 = np.median(mad_sleep_durations)
mad_value = (median2 * MEDIAN_ABSOLUTE_DEVIATION_MULTIPLIER)
outlier_border = (mad_value * OUTLIER_DETECTION_MULTIPLIER)
outlier_removed_sleep_durations = []
for sleep_duration in sleep_durations:
if ((sleep_duration > (median - outlier_border)) and (sleep_duration < (median + outlier_border))):
outlier_removed_sleep_durations.append(sleep_duration)
if (not len(outlier_removed_sleep_durations)):
outlier_removed_sleep_durations = sleep_durations
mean = np.mean(outlier_removed_sleep_durations)
standard_deviation = np.std(outlier_removed_sleep_durations)
for data in sleep_duration_data:
sleep_duration = data.sample[0]
if (sleep_duration > (mean + standard_deviation)):
data.sample.append('more_than_usual')
data.sample.append((sleep_duration - (mean + standard_deviation)))
data.sample.append(1)
elif (sleep_duration < (mean - standard_deviation)):
data.sample.append('less_than_usual')
data.sample.append(((mean - standard_deviation) - sleep_duration))
data.sample.append(0)
else:
data.sample.append('usual_sleep_duration')
data.sample.append(0)
data.sample.append(1)
try:
if (len(sleep_duration_data) > 0):
streams = self.CC.get_user_streams(user_id)
if streams:
for (stream_name, stream_metadata) in streams.items():
if (stream_name == Sleep_Durations_STREAM):
self.store_stream(filepath='sleep_duration_analysis.json', input_streams=[stream_metadata], user_id=user_id, data=sleep_duration_data)
break
except Exception as e:
print('Exception:', str(e))
print(traceback.format_exc())
self.CC.logging.log(('%s finished processing for user_id %s saved %d data points' % (self.__class__.__name__, str(user_id), len(sleep_duration_data)))) | Produce and save the list of sleep duration acoording to day in one stream and marked
each day's staying_time as Usual_sleep_duration or More_than_usual or Less_than_usual.
Sleep duration is saved in hour. For each day's sleep duration the deviation from usual
sleep duration is saved. All measure are in hour
:param str user_id: UUID of the stream owner
:param List(str) all_days: All days of the user in the format 'YYYYMMDD'
:return: | core/feature/sleep_duration_analysis/sleep_duration_analysis.py | listing_all_sleep_duration_analysis | Boris69bg/CerebralCortex-DataAnalysis | 1 | python | def listing_all_sleep_duration_analysis(self, user_id: str, all_days: List[str]):
"\n Produce and save the list of sleep duration acoording to day in one stream and marked\n each day's staying_time as Usual_sleep_duration or More_than_usual or Less_than_usual.\n Sleep duration is saved in hour. For each day's sleep duration the deviation from usual\n sleep duration is saved. All measure are in hour\n\n :param str user_id: UUID of the stream owner\n :param List(str) all_days: All days of the user in the format 'YYYYMMDD'\n :return:\n "
self.CC.logging.log(('%s started processing for user_id %s' % (self.__class__.__name__, str(user_id))))
stream_ids = self.get_latest_stream_id(user_id, Sleep_Durations_STREAM)
sleep_duration_data = []
sleep_durations = list()
for stream_id in stream_ids:
for day in all_days:
sleep_duration_stream = self.CC.get_stream(stream_id['identifier'], user_id, day)
for data in sleep_duration_stream.data:
sleep_duration = data.sample
sleep_durations.append(sleep_duration)
sample = []
sample.append(sleep_duration)
temp = DataPoint(data.start_time, data.end_time, data.offset, sample)
sleep_duration_data.append(temp)
if (not len(sleep_durations)):
return
median = np.median(sleep_durations)
mad_sleep_durations = []
for sleep_duration in sleep_durations:
mad_sleep_durations.append(abs((sleep_duration - median)))
median2 = np.median(mad_sleep_durations)
mad_value = (median2 * MEDIAN_ABSOLUTE_DEVIATION_MULTIPLIER)
outlier_border = (mad_value * OUTLIER_DETECTION_MULTIPLIER)
outlier_removed_sleep_durations = []
for sleep_duration in sleep_durations:
if ((sleep_duration > (median - outlier_border)) and (sleep_duration < (median + outlier_border))):
outlier_removed_sleep_durations.append(sleep_duration)
if (not len(outlier_removed_sleep_durations)):
outlier_removed_sleep_durations = sleep_durations
mean = np.mean(outlier_removed_sleep_durations)
standard_deviation = np.std(outlier_removed_sleep_durations)
for data in sleep_duration_data:
sleep_duration = data.sample[0]
if (sleep_duration > (mean + standard_deviation)):
data.sample.append('more_than_usual')
data.sample.append((sleep_duration - (mean + standard_deviation)))
data.sample.append(1)
elif (sleep_duration < (mean - standard_deviation)):
data.sample.append('less_than_usual')
data.sample.append(((mean - standard_deviation) - sleep_duration))
data.sample.append(0)
else:
data.sample.append('usual_sleep_duration')
data.sample.append(0)
data.sample.append(1)
try:
if (len(sleep_duration_data) > 0):
streams = self.CC.get_user_streams(user_id)
if streams:
for (stream_name, stream_metadata) in streams.items():
if (stream_name == Sleep_Durations_STREAM):
self.store_stream(filepath='sleep_duration_analysis.json', input_streams=[stream_metadata], user_id=user_id, data=sleep_duration_data)
break
except Exception as e:
print('Exception:', str(e))
print(traceback.format_exc())
self.CC.logging.log(('%s finished processing for user_id %s saved %d data points' % (self.__class__.__name__, str(user_id), len(sleep_duration_data)))) | def listing_all_sleep_duration_analysis(self, user_id: str, all_days: List[str]):
"\n Produce and save the list of sleep duration acoording to day in one stream and marked\n each day's staying_time as Usual_sleep_duration or More_than_usual or Less_than_usual.\n Sleep duration is saved in hour. For each day's sleep duration the deviation from usual\n sleep duration is saved. All measure are in hour\n\n :param str user_id: UUID of the stream owner\n :param List(str) all_days: All days of the user in the format 'YYYYMMDD'\n :return:\n "
self.CC.logging.log(('%s started processing for user_id %s' % (self.__class__.__name__, str(user_id))))
stream_ids = self.get_latest_stream_id(user_id, Sleep_Durations_STREAM)
sleep_duration_data = []
sleep_durations = list()
for stream_id in stream_ids:
for day in all_days:
sleep_duration_stream = self.CC.get_stream(stream_id['identifier'], user_id, day)
for data in sleep_duration_stream.data:
sleep_duration = data.sample
sleep_durations.append(sleep_duration)
sample = []
sample.append(sleep_duration)
temp = DataPoint(data.start_time, data.end_time, data.offset, sample)
sleep_duration_data.append(temp)
if (not len(sleep_durations)):
return
median = np.median(sleep_durations)
mad_sleep_durations = []
for sleep_duration in sleep_durations:
mad_sleep_durations.append(abs((sleep_duration - median)))
median2 = np.median(mad_sleep_durations)
mad_value = (median2 * MEDIAN_ABSOLUTE_DEVIATION_MULTIPLIER)
outlier_border = (mad_value * OUTLIER_DETECTION_MULTIPLIER)
outlier_removed_sleep_durations = []
for sleep_duration in sleep_durations:
if ((sleep_duration > (median - outlier_border)) and (sleep_duration < (median + outlier_border))):
outlier_removed_sleep_durations.append(sleep_duration)
if (not len(outlier_removed_sleep_durations)):
outlier_removed_sleep_durations = sleep_durations
mean = np.mean(outlier_removed_sleep_durations)
standard_deviation = np.std(outlier_removed_sleep_durations)
for data in sleep_duration_data:
sleep_duration = data.sample[0]
if (sleep_duration > (mean + standard_deviation)):
data.sample.append('more_than_usual')
data.sample.append((sleep_duration - (mean + standard_deviation)))
data.sample.append(1)
elif (sleep_duration < (mean - standard_deviation)):
data.sample.append('less_than_usual')
data.sample.append(((mean - standard_deviation) - sleep_duration))
data.sample.append(0)
else:
data.sample.append('usual_sleep_duration')
data.sample.append(0)
data.sample.append(1)
try:
if (len(sleep_duration_data) > 0):
streams = self.CC.get_user_streams(user_id)
if streams:
for (stream_name, stream_metadata) in streams.items():
if (stream_name == Sleep_Durations_STREAM):
self.store_stream(filepath='sleep_duration_analysis.json', input_streams=[stream_metadata], user_id=user_id, data=sleep_duration_data)
break
except Exception as e:
print('Exception:', str(e))
print(traceback.format_exc())
self.CC.logging.log(('%s finished processing for user_id %s saved %d data points' % (self.__class__.__name__, str(user_id), len(sleep_duration_data))))<|docstring|>Produce and save the list of sleep duration acoording to day in one stream and marked
each day's staying_time as Usual_sleep_duration or More_than_usual or Less_than_usual.
Sleep duration is saved in hour. For each day's sleep duration the deviation from usual
sleep duration is saved. All measure are in hour
:param str user_id: UUID of the stream owner
:param List(str) all_days: All days of the user in the format 'YYYYMMDD'
:return:<|endoftext|> |
c795181e5e9ce9df6946412f3679e28994044da1f2117d6ff3efca1c35e5f825 | def process(self, user_id: str, all_days: List[str]):
"\n Main processing function inherited from ComputerFeatureBase\n\n :param str user_id: UUID of the user\n :param List(str) all_days: List of days with format 'YYYYMMDD'\n :return:\n "
if (self.CC is not None):
self.CC.logging.log('Processing Sleep Duration Analysis')
self.listing_all_sleep_duration_analysis(user_id, all_days) | Main processing function inherited from ComputerFeatureBase
:param str user_id: UUID of the user
:param List(str) all_days: List of days with format 'YYYYMMDD'
:return: | core/feature/sleep_duration_analysis/sleep_duration_analysis.py | process | Boris69bg/CerebralCortex-DataAnalysis | 1 | python | def process(self, user_id: str, all_days: List[str]):
"\n Main processing function inherited from ComputerFeatureBase\n\n :param str user_id: UUID of the user\n :param List(str) all_days: List of days with format 'YYYYMMDD'\n :return:\n "
if (self.CC is not None):
self.CC.logging.log('Processing Sleep Duration Analysis')
self.listing_all_sleep_duration_analysis(user_id, all_days) | def process(self, user_id: str, all_days: List[str]):
"\n Main processing function inherited from ComputerFeatureBase\n\n :param str user_id: UUID of the user\n :param List(str) all_days: List of days with format 'YYYYMMDD'\n :return:\n "
if (self.CC is not None):
self.CC.logging.log('Processing Sleep Duration Analysis')
self.listing_all_sleep_duration_analysis(user_id, all_days)<|docstring|>Main processing function inherited from ComputerFeatureBase
:param str user_id: UUID of the user
:param List(str) all_days: List of days with format 'YYYYMMDD'
:return:<|endoftext|> |
7d456bc4b8dd3be8984d31736176f2b222c95db1123853df185bbc1389324de9 | def score(self, phrases):
'\n `phrases` should be a list of `Datapoint` instances.\n Return value is a `float` with the classification accuracy of the\n input.\n '
pred = self.predict(phrases)
return accuracy_score(preprocessor.getLabels(phrases), pred) | `phrases` should be a list of `Datapoint` instances.
Return value is a `float` with the classification accuracy of the
input. | samr/ensembleClassifier.py | score | EspenAlbert/sentimentAnalysisMovieReviews | 1 | python | def score(self, phrases):
'\n `phrases` should be a list of `Datapoint` instances.\n Return value is a `float` with the classification accuracy of the\n input.\n '
pred = self.predict(phrases)
return accuracy_score(preprocessor.getLabels(phrases), pred) | def score(self, phrases):
'\n `phrases` should be a list of `Datapoint` instances.\n Return value is a `float` with the classification accuracy of the\n input.\n '
pred = self.predict(phrases)
return accuracy_score(preprocessor.getLabels(phrases), pred)<|docstring|>`phrases` should be a list of `Datapoint` instances.
Return value is a `float` with the classification accuracy of the
input.<|endoftext|> |
9ab79e37e365d62ab61faf76b2c68badd58213ec2fb03fb6b90c90eda2676c11 | @staticmethod
def openapi_types():
"\n This must be a class method so a model may have properties that are\n of type self, this ensures that we don't create a cyclic import\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n "
return {'id': (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId,), 'name': (str,), 'description': (str,), 'created_by': (str,), 'created_at': (datetime,), 'modified_by': (str,), 'modified_at': (datetime,), 'account_balance': (int,), 'trial_end_date': (str,), 'coupon_type': (int,), 'coupon_valid_months': (int,), 'percent_off': (int,), 'amount_off': (int,), 'amount_off_currency': (str,), 'used_at': (datetime,), 'expires_at': (datetime,), 'new': (bool,)} | This must be a class method so a model may have properties that are
of type self, this ensures that we don't create a cyclic import
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. | python/onshape_client/oas/models/bt_discount.py | openapi_types | Rocketmakers/onshape-clients | 14 | python | @staticmethod
def openapi_types():
"\n This must be a class method so a model may have properties that are\n of type self, this ensures that we don't create a cyclic import\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n "
return {'id': (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId,), 'name': (str,), 'description': (str,), 'created_by': (str,), 'created_at': (datetime,), 'modified_by': (str,), 'modified_at': (datetime,), 'account_balance': (int,), 'trial_end_date': (str,), 'coupon_type': (int,), 'coupon_valid_months': (int,), 'percent_off': (int,), 'amount_off': (int,), 'amount_off_currency': (str,), 'used_at': (datetime,), 'expires_at': (datetime,), 'new': (bool,)} | @staticmethod
def openapi_types():
"\n This must be a class method so a model may have properties that are\n of type self, this ensures that we don't create a cyclic import\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n "
return {'id': (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId,), 'name': (str,), 'description': (str,), 'created_by': (str,), 'created_at': (datetime,), 'modified_by': (str,), 'modified_at': (datetime,), 'account_balance': (int,), 'trial_end_date': (str,), 'coupon_type': (int,), 'coupon_valid_months': (int,), 'percent_off': (int,), 'amount_off': (int,), 'amount_off_currency': (str,), 'used_at': (datetime,), 'expires_at': (datetime,), 'new': (bool,)}<|docstring|>This must be a class method so a model may have properties that are
of type self, this ensures that we don't create a cyclic import
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.<|endoftext|> |
4602c03ff3c37e6c1623fd862c917b72cf20fd3c98a84c77de760c3c29204009 | def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs):
'bt_discount.BTDiscount - a model defined in OpenAPI\n\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n raised if the wrong type is input.\n Defaults to True\n _path_to_item (tuple/list): This is a list of keys or values to\n drill down to the model in received_data\n when deserializing a response\n _from_server (bool): True if the data is from the server\n False if the data is from the client (default)\n _configuration (Configuration): the instance to use when\n deserializing a file_type parameter.\n If passed, type conversion is attempted\n If omitted no type conversion is done.\n id (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId): [optional] # noqa: E501\n name (str): [optional] # noqa: E501\n description (str): [optional] # noqa: E501\n created_by (str): [optional] # noqa: E501\n created_at (datetime): [optional] # noqa: E501\n modified_by (str): [optional] # noqa: E501\n modified_at (datetime): [optional] # noqa: E501\n account_balance (int): [optional] # noqa: E501\n trial_end_date (str): [optional] # noqa: E501\n coupon_type (int): [optional] # noqa: E501\n coupon_valid_months (int): [optional] # noqa: E501\n percent_off (int): [optional] # noqa: E501\n amount_off (int): [optional] # noqa: E501\n amount_off_currency (str): [optional] # noqa: E501\n used_at (datetime): [optional] # noqa: E501\n expires_at (datetime): [optional] # noqa: E501\n new (bool): [optional] # noqa: E501\n '
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for (var_name, var_value) in six.iteritems(kwargs):
setattr(self, var_name, var_value) | bt_discount.BTDiscount - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
id (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId): [optional] # noqa: E501
name (str): [optional] # noqa: E501
description (str): [optional] # noqa: E501
created_by (str): [optional] # noqa: E501
created_at (datetime): [optional] # noqa: E501
modified_by (str): [optional] # noqa: E501
modified_at (datetime): [optional] # noqa: E501
account_balance (int): [optional] # noqa: E501
trial_end_date (str): [optional] # noqa: E501
coupon_type (int): [optional] # noqa: E501
coupon_valid_months (int): [optional] # noqa: E501
percent_off (int): [optional] # noqa: E501
amount_off (int): [optional] # noqa: E501
amount_off_currency (str): [optional] # noqa: E501
used_at (datetime): [optional] # noqa: E501
expires_at (datetime): [optional] # noqa: E501
new (bool): [optional] # noqa: E501 | python/onshape_client/oas/models/bt_discount.py | __init__ | Rocketmakers/onshape-clients | 14 | python | def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs):
'bt_discount.BTDiscount - a model defined in OpenAPI\n\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n raised if the wrong type is input.\n Defaults to True\n _path_to_item (tuple/list): This is a list of keys or values to\n drill down to the model in received_data\n when deserializing a response\n _from_server (bool): True if the data is from the server\n False if the data is from the client (default)\n _configuration (Configuration): the instance to use when\n deserializing a file_type parameter.\n If passed, type conversion is attempted\n If omitted no type conversion is done.\n id (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId): [optional] # noqa: E501\n name (str): [optional] # noqa: E501\n description (str): [optional] # noqa: E501\n created_by (str): [optional] # noqa: E501\n created_at (datetime): [optional] # noqa: E501\n modified_by (str): [optional] # noqa: E501\n modified_at (datetime): [optional] # noqa: E501\n account_balance (int): [optional] # noqa: E501\n trial_end_date (str): [optional] # noqa: E501\n coupon_type (int): [optional] # noqa: E501\n coupon_valid_months (int): [optional] # noqa: E501\n percent_off (int): [optional] # noqa: E501\n amount_off (int): [optional] # noqa: E501\n amount_off_currency (str): [optional] # noqa: E501\n used_at (datetime): [optional] # noqa: E501\n expires_at (datetime): [optional] # noqa: E501\n new (bool): [optional] # noqa: E501\n '
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for (var_name, var_value) in six.iteritems(kwargs):
setattr(self, var_name, var_value) | def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs):
'bt_discount.BTDiscount - a model defined in OpenAPI\n\n\n Keyword Args:\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n raised if the wrong type is input.\n Defaults to True\n _path_to_item (tuple/list): This is a list of keys or values to\n drill down to the model in received_data\n when deserializing a response\n _from_server (bool): True if the data is from the server\n False if the data is from the client (default)\n _configuration (Configuration): the instance to use when\n deserializing a file_type parameter.\n If passed, type conversion is attempted\n If omitted no type conversion is done.\n id (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId): [optional] # noqa: E501\n name (str): [optional] # noqa: E501\n description (str): [optional] # noqa: E501\n created_by (str): [optional] # noqa: E501\n created_at (datetime): [optional] # noqa: E501\n modified_by (str): [optional] # noqa: E501\n modified_at (datetime): [optional] # noqa: E501\n account_balance (int): [optional] # noqa: E501\n trial_end_date (str): [optional] # noqa: E501\n coupon_type (int): [optional] # noqa: E501\n coupon_valid_months (int): [optional] # noqa: E501\n percent_off (int): [optional] # noqa: E501\n amount_off (int): [optional] # noqa: E501\n amount_off_currency (str): [optional] # noqa: E501\n used_at (datetime): [optional] # noqa: E501\n expires_at (datetime): [optional] # noqa: E501\n new (bool): [optional] # noqa: E501\n '
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for (var_name, var_value) in six.iteritems(kwargs):
setattr(self, var_name, var_value)<|docstring|>bt_discount.BTDiscount - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
id (bt_discount_owner_id_plan_id.BTDiscountOwnerIdPlanId): [optional] # noqa: E501
name (str): [optional] # noqa: E501
description (str): [optional] # noqa: E501
created_by (str): [optional] # noqa: E501
created_at (datetime): [optional] # noqa: E501
modified_by (str): [optional] # noqa: E501
modified_at (datetime): [optional] # noqa: E501
account_balance (int): [optional] # noqa: E501
trial_end_date (str): [optional] # noqa: E501
coupon_type (int): [optional] # noqa: E501
coupon_valid_months (int): [optional] # noqa: E501
percent_off (int): [optional] # noqa: E501
amount_off (int): [optional] # noqa: E501
amount_off_currency (str): [optional] # noqa: E501
used_at (datetime): [optional] # noqa: E501
expires_at (datetime): [optional] # noqa: E501
new (bool): [optional] # noqa: E501<|endoftext|> |
95809c0b7eb4addeb446bd30dcd45c1077039cfce6bce33156f9c015426d6581 | @commands.create('latlng', 'latlong', 'lat lng', 'lat long', category='Search')
@rate_limit()
async def lat_long(message):
'\n Geocode an address and return latitude and longitude.\n\n Example::\n\n /latlng disneyworld\n\n Response::\n\n 28.419185, -81.58211899999999 (Walt Disney World Monorail, Bay Lake, FL 32821, USA)\n\n '
q = message.content.strip()
if (not q):
raise CommandError('Address required')
r = (await http.get('https://maps.googleapis.com/maps/api/geocode/json', params=[('key', api_key()), ('address', q)]))
data = r.json()
if (data['status'] == 'ZERO_RESULTS'):
raise CommandError('Address could not be matched to any location')
elif (data['status'] == 'OK'):
entry = data['results'][0]
return '{}, {} ({})'.format(entry['geometry']['location']['lat'], entry['geometry']['location']['lng'], entry['formatted_address'])
else:
raise CommandError('Google Maps returned an error: {}'.format((data['error_message'] if ('error_message' in data) else data['status']))) | Geocode an address and return latitude and longitude.
Example::
/latlng disneyworld
Response::
28.419185, -81.58211899999999 (Walt Disney World Monorail, Bay Lake, FL 32821, USA) | orchard/google_maps.py | lat_long | sk89q/plumeria | 18 | python | @commands.create('latlng', 'latlong', 'lat lng', 'lat long', category='Search')
@rate_limit()
async def lat_long(message):
'\n Geocode an address and return latitude and longitude.\n\n Example::\n\n /latlng disneyworld\n\n Response::\n\n 28.419185, -81.58211899999999 (Walt Disney World Monorail, Bay Lake, FL 32821, USA)\n\n '
q = message.content.strip()
if (not q):
raise CommandError('Address required')
r = (await http.get('https://maps.googleapis.com/maps/api/geocode/json', params=[('key', api_key()), ('address', q)]))
data = r.json()
if (data['status'] == 'ZERO_RESULTS'):
raise CommandError('Address could not be matched to any location')
elif (data['status'] == 'OK'):
entry = data['results'][0]
return '{}, {} ({})'.format(entry['geometry']['location']['lat'], entry['geometry']['location']['lng'], entry['formatted_address'])
else:
raise CommandError('Google Maps returned an error: {}'.format((data['error_message'] if ('error_message' in data) else data['status']))) | @commands.create('latlng', 'latlong', 'lat lng', 'lat long', category='Search')
@rate_limit()
async def lat_long(message):
'\n Geocode an address and return latitude and longitude.\n\n Example::\n\n /latlng disneyworld\n\n Response::\n\n 28.419185, -81.58211899999999 (Walt Disney World Monorail, Bay Lake, FL 32821, USA)\n\n '
q = message.content.strip()
if (not q):
raise CommandError('Address required')
r = (await http.get('https://maps.googleapis.com/maps/api/geocode/json', params=[('key', api_key()), ('address', q)]))
data = r.json()
if (data['status'] == 'ZERO_RESULTS'):
raise CommandError('Address could not be matched to any location')
elif (data['status'] == 'OK'):
entry = data['results'][0]
return '{}, {} ({})'.format(entry['geometry']['location']['lat'], entry['geometry']['location']['lng'], entry['formatted_address'])
else:
raise CommandError('Google Maps returned an error: {}'.format((data['error_message'] if ('error_message' in data) else data['status'])))<|docstring|>Geocode an address and return latitude and longitude.
Example::
/latlng disneyworld
Response::
28.419185, -81.58211899999999 (Walt Disney World Monorail, Bay Lake, FL 32821, USA)<|endoftext|> |
ea6a288ed587d9adf2af232b0af9721e43884ac234185b26894bb3b56a2f33fa | @commands.create('directions', category='Search')
@rate_limit()
async def directions(message):
'\n Get driving directions between two places using Google Maps.\n Separate origin and destination with the word "to".\n\n Example::\n\n /directions oakland, ca to los angeles, ca\n\n The output can take up a lot of lines. If there are too many lines to fit into\n a Discord message, the entire output will be attached as a text file.\n\n Response::\n\n 372 mi (5 hours 24 mins)\n 1. Head southwest on Broadway toward 14th St (4 mins)\n 2. Turn left onto 5th St (1 min)\n 3. Take the ramp on the left onto I-880 S (10 mins)\n 4. Take exit 31 for I-238 toward Stockton/Fresno/I-580 (1 min)\n 5. Keep left to continue toward I-238 S (1 min)\n 6. Keep left at the fork, follow signs for I-238/I-880/Castro Valley/Stockton Fresno (1 min)\n [...]\n\n '
q = message.content.strip()
if (not q):
raise CommandError('Origin and destination required!')
parts = LOCATION_SPLIT_PATTERN.split(q)
if (len(parts) != 2):
raise CommandError("Origin and destination required! Separate with one mention of the word 'to'.")
(origin, destination) = (parts[0].strip(), parts[1].strip())
if (not len(origin)):
raise CommandError('Empty origin provided')
if (not len(destination)):
raise CommandError('Empty destination provided')
r = (await http.get('https://maps.googleapis.com/maps/api/directions/json', params=[('key', api_key()), ('origin', origin), ('destination', destination)]))
data = r.json()
if (data['status'] == 'NOT_FOUND'):
raise CommandError('Either or both the origin and destination were not found')
elif (data['status'] == 'ZERO_RESULTS'):
raise CommandError('No routes found')
elif (data['status'] == 'OK'):
buffer = io.StringIO()
route = data['routes'][0]
image_url = ('http://maps.googleapis.com/maps/api/staticmap?' + urllib.parse.urlencode({'path': 'weight:2|color:red|enc:{}'.format(route['overview_polyline']['points']), 'sensor': 'false', 'size': '640x350'}))
overview_attachment = (await fetch_image(image_url))
overview_attachment.filename = 'overview.png'
for leg in route['legs']:
buffer.write(':map: {} ({}) <https://maps.google.com/?q={}>\n'.format(leg['distance']['text'], leg['duration']['text'], urllib.parse.quote(q)))
for (i, step) in enumerate(leg['steps']):
buffer.write('{}. {} ({})\n'.format((i + 1), html2text.html2text(step['html_instructions']).replace('\n', ' ').strip(), step['duration']['text']))
return Response(buffer.getvalue().strip(), attachments=[overview_attachment])
else:
raise CommandError('Google Maps returned an error: {}'.format((data['error_message'] if ('error_message' in data) else data['status']))) | Get driving directions between two places using Google Maps.
Separate origin and destination with the word "to".
Example::
/directions oakland, ca to los angeles, ca
The output can take up a lot of lines. If there are too many lines to fit into
a Discord message, the entire output will be attached as a text file.
Response::
372 mi (5 hours 24 mins)
1. Head southwest on Broadway toward 14th St (4 mins)
2. Turn left onto 5th St (1 min)
3. Take the ramp on the left onto I-880 S (10 mins)
4. Take exit 31 for I-238 toward Stockton/Fresno/I-580 (1 min)
5. Keep left to continue toward I-238 S (1 min)
6. Keep left at the fork, follow signs for I-238/I-880/Castro Valley/Stockton Fresno (1 min)
[...] | orchard/google_maps.py | directions | sk89q/plumeria | 18 | python | @commands.create('directions', category='Search')
@rate_limit()
async def directions(message):
'\n Get driving directions between two places using Google Maps.\n Separate origin and destination with the word "to".\n\n Example::\n\n /directions oakland, ca to los angeles, ca\n\n The output can take up a lot of lines. If there are too many lines to fit into\n a Discord message, the entire output will be attached as a text file.\n\n Response::\n\n 372 mi (5 hours 24 mins)\n 1. Head southwest on Broadway toward 14th St (4 mins)\n 2. Turn left onto 5th St (1 min)\n 3. Take the ramp on the left onto I-880 S (10 mins)\n 4. Take exit 31 for I-238 toward Stockton/Fresno/I-580 (1 min)\n 5. Keep left to continue toward I-238 S (1 min)\n 6. Keep left at the fork, follow signs for I-238/I-880/Castro Valley/Stockton Fresno (1 min)\n [...]\n\n '
q = message.content.strip()
if (not q):
raise CommandError('Origin and destination required!')
parts = LOCATION_SPLIT_PATTERN.split(q)
if (len(parts) != 2):
raise CommandError("Origin and destination required! Separate with one mention of the word 'to'.")
(origin, destination) = (parts[0].strip(), parts[1].strip())
if (not len(origin)):
raise CommandError('Empty origin provided')
if (not len(destination)):
raise CommandError('Empty destination provided')
r = (await http.get('https://maps.googleapis.com/maps/api/directions/json', params=[('key', api_key()), ('origin', origin), ('destination', destination)]))
data = r.json()
if (data['status'] == 'NOT_FOUND'):
raise CommandError('Either or both the origin and destination were not found')
elif (data['status'] == 'ZERO_RESULTS'):
raise CommandError('No routes found')
elif (data['status'] == 'OK'):
buffer = io.StringIO()
route = data['routes'][0]
image_url = ('http://maps.googleapis.com/maps/api/staticmap?' + urllib.parse.urlencode({'path': 'weight:2|color:red|enc:{}'.format(route['overview_polyline']['points']), 'sensor': 'false', 'size': '640x350'}))
overview_attachment = (await fetch_image(image_url))
overview_attachment.filename = 'overview.png'
for leg in route['legs']:
buffer.write(':map: {} ({}) <https://maps.google.com/?q={}>\n'.format(leg['distance']['text'], leg['duration']['text'], urllib.parse.quote(q)))
for (i, step) in enumerate(leg['steps']):
buffer.write('{}. {} ({})\n'.format((i + 1), html2text.html2text(step['html_instructions']).replace('\n', ' ').strip(), step['duration']['text']))
return Response(buffer.getvalue().strip(), attachments=[overview_attachment])
else:
raise CommandError('Google Maps returned an error: {}'.format((data['error_message'] if ('error_message' in data) else data['status']))) | @commands.create('directions', category='Search')
@rate_limit()
async def directions(message):
'\n Get driving directions between two places using Google Maps.\n Separate origin and destination with the word "to".\n\n Example::\n\n /directions oakland, ca to los angeles, ca\n\n The output can take up a lot of lines. If there are too many lines to fit into\n a Discord message, the entire output will be attached as a text file.\n\n Response::\n\n 372 mi (5 hours 24 mins)\n 1. Head southwest on Broadway toward 14th St (4 mins)\n 2. Turn left onto 5th St (1 min)\n 3. Take the ramp on the left onto I-880 S (10 mins)\n 4. Take exit 31 for I-238 toward Stockton/Fresno/I-580 (1 min)\n 5. Keep left to continue toward I-238 S (1 min)\n 6. Keep left at the fork, follow signs for I-238/I-880/Castro Valley/Stockton Fresno (1 min)\n [...]\n\n '
q = message.content.strip()
if (not q):
raise CommandError('Origin and destination required!')
parts = LOCATION_SPLIT_PATTERN.split(q)
if (len(parts) != 2):
raise CommandError("Origin and destination required! Separate with one mention of the word 'to'.")
(origin, destination) = (parts[0].strip(), parts[1].strip())
if (not len(origin)):
raise CommandError('Empty origin provided')
if (not len(destination)):
raise CommandError('Empty destination provided')
r = (await http.get('https://maps.googleapis.com/maps/api/directions/json', params=[('key', api_key()), ('origin', origin), ('destination', destination)]))
data = r.json()
if (data['status'] == 'NOT_FOUND'):
raise CommandError('Either or both the origin and destination were not found')
elif (data['status'] == 'ZERO_RESULTS'):
raise CommandError('No routes found')
elif (data['status'] == 'OK'):
buffer = io.StringIO()
route = data['routes'][0]
image_url = ('http://maps.googleapis.com/maps/api/staticmap?' + urllib.parse.urlencode({'path': 'weight:2|color:red|enc:{}'.format(route['overview_polyline']['points']), 'sensor': 'false', 'size': '640x350'}))
overview_attachment = (await fetch_image(image_url))
overview_attachment.filename = 'overview.png'
for leg in route['legs']:
buffer.write(':map: {} ({}) <https://maps.google.com/?q={}>\n'.format(leg['distance']['text'], leg['duration']['text'], urllib.parse.quote(q)))
for (i, step) in enumerate(leg['steps']):
buffer.write('{}. {} ({})\n'.format((i + 1), html2text.html2text(step['html_instructions']).replace('\n', ' ').strip(), step['duration']['text']))
return Response(buffer.getvalue().strip(), attachments=[overview_attachment])
else:
raise CommandError('Google Maps returned an error: {}'.format((data['error_message'] if ('error_message' in data) else data['status'])))<|docstring|>Get driving directions between two places using Google Maps.
Separate origin and destination with the word "to".
Example::
/directions oakland, ca to los angeles, ca
The output can take up a lot of lines. If there are too many lines to fit into
a Discord message, the entire output will be attached as a text file.
Response::
372 mi (5 hours 24 mins)
1. Head southwest on Broadway toward 14th St (4 mins)
2. Turn left onto 5th St (1 min)
3. Take the ramp on the left onto I-880 S (10 mins)
4. Take exit 31 for I-238 toward Stockton/Fresno/I-580 (1 min)
5. Keep left to continue toward I-238 S (1 min)
6. Keep left at the fork, follow signs for I-238/I-880/Castro Valley/Stockton Fresno (1 min)
[...]<|endoftext|> |
ffe076982e31112c94ed3f98149836d514d5df37041fc122c9f35176e86a86e1 | @commands.create('map', category='Search', params=[Text('location')])
@rate_limit()
async def map(message, location):
'\n Get a map from Google Maps of a location.\n\n Example::\n\n /map san francisco\n\n '
return ('https://maps.googleapis.com/maps/api/staticmap?' + urllib.parse.urlencode({'center': location, 'size': '640x350'})) | Get a map from Google Maps of a location.
Example::
/map san francisco | orchard/google_maps.py | map | sk89q/plumeria | 18 | python | @commands.create('map', category='Search', params=[Text('location')])
@rate_limit()
async def map(message, location):
'\n Get a map from Google Maps of a location.\n\n Example::\n\n /map san francisco\n\n '
return ('https://maps.googleapis.com/maps/api/staticmap?' + urllib.parse.urlencode({'center': location, 'size': '640x350'})) | @commands.create('map', category='Search', params=[Text('location')])
@rate_limit()
async def map(message, location):
'\n Get a map from Google Maps of a location.\n\n Example::\n\n /map san francisco\n\n '
return ('https://maps.googleapis.com/maps/api/staticmap?' + urllib.parse.urlencode({'center': location, 'size': '640x350'}))<|docstring|>Get a map from Google Maps of a location.
Example::
/map san francisco<|endoftext|> |
fa0ff5e6c519d621e705fc4acf7d5e5f0f4aadb23e511f9a345f85ba66eb721c | def rep_graph(l_size=7, mid_size=5, r_size=7, reps=42):
'\n Creates a bigger tri-graph by repeating smaller graphs\n and concatenating all of them a set number of times.\n '
trivial_size = max(l_size, mid_size, r_size)
edges1_fin = []
edges2_fin = []
paths1 = []
for i in range(reps):
k = 0
while (((len(paths1) < (trivial_size + 2)) and (k < 100)) and ((len(paths1) < (trivial_size + 1)) and (k < 300))):
k += 1
(edges1, edges2) = neur_trig_edges(l_size, mid_size, r_size, shuffle_p=0.94)
paths1 = min_cover_trigraph(edges1, edges2)
edges1[(:, 0)] += (l_size * i)
edges1[(:, 1)] += (((l_size * reps) + (mid_size * i)) - l_size)
edges2[(:, 0)] += (((l_size * reps) + (mid_size * i)) - l_size)
edges2[(:, 1)] += (((l_size * (reps - 1)) + (mid_size * (reps - 1))) + (r_size * i))
paths1 = []
if (i == 0):
edges1_fin = np.copy(edges1)
edges2_fin = np.copy(edges2)
else:
edges1_fin = np.concatenate((edges1_fin, np.copy(edges1)))
edges2_fin = np.concatenate((edges2_fin, np.copy(edges2)))
return (edges1_fin, edges2_fin) | Creates a bigger tri-graph by repeating smaller graphs
and concatenating all of them a set number of times. | graphing/special_graphs/neural_trigraph/rand_graph.py | rep_graph | chuanluocs/graphing | 0 | python | def rep_graph(l_size=7, mid_size=5, r_size=7, reps=42):
'\n Creates a bigger tri-graph by repeating smaller graphs\n and concatenating all of them a set number of times.\n '
trivial_size = max(l_size, mid_size, r_size)
edges1_fin = []
edges2_fin = []
paths1 = []
for i in range(reps):
k = 0
while (((len(paths1) < (trivial_size + 2)) and (k < 100)) and ((len(paths1) < (trivial_size + 1)) and (k < 300))):
k += 1
(edges1, edges2) = neur_trig_edges(l_size, mid_size, r_size, shuffle_p=0.94)
paths1 = min_cover_trigraph(edges1, edges2)
edges1[(:, 0)] += (l_size * i)
edges1[(:, 1)] += (((l_size * reps) + (mid_size * i)) - l_size)
edges2[(:, 0)] += (((l_size * reps) + (mid_size * i)) - l_size)
edges2[(:, 1)] += (((l_size * (reps - 1)) + (mid_size * (reps - 1))) + (r_size * i))
paths1 = []
if (i == 0):
edges1_fin = np.copy(edges1)
edges2_fin = np.copy(edges2)
else:
edges1_fin = np.concatenate((edges1_fin, np.copy(edges1)))
edges2_fin = np.concatenate((edges2_fin, np.copy(edges2)))
return (edges1_fin, edges2_fin) | def rep_graph(l_size=7, mid_size=5, r_size=7, reps=42):
'\n Creates a bigger tri-graph by repeating smaller graphs\n and concatenating all of them a set number of times.\n '
trivial_size = max(l_size, mid_size, r_size)
edges1_fin = []
edges2_fin = []
paths1 = []
for i in range(reps):
k = 0
while (((len(paths1) < (trivial_size + 2)) and (k < 100)) and ((len(paths1) < (trivial_size + 1)) and (k < 300))):
k += 1
(edges1, edges2) = neur_trig_edges(l_size, mid_size, r_size, shuffle_p=0.94)
paths1 = min_cover_trigraph(edges1, edges2)
edges1[(:, 0)] += (l_size * i)
edges1[(:, 1)] += (((l_size * reps) + (mid_size * i)) - l_size)
edges2[(:, 0)] += (((l_size * reps) + (mid_size * i)) - l_size)
edges2[(:, 1)] += (((l_size * (reps - 1)) + (mid_size * (reps - 1))) + (r_size * i))
paths1 = []
if (i == 0):
edges1_fin = np.copy(edges1)
edges2_fin = np.copy(edges2)
else:
edges1_fin = np.concatenate((edges1_fin, np.copy(edges1)))
edges2_fin = np.concatenate((edges2_fin, np.copy(edges2)))
return (edges1_fin, edges2_fin)<|docstring|>Creates a bigger tri-graph by repeating smaller graphs
and concatenating all of them a set number of times.<|endoftext|> |
712adb3808a13cfd8d8cf877f489e1596944a82ec705985a95f4cf03a395a18e | def test_no_scopes():
'The credential should raise when get_token is called with no scopes'
credential = SharedTokenCacheCredential(_cache=TokenCache())
with pytest.raises(ClientAuthenticationError):
credential.get_token() | The credential should raise when get_token is called with no scopes | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_no_scopes | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_no_scopes():
credential = SharedTokenCacheCredential(_cache=TokenCache())
with pytest.raises(ClientAuthenticationError):
credential.get_token() | def test_no_scopes():
credential = SharedTokenCacheCredential(_cache=TokenCache())
with pytest.raises(ClientAuthenticationError):
credential.get_token()<|docstring|>The credential should raise when get_token is called with no scopes<|endoftext|> |
6b417c4d3fd3d2fc8d5c2c1b13c1a628a7cd508c7e9567c64ba60557520698dc | @pytest.mark.parametrize('authority', ('localhost', 'https://localhost'))
def test_authority(authority):
'the credential should accept an authority, with or without scheme, as an argument or environment variable'
parsed_authority = urlparse(authority)
expected_netloc = (parsed_authority.netloc or authority)
class MockCredential(SharedTokenCacheCredential):
def _get_auth_client(self, authority=None, **kwargs):
actual = urlparse(authority)
assert (actual.scheme == 'https')
assert (actual.netloc == expected_netloc)
transport = Mock(send=Mock(side_effect=Exception("credential shouldn't send a request")))
MockCredential(_cache=TokenCache(), authority=authority, transport=transport)
with patch.dict('os.environ', {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
MockCredential(_cache=TokenCache(), authority=authority, transport=transport) | the credential should accept an authority, with or without scheme, as an argument or environment variable | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_authority | MS-syh2qs/azure-sdk-for-python | 1 | python | @pytest.mark.parametrize('authority', ('localhost', 'https://localhost'))
def test_authority(authority):
parsed_authority = urlparse(authority)
expected_netloc = (parsed_authority.netloc or authority)
class MockCredential(SharedTokenCacheCredential):
def _get_auth_client(self, authority=None, **kwargs):
actual = urlparse(authority)
assert (actual.scheme == 'https')
assert (actual.netloc == expected_netloc)
transport = Mock(send=Mock(side_effect=Exception("credential shouldn't send a request")))
MockCredential(_cache=TokenCache(), authority=authority, transport=transport)
with patch.dict('os.environ', {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
MockCredential(_cache=TokenCache(), authority=authority, transport=transport) | @pytest.mark.parametrize('authority', ('localhost', 'https://localhost'))
def test_authority(authority):
parsed_authority = urlparse(authority)
expected_netloc = (parsed_authority.netloc or authority)
class MockCredential(SharedTokenCacheCredential):
def _get_auth_client(self, authority=None, **kwargs):
actual = urlparse(authority)
assert (actual.scheme == 'https')
assert (actual.netloc == expected_netloc)
transport = Mock(send=Mock(side_effect=Exception("credential shouldn't send a request")))
MockCredential(_cache=TokenCache(), authority=authority, transport=transport)
with patch.dict('os.environ', {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
MockCredential(_cache=TokenCache(), authority=authority, transport=transport)<|docstring|>the credential should accept an authority, with or without scheme, as an argument or environment variable<|endoftext|> |
29455c1de483169924f5d416cc22ae2731544cb5ed68ad4f99cd381645a85399 | def test_empty_cache():
'the credential should raise CredentialUnavailableError when the cache is empty'
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache()).get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), username='not@cache').get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), tenant_id='not-cached').get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), tenant_id='not-cached', username='not@cache').get_token('scope') | the credential should raise CredentialUnavailableError when the cache is empty | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_empty_cache | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_empty_cache():
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache()).get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), username='not@cache').get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), tenant_id='not-cached').get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), tenant_id='not-cached', username='not@cache').get_token('scope') | def test_empty_cache():
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache()).get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), username='not@cache').get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), tenant_id='not-cached').get_token('scope')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
SharedTokenCacheCredential(_cache=TokenCache(), tenant_id='not-cached', username='not@cache').get_token('scope')<|docstring|>the credential should raise CredentialUnavailableError when the cache is empty<|endoftext|> |
54f38bdd85380582741d0ee452ffc076ce561640f86b93563edad1309a3ae4da | def test_no_matching_account_for_username():
"one cached account, username specified, username doesn't match -> credential should raise"
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, username=('not' + upn)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert (('not' + upn) in ex.value.message) | one cached account, username specified, username doesn't match -> credential should raise | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_no_matching_account_for_username | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_no_matching_account_for_username():
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, username=('not' + upn)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert (('not' + upn) in ex.value.message) | def test_no_matching_account_for_username():
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, username=('not' + upn)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert (('not' + upn) in ex.value.message)<|docstring|>one cached account, username specified, username doesn't match -> credential should raise<|endoftext|> |
7aead979bf40ac33c523e0fd192e36edc4ad6299319d9bc3042d9c268c9e13c6 | def test_no_matching_account_for_tenant():
"one cached account, tenant specified, tenant doesn't match -> credential should raise"
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, tenant_id=('not-' + tenant)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert (('not-' + tenant) in ex.value.message) | one cached account, tenant specified, tenant doesn't match -> credential should raise | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_no_matching_account_for_tenant | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_no_matching_account_for_tenant():
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, tenant_id=('not-' + tenant)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert (('not-' + tenant) in ex.value.message) | def test_no_matching_account_for_tenant():
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, tenant_id=('not-' + tenant)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert (('not-' + tenant) in ex.value.message)<|docstring|>one cached account, tenant specified, tenant doesn't match -> credential should raise<|endoftext|> |
0361ca7b2f2262245dda03ca68511641624be55cf79f465f0d01964d1e2ec78b | def test_no_matching_account_for_tenant_and_username():
'one cached account, tenant and username specified, neither match -> credential should raise'
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, tenant_id=('not-' + tenant), username=('not' + upn)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((('not' + upn) in ex.value.message) and (('not-' + tenant) in ex.value.message)) | one cached account, tenant and username specified, neither match -> credential should raise | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_no_matching_account_for_tenant_and_username | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_no_matching_account_for_tenant_and_username():
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, tenant_id=('not-' + tenant), username=('not' + upn)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((('not' + upn) in ex.value.message) and (('not-' + tenant) in ex.value.message)) | def test_no_matching_account_for_tenant_and_username():
upn = 'spam@eggs'
tenant = 'some-guid'
account = get_account_event(username=upn, uid='uid', utid=tenant, refresh_token='refresh-token')
cache = populated_cache(account)
with pytest.raises(CredentialUnavailableError) as ex:
SharedTokenCacheCredential(_cache=cache, tenant_id=('not-' + tenant), username=('not' + upn)).get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((('not' + upn) in ex.value.message) and (('not-' + tenant) in ex.value.message))<|docstring|>one cached account, tenant and username specified, neither match -> credential should raise<|endoftext|> |
8d79dbd2427ad78ae87d8cc456599f9c34876dbc474eeaad61782c69241e3ee2 | def test_no_matching_account_for_tenant_or_username():
'two cached accounts, username and tenant specified, one account matches each -> credential should raise'
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_a = 'tenant-a'
tenant_b = 'tenant-b'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_a, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn_b, uid='uid_b', utid=tenant_b, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(username=upn_a, tenant_id=tenant_b, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((upn_a in ex.value.message) and (tenant_b in ex.value.message))
credential = SharedTokenCacheCredential(username=upn_b, tenant_id=tenant_a, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((upn_b in ex.value.message) and (tenant_a in ex.value.message)) | two cached accounts, username and tenant specified, one account matches each -> credential should raise | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_no_matching_account_for_tenant_or_username | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_no_matching_account_for_tenant_or_username():
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_a = 'tenant-a'
tenant_b = 'tenant-b'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_a, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn_b, uid='uid_b', utid=tenant_b, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(username=upn_a, tenant_id=tenant_b, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((upn_a in ex.value.message) and (tenant_b in ex.value.message))
credential = SharedTokenCacheCredential(username=upn_b, tenant_id=tenant_a, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((upn_b in ex.value.message) and (tenant_a in ex.value.message)) | def test_no_matching_account_for_tenant_or_username():
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_a = 'tenant-a'
tenant_b = 'tenant-b'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_a, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn_b, uid='uid_b', utid=tenant_b, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(username=upn_a, tenant_id=tenant_b, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((upn_a in ex.value.message) and (tenant_b in ex.value.message))
credential = SharedTokenCacheCredential(username=upn_b, tenant_id=tenant_a, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(NO_MATCHING_ACCOUNTS[:NO_MATCHING_ACCOUNTS.index('{')])
assert ((upn_b in ex.value.message) and (tenant_a in ex.value.message))<|docstring|>two cached accounts, username and tenant specified, one account matches each -> credential should raise<|endoftext|> |
9246073fd0c559dac19c166f0dc57a6460406a4e87c0b83c2a1e588681bcceb4 | def test_single_account_matching_username():
'one cached account, username specified, username matches -> credential should auth that account'
upn = 'spam@eggs'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid='utid', username=upn, refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, username=upn)
token = credential.get_token(scope)
assert (token.token == expected_token) | one cached account, username specified, username matches -> credential should auth that account | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_single_account_matching_username | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_single_account_matching_username():
upn = 'spam@eggs'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid='utid', username=upn, refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, username=upn)
token = credential.get_token(scope)
assert (token.token == expected_token) | def test_single_account_matching_username():
upn = 'spam@eggs'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid='utid', username=upn, refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, username=upn)
token = credential.get_token(scope)
assert (token.token == expected_token)<|docstring|>one cached account, username specified, username matches -> credential should auth that account<|endoftext|> |
c1877c9bfef09b746f6a9f42a9db6ff0a6a8522140f3c4d1e9f03aa2b5c3fc5d | def test_single_account_matching_tenant():
'one cached account, tenant specified, tenant matches -> credential should auth that account'
tenant_id = 'tenant-id'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid=tenant_id, username='spam@eggs', refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, tenant_id=tenant_id)
token = credential.get_token(scope)
assert (token.token == expected_token) | one cached account, tenant specified, tenant matches -> credential should auth that account | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_single_account_matching_tenant | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_single_account_matching_tenant():
tenant_id = 'tenant-id'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid=tenant_id, username='spam@eggs', refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, tenant_id=tenant_id)
token = credential.get_token(scope)
assert (token.token == expected_token) | def test_single_account_matching_tenant():
tenant_id = 'tenant-id'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid=tenant_id, username='spam@eggs', refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, tenant_id=tenant_id)
token = credential.get_token(scope)
assert (token.token == expected_token)<|docstring|>one cached account, tenant specified, tenant matches -> credential should auth that account<|endoftext|> |
bc8e0eb3639f05148dc13512359f51e1911dd4a8cf60a93b6a13032ba312705c | def test_single_account_matching_tenant_and_username():
'one cached account, tenant and username specified, both match -> credential should auth that account'
upn = 'spam@eggs'
tenant_id = 'tenant-id'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid=tenant_id, username=upn, refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, tenant_id=tenant_id, username=upn)
token = credential.get_token(scope)
assert (token.token == expected_token) | one cached account, tenant and username specified, both match -> credential should auth that account | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_single_account_matching_tenant_and_username | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_single_account_matching_tenant_and_username():
upn = 'spam@eggs'
tenant_id = 'tenant-id'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid=tenant_id, username=upn, refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, tenant_id=tenant_id, username=upn)
token = credential.get_token(scope)
assert (token.token == expected_token) | def test_single_account_matching_tenant_and_username():
upn = 'spam@eggs'
tenant_id = 'tenant-id'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid=tenant_id, username=upn, refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, tenant_id=tenant_id, username=upn)
token = credential.get_token(scope)
assert (token.token == expected_token)<|docstring|>one cached account, tenant and username specified, both match -> credential should auth that account<|endoftext|> |
43452a48fce7d3b2a9f65a39171a40f7e90dd47ff16434d35f2e1b718c97c592 | def test_single_account():
'one cached account, no username specified -> credential should auth that account'
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid='utid', username='spam@eggs', refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | one cached account, no username specified -> credential should auth that account | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_single_account | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_single_account():
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid='utid', username='spam@eggs', refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | def test_single_account():
refresh_token = 'refresh-token'
scope = 'scope'
account = get_account_event(uid='uid_a', utid='utid', username='spam@eggs', refresh_token=refresh_token)
cache = populated_cache(account)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token)<|docstring|>one cached account, no username specified -> credential should auth that account<|endoftext|> |
1b2396e51bfbcf0460b5818acaee81fe5201c0e14e3c35751f4a9585ba4aee54 | def test_no_refresh_token():
'one cached account, account has no refresh token -> credential should raise'
account = get_account_event(uid='uid_a', utid='utid', username='spam@eggs', refresh_token=None)
cache = populated_cache(account)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
credential.get_token('scope')
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, username='not@cache')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
credential.get_token('scope') | one cached account, account has no refresh token -> credential should raise | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_no_refresh_token | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_no_refresh_token():
account = get_account_event(uid='uid_a', utid='utid', username='spam@eggs', refresh_token=None)
cache = populated_cache(account)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
credential.get_token('scope')
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, username='not@cache')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
credential.get_token('scope') | def test_no_refresh_token():
account = get_account_event(uid='uid_a', utid='utid', username='spam@eggs', refresh_token=None)
cache = populated_cache(account)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
credential.get_token('scope')
credential = SharedTokenCacheCredential(_cache=cache, transport=transport, username='not@cache')
with pytest.raises(CredentialUnavailableError, match=NO_ACCOUNTS):
credential.get_token('scope')<|docstring|>one cached account, account has no refresh token -> credential should raise<|endoftext|> |
cd000279dbf928266e378fb7d8f0b6a221a201e7b201c0593353fa0eb58fa309 | def test_two_accounts_no_username_or_tenant():
'two cached accounts, no username or tenant specified -> credential should raise'
upn_a = 'a@foo'
upn_b = 'b@foo'
account_a = get_account_event(username=upn_a, uid='uid_a', utid='utid')
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid')
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
with pytest.raises(ClientAuthenticationError, match=MULTIPLE_ACCOUNTS) as ex:
credential.get_token('scope') | two cached accounts, no username or tenant specified -> credential should raise | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_two_accounts_no_username_or_tenant | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_two_accounts_no_username_or_tenant():
upn_a = 'a@foo'
upn_b = 'b@foo'
account_a = get_account_event(username=upn_a, uid='uid_a', utid='utid')
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid')
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
with pytest.raises(ClientAuthenticationError, match=MULTIPLE_ACCOUNTS) as ex:
credential.get_token('scope') | def test_two_accounts_no_username_or_tenant():
upn_a = 'a@foo'
upn_b = 'b@foo'
account_a = get_account_event(username=upn_a, uid='uid_a', utid='utid')
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid')
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(_cache=cache, transport=transport)
with pytest.raises(ClientAuthenticationError, match=MULTIPLE_ACCOUNTS) as ex:
credential.get_token('scope')<|docstring|>two cached accounts, no username or tenant specified -> credential should raise<|endoftext|> |
8b0b8d1d33a11aa8b3e8a7c3f506dffde60487eb77878ae414779bf3878baaa9 | def test_two_accounts_username_specified():
'two cached accounts, username specified, one account matches -> credential should auth that account'
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
account_a = get_account_event(username=upn_a, uid='uid_a', utid='utid', refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | two cached accounts, username specified, one account matches -> credential should auth that account | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_two_accounts_username_specified | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_two_accounts_username_specified():
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
account_a = get_account_event(username=upn_a, uid='uid_a', utid='utid', refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | def test_two_accounts_username_specified():
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
account_a = get_account_event(username=upn_a, uid='uid_a', utid='utid', refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token)<|docstring|>two cached accounts, username specified, one account matches -> credential should auth that account<|endoftext|> |
f14ed8a5fc4671b60e541d4b9f7f72c0db9fcfd41d2f9915c8764fb84c018427 | def test_two_accounts_tenant_specified():
'two cached accounts, tenant specified, one account matches -> credential should auth that account'
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_id = 'tenant-id'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_id, refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(tenant_id=tenant_id, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | two cached accounts, tenant specified, one account matches -> credential should auth that account | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_two_accounts_tenant_specified | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_two_accounts_tenant_specified():
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_id = 'tenant-id'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_id, refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(tenant_id=tenant_id, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | def test_two_accounts_tenant_specified():
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_id = 'tenant-id'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_id, refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(tenant_id=tenant_id, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token)<|docstring|>two cached accounts, tenant specified, one account matches -> credential should auth that account<|endoftext|> |
87ba8087a3f62eb266b409bed1787372f03262e79a62bfc4a17beff3bc1f86f6 | def test_two_accounts_tenant_and_username_specified():
'two cached accounts, tenant and username specified, one account matches both -> credential should auth that account'
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_id = 'tenant-id'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_id, refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(tenant_id=tenant_id, username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | two cached accounts, tenant and username specified, one account matches both -> credential should auth that account | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_two_accounts_tenant_and_username_specified | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_two_accounts_tenant_and_username_specified():
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_id = 'tenant-id'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_id, refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(tenant_id=tenant_id, username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token) | def test_two_accounts_tenant_and_username_specified():
scope = 'scope'
expected_refresh_token = 'refresh-token-a'
upn_a = 'a@foo'
upn_b = 'b@foo'
tenant_id = 'tenant-id'
account_a = get_account_event(username=upn_a, uid='uid_a', utid=tenant_id, refresh_token=expected_refresh_token)
account_b = get_account_event(username=upn_b, uid='uid_b', utid='utid', refresh_token='refresh_token_b')
cache = populated_cache(account_a, account_b)
expected_token = '***'
transport = validating_transport(requests=[Request(required_data={'refresh_token': expected_refresh_token, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_token))])
credential = SharedTokenCacheCredential(tenant_id=tenant_id, username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == expected_token)<|docstring|>two cached accounts, tenant and username specified, one account matches both -> credential should auth that account<|endoftext|> |
e6eac1909052fbbfa251d8da7b57af24e1a78c9ccf2e828dc8207a448f12f464 | def test_same_username_different_tenants():
'two cached accounts, same username, different tenants'
access_token_a = 'access-token-a'
access_token_b = 'access-token-b'
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn = 'spam@eggs'
tenant_a = 'tenant-a'
tenant_b = 'tenant-b'
account_a = get_account_event(username=upn, uid='another-guid', utid=tenant_a, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn, uid='more-guid', utid=tenant_b, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(username=upn, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(MULTIPLE_MATCHING_ACCOUNTS[:MULTIPLE_MATCHING_ACCOUNTS.index('{')])
assert (upn in ex.value.message)
scope = 'scope'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_a, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(tenant_id=tenant_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a)
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_b, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_b))])
credential = SharedTokenCacheCredential(tenant_id=tenant_b, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_b) | two cached accounts, same username, different tenants | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_same_username_different_tenants | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_same_username_different_tenants():
access_token_a = 'access-token-a'
access_token_b = 'access-token-b'
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn = 'spam@eggs'
tenant_a = 'tenant-a'
tenant_b = 'tenant-b'
account_a = get_account_event(username=upn, uid='another-guid', utid=tenant_a, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn, uid='more-guid', utid=tenant_b, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(username=upn, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(MULTIPLE_MATCHING_ACCOUNTS[:MULTIPLE_MATCHING_ACCOUNTS.index('{')])
assert (upn in ex.value.message)
scope = 'scope'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_a, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(tenant_id=tenant_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a)
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_b, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_b))])
credential = SharedTokenCacheCredential(tenant_id=tenant_b, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_b) | def test_same_username_different_tenants():
access_token_a = 'access-token-a'
access_token_b = 'access-token-b'
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn = 'spam@eggs'
tenant_a = 'tenant-a'
tenant_b = 'tenant-b'
account_a = get_account_event(username=upn, uid='another-guid', utid=tenant_a, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn, uid='more-guid', utid=tenant_b, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(username=upn, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(MULTIPLE_MATCHING_ACCOUNTS[:MULTIPLE_MATCHING_ACCOUNTS.index('{')])
assert (upn in ex.value.message)
scope = 'scope'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_a, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(tenant_id=tenant_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a)
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_b, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_b))])
credential = SharedTokenCacheCredential(tenant_id=tenant_b, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_b)<|docstring|>two cached accounts, same username, different tenants<|endoftext|> |
6b51484484d693fb0c228f1cd4e040ba110e0a713ea6a4f531ef9671745ce2eb | def test_same_tenant_different_usernames():
'two cached accounts, same tenant, different usernames'
access_token_a = 'access-token-a'
access_token_b = 'access-token-b'
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn_a = 'spam@eggs'
upn_b = 'eggs@spam'
tenant_id = 'the-tenant'
account_a = get_account_event(username=upn_a, uid='another-guid', utid=tenant_id, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn_b, uid='more-guid', utid=tenant_id, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(tenant_id=tenant_id, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(MULTIPLE_MATCHING_ACCOUNTS[:MULTIPLE_MATCHING_ACCOUNTS.index('{')])
assert (tenant_id in ex.value.message)
scope = 'scope'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_b, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(username=upn_b, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a)
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_a, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a) | two cached accounts, same tenant, different usernames | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_same_tenant_different_usernames | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_same_tenant_different_usernames():
access_token_a = 'access-token-a'
access_token_b = 'access-token-b'
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn_a = 'spam@eggs'
upn_b = 'eggs@spam'
tenant_id = 'the-tenant'
account_a = get_account_event(username=upn_a, uid='another-guid', utid=tenant_id, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn_b, uid='more-guid', utid=tenant_id, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(tenant_id=tenant_id, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(MULTIPLE_MATCHING_ACCOUNTS[:MULTIPLE_MATCHING_ACCOUNTS.index('{')])
assert (tenant_id in ex.value.message)
scope = 'scope'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_b, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(username=upn_b, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a)
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_a, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a) | def test_same_tenant_different_usernames():
access_token_a = 'access-token-a'
access_token_b = 'access-token-b'
refresh_token_a = 'refresh-token-a'
refresh_token_b = 'refresh-token-b'
upn_a = 'spam@eggs'
upn_b = 'eggs@spam'
tenant_id = 'the-tenant'
account_a = get_account_event(username=upn_a, uid='another-guid', utid=tenant_id, refresh_token=refresh_token_a)
account_b = get_account_event(username=upn_b, uid='more-guid', utid=tenant_id, refresh_token=refresh_token_b)
cache = populated_cache(account_a, account_b)
transport = Mock(side_effect=Exception())
credential = SharedTokenCacheCredential(tenant_id=tenant_id, _cache=cache, transport=transport)
with pytest.raises(CredentialUnavailableError) as ex:
credential.get_token('scope')
assert ex.value.message.startswith(MULTIPLE_MATCHING_ACCOUNTS[:MULTIPLE_MATCHING_ACCOUNTS.index('{')])
assert (tenant_id in ex.value.message)
scope = 'scope'
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_b, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(username=upn_b, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a)
transport = validating_transport(requests=[Request(required_data={'refresh_token': refresh_token_a, 'scope': scope})], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))])
credential = SharedTokenCacheCredential(username=upn_a, _cache=cache, transport=transport)
token = credential.get_token(scope)
assert (token.token == access_token_a)<|docstring|>two cached accounts, same tenant, different usernames<|endoftext|> |
178443b4bef5ea6df178f9efa4810e7674cafa1ae2eb8d1ef37b5ca01f9bb231 | def test_authority_aliases():
'the credential should use a refresh token valid for any known alias of its authority'
expected_access_token = 'access-token'
for authority in KNOWN_ALIASES:
expected_refresh_token = authority.replace('.', '')
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=authority, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token)
for alias in KNOWN_ALIASES[authority]:
transport = validating_transport(requests=[Request(authority=alias, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=alias, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token) | the credential should use a refresh token valid for any known alias of its authority | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_authority_aliases | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_authority_aliases():
expected_access_token = 'access-token'
for authority in KNOWN_ALIASES:
expected_refresh_token = authority.replace('.', )
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=authority, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token)
for alias in KNOWN_ALIASES[authority]:
transport = validating_transport(requests=[Request(authority=alias, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=alias, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token) | def test_authority_aliases():
expected_access_token = 'access-token'
for authority in KNOWN_ALIASES:
expected_refresh_token = authority.replace('.', )
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=authority, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token)
for alias in KNOWN_ALIASES[authority]:
transport = validating_transport(requests=[Request(authority=alias, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=alias, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token)<|docstring|>the credential should use a refresh token valid for any known alias of its authority<|endoftext|> |
4586ac8fb1c7823fc964cdf3b9779418b39490cd0e0fc9742360196eb0e3b13a | def test_authority_with_no_known_alias():
'given an appropriate token, an authority with no known aliases should work'
authority = 'unknown.authority'
expected_access_token = 'access-token'
expected_refresh_token = 'refresh-token'
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=authority, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token) | given an appropriate token, an authority with no known aliases should work | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_authority_with_no_known_alias | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_authority_with_no_known_alias():
authority = 'unknown.authority'
expected_access_token = 'access-token'
expected_refresh_token = 'refresh-token'
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=authority, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token) | def test_authority_with_no_known_alias():
authority = 'unknown.authority'
expected_access_token = 'access-token'
expected_refresh_token = 'refresh-token'
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
credential = SharedTokenCacheCredential(authority=authority, _cache=cache, transport=transport)
token = credential.get_token('scope')
assert (token.token == expected_access_token)<|docstring|>given an appropriate token, an authority with no known aliases should work<|endoftext|> |
cae40985d8a5086e7f4902bd1e0fe909894ff9b5dc3eba31a9eb643ad4bc95e6 | def test_authority_environment_variable():
'the credential should accept an authority by environment variable when none is otherwise specified'
authority = 'localhost'
expected_access_token = 'access-token'
expected_refresh_token = 'refresh-token'
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
with patch.dict('os.environ', {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
credential = SharedTokenCacheCredential(transport=transport, _cache=cache)
token = credential.get_token('scope')
assert (token.token == expected_access_token) | the credential should accept an authority by environment variable when none is otherwise specified | sdk/identity/azure-identity/tests/test_shared_cache_credential.py | test_authority_environment_variable | MS-syh2qs/azure-sdk-for-python | 1 | python | def test_authority_environment_variable():
authority = 'localhost'
expected_access_token = 'access-token'
expected_refresh_token = 'refresh-token'
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
with patch.dict('os.environ', {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
credential = SharedTokenCacheCredential(transport=transport, _cache=cache)
token = credential.get_token('scope')
assert (token.token == expected_access_token) | def test_authority_environment_variable():
authority = 'localhost'
expected_access_token = 'access-token'
expected_refresh_token = 'refresh-token'
account = get_account_event('spam@eggs', 'uid', 'tenant', authority=authority, refresh_token=expected_refresh_token)
cache = populated_cache(account)
transport = validating_transport(requests=[Request(authority=authority, required_data={'refresh_token': expected_refresh_token})], responses=[mock_response(json_payload=build_aad_response(access_token=expected_access_token))])
with patch.dict('os.environ', {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
credential = SharedTokenCacheCredential(transport=transport, _cache=cache)
token = credential.get_token('scope')
assert (token.token == expected_access_token)<|docstring|>the credential should accept an authority by environment variable when none is otherwise specified<|endoftext|> |
bedeca1133eda6eaa7262d7bf70ba65a5fe7dc8007da78b18e4a7ece1b847a33 | def level_0_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager:
'Level 0 pass manager: no explicit optimization other than mapping to backend.\n\n This pass manager applies the user-given initial layout. If none is given, a trivial\n layout consisting of mapping the i-th virtual qubit to the i-th physical qubit is used.\n Any unused physical qubit is allocated as ancilla space.\n\n The pass manager then unrolls the circuit to the desired basis, and transforms the\n circuit to match the coupling map.\n\n Note:\n In simulators where ``coupling_map=None``, only the unrolling and\n optimization stages are done.\n\n Args:\n pass_manager_config: configuration of the pass manager.\n\n Returns:\n a level 0 pass manager.\n\n Raises:\n TranspilerError: if the passmanager config is invalid.\n '
basis_gates = pass_manager_config.basis_gates
coupling_map = pass_manager_config.coupling_map
initial_layout = pass_manager_config.initial_layout
layout_method = (pass_manager_config.layout_method or 'trivial')
routing_method = (pass_manager_config.routing_method or 'stochastic')
translation_method = (pass_manager_config.translation_method or 'translator')
seed_transpiler = pass_manager_config.seed_transpiler
backend_properties = pass_manager_config.backend_properties
_given_layout = SetLayout(initial_layout)
def _choose_layout_condition(property_set):
return (not property_set['layout'])
if (layout_method == 'trivial'):
_choose_layout = TrivialLayout(coupling_map)
elif (layout_method == 'dense'):
_choose_layout = DenseLayout(coupling_map, backend_properties)
elif (layout_method == 'noise_adaptive'):
_choose_layout = NoiseAdaptiveLayout(backend_properties)
elif (layout_method == 'sabre'):
_choose_layout = SabreLayout(coupling_map, max_iterations=1, seed=seed_transpiler)
else:
raise TranspilerError(('Invalid layout method %s.' % layout_method))
_embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()]
_unroll3q = Unroll3qOrMore()
_swap_check = CheckMap(coupling_map)
def _swap_condition(property_set):
return (not property_set['is_swap_mapped'])
_swap = [BarrierBeforeFinalMeasurements()]
if (routing_method == 'basic'):
_swap += [BasicSwap(coupling_map)]
elif (routing_method == 'stochastic'):
_swap += [StochasticSwap(coupling_map, trials=20, seed=seed_transpiler)]
elif (routing_method == 'lookahead'):
_swap += [LookaheadSwap(coupling_map, search_depth=2, search_width=2)]
elif (routing_method == 'sabre'):
_swap += [SabreSwap(coupling_map, heuristic='basic', seed=seed_transpiler)]
else:
raise TranspilerError(('Invalid routing method %s.' % routing_method))
if (translation_method == 'unroller'):
_unroll = [Unroller(basis_gates)]
elif (translation_method == 'translator'):
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel
_unroll = [UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates)]
else:
raise TranspilerError(('Invalid translation method %s.' % translation_method))
_direction_check = [CheckCXDirection(coupling_map)]
def _direction_condition(property_set):
return (not property_set['is_direction_mapped'])
_direction = [CXDirection(coupling_map)]
pm0 = PassManager()
if coupling_map:
pm0.append(_given_layout)
pm0.append(_choose_layout, condition=_choose_layout_condition)
pm0.append(_embed)
pm0.append(_unroll3q)
pm0.append(_swap_check)
pm0.append(_swap, condition=_swap_condition)
pm0.append(_unroll)
if (coupling_map and (not coupling_map.is_symmetric)):
pm0.append(_direction_check)
pm0.append(_direction, condition=_direction_condition)
return pm0 | Level 0 pass manager: no explicit optimization other than mapping to backend.
This pass manager applies the user-given initial layout. If none is given, a trivial
layout consisting of mapping the i-th virtual qubit to the i-th physical qubit is used.
Any unused physical qubit is allocated as ancilla space.
The pass manager then unrolls the circuit to the desired basis, and transforms the
circuit to match the coupling map.
Note:
In simulators where ``coupling_map=None``, only the unrolling and
optimization stages are done.
Args:
pass_manager_config: configuration of the pass manager.
Returns:
a level 0 pass manager.
Raises:
TranspilerError: if the passmanager config is invalid. | qiskit/transpiler/preset_passmanagers/level0.py | level_0_pass_manager | rochisha0/qiskit-terra | 2 | python | def level_0_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager:
'Level 0 pass manager: no explicit optimization other than mapping to backend.\n\n This pass manager applies the user-given initial layout. If none is given, a trivial\n layout consisting of mapping the i-th virtual qubit to the i-th physical qubit is used.\n Any unused physical qubit is allocated as ancilla space.\n\n The pass manager then unrolls the circuit to the desired basis, and transforms the\n circuit to match the coupling map.\n\n Note:\n In simulators where ``coupling_map=None``, only the unrolling and\n optimization stages are done.\n\n Args:\n pass_manager_config: configuration of the pass manager.\n\n Returns:\n a level 0 pass manager.\n\n Raises:\n TranspilerError: if the passmanager config is invalid.\n '
basis_gates = pass_manager_config.basis_gates
coupling_map = pass_manager_config.coupling_map
initial_layout = pass_manager_config.initial_layout
layout_method = (pass_manager_config.layout_method or 'trivial')
routing_method = (pass_manager_config.routing_method or 'stochastic')
translation_method = (pass_manager_config.translation_method or 'translator')
seed_transpiler = pass_manager_config.seed_transpiler
backend_properties = pass_manager_config.backend_properties
_given_layout = SetLayout(initial_layout)
def _choose_layout_condition(property_set):
return (not property_set['layout'])
if (layout_method == 'trivial'):
_choose_layout = TrivialLayout(coupling_map)
elif (layout_method == 'dense'):
_choose_layout = DenseLayout(coupling_map, backend_properties)
elif (layout_method == 'noise_adaptive'):
_choose_layout = NoiseAdaptiveLayout(backend_properties)
elif (layout_method == 'sabre'):
_choose_layout = SabreLayout(coupling_map, max_iterations=1, seed=seed_transpiler)
else:
raise TranspilerError(('Invalid layout method %s.' % layout_method))
_embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()]
_unroll3q = Unroll3qOrMore()
_swap_check = CheckMap(coupling_map)
def _swap_condition(property_set):
return (not property_set['is_swap_mapped'])
_swap = [BarrierBeforeFinalMeasurements()]
if (routing_method == 'basic'):
_swap += [BasicSwap(coupling_map)]
elif (routing_method == 'stochastic'):
_swap += [StochasticSwap(coupling_map, trials=20, seed=seed_transpiler)]
elif (routing_method == 'lookahead'):
_swap += [LookaheadSwap(coupling_map, search_depth=2, search_width=2)]
elif (routing_method == 'sabre'):
_swap += [SabreSwap(coupling_map, heuristic='basic', seed=seed_transpiler)]
else:
raise TranspilerError(('Invalid routing method %s.' % routing_method))
if (translation_method == 'unroller'):
_unroll = [Unroller(basis_gates)]
elif (translation_method == 'translator'):
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel
_unroll = [UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates)]
else:
raise TranspilerError(('Invalid translation method %s.' % translation_method))
_direction_check = [CheckCXDirection(coupling_map)]
def _direction_condition(property_set):
return (not property_set['is_direction_mapped'])
_direction = [CXDirection(coupling_map)]
pm0 = PassManager()
if coupling_map:
pm0.append(_given_layout)
pm0.append(_choose_layout, condition=_choose_layout_condition)
pm0.append(_embed)
pm0.append(_unroll3q)
pm0.append(_swap_check)
pm0.append(_swap, condition=_swap_condition)
pm0.append(_unroll)
if (coupling_map and (not coupling_map.is_symmetric)):
pm0.append(_direction_check)
pm0.append(_direction, condition=_direction_condition)
return pm0 | def level_0_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager:
'Level 0 pass manager: no explicit optimization other than mapping to backend.\n\n This pass manager applies the user-given initial layout. If none is given, a trivial\n layout consisting of mapping the i-th virtual qubit to the i-th physical qubit is used.\n Any unused physical qubit is allocated as ancilla space.\n\n The pass manager then unrolls the circuit to the desired basis, and transforms the\n circuit to match the coupling map.\n\n Note:\n In simulators where ``coupling_map=None``, only the unrolling and\n optimization stages are done.\n\n Args:\n pass_manager_config: configuration of the pass manager.\n\n Returns:\n a level 0 pass manager.\n\n Raises:\n TranspilerError: if the passmanager config is invalid.\n '
basis_gates = pass_manager_config.basis_gates
coupling_map = pass_manager_config.coupling_map
initial_layout = pass_manager_config.initial_layout
layout_method = (pass_manager_config.layout_method or 'trivial')
routing_method = (pass_manager_config.routing_method or 'stochastic')
translation_method = (pass_manager_config.translation_method or 'translator')
seed_transpiler = pass_manager_config.seed_transpiler
backend_properties = pass_manager_config.backend_properties
_given_layout = SetLayout(initial_layout)
def _choose_layout_condition(property_set):
return (not property_set['layout'])
if (layout_method == 'trivial'):
_choose_layout = TrivialLayout(coupling_map)
elif (layout_method == 'dense'):
_choose_layout = DenseLayout(coupling_map, backend_properties)
elif (layout_method == 'noise_adaptive'):
_choose_layout = NoiseAdaptiveLayout(backend_properties)
elif (layout_method == 'sabre'):
_choose_layout = SabreLayout(coupling_map, max_iterations=1, seed=seed_transpiler)
else:
raise TranspilerError(('Invalid layout method %s.' % layout_method))
_embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()]
_unroll3q = Unroll3qOrMore()
_swap_check = CheckMap(coupling_map)
def _swap_condition(property_set):
return (not property_set['is_swap_mapped'])
_swap = [BarrierBeforeFinalMeasurements()]
if (routing_method == 'basic'):
_swap += [BasicSwap(coupling_map)]
elif (routing_method == 'stochastic'):
_swap += [StochasticSwap(coupling_map, trials=20, seed=seed_transpiler)]
elif (routing_method == 'lookahead'):
_swap += [LookaheadSwap(coupling_map, search_depth=2, search_width=2)]
elif (routing_method == 'sabre'):
_swap += [SabreSwap(coupling_map, heuristic='basic', seed=seed_transpiler)]
else:
raise TranspilerError(('Invalid routing method %s.' % routing_method))
if (translation_method == 'unroller'):
_unroll = [Unroller(basis_gates)]
elif (translation_method == 'translator'):
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel
_unroll = [UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates)]
else:
raise TranspilerError(('Invalid translation method %s.' % translation_method))
_direction_check = [CheckCXDirection(coupling_map)]
def _direction_condition(property_set):
return (not property_set['is_direction_mapped'])
_direction = [CXDirection(coupling_map)]
pm0 = PassManager()
if coupling_map:
pm0.append(_given_layout)
pm0.append(_choose_layout, condition=_choose_layout_condition)
pm0.append(_embed)
pm0.append(_unroll3q)
pm0.append(_swap_check)
pm0.append(_swap, condition=_swap_condition)
pm0.append(_unroll)
if (coupling_map and (not coupling_map.is_symmetric)):
pm0.append(_direction_check)
pm0.append(_direction, condition=_direction_condition)
return pm0<|docstring|>Level 0 pass manager: no explicit optimization other than mapping to backend.
This pass manager applies the user-given initial layout. If none is given, a trivial
layout consisting of mapping the i-th virtual qubit to the i-th physical qubit is used.
Any unused physical qubit is allocated as ancilla space.
The pass manager then unrolls the circuit to the desired basis, and transforms the
circuit to match the coupling map.
Note:
In simulators where ``coupling_map=None``, only the unrolling and
optimization stages are done.
Args:
pass_manager_config: configuration of the pass manager.
Returns:
a level 0 pass manager.
Raises:
TranspilerError: if the passmanager config is invalid.<|endoftext|> |
f19d6653a02f0f60b3c9bda69aee7574d91e06ea0754eaf6a2d9bf40aa5bd8c7 | def get_action_embedding(bert_module, word_embed_encoder, act_name, act_para_names, bert_act_name, bert_act_para_names, query_vec, query_states, dropout, args, embed_dim, scope):
'\n parameter domain or examples are excluded for now from learning ...\n :param action_name:\n :param parameters:\n :return:\n '
action_name_vec = encode_action_name(bert_module, word_embed_encoder, act_name, bert_act_name, query_vec, query_states, args, dropout, embed_dim, scope)
if ((args['encoder_type'] == 'rnn_bi') or (args['encoder_type'] == 'rnn_uni') or (args['encoder_type'] == 'cnn')):
action_para_name_embs = encode_action_para_names(word_embed_encoder, act_para_names, args, dropout, embed_dim)
action_para_name_vec = tf.reduce_mean(action_para_name_embs, axis=1)
else:
(_, action_para_name_vec) = encode_phrase(bert_module, word_embed_encoder, act_para_names, bert_act_para_names, args, dropout, embed_dim, 'rnn_encoding_act')
return (action_name_vec, action_para_name_vec) | parameter domain or examples are excluded for now from learning ...
:param action_name:
:param parameters:
:return: | code/nsm_model/action_embedding.py | get_action_embedding | microsoft/flin-nl2web | 3 | python | def get_action_embedding(bert_module, word_embed_encoder, act_name, act_para_names, bert_act_name, bert_act_para_names, query_vec, query_states, dropout, args, embed_dim, scope):
'\n parameter domain or examples are excluded for now from learning ...\n :param action_name:\n :param parameters:\n :return:\n '
action_name_vec = encode_action_name(bert_module, word_embed_encoder, act_name, bert_act_name, query_vec, query_states, args, dropout, embed_dim, scope)
if ((args['encoder_type'] == 'rnn_bi') or (args['encoder_type'] == 'rnn_uni') or (args['encoder_type'] == 'cnn')):
action_para_name_embs = encode_action_para_names(word_embed_encoder, act_para_names, args, dropout, embed_dim)
action_para_name_vec = tf.reduce_mean(action_para_name_embs, axis=1)
else:
(_, action_para_name_vec) = encode_phrase(bert_module, word_embed_encoder, act_para_names, bert_act_para_names, args, dropout, embed_dim, 'rnn_encoding_act')
return (action_name_vec, action_para_name_vec) | def get_action_embedding(bert_module, word_embed_encoder, act_name, act_para_names, bert_act_name, bert_act_para_names, query_vec, query_states, dropout, args, embed_dim, scope):
'\n parameter domain or examples are excluded for now from learning ...\n :param action_name:\n :param parameters:\n :return:\n '
action_name_vec = encode_action_name(bert_module, word_embed_encoder, act_name, bert_act_name, query_vec, query_states, args, dropout, embed_dim, scope)
if ((args['encoder_type'] == 'rnn_bi') or (args['encoder_type'] == 'rnn_uni') or (args['encoder_type'] == 'cnn')):
action_para_name_embs = encode_action_para_names(word_embed_encoder, act_para_names, args, dropout, embed_dim)
action_para_name_vec = tf.reduce_mean(action_para_name_embs, axis=1)
else:
(_, action_para_name_vec) = encode_phrase(bert_module, word_embed_encoder, act_para_names, bert_act_para_names, args, dropout, embed_dim, 'rnn_encoding_act')
return (action_name_vec, action_para_name_vec)<|docstring|>parameter domain or examples are excluded for now from learning ...
:param action_name:
:param parameters:
:return:<|endoftext|> |
ccd8ee9cdf5aa564de187bf002e5203b6a007862a7382a02c26e55ebe83a1301 | def getfiles(kstar1, kstar2, model):
"\n Get the list of COSMIC dat files used to create \n DWD populations.\n \n INPUTS\n ----------------------\n kstar1 [10, 11, 12]: type of first WD\n kstar2 [10, 11, 12]: type of second WD\n model: model variation from 'fiducial', 'q3', 'alpha25', 'alpha5'\n \n RETURNS\n ----------------------\n filename_list [list, str]: list of files names\n label [str]: DWD type label\n "
met_list = [0.0001, 0.00015029, 0.00022588, 0.00033948, 0.00051021, 0.00076681, 0.00115245, 0.00173205, 0.00260314, 0.00391233, 0.00587993, 0.0088371, 0.01328149, 0.01996108, 0.03]
filename_list = []
for ii in range(len(met_list)):
if (kstar1 == '12'):
fname = '{}_12_10_12_{}.h5'.format(model, ii)
else:
fname = '{}_{}_{}_{}.h5'.format(model, kstar1, kstar2, ii)
filename_list.append(fname)
if (kstar1 == '12'):
label = '12'
else:
label = '{}_{}'.format(kstar1, kstar2)
return (filename_list, label) | Get the list of COSMIC dat files used to create
DWD populations.
INPUTS
----------------------
kstar1 [10, 11, 12]: type of first WD
kstar2 [10, 11, 12]: type of second WD
model: model variation from 'fiducial', 'q3', 'alpha25', 'alpha5'
RETURNS
----------------------
filename_list [list, str]: list of files names
label [str]: DWD type label | src/figures/utils.py | getfiles | sarahthiele/hush | 2 | python | def getfiles(kstar1, kstar2, model):
"\n Get the list of COSMIC dat files used to create \n DWD populations.\n \n INPUTS\n ----------------------\n kstar1 [10, 11, 12]: type of first WD\n kstar2 [10, 11, 12]: type of second WD\n model: model variation from 'fiducial', 'q3', 'alpha25', 'alpha5'\n \n RETURNS\n ----------------------\n filename_list [list, str]: list of files names\n label [str]: DWD type label\n "
met_list = [0.0001, 0.00015029, 0.00022588, 0.00033948, 0.00051021, 0.00076681, 0.00115245, 0.00173205, 0.00260314, 0.00391233, 0.00587993, 0.0088371, 0.01328149, 0.01996108, 0.03]
filename_list = []
for ii in range(len(met_list)):
if (kstar1 == '12'):
fname = '{}_12_10_12_{}.h5'.format(model, ii)
else:
fname = '{}_{}_{}_{}.h5'.format(model, kstar1, kstar2, ii)
filename_list.append(fname)
if (kstar1 == '12'):
label = '12'
else:
label = '{}_{}'.format(kstar1, kstar2)
return (filename_list, label) | def getfiles(kstar1, kstar2, model):
"\n Get the list of COSMIC dat files used to create \n DWD populations.\n \n INPUTS\n ----------------------\n kstar1 [10, 11, 12]: type of first WD\n kstar2 [10, 11, 12]: type of second WD\n model: model variation from 'fiducial', 'q3', 'alpha25', 'alpha5'\n \n RETURNS\n ----------------------\n filename_list [list, str]: list of files names\n label [str]: DWD type label\n "
met_list = [0.0001, 0.00015029, 0.00022588, 0.00033948, 0.00051021, 0.00076681, 0.00115245, 0.00173205, 0.00260314, 0.00391233, 0.00587993, 0.0088371, 0.01328149, 0.01996108, 0.03]
filename_list = []
for ii in range(len(met_list)):
if (kstar1 == '12'):
fname = '{}_12_10_12_{}.h5'.format(model, ii)
else:
fname = '{}_{}_{}_{}.h5'.format(model, kstar1, kstar2, ii)
filename_list.append(fname)
if (kstar1 == '12'):
label = '12'
else:
label = '{}_{}'.format(kstar1, kstar2)
return (filename_list, label)<|docstring|>Get the list of COSMIC dat files used to create
DWD populations.
INPUTS
----------------------
kstar1 [10, 11, 12]: type of first WD
kstar2 [10, 11, 12]: type of second WD
model: model variation from 'fiducial', 'q3', 'alpha25', 'alpha5'
RETURNS
----------------------
filename_list [list, str]: list of files names
label [str]: DWD type label<|endoftext|> |
0aa12f4ac0c1e470129f7213144ab07a7253b857c9f4e1e6b623025de95ac889 | def get_binfrac_of_Z(Z):
'\n Calculates the theoretical binary fraction as a \n function of metallicity.\n \n INPUTS\n ----------------------\n Z [array]: metallicity Z values\n \n RETURNS\n ----------------------\n binfrac [array]: binary fraction values\n '
FeH = get_FeH_from_Z(Z)
FeH_low = FeH[np.where((FeH <= (- 1.0)))]
FeH_high = FeH[np.where((FeH > (- 1.0)))]
binfrac_low = (((- 0.0648) * FeH_low) + 0.3356)
binfrac_high = (((- 0.1977) * FeH_high) + 0.2025)
binfrac = np.append(binfrac_low, binfrac_high)
return binfrac | Calculates the theoretical binary fraction as a
function of metallicity.
INPUTS
----------------------
Z [array]: metallicity Z values
RETURNS
----------------------
binfrac [array]: binary fraction values | src/figures/utils.py | get_binfrac_of_Z | sarahthiele/hush | 2 | python | def get_binfrac_of_Z(Z):
'\n Calculates the theoretical binary fraction as a \n function of metallicity.\n \n INPUTS\n ----------------------\n Z [array]: metallicity Z values\n \n RETURNS\n ----------------------\n binfrac [array]: binary fraction values\n '
FeH = get_FeH_from_Z(Z)
FeH_low = FeH[np.where((FeH <= (- 1.0)))]
FeH_high = FeH[np.where((FeH > (- 1.0)))]
binfrac_low = (((- 0.0648) * FeH_low) + 0.3356)
binfrac_high = (((- 0.1977) * FeH_high) + 0.2025)
binfrac = np.append(binfrac_low, binfrac_high)
return binfrac | def get_binfrac_of_Z(Z):
'\n Calculates the theoretical binary fraction as a \n function of metallicity.\n \n INPUTS\n ----------------------\n Z [array]: metallicity Z values\n \n RETURNS\n ----------------------\n binfrac [array]: binary fraction values\n '
FeH = get_FeH_from_Z(Z)
FeH_low = FeH[np.where((FeH <= (- 1.0)))]
FeH_high = FeH[np.where((FeH > (- 1.0)))]
binfrac_low = (((- 0.0648) * FeH_low) + 0.3356)
binfrac_high = (((- 0.1977) * FeH_high) + 0.2025)
binfrac = np.append(binfrac_low, binfrac_high)
return binfrac<|docstring|>Calculates the theoretical binary fraction as a
function of metallicity.
INPUTS
----------------------
Z [array]: metallicity Z values
RETURNS
----------------------
binfrac [array]: binary fraction values<|endoftext|> |
f80de6562f2680d58763845231ae89789df706d403f474017cf7e428d449c843 | def get_Z_from_FeH(FeH, Z_sun=0.02):
'\n Converts from FeH to Z under the assumption that\n all stars have the same abundance as the sun\n \n INPUTS\n ----------------------\n FeH [array]: array of Fe/H values to convert\n Z_sun [float]: solar metallicity\n \n RETURNS\n ----------------------\n Z [array]: array of metallicities\n '
Z = (10 ** (FeH + np.log10(Z_sun)))
return Z | Converts from FeH to Z under the assumption that
all stars have the same abundance as the sun
INPUTS
----------------------
FeH [array]: array of Fe/H values to convert
Z_sun [float]: solar metallicity
RETURNS
----------------------
Z [array]: array of metallicities | src/figures/utils.py | get_Z_from_FeH | sarahthiele/hush | 2 | python | def get_Z_from_FeH(FeH, Z_sun=0.02):
'\n Converts from FeH to Z under the assumption that\n all stars have the same abundance as the sun\n \n INPUTS\n ----------------------\n FeH [array]: array of Fe/H values to convert\n Z_sun [float]: solar metallicity\n \n RETURNS\n ----------------------\n Z [array]: array of metallicities\n '
Z = (10 ** (FeH + np.log10(Z_sun)))
return Z | def get_Z_from_FeH(FeH, Z_sun=0.02):
'\n Converts from FeH to Z under the assumption that\n all stars have the same abundance as the sun\n \n INPUTS\n ----------------------\n FeH [array]: array of Fe/H values to convert\n Z_sun [float]: solar metallicity\n \n RETURNS\n ----------------------\n Z [array]: array of metallicities\n '
Z = (10 ** (FeH + np.log10(Z_sun)))
return Z<|docstring|>Converts from FeH to Z under the assumption that
all stars have the same abundance as the sun
INPUTS
----------------------
FeH [array]: array of Fe/H values to convert
Z_sun [float]: solar metallicity
RETURNS
----------------------
Z [array]: array of metallicities<|endoftext|> |
192ca628c8262a1252429121c307c69d35cfee8e867b30781c2bbf3815bcb606 | def get_FeH_from_Z(Z, Z_sun=0.02):
'\n Converts from Z to FeH under the assumption that\n all stars have the same abundance as the sun\n \n INPUTS\n ----------------------\n Z [array]: array of metallicities to convert\n Z_sun [float]: solar metallicity\n \n RETURNS\n ----------------------\n Z [array]: array of FeH values\n '
FeH = (np.log10(Z) - np.log10(Z_sun))
return FeH | Converts from Z to FeH under the assumption that
all stars have the same abundance as the sun
INPUTS
----------------------
Z [array]: array of metallicities to convert
Z_sun [float]: solar metallicity
RETURNS
----------------------
Z [array]: array of FeH values | src/figures/utils.py | get_FeH_from_Z | sarahthiele/hush | 2 | python | def get_FeH_from_Z(Z, Z_sun=0.02):
'\n Converts from Z to FeH under the assumption that\n all stars have the same abundance as the sun\n \n INPUTS\n ----------------------\n Z [array]: array of metallicities to convert\n Z_sun [float]: solar metallicity\n \n RETURNS\n ----------------------\n Z [array]: array of FeH values\n '
FeH = (np.log10(Z) - np.log10(Z_sun))
return FeH | def get_FeH_from_Z(Z, Z_sun=0.02):
'\n Converts from Z to FeH under the assumption that\n all stars have the same abundance as the sun\n \n INPUTS\n ----------------------\n Z [array]: array of metallicities to convert\n Z_sun [float]: solar metallicity\n \n RETURNS\n ----------------------\n Z [array]: array of FeH values\n '
FeH = (np.log10(Z) - np.log10(Z_sun))
return FeH<|docstring|>Converts from Z to FeH under the assumption that
all stars have the same abundance as the sun
INPUTS
----------------------
Z [array]: array of metallicities to convert
Z_sun [float]: solar metallicity
RETURNS
----------------------
Z [array]: array of FeH values<|endoftext|> |
c5760a8f8c86e91e2906f6308e7d741c06acefd3559f73170a7146e12212ba1b | def custom_centrality(G, max_iter=1000, tol=1e-06, nstart=None, weight=None):
'Compute the eigenvector centrality for the graph `G`.\n\n Eigenvector centrality computes the centrality for a node based on the\n centrality of its neighbors. The eigenvector centrality for node $i$ is\n the $i$-th element of the vector $x$ defined by the equation\n\n .. math::\n\n Ax = \\lambda x\n\n where $A$ is the adjacency matrix of the graph `G` with eigenvalue\n $\\lambda$. By virtue of the Perron–Frobenius theorem, there is a unique\n solution $x$, all of whose entries are positive, if $\\lambda$ is the\n largest eigenvalue of the adjacency matrix $A$ ([2]_).\n\n Parameters\n ----------\n G : graph\n A networkx graph\n\n max_iter : integer, optional (default=100)\n Maximum number of iterations in power method.\n\n tol : float, optional (default=1.0e-6)\n Error tolerance used to check convergence in power method iteration.\n\n nstart : dictionary, optional (default=None)\n Starting value of eigenvector iteration for each node.\n\n weight : None or string, optional (default=None)\n If None, all edge weights are considered equal.\n Otherwise holds the name of the edge attribute used as weight.\n\n Returns\n -------\n nodes : dictionary\n Dictionary of nodes with eigenvector centrality as the value.\n\n Examples\n --------\n >>> G = nx.path_graph(4)\n >>> centrality = nx.eigenvector_centrality(G)\n >>> sorted((v, \'{:0.2f}\'.format(c)) for v, c in centrality.items())\n [(0, \'0.37\'), (1, \'0.60\'), (2, \'0.60\'), (3, \'0.37\')]\n\n Raises\n ------\n NetworkXPointlessConcept\n If the graph `G` is the null graph.\n\n NetworkXError\n If each value in `nstart` is zero.\n\n PowerIterationFailedConvergence\n If the algorithm fails to converge to the specified tolerance\n within the specified number of iterations of the power iteration\n method.\n\n See Also\n --------\n eigenvector_centrality_numpy\n pagerank\n hits\n\n Notes\n -----\n The measure was introduced by [1]_ and is discussed in [2]_.\n\n The power iteration method is used to compute the eigenvector and\n convergence is **not** guaranteed. Our method stops after ``max_iter``\n iterations or when the change in the computed vector between two\n iterations is smaller than an error tolerance of\n ``G.number_of_nodes() * tol``. This implementation uses ($A + I$)\n rather than the adjacency matrix $A$ because it shifts the spectrum\n to enable discerning the correct eigenvector even for networks with\n multiple dominant eigenvalues.\n\n For directed graphs this is "left" eigenvector centrality which corresponds\n to the in-edges in the graph. For out-edges eigenvector centrality\n first reverse the graph with ``G.reverse()``.\n\n References\n ----------\n .. [1] Phillip Bonacich.\n "Power and Centrality: A Family of Measures."\n *American Journal of Sociology* 92(5):1170–1182, 1986\n <http://www.leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf>\n .. [2] Mark E. J. Newman.\n *Networks: An Introduction.*\n Oxford University Press, USA, 2010, pp. 169.\n\n '
if (len(G) == 0):
raise nx.NetworkXPointlessConcept('cannot compute centrality for the null graph')
if (nstart is None):
nstart = {v: 1 for v in G}
if all(((v == 0) for v in nstart.values())):
raise nx.NetworkXError('initial vector cannot have all zero values')
x = {k: (v / sum(nstart.values())) for (k, v) in nstart.items()}
y = {k: (v / sum(nstart.values())) for (k, v) in nstart.items()}
nnodes = G.number_of_nodes()
for i in range(max_iter):
print((i + 1))
xlast = x
x = xlast.copy()
ylast = y
y = ylast.copy()
for xj in x:
for nbr in G[xj]:
y[nbr] += (xlast[xj] * G[xj][nbr].get(weight, 1))
x[xj] += (ylast[nbr] * G[xj][nbr].get(weight, 1))
norm_x = (sqrt(sum(((z ** 2) for z in x.values()))) or 1)
norm_y = (sqrt(sum(((z ** 2) for z in y.values()))) or 1)
x = {k: (v / norm_x) for (k, v) in x.items()}
y = {k: (v / norm_y) for (k, v) in y.items()}
if ((sum((abs((x[n] - xlast[n])) for n in x)) < (nnodes * tol)) and (sum((abs((y[n] - ylast[n])) for n in y)) < (nnodes * tol))):
return (x, y)
raise nx.PowerIterationFailedConvergence(max_iter) | Compute the eigenvector centrality for the graph `G`.
Eigenvector centrality computes the centrality for a node based on the
centrality of its neighbors. The eigenvector centrality for node $i$ is
the $i$-th element of the vector $x$ defined by the equation
.. math::
Ax = \lambda x
where $A$ is the adjacency matrix of the graph `G` with eigenvalue
$\lambda$. By virtue of the Perron–Frobenius theorem, there is a unique
solution $x$, all of whose entries are positive, if $\lambda$ is the
largest eigenvalue of the adjacency matrix $A$ ([2]_).
Parameters
----------
G : graph
A networkx graph
max_iter : integer, optional (default=100)
Maximum number of iterations in power method.
tol : float, optional (default=1.0e-6)
Error tolerance used to check convergence in power method iteration.
nstart : dictionary, optional (default=None)
Starting value of eigenvector iteration for each node.
weight : None or string, optional (default=None)
If None, all edge weights are considered equal.
Otherwise holds the name of the edge attribute used as weight.
Returns
-------
nodes : dictionary
Dictionary of nodes with eigenvector centrality as the value.
Examples
--------
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> sorted((v, '{:0.2f}'.format(c)) for v, c in centrality.items())
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]
Raises
------
NetworkXPointlessConcept
If the graph `G` is the null graph.
NetworkXError
If each value in `nstart` is zero.
PowerIterationFailedConvergence
If the algorithm fails to converge to the specified tolerance
within the specified number of iterations of the power iteration
method.
See Also
--------
eigenvector_centrality_numpy
pagerank
hits
Notes
-----
The measure was introduced by [1]_ and is discussed in [2]_.
The power iteration method is used to compute the eigenvector and
convergence is **not** guaranteed. Our method stops after ``max_iter``
iterations or when the change in the computed vector between two
iterations is smaller than an error tolerance of
``G.number_of_nodes() * tol``. This implementation uses ($A + I$)
rather than the adjacency matrix $A$ because it shifts the spectrum
to enable discerning the correct eigenvector even for networks with
multiple dominant eigenvalues.
For directed graphs this is "left" eigenvector centrality which corresponds
to the in-edges in the graph. For out-edges eigenvector centrality
first reverse the graph with ``G.reverse()``.
References
----------
.. [1] Phillip Bonacich.
"Power and Centrality: A Family of Measures."
*American Journal of Sociology* 92(5):1170–1182, 1986
<http://www.leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf>
.. [2] Mark E. J. Newman.
*Networks: An Introduction.*
Oxford University Press, USA, 2010, pp. 169. | custom.py | custom_centrality | athityakumar/harvey | 2 | python | def custom_centrality(G, max_iter=1000, tol=1e-06, nstart=None, weight=None):
'Compute the eigenvector centrality for the graph `G`.\n\n Eigenvector centrality computes the centrality for a node based on the\n centrality of its neighbors. The eigenvector centrality for node $i$ is\n the $i$-th element of the vector $x$ defined by the equation\n\n .. math::\n\n Ax = \\lambda x\n\n where $A$ is the adjacency matrix of the graph `G` with eigenvalue\n $\\lambda$. By virtue of the Perron–Frobenius theorem, there is a unique\n solution $x$, all of whose entries are positive, if $\\lambda$ is the\n largest eigenvalue of the adjacency matrix $A$ ([2]_).\n\n Parameters\n ----------\n G : graph\n A networkx graph\n\n max_iter : integer, optional (default=100)\n Maximum number of iterations in power method.\n\n tol : float, optional (default=1.0e-6)\n Error tolerance used to check convergence in power method iteration.\n\n nstart : dictionary, optional (default=None)\n Starting value of eigenvector iteration for each node.\n\n weight : None or string, optional (default=None)\n If None, all edge weights are considered equal.\n Otherwise holds the name of the edge attribute used as weight.\n\n Returns\n -------\n nodes : dictionary\n Dictionary of nodes with eigenvector centrality as the value.\n\n Examples\n --------\n >>> G = nx.path_graph(4)\n >>> centrality = nx.eigenvector_centrality(G)\n >>> sorted((v, \'{:0.2f}\'.format(c)) for v, c in centrality.items())\n [(0, \'0.37\'), (1, \'0.60\'), (2, \'0.60\'), (3, \'0.37\')]\n\n Raises\n ------\n NetworkXPointlessConcept\n If the graph `G` is the null graph.\n\n NetworkXError\n If each value in `nstart` is zero.\n\n PowerIterationFailedConvergence\n If the algorithm fails to converge to the specified tolerance\n within the specified number of iterations of the power iteration\n method.\n\n See Also\n --------\n eigenvector_centrality_numpy\n pagerank\n hits\n\n Notes\n -----\n The measure was introduced by [1]_ and is discussed in [2]_.\n\n The power iteration method is used to compute the eigenvector and\n convergence is **not** guaranteed. Our method stops after ``max_iter``\n iterations or when the change in the computed vector between two\n iterations is smaller than an error tolerance of\n ``G.number_of_nodes() * tol``. This implementation uses ($A + I$)\n rather than the adjacency matrix $A$ because it shifts the spectrum\n to enable discerning the correct eigenvector even for networks with\n multiple dominant eigenvalues.\n\n For directed graphs this is "left" eigenvector centrality which corresponds\n to the in-edges in the graph. For out-edges eigenvector centrality\n first reverse the graph with ``G.reverse()``.\n\n References\n ----------\n .. [1] Phillip Bonacich.\n "Power and Centrality: A Family of Measures."\n *American Journal of Sociology* 92(5):1170–1182, 1986\n <http://www.leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf>\n .. [2] Mark E. J. Newman.\n *Networks: An Introduction.*\n Oxford University Press, USA, 2010, pp. 169.\n\n '
if (len(G) == 0):
raise nx.NetworkXPointlessConcept('cannot compute centrality for the null graph')
if (nstart is None):
nstart = {v: 1 for v in G}
if all(((v == 0) for v in nstart.values())):
raise nx.NetworkXError('initial vector cannot have all zero values')
x = {k: (v / sum(nstart.values())) for (k, v) in nstart.items()}
y = {k: (v / sum(nstart.values())) for (k, v) in nstart.items()}
nnodes = G.number_of_nodes()
for i in range(max_iter):
print((i + 1))
xlast = x
x = xlast.copy()
ylast = y
y = ylast.copy()
for xj in x:
for nbr in G[xj]:
y[nbr] += (xlast[xj] * G[xj][nbr].get(weight, 1))
x[xj] += (ylast[nbr] * G[xj][nbr].get(weight, 1))
norm_x = (sqrt(sum(((z ** 2) for z in x.values()))) or 1)
norm_y = (sqrt(sum(((z ** 2) for z in y.values()))) or 1)
x = {k: (v / norm_x) for (k, v) in x.items()}
y = {k: (v / norm_y) for (k, v) in y.items()}
if ((sum((abs((x[n] - xlast[n])) for n in x)) < (nnodes * tol)) and (sum((abs((y[n] - ylast[n])) for n in y)) < (nnodes * tol))):
return (x, y)
raise nx.PowerIterationFailedConvergence(max_iter) | def custom_centrality(G, max_iter=1000, tol=1e-06, nstart=None, weight=None):
'Compute the eigenvector centrality for the graph `G`.\n\n Eigenvector centrality computes the centrality for a node based on the\n centrality of its neighbors. The eigenvector centrality for node $i$ is\n the $i$-th element of the vector $x$ defined by the equation\n\n .. math::\n\n Ax = \\lambda x\n\n where $A$ is the adjacency matrix of the graph `G` with eigenvalue\n $\\lambda$. By virtue of the Perron–Frobenius theorem, there is a unique\n solution $x$, all of whose entries are positive, if $\\lambda$ is the\n largest eigenvalue of the adjacency matrix $A$ ([2]_).\n\n Parameters\n ----------\n G : graph\n A networkx graph\n\n max_iter : integer, optional (default=100)\n Maximum number of iterations in power method.\n\n tol : float, optional (default=1.0e-6)\n Error tolerance used to check convergence in power method iteration.\n\n nstart : dictionary, optional (default=None)\n Starting value of eigenvector iteration for each node.\n\n weight : None or string, optional (default=None)\n If None, all edge weights are considered equal.\n Otherwise holds the name of the edge attribute used as weight.\n\n Returns\n -------\n nodes : dictionary\n Dictionary of nodes with eigenvector centrality as the value.\n\n Examples\n --------\n >>> G = nx.path_graph(4)\n >>> centrality = nx.eigenvector_centrality(G)\n >>> sorted((v, \'{:0.2f}\'.format(c)) for v, c in centrality.items())\n [(0, \'0.37\'), (1, \'0.60\'), (2, \'0.60\'), (3, \'0.37\')]\n\n Raises\n ------\n NetworkXPointlessConcept\n If the graph `G` is the null graph.\n\n NetworkXError\n If each value in `nstart` is zero.\n\n PowerIterationFailedConvergence\n If the algorithm fails to converge to the specified tolerance\n within the specified number of iterations of the power iteration\n method.\n\n See Also\n --------\n eigenvector_centrality_numpy\n pagerank\n hits\n\n Notes\n -----\n The measure was introduced by [1]_ and is discussed in [2]_.\n\n The power iteration method is used to compute the eigenvector and\n convergence is **not** guaranteed. Our method stops after ``max_iter``\n iterations or when the change in the computed vector between two\n iterations is smaller than an error tolerance of\n ``G.number_of_nodes() * tol``. This implementation uses ($A + I$)\n rather than the adjacency matrix $A$ because it shifts the spectrum\n to enable discerning the correct eigenvector even for networks with\n multiple dominant eigenvalues.\n\n For directed graphs this is "left" eigenvector centrality which corresponds\n to the in-edges in the graph. For out-edges eigenvector centrality\n first reverse the graph with ``G.reverse()``.\n\n References\n ----------\n .. [1] Phillip Bonacich.\n "Power and Centrality: A Family of Measures."\n *American Journal of Sociology* 92(5):1170–1182, 1986\n <http://www.leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf>\n .. [2] Mark E. J. Newman.\n *Networks: An Introduction.*\n Oxford University Press, USA, 2010, pp. 169.\n\n '
if (len(G) == 0):
raise nx.NetworkXPointlessConcept('cannot compute centrality for the null graph')
if (nstart is None):
nstart = {v: 1 for v in G}
if all(((v == 0) for v in nstart.values())):
raise nx.NetworkXError('initial vector cannot have all zero values')
x = {k: (v / sum(nstart.values())) for (k, v) in nstart.items()}
y = {k: (v / sum(nstart.values())) for (k, v) in nstart.items()}
nnodes = G.number_of_nodes()
for i in range(max_iter):
print((i + 1))
xlast = x
x = xlast.copy()
ylast = y
y = ylast.copy()
for xj in x:
for nbr in G[xj]:
y[nbr] += (xlast[xj] * G[xj][nbr].get(weight, 1))
x[xj] += (ylast[nbr] * G[xj][nbr].get(weight, 1))
norm_x = (sqrt(sum(((z ** 2) for z in x.values()))) or 1)
norm_y = (sqrt(sum(((z ** 2) for z in y.values()))) or 1)
x = {k: (v / norm_x) for (k, v) in x.items()}
y = {k: (v / norm_y) for (k, v) in y.items()}
if ((sum((abs((x[n] - xlast[n])) for n in x)) < (nnodes * tol)) and (sum((abs((y[n] - ylast[n])) for n in y)) < (nnodes * tol))):
return (x, y)
raise nx.PowerIterationFailedConvergence(max_iter)<|docstring|>Compute the eigenvector centrality for the graph `G`.
Eigenvector centrality computes the centrality for a node based on the
centrality of its neighbors. The eigenvector centrality for node $i$ is
the $i$-th element of the vector $x$ defined by the equation
.. math::
Ax = \lambda x
where $A$ is the adjacency matrix of the graph `G` with eigenvalue
$\lambda$. By virtue of the Perron–Frobenius theorem, there is a unique
solution $x$, all of whose entries are positive, if $\lambda$ is the
largest eigenvalue of the adjacency matrix $A$ ([2]_).
Parameters
----------
G : graph
A networkx graph
max_iter : integer, optional (default=100)
Maximum number of iterations in power method.
tol : float, optional (default=1.0e-6)
Error tolerance used to check convergence in power method iteration.
nstart : dictionary, optional (default=None)
Starting value of eigenvector iteration for each node.
weight : None or string, optional (default=None)
If None, all edge weights are considered equal.
Otherwise holds the name of the edge attribute used as weight.
Returns
-------
nodes : dictionary
Dictionary of nodes with eigenvector centrality as the value.
Examples
--------
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> sorted((v, '{:0.2f}'.format(c)) for v, c in centrality.items())
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]
Raises
------
NetworkXPointlessConcept
If the graph `G` is the null graph.
NetworkXError
If each value in `nstart` is zero.
PowerIterationFailedConvergence
If the algorithm fails to converge to the specified tolerance
within the specified number of iterations of the power iteration
method.
See Also
--------
eigenvector_centrality_numpy
pagerank
hits
Notes
-----
The measure was introduced by [1]_ and is discussed in [2]_.
The power iteration method is used to compute the eigenvector and
convergence is **not** guaranteed. Our method stops after ``max_iter``
iterations or when the change in the computed vector between two
iterations is smaller than an error tolerance of
``G.number_of_nodes() * tol``. This implementation uses ($A + I$)
rather than the adjacency matrix $A$ because it shifts the spectrum
to enable discerning the correct eigenvector even for networks with
multiple dominant eigenvalues.
For directed graphs this is "left" eigenvector centrality which corresponds
to the in-edges in the graph. For out-edges eigenvector centrality
first reverse the graph with ``G.reverse()``.
References
----------
.. [1] Phillip Bonacich.
"Power and Centrality: A Family of Measures."
*American Journal of Sociology* 92(5):1170–1182, 1986
<http://www.leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf>
.. [2] Mark E. J. Newman.
*Networks: An Introduction.*
Oxford University Press, USA, 2010, pp. 169.<|endoftext|> |
c95e6332980d73cb8ed275e523f4a22c55fe4ba2c58d765b02d8866673cb9bf4 | def validate(self, application_description):
'\n Queries Zoe for versions and local configuration parameters.\n\n :return:\n '
(data_, status_code) = self._rest_post('/zapp_validate', application_description)
if (status_code != 200):
return False
else:
return True | Queries Zoe for versions and local configuration parameters.
:return: | zoe_cmd/api_lib/validation.py | validate | AtosCodex/atos-zoe | 0 | python | def validate(self, application_description):
'\n Queries Zoe for versions and local configuration parameters.\n\n :return:\n '
(data_, status_code) = self._rest_post('/zapp_validate', application_description)
if (status_code != 200):
return False
else:
return True | def validate(self, application_description):
'\n Queries Zoe for versions and local configuration parameters.\n\n :return:\n '
(data_, status_code) = self._rest_post('/zapp_validate', application_description)
if (status_code != 200):
return False
else:
return True<|docstring|>Queries Zoe for versions and local configuration parameters.
:return:<|endoftext|> |
e87207bb05b36951c5421fdbf3b0cf00b6f9fe81042e140bd3f37d54f4013892 | def start_lab_mode(*, config: Dict[(str, bool)]={'change_ipython_dict_repr': True, 'change_matplotlib_defaults': True, 'change_numpy_print_options': True, 'change_warnings_format': True}) -> None:
"\n Set Kinetics Toolkit to lab mode.\n\n This function does not affect Kinetics Toolkit's inner working. It exists\n mostly for cosmetic reasons, so that working with ktk in an IPython console\n (e.g., Spyder, Jupyter) is more enjoyable, at least to the developer's\n taste. It changes defaults and is not reversible in a given session. The\n usual way to call it is right after importing ktk.\n\n Parameters\n ----------\n config:\n 'change_ipython_dict_repr' :\n True to summarize defaults dict printouts in IPython.\n 'change_matplotlib_defaults' :\n True to change default figure size, autolayout, dpi, line width\n and color order in Matplotlib.\n 'change_numpy_print_options' :\n True to change default print options in numpy to use fixed point\n notation in printouts.\n 'change_logging_defaults' :\n True to change logging module's default to a more extended format\n with file and line number.\n\n Returns\n -------\n None\n\n "
if config['change_ipython_dict_repr']:
try:
import IPython as _IPython
_ip = _IPython.get_ipython()
formatter = _ip.display_formatter.formatters['text/plain']
formatter.for_type(dict, (lambda n, p, cycle: _repr._ktk_format_dict(n, p, cycle)))
except Exception:
pass
if config['change_matplotlib_defaults']:
import matplotlib as _mpl
_mpl.rcParams['figure.figsize'] = [10, 5]
_mpl.rcParams['figure.dpi'] = 75
_mpl.rcParams['lines.linewidth'] = 1
kineticstoolkit.gui.set_color_order('xyz')
if config['change_numpy_print_options']:
import numpy as _np
_np.set_printoptions(suppress=True)
if config['change_warnings_format']:
def formatwarning(message, category, filename, lineno, line=None):
return f'''{category.__name__} [{filename}:{lineno}] {message}
'''
warnings.formatwarning = formatwarning | Set Kinetics Toolkit to lab mode.
This function does not affect Kinetics Toolkit's inner working. It exists
mostly for cosmetic reasons, so that working with ktk in an IPython console
(e.g., Spyder, Jupyter) is more enjoyable, at least to the developer's
taste. It changes defaults and is not reversible in a given session. The
usual way to call it is right after importing ktk.
Parameters
----------
config:
'change_ipython_dict_repr' :
True to summarize defaults dict printouts in IPython.
'change_matplotlib_defaults' :
True to change default figure size, autolayout, dpi, line width
and color order in Matplotlib.
'change_numpy_print_options' :
True to change default print options in numpy to use fixed point
notation in printouts.
'change_logging_defaults' :
True to change logging module's default to a more extended format
with file and line number.
Returns
-------
None | kineticstoolkit/tools.py | start_lab_mode | alcantarar/kineticstoolkit | 13 | python | def start_lab_mode(*, config: Dict[(str, bool)]={'change_ipython_dict_repr': True, 'change_matplotlib_defaults': True, 'change_numpy_print_options': True, 'change_warnings_format': True}) -> None:
"\n Set Kinetics Toolkit to lab mode.\n\n This function does not affect Kinetics Toolkit's inner working. It exists\n mostly for cosmetic reasons, so that working with ktk in an IPython console\n (e.g., Spyder, Jupyter) is more enjoyable, at least to the developer's\n taste. It changes defaults and is not reversible in a given session. The\n usual way to call it is right after importing ktk.\n\n Parameters\n ----------\n config:\n 'change_ipython_dict_repr' :\n True to summarize defaults dict printouts in IPython.\n 'change_matplotlib_defaults' :\n True to change default figure size, autolayout, dpi, line width\n and color order in Matplotlib.\n 'change_numpy_print_options' :\n True to change default print options in numpy to use fixed point\n notation in printouts.\n 'change_logging_defaults' :\n True to change logging module's default to a more extended format\n with file and line number.\n\n Returns\n -------\n None\n\n "
if config['change_ipython_dict_repr']:
try:
import IPython as _IPython
_ip = _IPython.get_ipython()
formatter = _ip.display_formatter.formatters['text/plain']
formatter.for_type(dict, (lambda n, p, cycle: _repr._ktk_format_dict(n, p, cycle)))
except Exception:
pass
if config['change_matplotlib_defaults']:
import matplotlib as _mpl
_mpl.rcParams['figure.figsize'] = [10, 5]
_mpl.rcParams['figure.dpi'] = 75
_mpl.rcParams['lines.linewidth'] = 1
kineticstoolkit.gui.set_color_order('xyz')
if config['change_numpy_print_options']:
import numpy as _np
_np.set_printoptions(suppress=True)
if config['change_warnings_format']:
def formatwarning(message, category, filename, lineno, line=None):
return f'{category.__name__} [{filename}:{lineno}] {message}
'
warnings.formatwarning = formatwarning | def start_lab_mode(*, config: Dict[(str, bool)]={'change_ipython_dict_repr': True, 'change_matplotlib_defaults': True, 'change_numpy_print_options': True, 'change_warnings_format': True}) -> None:
"\n Set Kinetics Toolkit to lab mode.\n\n This function does not affect Kinetics Toolkit's inner working. It exists\n mostly for cosmetic reasons, so that working with ktk in an IPython console\n (e.g., Spyder, Jupyter) is more enjoyable, at least to the developer's\n taste. It changes defaults and is not reversible in a given session. The\n usual way to call it is right after importing ktk.\n\n Parameters\n ----------\n config:\n 'change_ipython_dict_repr' :\n True to summarize defaults dict printouts in IPython.\n 'change_matplotlib_defaults' :\n True to change default figure size, autolayout, dpi, line width\n and color order in Matplotlib.\n 'change_numpy_print_options' :\n True to change default print options in numpy to use fixed point\n notation in printouts.\n 'change_logging_defaults' :\n True to change logging module's default to a more extended format\n with file and line number.\n\n Returns\n -------\n None\n\n "
if config['change_ipython_dict_repr']:
try:
import IPython as _IPython
_ip = _IPython.get_ipython()
formatter = _ip.display_formatter.formatters['text/plain']
formatter.for_type(dict, (lambda n, p, cycle: _repr._ktk_format_dict(n, p, cycle)))
except Exception:
pass
if config['change_matplotlib_defaults']:
import matplotlib as _mpl
_mpl.rcParams['figure.figsize'] = [10, 5]
_mpl.rcParams['figure.dpi'] = 75
_mpl.rcParams['lines.linewidth'] = 1
kineticstoolkit.gui.set_color_order('xyz')
if config['change_numpy_print_options']:
import numpy as _np
_np.set_printoptions(suppress=True)
if config['change_warnings_format']:
def formatwarning(message, category, filename, lineno, line=None):
return f'{category.__name__} [{filename}:{lineno}] {message}
'
warnings.formatwarning = formatwarning<|docstring|>Set Kinetics Toolkit to lab mode.
This function does not affect Kinetics Toolkit's inner working. It exists
mostly for cosmetic reasons, so that working with ktk in an IPython console
(e.g., Spyder, Jupyter) is more enjoyable, at least to the developer's
taste. It changes defaults and is not reversible in a given session. The
usual way to call it is right after importing ktk.
Parameters
----------
config:
'change_ipython_dict_repr' :
True to summarize defaults dict printouts in IPython.
'change_matplotlib_defaults' :
True to change default figure size, autolayout, dpi, line width
and color order in Matplotlib.
'change_numpy_print_options' :
True to change default print options in numpy to use fixed point
notation in printouts.
'change_logging_defaults' :
True to change logging module's default to a more extended format
with file and line number.
Returns
-------
None<|endoftext|> |
5070e56c23e680ab0b6b24a9238e0011de27788fabcefda1198dc7d1e61201c4 | def tutorials() -> None:
'\n Open the Kinetics Toolkits tutorials in a web browser.\n\n Usage: ktk.tutorials()\n\n Warning\n -------\n This function, which has been introduced in 0.3, is still experimental and\n may change signature or behaviour in the future.\n\n '
_webbrowser.open((('file:///' + kineticstoolkit.config.root_folder) + '/tutorials/index.html'), new=2) | Open the Kinetics Toolkits tutorials in a web browser.
Usage: ktk.tutorials()
Warning
-------
This function, which has been introduced in 0.3, is still experimental and
may change signature or behaviour in the future. | kineticstoolkit/tools.py | tutorials | alcantarar/kineticstoolkit | 13 | python | def tutorials() -> None:
'\n Open the Kinetics Toolkits tutorials in a web browser.\n\n Usage: ktk.tutorials()\n\n Warning\n -------\n This function, which has been introduced in 0.3, is still experimental and\n may change signature or behaviour in the future.\n\n '
_webbrowser.open((('file:///' + kineticstoolkit.config.root_folder) + '/tutorials/index.html'), new=2) | def tutorials() -> None:
'\n Open the Kinetics Toolkits tutorials in a web browser.\n\n Usage: ktk.tutorials()\n\n Warning\n -------\n This function, which has been introduced in 0.3, is still experimental and\n may change signature or behaviour in the future.\n\n '
_webbrowser.open((('file:///' + kineticstoolkit.config.root_folder) + '/tutorials/index.html'), new=2)<|docstring|>Open the Kinetics Toolkits tutorials in a web browser.
Usage: ktk.tutorials()
Warning
-------
This function, which has been introduced in 0.3, is still experimental and
may change signature or behaviour in the future.<|endoftext|> |
8a214b63bada83612d4f6785b471e3b5f653c174c3bd2d5ab5c1d7cfc783c389 | def make_jump_url(base_message: Message, dispand_message: Message, extra_messages: list[Message]) -> str:
'\n make jump url which include more information\n :param base_message: メッセージリンクが貼られていたメッセージ\n :param dispand_message: 展開中のメッセージ\n :param extra_messages: 展開する際にでた二つ目以降のメッセージ(e.g. 画像やembed)\n :return: 混入が完了したメッセージリンク\n '
return f"{dispand_message.jump_url}?base_aid={dispand_message.author.id}&aid={base_message.author.id}&extra={','.join((str(msg.id) for msg in extra_messages))}" | make jump url which include more information
:param base_message: メッセージリンクが貼られていたメッセージ
:param dispand_message: 展開中のメッセージ
:param extra_messages: 展開する際にでた二つ目以降のメッセージ(e.g. 画像やembed)
:return: 混入が完了したメッセージリンク | dispander/module.py | make_jump_url | hawk-tomy/dispander | 0 | python | def make_jump_url(base_message: Message, dispand_message: Message, extra_messages: list[Message]) -> str:
'\n make jump url which include more information\n :param base_message: メッセージリンクが貼られていたメッセージ\n :param dispand_message: 展開中のメッセージ\n :param extra_messages: 展開する際にでた二つ目以降のメッセージ(e.g. 画像やembed)\n :return: 混入が完了したメッセージリンク\n '
return f"{dispand_message.jump_url}?base_aid={dispand_message.author.id}&aid={base_message.author.id}&extra={','.join((str(msg.id) for msg in extra_messages))}" | def make_jump_url(base_message: Message, dispand_message: Message, extra_messages: list[Message]) -> str:
'\n make jump url which include more information\n :param base_message: メッセージリンクが貼られていたメッセージ\n :param dispand_message: 展開中のメッセージ\n :param extra_messages: 展開する際にでた二つ目以降のメッセージ(e.g. 画像やembed)\n :return: 混入が完了したメッセージリンク\n '
return f"{dispand_message.jump_url}?base_aid={dispand_message.author.id}&aid={base_message.author.id}&extra={','.join((str(msg.id) for msg in extra_messages))}"<|docstring|>make jump url which include more information
:param base_message: メッセージリンクが貼られていたメッセージ
:param dispand_message: 展開中のメッセージ
:param extra_messages: 展開する際にでた二つ目以降のメッセージ(e.g. 画像やembed)
:return: 混入が完了したメッセージリンク<|endoftext|> |
6f9629ab4ef725f4c5ab6e64540b1de4d118cb43003108041d5212c0bd2884e4 | def from_jump_url(url: str) -> dict[(str, str)]:
'\n メッセージリンクから情報を取得します。\n :param url: メッセージリンク\n :return: dict\n '
base_url_match = re.match((regex_discord_message_url + regex_extra_url), url)
data = base_url_match.groupdict()
return {'base_author_id': int(data['base_author_id']), 'author_id': int(data['author_id']), 'extra_messages': ([int(_id) for _id in data['extra_messages'].split(',')] if data['extra_messages'] else [])} | メッセージリンクから情報を取得します。
:param url: メッセージリンク
:return: dict | dispander/module.py | from_jump_url | hawk-tomy/dispander | 0 | python | def from_jump_url(url: str) -> dict[(str, str)]:
'\n メッセージリンクから情報を取得します。\n :param url: メッセージリンク\n :return: dict\n '
base_url_match = re.match((regex_discord_message_url + regex_extra_url), url)
data = base_url_match.groupdict()
return {'base_author_id': int(data['base_author_id']), 'author_id': int(data['author_id']), 'extra_messages': ([int(_id) for _id in data['extra_messages'].split(',')] if data['extra_messages'] else [])} | def from_jump_url(url: str) -> dict[(str, str)]:
'\n メッセージリンクから情報を取得します。\n :param url: メッセージリンク\n :return: dict\n '
base_url_match = re.match((regex_discord_message_url + regex_extra_url), url)
data = base_url_match.groupdict()
return {'base_author_id': int(data['base_author_id']), 'author_id': int(data['author_id']), 'extra_messages': ([int(_id) for _id in data['extra_messages'].split(',')] if data['extra_messages'] else [])}<|docstring|>メッセージリンクから情報を取得します。
:param url: メッセージリンク
:return: dict<|endoftext|> |
e636537e7860c87d01257af808e2ae6cafc2c264a2d7b79db1c4859553be7c65 | def lenovo_umount_virtual_media(ip, login_account, login_password, image, mounttype):
'Unmount virtual media, supporting both 18D and 19A version of Lenovo XCC.\n :params ip: BMC IP address\n :type ip: string\n :params login_account: BMC user name\n :type login_account: string\n :params login_password: BMC user password\n :type login_password: string\n :param mounttype: Types of mount virtual media.\n :type mounttype:string\n :params image: This value shall specify the eject virtual media image mame\n :type image:string\n :returns: returns eject virtual media iso result when succeeded or error message when failed\n '
result = {}
login_host = ('https://' + ip)
try:
REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE)
REDFISH_OBJ.login(auth='basic')
except:
traceback.print_exc()
result = {'ret': False, 'msg': 'Please check the username, password, IP is correct\n'}
return result
try:
response_base_url = REDFISH_OBJ.get('/redfish/v1', None)
if (response_base_url.status == 200):
account_managers_url = response_base_url.dict['Managers']['@odata.id']
else:
error_message = utils.get_extended_error(response_base_url)
result = {'ret': False, 'msg': (" Url '/redfish/v1' response Error code %s \nerror_message: %s" % (response_base_url.status, error_message))}
return result
response_managers_url = REDFISH_OBJ.get(account_managers_url, None)
if (response_managers_url.status == 200):
count = response_managers_url.dict['example@example.com']
for i in range(count):
manager_url = response_managers_url.dict['Members'][i]['@odata.id']
response_manager_url = REDFISH_OBJ.get(manager_url, None)
if (response_manager_url.status == 200):
virtual_media_url = response_manager_url.dict['VirtualMedia']['@odata.id']
remotecontrol_url = ''
remotemap_url = ''
if ('Oem' in response_manager_url.dict):
Oem_dict = response_manager_url.dict['Oem']
if (('Ami' not in Oem_dict) and ('Lenovo' in Oem_dict)):
remotemap_url = Oem_dict['Lenovo']['RemoteMap']['@odata.id']
remotecontrol_url = Oem_dict['Lenovo']['RemoteControl']['@odata.id']
else:
error_message = utils.get_extended_error(response_manager_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (manager_url, response_manager_url.status, error_message))}
return result
response_virtual_media = REDFISH_OBJ.get(virtual_media_url, None)
if (response_virtual_media.status == 200):
members_list = response_virtual_media.dict['Members']
else:
error_message = utils.get_extended_error(response_virtual_media)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (virtual_media_url, response_virtual_media.status, error_message))}
return result
if (len(members_list) == 10):
result = umount_virtual_media(REDFISH_OBJ, members_list, image)
elif (len(members_list) <= 4):
result = umount_virtual_media_from_cd(REDFISH_OBJ, members_list, image)
elif (mounttype == 'Network'):
result = umount_all_virtual_from_network(REDFISH_OBJ, remotemap_url)
else:
result = umount_virtual_media_from_rdoc(REDFISH_OBJ, remotecontrol_url, image)
else:
error_message = utils.get_extended_error(response_managers_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (account_managers_url, response_managers_url.status, error_message))}
except Exception as e:
traceback.print_exc()
result = {'ret': False, 'msg': ('error_message: %s' % e)}
finally:
try:
REDFISH_OBJ.logout()
except:
pass
return result | Unmount virtual media, supporting both 18D and 19A version of Lenovo XCC.
:params ip: BMC IP address
:type ip: string
:params login_account: BMC user name
:type login_account: string
:params login_password: BMC user password
:type login_password: string
:param mounttype: Types of mount virtual media.
:type mounttype:string
:params image: This value shall specify the eject virtual media image mame
:type image:string
:returns: returns eject virtual media iso result when succeeded or error message when failed | examples/lenovo_umount_virtual_media.py | lenovo_umount_virtual_media | wgf0210/python-redfish-lenovo | 56 | python | def lenovo_umount_virtual_media(ip, login_account, login_password, image, mounttype):
'Unmount virtual media, supporting both 18D and 19A version of Lenovo XCC.\n :params ip: BMC IP address\n :type ip: string\n :params login_account: BMC user name\n :type login_account: string\n :params login_password: BMC user password\n :type login_password: string\n :param mounttype: Types of mount virtual media.\n :type mounttype:string\n :params image: This value shall specify the eject virtual media image mame\n :type image:string\n :returns: returns eject virtual media iso result when succeeded or error message when failed\n '
result = {}
login_host = ('https://' + ip)
try:
REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE)
REDFISH_OBJ.login(auth='basic')
except:
traceback.print_exc()
result = {'ret': False, 'msg': 'Please check the username, password, IP is correct\n'}
return result
try:
response_base_url = REDFISH_OBJ.get('/redfish/v1', None)
if (response_base_url.status == 200):
account_managers_url = response_base_url.dict['Managers']['@odata.id']
else:
error_message = utils.get_extended_error(response_base_url)
result = {'ret': False, 'msg': (" Url '/redfish/v1' response Error code %s \nerror_message: %s" % (response_base_url.status, error_message))}
return result
response_managers_url = REDFISH_OBJ.get(account_managers_url, None)
if (response_managers_url.status == 200):
count = response_managers_url.dict['example@example.com']
for i in range(count):
manager_url = response_managers_url.dict['Members'][i]['@odata.id']
response_manager_url = REDFISH_OBJ.get(manager_url, None)
if (response_manager_url.status == 200):
virtual_media_url = response_manager_url.dict['VirtualMedia']['@odata.id']
remotecontrol_url =
remotemap_url =
if ('Oem' in response_manager_url.dict):
Oem_dict = response_manager_url.dict['Oem']
if (('Ami' not in Oem_dict) and ('Lenovo' in Oem_dict)):
remotemap_url = Oem_dict['Lenovo']['RemoteMap']['@odata.id']
remotecontrol_url = Oem_dict['Lenovo']['RemoteControl']['@odata.id']
else:
error_message = utils.get_extended_error(response_manager_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (manager_url, response_manager_url.status, error_message))}
return result
response_virtual_media = REDFISH_OBJ.get(virtual_media_url, None)
if (response_virtual_media.status == 200):
members_list = response_virtual_media.dict['Members']
else:
error_message = utils.get_extended_error(response_virtual_media)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (virtual_media_url, response_virtual_media.status, error_message))}
return result
if (len(members_list) == 10):
result = umount_virtual_media(REDFISH_OBJ, members_list, image)
elif (len(members_list) <= 4):
result = umount_virtual_media_from_cd(REDFISH_OBJ, members_list, image)
elif (mounttype == 'Network'):
result = umount_all_virtual_from_network(REDFISH_OBJ, remotemap_url)
else:
result = umount_virtual_media_from_rdoc(REDFISH_OBJ, remotecontrol_url, image)
else:
error_message = utils.get_extended_error(response_managers_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (account_managers_url, response_managers_url.status, error_message))}
except Exception as e:
traceback.print_exc()
result = {'ret': False, 'msg': ('error_message: %s' % e)}
finally:
try:
REDFISH_OBJ.logout()
except:
pass
return result | def lenovo_umount_virtual_media(ip, login_account, login_password, image, mounttype):
'Unmount virtual media, supporting both 18D and 19A version of Lenovo XCC.\n :params ip: BMC IP address\n :type ip: string\n :params login_account: BMC user name\n :type login_account: string\n :params login_password: BMC user password\n :type login_password: string\n :param mounttype: Types of mount virtual media.\n :type mounttype:string\n :params image: This value shall specify the eject virtual media image mame\n :type image:string\n :returns: returns eject virtual media iso result when succeeded or error message when failed\n '
result = {}
login_host = ('https://' + ip)
try:
REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE)
REDFISH_OBJ.login(auth='basic')
except:
traceback.print_exc()
result = {'ret': False, 'msg': 'Please check the username, password, IP is correct\n'}
return result
try:
response_base_url = REDFISH_OBJ.get('/redfish/v1', None)
if (response_base_url.status == 200):
account_managers_url = response_base_url.dict['Managers']['@odata.id']
else:
error_message = utils.get_extended_error(response_base_url)
result = {'ret': False, 'msg': (" Url '/redfish/v1' response Error code %s \nerror_message: %s" % (response_base_url.status, error_message))}
return result
response_managers_url = REDFISH_OBJ.get(account_managers_url, None)
if (response_managers_url.status == 200):
count = response_managers_url.dict['example@example.com']
for i in range(count):
manager_url = response_managers_url.dict['Members'][i]['@odata.id']
response_manager_url = REDFISH_OBJ.get(manager_url, None)
if (response_manager_url.status == 200):
virtual_media_url = response_manager_url.dict['VirtualMedia']['@odata.id']
remotecontrol_url =
remotemap_url =
if ('Oem' in response_manager_url.dict):
Oem_dict = response_manager_url.dict['Oem']
if (('Ami' not in Oem_dict) and ('Lenovo' in Oem_dict)):
remotemap_url = Oem_dict['Lenovo']['RemoteMap']['@odata.id']
remotecontrol_url = Oem_dict['Lenovo']['RemoteControl']['@odata.id']
else:
error_message = utils.get_extended_error(response_manager_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (manager_url, response_manager_url.status, error_message))}
return result
response_virtual_media = REDFISH_OBJ.get(virtual_media_url, None)
if (response_virtual_media.status == 200):
members_list = response_virtual_media.dict['Members']
else:
error_message = utils.get_extended_error(response_virtual_media)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (virtual_media_url, response_virtual_media.status, error_message))}
return result
if (len(members_list) == 10):
result = umount_virtual_media(REDFISH_OBJ, members_list, image)
elif (len(members_list) <= 4):
result = umount_virtual_media_from_cd(REDFISH_OBJ, members_list, image)
elif (mounttype == 'Network'):
result = umount_all_virtual_from_network(REDFISH_OBJ, remotemap_url)
else:
result = umount_virtual_media_from_rdoc(REDFISH_OBJ, remotecontrol_url, image)
else:
error_message = utils.get_extended_error(response_managers_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (account_managers_url, response_managers_url.status, error_message))}
except Exception as e:
traceback.print_exc()
result = {'ret': False, 'msg': ('error_message: %s' % e)}
finally:
try:
REDFISH_OBJ.logout()
except:
pass
return result<|docstring|>Unmount virtual media, supporting both 18D and 19A version of Lenovo XCC.
:params ip: BMC IP address
:type ip: string
:params login_account: BMC user name
:type login_account: string
:params login_password: BMC user password
:type login_password: string
:param mounttype: Types of mount virtual media.
:type mounttype:string
:params image: This value shall specify the eject virtual media image mame
:type image:string
:returns: returns eject virtual media iso result when succeeded or error message when failed<|endoftext|> |
a7afa602de4f54d2e507b6caba533e63f9573888a7a0f18ee99467724b022504 | def umount_virtual_media_from_cd(REDFISH_OBJ, members_list, image):
'\n This function uses the post method to umount virtual media, support AMD server.\n '
for members in members_list:
members_url = members['@odata.id']
response_members = REDFISH_OBJ.get(members_url, None)
if (response_members.status == 200):
image_name = response_members.dict['ImageName']
eject_media_url = response_members.dict['Actions']['#VirtualMedia.EjectMedia']['target']
else:
error_message = utils.get_extended_error(response_members)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response_members.status, error_message))}
return result
if (image_name == image):
body = {}
response = REDFISH_OBJ.post(eject_media_url, body=body)
if (response.status == 204):
result = {'ret': True, 'msg': ("'%s' Umount successfully" % image)}
return result
else:
error_message = utils.get_extended_error(response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (eject_media_url, response.status, error_message))}
return result
else:
continue
result = {'ret': False, 'msg': 'Please check the image name is correct and has been mounted.'}
return result | This function uses the post method to umount virtual media, support AMD server. | examples/lenovo_umount_virtual_media.py | umount_virtual_media_from_cd | wgf0210/python-redfish-lenovo | 56 | python | def umount_virtual_media_from_cd(REDFISH_OBJ, members_list, image):
'\n \n '
for members in members_list:
members_url = members['@odata.id']
response_members = REDFISH_OBJ.get(members_url, None)
if (response_members.status == 200):
image_name = response_members.dict['ImageName']
eject_media_url = response_members.dict['Actions']['#VirtualMedia.EjectMedia']['target']
else:
error_message = utils.get_extended_error(response_members)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response_members.status, error_message))}
return result
if (image_name == image):
body = {}
response = REDFISH_OBJ.post(eject_media_url, body=body)
if (response.status == 204):
result = {'ret': True, 'msg': ("'%s' Umount successfully" % image)}
return result
else:
error_message = utils.get_extended_error(response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (eject_media_url, response.status, error_message))}
return result
else:
continue
result = {'ret': False, 'msg': 'Please check the image name is correct and has been mounted.'}
return result | def umount_virtual_media_from_cd(REDFISH_OBJ, members_list, image):
'\n \n '
for members in members_list:
members_url = members['@odata.id']
response_members = REDFISH_OBJ.get(members_url, None)
if (response_members.status == 200):
image_name = response_members.dict['ImageName']
eject_media_url = response_members.dict['Actions']['#VirtualMedia.EjectMedia']['target']
else:
error_message = utils.get_extended_error(response_members)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response_members.status, error_message))}
return result
if (image_name == image):
body = {}
response = REDFISH_OBJ.post(eject_media_url, body=body)
if (response.status == 204):
result = {'ret': True, 'msg': ("'%s' Umount successfully" % image)}
return result
else:
error_message = utils.get_extended_error(response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (eject_media_url, response.status, error_message))}
return result
else:
continue
result = {'ret': False, 'msg': 'Please check the image name is correct and has been mounted.'}
return result<|docstring|>This function uses the post method to umount virtual media, support AMD server.<|endoftext|> |
514a4320f78e2fcd346c1a79272cd02bdec2e917214394f20fae63187385f3df | def umount_virtual_media(REDFISH_OBJ, members_list, image):
'\n This function uses the patch method to umount virtual media, support 19A version of XCC.\n '
for members in members_list:
members_url = members['@odata.id']
if (not members_url.split('/')[(- 1)].startswith('Remote')):
response_members = REDFISH_OBJ.get(members_url, None)
if (response_members.status == 200):
image_name = response_members.dict['ImageName']
else:
error_message = utils.get_extended_error(response_members)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response_members.status, error_message))}
return result
if (image_name == image):
body = {'Image': None}
response = REDFISH_OBJ.patch(members_url, body=body)
if (response.status == 200):
result = {'ret': True, 'msg': ("'%s' Umount successfully" % image)}
return result
else:
error_message = utils.get_extended_error(response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response.status, error_message))}
return result
else:
continue
result = {'ret': False, 'msg': 'Please check the image name is correct and has been mounted.'}
return result | This function uses the patch method to umount virtual media, support 19A version of XCC. | examples/lenovo_umount_virtual_media.py | umount_virtual_media | wgf0210/python-redfish-lenovo | 56 | python | def umount_virtual_media(REDFISH_OBJ, members_list, image):
'\n \n '
for members in members_list:
members_url = members['@odata.id']
if (not members_url.split('/')[(- 1)].startswith('Remote')):
response_members = REDFISH_OBJ.get(members_url, None)
if (response_members.status == 200):
image_name = response_members.dict['ImageName']
else:
error_message = utils.get_extended_error(response_members)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response_members.status, error_message))}
return result
if (image_name == image):
body = {'Image': None}
response = REDFISH_OBJ.patch(members_url, body=body)
if (response.status == 200):
result = {'ret': True, 'msg': ("'%s' Umount successfully" % image)}
return result
else:
error_message = utils.get_extended_error(response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response.status, error_message))}
return result
else:
continue
result = {'ret': False, 'msg': 'Please check the image name is correct and has been mounted.'}
return result | def umount_virtual_media(REDFISH_OBJ, members_list, image):
'\n \n '
for members in members_list:
members_url = members['@odata.id']
if (not members_url.split('/')[(- 1)].startswith('Remote')):
response_members = REDFISH_OBJ.get(members_url, None)
if (response_members.status == 200):
image_name = response_members.dict['ImageName']
else:
error_message = utils.get_extended_error(response_members)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response_members.status, error_message))}
return result
if (image_name == image):
body = {'Image': None}
response = REDFISH_OBJ.patch(members_url, body=body)
if (response.status == 200):
result = {'ret': True, 'msg': ("'%s' Umount successfully" % image)}
return result
else:
error_message = utils.get_extended_error(response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (members_url, response.status, error_message))}
return result
else:
continue
result = {'ret': False, 'msg': 'Please check the image name is correct and has been mounted.'}
return result<|docstring|>This function uses the patch method to umount virtual media, support 19A version of XCC.<|endoftext|> |
1dd42723aa0246f4cf147b9e6360e1be3f067062eb0f716a920a17ae818e6433 | def umount_virtual_media_from_rdoc(REDFISH_OBJ, remotecontrol_url, image):
'\n This function use the Lenovo OEM extensions to umount virtual media from RDOC, support 18D version of XCC.\n '
response_remotecontrol_url = REDFISH_OBJ.get(remotecontrol_url, None)
if (response_remotecontrol_url.status == 200):
mount_image_url = response_remotecontrol_url.dict['MountImages']['@odata.id']
else:
error_message = utils.get_extended_error(response_remotecontrol_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (remotecontrol_url, response_remotecontrol_url.status, error_message))}
return result
response_mount_images = REDFISH_OBJ.get(mount_image_url, None)
if (response_mount_images.status == 200):
image_url_list = response_mount_images.dict['Members']
else:
error_message = utils.get_extended_error(response_mount_images)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (mount_image_url, response_mount_images.status, error_message))}
return result
if (image == 'all'):
for image_url in image_url_list:
image_url = image_url['@odata.id']
if image_url.split('/')[(- 1)].startswith('RDOC'):
delete_image_response = REDFISH_OBJ.delete(image_url, None)
if (delete_image_response.status not in [200, 204]):
error_message = utils.get_extended_error(delete_image_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, delete_image_response.status, error_message))}
return result
else:
continue
result = {'ret': True, 'msg': 'Umount all virtual media successfully.'}
return result
else:
for image_url in image_url_list:
image_url = image_url['@odata.id']
get_image_response = REDFISH_OBJ.get(image_url, None)
if (get_image_response.status == 200):
mount_iso_name = get_image_response.dict['Name']
if (image == mount_iso_name):
umount_iso_response = REDFISH_OBJ.delete(image_url, None)
if (umount_iso_response.status in [200, 204]):
result = {'ret': True, 'msg': ('Virtual media iso (%s) umount successfully' % image)}
return result
else:
error_message = utils.get_extended_error(umount_iso_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, umount_iso_response.status, error_message))}
return result
else:
continue
else:
error_message = utils.get_extended_error(get_image_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, get_image_response.status, error_message))}
return result
result = {'ret': False, 'msg': 'Please check the iso name is correct and has been mounted.'}
return result | This function use the Lenovo OEM extensions to umount virtual media from RDOC, support 18D version of XCC. | examples/lenovo_umount_virtual_media.py | umount_virtual_media_from_rdoc | wgf0210/python-redfish-lenovo | 56 | python | def umount_virtual_media_from_rdoc(REDFISH_OBJ, remotecontrol_url, image):
'\n \n '
response_remotecontrol_url = REDFISH_OBJ.get(remotecontrol_url, None)
if (response_remotecontrol_url.status == 200):
mount_image_url = response_remotecontrol_url.dict['MountImages']['@odata.id']
else:
error_message = utils.get_extended_error(response_remotecontrol_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (remotecontrol_url, response_remotecontrol_url.status, error_message))}
return result
response_mount_images = REDFISH_OBJ.get(mount_image_url, None)
if (response_mount_images.status == 200):
image_url_list = response_mount_images.dict['Members']
else:
error_message = utils.get_extended_error(response_mount_images)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (mount_image_url, response_mount_images.status, error_message))}
return result
if (image == 'all'):
for image_url in image_url_list:
image_url = image_url['@odata.id']
if image_url.split('/')[(- 1)].startswith('RDOC'):
delete_image_response = REDFISH_OBJ.delete(image_url, None)
if (delete_image_response.status not in [200, 204]):
error_message = utils.get_extended_error(delete_image_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, delete_image_response.status, error_message))}
return result
else:
continue
result = {'ret': True, 'msg': 'Umount all virtual media successfully.'}
return result
else:
for image_url in image_url_list:
image_url = image_url['@odata.id']
get_image_response = REDFISH_OBJ.get(image_url, None)
if (get_image_response.status == 200):
mount_iso_name = get_image_response.dict['Name']
if (image == mount_iso_name):
umount_iso_response = REDFISH_OBJ.delete(image_url, None)
if (umount_iso_response.status in [200, 204]):
result = {'ret': True, 'msg': ('Virtual media iso (%s) umount successfully' % image)}
return result
else:
error_message = utils.get_extended_error(umount_iso_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, umount_iso_response.status, error_message))}
return result
else:
continue
else:
error_message = utils.get_extended_error(get_image_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, get_image_response.status, error_message))}
return result
result = {'ret': False, 'msg': 'Please check the iso name is correct and has been mounted.'}
return result | def umount_virtual_media_from_rdoc(REDFISH_OBJ, remotecontrol_url, image):
'\n \n '
response_remotecontrol_url = REDFISH_OBJ.get(remotecontrol_url, None)
if (response_remotecontrol_url.status == 200):
mount_image_url = response_remotecontrol_url.dict['MountImages']['@odata.id']
else:
error_message = utils.get_extended_error(response_remotecontrol_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (remotecontrol_url, response_remotecontrol_url.status, error_message))}
return result
response_mount_images = REDFISH_OBJ.get(mount_image_url, None)
if (response_mount_images.status == 200):
image_url_list = response_mount_images.dict['Members']
else:
error_message = utils.get_extended_error(response_mount_images)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (mount_image_url, response_mount_images.status, error_message))}
return result
if (image == 'all'):
for image_url in image_url_list:
image_url = image_url['@odata.id']
if image_url.split('/')[(- 1)].startswith('RDOC'):
delete_image_response = REDFISH_OBJ.delete(image_url, None)
if (delete_image_response.status not in [200, 204]):
error_message = utils.get_extended_error(delete_image_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, delete_image_response.status, error_message))}
return result
else:
continue
result = {'ret': True, 'msg': 'Umount all virtual media successfully.'}
return result
else:
for image_url in image_url_list:
image_url = image_url['@odata.id']
get_image_response = REDFISH_OBJ.get(image_url, None)
if (get_image_response.status == 200):
mount_iso_name = get_image_response.dict['Name']
if (image == mount_iso_name):
umount_iso_response = REDFISH_OBJ.delete(image_url, None)
if (umount_iso_response.status in [200, 204]):
result = {'ret': True, 'msg': ('Virtual media iso (%s) umount successfully' % image)}
return result
else:
error_message = utils.get_extended_error(umount_iso_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, umount_iso_response.status, error_message))}
return result
else:
continue
else:
error_message = utils.get_extended_error(get_image_response)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (image_url, get_image_response.status, error_message))}
return result
result = {'ret': False, 'msg': 'Please check the iso name is correct and has been mounted.'}
return result<|docstring|>This function use the Lenovo OEM extensions to umount virtual media from RDOC, support 18D version of XCC.<|endoftext|> |
f4b59a77892ec91e63d65f9f381a5c3f0e233d198971236132832c9111e5f88a | def umount_all_virtual_from_network(REDFISH_OBJ, remotemap_url):
'\n This function use the Lenovo OEM extensions to umount virtual media from Network, support 18D version of XCC.\n '
response_remotemap_url = REDFISH_OBJ.get(remotemap_url, None)
if (response_remotemap_url.status == 200):
umount_image_url = response_remotemap_url.dict['Actions']['#LenovoRemoteMapService.UMount']['target']
response_umount_image = REDFISH_OBJ.post(umount_image_url, None)
if (response_umount_image.status in [200, 204]):
result = {'ret': True, 'msg': 'All Media File from Network umount successfully'}
return result
else:
error_message = utils.get_extended_error(response_umount_image)
result = {'ret': False, 'msg': ("Umount media iso failed, '%s' response Error code %s \nerror_message: %s" % (umount_image_url, response_umount_image.status, error_message))}
return result
else:
error_message = utils.get_extended_error(response_remotemap_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (remotemap_url, response_remotemap_url.status, error_message))}
return result | This function use the Lenovo OEM extensions to umount virtual media from Network, support 18D version of XCC. | examples/lenovo_umount_virtual_media.py | umount_all_virtual_from_network | wgf0210/python-redfish-lenovo | 56 | python | def umount_all_virtual_from_network(REDFISH_OBJ, remotemap_url):
'\n \n '
response_remotemap_url = REDFISH_OBJ.get(remotemap_url, None)
if (response_remotemap_url.status == 200):
umount_image_url = response_remotemap_url.dict['Actions']['#LenovoRemoteMapService.UMount']['target']
response_umount_image = REDFISH_OBJ.post(umount_image_url, None)
if (response_umount_image.status in [200, 204]):
result = {'ret': True, 'msg': 'All Media File from Network umount successfully'}
return result
else:
error_message = utils.get_extended_error(response_umount_image)
result = {'ret': False, 'msg': ("Umount media iso failed, '%s' response Error code %s \nerror_message: %s" % (umount_image_url, response_umount_image.status, error_message))}
return result
else:
error_message = utils.get_extended_error(response_remotemap_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (remotemap_url, response_remotemap_url.status, error_message))}
return result | def umount_all_virtual_from_network(REDFISH_OBJ, remotemap_url):
'\n \n '
response_remotemap_url = REDFISH_OBJ.get(remotemap_url, None)
if (response_remotemap_url.status == 200):
umount_image_url = response_remotemap_url.dict['Actions']['#LenovoRemoteMapService.UMount']['target']
response_umount_image = REDFISH_OBJ.post(umount_image_url, None)
if (response_umount_image.status in [200, 204]):
result = {'ret': True, 'msg': 'All Media File from Network umount successfully'}
return result
else:
error_message = utils.get_extended_error(response_umount_image)
result = {'ret': False, 'msg': ("Umount media iso failed, '%s' response Error code %s \nerror_message: %s" % (umount_image_url, response_umount_image.status, error_message))}
return result
else:
error_message = utils.get_extended_error(response_remotemap_url)
result = {'ret': False, 'msg': ("Url '%s' response Error code %s \nerror_message: %s" % (remotemap_url, response_remotemap_url.status, error_message))}
return result<|docstring|>This function use the Lenovo OEM extensions to umount virtual media from Network, support 18D version of XCC.<|endoftext|> |
4c9cd97b59f7252e52fd65cd6cd1d87f9f724bf4eda5ea77f2cb210fa7722206 | def add_parameter():
'Add mount media iso parameter'
argget = utils.create_common_parameter_list()
add_helpmessage(argget)
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
parameter_info['image'] = args.image
parameter_info['mounttype'] = args.mounttype
return parameter_info | Add mount media iso parameter | examples/lenovo_umount_virtual_media.py | add_parameter | wgf0210/python-redfish-lenovo | 56 | python | def add_parameter():
argget = utils.create_common_parameter_list()
add_helpmessage(argget)
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
parameter_info['image'] = args.image
parameter_info['mounttype'] = args.mounttype
return parameter_info | def add_parameter():
argget = utils.create_common_parameter_list()
add_helpmessage(argget)
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
parameter_info['image'] = args.image
parameter_info['mounttype'] = args.mounttype
return parameter_info<|docstring|>Add mount media iso parameter<|endoftext|> |
ef9c8b8949a981747e65c89d7ca3bff1bb4b7be85d51ed8c060f54b2f4964e5b | def driver_needed(func):
'\n Decorator for WhatsappObjectWithId methods that need to communicate with the browser\n\n It ensures that the object receives a driver instance at construction\n\n :param func: WhatsappObjectWithId method\n :return: Wrapped method\n '
def wrapped(self, *args):
if (not self.driver):
raise AttributeError('No driver passed to object')
return func(self, *args)
return wrapped | Decorator for WhatsappObjectWithId methods that need to communicate with the browser
It ensures that the object receives a driver instance at construction
:param func: WhatsappObjectWithId method
:return: Wrapped method | webwhatsapi/objects/whatsapp_object.py | driver_needed | aroyalheart/WebWhatsapp-Wrapper | 1,690 | python | def driver_needed(func):
'\n Decorator for WhatsappObjectWithId methods that need to communicate with the browser\n\n It ensures that the object receives a driver instance at construction\n\n :param func: WhatsappObjectWithId method\n :return: Wrapped method\n '
def wrapped(self, *args):
if (not self.driver):
raise AttributeError('No driver passed to object')
return func(self, *args)
return wrapped | def driver_needed(func):
'\n Decorator for WhatsappObjectWithId methods that need to communicate with the browser\n\n It ensures that the object receives a driver instance at construction\n\n :param func: WhatsappObjectWithId method\n :return: Wrapped method\n '
def wrapped(self, *args):
if (not self.driver):
raise AttributeError('No driver passed to object')
return func(self, *args)
return wrapped<|docstring|>Decorator for WhatsappObjectWithId methods that need to communicate with the browser
It ensures that the object receives a driver instance at construction
:param func: WhatsappObjectWithId method
:return: Wrapped method<|endoftext|> |
1f5eb0cc336ee6dd14e0fec6f6fc9360228efa79c0834e9f96e1d837c3ce0823 | def __init__(self, js_obj, driver=None):
'\n Constructor\n\n :param js_obj: Whatsapp JS object to wrap\n :type js_obj: dict\n :param driver: Optional driver instance\n :type driver: WhatsAPIDriver\n '
self._js_obj = js_obj
self._driver = ref(driver) | Constructor
:param js_obj: Whatsapp JS object to wrap
:type js_obj: dict
:param driver: Optional driver instance
:type driver: WhatsAPIDriver | webwhatsapi/objects/whatsapp_object.py | __init__ | aroyalheart/WebWhatsapp-Wrapper | 1,690 | python | def __init__(self, js_obj, driver=None):
'\n Constructor\n\n :param js_obj: Whatsapp JS object to wrap\n :type js_obj: dict\n :param driver: Optional driver instance\n :type driver: WhatsAPIDriver\n '
self._js_obj = js_obj
self._driver = ref(driver) | def __init__(self, js_obj, driver=None):
'\n Constructor\n\n :param js_obj: Whatsapp JS object to wrap\n :type js_obj: dict\n :param driver: Optional driver instance\n :type driver: WhatsAPIDriver\n '
self._js_obj = js_obj
self._driver = ref(driver)<|docstring|>Constructor
:param js_obj: Whatsapp JS object to wrap
:type js_obj: dict
:param driver: Optional driver instance
:type driver: WhatsAPIDriver<|endoftext|> |
b577f55904ee0399d98927346ff004c489d0d99777b936ffda0af94d658bbb82 | def __init__(self, js_obj, driver=None):
'\n Constructor\n\n :param js_obj: Whatsapp JS object to wrap\n :type js_obj: dict\n :param driver: Optional driver instance\n :type driver: WhatsAPIDriver\n '
super(WhatsappObjectWithId, self).__init__(js_obj, driver)
if ('id' in js_obj):
try:
self.id = js_obj['id']['_serialized']
except Exception:
self.id = js_obj['id']
if ('name' in js_obj):
self.name = js_obj['name'] | Constructor
:param js_obj: Whatsapp JS object to wrap
:type js_obj: dict
:param driver: Optional driver instance
:type driver: WhatsAPIDriver | webwhatsapi/objects/whatsapp_object.py | __init__ | aroyalheart/WebWhatsapp-Wrapper | 1,690 | python | def __init__(self, js_obj, driver=None):
'\n Constructor\n\n :param js_obj: Whatsapp JS object to wrap\n :type js_obj: dict\n :param driver: Optional driver instance\n :type driver: WhatsAPIDriver\n '
super(WhatsappObjectWithId, self).__init__(js_obj, driver)
if ('id' in js_obj):
try:
self.id = js_obj['id']['_serialized']
except Exception:
self.id = js_obj['id']
if ('name' in js_obj):
self.name = js_obj['name'] | def __init__(self, js_obj, driver=None):
'\n Constructor\n\n :param js_obj: Whatsapp JS object to wrap\n :type js_obj: dict\n :param driver: Optional driver instance\n :type driver: WhatsAPIDriver\n '
super(WhatsappObjectWithId, self).__init__(js_obj, driver)
if ('id' in js_obj):
try:
self.id = js_obj['id']['_serialized']
except Exception:
self.id = js_obj['id']
if ('name' in js_obj):
self.name = js_obj['name']<|docstring|>Constructor
:param js_obj: Whatsapp JS object to wrap
:type js_obj: dict
:param driver: Optional driver instance
:type driver: WhatsAPIDriver<|endoftext|> |
cd66c95193ab5efe2cd8908792e1fba3b481cafc7aa28d19c4f456602fd9581d | @Memoize
def fibonacci(x):
'Return the xth Fibonacci number'
if (x < 2):
return x
return (fibonacci((x - 1)) + fibonacci((x - 2))) | Return the xth Fibonacci number | section6/video1/memoclass.py | fibonacci | PacktPublishing/Mastering-Python-3.x-3rd-Edition | 6 | python | @Memoize
def fibonacci(x):
if (x < 2):
return x
return (fibonacci((x - 1)) + fibonacci((x - 2))) | @Memoize
def fibonacci(x):
if (x < 2):
return x
return (fibonacci((x - 1)) + fibonacci((x - 2)))<|docstring|>Return the xth Fibonacci number<|endoftext|> |
013766be5d0b78462ad26886cd0102a0bd072952a894d92ffc8ff0d72df6a74d | def pack_string(message):
'Pack a single message in the TCP protocol format'
return (struct.pack('>l', len(message)) + message) | Pack a single message in the TCP protocol format | nsq/util.py | pack_string | dlecocq/nsq-py | 41 | python | def pack_string(message):
return (struct.pack('>l', len(message)) + message) | def pack_string(message):
return (struct.pack('>l', len(message)) + message)<|docstring|>Pack a single message in the TCP protocol format<|endoftext|> |
87d9733e227c1fed8fd61d466ac690ce5bd50e51ea5d259c337d42f54d749f57 | def pack_iterable(messages):
'Pack an iterable of messages in the TCP protocol format'
return pack_string((struct.pack('>l', len(messages)) + b''.join(map(pack_string, messages)))) | Pack an iterable of messages in the TCP protocol format | nsq/util.py | pack_iterable | dlecocq/nsq-py | 41 | python | def pack_iterable(messages):
return pack_string((struct.pack('>l', len(messages)) + b.join(map(pack_string, messages)))) | def pack_iterable(messages):
return pack_string((struct.pack('>l', len(messages)) + b.join(map(pack_string, messages))))<|docstring|>Pack an iterable of messages in the TCP protocol format<|endoftext|> |
a9c0b36b5efa0c4d4d8b33a33b0f13c379a1e2475d9f85b48ac2b62decd874b0 | def pack(message):
'Pack the provided message'
if isinstance(message, bytes):
return pack_string(message)
else:
return pack_iterable(message) | Pack the provided message | nsq/util.py | pack | dlecocq/nsq-py | 41 | python | def pack(message):
if isinstance(message, bytes):
return pack_string(message)
else:
return pack_iterable(message) | def pack(message):
if isinstance(message, bytes):
return pack_string(message)
else:
return pack_iterable(message)<|docstring|>Pack the provided message<|endoftext|> |
5ad7e6e3015271241792b091b49be96b24bfcb3b0ba78f1790f601ad7d3125ef | def hexify(message):
'Print out printable characters, but others in hex'
import string
hexified = []
for char in message:
if ((char in '\n\r \t') or (char not in string.printable)):
hexified.append(('\\x%02x' % ord(char)))
else:
hexified.append(char)
return ''.join(hexified) | Print out printable characters, but others in hex | nsq/util.py | hexify | dlecocq/nsq-py | 41 | python | def hexify(message):
import string
hexified = []
for char in message:
if ((char in '\n\r \t') or (char not in string.printable)):
hexified.append(('\\x%02x' % ord(char)))
else:
hexified.append(char)
return .join(hexified) | def hexify(message):
import string
hexified = []
for char in message:
if ((char in '\n\r \t') or (char not in string.printable)):
hexified.append(('\\x%02x' % ord(char)))
else:
hexified.append(char)
return .join(hexified)<|docstring|>Print out printable characters, but others in hex<|endoftext|> |
30540153ef39bf9f062433e451d2505bbe73ebf5f9ae7f1aa966ce3c1a955718 | def distribute(total, objects):
'Generator for (count, object) tuples that distributes count evenly among\n the provided objects'
for (index, obj) in enumerate(objects):
start = ((index * total) // len(objects))
stop = (((index + 1) * total) // len(objects))
(yield ((stop - start), obj)) | Generator for (count, object) tuples that distributes count evenly among
the provided objects | nsq/util.py | distribute | dlecocq/nsq-py | 41 | python | def distribute(total, objects):
'Generator for (count, object) tuples that distributes count evenly among\n the provided objects'
for (index, obj) in enumerate(objects):
start = ((index * total) // len(objects))
stop = (((index + 1) * total) // len(objects))
(yield ((stop - start), obj)) | def distribute(total, objects):
'Generator for (count, object) tuples that distributes count evenly among\n the provided objects'
for (index, obj) in enumerate(objects):
start = ((index * total) // len(objects))
stop = (((index + 1) * total) // len(objects))
(yield ((stop - start), obj))<|docstring|>Generator for (count, object) tuples that distributes count evenly among
the provided objects<|endoftext|> |
f380e600a642c0ad93c428a082639d2756864393c88379964930188c0c965998 | def flipLights(self, n, m):
'\n :type n: int\n :type m: int\n :rtype: int\n '
n = min(n, 3)
if (m == 0):
return 1
elif (m == 1):
return [2, 3, 4][(n - 1)]
elif (m == 2):
return [2, 4, 7][(n - 1)]
return [2, 4, 8][(n - 1)] | :type n: int
:type m: int
:rtype: int | Python3/0672-Bulb-Switcher-II/soln.py | flipLights | wyaadarsh/LeetCode-Solutions | 5 | python | def flipLights(self, n, m):
'\n :type n: int\n :type m: int\n :rtype: int\n '
n = min(n, 3)
if (m == 0):
return 1
elif (m == 1):
return [2, 3, 4][(n - 1)]
elif (m == 2):
return [2, 4, 7][(n - 1)]
return [2, 4, 8][(n - 1)] | def flipLights(self, n, m):
'\n :type n: int\n :type m: int\n :rtype: int\n '
n = min(n, 3)
if (m == 0):
return 1
elif (m == 1):
return [2, 3, 4][(n - 1)]
elif (m == 2):
return [2, 4, 7][(n - 1)]
return [2, 4, 8][(n - 1)]<|docstring|>:type n: int
:type m: int
:rtype: int<|endoftext|> |
4798523b606f74134d3d78026933845c96a994b52b5da83dcdf47ad3a6764538 | def get_intrastat_recursively(self, cr, uid, category, context=None):
' Recursively search in categories to find an intrastat code id\n\n :param category : Browse record of a category\n '
if category.intrastat_id:
res = category.intrastat_id.id
elif category.parent_id:
res = self.get_intrastat_recursively(cr, uid, category.parent_id, context=context)
else:
res = None
return res | Recursively search in categories to find an intrastat code id
:param category : Browse record of a category | Code/odooerp/odoo-8.0/openerp/addons/l10n_be_intrastat/l10n_be_intrastat.py | get_intrastat_recursively | zhupangithub/WEBERP | 1 | python | def get_intrastat_recursively(self, cr, uid, category, context=None):
' Recursively search in categories to find an intrastat code id\n\n :param category : Browse record of a category\n '
if category.intrastat_id:
res = category.intrastat_id.id
elif category.parent_id:
res = self.get_intrastat_recursively(cr, uid, category.parent_id, context=context)
else:
res = None
return res | def get_intrastat_recursively(self, cr, uid, category, context=None):
' Recursively search in categories to find an intrastat code id\n\n :param category : Browse record of a category\n '
if category.intrastat_id:
res = category.intrastat_id.id
elif category.parent_id:
res = self.get_intrastat_recursively(cr, uid, category.parent_id, context=context)
else:
res = None
return res<|docstring|>Recursively search in categories to find an intrastat code id
:param category : Browse record of a category<|endoftext|> |
c7ad49ad18ad0814bdfebbef844f11ea740a6986993faebb6c7ff178d54a9c4b | def get_intrastat_recursively(self, cr, uid, id, context=None):
' Recursively search in categories to find an intrastat code id\n '
product = self.browse(cr, uid, id, context=context)
if product.intrastat_id:
res = product.intrastat_id.id
elif product.categ_id:
res = self.pool['product.category'].get_intrastat_recursively(cr, uid, product.categ_id, context=context)
else:
res = None
return res | Recursively search in categories to find an intrastat code id | Code/odooerp/odoo-8.0/openerp/addons/l10n_be_intrastat/l10n_be_intrastat.py | get_intrastat_recursively | zhupangithub/WEBERP | 1 | python | def get_intrastat_recursively(self, cr, uid, id, context=None):
' \n '
product = self.browse(cr, uid, id, context=context)
if product.intrastat_id:
res = product.intrastat_id.id
elif product.categ_id:
res = self.pool['product.category'].get_intrastat_recursively(cr, uid, product.categ_id, context=context)
else:
res = None
return res | def get_intrastat_recursively(self, cr, uid, id, context=None):
' \n '
product = self.browse(cr, uid, id, context=context)
if product.intrastat_id:
res = product.intrastat_id.id
elif product.categ_id:
res = self.pool['product.category'].get_intrastat_recursively(cr, uid, product.categ_id, context=context)
else:
res = None
return res<|docstring|>Recursively search in categories to find an intrastat code id<|endoftext|> |
961c8e975e031d3c041a2af9f56511c9801d85ed997013b0d5233f78a29f4bc3 | def _prepare_invoice(self, cr, uid, order, line_ids, context=None):
'\n copy incoterm from purchase order to invoice\n '
invoice = super(purchase_order, self)._prepare_invoice(cr, uid, order, line_ids, context=context)
if order.incoterm_id:
invoice['incoterm_id'] = order.incoterm_id.id
if order.partner_id.country_id:
invoice['intrastat_country_id'] = order.partner_id.country_id.id
return invoice | copy incoterm from purchase order to invoice | Code/odooerp/odoo-8.0/openerp/addons/l10n_be_intrastat/l10n_be_intrastat.py | _prepare_invoice | zhupangithub/WEBERP | 1 | python | def _prepare_invoice(self, cr, uid, order, line_ids, context=None):
'\n \n '
invoice = super(purchase_order, self)._prepare_invoice(cr, uid, order, line_ids, context=context)
if order.incoterm_id:
invoice['incoterm_id'] = order.incoterm_id.id
if order.partner_id.country_id:
invoice['intrastat_country_id'] = order.partner_id.country_id.id
return invoice | def _prepare_invoice(self, cr, uid, order, line_ids, context=None):
'\n \n '
invoice = super(purchase_order, self)._prepare_invoice(cr, uid, order, line_ids, context=context)
if order.incoterm_id:
invoice['incoterm_id'] = order.incoterm_id.id
if order.partner_id.country_id:
invoice['intrastat_country_id'] = order.partner_id.country_id.id
return invoice<|docstring|>copy incoterm from purchase order to invoice<|endoftext|> |
cab9b70c8e2142e5f7f5367de04835712ade9811a796edcda1b952ed1066efea | def _prepare_invoice(self, cr, uid, saleorder, lines, context=None):
'\n copy incoterm from sale order to invoice\n '
invoice = super(sale_order, self)._prepare_invoice(cr, uid, saleorder, lines, context=context)
if saleorder.incoterm:
invoice['incoterm_id'] = saleorder.incoterm.id
if saleorder.partner_shipping_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_shipping_id.country_id.id
elif saleorder.partner_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_id.country_id.id
elif saleorder.partner_invoice_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_invoice_id.country_id.id
return invoice | copy incoterm from sale order to invoice | Code/odooerp/odoo-8.0/openerp/addons/l10n_be_intrastat/l10n_be_intrastat.py | _prepare_invoice | zhupangithub/WEBERP | 1 | python | def _prepare_invoice(self, cr, uid, saleorder, lines, context=None):
'\n \n '
invoice = super(sale_order, self)._prepare_invoice(cr, uid, saleorder, lines, context=context)
if saleorder.incoterm:
invoice['incoterm_id'] = saleorder.incoterm.id
if saleorder.partner_shipping_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_shipping_id.country_id.id
elif saleorder.partner_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_id.country_id.id
elif saleorder.partner_invoice_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_invoice_id.country_id.id
return invoice | def _prepare_invoice(self, cr, uid, saleorder, lines, context=None):
'\n \n '
invoice = super(sale_order, self)._prepare_invoice(cr, uid, saleorder, lines, context=context)
if saleorder.incoterm:
invoice['incoterm_id'] = saleorder.incoterm.id
if saleorder.partner_shipping_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_shipping_id.country_id.id
elif saleorder.partner_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_id.country_id.id
elif saleorder.partner_invoice_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_invoice_id.country_id.id
return invoice<|docstring|>copy incoterm from sale order to invoice<|endoftext|> |
1ee4540ac254652891def66cf08379dfde30ec64279d8e13d499903e1eaebe20 | def f():
'Adding a docstring made this test fail in Py2.5.0'
return None | Adding a docstring made this test fail in Py2.5.0 | Codes/Python32/Lib/test/test_peepholer.py | f | eyantra/FireBird_Swiss_Knife | 2 | python | def f():
return None | def f():
return None<|docstring|>Adding a docstring made this test fail in Py2.5.0<|endoftext|> |
51f1cb7e5c43f5321923e0f3647c457e7cd4860dd91eff525f54e07a64bb350e | def gaussian_kl(mu_i, mu, A_i, A):
'\n decoupled KL between two multivariate gaussian distribution\n C_μ = KL(f(x|μi,Σi)||f(x|μ,Σi))\n C_Σ = KL(f(x|μi,Σi)||f(x|μi,Σ))\n :param μi: (B, dim-a)\n :param μ: (B, dim-a)\n :param Ai: (B, dim-a, dim-a)\n :param A: (B, dim-a, dim-a)\n :return: C_μ, C_Σ: mean and covariance terms of the KL\n '
n = A.size((- 1))
mu_i = mu_i.unsqueeze((- 1))
mu = mu.unsqueeze((- 1))
sigma_i = (A_i @ bt(A_i))
sigma = (A @ bt(A))
sigma_i_inv = sigma_i.inverse()
sigma_inv = sigma.inverse()
inner_mu = (((mu - mu_i).transpose((- 2), (- 1)) @ sigma_i_inv) @ (mu - mu_i)).squeeze()
inner_sigma = ((torch.log((sigma_inv.det() / sigma_i_inv.det())) - n) + btr((sigma_i_inv @ sigma_inv)))
C_mu = (0.5 * torch.mean(inner_mu))
C_sigma = (0.5 * torch.mean(inner_sigma))
return (C_mu, C_sigma) | decoupled KL between two multivariate gaussian distribution
C_μ = KL(f(x|μi,Σi)||f(x|μ,Σi))
C_Σ = KL(f(x|μi,Σi)||f(x|μi,Σ))
:param μi: (B, dim-a)
:param μ: (B, dim-a)
:param Ai: (B, dim-a, dim-a)
:param A: (B, dim-a, dim-a)
:return: C_μ, C_Σ: mean and covariance terms of the KL | ray_elegantrl/agent.py | gaussian_kl | GyChou/ray_elegant_carla | 0 | python | def gaussian_kl(mu_i, mu, A_i, A):
'\n decoupled KL between two multivariate gaussian distribution\n C_μ = KL(f(x|μi,Σi)||f(x|μ,Σi))\n C_Σ = KL(f(x|μi,Σi)||f(x|μi,Σ))\n :param μi: (B, dim-a)\n :param μ: (B, dim-a)\n :param Ai: (B, dim-a, dim-a)\n :param A: (B, dim-a, dim-a)\n :return: C_μ, C_Σ: mean and covariance terms of the KL\n '
n = A.size((- 1))
mu_i = mu_i.unsqueeze((- 1))
mu = mu.unsqueeze((- 1))
sigma_i = (A_i @ bt(A_i))
sigma = (A @ bt(A))
sigma_i_inv = sigma_i.inverse()
sigma_inv = sigma.inverse()
inner_mu = (((mu - mu_i).transpose((- 2), (- 1)) @ sigma_i_inv) @ (mu - mu_i)).squeeze()
inner_sigma = ((torch.log((sigma_inv.det() / sigma_i_inv.det())) - n) + btr((sigma_i_inv @ sigma_inv)))
C_mu = (0.5 * torch.mean(inner_mu))
C_sigma = (0.5 * torch.mean(inner_sigma))
return (C_mu, C_sigma) | def gaussian_kl(mu_i, mu, A_i, A):
'\n decoupled KL between two multivariate gaussian distribution\n C_μ = KL(f(x|μi,Σi)||f(x|μ,Σi))\n C_Σ = KL(f(x|μi,Σi)||f(x|μi,Σ))\n :param μi: (B, dim-a)\n :param μ: (B, dim-a)\n :param Ai: (B, dim-a, dim-a)\n :param A: (B, dim-a, dim-a)\n :return: C_μ, C_Σ: mean and covariance terms of the KL\n '
n = A.size((- 1))
mu_i = mu_i.unsqueeze((- 1))
mu = mu.unsqueeze((- 1))
sigma_i = (A_i @ bt(A_i))
sigma = (A @ bt(A))
sigma_i_inv = sigma_i.inverse()
sigma_inv = sigma.inverse()
inner_mu = (((mu - mu_i).transpose((- 2), (- 1)) @ sigma_i_inv) @ (mu - mu_i)).squeeze()
inner_sigma = ((torch.log((sigma_inv.det() / sigma_i_inv.det())) - n) + btr((sigma_i_inv @ sigma_inv)))
C_mu = (0.5 * torch.mean(inner_mu))
C_sigma = (0.5 * torch.mean(inner_sigma))
return (C_mu, C_sigma)<|docstring|>decoupled KL between two multivariate gaussian distribution
C_μ = KL(f(x|μi,Σi)||f(x|μ,Σi))
C_Σ = KL(f(x|μi,Σi)||f(x|μi,Σ))
:param μi: (B, dim-a)
:param μ: (B, dim-a)
:param Ai: (B, dim-a, dim-a)
:param A: (B, dim-a, dim-a)
:return: C_μ, C_Σ: mean and covariance terms of the KL<|endoftext|> |
e349a2a2c7b11d50f0df623f69e757358981f5df731111a31958f124a1ff89db | def init(self, net_dim, state_dim, action_dim, reward_dim=1, if_per=False):
'initialize the self.object in `__init__()`\n\n replace by different DRL algorithms\n explict call self.init() for multiprocessing.\n\n `int net_dim` the dimension of networks (the width of neural networks)\n `int state_dim` the dimension of state (the number of state vector)\n `int action_dim` the dimension of action (the number of discrete action)\n `bool if_per` Prioritized Experience Replay for sparse reward\n ' | initialize the self.object in `__init__()`
replace by different DRL algorithms
explict call self.init() for multiprocessing.
`int net_dim` the dimension of networks (the width of neural networks)
`int state_dim` the dimension of state (the number of state vector)
`int action_dim` the dimension of action (the number of discrete action)
`bool if_per` Prioritized Experience Replay for sparse reward | ray_elegantrl/agent.py | init | GyChou/ray_elegant_carla | 0 | python | def init(self, net_dim, state_dim, action_dim, reward_dim=1, if_per=False):
'initialize the self.object in `__init__()`\n\n replace by different DRL algorithms\n explict call self.init() for multiprocessing.\n\n `int net_dim` the dimension of networks (the width of neural networks)\n `int state_dim` the dimension of state (the number of state vector)\n `int action_dim` the dimension of action (the number of discrete action)\n `bool if_per` Prioritized Experience Replay for sparse reward\n ' | def init(self, net_dim, state_dim, action_dim, reward_dim=1, if_per=False):
'initialize the self.object in `__init__()`\n\n replace by different DRL algorithms\n explict call self.init() for multiprocessing.\n\n `int net_dim` the dimension of networks (the width of neural networks)\n `int state_dim` the dimension of state (the number of state vector)\n `int action_dim` the dimension of action (the number of discrete action)\n `bool if_per` Prioritized Experience Replay for sparse reward\n '<|docstring|>initialize the self.object in `__init__()`
replace by different DRL algorithms
explict call self.init() for multiprocessing.
`int net_dim` the dimension of networks (the width of neural networks)
`int state_dim` the dimension of state (the number of state vector)
`int action_dim` the dimension of action (the number of discrete action)
`bool if_per` Prioritized Experience Replay for sparse reward<|endoftext|> |
7583166cabbf31e9d99a595553c85a50839179bfa926a20f0678190334b4ceea | @staticmethod
def select_action(state, policy, explore_rate=1.0) -> np.ndarray:
'Select actions for exploration; run on cpu\n\n :array state: state.shape==(state_dim, )\n :return array action: action.shape==(action_dim, ), (action.min(), action.max())==(-1, +1)\n '
states = torch.as_tensor((state,), dtype=torch.float32).detach_()
if (rd.rand() < explore_rate):
action = policy.get_action(states)[0]
else:
action = policy(states)[0]
return action.cpu().numpy() | Select actions for exploration; run on cpu
:array state: state.shape==(state_dim, )
:return array action: action.shape==(action_dim, ), (action.min(), action.max())==(-1, +1) | ray_elegantrl/agent.py | select_action | GyChou/ray_elegant_carla | 0 | python | @staticmethod
def select_action(state, policy, explore_rate=1.0) -> np.ndarray:
'Select actions for exploration; run on cpu\n\n :array state: state.shape==(state_dim, )\n :return array action: action.shape==(action_dim, ), (action.min(), action.max())==(-1, +1)\n '
states = torch.as_tensor((state,), dtype=torch.float32).detach_()
if (rd.rand() < explore_rate):
action = policy.get_action(states)[0]
else:
action = policy(states)[0]
return action.cpu().numpy() | @staticmethod
def select_action(state, policy, explore_rate=1.0) -> np.ndarray:
'Select actions for exploration; run on cpu\n\n :array state: state.shape==(state_dim, )\n :return array action: action.shape==(action_dim, ), (action.min(), action.max())==(-1, +1)\n '
states = torch.as_tensor((state,), dtype=torch.float32).detach_()
if (rd.rand() < explore_rate):
action = policy.get_action(states)[0]
else:
action = policy(states)[0]
return action.cpu().numpy()<|docstring|>Select actions for exploration; run on cpu
:array state: state.shape==(state_dim, )
:return array action: action.shape==(action_dim, ), (action.min(), action.max())==(-1, +1)<|endoftext|> |
eb1b041e792c95dc301c3d36fe26c6af3d46e0a61f651dfd42970ff7ca868860 | def update_net(self, buffer, target_step, batch_size, repeat_times) -> (float, float):
'update the neural network by sampling batch data from ReplayBuffer\n\n replace by different DRL algorithms.\n return the objective value as training information to help fine-tuning\n\n `buffer` Experience replay buffer. buffer.append_buffer() buffer.extend_buffer()\n :int target_step: explore target_step number of step in env\n `int batch_size` sample batch_size of data for Stochastic Gradient Descent\n :float repeat_times: the times of sample batch = int(target_step * repeat_times) in off-policy\n :return float obj_a: the objective value of actor\n :return float obj_c: the objective value of critic\n ' | update the neural network by sampling batch data from ReplayBuffer
replace by different DRL algorithms.
return the objective value as training information to help fine-tuning
`buffer` Experience replay buffer. buffer.append_buffer() buffer.extend_buffer()
:int target_step: explore target_step number of step in env
`int batch_size` sample batch_size of data for Stochastic Gradient Descent
:float repeat_times: the times of sample batch = int(target_step * repeat_times) in off-policy
:return float obj_a: the objective value of actor
:return float obj_c: the objective value of critic | ray_elegantrl/agent.py | update_net | GyChou/ray_elegant_carla | 0 | python | def update_net(self, buffer, target_step, batch_size, repeat_times) -> (float, float):
'update the neural network by sampling batch data from ReplayBuffer\n\n replace by different DRL algorithms.\n return the objective value as training information to help fine-tuning\n\n `buffer` Experience replay buffer. buffer.append_buffer() buffer.extend_buffer()\n :int target_step: explore target_step number of step in env\n `int batch_size` sample batch_size of data for Stochastic Gradient Descent\n :float repeat_times: the times of sample batch = int(target_step * repeat_times) in off-policy\n :return float obj_a: the objective value of actor\n :return float obj_c: the objective value of critic\n ' | def update_net(self, buffer, target_step, batch_size, repeat_times) -> (float, float):
'update the neural network by sampling batch data from ReplayBuffer\n\n replace by different DRL algorithms.\n return the objective value as training information to help fine-tuning\n\n `buffer` Experience replay buffer. buffer.append_buffer() buffer.extend_buffer()\n :int target_step: explore target_step number of step in env\n `int batch_size` sample batch_size of data for Stochastic Gradient Descent\n :float repeat_times: the times of sample batch = int(target_step * repeat_times) in off-policy\n :return float obj_a: the objective value of actor\n :return float obj_c: the objective value of critic\n '<|docstring|>update the neural network by sampling batch data from ReplayBuffer
replace by different DRL algorithms.
return the objective value as training information to help fine-tuning
`buffer` Experience replay buffer. buffer.append_buffer() buffer.extend_buffer()
:int target_step: explore target_step number of step in env
`int batch_size` sample batch_size of data for Stochastic Gradient Descent
:float repeat_times: the times of sample batch = int(target_step * repeat_times) in off-policy
:return float obj_a: the objective value of actor
:return float obj_c: the objective value of critic<|endoftext|> |
ab18c9446adc4e805c98442390dcfd15ed8ab812155ce3029f9a2460d7a63e22 | @staticmethod
def soft_update(target_net, current_net, tau):
'soft update a target network via current network\n\n :nn.Module target_net: target network update via a current network, it is more stable\n :nn.Module current_net: current network update via an optimizer\n '
for (tar, cur) in zip(target_net.parameters(), current_net.parameters()):
tar.data.copy_((cur.data.__mul__(tau) + tar.data.__mul__((1 - tau)))) | soft update a target network via current network
:nn.Module target_net: target network update via a current network, it is more stable
:nn.Module current_net: current network update via an optimizer | ray_elegantrl/agent.py | soft_update | GyChou/ray_elegant_carla | 0 | python | @staticmethod
def soft_update(target_net, current_net, tau):
'soft update a target network via current network\n\n :nn.Module target_net: target network update via a current network, it is more stable\n :nn.Module current_net: current network update via an optimizer\n '
for (tar, cur) in zip(target_net.parameters(), current_net.parameters()):
tar.data.copy_((cur.data.__mul__(tau) + tar.data.__mul__((1 - tau)))) | @staticmethod
def soft_update(target_net, current_net, tau):
'soft update a target network via current network\n\n :nn.Module target_net: target network update via a current network, it is more stable\n :nn.Module current_net: current network update via an optimizer\n '
for (tar, cur) in zip(target_net.parameters(), current_net.parameters()):
tar.data.copy_((cur.data.__mul__(tau) + tar.data.__mul__((1 - tau))))<|docstring|>soft update a target network via current network
:nn.Module target_net: target network update via a current network, it is more stable
:nn.Module current_net: current network update via an optimizer<|endoftext|> |
cbe7110c0cb614675aba610ba76b7fe245521fdc31b89620a414ad46ea235b91 | def update_record(self, **kwargs):
'update the self.train_record for recording the metrics in training process\n :**kwargs :named arguments is the metrics name, arguments value is the metrics value.\n both of them will be prined and showed in tensorboard\n '
self.train_record.update(kwargs) | update the self.train_record for recording the metrics in training process
:**kwargs :named arguments is the metrics name, arguments value is the metrics value.
both of them will be prined and showed in tensorboard | ray_elegantrl/agent.py | update_record | GyChou/ray_elegant_carla | 0 | python | def update_record(self, **kwargs):
'update the self.train_record for recording the metrics in training process\n :**kwargs :named arguments is the metrics name, arguments value is the metrics value.\n both of them will be prined and showed in tensorboard\n '
self.train_record.update(kwargs) | def update_record(self, **kwargs):
'update the self.train_record for recording the metrics in training process\n :**kwargs :named arguments is the metrics name, arguments value is the metrics value.\n both of them will be prined and showed in tensorboard\n '
self.train_record.update(kwargs)<|docstring|>update the self.train_record for recording the metrics in training process
:**kwargs :named arguments is the metrics name, arguments value is the metrics value.
both of them will be prined and showed in tensorboard<|endoftext|> |
297e054f7569cfa06ee4c4e876947986da23509f83335802cc85a9ce62b5c24a | def get_obj_critic_per(self, buffer, batch_size):
'Prioritized Experience Replay\n\n Contributor: Github GyChou\n '
with torch.no_grad():
(reward, mask, action, state, next_s, is_weights) = buffer.sample_batch(batch_size)
next_a = self.act_target.get_action(next_s, self.policy_noise)
next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a))
q_label = (reward + (mask * next_q))
(q1, q2) = self.cri.get_q1_q2(state, action)
obj_critic = ((self.criterion(q1, q_label) + self.criterion(q2, q_label)) * is_weights).mean()
td_error = (q_label - torch.min(q1, q1).detach()).abs()
buffer.td_error_update(td_error)
return (obj_critic, state) | Prioritized Experience Replay
Contributor: Github GyChou | ray_elegantrl/agent.py | get_obj_critic_per | GyChou/ray_elegant_carla | 0 | python | def get_obj_critic_per(self, buffer, batch_size):
'Prioritized Experience Replay\n\n Contributor: Github GyChou\n '
with torch.no_grad():
(reward, mask, action, state, next_s, is_weights) = buffer.sample_batch(batch_size)
next_a = self.act_target.get_action(next_s, self.policy_noise)
next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a))
q_label = (reward + (mask * next_q))
(q1, q2) = self.cri.get_q1_q2(state, action)
obj_critic = ((self.criterion(q1, q_label) + self.criterion(q2, q_label)) * is_weights).mean()
td_error = (q_label - torch.min(q1, q1).detach()).abs()
buffer.td_error_update(td_error)
return (obj_critic, state) | def get_obj_critic_per(self, buffer, batch_size):
'Prioritized Experience Replay\n\n Contributor: Github GyChou\n '
with torch.no_grad():
(reward, mask, action, state, next_s, is_weights) = buffer.sample_batch(batch_size)
next_a = self.act_target.get_action(next_s, self.policy_noise)
next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a))
q_label = (reward + (mask * next_q))
(q1, q2) = self.cri.get_q1_q2(state, action)
obj_critic = ((self.criterion(q1, q_label) + self.criterion(q2, q_label)) * is_weights).mean()
td_error = (q_label - torch.min(q1, q1).detach()).abs()
buffer.td_error_update(td_error)
return (obj_critic, state)<|docstring|>Prioritized Experience Replay
Contributor: Github GyChou<|endoftext|> |
41cfb1117d70ed89bfe869d8d448f67749a3e7939d72499e674b9d76037a4824 | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1) | ray_elegantrl/agent.py | compute_reward_adv | GyChou/ray_elegant_carla | 0 | python | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv)<|docstring|>compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)<|endoftext|> |
05db739cbac8a39baf81f09e1638a6b5c0f63549f094968d7f08e7242eaf8a44 | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1) | ray_elegantrl/agent.py | compute_reward_gae | GyChou/ray_elegant_carla | 0 | python | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv)<|docstring|>compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)<|endoftext|> |
41cfb1117d70ed89bfe869d8d448f67749a3e7939d72499e674b9d76037a4824 | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1) | ray_elegantrl/agent.py | compute_reward_adv | GyChou/ray_elegant_carla | 0 | python | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv)<|docstring|>compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)<|endoftext|> |
05db739cbac8a39baf81f09e1638a6b5c0f63549f094968d7f08e7242eaf8a44 | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1) | ray_elegantrl/agent.py | compute_reward_gae | GyChou/ray_elegant_carla | 0 | python | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv)<|docstring|>compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)<|endoftext|> |
e77711c7dba2d91a24b1665563d12d4887f31ffbed2b3530c2b76cffcdfa0bd8 | @staticmethod
def select_action(state, policy):
'select action for PPO\n\n :array state: state.shape==(state_dim, )\n\n :return array action: state.shape==(action_dim, )\n :return array noise: noise.shape==(action_dim, ), the noise\n '
states = torch.as_tensor((state,), dtype=torch.float32).detach_()
action = policy.get_action(states)[0]
return action.detach().numpy() | select action for PPO
:array state: state.shape==(state_dim, )
:return array action: state.shape==(action_dim, )
:return array noise: noise.shape==(action_dim, ), the noise | ray_elegantrl/agent.py | select_action | GyChou/ray_elegant_carla | 0 | python | @staticmethod
def select_action(state, policy):
'select action for PPO\n\n :array state: state.shape==(state_dim, )\n\n :return array action: state.shape==(action_dim, )\n :return array noise: noise.shape==(action_dim, ), the noise\n '
states = torch.as_tensor((state,), dtype=torch.float32).detach_()
action = policy.get_action(states)[0]
return action.detach().numpy() | @staticmethod
def select_action(state, policy):
'select action for PPO\n\n :array state: state.shape==(state_dim, )\n\n :return array action: state.shape==(action_dim, )\n :return array noise: noise.shape==(action_dim, ), the noise\n '
states = torch.as_tensor((state,), dtype=torch.float32).detach_()
action = policy.get_action(states)[0]
return action.detach().numpy()<|docstring|>select action for PPO
:array state: state.shape==(state_dim, )
:return array action: state.shape==(action_dim, )
:return array noise: noise.shape==(action_dim, ), the noise<|endoftext|> |
41cfb1117d70ed89bfe869d8d448f67749a3e7939d72499e674b9d76037a4824 | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1) | ray_elegantrl/agent.py | compute_reward_adv | GyChou/ray_elegant_carla | 0 | python | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | def compute_reward_adv(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv = (buf_r_ret - (buf_mask * buf_value))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv)<|docstring|>compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)<|endoftext|> |
05db739cbac8a39baf81f09e1638a6b5c0f63549f094968d7f08e7242eaf8a44 | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1) | ray_elegantrl/agent.py | compute_reward_gae | GyChou/ray_elegant_carla | 0 | python | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv) | def compute_reward_gae(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):
'compute the excepted discounted episode return\n\n :int buf_len: the length of ReplayBuffer\n :torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)\n :torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)\n :torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)\n :return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)\n :return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)\n '
buf_r_ret = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
buf_adv = torch.empty(buf_reward.shape, dtype=torch.float32, device=self.device)
pre_r_ret = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
pre_adv = torch.zeros(buf_reward.shape[1], dtype=torch.float32, device=self.device)
for i in range((buf_len - 1), (- 1), (- 1)):
buf_r_ret[i] = (buf_reward[i] + (buf_mask[i] * pre_r_ret))
pre_r_ret = buf_r_ret[i]
buf_adv[i] = ((buf_reward[i] + (buf_mask[i] * pre_adv)) - buf_value[i])
pre_adv = (buf_value[i] + (buf_adv[i] * self.lambda_gae_adv))
buf_adv = ((buf_adv - buf_adv.mean(dim=0)) / (buf_adv.std(dim=0) + 1e-05))
return (buf_r_ret, buf_adv)<|docstring|>compute the excepted discounted episode return
:int buf_len: the length of ReplayBuffer
:torch.Tensor buf_reward: buf_reward.shape==(buf_len, 1)
:torch.Tensor buf_mask: buf_mask.shape ==(buf_len, 1)
:torch.Tensor buf_value: buf_value.shape ==(buf_len, 1)
:return torch.Tensor buf_r_sum: buf_r_sum.shape ==(buf_len, 1)
:return torch.Tensor buf_advantage: buf_advantage.shape ==(buf_len, 1)<|endoftext|> |
7cb039a032cc8eccd38981e265139542000a4b78bd70d42081d12bf54051b96f | def __init__(self, size, theta=0.15, sigma=0.3, ou_noise=0.0, dt=0.01):
"The noise of Ornstein-Uhlenbeck Process\n\n Source: https://github.com/slowbull/DDPG/blob/master/src/explorationnoise.py\n It makes Zero-mean Gaussian Noise more stable.\n It helps agent explore better in a inertial system.\n Don't abuse OU Process. OU process has too much hyper-parameters and over fine-tuning make no sense.\n\n :int size: the size of noise, noise.shape==(-1, action_dim)\n :float theta: related to the not independent of OU-noise\n :float sigma: related to action noise std\n :float ou_noise: initialize OU-noise\n :float dt: derivative\n "
self.theta = theta
self.sigma = sigma
self.ou_noise = ou_noise
self.dt = dt
self.size = size | The noise of Ornstein-Uhlenbeck Process
Source: https://github.com/slowbull/DDPG/blob/master/src/explorationnoise.py
It makes Zero-mean Gaussian Noise more stable.
It helps agent explore better in a inertial system.
Don't abuse OU Process. OU process has too much hyper-parameters and over fine-tuning make no sense.
:int size: the size of noise, noise.shape==(-1, action_dim)
:float theta: related to the not independent of OU-noise
:float sigma: related to action noise std
:float ou_noise: initialize OU-noise
:float dt: derivative | ray_elegantrl/agent.py | __init__ | GyChou/ray_elegant_carla | 0 | python | def __init__(self, size, theta=0.15, sigma=0.3, ou_noise=0.0, dt=0.01):
"The noise of Ornstein-Uhlenbeck Process\n\n Source: https://github.com/slowbull/DDPG/blob/master/src/explorationnoise.py\n It makes Zero-mean Gaussian Noise more stable.\n It helps agent explore better in a inertial system.\n Don't abuse OU Process. OU process has too much hyper-parameters and over fine-tuning make no sense.\n\n :int size: the size of noise, noise.shape==(-1, action_dim)\n :float theta: related to the not independent of OU-noise\n :float sigma: related to action noise std\n :float ou_noise: initialize OU-noise\n :float dt: derivative\n "
self.theta = theta
self.sigma = sigma
self.ou_noise = ou_noise
self.dt = dt
self.size = size | def __init__(self, size, theta=0.15, sigma=0.3, ou_noise=0.0, dt=0.01):
"The noise of Ornstein-Uhlenbeck Process\n\n Source: https://github.com/slowbull/DDPG/blob/master/src/explorationnoise.py\n It makes Zero-mean Gaussian Noise more stable.\n It helps agent explore better in a inertial system.\n Don't abuse OU Process. OU process has too much hyper-parameters and over fine-tuning make no sense.\n\n :int size: the size of noise, noise.shape==(-1, action_dim)\n :float theta: related to the not independent of OU-noise\n :float sigma: related to action noise std\n :float ou_noise: initialize OU-noise\n :float dt: derivative\n "
self.theta = theta
self.sigma = sigma
self.ou_noise = ou_noise
self.dt = dt
self.size = size<|docstring|>The noise of Ornstein-Uhlenbeck Process
Source: https://github.com/slowbull/DDPG/blob/master/src/explorationnoise.py
It makes Zero-mean Gaussian Noise more stable.
It helps agent explore better in a inertial system.
Don't abuse OU Process. OU process has too much hyper-parameters and over fine-tuning make no sense.
:int size: the size of noise, noise.shape==(-1, action_dim)
:float theta: related to the not independent of OU-noise
:float sigma: related to action noise std
:float ou_noise: initialize OU-noise
:float dt: derivative<|endoftext|> |
e99c2ababa87247155b6240675b83fa817b67dae3d661f2e91e7b9b2db692815 | def __call__(self) -> float:
'output a OU-noise\n :return array ou_noise: a noise generated by Ornstein-Uhlenbeck Process\n '
noise = ((self.sigma * np.sqrt(self.dt)) * rd.normal(size=self.size))
self.ou_noise -= (((self.theta * self.ou_noise) * self.dt) + noise)
return self.ou_noise | output a OU-noise
:return array ou_noise: a noise generated by Ornstein-Uhlenbeck Process | ray_elegantrl/agent.py | __call__ | GyChou/ray_elegant_carla | 0 | python | def __call__(self) -> float:
'output a OU-noise\n :return array ou_noise: a noise generated by Ornstein-Uhlenbeck Process\n '
noise = ((self.sigma * np.sqrt(self.dt)) * rd.normal(size=self.size))
self.ou_noise -= (((self.theta * self.ou_noise) * self.dt) + noise)
return self.ou_noise | def __call__(self) -> float:
'output a OU-noise\n :return array ou_noise: a noise generated by Ornstein-Uhlenbeck Process\n '
noise = ((self.sigma * np.sqrt(self.dt)) * rd.normal(size=self.size))
self.ou_noise -= (((self.theta * self.ou_noise) * self.dt) + noise)
return self.ou_noise<|docstring|>output a OU-noise
:return array ou_noise: a noise generated by Ornstein-Uhlenbeck Process<|endoftext|> |
dd2713c6c5a4a602e40f22a0fad6482c2251b48b117b09201c8999ccf8613c6f | def freq_from_autocorr(signal, fs):
"\n Estimate frequency using autocorrelation.\n\n Pros: Best method for finding the true fundamental of any repeating wave,\n even with strong harmonics or completely missing fundamental\n\n Cons: Not as accurate, doesn't work for inharmonic things like musical\n instruments, this implementation has trouble with finding the true peak\n\n From: https://gist.github.com/endolith/255291 and\n https://github.com/endolith/waveform-analyzer\n\n Parameters\n ----------\n signal : list or array\n time series data\n fs : integer\n sample rate\n\n Returns\n -------\n frequency : float\n frequency (Hz)\n\n "
import numpy as np
from scipy.signal import fftconvolve
from matplotlib.mlab import find
from mhealthx.signals import parabolic
signal -= np.mean(signal)
corr = fftconvolve(signal, signal[::(- 1)], mode='full')
corr = corr[(len(corr) / 2):]
d = np.diff(corr)
start = find((d > 0))[0]
i_peak = (np.argmax(corr[start:]) + start)
i_interp = parabolic(corr, i_peak)[0]
frequency = (fs / i_interp)
return frequency | Estimate frequency using autocorrelation.
Pros: Best method for finding the true fundamental of any repeating wave,
even with strong harmonics or completely missing fundamental
Cons: Not as accurate, doesn't work for inharmonic things like musical
instruments, this implementation has trouble with finding the true peak
From: https://gist.github.com/endolith/255291 and
https://github.com/endolith/waveform-analyzer
Parameters
----------
signal : list or array
time series data
fs : integer
sample rate
Returns
-------
frequency : float
frequency (Hz) | mhealthx/xtras/frequency_estimator.py | freq_from_autocorr | sensein/mhealthx | 2 | python | def freq_from_autocorr(signal, fs):
"\n Estimate frequency using autocorrelation.\n\n Pros: Best method for finding the true fundamental of any repeating wave,\n even with strong harmonics or completely missing fundamental\n\n Cons: Not as accurate, doesn't work for inharmonic things like musical\n instruments, this implementation has trouble with finding the true peak\n\n From: https://gist.github.com/endolith/255291 and\n https://github.com/endolith/waveform-analyzer\n\n Parameters\n ----------\n signal : list or array\n time series data\n fs : integer\n sample rate\n\n Returns\n -------\n frequency : float\n frequency (Hz)\n\n "
import numpy as np
from scipy.signal import fftconvolve
from matplotlib.mlab import find
from mhealthx.signals import parabolic
signal -= np.mean(signal)
corr = fftconvolve(signal, signal[::(- 1)], mode='full')
corr = corr[(len(corr) / 2):]
d = np.diff(corr)
start = find((d > 0))[0]
i_peak = (np.argmax(corr[start:]) + start)
i_interp = parabolic(corr, i_peak)[0]
frequency = (fs / i_interp)
return frequency | def freq_from_autocorr(signal, fs):
"\n Estimate frequency using autocorrelation.\n\n Pros: Best method for finding the true fundamental of any repeating wave,\n even with strong harmonics or completely missing fundamental\n\n Cons: Not as accurate, doesn't work for inharmonic things like musical\n instruments, this implementation has trouble with finding the true peak\n\n From: https://gist.github.com/endolith/255291 and\n https://github.com/endolith/waveform-analyzer\n\n Parameters\n ----------\n signal : list or array\n time series data\n fs : integer\n sample rate\n\n Returns\n -------\n frequency : float\n frequency (Hz)\n\n "
import numpy as np
from scipy.signal import fftconvolve
from matplotlib.mlab import find
from mhealthx.signals import parabolic
signal -= np.mean(signal)
corr = fftconvolve(signal, signal[::(- 1)], mode='full')
corr = corr[(len(corr) / 2):]
d = np.diff(corr)
start = find((d > 0))[0]
i_peak = (np.argmax(corr[start:]) + start)
i_interp = parabolic(corr, i_peak)[0]
frequency = (fs / i_interp)
return frequency<|docstring|>Estimate frequency using autocorrelation.
Pros: Best method for finding the true fundamental of any repeating wave,
even with strong harmonics or completely missing fundamental
Cons: Not as accurate, doesn't work for inharmonic things like musical
instruments, this implementation has trouble with finding the true peak
From: https://gist.github.com/endolith/255291 and
https://github.com/endolith/waveform-analyzer
Parameters
----------
signal : list or array
time series data
fs : integer
sample rate
Returns
-------
frequency : float
frequency (Hz)<|endoftext|> |
648660b32c42a9abcf1c151c2f87731e0c71348e8dbd2c5575ba3bab3199d486 | def freq_from_hps(signal, fs):
'\n Estimate frequency using harmonic product spectrum.\n\n Note: Low frequency noise piles up and overwhelms the desired peaks.\n\n From: https://gist.github.com/endolith/255291 and\n https://github.com/endolith/waveform-analyzer\n\n Parameters\n ----------\n signal : list or array\n time series data\n fs : integer\n sample rate\n\n Returns\n -------\n frequency : float\n frequency (Hz)\n\n '
import numpy as np
from scipy.signal import blackmanharris, decimate
from mhealthx.signals import parabolic
N = len(signal)
signal -= np.mean(signal)
windowed = (signal * blackmanharris(len(signal)))
X = np.log(abs(np.fft.rfft(windowed)))
hps = np.copy(X)
for h in np.arange(2, 9):
dec = decimate(X, h)
hps[:len(dec)] += dec
i_peak = np.argmax(hps[:len(dec)])
i_interp = parabolic(hps, i_peak)[0]
frequency = ((fs * i_interp) / N)
return frequency | Estimate frequency using harmonic product spectrum.
Note: Low frequency noise piles up and overwhelms the desired peaks.
From: https://gist.github.com/endolith/255291 and
https://github.com/endolith/waveform-analyzer
Parameters
----------
signal : list or array
time series data
fs : integer
sample rate
Returns
-------
frequency : float
frequency (Hz) | mhealthx/xtras/frequency_estimator.py | freq_from_hps | sensein/mhealthx | 2 | python | def freq_from_hps(signal, fs):
'\n Estimate frequency using harmonic product spectrum.\n\n Note: Low frequency noise piles up and overwhelms the desired peaks.\n\n From: https://gist.github.com/endolith/255291 and\n https://github.com/endolith/waveform-analyzer\n\n Parameters\n ----------\n signal : list or array\n time series data\n fs : integer\n sample rate\n\n Returns\n -------\n frequency : float\n frequency (Hz)\n\n '
import numpy as np
from scipy.signal import blackmanharris, decimate
from mhealthx.signals import parabolic
N = len(signal)
signal -= np.mean(signal)
windowed = (signal * blackmanharris(len(signal)))
X = np.log(abs(np.fft.rfft(windowed)))
hps = np.copy(X)
for h in np.arange(2, 9):
dec = decimate(X, h)
hps[:len(dec)] += dec
i_peak = np.argmax(hps[:len(dec)])
i_interp = parabolic(hps, i_peak)[0]
frequency = ((fs * i_interp) / N)
return frequency | def freq_from_hps(signal, fs):
'\n Estimate frequency using harmonic product spectrum.\n\n Note: Low frequency noise piles up and overwhelms the desired peaks.\n\n From: https://gist.github.com/endolith/255291 and\n https://github.com/endolith/waveform-analyzer\n\n Parameters\n ----------\n signal : list or array\n time series data\n fs : integer\n sample rate\n\n Returns\n -------\n frequency : float\n frequency (Hz)\n\n '
import numpy as np
from scipy.signal import blackmanharris, decimate
from mhealthx.signals import parabolic
N = len(signal)
signal -= np.mean(signal)
windowed = (signal * blackmanharris(len(signal)))
X = np.log(abs(np.fft.rfft(windowed)))
hps = np.copy(X)
for h in np.arange(2, 9):
dec = decimate(X, h)
hps[:len(dec)] += dec
i_peak = np.argmax(hps[:len(dec)])
i_interp = parabolic(hps, i_peak)[0]
frequency = ((fs * i_interp) / N)
return frequency<|docstring|>Estimate frequency using harmonic product spectrum.
Note: Low frequency noise piles up and overwhelms the desired peaks.
From: https://gist.github.com/endolith/255291 and
https://github.com/endolith/waveform-analyzer
Parameters
----------
signal : list or array
time series data
fs : integer
sample rate
Returns
-------
frequency : float
frequency (Hz)<|endoftext|> |
6bf9836067a8b5c788dfe1cda27532a765aa717d1b7d0bbac0cf5588708489bc | def __init__(self):
'Base\n '
super(WordClassifierBase, self).__init__() | Base | python/baseline/tf/classify/model.py | __init__ | ZhenyueChin/baseline | 2 | python | def __init__(self):
'\n '
super(WordClassifier, self).__init__() | def __init__(self):
'\n '
super(WordClassifier, self).__init__()<|docstring|>Base<|endoftext|> |
e813df12e1098c330d9a051faaf26c780442d24155c521fc91767185347313fd | def create_loss(self):
'The loss function is currently provided here, although this is not a great place for it\n as it provides a coupling between the model and its loss function. Just here for convenience at the moment.\n \n :return: \n '
with tf.name_scope('loss'):
loss = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=tf.cast(self.y, 'float'))
all_loss = tf.reduce_mean(loss)
return all_loss | The loss function is currently provided here, although this is not a great place for it
as it provides a coupling between the model and its loss function. Just here for convenience at the moment.
:return: | python/baseline/tf/classify/model.py | create_loss | ZhenyueChin/baseline | 2 | python | def create_loss(self):
'The loss function is currently provided here, although this is not a great place for it\n as it provides a coupling between the model and its loss function. Just here for convenience at the moment.\n \n :return: \n '
with tf.name_scope('loss'):
loss = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=tf.cast(self.y, 'float'))
all_loss = tf.reduce_mean(loss)
return all_loss | def create_loss(self):
'The loss function is currently provided here, although this is not a great place for it\n as it provides a coupling between the model and its loss function. Just here for convenience at the moment.\n \n :return: \n '
with tf.name_scope('loss'):
loss = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=tf.cast(self.y, 'float'))
all_loss = tf.reduce_mean(loss)
return all_loss<|docstring|>The loss function is currently provided here, although this is not a great place for it
as it provides a coupling between the model and its loss function. Just here for convenience at the moment.
:return:<|endoftext|> |
ce07185189c5fc16e93831cf7c4fb3c00f2c1107fd7b1fbd09f4c04136619995 | def classify(self, batch_dict):
'This method provides a basic routine to run "inference" or predict outputs based on data.\n It runs the `x` tensor in (`BxT`), and turns dropout off, running the network all the way to a softmax\n output\n \n :param batch_dict: (``dict``) contains `x` tensor of input (`BxT`)\n :return: Each outcome as a ``list`` of tuples `(label, probability)`\n '
feed_dict = self.make_input(batch_dict)
probs = self.sess.run(tf.nn.softmax(self.logits), feed_dict=feed_dict)
results = []
batchsz = probs.shape[0]
for b in range(batchsz):
outcomes = [(self.labels[id_i], prob_i) for (id_i, prob_i) in enumerate(probs[b])]
results.append(outcomes)
return results | This method provides a basic routine to run "inference" or predict outputs based on data.
It runs the `x` tensor in (`BxT`), and turns dropout off, running the network all the way to a softmax
output
:param batch_dict: (``dict``) contains `x` tensor of input (`BxT`)
:return: Each outcome as a ``list`` of tuples `(label, probability)` | python/baseline/tf/classify/model.py | classify | ZhenyueChin/baseline | 2 | python | def classify(self, batch_dict):
'This method provides a basic routine to run "inference" or predict outputs based on data.\n It runs the `x` tensor in (`BxT`), and turns dropout off, running the network all the way to a softmax\n output\n \n :param batch_dict: (``dict``) contains `x` tensor of input (`BxT`)\n :return: Each outcome as a ``list`` of tuples `(label, probability)`\n '
feed_dict = self.make_input(batch_dict)
probs = self.sess.run(tf.nn.softmax(self.logits), feed_dict=feed_dict)
results = []
batchsz = probs.shape[0]
for b in range(batchsz):
outcomes = [(self.labels[id_i], prob_i) for (id_i, prob_i) in enumerate(probs[b])]
results.append(outcomes)
return results | def classify(self, batch_dict):
'This method provides a basic routine to run "inference" or predict outputs based on data.\n It runs the `x` tensor in (`BxT`), and turns dropout off, running the network all the way to a softmax\n output\n \n :param batch_dict: (``dict``) contains `x` tensor of input (`BxT`)\n :return: Each outcome as a ``list`` of tuples `(label, probability)`\n '
feed_dict = self.make_input(batch_dict)
probs = self.sess.run(tf.nn.softmax(self.logits), feed_dict=feed_dict)
results = []
batchsz = probs.shape[0]
for b in range(batchsz):
outcomes = [(self.labels[id_i], prob_i) for (id_i, prob_i) in enumerate(probs[b])]
results.append(outcomes)
return results<|docstring|>This method provides a basic routine to run "inference" or predict outputs based on data.
It runs the `x` tensor in (`BxT`), and turns dropout off, running the network all the way to a softmax
output
:param batch_dict: (``dict``) contains `x` tensor of input (`BxT`)
:return: Each outcome as a ``list`` of tuples `(label, probability)`<|endoftext|> |
f5ad7c6967038a7e1de47e778a4d498a56665f6a474d8c642faee409492c8d89 | def get_labels(self):
'Get the string labels back\n \n :return: labels\n '
return self.labels | Get the string labels back
:return: labels | python/baseline/tf/classify/model.py | get_labels | ZhenyueChin/baseline | 2 | python | def get_labels(self):
'Get the string labels back\n \n :return: labels\n '
return self.labels | def get_labels(self):
'Get the string labels back\n \n :return: labels\n '
return self.labels<|docstring|>Get the string labels back
:return: labels<|endoftext|> |
92c43eab0b4cb8ee7a53bf966f1f07e8938b39b79b075b3b7cecdc0ee4a864f9 | def get_vocab(self, name='word'):
'Get the vocab back, as a ``dict`` of ``str`` keys mapped to ``int`` values\n \n :return: A ``dict`` of words mapped to indices\n '
return self.vocab.get(name) | Get the vocab back, as a ``dict`` of ``str`` keys mapped to ``int`` values
:return: A ``dict`` of words mapped to indices | python/baseline/tf/classify/model.py | get_vocab | ZhenyueChin/baseline | 2 | python | def get_vocab(self, name='word'):
'Get the vocab back, as a ``dict`` of ``str`` keys mapped to ``int`` values\n \n :return: A ``dict`` of words mapped to indices\n '
return self.vocab.get(name) | def get_vocab(self, name='word'):
'Get the vocab back, as a ``dict`` of ``str`` keys mapped to ``int`` values\n \n :return: A ``dict`` of words mapped to indices\n '
return self.vocab.get(name)<|docstring|>Get the vocab back, as a ``dict`` of ``str`` keys mapped to ``int`` values
:return: A ``dict`` of words mapped to indices<|endoftext|> |
943c966e9f8eff164a8856c4055832d53b5674c9c45419397c95ff69a2226f0e | @classmethod
def load(cls, basename, **kwargs):
'Reload the model from a graph file and a checkpoint\n \n The model that is loaded is independent of the pooling and stacking layers, making this class reusable\n by sub-classes.\n \n :param basename: The base directory to load from\n :param kwargs: See below\n \n :Keyword Arguments:\n * *session* -- An optional tensorflow session. If not passed, a new session is\n created\n \n :return: A restored model\n '
sess = kwargs.get('session', kwargs.get('sess', tf.Session()))
model = cls()
with open((basename + '.saver')) as fsv:
saver_def = tf.train.SaverDef()
text_format.Merge(fsv.read(), saver_def)
checkpoint_name = kwargs.get('checkpoint_name', basename)
checkpoint_name = (checkpoint_name or basename)
with gfile.FastGFile((basename + '.graph'), 'rb') as f:
gd = tf.GraphDef()
gd.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(gd, name='')
try:
sess.run(saver_def.restore_op_name, {saver_def.filename_tensor_name: checkpoint_name})
except:
sess.run(saver_def.restore_op_name, {saver_def.filename_tensor_name: (checkpoint_name + '.model')})
model.x = tf.get_default_graph().get_tensor_by_name('x:0')
model.y = tf.get_default_graph().get_tensor_by_name('y:0')
try:
model.xch = tf.get_default_graph().get_tensor_by_name('xch:0')
except:
model.xch = None
try:
model.lengths = tf.get_default_graph().get_tensor_by_name('lengths:0')
except:
model.lengths = None
model.pkeep = tf.get_default_graph().get_tensor_by_name('pkeep:0')
model.best = tf.get_default_graph().get_tensor_by_name('output/best:0')
model.logits = tf.get_default_graph().get_tensor_by_name('output/logits:0')
with open((basename + '.labels'), 'r') as f:
model.labels = json.load(f)
model.vocab = {}
if os.path.exists((basename + '.vocab')):
with open((basename + '.vocab'), 'r') as f:
model.vocab['word'] = json.load(f)
else:
vocab_suffixes = get_vocab_file_suffixes(basename)
for ty in vocab_suffixes:
vocab_file = '{}-{}.vocab'.format(basename, ty)
print('Reading {}'.format(vocab_file))
with open(vocab_file, 'r') as f:
model.vocab[ty] = json.load(f)
model.sess = sess
model.load_md(basename)
return model | Reload the model from a graph file and a checkpoint
The model that is loaded is independent of the pooling and stacking layers, making this class reusable
by sub-classes.
:param basename: The base directory to load from
:param kwargs: See below
:Keyword Arguments:
* *session* -- An optional tensorflow session. If not passed, a new session is
created
:return: A restored model | python/baseline/tf/classify/model.py | load | ZhenyueChin/baseline | 2 | python | @classmethod
def load(cls, basename, **kwargs):
'Reload the model from a graph file and a checkpoint\n \n The model that is loaded is independent of the pooling and stacking layers, making this class reusable\n by sub-classes.\n \n :param basename: The base directory to load from\n :param kwargs: See below\n \n :Keyword Arguments:\n * *session* -- An optional tensorflow session. If not passed, a new session is\n created\n \n :return: A restored model\n '
sess = kwargs.get('session', kwargs.get('sess', tf.Session()))
model = cls()
with open((basename + '.saver')) as fsv:
saver_def = tf.train.SaverDef()
text_format.Merge(fsv.read(), saver_def)
checkpoint_name = kwargs.get('checkpoint_name', basename)
checkpoint_name = (checkpoint_name or basename)
with gfile.FastGFile((basename + '.graph'), 'rb') as f:
gd = tf.GraphDef()
gd.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(gd, name=)
try:
sess.run(saver_def.restore_op_name, {saver_def.filename_tensor_name: checkpoint_name})
except:
sess.run(saver_def.restore_op_name, {saver_def.filename_tensor_name: (checkpoint_name + '.model')})
model.x = tf.get_default_graph().get_tensor_by_name('x:0')
model.y = tf.get_default_graph().get_tensor_by_name('y:0')
try:
model.xch = tf.get_default_graph().get_tensor_by_name('xch:0')
except:
model.xch = None
try:
model.lengths = tf.get_default_graph().get_tensor_by_name('lengths:0')
except:
model.lengths = None
model.pkeep = tf.get_default_graph().get_tensor_by_name('pkeep:0')
model.best = tf.get_default_graph().get_tensor_by_name('output/best:0')
model.logits = tf.get_default_graph().get_tensor_by_name('output/logits:0')
with open((basename + '.labels'), 'r') as f:
model.labels = json.load(f)
model.vocab = {}
if os.path.exists((basename + '.vocab')):
with open((basename + '.vocab'), 'r') as f:
model.vocab['word'] = json.load(f)
else:
vocab_suffixes = get_vocab_file_suffixes(basename)
for ty in vocab_suffixes:
vocab_file = '{}-{}.vocab'.format(basename, ty)
print('Reading {}'.format(vocab_file))
with open(vocab_file, 'r') as f:
model.vocab[ty] = json.load(f)
model.sess = sess
model.load_md(basename)
return model | @classmethod
def load(cls, basename, **kwargs):
'Reload the model from a graph file and a checkpoint\n \n The model that is loaded is independent of the pooling and stacking layers, making this class reusable\n by sub-classes.\n \n :param basename: The base directory to load from\n :param kwargs: See below\n \n :Keyword Arguments:\n * *session* -- An optional tensorflow session. If not passed, a new session is\n created\n \n :return: A restored model\n '
sess = kwargs.get('session', kwargs.get('sess', tf.Session()))
model = cls()
with open((basename + '.saver')) as fsv:
saver_def = tf.train.SaverDef()
text_format.Merge(fsv.read(), saver_def)
checkpoint_name = kwargs.get('checkpoint_name', basename)
checkpoint_name = (checkpoint_name or basename)
with gfile.FastGFile((basename + '.graph'), 'rb') as f:
gd = tf.GraphDef()
gd.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(gd, name=)
try:
sess.run(saver_def.restore_op_name, {saver_def.filename_tensor_name: checkpoint_name})
except:
sess.run(saver_def.restore_op_name, {saver_def.filename_tensor_name: (checkpoint_name + '.model')})
model.x = tf.get_default_graph().get_tensor_by_name('x:0')
model.y = tf.get_default_graph().get_tensor_by_name('y:0')
try:
model.xch = tf.get_default_graph().get_tensor_by_name('xch:0')
except:
model.xch = None
try:
model.lengths = tf.get_default_graph().get_tensor_by_name('lengths:0')
except:
model.lengths = None
model.pkeep = tf.get_default_graph().get_tensor_by_name('pkeep:0')
model.best = tf.get_default_graph().get_tensor_by_name('output/best:0')
model.logits = tf.get_default_graph().get_tensor_by_name('output/logits:0')
with open((basename + '.labels'), 'r') as f:
model.labels = json.load(f)
model.vocab = {}
if os.path.exists((basename + '.vocab')):
with open((basename + '.vocab'), 'r') as f:
model.vocab['word'] = json.load(f)
else:
vocab_suffixes = get_vocab_file_suffixes(basename)
for ty in vocab_suffixes:
vocab_file = '{}-{}.vocab'.format(basename, ty)
print('Reading {}'.format(vocab_file))
with open(vocab_file, 'r') as f:
model.vocab[ty] = json.load(f)
model.sess = sess
model.load_md(basename)
return model<|docstring|>Reload the model from a graph file and a checkpoint
The model that is loaded is independent of the pooling and stacking layers, making this class reusable
by sub-classes.
:param basename: The base directory to load from
:param kwargs: See below
:Keyword Arguments:
* *session* -- An optional tensorflow session. If not passed, a new session is
created
:return: A restored model<|endoftext|> |
d012d9275c34973a12a5e724cd80949f96f339231c2ae6599fbf1224c53cfdfa | @classmethod
def create(cls, embeddings, labels, **kwargs):
'The main method for creating all :class:`WordBasedModel` types.\n \n This method instantiates a model with pooling and optional stacking layers.\n Many of the arguments provided are reused by each implementation, but some sub-classes need more\n information in order to properly initialize. For this reason, the full list of keyword args are passed\n to the :method:`pool` and :method:`stacked` methods.\n \n :param embeddings: This is a dictionary of embeddings, mapped to their numerical indices in the lookup table\n :param labels: This is a list of the `str` labels\n :param kwargs: See below\n \n :Keyword Arguments:\n * *model_type* -- The string name for the model (defaults to `default`)\n * *session* -- An optional tensorflow session. If not passed, a new session is\n created\n * *finetune* -- Are we doing fine-tuning of word embeddings (defaults to `True`)\n * *mxlen* -- The maximum signal (`x` tensor temporal) length (defaults to `100`)\n * *dropout* -- This indicates how much dropout should be applied to the model when training.\n * *pkeep* -- By default, this is a `tf.placeholder`, but it can be passed in as part of a sub-graph.\n This is useful for exporting tensorflow models or potentially for using input tf queues\n * *x* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.\n * *y* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.\n * *filtsz* -- This is actually a top-level param due to an unfortunate coupling between the pooling layer\n and the input, which, for convolution, requires input padding.\n \n :return: A fully-initialized tensorflow classifier \n '
gpus = kwargs.get('gpus')
if (gpus is not None):
return ClassifyParallelModel(cls.create, embeddings, labels, **kwargs)
sess = kwargs.get('sess', tf.Session())
finetune = bool(kwargs.get('finetune', True))
w2v = embeddings['word']
c2v = embeddings.get('char')
model = cls()
word_dsz = w2v.dsz
wchsz = 0
model.labels = labels
nc = len(labels)
model.vocab = {}
for k in embeddings.keys():
model.vocab[k] = embeddings[k].vocab
model.mxlen = int(kwargs.get('mxlen', 100))
model.mxwlen = None
model.pkeep = kwargs.get('pkeep', tf.placeholder_with_default(1.0, shape=(), name='pkeep'))
model.pdrop_value = kwargs.get('dropout', 0.5)
model.x = kwargs.get('x', tf.placeholder(tf.int32, [None, model.mxlen], name='x'))
model.y = kwargs.get('y', tf.placeholder(tf.int32, [None, nc], name='y'))
model.lengths = kwargs.get('lengths', tf.placeholder(tf.int32, [None], name='lengths'))
model.xch = None
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
seed = np.random.randint(1000000000.0)
init = tf.random_uniform_initializer((- 0.05), 0.05, dtype=tf.float32, seed=seed)
xavier_init = xavier_initializer(True, seed)
with tf.name_scope('LUT'):
W = tf.get_variable('W', initializer=tf.constant_initializer(w2v.weights, dtype=tf.float32, verify_shape=True), shape=[len(w2v.vocab), w2v.dsz], trainable=finetune)
e0 = tf.scatter_update(W, tf.constant(0, dtype=tf.int32, shape=[1]), tf.zeros(shape=[1, word_dsz]))
with tf.control_dependencies([e0]):
word_embeddings = tf.nn.embedding_lookup(W, model.x)
if (c2v is not None):
model.mxwlen = int(kwargs.get('mxwlen', 40))
model.xch = kwargs.get('xch', tf.placeholder(tf.int32, [None, model.mxlen, model.mxwlen], name='xch'))
char_dsz = c2v.dsz
with tf.name_scope('CharLUT'):
Wch = tf.get_variable('Wch', initializer=tf.constant_initializer(c2v.weights, dtype=tf.float32, verify_shape=True), shape=[len(c2v.vocab), c2v.dsz], trainable=True)
ech0 = tf.scatter_update(Wch, tf.constant(0, dtype=tf.int32, shape=[1]), tf.zeros(shape=[1, char_dsz]))
(char_comp, wchsz) = pool_chars(model.xch, Wch, ech0, char_dsz, **kwargs)
word_embeddings = tf.concat(values=[word_embeddings, char_comp], axis=2)
input_sz = (word_dsz + wchsz)
pooled = model.pool(word_embeddings, input_sz, init, **kwargs)
stacked = model.stacked(pooled, init, **kwargs)
with tf.contrib.slim.arg_scope([fully_connected], weights_initializer=xavier_init):
with tf.name_scope('output'):
model.logits = tf.identity(fully_connected(stacked, nc, activation_fn=None), name='logits')
model.best = tf.argmax(model.logits, 1, name='best')
model.sess = sess
return model | The main method for creating all :class:`WordBasedModel` types.
This method instantiates a model with pooling and optional stacking layers.
Many of the arguments provided are reused by each implementation, but some sub-classes need more
information in order to properly initialize. For this reason, the full list of keyword args are passed
to the :method:`pool` and :method:`stacked` methods.
:param embeddings: This is a dictionary of embeddings, mapped to their numerical indices in the lookup table
:param labels: This is a list of the `str` labels
:param kwargs: See below
:Keyword Arguments:
* *model_type* -- The string name for the model (defaults to `default`)
* *session* -- An optional tensorflow session. If not passed, a new session is
created
* *finetune* -- Are we doing fine-tuning of word embeddings (defaults to `True`)
* *mxlen* -- The maximum signal (`x` tensor temporal) length (defaults to `100`)
* *dropout* -- This indicates how much dropout should be applied to the model when training.
* *pkeep* -- By default, this is a `tf.placeholder`, but it can be passed in as part of a sub-graph.
This is useful for exporting tensorflow models or potentially for using input tf queues
* *x* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.
* *y* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.
* *filtsz* -- This is actually a top-level param due to an unfortunate coupling between the pooling layer
and the input, which, for convolution, requires input padding.
:return: A fully-initialized tensorflow classifier | python/baseline/tf/classify/model.py | create | ZhenyueChin/baseline | 2 | python | @classmethod
def create(cls, embeddings, labels, **kwargs):
'The main method for creating all :class:`WordBasedModel` types.\n \n This method instantiates a model with pooling and optional stacking layers.\n Many of the arguments provided are reused by each implementation, but some sub-classes need more\n information in order to properly initialize. For this reason, the full list of keyword args are passed\n to the :method:`pool` and :method:`stacked` methods.\n \n :param embeddings: This is a dictionary of embeddings, mapped to their numerical indices in the lookup table\n :param labels: This is a list of the `str` labels\n :param kwargs: See below\n \n :Keyword Arguments:\n * *model_type* -- The string name for the model (defaults to `default`)\n * *session* -- An optional tensorflow session. If not passed, a new session is\n created\n * *finetune* -- Are we doing fine-tuning of word embeddings (defaults to `True`)\n * *mxlen* -- The maximum signal (`x` tensor temporal) length (defaults to `100`)\n * *dropout* -- This indicates how much dropout should be applied to the model when training.\n * *pkeep* -- By default, this is a `tf.placeholder`, but it can be passed in as part of a sub-graph.\n This is useful for exporting tensorflow models or potentially for using input tf queues\n * *x* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.\n * *y* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.\n * *filtsz* -- This is actually a top-level param due to an unfortunate coupling between the pooling layer\n and the input, which, for convolution, requires input padding.\n \n :return: A fully-initialized tensorflow classifier \n '
gpus = kwargs.get('gpus')
if (gpus is not None):
return ClassifyParallelModel(cls.create, embeddings, labels, **kwargs)
sess = kwargs.get('sess', tf.Session())
finetune = bool(kwargs.get('finetune', True))
w2v = embeddings['word']
c2v = embeddings.get('char')
model = cls()
word_dsz = w2v.dsz
wchsz = 0
model.labels = labels
nc = len(labels)
model.vocab = {}
for k in embeddings.keys():
model.vocab[k] = embeddings[k].vocab
model.mxlen = int(kwargs.get('mxlen', 100))
model.mxwlen = None
model.pkeep = kwargs.get('pkeep', tf.placeholder_with_default(1.0, shape=(), name='pkeep'))
model.pdrop_value = kwargs.get('dropout', 0.5)
model.x = kwargs.get('x', tf.placeholder(tf.int32, [None, model.mxlen], name='x'))
model.y = kwargs.get('y', tf.placeholder(tf.int32, [None, nc], name='y'))
model.lengths = kwargs.get('lengths', tf.placeholder(tf.int32, [None], name='lengths'))
model.xch = None
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
seed = np.random.randint(1000000000.0)
init = tf.random_uniform_initializer((- 0.05), 0.05, dtype=tf.float32, seed=seed)
xavier_init = xavier_initializer(True, seed)
with tf.name_scope('LUT'):
W = tf.get_variable('W', initializer=tf.constant_initializer(w2v.weights, dtype=tf.float32, verify_shape=True), shape=[len(w2v.vocab), w2v.dsz], trainable=finetune)
e0 = tf.scatter_update(W, tf.constant(0, dtype=tf.int32, shape=[1]), tf.zeros(shape=[1, word_dsz]))
with tf.control_dependencies([e0]):
word_embeddings = tf.nn.embedding_lookup(W, model.x)
if (c2v is not None):
model.mxwlen = int(kwargs.get('mxwlen', 40))
model.xch = kwargs.get('xch', tf.placeholder(tf.int32, [None, model.mxlen, model.mxwlen], name='xch'))
char_dsz = c2v.dsz
with tf.name_scope('CharLUT'):
Wch = tf.get_variable('Wch', initializer=tf.constant_initializer(c2v.weights, dtype=tf.float32, verify_shape=True), shape=[len(c2v.vocab), c2v.dsz], trainable=True)
ech0 = tf.scatter_update(Wch, tf.constant(0, dtype=tf.int32, shape=[1]), tf.zeros(shape=[1, char_dsz]))
(char_comp, wchsz) = pool_chars(model.xch, Wch, ech0, char_dsz, **kwargs)
word_embeddings = tf.concat(values=[word_embeddings, char_comp], axis=2)
input_sz = (word_dsz + wchsz)
pooled = model.pool(word_embeddings, input_sz, init, **kwargs)
stacked = model.stacked(pooled, init, **kwargs)
with tf.contrib.slim.arg_scope([fully_connected], weights_initializer=xavier_init):
with tf.name_scope('output'):
model.logits = tf.identity(fully_connected(stacked, nc, activation_fn=None), name='logits')
model.best = tf.argmax(model.logits, 1, name='best')
model.sess = sess
return model | @classmethod
def create(cls, embeddings, labels, **kwargs):
'The main method for creating all :class:`WordBasedModel` types.\n \n This method instantiates a model with pooling and optional stacking layers.\n Many of the arguments provided are reused by each implementation, but some sub-classes need more\n information in order to properly initialize. For this reason, the full list of keyword args are passed\n to the :method:`pool` and :method:`stacked` methods.\n \n :param embeddings: This is a dictionary of embeddings, mapped to their numerical indices in the lookup table\n :param labels: This is a list of the `str` labels\n :param kwargs: See below\n \n :Keyword Arguments:\n * *model_type* -- The string name for the model (defaults to `default`)\n * *session* -- An optional tensorflow session. If not passed, a new session is\n created\n * *finetune* -- Are we doing fine-tuning of word embeddings (defaults to `True`)\n * *mxlen* -- The maximum signal (`x` tensor temporal) length (defaults to `100`)\n * *dropout* -- This indicates how much dropout should be applied to the model when training.\n * *pkeep* -- By default, this is a `tf.placeholder`, but it can be passed in as part of a sub-graph.\n This is useful for exporting tensorflow models or potentially for using input tf queues\n * *x* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.\n * *y* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.\n * *filtsz* -- This is actually a top-level param due to an unfortunate coupling between the pooling layer\n and the input, which, for convolution, requires input padding.\n \n :return: A fully-initialized tensorflow classifier \n '
gpus = kwargs.get('gpus')
if (gpus is not None):
return ClassifyParallelModel(cls.create, embeddings, labels, **kwargs)
sess = kwargs.get('sess', tf.Session())
finetune = bool(kwargs.get('finetune', True))
w2v = embeddings['word']
c2v = embeddings.get('char')
model = cls()
word_dsz = w2v.dsz
wchsz = 0
model.labels = labels
nc = len(labels)
model.vocab = {}
for k in embeddings.keys():
model.vocab[k] = embeddings[k].vocab
model.mxlen = int(kwargs.get('mxlen', 100))
model.mxwlen = None
model.pkeep = kwargs.get('pkeep', tf.placeholder_with_default(1.0, shape=(), name='pkeep'))
model.pdrop_value = kwargs.get('dropout', 0.5)
model.x = kwargs.get('x', tf.placeholder(tf.int32, [None, model.mxlen], name='x'))
model.y = kwargs.get('y', tf.placeholder(tf.int32, [None, nc], name='y'))
model.lengths = kwargs.get('lengths', tf.placeholder(tf.int32, [None], name='lengths'))
model.xch = None
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
seed = np.random.randint(1000000000.0)
init = tf.random_uniform_initializer((- 0.05), 0.05, dtype=tf.float32, seed=seed)
xavier_init = xavier_initializer(True, seed)
with tf.name_scope('LUT'):
W = tf.get_variable('W', initializer=tf.constant_initializer(w2v.weights, dtype=tf.float32, verify_shape=True), shape=[len(w2v.vocab), w2v.dsz], trainable=finetune)
e0 = tf.scatter_update(W, tf.constant(0, dtype=tf.int32, shape=[1]), tf.zeros(shape=[1, word_dsz]))
with tf.control_dependencies([e0]):
word_embeddings = tf.nn.embedding_lookup(W, model.x)
if (c2v is not None):
model.mxwlen = int(kwargs.get('mxwlen', 40))
model.xch = kwargs.get('xch', tf.placeholder(tf.int32, [None, model.mxlen, model.mxwlen], name='xch'))
char_dsz = c2v.dsz
with tf.name_scope('CharLUT'):
Wch = tf.get_variable('Wch', initializer=tf.constant_initializer(c2v.weights, dtype=tf.float32, verify_shape=True), shape=[len(c2v.vocab), c2v.dsz], trainable=True)
ech0 = tf.scatter_update(Wch, tf.constant(0, dtype=tf.int32, shape=[1]), tf.zeros(shape=[1, char_dsz]))
(char_comp, wchsz) = pool_chars(model.xch, Wch, ech0, char_dsz, **kwargs)
word_embeddings = tf.concat(values=[word_embeddings, char_comp], axis=2)
input_sz = (word_dsz + wchsz)
pooled = model.pool(word_embeddings, input_sz, init, **kwargs)
stacked = model.stacked(pooled, init, **kwargs)
with tf.contrib.slim.arg_scope([fully_connected], weights_initializer=xavier_init):
with tf.name_scope('output'):
model.logits = tf.identity(fully_connected(stacked, nc, activation_fn=None), name='logits')
model.best = tf.argmax(model.logits, 1, name='best')
model.sess = sess
return model<|docstring|>The main method for creating all :class:`WordBasedModel` types.
This method instantiates a model with pooling and optional stacking layers.
Many of the arguments provided are reused by each implementation, but some sub-classes need more
information in order to properly initialize. For this reason, the full list of keyword args are passed
to the :method:`pool` and :method:`stacked` methods.
:param embeddings: This is a dictionary of embeddings, mapped to their numerical indices in the lookup table
:param labels: This is a list of the `str` labels
:param kwargs: See below
:Keyword Arguments:
* *model_type* -- The string name for the model (defaults to `default`)
* *session* -- An optional tensorflow session. If not passed, a new session is
created
* *finetune* -- Are we doing fine-tuning of word embeddings (defaults to `True`)
* *mxlen* -- The maximum signal (`x` tensor temporal) length (defaults to `100`)
* *dropout* -- This indicates how much dropout should be applied to the model when training.
* *pkeep* -- By default, this is a `tf.placeholder`, but it can be passed in as part of a sub-graph.
This is useful for exporting tensorflow models or potentially for using input tf queues
* *x* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.
* *y* -- By default, this is a `tf.placeholder`, but it can be optionally passed as part of a sub-graph.
* *filtsz* -- This is actually a top-level param due to an unfortunate coupling between the pooling layer
and the input, which, for convolution, requires input padding.
:return: A fully-initialized tensorflow classifier<|endoftext|> |
c7442e37d20a46221ddec7e59544f8c2a5d21019d4bc38fea09d047a36afcc7e | def pool(self, word_embeddings, dsz, init, **kwargs):
'This method performs a transformation between a temporal signal and a fixed representation\n \n :param word_embeddings: The output of the embedded lookup, which is the starting point for this operation\n :param dsz: The depth of the embeddings\n :param init: The tensorflow initializer to use for these methods\n :param kwargs: Model-specific arguments\n :return: A fixed representation of the data\n '
pass | This method performs a transformation between a temporal signal and a fixed representation
:param word_embeddings: The output of the embedded lookup, which is the starting point for this operation
:param dsz: The depth of the embeddings
:param init: The tensorflow initializer to use for these methods
:param kwargs: Model-specific arguments
:return: A fixed representation of the data | python/baseline/tf/classify/model.py | pool | ZhenyueChin/baseline | 2 | python | def pool(self, word_embeddings, dsz, init, **kwargs):
'This method performs a transformation between a temporal signal and a fixed representation\n \n :param word_embeddings: The output of the embedded lookup, which is the starting point for this operation\n :param dsz: The depth of the embeddings\n :param init: The tensorflow initializer to use for these methods\n :param kwargs: Model-specific arguments\n :return: A fixed representation of the data\n '
pass | def pool(self, word_embeddings, dsz, init, **kwargs):
'This method performs a transformation between a temporal signal and a fixed representation\n \n :param word_embeddings: The output of the embedded lookup, which is the starting point for this operation\n :param dsz: The depth of the embeddings\n :param init: The tensorflow initializer to use for these methods\n :param kwargs: Model-specific arguments\n :return: A fixed representation of the data\n '
pass<|docstring|>This method performs a transformation between a temporal signal and a fixed representation
:param word_embeddings: The output of the embedded lookup, which is the starting point for this operation
:param dsz: The depth of the embeddings
:param init: The tensorflow initializer to use for these methods
:param kwargs: Model-specific arguments
:return: A fixed representation of the data<|endoftext|> |
ee06ddebc5f8c022e4771df363f1e9e34ca77c0a8f651b85f6a32c0abfeda92b | def stacked(self, pooled, init, **kwargs):
'Stack 1 or more hidden layers, optionally (forming an MLP)\n\n :param pooled: The fixed representation of the model\n :param init: The tensorflow initializer\n :param kwargs: See below\n\n :Keyword Arguments:\n * *hsz* -- (``int``) The number of hidden units (defaults to `100`)\n\n :return: The final layer\n '
hszs = listify(kwargs.get('hsz', []))
if (len(hszs) == 0):
return pooled
in_layer = pooled
for (i, hsz) in enumerate(hszs):
with tf.variable_scope('fc-{}'.format(i)):
with tf.contrib.slim.arg_scope([fully_connected], weights_initializer=init):
fc = fully_connected(in_layer, hsz, activation_fn=tf.nn.relu)
in_layer = tf.nn.dropout(fc, self.pkeep)
return in_layer | Stack 1 or more hidden layers, optionally (forming an MLP)
:param pooled: The fixed representation of the model
:param init: The tensorflow initializer
:param kwargs: See below
:Keyword Arguments:
* *hsz* -- (``int``) The number of hidden units (defaults to `100`)
:return: The final layer | python/baseline/tf/classify/model.py | stacked | ZhenyueChin/baseline | 2 | python | def stacked(self, pooled, init, **kwargs):
'Stack 1 or more hidden layers, optionally (forming an MLP)\n\n :param pooled: The fixed representation of the model\n :param init: The tensorflow initializer\n :param kwargs: See below\n\n :Keyword Arguments:\n * *hsz* -- (``int``) The number of hidden units (defaults to `100`)\n\n :return: The final layer\n '
hszs = listify(kwargs.get('hsz', []))
if (len(hszs) == 0):
return pooled
in_layer = pooled
for (i, hsz) in enumerate(hszs):
with tf.variable_scope('fc-{}'.format(i)):
with tf.contrib.slim.arg_scope([fully_connected], weights_initializer=init):
fc = fully_connected(in_layer, hsz, activation_fn=tf.nn.relu)
in_layer = tf.nn.dropout(fc, self.pkeep)
return in_layer | def stacked(self, pooled, init, **kwargs):
'Stack 1 or more hidden layers, optionally (forming an MLP)\n\n :param pooled: The fixed representation of the model\n :param init: The tensorflow initializer\n :param kwargs: See below\n\n :Keyword Arguments:\n * *hsz* -- (``int``) The number of hidden units (defaults to `100`)\n\n :return: The final layer\n '
hszs = listify(kwargs.get('hsz', []))
if (len(hszs) == 0):
return pooled
in_layer = pooled
for (i, hsz) in enumerate(hszs):
with tf.variable_scope('fc-{}'.format(i)):
with tf.contrib.slim.arg_scope([fully_connected], weights_initializer=init):
fc = fully_connected(in_layer, hsz, activation_fn=tf.nn.relu)
in_layer = tf.nn.dropout(fc, self.pkeep)
return in_layer<|docstring|>Stack 1 or more hidden layers, optionally (forming an MLP)
:param pooled: The fixed representation of the model
:param init: The tensorflow initializer
:param kwargs: See below
:Keyword Arguments:
* *hsz* -- (``int``) The number of hidden units (defaults to `100`)
:return: The final layer<|endoftext|> |
c12649c9f3683cd1a74b30add793efd0df53cc3af60fd502b2a3389ad95a2872 | def __init__(self):
'Constructor \n '
super(ConvModel, self).__init__() | Constructor | python/baseline/tf/classify/model.py | __init__ | ZhenyueChin/baseline | 2 | python | def __init__(self):
' \n '
super(ConvModel, self).__init__() | def __init__(self):
' \n '
super(ConvModel, self).__init__()<|docstring|>Constructor<|endoftext|> |
c6a6069caacb042f21d4c3da64d7f2b4d1d9a5cfb74cde886972c60c5dc7cbea | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do parallel convolutional filtering with varied receptive field widths, followed by max-over-time pooling\n \n :param word_embeddings: The word embeddings, which are inputs here\n :param dsz: The depth of the word embeddings\n :param init: The tensorflow initializer\n :param kwargs: See below\n \n :Keyword Arguments:\n * *cmotsz* -- (``int``) The number of convolutional feature maps for each filter\n These are MOT-filtered, leaving this # of units per parallel filter\n * *filtsz* -- (``list``) This is a list of filter widths to use\n \n \n :return: \n '
cmotsz = kwargs['cmotsz']
filtsz = kwargs['filtsz']
(combine, _) = parallel_conv(word_embeddings, filtsz, dsz, cmotsz)
with tf.name_scope('dropout'):
combine = tf.nn.dropout(combine, self.pkeep)
return combine | Do parallel convolutional filtering with varied receptive field widths, followed by max-over-time pooling
:param word_embeddings: The word embeddings, which are inputs here
:param dsz: The depth of the word embeddings
:param init: The tensorflow initializer
:param kwargs: See below
:Keyword Arguments:
* *cmotsz* -- (``int``) The number of convolutional feature maps for each filter
These are MOT-filtered, leaving this # of units per parallel filter
* *filtsz* -- (``list``) This is a list of filter widths to use
:return: | python/baseline/tf/classify/model.py | pool | ZhenyueChin/baseline | 2 | python | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do parallel convolutional filtering with varied receptive field widths, followed by max-over-time pooling\n \n :param word_embeddings: The word embeddings, which are inputs here\n :param dsz: The depth of the word embeddings\n :param init: The tensorflow initializer\n :param kwargs: See below\n \n :Keyword Arguments:\n * *cmotsz* -- (``int``) The number of convolutional feature maps for each filter\n These are MOT-filtered, leaving this # of units per parallel filter\n * *filtsz* -- (``list``) This is a list of filter widths to use\n \n \n :return: \n '
cmotsz = kwargs['cmotsz']
filtsz = kwargs['filtsz']
(combine, _) = parallel_conv(word_embeddings, filtsz, dsz, cmotsz)
with tf.name_scope('dropout'):
combine = tf.nn.dropout(combine, self.pkeep)
return combine | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do parallel convolutional filtering with varied receptive field widths, followed by max-over-time pooling\n \n :param word_embeddings: The word embeddings, which are inputs here\n :param dsz: The depth of the word embeddings\n :param init: The tensorflow initializer\n :param kwargs: See below\n \n :Keyword Arguments:\n * *cmotsz* -- (``int``) The number of convolutional feature maps for each filter\n These are MOT-filtered, leaving this # of units per parallel filter\n * *filtsz* -- (``list``) This is a list of filter widths to use\n \n \n :return: \n '
cmotsz = kwargs['cmotsz']
filtsz = kwargs['filtsz']
(combine, _) = parallel_conv(word_embeddings, filtsz, dsz, cmotsz)
with tf.name_scope('dropout'):
combine = tf.nn.dropout(combine, self.pkeep)
return combine<|docstring|>Do parallel convolutional filtering with varied receptive field widths, followed by max-over-time pooling
:param word_embeddings: The word embeddings, which are inputs here
:param dsz: The depth of the word embeddings
:param init: The tensorflow initializer
:param kwargs: See below
:Keyword Arguments:
* *cmotsz* -- (``int``) The number of convolutional feature maps for each filter
These are MOT-filtered, leaving this # of units per parallel filter
* *filtsz* -- (``list``) This is a list of filter widths to use
:return:<|endoftext|> |
0c02f032a6df8e833872167b3b14204516c0552951c9f51a140185da63b5faff | def pool(self, word_embeddings, dsz, init, **kwargs):
'LSTM with dropout yielding a final-state as output\n \n :param word_embeddings: The input word embeddings\n :param dsz: The input word embedding depth\n :param init: The tensorflow initializer to use (currently ignored)\n :param kwargs: See below\n \n :Keyword Arguments:\n * *hsz* -- (``int``) The number of hidden units (defaults to `100`)\n * *cmotsz* -- (``int``) An alias for `hsz`\n \n :return: \n '
hsz = kwargs.get('rnnsz', kwargs.get('hsz', 100))
if (type(hsz) is list):
hsz = hsz[0]
char_rnnfwd = lstm_cell_w_dropout(hsz, self.pkeep)
(rnnout, final_state) = tf.nn.dynamic_rnn(char_rnnfwd, word_embeddings, dtype=tf.float32, sequence_length=self.lengths)
output_state = final_state.h
combine = tf.reshape(output_state, [(- 1), hsz])
return combine | LSTM with dropout yielding a final-state as output
:param word_embeddings: The input word embeddings
:param dsz: The input word embedding depth
:param init: The tensorflow initializer to use (currently ignored)
:param kwargs: See below
:Keyword Arguments:
* *hsz* -- (``int``) The number of hidden units (defaults to `100`)
* *cmotsz* -- (``int``) An alias for `hsz`
:return: | python/baseline/tf/classify/model.py | pool | ZhenyueChin/baseline | 2 | python | def pool(self, word_embeddings, dsz, init, **kwargs):
'LSTM with dropout yielding a final-state as output\n \n :param word_embeddings: The input word embeddings\n :param dsz: The input word embedding depth\n :param init: The tensorflow initializer to use (currently ignored)\n :param kwargs: See below\n \n :Keyword Arguments:\n * *hsz* -- (``int``) The number of hidden units (defaults to `100`)\n * *cmotsz* -- (``int``) An alias for `hsz`\n \n :return: \n '
hsz = kwargs.get('rnnsz', kwargs.get('hsz', 100))
if (type(hsz) is list):
hsz = hsz[0]
char_rnnfwd = lstm_cell_w_dropout(hsz, self.pkeep)
(rnnout, final_state) = tf.nn.dynamic_rnn(char_rnnfwd, word_embeddings, dtype=tf.float32, sequence_length=self.lengths)
output_state = final_state.h
combine = tf.reshape(output_state, [(- 1), hsz])
return combine | def pool(self, word_embeddings, dsz, init, **kwargs):
'LSTM with dropout yielding a final-state as output\n \n :param word_embeddings: The input word embeddings\n :param dsz: The input word embedding depth\n :param init: The tensorflow initializer to use (currently ignored)\n :param kwargs: See below\n \n :Keyword Arguments:\n * *hsz* -- (``int``) The number of hidden units (defaults to `100`)\n * *cmotsz* -- (``int``) An alias for `hsz`\n \n :return: \n '
hsz = kwargs.get('rnnsz', kwargs.get('hsz', 100))
if (type(hsz) is list):
hsz = hsz[0]
char_rnnfwd = lstm_cell_w_dropout(hsz, self.pkeep)
(rnnout, final_state) = tf.nn.dynamic_rnn(char_rnnfwd, word_embeddings, dtype=tf.float32, sequence_length=self.lengths)
output_state = final_state.h
combine = tf.reshape(output_state, [(- 1), hsz])
return combine<|docstring|>LSTM with dropout yielding a final-state as output
:param word_embeddings: The input word embeddings
:param dsz: The input word embedding depth
:param init: The tensorflow initializer to use (currently ignored)
:param kwargs: See below
:Keyword Arguments:
* *hsz* -- (``int``) The number of hidden units (defaults to `100`)
* *cmotsz* -- (``int``) An alias for `hsz`
:return:<|endoftext|> |
235c0c9b792031fbffcdf25d7489522c022e0f6f1e6a0fc8941071e52753d77b | def stacked(self, pooled, init, **kwargs):
'Force at least one hidden layer here\n\n :param pooled:\n :param init:\n :param kwargs:\n :return:\n '
kwargs['hsz'] = kwargs.get('hsz', [100])
return super(NBowBase, self).stacked() | Force at least one hidden layer here
:param pooled:
:param init:
:param kwargs:
:return: | python/baseline/tf/classify/model.py | stacked | ZhenyueChin/baseline | 2 | python | def stacked(self, pooled, init, **kwargs):
'Force at least one hidden layer here\n\n :param pooled:\n :param init:\n :param kwargs:\n :return:\n '
kwargs['hsz'] = kwargs.get('hsz', [100])
return super(NBowBase, self).stacked() | def stacked(self, pooled, init, **kwargs):
'Force at least one hidden layer here\n\n :param pooled:\n :param init:\n :param kwargs:\n :return:\n '
kwargs['hsz'] = kwargs.get('hsz', [100])
return super(NBowBase, self).stacked()<|docstring|>Force at least one hidden layer here
:param pooled:
:param init:
:param kwargs:
:return:<|endoftext|> |
11a99d9a72e129cba07e35d40e21a55b36014ff58bbbb283ed99eabc833f07a4 | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do average pooling on input embeddings, yielding a `dsz` output layer\n \n :param word_embeddings: The word embedding input\n :param dsz: The word embedding depth\n :param init: The tensorflow initializer\n :param kwargs: None\n :return: The average pooling representation\n '
return tf.reduce_mean(word_embeddings, 1, keep_dims=False) | Do average pooling on input embeddings, yielding a `dsz` output layer
:param word_embeddings: The word embedding input
:param dsz: The word embedding depth
:param init: The tensorflow initializer
:param kwargs: None
:return: The average pooling representation | python/baseline/tf/classify/model.py | pool | ZhenyueChin/baseline | 2 | python | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do average pooling on input embeddings, yielding a `dsz` output layer\n \n :param word_embeddings: The word embedding input\n :param dsz: The word embedding depth\n :param init: The tensorflow initializer\n :param kwargs: None\n :return: The average pooling representation\n '
return tf.reduce_mean(word_embeddings, 1, keep_dims=False) | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do average pooling on input embeddings, yielding a `dsz` output layer\n \n :param word_embeddings: The word embedding input\n :param dsz: The word embedding depth\n :param init: The tensorflow initializer\n :param kwargs: None\n :return: The average pooling representation\n '
return tf.reduce_mean(word_embeddings, 1, keep_dims=False)<|docstring|>Do average pooling on input embeddings, yielding a `dsz` output layer
:param word_embeddings: The word embedding input
:param dsz: The word embedding depth
:param init: The tensorflow initializer
:param kwargs: None
:return: The average pooling representation<|endoftext|> |
1fe80eae34bb24c3812ac7ec5584329fdeee1ca6695ff1a4a4cebac6e0f5f1b5 | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do max pooling on input embeddings, yielding a `dsz` output layer\n \n :param word_embeddings: The word embedding input\n :param dsz: The word embedding depth\n :param init: The tensorflow initializer\n :param kwargs: None\n :return: The max pooling representation\n '
return tf.reduce_max(word_embeddings, 1, keep_dims=False) | Do max pooling on input embeddings, yielding a `dsz` output layer
:param word_embeddings: The word embedding input
:param dsz: The word embedding depth
:param init: The tensorflow initializer
:param kwargs: None
:return: The max pooling representation | python/baseline/tf/classify/model.py | pool | ZhenyueChin/baseline | 2 | python | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do max pooling on input embeddings, yielding a `dsz` output layer\n \n :param word_embeddings: The word embedding input\n :param dsz: The word embedding depth\n :param init: The tensorflow initializer\n :param kwargs: None\n :return: The max pooling representation\n '
return tf.reduce_max(word_embeddings, 1, keep_dims=False) | def pool(self, word_embeddings, dsz, init, **kwargs):
'Do max pooling on input embeddings, yielding a `dsz` output layer\n \n :param word_embeddings: The word embedding input\n :param dsz: The word embedding depth\n :param init: The tensorflow initializer\n :param kwargs: None\n :return: The max pooling representation\n '
return tf.reduce_max(word_embeddings, 1, keep_dims=False)<|docstring|>Do max pooling on input embeddings, yielding a `dsz` output layer
:param word_embeddings: The word embedding input
:param dsz: The word embedding depth
:param init: The tensorflow initializer
:param kwargs: None
:return: The max pooling representation<|endoftext|> |
e59a8482080ada9c819c914ebe39f0a9aa47f1cb744029e770345e33bfd06184 | def get_version():
'\n Returns shorter version (digit parts only) as string.\n '
return '.'.join((str(each) for each in VERSION[:4])) | Returns shorter version (digit parts only) as string. | guardian/__init__.py | get_version | thedrow/django-guardian | 1 | python | def get_version():
'\n \n '
return '.'.join((str(each) for each in VERSION[:4])) | def get_version():
'\n \n '
return '.'.join((str(each) for each in VERSION[:4]))<|docstring|>Returns shorter version (digit parts only) as string.<|endoftext|> |
c5f5880f4115f850d5ffd24e5a045be055b1fca83eaef4597a83b8595227e989 | @pytest.mark.e2e_cpu
def test_noop_pause() -> None:
'\n Walk through starting, pausing, and resuming a single no-op experiment.\n '
experiment_id = exp.create_experiment(conf.fixtures_path('no_op/single-medium-train-step.yaml'), conf.fixtures_path('no_op'), None)
exp.wait_for_experiment_state(experiment_id, 'ACTIVE')
workload_active = False
for _ in range(conf.MAX_TASK_SCHEDULED_SECS):
workload_active = exp.experiment_has_active_workload(experiment_id)
if workload_active:
break
else:
time.sleep(1)
check.true(workload_active, f'The only trial cannot be scheduled within {conf.MAX_TASK_SCHEDULED_SECS} seconds.')
num_steps = 0
for _ in range(conf.MAX_TRIAL_BUILD_SECS):
trials = exp.experiment_trials(experiment_id)
if (len(trials) > 0):
only_trial = trials[0]
num_steps = len(only_trial['steps'])
if (num_steps > 1):
break
time.sleep(1)
check.true((num_steps > 1), f'The only trial cannot start training within {conf.MAX_TRIAL_BUILD_SECS} seconds.')
exp.pause_experiment(experiment_id)
exp.wait_for_experiment_state(experiment_id, 'PAUSED')
for _ in range(20):
workload_active = exp.experiment_has_active_workload(experiment_id)
if (not workload_active):
break
else:
time.sleep(1)
check.true((not workload_active), f'The experiment cannot be paused within 20 seconds.')
exp.activate_experiment(experiment_id)
exp.wait_for_experiment_state(experiment_id, 'COMPLETED') | Walk through starting, pausing, and resuming a single no-op experiment. | tests/integrations/experiment/test_noop.py | test_noop_pause | sidneyw/determined | 3 | python | @pytest.mark.e2e_cpu
def test_noop_pause() -> None:
'\n \n '
experiment_id = exp.create_experiment(conf.fixtures_path('no_op/single-medium-train-step.yaml'), conf.fixtures_path('no_op'), None)
exp.wait_for_experiment_state(experiment_id, 'ACTIVE')
workload_active = False
for _ in range(conf.MAX_TASK_SCHEDULED_SECS):
workload_active = exp.experiment_has_active_workload(experiment_id)
if workload_active:
break
else:
time.sleep(1)
check.true(workload_active, f'The only trial cannot be scheduled within {conf.MAX_TASK_SCHEDULED_SECS} seconds.')
num_steps = 0
for _ in range(conf.MAX_TRIAL_BUILD_SECS):
trials = exp.experiment_trials(experiment_id)
if (len(trials) > 0):
only_trial = trials[0]
num_steps = len(only_trial['steps'])
if (num_steps > 1):
break
time.sleep(1)
check.true((num_steps > 1), f'The only trial cannot start training within {conf.MAX_TRIAL_BUILD_SECS} seconds.')
exp.pause_experiment(experiment_id)
exp.wait_for_experiment_state(experiment_id, 'PAUSED')
for _ in range(20):
workload_active = exp.experiment_has_active_workload(experiment_id)
if (not workload_active):
break
else:
time.sleep(1)
check.true((not workload_active), f'The experiment cannot be paused within 20 seconds.')
exp.activate_experiment(experiment_id)
exp.wait_for_experiment_state(experiment_id, 'COMPLETED') | @pytest.mark.e2e_cpu
def test_noop_pause() -> None:
'\n \n '
experiment_id = exp.create_experiment(conf.fixtures_path('no_op/single-medium-train-step.yaml'), conf.fixtures_path('no_op'), None)
exp.wait_for_experiment_state(experiment_id, 'ACTIVE')
workload_active = False
for _ in range(conf.MAX_TASK_SCHEDULED_SECS):
workload_active = exp.experiment_has_active_workload(experiment_id)
if workload_active:
break
else:
time.sleep(1)
check.true(workload_active, f'The only trial cannot be scheduled within {conf.MAX_TASK_SCHEDULED_SECS} seconds.')
num_steps = 0
for _ in range(conf.MAX_TRIAL_BUILD_SECS):
trials = exp.experiment_trials(experiment_id)
if (len(trials) > 0):
only_trial = trials[0]
num_steps = len(only_trial['steps'])
if (num_steps > 1):
break
time.sleep(1)
check.true((num_steps > 1), f'The only trial cannot start training within {conf.MAX_TRIAL_BUILD_SECS} seconds.')
exp.pause_experiment(experiment_id)
exp.wait_for_experiment_state(experiment_id, 'PAUSED')
for _ in range(20):
workload_active = exp.experiment_has_active_workload(experiment_id)
if (not workload_active):
break
else:
time.sleep(1)
check.true((not workload_active), f'The experiment cannot be paused within 20 seconds.')
exp.activate_experiment(experiment_id)
exp.wait_for_experiment_state(experiment_id, 'COMPLETED')<|docstring|>Walk through starting, pausing, and resuming a single no-op experiment.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.