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
f793c3fd1b90376b5593ca6a130de772180119370b10b73aac9db29a09061af0
def deleteBucketObject(this, bucketName: str, key: str, versionId='null', region: str='', client=None, isTopAction=True): '\n Delete specific object from the bucket.\n\n Could be used to delete specified bucket object version.\n ' if (not client): client = this._getBotoClient('s3', region) if isTopAction: this.__confirmOperation('Bucket object deletion', '\n Bucket name: {}\n Object key: {}\n version id: {}\n '.format(bucketName, key, versionId)) client.delete_object(Bucket=bucketName, Key=key, VersionId=versionId)
Delete specific object from the bucket. Could be used to delete specified bucket object version.
awshelper.py
deleteBucketObject
andreyess/AWS-helper
0
python
def deleteBucketObject(this, bucketName: str, key: str, versionId='null', region: str=, client=None, isTopAction=True): '\n Delete specific object from the bucket.\n\n Could be used to delete specified bucket object version.\n ' if (not client): client = this._getBotoClient('s3', region) if isTopAction: this.__confirmOperation('Bucket object deletion', '\n Bucket name: {}\n Object key: {}\n version id: {}\n '.format(bucketName, key, versionId)) client.delete_object(Bucket=bucketName, Key=key, VersionId=versionId)
def deleteBucketObject(this, bucketName: str, key: str, versionId='null', region: str=, client=None, isTopAction=True): '\n Delete specific object from the bucket.\n\n Could be used to delete specified bucket object version.\n ' if (not client): client = this._getBotoClient('s3', region) if isTopAction: this.__confirmOperation('Bucket object deletion', '\n Bucket name: {}\n Object key: {}\n version id: {}\n '.format(bucketName, key, versionId)) client.delete_object(Bucket=bucketName, Key=key, VersionId=versionId)<|docstring|>Delete specific object from the bucket. Could be used to delete specified bucket object version.<|endoftext|>
9a92b410424793ef5b8b54c80fa94d2dbed28aadf3613a61737f11bad092fafa
def getS3BucketPolicies(this, bucketName: str, region: str='', client=None): '\n Gets bucket policies.\n ' if (not client): client = this._getBotoClient('s3', region) bucketPolicy = client.get_bucket_policy(Bucket=bucketName) return bucketPolicy
Gets bucket policies.
awshelper.py
getS3BucketPolicies
andreyess/AWS-helper
0
python
def getS3BucketPolicies(this, bucketName: str, region: str=, client=None): '\n \n ' if (not client): client = this._getBotoClient('s3', region) bucketPolicy = client.get_bucket_policy(Bucket=bucketName) return bucketPolicy
def getS3BucketPolicies(this, bucketName: str, region: str=, client=None): '\n \n ' if (not client): client = this._getBotoClient('s3', region) bucketPolicy = client.get_bucket_policy(Bucket=bucketName) return bucketPolicy<|docstring|>Gets bucket policies.<|endoftext|>
9c436a2b0bb2275cc6ebb69174b115ad33519a37c8cd56f736bf31c1f9ac391a
def listBucketObjects(this, bucketName: str, versioned: bool, excludePrefix=[], filterPrefix=[], region: str='', client=None): '\n Lists bucket objects.\n\n Objects can be filtered by prefix using `excludePrefix` and `filterPrefix` parameters.\n ' if (not client): client = this._getBotoClient('s3', region) bucketObjects = [] if (not versioned): response = client.list_objects(Bucket=bucketName, MaxKeys=256) if ('Contents' in response): for obj in response['Contents']: bucketObjects.append({'Key': obj['Key']}) else: response = client.list_object_versions(Bucket=bucketName, MaxKeys=256) if ('DeleteMarkers' in response): for obj in response['DeleteMarkers']: bucketObjects.append({'Key': obj['Key'], 'VersionId': obj['VersionId']}) if ('Versions' in response): for obj in response['Versions']: bucketObjects.append({'Key': obj['Key'], 'VersionId': obj['VersionId']}) bucketObjects.sort(key=(lambda x: len(x['Key']))) if len(excludePrefix): bucketObjects = list(filter((lambda obj: (False in [obj['Key'].startswith(prefix) for prefix in excludePrefix])), bucketObjects)) if len(filterPrefix): bucketObjects = list(filter((lambda obj: (True in [obj['Key'].startswith(prefix) for prefix in filterPrefix])), bucketObjects)) return bucketObjects
Lists bucket objects. Objects can be filtered by prefix using `excludePrefix` and `filterPrefix` parameters.
awshelper.py
listBucketObjects
andreyess/AWS-helper
0
python
def listBucketObjects(this, bucketName: str, versioned: bool, excludePrefix=[], filterPrefix=[], region: str=, client=None): '\n Lists bucket objects.\n\n Objects can be filtered by prefix using `excludePrefix` and `filterPrefix` parameters.\n ' if (not client): client = this._getBotoClient('s3', region) bucketObjects = [] if (not versioned): response = client.list_objects(Bucket=bucketName, MaxKeys=256) if ('Contents' in response): for obj in response['Contents']: bucketObjects.append({'Key': obj['Key']}) else: response = client.list_object_versions(Bucket=bucketName, MaxKeys=256) if ('DeleteMarkers' in response): for obj in response['DeleteMarkers']: bucketObjects.append({'Key': obj['Key'], 'VersionId': obj['VersionId']}) if ('Versions' in response): for obj in response['Versions']: bucketObjects.append({'Key': obj['Key'], 'VersionId': obj['VersionId']}) bucketObjects.sort(key=(lambda x: len(x['Key']))) if len(excludePrefix): bucketObjects = list(filter((lambda obj: (False in [obj['Key'].startswith(prefix) for prefix in excludePrefix])), bucketObjects)) if len(filterPrefix): bucketObjects = list(filter((lambda obj: (True in [obj['Key'].startswith(prefix) for prefix in filterPrefix])), bucketObjects)) return bucketObjects
def listBucketObjects(this, bucketName: str, versioned: bool, excludePrefix=[], filterPrefix=[], region: str=, client=None): '\n Lists bucket objects.\n\n Objects can be filtered by prefix using `excludePrefix` and `filterPrefix` parameters.\n ' if (not client): client = this._getBotoClient('s3', region) bucketObjects = [] if (not versioned): response = client.list_objects(Bucket=bucketName, MaxKeys=256) if ('Contents' in response): for obj in response['Contents']: bucketObjects.append({'Key': obj['Key']}) else: response = client.list_object_versions(Bucket=bucketName, MaxKeys=256) if ('DeleteMarkers' in response): for obj in response['DeleteMarkers']: bucketObjects.append({'Key': obj['Key'], 'VersionId': obj['VersionId']}) if ('Versions' in response): for obj in response['Versions']: bucketObjects.append({'Key': obj['Key'], 'VersionId': obj['VersionId']}) bucketObjects.sort(key=(lambda x: len(x['Key']))) if len(excludePrefix): bucketObjects = list(filter((lambda obj: (False in [obj['Key'].startswith(prefix) for prefix in excludePrefix])), bucketObjects)) if len(filterPrefix): bucketObjects = list(filter((lambda obj: (True in [obj['Key'].startswith(prefix) for prefix in filterPrefix])), bucketObjects)) return bucketObjects<|docstring|>Lists bucket objects. Objects can be filtered by prefix using `excludePrefix` and `filterPrefix` parameters.<|endoftext|>
216a40661f25d8a61b005d99658413a89536f872a8f5499e4df358919959e70f
def clearBucket(this, bucketName: str, bucketObjects=None, versioned: bool=None, maxDeleteCycles: int=5, excludePrefix=[], filterPrefix=[], region: str='', client=None, isTopAction=True): '\n Clears bucket objects.\n \n If excludePrefix and filterPrefix are not specified - all objects will be deleted. Otherwise objects\n with prefixes from excludePrefix will be retained and objects with filterPrefix will be deleted.\n ' if (not client): client = this._getBotoClient('s3', region) if (versioned == None): versioned = (client.get_bucket_versioning(Bucket=bucketName)['Status'] == 'Enabled') if (not bucketObjects): bucketObjects = this.listBucketObjects(bucketName, versioned, client=client, excludePrefix=excludePrefix, filterPrefix=filterPrefix) if isTopAction: this.__confirmOperation('Bucket {} clear'.format(bucketName), '\n Versioned: {}\n Objects inside: {}\n '.format(versioned, len(bucketObjects))) print('\n==============================\nDelete operation confirmed. Deleting bucket objects\n==============================') deleteCyclesCounter = 0 while (len(bucketObjects) != 0): for objectToDelete in bucketObjects: if ('VersionId' in objectToDelete): this.deleteBucketObject(bucketName, objectToDelete['Key'], versionId=objectToDelete['VersionId'], client=client, isTopAction=False) else: this.deleteBucketObject(bucketName, objectToDelete['Key'], client=client, isTopAction=False) print('Bucket objects delete cycle was ended. Checking for existing objects...') bucketObjects = this.listBucketObjects(bucketName, versioned, client=client, excludePrefix=excludePrefix, filterPrefix=filterPrefix) if (len(bucketObjects) != 0): deleteCyclesCounter += 1 if (deleteCyclesCounter == maxDeleteCycles): raise DeleteCyclesLimitReached() else: print('Here are more {} objects inside the bucket. Trying to delete them') print('All bucket objects were deleted successfully!')
Clears bucket objects. If excludePrefix and filterPrefix are not specified - all objects will be deleted. Otherwise objects with prefixes from excludePrefix will be retained and objects with filterPrefix will be deleted.
awshelper.py
clearBucket
andreyess/AWS-helper
0
python
def clearBucket(this, bucketName: str, bucketObjects=None, versioned: bool=None, maxDeleteCycles: int=5, excludePrefix=[], filterPrefix=[], region: str=, client=None, isTopAction=True): '\n Clears bucket objects.\n \n If excludePrefix and filterPrefix are not specified - all objects will be deleted. Otherwise objects\n with prefixes from excludePrefix will be retained and objects with filterPrefix will be deleted.\n ' if (not client): client = this._getBotoClient('s3', region) if (versioned == None): versioned = (client.get_bucket_versioning(Bucket=bucketName)['Status'] == 'Enabled') if (not bucketObjects): bucketObjects = this.listBucketObjects(bucketName, versioned, client=client, excludePrefix=excludePrefix, filterPrefix=filterPrefix) if isTopAction: this.__confirmOperation('Bucket {} clear'.format(bucketName), '\n Versioned: {}\n Objects inside: {}\n '.format(versioned, len(bucketObjects))) print('\n==============================\nDelete operation confirmed. Deleting bucket objects\n==============================') deleteCyclesCounter = 0 while (len(bucketObjects) != 0): for objectToDelete in bucketObjects: if ('VersionId' in objectToDelete): this.deleteBucketObject(bucketName, objectToDelete['Key'], versionId=objectToDelete['VersionId'], client=client, isTopAction=False) else: this.deleteBucketObject(bucketName, objectToDelete['Key'], client=client, isTopAction=False) print('Bucket objects delete cycle was ended. Checking for existing objects...') bucketObjects = this.listBucketObjects(bucketName, versioned, client=client, excludePrefix=excludePrefix, filterPrefix=filterPrefix) if (len(bucketObjects) != 0): deleteCyclesCounter += 1 if (deleteCyclesCounter == maxDeleteCycles): raise DeleteCyclesLimitReached() else: print('Here are more {} objects inside the bucket. Trying to delete them') print('All bucket objects were deleted successfully!')
def clearBucket(this, bucketName: str, bucketObjects=None, versioned: bool=None, maxDeleteCycles: int=5, excludePrefix=[], filterPrefix=[], region: str=, client=None, isTopAction=True): '\n Clears bucket objects.\n \n If excludePrefix and filterPrefix are not specified - all objects will be deleted. Otherwise objects\n with prefixes from excludePrefix will be retained and objects with filterPrefix will be deleted.\n ' if (not client): client = this._getBotoClient('s3', region) if (versioned == None): versioned = (client.get_bucket_versioning(Bucket=bucketName)['Status'] == 'Enabled') if (not bucketObjects): bucketObjects = this.listBucketObjects(bucketName, versioned, client=client, excludePrefix=excludePrefix, filterPrefix=filterPrefix) if isTopAction: this.__confirmOperation('Bucket {} clear'.format(bucketName), '\n Versioned: {}\n Objects inside: {}\n '.format(versioned, len(bucketObjects))) print('\n==============================\nDelete operation confirmed. Deleting bucket objects\n==============================') deleteCyclesCounter = 0 while (len(bucketObjects) != 0): for objectToDelete in bucketObjects: if ('VersionId' in objectToDelete): this.deleteBucketObject(bucketName, objectToDelete['Key'], versionId=objectToDelete['VersionId'], client=client, isTopAction=False) else: this.deleteBucketObject(bucketName, objectToDelete['Key'], client=client, isTopAction=False) print('Bucket objects delete cycle was ended. Checking for existing objects...') bucketObjects = this.listBucketObjects(bucketName, versioned, client=client, excludePrefix=excludePrefix, filterPrefix=filterPrefix) if (len(bucketObjects) != 0): deleteCyclesCounter += 1 if (deleteCyclesCounter == maxDeleteCycles): raise DeleteCyclesLimitReached() else: print('Here are more {} objects inside the bucket. Trying to delete them') print('All bucket objects were deleted successfully!')<|docstring|>Clears bucket objects. If excludePrefix and filterPrefix are not specified - all objects will be deleted. Otherwise objects with prefixes from excludePrefix will be retained and objects with filterPrefix will be deleted.<|endoftext|>
bb4c5126910c189b8af20de4853e6346b7006e4b5d67acc32a70d1eafd6421be
def deleteBucket(this, bucketName: str, versioned: bool=None, maxDeleteCycles: int=5, region: str='', client=None, isTopAction=True): '\n Deletes bucket with all objects inside.\n ' if (not client): client = this._getBotoClient('s3', region) if (versioned == None): versioned = (client.get_bucket_versioning(Bucket=bucketName)['Status'] == 'Enabled') bucketObjects = this.listBucketObjects(bucketName, versioned, client=client) if isTopAction: this.__confirmOperation('Bucket {} deletion'.format(bucketName), '\n Versioned: {}\n Objects inside: {}\n '.format(versioned, len(bucketObjects))) this.clearBucket(bucketName, bucketObjects, versioned, maxDeleteCycles, region, client, False) print('Starting bucket delete operation.') print(client.delete_bucket(Bucket=bucketName))
Deletes bucket with all objects inside.
awshelper.py
deleteBucket
andreyess/AWS-helper
0
python
def deleteBucket(this, bucketName: str, versioned: bool=None, maxDeleteCycles: int=5, region: str=, client=None, isTopAction=True): '\n \n ' if (not client): client = this._getBotoClient('s3', region) if (versioned == None): versioned = (client.get_bucket_versioning(Bucket=bucketName)['Status'] == 'Enabled') bucketObjects = this.listBucketObjects(bucketName, versioned, client=client) if isTopAction: this.__confirmOperation('Bucket {} deletion'.format(bucketName), '\n Versioned: {}\n Objects inside: {}\n '.format(versioned, len(bucketObjects))) this.clearBucket(bucketName, bucketObjects, versioned, maxDeleteCycles, region, client, False) print('Starting bucket delete operation.') print(client.delete_bucket(Bucket=bucketName))
def deleteBucket(this, bucketName: str, versioned: bool=None, maxDeleteCycles: int=5, region: str=, client=None, isTopAction=True): '\n \n ' if (not client): client = this._getBotoClient('s3', region) if (versioned == None): versioned = (client.get_bucket_versioning(Bucket=bucketName)['Status'] == 'Enabled') bucketObjects = this.listBucketObjects(bucketName, versioned, client=client) if isTopAction: this.__confirmOperation('Bucket {} deletion'.format(bucketName), '\n Versioned: {}\n Objects inside: {}\n '.format(versioned, len(bucketObjects))) this.clearBucket(bucketName, bucketObjects, versioned, maxDeleteCycles, region, client, False) print('Starting bucket delete operation.') print(client.delete_bucket(Bucket=bucketName))<|docstring|>Deletes bucket with all objects inside.<|endoftext|>
fa4bdc4721d987ab0ce5b566881b5028842053a263fb8b681317899fb035214b
def ready(self): '\n This function is called whenever the Part app is loaded.\n ' if canAppAccessDatabase(): self.update_trackable_status()
This function is called whenever the Part app is loaded.
InvenTree/part/apps.py
ready
killerfish/InvenTree
656
python
def ready(self): '\n \n ' if canAppAccessDatabase(): self.update_trackable_status()
def ready(self): '\n \n ' if canAppAccessDatabase(): self.update_trackable_status()<|docstring|>This function is called whenever the Part app is loaded.<|endoftext|>
b19e9f394e5e94f91bdae52246beb181726c4e6d33a4c23093dbc545aa35ce36
def update_trackable_status(self): '\n Check for any instances where a trackable part is used in the BOM\n for a non-trackable part.\n\n In such a case, force the top-level part to be trackable too.\n ' from .models import BomItem try: items = BomItem.objects.filter(part__trackable=False, sub_part__trackable=True) for item in items: logger.info(f"Marking part '{item.part.name}' as trackable") item.part.trackable = True item.part.clean() item.part.save() except (OperationalError, ProgrammingError): pass
Check for any instances where a trackable part is used in the BOM for a non-trackable part. In such a case, force the top-level part to be trackable too.
InvenTree/part/apps.py
update_trackable_status
killerfish/InvenTree
656
python
def update_trackable_status(self): '\n Check for any instances where a trackable part is used in the BOM\n for a non-trackable part.\n\n In such a case, force the top-level part to be trackable too.\n ' from .models import BomItem try: items = BomItem.objects.filter(part__trackable=False, sub_part__trackable=True) for item in items: logger.info(f"Marking part '{item.part.name}' as trackable") item.part.trackable = True item.part.clean() item.part.save() except (OperationalError, ProgrammingError): pass
def update_trackable_status(self): '\n Check for any instances where a trackable part is used in the BOM\n for a non-trackable part.\n\n In such a case, force the top-level part to be trackable too.\n ' from .models import BomItem try: items = BomItem.objects.filter(part__trackable=False, sub_part__trackable=True) for item in items: logger.info(f"Marking part '{item.part.name}' as trackable") item.part.trackable = True item.part.clean() item.part.save() except (OperationalError, ProgrammingError): pass<|docstring|>Check for any instances where a trackable part is used in the BOM for a non-trackable part. In such a case, force the top-level part to be trackable too.<|endoftext|>
241d683509d2f43d1a011c7beaf697e2a33540a946986fa2d5bae8866b00f92c
def adjust_learning_rate(optimizer, epoch): 'For resnet, the lr starts from 0.1, and is divided by 10 at 80 and 120 epochs' lr = (0.025 * (1 + math.cos(((float(epoch) / 400) * math.pi)))) for param_group in optimizer.param_groups: param_group['lr'] = lr
For resnet, the lr starts from 0.1, and is divided by 10 at 80 and 120 epochs
main.py
adjust_learning_rate
LingYeAI/AdderNetCUDA
6
python
def adjust_learning_rate(optimizer, epoch): lr = (0.025 * (1 + math.cos(((float(epoch) / 400) * math.pi)))) for param_group in optimizer.param_groups: param_group['lr'] = lr
def adjust_learning_rate(optimizer, epoch): lr = (0.025 * (1 + math.cos(((float(epoch) / 400) * math.pi)))) for param_group in optimizer.param_groups: param_group['lr'] = lr<|docstring|>For resnet, the lr starts from 0.1, and is divided by 10 at 80 and 120 epochs<|endoftext|>
86d31b9b7c5dfa1db76f9d823663fecac06e3e8205c2a0e02e7e1c5b4c427e13
async def apply(self): '\n `coroutine`\n\n Add the two stacks to the carrier.\n\n --\n\n Return : None\n ' if (not self.triggered): effect_checker = Effect_checker(self.carrier) triple_ref = (await effect_checker.get_effect(6, self.client, self.ctx, self.carrier, self.team_a, self.team_b)) has_triple = (await effect_checker.get_buff(triple_ref)) if (has_triple != None): has_triple.stack += 2 else: triple_ref.stack = 2 self.carrier.bonus.append(triple_ref) self.triggered = True return
`coroutine` Add the two stacks to the carrier. -- Return : None
utility/cog/character/ability/passive/triple_pilots.py
apply
RvstFyth/discordballz
4
python
async def apply(self): '\n `coroutine`\n\n Add the two stacks to the carrier.\n\n --\n\n Return : None\n ' if (not self.triggered): effect_checker = Effect_checker(self.carrier) triple_ref = (await effect_checker.get_effect(6, self.client, self.ctx, self.carrier, self.team_a, self.team_b)) has_triple = (await effect_checker.get_buff(triple_ref)) if (has_triple != None): has_triple.stack += 2 else: triple_ref.stack = 2 self.carrier.bonus.append(triple_ref) self.triggered = True return
async def apply(self): '\n `coroutine`\n\n Add the two stacks to the carrier.\n\n --\n\n Return : None\n ' if (not self.triggered): effect_checker = Effect_checker(self.carrier) triple_ref = (await effect_checker.get_effect(6, self.client, self.ctx, self.carrier, self.team_a, self.team_b)) has_triple = (await effect_checker.get_buff(triple_ref)) if (has_triple != None): has_triple.stack += 2 else: triple_ref.stack = 2 self.carrier.bonus.append(triple_ref) self.triggered = True return<|docstring|>`coroutine` Add the two stacks to the carrier. -- Return : None<|endoftext|>
54606c50ba4687d07b91a44e6393bbc3d600d311ed8506f168bef1557753ae8a
def _limit(value, min_value, max_value): 'Limit value by min_value and max_value.' if (value < min_value): return min_value if (value > max_value): return max_value return value
Limit value by min_value and max_value.
rocket.py
_limit
FrCln/SpaceGarbage
0
python
def _limit(value, min_value, max_value): if (value < min_value): return min_value if (value > max_value): return max_value return value
def _limit(value, min_value, max_value): if (value < min_value): return min_value if (value > max_value): return max_value return value<|docstring|>Limit value by min_value and max_value.<|endoftext|>
d2a3ff2e5153341126484ae76e77b210a17e7ed0dbf4aaf2ead8efe69a0f2ca6
def _apply_acceleration(speed, speed_limit, forward=True): 'Change speed β€” accelerate or brake β€” according to force direction.' speed_limit = abs(speed_limit) speed_fraction = (speed / speed_limit) delta = (math.cos(speed_fraction) * 0.75) if forward: result_speed = (speed + delta) else: result_speed = (speed - delta) result_speed = _limit(result_speed, (- speed_limit), speed_limit) if (abs(result_speed) < 0.1): result_speed = 0 return result_speed
Change speed β€” accelerate or brake β€” according to force direction.
rocket.py
_apply_acceleration
FrCln/SpaceGarbage
0
python
def _apply_acceleration(speed, speed_limit, forward=True): speed_limit = abs(speed_limit) speed_fraction = (speed / speed_limit) delta = (math.cos(speed_fraction) * 0.75) if forward: result_speed = (speed + delta) else: result_speed = (speed - delta) result_speed = _limit(result_speed, (- speed_limit), speed_limit) if (abs(result_speed) < 0.1): result_speed = 0 return result_speed
def _apply_acceleration(speed, speed_limit, forward=True): speed_limit = abs(speed_limit) speed_fraction = (speed / speed_limit) delta = (math.cos(speed_fraction) * 0.75) if forward: result_speed = (speed + delta) else: result_speed = (speed - delta) result_speed = _limit(result_speed, (- speed_limit), speed_limit) if (abs(result_speed) < 0.1): result_speed = 0 return result_speed<|docstring|>Change speed β€” accelerate or brake β€” according to force direction.<|endoftext|>
897d5fa139f54324200de4420ee85d2c5509adfeaae01eca2e6650ea648350c9
def update_speed(self, rows_direction, columns_direction, row_speed_limit=2, column_speed_limit=2, fading=0.9): 'Update speed smootly to make control handy for player. Return new speed value (row_speed, column_speed)\n\n rows_direction β€” is a force direction by rows axis. Possible values:\n -1 β€” if force pulls up\n 0 β€” if force has no effect\n 1 β€” if force pulls down\n columns_direction β€” is a force direction by colums axis. Possible values:\n -1 β€” if force pulls left\n 0 β€” if force has no effect\n 1 β€” if force pulls right\n ' if (rows_direction not in ((- 1), 0, 1)): raise ValueError(f'Wrong rows_direction value {rows_direction}. Expects -1, 0 or 1.') if (columns_direction not in ((- 1), 0, 1)): raise ValueError(f'Wrong columns_direction value {columns_direction}. Expects -1, 0 or 1.') if ((fading < 0) or (fading > 1)): raise ValueError(f'Wrong fading value {fading}. Expects float between 0 and 1.') self.row_speed *= fading self.column_speed *= fading (row_speed_limit, column_speed_limit) = (abs(row_speed_limit), abs(column_speed_limit)) if (rows_direction != 0): self.row_speed = _apply_acceleration(self.row_speed, row_speed_limit, (rows_direction > 0)) if (columns_direction != 0): self.column_speed = _apply_acceleration(self.column_speed, column_speed_limit, (columns_direction > 0))
Update speed smootly to make control handy for player. Return new speed value (row_speed, column_speed) rows_direction β€” is a force direction by rows axis. Possible values: -1 β€” if force pulls up 0 β€” if force has no effect 1 β€” if force pulls down columns_direction β€” is a force direction by colums axis. Possible values: -1 β€” if force pulls left 0 β€” if force has no effect 1 β€” if force pulls right
rocket.py
update_speed
FrCln/SpaceGarbage
0
python
def update_speed(self, rows_direction, columns_direction, row_speed_limit=2, column_speed_limit=2, fading=0.9): 'Update speed smootly to make control handy for player. Return new speed value (row_speed, column_speed)\n\n rows_direction β€” is a force direction by rows axis. Possible values:\n -1 β€” if force pulls up\n 0 β€” if force has no effect\n 1 β€” if force pulls down\n columns_direction β€” is a force direction by colums axis. Possible values:\n -1 β€” if force pulls left\n 0 β€” if force has no effect\n 1 β€” if force pulls right\n ' if (rows_direction not in ((- 1), 0, 1)): raise ValueError(f'Wrong rows_direction value {rows_direction}. Expects -1, 0 or 1.') if (columns_direction not in ((- 1), 0, 1)): raise ValueError(f'Wrong columns_direction value {columns_direction}. Expects -1, 0 or 1.') if ((fading < 0) or (fading > 1)): raise ValueError(f'Wrong fading value {fading}. Expects float between 0 and 1.') self.row_speed *= fading self.column_speed *= fading (row_speed_limit, column_speed_limit) = (abs(row_speed_limit), abs(column_speed_limit)) if (rows_direction != 0): self.row_speed = _apply_acceleration(self.row_speed, row_speed_limit, (rows_direction > 0)) if (columns_direction != 0): self.column_speed = _apply_acceleration(self.column_speed, column_speed_limit, (columns_direction > 0))
def update_speed(self, rows_direction, columns_direction, row_speed_limit=2, column_speed_limit=2, fading=0.9): 'Update speed smootly to make control handy for player. Return new speed value (row_speed, column_speed)\n\n rows_direction β€” is a force direction by rows axis. Possible values:\n -1 β€” if force pulls up\n 0 β€” if force has no effect\n 1 β€” if force pulls down\n columns_direction β€” is a force direction by colums axis. Possible values:\n -1 β€” if force pulls left\n 0 β€” if force has no effect\n 1 β€” if force pulls right\n ' if (rows_direction not in ((- 1), 0, 1)): raise ValueError(f'Wrong rows_direction value {rows_direction}. Expects -1, 0 or 1.') if (columns_direction not in ((- 1), 0, 1)): raise ValueError(f'Wrong columns_direction value {columns_direction}. Expects -1, 0 or 1.') if ((fading < 0) or (fading > 1)): raise ValueError(f'Wrong fading value {fading}. Expects float between 0 and 1.') self.row_speed *= fading self.column_speed *= fading (row_speed_limit, column_speed_limit) = (abs(row_speed_limit), abs(column_speed_limit)) if (rows_direction != 0): self.row_speed = _apply_acceleration(self.row_speed, row_speed_limit, (rows_direction > 0)) if (columns_direction != 0): self.column_speed = _apply_acceleration(self.column_speed, column_speed_limit, (columns_direction > 0))<|docstring|>Update speed smootly to make control handy for player. Return new speed value (row_speed, column_speed) rows_direction β€” is a force direction by rows axis. Possible values: -1 β€” if force pulls up 0 β€” if force has no effect 1 β€” if force pulls down columns_direction β€” is a force direction by colums axis. Possible values: -1 β€” if force pulls left 0 β€” if force has no effect 1 β€” if force pulls right<|endoftext|>
073c719a4a1ba4615a7b71fd2cc7f3feb1b5d0808fbc16fb2ca0cbb47d386eca
def __init__(__self__, *, api_id: pulumi.Input[str], issue_id: pulumi.Input[str], resource_group_name: pulumi.Input[str], service_name: pulumi.Input[str], text: pulumi.Input[str], user_id: pulumi.Input[str], comment_id: Optional[pulumi.Input[str]]=None, created_date: Optional[pulumi.Input[str]]=None): '\n The set of arguments for constructing a ApiIssueComment resource.\n :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[str] text: Comment text.\n :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.\n :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue.\n :param pulumi.Input[str] created_date: Date and time when the comment was created.\n ' pulumi.set(__self__, 'api_id', api_id) pulumi.set(__self__, 'issue_id', issue_id) pulumi.set(__self__, 'resource_group_name', resource_group_name) pulumi.set(__self__, 'service_name', service_name) pulumi.set(__self__, 'text', text) pulumi.set(__self__, 'user_id', user_id) if (comment_id is not None): pulumi.set(__self__, 'comment_id', comment_id) if (created_date is not None): pulumi.set(__self__, 'created_date', created_date)
The set of arguments for constructing a ApiIssueComment resource. :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] service_name: The name of the API Management service. :param pulumi.Input[str] text: Comment text. :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment. :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue. :param pulumi.Input[str] created_date: Date and time when the comment was created.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
__init__
sebtelko/pulumi-azure-native
0
python
def __init__(__self__, *, api_id: pulumi.Input[str], issue_id: pulumi.Input[str], resource_group_name: pulumi.Input[str], service_name: pulumi.Input[str], text: pulumi.Input[str], user_id: pulumi.Input[str], comment_id: Optional[pulumi.Input[str]]=None, created_date: Optional[pulumi.Input[str]]=None): '\n The set of arguments for constructing a ApiIssueComment resource.\n :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[str] text: Comment text.\n :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.\n :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue.\n :param pulumi.Input[str] created_date: Date and time when the comment was created.\n ' pulumi.set(__self__, 'api_id', api_id) pulumi.set(__self__, 'issue_id', issue_id) pulumi.set(__self__, 'resource_group_name', resource_group_name) pulumi.set(__self__, 'service_name', service_name) pulumi.set(__self__, 'text', text) pulumi.set(__self__, 'user_id', user_id) if (comment_id is not None): pulumi.set(__self__, 'comment_id', comment_id) if (created_date is not None): pulumi.set(__self__, 'created_date', created_date)
def __init__(__self__, *, api_id: pulumi.Input[str], issue_id: pulumi.Input[str], resource_group_name: pulumi.Input[str], service_name: pulumi.Input[str], text: pulumi.Input[str], user_id: pulumi.Input[str], comment_id: Optional[pulumi.Input[str]]=None, created_date: Optional[pulumi.Input[str]]=None): '\n The set of arguments for constructing a ApiIssueComment resource.\n :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[str] text: Comment text.\n :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.\n :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue.\n :param pulumi.Input[str] created_date: Date and time when the comment was created.\n ' pulumi.set(__self__, 'api_id', api_id) pulumi.set(__self__, 'issue_id', issue_id) pulumi.set(__self__, 'resource_group_name', resource_group_name) pulumi.set(__self__, 'service_name', service_name) pulumi.set(__self__, 'text', text) pulumi.set(__self__, 'user_id', user_id) if (comment_id is not None): pulumi.set(__self__, 'comment_id', comment_id) if (created_date is not None): pulumi.set(__self__, 'created_date', created_date)<|docstring|>The set of arguments for constructing a ApiIssueComment resource. :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] service_name: The name of the API Management service. :param pulumi.Input[str] text: Comment text. :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment. :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue. :param pulumi.Input[str] created_date: Date and time when the comment was created.<|endoftext|>
b85278d86135053f5ac651832e8762a2b597fcca8bae828cc43d8415e7a48e81
@property @pulumi.getter(name='apiId') def api_id(self) -> pulumi.Input[str]: '\n API identifier. Must be unique in the current API Management service instance.\n ' return pulumi.get(self, 'api_id')
API identifier. Must be unique in the current API Management service instance.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
api_id
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='apiId') def api_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'api_id')
@property @pulumi.getter(name='apiId') def api_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'api_id')<|docstring|>API identifier. Must be unique in the current API Management service instance.<|endoftext|>
13f805f68fdb1b3adefd4a1da66f76a7072bf0d7e79fb90c6a196a60613e71b9
@property @pulumi.getter(name='issueId') def issue_id(self) -> pulumi.Input[str]: '\n Issue identifier. Must be unique in the current API Management service instance.\n ' return pulumi.get(self, 'issue_id')
Issue identifier. Must be unique in the current API Management service instance.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
issue_id
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='issueId') def issue_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'issue_id')
@property @pulumi.getter(name='issueId') def issue_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'issue_id')<|docstring|>Issue identifier. Must be unique in the current API Management service instance.<|endoftext|>
98eb6c85f4a5186d9d5e838be1c375ba32ee58272931f0c5f93ad28266f15668
@property @pulumi.getter(name='resourceGroupName') def resource_group_name(self) -> pulumi.Input[str]: '\n The name of the resource group.\n ' return pulumi.get(self, 'resource_group_name')
The name of the resource group.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
resource_group_name
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='resourceGroupName') def resource_group_name(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'resource_group_name')
@property @pulumi.getter(name='resourceGroupName') def resource_group_name(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'resource_group_name')<|docstring|>The name of the resource group.<|endoftext|>
615817b39307a427bb47510707432d6de22fdf19f2a828956f3ae4ce83d22a59
@property @pulumi.getter(name='serviceName') def service_name(self) -> pulumi.Input[str]: '\n The name of the API Management service.\n ' return pulumi.get(self, 'service_name')
The name of the API Management service.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
service_name
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='serviceName') def service_name(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'service_name')
@property @pulumi.getter(name='serviceName') def service_name(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'service_name')<|docstring|>The name of the API Management service.<|endoftext|>
6ddb3cd03078f2bb0516c5ddd3152d70ec4ad33e4a27ef98edceced0a8b47fdd
@property @pulumi.getter def text(self) -> pulumi.Input[str]: '\n Comment text.\n ' return pulumi.get(self, 'text')
Comment text.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
text
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter def text(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'text')
@property @pulumi.getter def text(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'text')<|docstring|>Comment text.<|endoftext|>
dcb7c7bc57b05572c8efa4dce19723b336c0c058243ce309035cd6191d4d2165
@property @pulumi.getter(name='userId') def user_id(self) -> pulumi.Input[str]: '\n A resource identifier for the user who left the comment.\n ' return pulumi.get(self, 'user_id')
A resource identifier for the user who left the comment.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
user_id
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='userId') def user_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'user_id')
@property @pulumi.getter(name='userId') def user_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'user_id')<|docstring|>A resource identifier for the user who left the comment.<|endoftext|>
aa41f73bf368b44a9f9b06ecf2f640dc5d665234378066057f59048752066ef9
@property @pulumi.getter(name='commentId') def comment_id(self) -> Optional[pulumi.Input[str]]: '\n Comment identifier within an Issue. Must be unique in the current Issue.\n ' return pulumi.get(self, 'comment_id')
Comment identifier within an Issue. Must be unique in the current Issue.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
comment_id
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='commentId') def comment_id(self) -> Optional[pulumi.Input[str]]: '\n \n ' return pulumi.get(self, 'comment_id')
@property @pulumi.getter(name='commentId') def comment_id(self) -> Optional[pulumi.Input[str]]: '\n \n ' return pulumi.get(self, 'comment_id')<|docstring|>Comment identifier within an Issue. Must be unique in the current Issue.<|endoftext|>
666ae96459aaf15486862f751107a8f5f3399e154babec48593d71d0a8c51571
@property @pulumi.getter(name='createdDate') def created_date(self) -> Optional[pulumi.Input[str]]: '\n Date and time when the comment was created.\n ' return pulumi.get(self, 'created_date')
Date and time when the comment was created.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
created_date
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='createdDate') def created_date(self) -> Optional[pulumi.Input[str]]: '\n \n ' return pulumi.get(self, 'created_date')
@property @pulumi.getter(name='createdDate') def created_date(self) -> Optional[pulumi.Input[str]]: '\n \n ' return pulumi.get(self, 'created_date')<|docstring|>Date and time when the comment was created.<|endoftext|>
8ef10d315a31695bd30ed2644d421c9ce9c4b9f2a448ef7b73621e1ec32870ea
@overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, api_id: Optional[pulumi.Input[str]]=None, comment_id: Optional[pulumi.Input[str]]=None, created_date: Optional[pulumi.Input[str]]=None, issue_id: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, service_name: Optional[pulumi.Input[str]]=None, text: Optional[pulumi.Input[str]]=None, user_id: Optional[pulumi.Input[str]]=None, __props__=None): '\n Issue Comment Contract details.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue.\n :param pulumi.Input[str] created_date: Date and time when the comment was created.\n :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[str] text: Comment text.\n :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.\n ' ...
Issue Comment Contract details. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue. :param pulumi.Input[str] created_date: Date and time when the comment was created. :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] service_name: The name of the API Management service. :param pulumi.Input[str] text: Comment text. :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
__init__
sebtelko/pulumi-azure-native
0
python
@overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, api_id: Optional[pulumi.Input[str]]=None, comment_id: Optional[pulumi.Input[str]]=None, created_date: Optional[pulumi.Input[str]]=None, issue_id: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, service_name: Optional[pulumi.Input[str]]=None, text: Optional[pulumi.Input[str]]=None, user_id: Optional[pulumi.Input[str]]=None, __props__=None): '\n Issue Comment Contract details.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue.\n :param pulumi.Input[str] created_date: Date and time when the comment was created.\n :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[str] text: Comment text.\n :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.\n ' ...
@overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, api_id: Optional[pulumi.Input[str]]=None, comment_id: Optional[pulumi.Input[str]]=None, created_date: Optional[pulumi.Input[str]]=None, issue_id: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, service_name: Optional[pulumi.Input[str]]=None, text: Optional[pulumi.Input[str]]=None, user_id: Optional[pulumi.Input[str]]=None, __props__=None): '\n Issue Comment Contract details.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue.\n :param pulumi.Input[str] created_date: Date and time when the comment was created.\n :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[str] text: Comment text.\n :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.\n ' ...<|docstring|>Issue Comment Contract details. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] api_id: API identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] comment_id: Comment identifier within an Issue. Must be unique in the current Issue. :param pulumi.Input[str] created_date: Date and time when the comment was created. :param pulumi.Input[str] issue_id: Issue identifier. Must be unique in the current API Management service instance. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] service_name: The name of the API Management service. :param pulumi.Input[str] text: Comment text. :param pulumi.Input[str] user_id: A resource identifier for the user who left the comment.<|endoftext|>
cd5d9a357356e1116e4b4e6427ecb226a4a9df38950ec5b09f2104cdc73f24d8
@overload def __init__(__self__, resource_name: str, args: ApiIssueCommentArgs, opts: Optional[pulumi.ResourceOptions]=None): "\n Issue Comment Contract details.\n\n :param str resource_name: The name of the resource.\n :param ApiIssueCommentArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " ...
Issue Comment Contract details. :param str resource_name: The name of the resource. :param ApiIssueCommentArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
__init__
sebtelko/pulumi-azure-native
0
python
@overload def __init__(__self__, resource_name: str, args: ApiIssueCommentArgs, opts: Optional[pulumi.ResourceOptions]=None): "\n Issue Comment Contract details.\n\n :param str resource_name: The name of the resource.\n :param ApiIssueCommentArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " ...
@overload def __init__(__self__, resource_name: str, args: ApiIssueCommentArgs, opts: Optional[pulumi.ResourceOptions]=None): "\n Issue Comment Contract details.\n\n :param str resource_name: The name of the resource.\n :param ApiIssueCommentArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " ...<|docstring|>Issue Comment Contract details. :param str resource_name: The name of the resource. :param ApiIssueCommentArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource.<|endoftext|>
f927e34b043a5a72685439c3c51825952ce51a54f7fd8e9050ffa7501c5ad7b5
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'ApiIssueComment': "\n Get an existing ApiIssueComment resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ApiIssueCommentArgs.__new__(ApiIssueCommentArgs) __props__.__dict__['created_date'] = None __props__.__dict__['name'] = None __props__.__dict__['text'] = None __props__.__dict__['type'] = None __props__.__dict__['user_id'] = None return ApiIssueComment(resource_name, opts=opts, __props__=__props__)
Get an existing ApiIssueComment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
get
sebtelko/pulumi-azure-native
0
python
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'ApiIssueComment': "\n Get an existing ApiIssueComment resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ApiIssueCommentArgs.__new__(ApiIssueCommentArgs) __props__.__dict__['created_date'] = None __props__.__dict__['name'] = None __props__.__dict__['text'] = None __props__.__dict__['type'] = None __props__.__dict__['user_id'] = None return ApiIssueComment(resource_name, opts=opts, __props__=__props__)
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'ApiIssueComment': "\n Get an existing ApiIssueComment resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ApiIssueCommentArgs.__new__(ApiIssueCommentArgs) __props__.__dict__['created_date'] = None __props__.__dict__['name'] = None __props__.__dict__['text'] = None __props__.__dict__['type'] = None __props__.__dict__['user_id'] = None return ApiIssueComment(resource_name, opts=opts, __props__=__props__)<|docstring|>Get an existing ApiIssueComment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource.<|endoftext|>
e0482040be06204e5dd870b0e522f699c312279a749d4e334bbc5062a97cfdae
@property @pulumi.getter(name='createdDate') def created_date(self) -> pulumi.Output[Optional[str]]: '\n Date and time when the comment was created.\n ' return pulumi.get(self, 'created_date')
Date and time when the comment was created.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
created_date
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='createdDate') def created_date(self) -> pulumi.Output[Optional[str]]: '\n \n ' return pulumi.get(self, 'created_date')
@property @pulumi.getter(name='createdDate') def created_date(self) -> pulumi.Output[Optional[str]]: '\n \n ' return pulumi.get(self, 'created_date')<|docstring|>Date and time when the comment was created.<|endoftext|>
a4e4e82a2a3c7ece9d2d421b2e96b6188500f00a67c0b68eb10f134111e2eec7
@property @pulumi.getter def name(self) -> pulumi.Output[str]: '\n Resource name.\n ' return pulumi.get(self, 'name')
Resource name.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
name
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter def name(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'name')
@property @pulumi.getter def name(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'name')<|docstring|>Resource name.<|endoftext|>
6c4f60f4c673d4f5283b2f8717c3da0cce107f77d3379185eeae199254548214
@property @pulumi.getter def text(self) -> pulumi.Output[str]: '\n Comment text.\n ' return pulumi.get(self, 'text')
Comment text.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
text
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter def text(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'text')
@property @pulumi.getter def text(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'text')<|docstring|>Comment text.<|endoftext|>
7577a949c3b104dffd92eabaca4fb5dd34600064a3ca0b7106de16c6d576a571
@property @pulumi.getter def type(self) -> pulumi.Output[str]: '\n Resource type for API Management resource.\n ' return pulumi.get(self, 'type')
Resource type for API Management resource.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
type
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter def type(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'type')
@property @pulumi.getter def type(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'type')<|docstring|>Resource type for API Management resource.<|endoftext|>
a390ccbb4a4b3d9a682a1032164fc9ec775c9289d0dc3525ab24aeca2ab7b003
@property @pulumi.getter(name='userId') def user_id(self) -> pulumi.Output[str]: '\n A resource identifier for the user who left the comment.\n ' return pulumi.get(self, 'user_id')
A resource identifier for the user who left the comment.
sdk/python/pulumi_azure_native/apimanagement/v20210101preview/api_issue_comment.py
user_id
sebtelko/pulumi-azure-native
0
python
@property @pulumi.getter(name='userId') def user_id(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'user_id')
@property @pulumi.getter(name='userId') def user_id(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'user_id')<|docstring|>A resource identifier for the user who left the comment.<|endoftext|>
5b4d6bcfac0efa0a9fc39a95c1a67e95c8d066b54738cf83f777b6ed02827b24
def create_prob_mtx(probs, c_pro, n_pro, pro_ls, output_dir): '\n Organize the interaction probability from Ouroboros analysis to a\n dataframe\n ' print(f'Creating interaction probability matrix...') prob_mtx = df(index=pro_ls, columns=pro_ls) for i in range(len(probs)): c_term = c_pro[i] n_term = n_pro[i] prob_mtx.loc[c_term][n_term] = probs[i] prob_mtx.to_csv(path_or_buf=f'{output_dir}/int_prob_mtx.csv') return prob_mtx
Organize the interaction probability from Ouroboros analysis to a dataframe
code/int_prob.py
create_prob_mtx
yanwang271/PKSpop
2
python
def create_prob_mtx(probs, c_pro, n_pro, pro_ls, output_dir): '\n Organize the interaction probability from Ouroboros analysis to a\n dataframe\n ' print(f'Creating interaction probability matrix...') prob_mtx = df(index=pro_ls, columns=pro_ls) for i in range(len(probs)): c_term = c_pro[i] n_term = n_pro[i] prob_mtx.loc[c_term][n_term] = probs[i] prob_mtx.to_csv(path_or_buf=f'{output_dir}/int_prob_mtx.csv') return prob_mtx
def create_prob_mtx(probs, c_pro, n_pro, pro_ls, output_dir): '\n Organize the interaction probability from Ouroboros analysis to a\n dataframe\n ' print(f'Creating interaction probability matrix...') prob_mtx = df(index=pro_ls, columns=pro_ls) for i in range(len(probs)): c_term = c_pro[i] n_term = n_pro[i] prob_mtx.loc[c_term][n_term] = probs[i] prob_mtx.to_csv(path_or_buf=f'{output_dir}/int_prob_mtx.csv') return prob_mtx<|docstring|>Organize the interaction probability from Ouroboros analysis to a dataframe<|endoftext|>
4c78e872c25da0decee014c423f212c9b39679f5a5e93ab3b0156cc5986a8cfc
def find_other_class(all_pro, class1_pro, start_end): '\n Find the proteins that not belong to class 1\n ' other_class = [] for p in all_pro: if ((p not in class1_pro) and (p not in start_end)): other_class.append(p) return other_class
Find the proteins that not belong to class 1
code/int_prob.py
find_other_class
yanwang271/PKSpop
2
python
def find_other_class(all_pro, class1_pro, start_end): '\n \n ' other_class = [] for p in all_pro: if ((p not in class1_pro) and (p not in start_end)): other_class.append(p) return other_class
def find_other_class(all_pro, class1_pro, start_end): '\n \n ' other_class = [] for p in all_pro: if ((p not in class1_pro) and (p not in start_end)): other_class.append(p) return other_class<|docstring|>Find the proteins that not belong to class 1<|endoftext|>
65ab5d8d5ae17029b4039a0748a53c84cf64204758e5c8c3e36a6996dc2c8b77
def __init__(self, data_path, batch_size, percent_train=0.8, pre_split_shuffle=True, **kwargs): 'Initialize.\n\n Args:\n data_path: The file path for the BraTS dataset\n batch_size (int): The batch size to use\n percent_train (float): The percentage of the data to use for training (Default=0.8)\n pre_split_shuffle (bool): True= shuffle the dataset before\n performing the train/validate split (Default=True)\n **kwargs: Additional arguments, passed to super init and load_from_nifti\n\n Returns:\n Data loader with BraTS data\n ' super().__init__(batch_size, **kwargs) (X_train, y_train, X_valid, y_valid) = load_from_nifti(parent_dir=data_path, percent_train=percent_train, shuffle=pre_split_shuffle, **kwargs) self.X_train = X_train self.y_train = y_train self.X_valid = X_valid self.y_valid = y_valid
Initialize. Args: data_path: The file path for the BraTS dataset batch_size (int): The batch size to use percent_train (float): The percentage of the data to use for training (Default=0.8) pre_split_shuffle (bool): True= shuffle the dataset before performing the train/validate split (Default=True) **kwargs: Additional arguments, passed to super init and load_from_nifti Returns: Data loader with BraTS data
openfl-workspace/tf_2dunet/src/tfbrats_inmemory.py
__init__
psfoley/openfl
297
python
def __init__(self, data_path, batch_size, percent_train=0.8, pre_split_shuffle=True, **kwargs): 'Initialize.\n\n Args:\n data_path: The file path for the BraTS dataset\n batch_size (int): The batch size to use\n percent_train (float): The percentage of the data to use for training (Default=0.8)\n pre_split_shuffle (bool): True= shuffle the dataset before\n performing the train/validate split (Default=True)\n **kwargs: Additional arguments, passed to super init and load_from_nifti\n\n Returns:\n Data loader with BraTS data\n ' super().__init__(batch_size, **kwargs) (X_train, y_train, X_valid, y_valid) = load_from_nifti(parent_dir=data_path, percent_train=percent_train, shuffle=pre_split_shuffle, **kwargs) self.X_train = X_train self.y_train = y_train self.X_valid = X_valid self.y_valid = y_valid
def __init__(self, data_path, batch_size, percent_train=0.8, pre_split_shuffle=True, **kwargs): 'Initialize.\n\n Args:\n data_path: The file path for the BraTS dataset\n batch_size (int): The batch size to use\n percent_train (float): The percentage of the data to use for training (Default=0.8)\n pre_split_shuffle (bool): True= shuffle the dataset before\n performing the train/validate split (Default=True)\n **kwargs: Additional arguments, passed to super init and load_from_nifti\n\n Returns:\n Data loader with BraTS data\n ' super().__init__(batch_size, **kwargs) (X_train, y_train, X_valid, y_valid) = load_from_nifti(parent_dir=data_path, percent_train=percent_train, shuffle=pre_split_shuffle, **kwargs) self.X_train = X_train self.y_train = y_train self.X_valid = X_valid self.y_valid = y_valid<|docstring|>Initialize. Args: data_path: The file path for the BraTS dataset batch_size (int): The batch size to use percent_train (float): The percentage of the data to use for training (Default=0.8) pre_split_shuffle (bool): True= shuffle the dataset before performing the train/validate split (Default=True) **kwargs: Additional arguments, passed to super init and load_from_nifti Returns: Data loader with BraTS data<|endoftext|>
6f9494870d3a78af5e220b394d8b0fef552950acb1ec94dbbadc631be8902451
def gamma(a, *args, **kwds): '\n Gamma and incomplete gamma functions.\n This is defined by the integral\n\n .. math::\n\n \\Gamma(a, z) = \\int_z^\\infty t^{a-1}e^{-t} dt\n\n EXAMPLES::\n\n Recall that `\\Gamma(n)` is `n-1` factorial::\n\n sage: gamma(11) == factorial(10)\n True\n sage: gamma(6)\n 120\n sage: gamma(1/2)\n sqrt(pi)\n sage: gamma(-4/3)\n gamma(-4/3)\n sage: gamma(-1)\n Infinity\n sage: gamma(0)\n Infinity\n\n ::\n\n sage: gamma_inc(3,2)\n gamma(3, 2)\n sage: gamma_inc(x,0)\n gamma(x)\n\n ::\n\n sage: gamma(5, hold=True)\n gamma(5)\n sage: gamma(x, 0, hold=True)\n gamma(x, 0)\n\n ::\n\n sage: gamma(CDF(0.5,14))\n -4.05370307804e-10 - 5.77329983455e-10*I\n sage: gamma(CDF(I))\n -0.154949828302 - 0.498015668118*I\n\n The gamma function only works with input that can be coerced to the\n Symbolic Ring::\n\n sage: Q.<i> = NumberField(x^2+1)\n sage: gamma(i)\n doctest:...: DeprecationWarning: Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated.\n See http://trac.sagemath.org/7490 for details.\n -0.154949828301811 - 0.498015668118356*I\n\n We make an exception for elements of AA or QQbar, which cannot be\n coerced into symbolic expressions to allow this usage::\n\n sage: t = QQbar(sqrt(2)) + sqrt(3); t\n 3.146264369941973?\n sage: t.parent()\n Algebraic Field\n\n Symbolic functions convert the arguments to symbolic expressions if they\n are in QQbar or AA::\n\n sage: gamma(QQbar(I))\n -0.154949828301811 - 0.498015668118356*I\n ' if (not args): return gamma1(a, **kwds) if (len(args) > 1): raise TypeError(('Symbolic function gamma takes at most 2 arguments (%s given)' % (len(args) + 1))) return incomplete_gamma(a, args[0], **kwds)
Gamma and incomplete gamma functions. This is defined by the integral .. math:: \Gamma(a, z) = \int_z^\infty t^{a-1}e^{-t} dt EXAMPLES:: Recall that `\Gamma(n)` is `n-1` factorial:: sage: gamma(11) == factorial(10) True sage: gamma(6) 120 sage: gamma(1/2) sqrt(pi) sage: gamma(-4/3) gamma(-4/3) sage: gamma(-1) Infinity sage: gamma(0) Infinity :: sage: gamma_inc(3,2) gamma(3, 2) sage: gamma_inc(x,0) gamma(x) :: sage: gamma(5, hold=True) gamma(5) sage: gamma(x, 0, hold=True) gamma(x, 0) :: sage: gamma(CDF(0.5,14)) -4.05370307804e-10 - 5.77329983455e-10*I sage: gamma(CDF(I)) -0.154949828302 - 0.498015668118*I The gamma function only works with input that can be coerced to the Symbolic Ring:: sage: Q.<i> = NumberField(x^2+1) sage: gamma(i) doctest:...: DeprecationWarning: Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated. See http://trac.sagemath.org/7490 for details. -0.154949828301811 - 0.498015668118356*I We make an exception for elements of AA or QQbar, which cannot be coerced into symbolic expressions to allow this usage:: sage: t = QQbar(sqrt(2)) + sqrt(3); t 3.146264369941973? sage: t.parent() Algebraic Field Symbolic functions convert the arguments to symbolic expressions if they are in QQbar or AA:: sage: gamma(QQbar(I)) -0.154949828301811 - 0.498015668118356*I
src/sage/functions/other.py
gamma
drvinceknight/sage
2
python
def gamma(a, *args, **kwds): '\n Gamma and incomplete gamma functions.\n This is defined by the integral\n\n .. math::\n\n \\Gamma(a, z) = \\int_z^\\infty t^{a-1}e^{-t} dt\n\n EXAMPLES::\n\n Recall that `\\Gamma(n)` is `n-1` factorial::\n\n sage: gamma(11) == factorial(10)\n True\n sage: gamma(6)\n 120\n sage: gamma(1/2)\n sqrt(pi)\n sage: gamma(-4/3)\n gamma(-4/3)\n sage: gamma(-1)\n Infinity\n sage: gamma(0)\n Infinity\n\n ::\n\n sage: gamma_inc(3,2)\n gamma(3, 2)\n sage: gamma_inc(x,0)\n gamma(x)\n\n ::\n\n sage: gamma(5, hold=True)\n gamma(5)\n sage: gamma(x, 0, hold=True)\n gamma(x, 0)\n\n ::\n\n sage: gamma(CDF(0.5,14))\n -4.05370307804e-10 - 5.77329983455e-10*I\n sage: gamma(CDF(I))\n -0.154949828302 - 0.498015668118*I\n\n The gamma function only works with input that can be coerced to the\n Symbolic Ring::\n\n sage: Q.<i> = NumberField(x^2+1)\n sage: gamma(i)\n doctest:...: DeprecationWarning: Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated.\n See http://trac.sagemath.org/7490 for details.\n -0.154949828301811 - 0.498015668118356*I\n\n We make an exception for elements of AA or QQbar, which cannot be\n coerced into symbolic expressions to allow this usage::\n\n sage: t = QQbar(sqrt(2)) + sqrt(3); t\n 3.146264369941973?\n sage: t.parent()\n Algebraic Field\n\n Symbolic functions convert the arguments to symbolic expressions if they\n are in QQbar or AA::\n\n sage: gamma(QQbar(I))\n -0.154949828301811 - 0.498015668118356*I\n ' if (not args): return gamma1(a, **kwds) if (len(args) > 1): raise TypeError(('Symbolic function gamma takes at most 2 arguments (%s given)' % (len(args) + 1))) return incomplete_gamma(a, args[0], **kwds)
def gamma(a, *args, **kwds): '\n Gamma and incomplete gamma functions.\n This is defined by the integral\n\n .. math::\n\n \\Gamma(a, z) = \\int_z^\\infty t^{a-1}e^{-t} dt\n\n EXAMPLES::\n\n Recall that `\\Gamma(n)` is `n-1` factorial::\n\n sage: gamma(11) == factorial(10)\n True\n sage: gamma(6)\n 120\n sage: gamma(1/2)\n sqrt(pi)\n sage: gamma(-4/3)\n gamma(-4/3)\n sage: gamma(-1)\n Infinity\n sage: gamma(0)\n Infinity\n\n ::\n\n sage: gamma_inc(3,2)\n gamma(3, 2)\n sage: gamma_inc(x,0)\n gamma(x)\n\n ::\n\n sage: gamma(5, hold=True)\n gamma(5)\n sage: gamma(x, 0, hold=True)\n gamma(x, 0)\n\n ::\n\n sage: gamma(CDF(0.5,14))\n -4.05370307804e-10 - 5.77329983455e-10*I\n sage: gamma(CDF(I))\n -0.154949828302 - 0.498015668118*I\n\n The gamma function only works with input that can be coerced to the\n Symbolic Ring::\n\n sage: Q.<i> = NumberField(x^2+1)\n sage: gamma(i)\n doctest:...: DeprecationWarning: Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated.\n See http://trac.sagemath.org/7490 for details.\n -0.154949828301811 - 0.498015668118356*I\n\n We make an exception for elements of AA or QQbar, which cannot be\n coerced into symbolic expressions to allow this usage::\n\n sage: t = QQbar(sqrt(2)) + sqrt(3); t\n 3.146264369941973?\n sage: t.parent()\n Algebraic Field\n\n Symbolic functions convert the arguments to symbolic expressions if they\n are in QQbar or AA::\n\n sage: gamma(QQbar(I))\n -0.154949828301811 - 0.498015668118356*I\n ' if (not args): return gamma1(a, **kwds) if (len(args) > 1): raise TypeError(('Symbolic function gamma takes at most 2 arguments (%s given)' % (len(args) + 1))) return incomplete_gamma(a, args[0], **kwds)<|docstring|>Gamma and incomplete gamma functions. This is defined by the integral .. math:: \Gamma(a, z) = \int_z^\infty t^{a-1}e^{-t} dt EXAMPLES:: Recall that `\Gamma(n)` is `n-1` factorial:: sage: gamma(11) == factorial(10) True sage: gamma(6) 120 sage: gamma(1/2) sqrt(pi) sage: gamma(-4/3) gamma(-4/3) sage: gamma(-1) Infinity sage: gamma(0) Infinity :: sage: gamma_inc(3,2) gamma(3, 2) sage: gamma_inc(x,0) gamma(x) :: sage: gamma(5, hold=True) gamma(5) sage: gamma(x, 0, hold=True) gamma(x, 0) :: sage: gamma(CDF(0.5,14)) -4.05370307804e-10 - 5.77329983455e-10*I sage: gamma(CDF(I)) -0.154949828302 - 0.498015668118*I The gamma function only works with input that can be coerced to the Symbolic Ring:: sage: Q.<i> = NumberField(x^2+1) sage: gamma(i) doctest:...: DeprecationWarning: Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated. See http://trac.sagemath.org/7490 for details. -0.154949828301811 - 0.498015668118356*I We make an exception for elements of AA or QQbar, which cannot be coerced into symbolic expressions to allow this usage:: sage: t = QQbar(sqrt(2)) + sqrt(3); t 3.146264369941973? sage: t.parent() Algebraic Field Symbolic functions convert the arguments to symbolic expressions if they are in QQbar or AA:: sage: gamma(QQbar(I)) -0.154949828301811 - 0.498015668118356*I<|endoftext|>
642928b65346fc3971734526e6679fdebfe2a21909c66696e1c0af0fafcdaa92
def psi(x, *args, **kwds): "\n The digamma function, `\\psi(x)`, is the logarithmic derivative of the\n gamma function.\n\n .. math::\n\n \\psi(x) = \\frac{d}{dx} \\log(\\Gamma(x)) = \\frac{\\Gamma'(x)}{\\Gamma(x)}\n\n We represent the `n`-th derivative of the digamma function with\n `\\psi(n, x)` or `psi(n, x)`.\n\n EXAMPLES::\n\n sage: psi(x)\n psi(x)\n sage: psi(.5)\n -1.96351002602142\n sage: psi(3)\n -euler_gamma + 3/2\n sage: psi(1, 5)\n 1/6*pi^2 - 205/144\n sage: psi(1, x)\n psi(1, x)\n sage: psi(1, x).derivative(x)\n psi(2, x)\n\n ::\n\n sage: psi(3, hold=True)\n psi(3)\n sage: psi(1, 5, hold=True)\n psi(1, 5)\n\n TESTS::\n\n sage: psi(2, x, 3)\n Traceback (most recent call last):\n ...\n TypeError: Symbolic function psi takes at most 2 arguments (3 given)\n " if (not args): return psi1(x, **kwds) if (len(args) > 1): raise TypeError(('Symbolic function psi takes at most 2 arguments (%s given)' % (len(args) + 1))) return psi2(x, args[0], **kwds)
The digamma function, `\psi(x)`, is the logarithmic derivative of the gamma function. .. math:: \psi(x) = \frac{d}{dx} \log(\Gamma(x)) = \frac{\Gamma'(x)}{\Gamma(x)} We represent the `n`-th derivative of the digamma function with `\psi(n, x)` or `psi(n, x)`. EXAMPLES:: sage: psi(x) psi(x) sage: psi(.5) -1.96351002602142 sage: psi(3) -euler_gamma + 3/2 sage: psi(1, 5) 1/6*pi^2 - 205/144 sage: psi(1, x) psi(1, x) sage: psi(1, x).derivative(x) psi(2, x) :: sage: psi(3, hold=True) psi(3) sage: psi(1, 5, hold=True) psi(1, 5) TESTS:: sage: psi(2, x, 3) Traceback (most recent call last): ... TypeError: Symbolic function psi takes at most 2 arguments (3 given)
src/sage/functions/other.py
psi
drvinceknight/sage
2
python
def psi(x, *args, **kwds): "\n The digamma function, `\\psi(x)`, is the logarithmic derivative of the\n gamma function.\n\n .. math::\n\n \\psi(x) = \\frac{d}{dx} \\log(\\Gamma(x)) = \\frac{\\Gamma'(x)}{\\Gamma(x)}\n\n We represent the `n`-th derivative of the digamma function with\n `\\psi(n, x)` or `psi(n, x)`.\n\n EXAMPLES::\n\n sage: psi(x)\n psi(x)\n sage: psi(.5)\n -1.96351002602142\n sage: psi(3)\n -euler_gamma + 3/2\n sage: psi(1, 5)\n 1/6*pi^2 - 205/144\n sage: psi(1, x)\n psi(1, x)\n sage: psi(1, x).derivative(x)\n psi(2, x)\n\n ::\n\n sage: psi(3, hold=True)\n psi(3)\n sage: psi(1, 5, hold=True)\n psi(1, 5)\n\n TESTS::\n\n sage: psi(2, x, 3)\n Traceback (most recent call last):\n ...\n TypeError: Symbolic function psi takes at most 2 arguments (3 given)\n " if (not args): return psi1(x, **kwds) if (len(args) > 1): raise TypeError(('Symbolic function psi takes at most 2 arguments (%s given)' % (len(args) + 1))) return psi2(x, args[0], **kwds)
def psi(x, *args, **kwds): "\n The digamma function, `\\psi(x)`, is the logarithmic derivative of the\n gamma function.\n\n .. math::\n\n \\psi(x) = \\frac{d}{dx} \\log(\\Gamma(x)) = \\frac{\\Gamma'(x)}{\\Gamma(x)}\n\n We represent the `n`-th derivative of the digamma function with\n `\\psi(n, x)` or `psi(n, x)`.\n\n EXAMPLES::\n\n sage: psi(x)\n psi(x)\n sage: psi(.5)\n -1.96351002602142\n sage: psi(3)\n -euler_gamma + 3/2\n sage: psi(1, 5)\n 1/6*pi^2 - 205/144\n sage: psi(1, x)\n psi(1, x)\n sage: psi(1, x).derivative(x)\n psi(2, x)\n\n ::\n\n sage: psi(3, hold=True)\n psi(3)\n sage: psi(1, 5, hold=True)\n psi(1, 5)\n\n TESTS::\n\n sage: psi(2, x, 3)\n Traceback (most recent call last):\n ...\n TypeError: Symbolic function psi takes at most 2 arguments (3 given)\n " if (not args): return psi1(x, **kwds) if (len(args) > 1): raise TypeError(('Symbolic function psi takes at most 2 arguments (%s given)' % (len(args) + 1))) return psi2(x, args[0], **kwds)<|docstring|>The digamma function, `\psi(x)`, is the logarithmic derivative of the gamma function. .. math:: \psi(x) = \frac{d}{dx} \log(\Gamma(x)) = \frac{\Gamma'(x)}{\Gamma(x)} We represent the `n`-th derivative of the digamma function with `\psi(n, x)` or `psi(n, x)`. EXAMPLES:: sage: psi(x) psi(x) sage: psi(.5) -1.96351002602142 sage: psi(3) -euler_gamma + 3/2 sage: psi(1, 5) 1/6*pi^2 - 205/144 sage: psi(1, x) psi(1, x) sage: psi(1, x).derivative(x) psi(2, x) :: sage: psi(3, hold=True) psi(3) sage: psi(1, 5, hold=True) psi(1, 5) TESTS:: sage: psi(2, x, 3) Traceback (most recent call last): ... TypeError: Symbolic function psi takes at most 2 arguments (3 given)<|endoftext|>
15019e4c0e98bb162dde714ba811284f238d667e9c54d3301a303616f8edfe38
def _do_sqrt(x, prec=None, extend=True, all=False): '\n Used internally to compute the square root of x.\n\n INPUT:\n\n - ``x`` - a number\n\n - ``prec`` - None (default) or a positive integer\n (bits of precision) If not None, then compute the square root\n numerically to prec bits of precision.\n\n - ``extend`` - bool (default: True); this is a place\n holder, and is always ignored since in the symbolic ring everything\n has a square root.\n\n - ``extend`` - bool (default: True); whether to extend\n the base ring to find roots. The extend parameter is ignored if\n prec is a positive integer.\n\n - ``all`` - bool (default: False); whether to return\n a list of all the square roots of x.\n\n\n EXAMPLES::\n\n sage: from sage.functions.other import _do_sqrt\n sage: _do_sqrt(3)\n sqrt(3)\n sage: _do_sqrt(3,prec=10)\n 1.7\n sage: _do_sqrt(3,prec=100)\n 1.7320508075688772935274463415\n sage: _do_sqrt(3,all=True)\n [sqrt(3), -sqrt(3)]\n\n Note that the extend parameter is ignored in the symbolic ring::\n\n sage: _do_sqrt(3,extend=False)\n sqrt(3)\n ' from sage.rings.all import RealField, ComplexField if prec: if (x >= 0): return RealField(prec)(x).sqrt(all=all) else: return ComplexField(prec)(x).sqrt(all=all) if (x == (- 1)): from sage.symbolic.pynac import I z = I else: z = (SR(x) ** one_half) if all: if z: return [z, (- z)] else: return [z] return z
Used internally to compute the square root of x. INPUT: - ``x`` - a number - ``prec`` - None (default) or a positive integer (bits of precision) If not None, then compute the square root numerically to prec bits of precision. - ``extend`` - bool (default: True); this is a place holder, and is always ignored since in the symbolic ring everything has a square root. - ``extend`` - bool (default: True); whether to extend the base ring to find roots. The extend parameter is ignored if prec is a positive integer. - ``all`` - bool (default: False); whether to return a list of all the square roots of x. EXAMPLES:: sage: from sage.functions.other import _do_sqrt sage: _do_sqrt(3) sqrt(3) sage: _do_sqrt(3,prec=10) 1.7 sage: _do_sqrt(3,prec=100) 1.7320508075688772935274463415 sage: _do_sqrt(3,all=True) [sqrt(3), -sqrt(3)] Note that the extend parameter is ignored in the symbolic ring:: sage: _do_sqrt(3,extend=False) sqrt(3)
src/sage/functions/other.py
_do_sqrt
drvinceknight/sage
2
python
def _do_sqrt(x, prec=None, extend=True, all=False): '\n Used internally to compute the square root of x.\n\n INPUT:\n\n - ``x`` - a number\n\n - ``prec`` - None (default) or a positive integer\n (bits of precision) If not None, then compute the square root\n numerically to prec bits of precision.\n\n - ``extend`` - bool (default: True); this is a place\n holder, and is always ignored since in the symbolic ring everything\n has a square root.\n\n - ``extend`` - bool (default: True); whether to extend\n the base ring to find roots. The extend parameter is ignored if\n prec is a positive integer.\n\n - ``all`` - bool (default: False); whether to return\n a list of all the square roots of x.\n\n\n EXAMPLES::\n\n sage: from sage.functions.other import _do_sqrt\n sage: _do_sqrt(3)\n sqrt(3)\n sage: _do_sqrt(3,prec=10)\n 1.7\n sage: _do_sqrt(3,prec=100)\n 1.7320508075688772935274463415\n sage: _do_sqrt(3,all=True)\n [sqrt(3), -sqrt(3)]\n\n Note that the extend parameter is ignored in the symbolic ring::\n\n sage: _do_sqrt(3,extend=False)\n sqrt(3)\n ' from sage.rings.all import RealField, ComplexField if prec: if (x >= 0): return RealField(prec)(x).sqrt(all=all) else: return ComplexField(prec)(x).sqrt(all=all) if (x == (- 1)): from sage.symbolic.pynac import I z = I else: z = (SR(x) ** one_half) if all: if z: return [z, (- z)] else: return [z] return z
def _do_sqrt(x, prec=None, extend=True, all=False): '\n Used internally to compute the square root of x.\n\n INPUT:\n\n - ``x`` - a number\n\n - ``prec`` - None (default) or a positive integer\n (bits of precision) If not None, then compute the square root\n numerically to prec bits of precision.\n\n - ``extend`` - bool (default: True); this is a place\n holder, and is always ignored since in the symbolic ring everything\n has a square root.\n\n - ``extend`` - bool (default: True); whether to extend\n the base ring to find roots. The extend parameter is ignored if\n prec is a positive integer.\n\n - ``all`` - bool (default: False); whether to return\n a list of all the square roots of x.\n\n\n EXAMPLES::\n\n sage: from sage.functions.other import _do_sqrt\n sage: _do_sqrt(3)\n sqrt(3)\n sage: _do_sqrt(3,prec=10)\n 1.7\n sage: _do_sqrt(3,prec=100)\n 1.7320508075688772935274463415\n sage: _do_sqrt(3,all=True)\n [sqrt(3), -sqrt(3)]\n\n Note that the extend parameter is ignored in the symbolic ring::\n\n sage: _do_sqrt(3,extend=False)\n sqrt(3)\n ' from sage.rings.all import RealField, ComplexField if prec: if (x >= 0): return RealField(prec)(x).sqrt(all=all) else: return ComplexField(prec)(x).sqrt(all=all) if (x == (- 1)): from sage.symbolic.pynac import I z = I else: z = (SR(x) ** one_half) if all: if z: return [z, (- z)] else: return [z] return z<|docstring|>Used internally to compute the square root of x. INPUT: - ``x`` - a number - ``prec`` - None (default) or a positive integer (bits of precision) If not None, then compute the square root numerically to prec bits of precision. - ``extend`` - bool (default: True); this is a place holder, and is always ignored since in the symbolic ring everything has a square root. - ``extend`` - bool (default: True); whether to extend the base ring to find roots. The extend parameter is ignored if prec is a positive integer. - ``all`` - bool (default: False); whether to return a list of all the square roots of x. EXAMPLES:: sage: from sage.functions.other import _do_sqrt sage: _do_sqrt(3) sqrt(3) sage: _do_sqrt(3,prec=10) 1.7 sage: _do_sqrt(3,prec=100) 1.7320508075688772935274463415 sage: _do_sqrt(3,all=True) [sqrt(3), -sqrt(3)] Note that the extend parameter is ignored in the symbolic ring:: sage: _do_sqrt(3,extend=False) sqrt(3)<|endoftext|>
5331cf1371c40af19cc6f8bea554cdfecb22a78ebff40bd104e582be8d5bacb4
def sqrt(x, *args, **kwds): "\n INPUT:\n\n - ``x`` - a number\n\n - ``prec`` - integer (default: None): if None, returns\n an exact square root; otherwise returns a numerical square root if\n necessary, to the given bits of precision.\n\n - ``extend`` - bool (default: True); this is a place\n holder, and is always ignored or passed to the sqrt function for x,\n since in the symbolic ring everything has a square root.\n\n - ``all`` - bool (default: False); if True, return all\n square roots of self, instead of just one.\n\n EXAMPLES::\n\n sage: sqrt(-1)\n I\n sage: sqrt(2)\n sqrt(2)\n sage: sqrt(2)^2\n 2\n sage: sqrt(4)\n 2\n sage: sqrt(4,all=True)\n [2, -2]\n sage: sqrt(x^2)\n sqrt(x^2)\n sage: sqrt(2).n()\n 1.41421356237310\n\n To prevent automatic evaluation, one can use the ``hold`` parameter\n after coercing to the symbolic ring::\n\n sage: sqrt(SR(4),hold=True)\n sqrt(4)\n sage: sqrt(4,hold=True)\n Traceback (most recent call last):\n ...\n TypeError: _do_sqrt() got an unexpected keyword argument 'hold'\n\n This illustrates that the bug reported in #6171 has been fixed::\n\n sage: a = 1.1\n sage: a.sqrt(prec=100) # this is supposed to fail\n Traceback (most recent call last):\n ...\n TypeError: sqrt() got an unexpected keyword argument 'prec'\n sage: sqrt(a, prec=100)\n 1.0488088481701515469914535137\n sage: sqrt(4.00, prec=250)\n 2.0000000000000000000000000000000000000000000000000000000000000000000000000\n\n One can use numpy input as well::\n\n sage: import numpy\n sage: a = numpy.arange(2,5)\n sage: sqrt(a)\n array([ 1.41421356, 1.73205081, 2. ])\n " if isinstance(x, float): return math.sqrt(x) elif (type(x).__module__ == 'numpy'): from numpy import sqrt return sqrt(x) try: return x.sqrt(*args, **kwds) except (AttributeError, TypeError): pass return _do_sqrt(x, *args, **kwds)
INPUT: - ``x`` - a number - ``prec`` - integer (default: None): if None, returns an exact square root; otherwise returns a numerical square root if necessary, to the given bits of precision. - ``extend`` - bool (default: True); this is a place holder, and is always ignored or passed to the sqrt function for x, since in the symbolic ring everything has a square root. - ``all`` - bool (default: False); if True, return all square roots of self, instead of just one. EXAMPLES:: sage: sqrt(-1) I sage: sqrt(2) sqrt(2) sage: sqrt(2)^2 2 sage: sqrt(4) 2 sage: sqrt(4,all=True) [2, -2] sage: sqrt(x^2) sqrt(x^2) sage: sqrt(2).n() 1.41421356237310 To prevent automatic evaluation, one can use the ``hold`` parameter after coercing to the symbolic ring:: sage: sqrt(SR(4),hold=True) sqrt(4) sage: sqrt(4,hold=True) Traceback (most recent call last): ... TypeError: _do_sqrt() got an unexpected keyword argument 'hold' This illustrates that the bug reported in #6171 has been fixed:: sage: a = 1.1 sage: a.sqrt(prec=100) # this is supposed to fail Traceback (most recent call last): ... TypeError: sqrt() got an unexpected keyword argument 'prec' sage: sqrt(a, prec=100) 1.0488088481701515469914535137 sage: sqrt(4.00, prec=250) 2.0000000000000000000000000000000000000000000000000000000000000000000000000 One can use numpy input as well:: sage: import numpy sage: a = numpy.arange(2,5) sage: sqrt(a) array([ 1.41421356, 1.73205081, 2. ])
src/sage/functions/other.py
sqrt
drvinceknight/sage
2
python
def sqrt(x, *args, **kwds): "\n INPUT:\n\n - ``x`` - a number\n\n - ``prec`` - integer (default: None): if None, returns\n an exact square root; otherwise returns a numerical square root if\n necessary, to the given bits of precision.\n\n - ``extend`` - bool (default: True); this is a place\n holder, and is always ignored or passed to the sqrt function for x,\n since in the symbolic ring everything has a square root.\n\n - ``all`` - bool (default: False); if True, return all\n square roots of self, instead of just one.\n\n EXAMPLES::\n\n sage: sqrt(-1)\n I\n sage: sqrt(2)\n sqrt(2)\n sage: sqrt(2)^2\n 2\n sage: sqrt(4)\n 2\n sage: sqrt(4,all=True)\n [2, -2]\n sage: sqrt(x^2)\n sqrt(x^2)\n sage: sqrt(2).n()\n 1.41421356237310\n\n To prevent automatic evaluation, one can use the ``hold`` parameter\n after coercing to the symbolic ring::\n\n sage: sqrt(SR(4),hold=True)\n sqrt(4)\n sage: sqrt(4,hold=True)\n Traceback (most recent call last):\n ...\n TypeError: _do_sqrt() got an unexpected keyword argument 'hold'\n\n This illustrates that the bug reported in #6171 has been fixed::\n\n sage: a = 1.1\n sage: a.sqrt(prec=100) # this is supposed to fail\n Traceback (most recent call last):\n ...\n TypeError: sqrt() got an unexpected keyword argument 'prec'\n sage: sqrt(a, prec=100)\n 1.0488088481701515469914535137\n sage: sqrt(4.00, prec=250)\n 2.0000000000000000000000000000000000000000000000000000000000000000000000000\n\n One can use numpy input as well::\n\n sage: import numpy\n sage: a = numpy.arange(2,5)\n sage: sqrt(a)\n array([ 1.41421356, 1.73205081, 2. ])\n " if isinstance(x, float): return math.sqrt(x) elif (type(x).__module__ == 'numpy'): from numpy import sqrt return sqrt(x) try: return x.sqrt(*args, **kwds) except (AttributeError, TypeError): pass return _do_sqrt(x, *args, **kwds)
def sqrt(x, *args, **kwds): "\n INPUT:\n\n - ``x`` - a number\n\n - ``prec`` - integer (default: None): if None, returns\n an exact square root; otherwise returns a numerical square root if\n necessary, to the given bits of precision.\n\n - ``extend`` - bool (default: True); this is a place\n holder, and is always ignored or passed to the sqrt function for x,\n since in the symbolic ring everything has a square root.\n\n - ``all`` - bool (default: False); if True, return all\n square roots of self, instead of just one.\n\n EXAMPLES::\n\n sage: sqrt(-1)\n I\n sage: sqrt(2)\n sqrt(2)\n sage: sqrt(2)^2\n 2\n sage: sqrt(4)\n 2\n sage: sqrt(4,all=True)\n [2, -2]\n sage: sqrt(x^2)\n sqrt(x^2)\n sage: sqrt(2).n()\n 1.41421356237310\n\n To prevent automatic evaluation, one can use the ``hold`` parameter\n after coercing to the symbolic ring::\n\n sage: sqrt(SR(4),hold=True)\n sqrt(4)\n sage: sqrt(4,hold=True)\n Traceback (most recent call last):\n ...\n TypeError: _do_sqrt() got an unexpected keyword argument 'hold'\n\n This illustrates that the bug reported in #6171 has been fixed::\n\n sage: a = 1.1\n sage: a.sqrt(prec=100) # this is supposed to fail\n Traceback (most recent call last):\n ...\n TypeError: sqrt() got an unexpected keyword argument 'prec'\n sage: sqrt(a, prec=100)\n 1.0488088481701515469914535137\n sage: sqrt(4.00, prec=250)\n 2.0000000000000000000000000000000000000000000000000000000000000000000000000\n\n One can use numpy input as well::\n\n sage: import numpy\n sage: a = numpy.arange(2,5)\n sage: sqrt(a)\n array([ 1.41421356, 1.73205081, 2. ])\n " if isinstance(x, float): return math.sqrt(x) elif (type(x).__module__ == 'numpy'): from numpy import sqrt return sqrt(x) try: return x.sqrt(*args, **kwds) except (AttributeError, TypeError): pass return _do_sqrt(x, *args, **kwds)<|docstring|>INPUT: - ``x`` - a number - ``prec`` - integer (default: None): if None, returns an exact square root; otherwise returns a numerical square root if necessary, to the given bits of precision. - ``extend`` - bool (default: True); this is a place holder, and is always ignored or passed to the sqrt function for x, since in the symbolic ring everything has a square root. - ``all`` - bool (default: False); if True, return all square roots of self, instead of just one. EXAMPLES:: sage: sqrt(-1) I sage: sqrt(2) sqrt(2) sage: sqrt(2)^2 2 sage: sqrt(4) 2 sage: sqrt(4,all=True) [2, -2] sage: sqrt(x^2) sqrt(x^2) sage: sqrt(2).n() 1.41421356237310 To prevent automatic evaluation, one can use the ``hold`` parameter after coercing to the symbolic ring:: sage: sqrt(SR(4),hold=True) sqrt(4) sage: sqrt(4,hold=True) Traceback (most recent call last): ... TypeError: _do_sqrt() got an unexpected keyword argument 'hold' This illustrates that the bug reported in #6171 has been fixed:: sage: a = 1.1 sage: a.sqrt(prec=100) # this is supposed to fail Traceback (most recent call last): ... TypeError: sqrt() got an unexpected keyword argument 'prec' sage: sqrt(a, prec=100) 1.0488088481701515469914535137 sage: sqrt(4.00, prec=250) 2.0000000000000000000000000000000000000000000000000000000000000000000000000 One can use numpy input as well:: sage: import numpy sage: a = numpy.arange(2,5) sage: sqrt(a) array([ 1.41421356, 1.73205081, 2. ])<|endoftext|>
6b85d9f357bd4758fe55ca561f5d766ad8797ca94dec795c8346899b55a16de1
def __init__(self): '\n See docstring for :meth:`Function_erf`.\n\n EXAMPLES::\n\n sage: erf(2)\n erf(2)\n ' BuiltinFunction.__init__(self, 'erf', latex_name='\\text{erf}')
See docstring for :meth:`Function_erf`. EXAMPLES:: sage: erf(2) erf(2)
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): '\n See docstring for :meth:`Function_erf`.\n\n EXAMPLES::\n\n sage: erf(2)\n erf(2)\n ' BuiltinFunction.__init__(self, 'erf', latex_name='\\text{erf}')
def __init__(self): '\n See docstring for :meth:`Function_erf`.\n\n EXAMPLES::\n\n sage: erf(2)\n erf(2)\n ' BuiltinFunction.__init__(self, 'erf', latex_name='\\text{erf}')<|docstring|>See docstring for :meth:`Function_erf`. EXAMPLES:: sage: erf(2) erf(2)<|endoftext|>
52bad6edd3c629131530cf8b5e0c1843d7313a60cd3b3723e8c6eb2cea5264a5
def _eval_(self, x): '\n EXAMPLES:\n\n Input is not an expression but is exact::\n\n sage: erf(0)\n 0\n sage: erf(1)\n erf(1)\n\n Input is not an expression and is not exact::\n\n sage: erf(0.0)\n 0.000000000000000\n\n Input is an expression but not a trivial zero::\n\n sage: erf(x)\n erf(x)\n\n Input is an expression which is trivially zero::\n\n sage: erf(SR(0))\n 0\n ' if (not isinstance(x, Expression)): if is_inexact(x): return self._evalf_(x, parent=s_parent(x)) elif (x == Integer(0)): return Integer(0) elif x.is_trivial_zero(): return x return None
EXAMPLES: Input is not an expression but is exact:: sage: erf(0) 0 sage: erf(1) erf(1) Input is not an expression and is not exact:: sage: erf(0.0) 0.000000000000000 Input is an expression but not a trivial zero:: sage: erf(x) erf(x) Input is an expression which is trivially zero:: sage: erf(SR(0)) 0
src/sage/functions/other.py
_eval_
drvinceknight/sage
2
python
def _eval_(self, x): '\n EXAMPLES:\n\n Input is not an expression but is exact::\n\n sage: erf(0)\n 0\n sage: erf(1)\n erf(1)\n\n Input is not an expression and is not exact::\n\n sage: erf(0.0)\n 0.000000000000000\n\n Input is an expression but not a trivial zero::\n\n sage: erf(x)\n erf(x)\n\n Input is an expression which is trivially zero::\n\n sage: erf(SR(0))\n 0\n ' if (not isinstance(x, Expression)): if is_inexact(x): return self._evalf_(x, parent=s_parent(x)) elif (x == Integer(0)): return Integer(0) elif x.is_trivial_zero(): return x return None
def _eval_(self, x): '\n EXAMPLES:\n\n Input is not an expression but is exact::\n\n sage: erf(0)\n 0\n sage: erf(1)\n erf(1)\n\n Input is not an expression and is not exact::\n\n sage: erf(0.0)\n 0.000000000000000\n\n Input is an expression but not a trivial zero::\n\n sage: erf(x)\n erf(x)\n\n Input is an expression which is trivially zero::\n\n sage: erf(SR(0))\n 0\n ' if (not isinstance(x, Expression)): if is_inexact(x): return self._evalf_(x, parent=s_parent(x)) elif (x == Integer(0)): return Integer(0) elif x.is_trivial_zero(): return x return None<|docstring|>EXAMPLES: Input is not an expression but is exact:: sage: erf(0) 0 sage: erf(1) erf(1) Input is not an expression and is not exact:: sage: erf(0.0) 0.000000000000000 Input is an expression but not a trivial zero:: sage: erf(x) erf(x) Input is an expression which is trivially zero:: sage: erf(SR(0)) 0<|endoftext|>
c29c43fa4a1c9529961481dc869c53afcfe9edf02e0ca4d0af758b7aab9f49ec
def _evalf_(self, x, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: erf(2).n()\n 0.995322265018953\n sage: erf(2).n(200)\n 0.99532226501895273416206925636725292861089179704006007673835\n sage: erf(pi - 1/2*I).n(100)\n 1.0000111669099367825726058952 + 1.6332655417638522934072124547e-6*I\n\n TESTS:\n\n Check that PARI/GP through the GP interface gives the same answer::\n\n sage: gp.set_real_precision(59) # random\n 38\n sage: print gp.eval("1 - erfc(1)"); print erf(1).n(200);\n 0.84270079294971486934122063508260925929606699796630290845994\n 0.84270079294971486934122063508260925929606699796630290845994\n\n Check that for an imaginary input, the output is also imaginary, see\n :trac:`13193`::\n\n sage: erf(3.0*I)\n 1629.99462260157*I\n sage: erf(33.0*I)\n 1.51286977510409e471*I\n ' R = (parent or s_parent(x)) import mpmath return mpmath_utils.call(mpmath.erf, x, parent=R)
EXAMPLES:: sage: erf(2).n() 0.995322265018953 sage: erf(2).n(200) 0.99532226501895273416206925636725292861089179704006007673835 sage: erf(pi - 1/2*I).n(100) 1.0000111669099367825726058952 + 1.6332655417638522934072124547e-6*I TESTS: Check that PARI/GP through the GP interface gives the same answer:: sage: gp.set_real_precision(59) # random 38 sage: print gp.eval("1 - erfc(1)"); print erf(1).n(200); 0.84270079294971486934122063508260925929606699796630290845994 0.84270079294971486934122063508260925929606699796630290845994 Check that for an imaginary input, the output is also imaginary, see :trac:`13193`:: sage: erf(3.0*I) 1629.99462260157*I sage: erf(33.0*I) 1.51286977510409e471*I
src/sage/functions/other.py
_evalf_
drvinceknight/sage
2
python
def _evalf_(self, x, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: erf(2).n()\n 0.995322265018953\n sage: erf(2).n(200)\n 0.99532226501895273416206925636725292861089179704006007673835\n sage: erf(pi - 1/2*I).n(100)\n 1.0000111669099367825726058952 + 1.6332655417638522934072124547e-6*I\n\n TESTS:\n\n Check that PARI/GP through the GP interface gives the same answer::\n\n sage: gp.set_real_precision(59) # random\n 38\n sage: print gp.eval("1 - erfc(1)"); print erf(1).n(200);\n 0.84270079294971486934122063508260925929606699796630290845994\n 0.84270079294971486934122063508260925929606699796630290845994\n\n Check that for an imaginary input, the output is also imaginary, see\n :trac:`13193`::\n\n sage: erf(3.0*I)\n 1629.99462260157*I\n sage: erf(33.0*I)\n 1.51286977510409e471*I\n ' R = (parent or s_parent(x)) import mpmath return mpmath_utils.call(mpmath.erf, x, parent=R)
def _evalf_(self, x, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: erf(2).n()\n 0.995322265018953\n sage: erf(2).n(200)\n 0.99532226501895273416206925636725292861089179704006007673835\n sage: erf(pi - 1/2*I).n(100)\n 1.0000111669099367825726058952 + 1.6332655417638522934072124547e-6*I\n\n TESTS:\n\n Check that PARI/GP through the GP interface gives the same answer::\n\n sage: gp.set_real_precision(59) # random\n 38\n sage: print gp.eval("1 - erfc(1)"); print erf(1).n(200);\n 0.84270079294971486934122063508260925929606699796630290845994\n 0.84270079294971486934122063508260925929606699796630290845994\n\n Check that for an imaginary input, the output is also imaginary, see\n :trac:`13193`::\n\n sage: erf(3.0*I)\n 1629.99462260157*I\n sage: erf(33.0*I)\n 1.51286977510409e471*I\n ' R = (parent or s_parent(x)) import mpmath return mpmath_utils.call(mpmath.erf, x, parent=R)<|docstring|>EXAMPLES:: sage: erf(2).n() 0.995322265018953 sage: erf(2).n(200) 0.99532226501895273416206925636725292861089179704006007673835 sage: erf(pi - 1/2*I).n(100) 1.0000111669099367825726058952 + 1.6332655417638522934072124547e-6*I TESTS: Check that PARI/GP through the GP interface gives the same answer:: sage: gp.set_real_precision(59) # random 38 sage: print gp.eval("1 - erfc(1)"); print erf(1).n(200); 0.84270079294971486934122063508260925929606699796630290845994 0.84270079294971486934122063508260925929606699796630290845994 Check that for an imaginary input, the output is also imaginary, see :trac:`13193`:: sage: erf(3.0*I) 1629.99462260157*I sage: erf(33.0*I) 1.51286977510409e471*I<|endoftext|>
6fc6dd7722fc5524f791b73a2fdd57de22bc200ad3c800129b28fdc6ea15b693
def _derivative_(self, x, diff_param=None): "\n Derivative of erf function\n\n EXAMPLES::\n\n sage: erf(x).diff(x)\n 2*e^(-x^2)/sqrt(pi)\n\n TESTS:\n\n Check if #8568 is fixed::\n\n sage: var('c,x')\n (c, x)\n sage: derivative(erf(c*x),x)\n 2*c*e^(-c^2*x^2)/sqrt(pi)\n sage: erf(c*x).diff(x)._maxima_init_()\n '((%pi)^(-1/2))*(_SAGE_VAR_c)*(exp(((_SAGE_VAR_c)^(2))*((_SAGE_VAR_x)^(2))*(-1)))*(2)'\n " return ((2 * exp((- (x ** 2)))) / sqrt(pi))
Derivative of erf function EXAMPLES:: sage: erf(x).diff(x) 2*e^(-x^2)/sqrt(pi) TESTS: Check if #8568 is fixed:: sage: var('c,x') (c, x) sage: derivative(erf(c*x),x) 2*c*e^(-c^2*x^2)/sqrt(pi) sage: erf(c*x).diff(x)._maxima_init_() '((%pi)^(-1/2))*(_SAGE_VAR_c)*(exp(((_SAGE_VAR_c)^(2))*((_SAGE_VAR_x)^(2))*(-1)))*(2)'
src/sage/functions/other.py
_derivative_
drvinceknight/sage
2
python
def _derivative_(self, x, diff_param=None): "\n Derivative of erf function\n\n EXAMPLES::\n\n sage: erf(x).diff(x)\n 2*e^(-x^2)/sqrt(pi)\n\n TESTS:\n\n Check if #8568 is fixed::\n\n sage: var('c,x')\n (c, x)\n sage: derivative(erf(c*x),x)\n 2*c*e^(-c^2*x^2)/sqrt(pi)\n sage: erf(c*x).diff(x)._maxima_init_()\n '((%pi)^(-1/2))*(_SAGE_VAR_c)*(exp(((_SAGE_VAR_c)^(2))*((_SAGE_VAR_x)^(2))*(-1)))*(2)'\n " return ((2 * exp((- (x ** 2)))) / sqrt(pi))
def _derivative_(self, x, diff_param=None): "\n Derivative of erf function\n\n EXAMPLES::\n\n sage: erf(x).diff(x)\n 2*e^(-x^2)/sqrt(pi)\n\n TESTS:\n\n Check if #8568 is fixed::\n\n sage: var('c,x')\n (c, x)\n sage: derivative(erf(c*x),x)\n 2*c*e^(-c^2*x^2)/sqrt(pi)\n sage: erf(c*x).diff(x)._maxima_init_()\n '((%pi)^(-1/2))*(_SAGE_VAR_c)*(exp(((_SAGE_VAR_c)^(2))*((_SAGE_VAR_x)^(2))*(-1)))*(2)'\n " return ((2 * exp((- (x ** 2)))) / sqrt(pi))<|docstring|>Derivative of erf function EXAMPLES:: sage: erf(x).diff(x) 2*e^(-x^2)/sqrt(pi) TESTS: Check if #8568 is fixed:: sage: var('c,x') (c, x) sage: derivative(erf(c*x),x) 2*c*e^(-c^2*x^2)/sqrt(pi) sage: erf(c*x).diff(x)._maxima_init_() '((%pi)^(-1/2))*(_SAGE_VAR_c)*(exp(((_SAGE_VAR_c)^(2))*((_SAGE_VAR_x)^(2))*(-1)))*(2)'<|endoftext|>
d8f850471ac1e73f2865034ca15bd9d58b7eccb3e7d2b57f904a40c53c443e06
def __init__(self): "\n The absolute value function.\n\n EXAMPLES::\n\n sage: var('x y')\n (x, y)\n sage: abs(x)\n abs(x)\n sage: abs(x^2 + y^2)\n abs(x^2 + y^2)\n sage: abs(-2)\n 2\n sage: sqrt(x^2)\n sqrt(x^2)\n sage: abs(sqrt(x))\n abs(sqrt(x))\n sage: complex(abs(3*I))\n (3+0j)\n\n sage: f = sage.functions.other.Function_abs()\n sage: latex(f)\n \\mathrm{abs}\n sage: latex(abs(x))\n {\\left| x \\right|}\n\n Test pickling::\n\n sage: loads(dumps(abs(x)))\n abs(x)\n " GinacFunction.__init__(self, 'abs', latex_name='\\mathrm{abs}')
The absolute value function. EXAMPLES:: sage: var('x y') (x, y) sage: abs(x) abs(x) sage: abs(x^2 + y^2) abs(x^2 + y^2) sage: abs(-2) 2 sage: sqrt(x^2) sqrt(x^2) sage: abs(sqrt(x)) abs(sqrt(x)) sage: complex(abs(3*I)) (3+0j) sage: f = sage.functions.other.Function_abs() sage: latex(f) \mathrm{abs} sage: latex(abs(x)) {\left| x \right|} Test pickling:: sage: loads(dumps(abs(x))) abs(x)
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n The absolute value function.\n\n EXAMPLES::\n\n sage: var('x y')\n (x, y)\n sage: abs(x)\n abs(x)\n sage: abs(x^2 + y^2)\n abs(x^2 + y^2)\n sage: abs(-2)\n 2\n sage: sqrt(x^2)\n sqrt(x^2)\n sage: abs(sqrt(x))\n abs(sqrt(x))\n sage: complex(abs(3*I))\n (3+0j)\n\n sage: f = sage.functions.other.Function_abs()\n sage: latex(f)\n \\mathrm{abs}\n sage: latex(abs(x))\n {\\left| x \\right|}\n\n Test pickling::\n\n sage: loads(dumps(abs(x)))\n abs(x)\n " GinacFunction.__init__(self, 'abs', latex_name='\\mathrm{abs}')
def __init__(self): "\n The absolute value function.\n\n EXAMPLES::\n\n sage: var('x y')\n (x, y)\n sage: abs(x)\n abs(x)\n sage: abs(x^2 + y^2)\n abs(x^2 + y^2)\n sage: abs(-2)\n 2\n sage: sqrt(x^2)\n sqrt(x^2)\n sage: abs(sqrt(x))\n abs(sqrt(x))\n sage: complex(abs(3*I))\n (3+0j)\n\n sage: f = sage.functions.other.Function_abs()\n sage: latex(f)\n \\mathrm{abs}\n sage: latex(abs(x))\n {\\left| x \\right|}\n\n Test pickling::\n\n sage: loads(dumps(abs(x)))\n abs(x)\n " GinacFunction.__init__(self, 'abs', latex_name='\\mathrm{abs}')<|docstring|>The absolute value function. EXAMPLES:: sage: var('x y') (x, y) sage: abs(x) abs(x) sage: abs(x^2 + y^2) abs(x^2 + y^2) sage: abs(-2) 2 sage: sqrt(x^2) sqrt(x^2) sage: abs(sqrt(x)) abs(sqrt(x)) sage: complex(abs(3*I)) (3+0j) sage: f = sage.functions.other.Function_abs() sage: latex(f) \mathrm{abs} sage: latex(abs(x)) {\left| x \right|} Test pickling:: sage: loads(dumps(abs(x))) abs(x)<|endoftext|>
6bb1b05284d68936f38ad09799bf52acfc39115eb90466d9c74b20753e91bff5
def __init__(self): "\n The ceiling function.\n\n The ceiling of `x` is computed in the following manner.\n\n\n #. The ``x.ceil()`` method is called and returned if it\n is there. If it is not, then Sage checks if `x` is one of\n Python's native numeric data types. If so, then it calls and\n returns ``Integer(int(math.ceil(x)))``.\n\n #. Sage tries to convert `x` into a\n ``RealIntervalField`` with 53 bits of precision. Next,\n the ceilings of the endpoints are computed. If they are the same,\n then that value is returned. Otherwise, the precision of the\n ``RealIntervalField`` is increased until they do match\n up or it reaches ``maximum_bits`` of precision.\n\n #. If none of the above work, Sage returns a\n ``Expression`` object.\n\n\n EXAMPLES::\n\n sage: a = ceil(2/5 + x)\n sage: a\n ceil(x + 2/5)\n sage: a(x=4)\n 5\n sage: a(x=4.0)\n 5\n sage: ZZ(a(x=3))\n 4\n sage: a = ceil(x^3 + x + 5/2); a\n ceil(x^3 + x + 5/2)\n sage: a.simplify()\n ceil(x^3 + x + 1/2) + 2\n sage: a(x=2)\n 13\n\n ::\n\n sage: ceil(sin(8)/sin(2))\n 2\n\n ::\n\n sage: ceil(5.4)\n 6\n sage: type(ceil(5.4))\n <type 'sage.rings.integer.Integer'>\n\n ::\n\n sage: ceil(factorial(50)/exp(1))\n 11188719610782480504630258070757734324011354208865721592720336801\n sage: ceil(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000001\n sage: ceil(SR(10^50 - 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n\n sage: ceil(sec(e))\n -1\n\n sage: latex(ceil(x))\n \\left \\lceil x \\right \\rceil\n\n ::\n\n sage: import numpy\n sage: a = numpy.linspace(0,2,6)\n sage: ceil(a)\n array([ 0., 1., 1., 2., 2., 2.])\n\n Test pickling::\n\n sage: loads(dumps(ceil))\n ceil\n " BuiltinFunction.__init__(self, 'ceil', conversions=dict(maxima='ceiling'))
The ceiling function. The ceiling of `x` is computed in the following manner. #. The ``x.ceil()`` method is called and returned if it is there. If it is not, then Sage checks if `x` is one of Python's native numeric data types. If so, then it calls and returns ``Integer(int(math.ceil(x)))``. #. Sage tries to convert `x` into a ``RealIntervalField`` with 53 bits of precision. Next, the ceilings of the endpoints are computed. If they are the same, then that value is returned. Otherwise, the precision of the ``RealIntervalField`` is increased until they do match up or it reaches ``maximum_bits`` of precision. #. If none of the above work, Sage returns a ``Expression`` object. EXAMPLES:: sage: a = ceil(2/5 + x) sage: a ceil(x + 2/5) sage: a(x=4) 5 sage: a(x=4.0) 5 sage: ZZ(a(x=3)) 4 sage: a = ceil(x^3 + x + 5/2); a ceil(x^3 + x + 5/2) sage: a.simplify() ceil(x^3 + x + 1/2) + 2 sage: a(x=2) 13 :: sage: ceil(sin(8)/sin(2)) 2 :: sage: ceil(5.4) 6 sage: type(ceil(5.4)) <type 'sage.rings.integer.Integer'> :: sage: ceil(factorial(50)/exp(1)) 11188719610782480504630258070757734324011354208865721592720336801 sage: ceil(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000001 sage: ceil(SR(10^50 - 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: ceil(sec(e)) -1 sage: latex(ceil(x)) \left \lceil x \right \rceil :: sage: import numpy sage: a = numpy.linspace(0,2,6) sage: ceil(a) array([ 0., 1., 1., 2., 2., 2.]) Test pickling:: sage: loads(dumps(ceil)) ceil
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n The ceiling function.\n\n The ceiling of `x` is computed in the following manner.\n\n\n #. The ``x.ceil()`` method is called and returned if it\n is there. If it is not, then Sage checks if `x` is one of\n Python's native numeric data types. If so, then it calls and\n returns ``Integer(int(math.ceil(x)))``.\n\n #. Sage tries to convert `x` into a\n ``RealIntervalField`` with 53 bits of precision. Next,\n the ceilings of the endpoints are computed. If they are the same,\n then that value is returned. Otherwise, the precision of the\n ``RealIntervalField`` is increased until they do match\n up or it reaches ``maximum_bits`` of precision.\n\n #. If none of the above work, Sage returns a\n ``Expression`` object.\n\n\n EXAMPLES::\n\n sage: a = ceil(2/5 + x)\n sage: a\n ceil(x + 2/5)\n sage: a(x=4)\n 5\n sage: a(x=4.0)\n 5\n sage: ZZ(a(x=3))\n 4\n sage: a = ceil(x^3 + x + 5/2); a\n ceil(x^3 + x + 5/2)\n sage: a.simplify()\n ceil(x^3 + x + 1/2) + 2\n sage: a(x=2)\n 13\n\n ::\n\n sage: ceil(sin(8)/sin(2))\n 2\n\n ::\n\n sage: ceil(5.4)\n 6\n sage: type(ceil(5.4))\n <type 'sage.rings.integer.Integer'>\n\n ::\n\n sage: ceil(factorial(50)/exp(1))\n 11188719610782480504630258070757734324011354208865721592720336801\n sage: ceil(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000001\n sage: ceil(SR(10^50 - 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n\n sage: ceil(sec(e))\n -1\n\n sage: latex(ceil(x))\n \\left \\lceil x \\right \\rceil\n\n ::\n\n sage: import numpy\n sage: a = numpy.linspace(0,2,6)\n sage: ceil(a)\n array([ 0., 1., 1., 2., 2., 2.])\n\n Test pickling::\n\n sage: loads(dumps(ceil))\n ceil\n " BuiltinFunction.__init__(self, 'ceil', conversions=dict(maxima='ceiling'))
def __init__(self): "\n The ceiling function.\n\n The ceiling of `x` is computed in the following manner.\n\n\n #. The ``x.ceil()`` method is called and returned if it\n is there. If it is not, then Sage checks if `x` is one of\n Python's native numeric data types. If so, then it calls and\n returns ``Integer(int(math.ceil(x)))``.\n\n #. Sage tries to convert `x` into a\n ``RealIntervalField`` with 53 bits of precision. Next,\n the ceilings of the endpoints are computed. If they are the same,\n then that value is returned. Otherwise, the precision of the\n ``RealIntervalField`` is increased until they do match\n up or it reaches ``maximum_bits`` of precision.\n\n #. If none of the above work, Sage returns a\n ``Expression`` object.\n\n\n EXAMPLES::\n\n sage: a = ceil(2/5 + x)\n sage: a\n ceil(x + 2/5)\n sage: a(x=4)\n 5\n sage: a(x=4.0)\n 5\n sage: ZZ(a(x=3))\n 4\n sage: a = ceil(x^3 + x + 5/2); a\n ceil(x^3 + x + 5/2)\n sage: a.simplify()\n ceil(x^3 + x + 1/2) + 2\n sage: a(x=2)\n 13\n\n ::\n\n sage: ceil(sin(8)/sin(2))\n 2\n\n ::\n\n sage: ceil(5.4)\n 6\n sage: type(ceil(5.4))\n <type 'sage.rings.integer.Integer'>\n\n ::\n\n sage: ceil(factorial(50)/exp(1))\n 11188719610782480504630258070757734324011354208865721592720336801\n sage: ceil(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000001\n sage: ceil(SR(10^50 - 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n\n sage: ceil(sec(e))\n -1\n\n sage: latex(ceil(x))\n \\left \\lceil x \\right \\rceil\n\n ::\n\n sage: import numpy\n sage: a = numpy.linspace(0,2,6)\n sage: ceil(a)\n array([ 0., 1., 1., 2., 2., 2.])\n\n Test pickling::\n\n sage: loads(dumps(ceil))\n ceil\n " BuiltinFunction.__init__(self, 'ceil', conversions=dict(maxima='ceiling'))<|docstring|>The ceiling function. The ceiling of `x` is computed in the following manner. #. The ``x.ceil()`` method is called and returned if it is there. If it is not, then Sage checks if `x` is one of Python's native numeric data types. If so, then it calls and returns ``Integer(int(math.ceil(x)))``. #. Sage tries to convert `x` into a ``RealIntervalField`` with 53 bits of precision. Next, the ceilings of the endpoints are computed. If they are the same, then that value is returned. Otherwise, the precision of the ``RealIntervalField`` is increased until they do match up or it reaches ``maximum_bits`` of precision. #. If none of the above work, Sage returns a ``Expression`` object. EXAMPLES:: sage: a = ceil(2/5 + x) sage: a ceil(x + 2/5) sage: a(x=4) 5 sage: a(x=4.0) 5 sage: ZZ(a(x=3)) 4 sage: a = ceil(x^3 + x + 5/2); a ceil(x^3 + x + 5/2) sage: a.simplify() ceil(x^3 + x + 1/2) + 2 sage: a(x=2) 13 :: sage: ceil(sin(8)/sin(2)) 2 :: sage: ceil(5.4) 6 sage: type(ceil(5.4)) <type 'sage.rings.integer.Integer'> :: sage: ceil(factorial(50)/exp(1)) 11188719610782480504630258070757734324011354208865721592720336801 sage: ceil(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000001 sage: ceil(SR(10^50 - 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: ceil(sec(e)) -1 sage: latex(ceil(x)) \left \lceil x \right \rceil :: sage: import numpy sage: a = numpy.linspace(0,2,6) sage: ceil(a) array([ 0., 1., 1., 2., 2., 2.]) Test pickling:: sage: loads(dumps(ceil)) ceil<|endoftext|>
fab0fc461a37117548214fd6dc210d39412d289d9bea23cb075c3173bb6fc3e9
def _print_latex_(self, x): '\n EXAMPLES::\n\n sage: latex(ceil(x)) # indirect doctest\n \\left \\lceil x \\right \\rceil\n ' return ('\\left \\lceil %s \\right \\rceil' % latex(x))
EXAMPLES:: sage: latex(ceil(x)) # indirect doctest \left \lceil x \right \rceil
src/sage/functions/other.py
_print_latex_
drvinceknight/sage
2
python
def _print_latex_(self, x): '\n EXAMPLES::\n\n sage: latex(ceil(x)) # indirect doctest\n \\left \\lceil x \\right \\rceil\n ' return ('\\left \\lceil %s \\right \\rceil' % latex(x))
def _print_latex_(self, x): '\n EXAMPLES::\n\n sage: latex(ceil(x)) # indirect doctest\n \\left \\lceil x \\right \\rceil\n ' return ('\\left \\lceil %s \\right \\rceil' % latex(x))<|docstring|>EXAMPLES:: sage: latex(ceil(x)) # indirect doctest \left \lceil x \right \rceil<|endoftext|>
3eed97377320e40a5957bcac09575544b40168e263cbe23fe384c29ca8bf2238
def __call__(self, x, maximum_bits=20000): '\n Allows an object of this class to behave like a function. If\n ``ceil`` is an instance of this class, we can do ``ceil(n)`` to get\n the ceiling of ``n``.\n\n TESTS::\n\n sage: ceil(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000001\n sage: ceil(SR(10^50 - 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: ceil(int(10^50))\n 100000000000000000000000000000000000000000000000000\n ' try: return x.ceil() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.ceil(x))) elif (type(x).__module__ == 'numpy'): import numpy return numpy.ceil(x) x_original = x from sage.rings.all import RealIntervalField bits = 53 try: x_interval = RealIntervalField(bits)(x) upper_ceil = x_interval.upper().ceil() lower_ceil = x_interval.lower().ceil() while ((upper_ceil != lower_ceil) and (bits < maximum_bits)): bits += 100 x_interval = RealIntervalField(bits)(x) upper_ceil = x_interval.upper().ceil() lower_ceil = x_interval.lower().ceil() if (bits < maximum_bits): return lower_ceil else: try: return ceil(SR(x).full_simplify().simplify_radical()) except ValueError: pass raise ValueError(('x (= %s) requires more than %s bits of precision to compute its ceiling' % (x, maximum_bits))) except TypeError: return BuiltinFunction.__call__(self, SR(x_original))
Allows an object of this class to behave like a function. If ``ceil`` is an instance of this class, we can do ``ceil(n)`` to get the ceiling of ``n``. TESTS:: sage: ceil(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000001 sage: ceil(SR(10^50 - 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: ceil(int(10^50)) 100000000000000000000000000000000000000000000000000
src/sage/functions/other.py
__call__
drvinceknight/sage
2
python
def __call__(self, x, maximum_bits=20000): '\n Allows an object of this class to behave like a function. If\n ``ceil`` is an instance of this class, we can do ``ceil(n)`` to get\n the ceiling of ``n``.\n\n TESTS::\n\n sage: ceil(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000001\n sage: ceil(SR(10^50 - 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: ceil(int(10^50))\n 100000000000000000000000000000000000000000000000000\n ' try: return x.ceil() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.ceil(x))) elif (type(x).__module__ == 'numpy'): import numpy return numpy.ceil(x) x_original = x from sage.rings.all import RealIntervalField bits = 53 try: x_interval = RealIntervalField(bits)(x) upper_ceil = x_interval.upper().ceil() lower_ceil = x_interval.lower().ceil() while ((upper_ceil != lower_ceil) and (bits < maximum_bits)): bits += 100 x_interval = RealIntervalField(bits)(x) upper_ceil = x_interval.upper().ceil() lower_ceil = x_interval.lower().ceil() if (bits < maximum_bits): return lower_ceil else: try: return ceil(SR(x).full_simplify().simplify_radical()) except ValueError: pass raise ValueError(('x (= %s) requires more than %s bits of precision to compute its ceiling' % (x, maximum_bits))) except TypeError: return BuiltinFunction.__call__(self, SR(x_original))
def __call__(self, x, maximum_bits=20000): '\n Allows an object of this class to behave like a function. If\n ``ceil`` is an instance of this class, we can do ``ceil(n)`` to get\n the ceiling of ``n``.\n\n TESTS::\n\n sage: ceil(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000001\n sage: ceil(SR(10^50 - 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: ceil(int(10^50))\n 100000000000000000000000000000000000000000000000000\n ' try: return x.ceil() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.ceil(x))) elif (type(x).__module__ == 'numpy'): import numpy return numpy.ceil(x) x_original = x from sage.rings.all import RealIntervalField bits = 53 try: x_interval = RealIntervalField(bits)(x) upper_ceil = x_interval.upper().ceil() lower_ceil = x_interval.lower().ceil() while ((upper_ceil != lower_ceil) and (bits < maximum_bits)): bits += 100 x_interval = RealIntervalField(bits)(x) upper_ceil = x_interval.upper().ceil() lower_ceil = x_interval.lower().ceil() if (bits < maximum_bits): return lower_ceil else: try: return ceil(SR(x).full_simplify().simplify_radical()) except ValueError: pass raise ValueError(('x (= %s) requires more than %s bits of precision to compute its ceiling' % (x, maximum_bits))) except TypeError: return BuiltinFunction.__call__(self, SR(x_original))<|docstring|>Allows an object of this class to behave like a function. If ``ceil`` is an instance of this class, we can do ``ceil(n)`` to get the ceiling of ``n``. TESTS:: sage: ceil(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000001 sage: ceil(SR(10^50 - 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: ceil(int(10^50)) 100000000000000000000000000000000000000000000000000<|endoftext|>
0213689006d5d4cb149213824eb84bd473448e27d638ca3cb63049ea0e196d1a
def _eval_(self, x): '\n EXAMPLES::\n\n sage: ceil(x).subs(x==7.5)\n 8\n sage: ceil(x)\n ceil(x)\n ' try: return x.ceil() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.ceil(x))) return None
EXAMPLES:: sage: ceil(x).subs(x==7.5) 8 sage: ceil(x) ceil(x)
src/sage/functions/other.py
_eval_
drvinceknight/sage
2
python
def _eval_(self, x): '\n EXAMPLES::\n\n sage: ceil(x).subs(x==7.5)\n 8\n sage: ceil(x)\n ceil(x)\n ' try: return x.ceil() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.ceil(x))) return None
def _eval_(self, x): '\n EXAMPLES::\n\n sage: ceil(x).subs(x==7.5)\n 8\n sage: ceil(x)\n ceil(x)\n ' try: return x.ceil() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.ceil(x))) return None<|docstring|>EXAMPLES:: sage: ceil(x).subs(x==7.5) 8 sage: ceil(x) ceil(x)<|endoftext|>
8adefc2b2b29b2552d2d886104bc74aaab4f8e2d9c6e7a46bb328ea3f4811380
def __init__(self): "\n The floor function.\n\n The floor of `x` is computed in the following manner.\n\n\n #. The ``x.floor()`` method is called and returned if\n it is there. If it is not, then Sage checks if `x` is one\n of Python's native numeric data types. If so, then it calls and\n returns ``Integer(int(math.floor(x)))``.\n\n #. Sage tries to convert `x` into a\n ``RealIntervalField`` with 53 bits of precision. Next,\n the floors of the endpoints are computed. If they are the same,\n then that value is returned. Otherwise, the precision of the\n ``RealIntervalField`` is increased until they do match\n up or it reaches ``maximum_bits`` of precision.\n\n #. If none of the above work, Sage returns a\n symbolic ``Expression`` object.\n\n\n EXAMPLES::\n\n sage: floor(5.4)\n 5\n sage: type(floor(5.4))\n <type 'sage.rings.integer.Integer'>\n sage: var('x')\n x\n sage: a = floor(5.4 + x); a\n floor(x + 5.40000000000000)\n sage: a.simplify()\n floor(x + 0.4) + 5\n sage: a(x=2)\n 7\n\n ::\n\n sage: floor(cos(8)/cos(2))\n 0\n\n ::\n\n sage: floor(factorial(50)/exp(1))\n 11188719610782480504630258070757734324011354208865721592720336800\n sage: floor(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: floor(SR(10^50 - 10^(-50)))\n 99999999999999999999999999999999999999999999999999\n sage: floor(int(10^50))\n 100000000000000000000000000000000000000000000000000\n\n ::\n\n sage: import numpy\n sage: a = numpy.linspace(0,2,6)\n sage: floor(a)\n array([ 0., 0., 0., 1., 1., 2.])\n\n Test pickling::\n\n sage: loads(dumps(floor))\n floor\n " BuiltinFunction.__init__(self, 'floor')
The floor function. The floor of `x` is computed in the following manner. #. The ``x.floor()`` method is called and returned if it is there. If it is not, then Sage checks if `x` is one of Python's native numeric data types. If so, then it calls and returns ``Integer(int(math.floor(x)))``. #. Sage tries to convert `x` into a ``RealIntervalField`` with 53 bits of precision. Next, the floors of the endpoints are computed. If they are the same, then that value is returned. Otherwise, the precision of the ``RealIntervalField`` is increased until they do match up or it reaches ``maximum_bits`` of precision. #. If none of the above work, Sage returns a symbolic ``Expression`` object. EXAMPLES:: sage: floor(5.4) 5 sage: type(floor(5.4)) <type 'sage.rings.integer.Integer'> sage: var('x') x sage: a = floor(5.4 + x); a floor(x + 5.40000000000000) sage: a.simplify() floor(x + 0.4) + 5 sage: a(x=2) 7 :: sage: floor(cos(8)/cos(2)) 0 :: sage: floor(factorial(50)/exp(1)) 11188719610782480504630258070757734324011354208865721592720336800 sage: floor(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: floor(SR(10^50 - 10^(-50))) 99999999999999999999999999999999999999999999999999 sage: floor(int(10^50)) 100000000000000000000000000000000000000000000000000 :: sage: import numpy sage: a = numpy.linspace(0,2,6) sage: floor(a) array([ 0., 0., 0., 1., 1., 2.]) Test pickling:: sage: loads(dumps(floor)) floor
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n The floor function.\n\n The floor of `x` is computed in the following manner.\n\n\n #. The ``x.floor()`` method is called and returned if\n it is there. If it is not, then Sage checks if `x` is one\n of Python's native numeric data types. If so, then it calls and\n returns ``Integer(int(math.floor(x)))``.\n\n #. Sage tries to convert `x` into a\n ``RealIntervalField`` with 53 bits of precision. Next,\n the floors of the endpoints are computed. If they are the same,\n then that value is returned. Otherwise, the precision of the\n ``RealIntervalField`` is increased until they do match\n up or it reaches ``maximum_bits`` of precision.\n\n #. If none of the above work, Sage returns a\n symbolic ``Expression`` object.\n\n\n EXAMPLES::\n\n sage: floor(5.4)\n 5\n sage: type(floor(5.4))\n <type 'sage.rings.integer.Integer'>\n sage: var('x')\n x\n sage: a = floor(5.4 + x); a\n floor(x + 5.40000000000000)\n sage: a.simplify()\n floor(x + 0.4) + 5\n sage: a(x=2)\n 7\n\n ::\n\n sage: floor(cos(8)/cos(2))\n 0\n\n ::\n\n sage: floor(factorial(50)/exp(1))\n 11188719610782480504630258070757734324011354208865721592720336800\n sage: floor(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: floor(SR(10^50 - 10^(-50)))\n 99999999999999999999999999999999999999999999999999\n sage: floor(int(10^50))\n 100000000000000000000000000000000000000000000000000\n\n ::\n\n sage: import numpy\n sage: a = numpy.linspace(0,2,6)\n sage: floor(a)\n array([ 0., 0., 0., 1., 1., 2.])\n\n Test pickling::\n\n sage: loads(dumps(floor))\n floor\n " BuiltinFunction.__init__(self, 'floor')
def __init__(self): "\n The floor function.\n\n The floor of `x` is computed in the following manner.\n\n\n #. The ``x.floor()`` method is called and returned if\n it is there. If it is not, then Sage checks if `x` is one\n of Python's native numeric data types. If so, then it calls and\n returns ``Integer(int(math.floor(x)))``.\n\n #. Sage tries to convert `x` into a\n ``RealIntervalField`` with 53 bits of precision. Next,\n the floors of the endpoints are computed. If they are the same,\n then that value is returned. Otherwise, the precision of the\n ``RealIntervalField`` is increased until they do match\n up or it reaches ``maximum_bits`` of precision.\n\n #. If none of the above work, Sage returns a\n symbolic ``Expression`` object.\n\n\n EXAMPLES::\n\n sage: floor(5.4)\n 5\n sage: type(floor(5.4))\n <type 'sage.rings.integer.Integer'>\n sage: var('x')\n x\n sage: a = floor(5.4 + x); a\n floor(x + 5.40000000000000)\n sage: a.simplify()\n floor(x + 0.4) + 5\n sage: a(x=2)\n 7\n\n ::\n\n sage: floor(cos(8)/cos(2))\n 0\n\n ::\n\n sage: floor(factorial(50)/exp(1))\n 11188719610782480504630258070757734324011354208865721592720336800\n sage: floor(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: floor(SR(10^50 - 10^(-50)))\n 99999999999999999999999999999999999999999999999999\n sage: floor(int(10^50))\n 100000000000000000000000000000000000000000000000000\n\n ::\n\n sage: import numpy\n sage: a = numpy.linspace(0,2,6)\n sage: floor(a)\n array([ 0., 0., 0., 1., 1., 2.])\n\n Test pickling::\n\n sage: loads(dumps(floor))\n floor\n " BuiltinFunction.__init__(self, 'floor')<|docstring|>The floor function. The floor of `x` is computed in the following manner. #. The ``x.floor()`` method is called and returned if it is there. If it is not, then Sage checks if `x` is one of Python's native numeric data types. If so, then it calls and returns ``Integer(int(math.floor(x)))``. #. Sage tries to convert `x` into a ``RealIntervalField`` with 53 bits of precision. Next, the floors of the endpoints are computed. If they are the same, then that value is returned. Otherwise, the precision of the ``RealIntervalField`` is increased until they do match up or it reaches ``maximum_bits`` of precision. #. If none of the above work, Sage returns a symbolic ``Expression`` object. EXAMPLES:: sage: floor(5.4) 5 sage: type(floor(5.4)) <type 'sage.rings.integer.Integer'> sage: var('x') x sage: a = floor(5.4 + x); a floor(x + 5.40000000000000) sage: a.simplify() floor(x + 0.4) + 5 sage: a(x=2) 7 :: sage: floor(cos(8)/cos(2)) 0 :: sage: floor(factorial(50)/exp(1)) 11188719610782480504630258070757734324011354208865721592720336800 sage: floor(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: floor(SR(10^50 - 10^(-50))) 99999999999999999999999999999999999999999999999999 sage: floor(int(10^50)) 100000000000000000000000000000000000000000000000000 :: sage: import numpy sage: a = numpy.linspace(0,2,6) sage: floor(a) array([ 0., 0., 0., 1., 1., 2.]) Test pickling:: sage: loads(dumps(floor)) floor<|endoftext|>
d973fad094f820554b000ab97331b35a995c38f495fb701022ed44063e8db312
def _print_latex_(self, x): '\n EXAMPLES::\n\n sage: latex(floor(x))\n \\left \\lfloor x \\right \\rfloor\n ' return ('\\left \\lfloor %s \\right \\rfloor' % latex(x))
EXAMPLES:: sage: latex(floor(x)) \left \lfloor x \right \rfloor
src/sage/functions/other.py
_print_latex_
drvinceknight/sage
2
python
def _print_latex_(self, x): '\n EXAMPLES::\n\n sage: latex(floor(x))\n \\left \\lfloor x \\right \\rfloor\n ' return ('\\left \\lfloor %s \\right \\rfloor' % latex(x))
def _print_latex_(self, x): '\n EXAMPLES::\n\n sage: latex(floor(x))\n \\left \\lfloor x \\right \\rfloor\n ' return ('\\left \\lfloor %s \\right \\rfloor' % latex(x))<|docstring|>EXAMPLES:: sage: latex(floor(x)) \left \lfloor x \right \rfloor<|endoftext|>
0bead0ca8eabb278ed5c7af8c54369df3de9e4c2cdc65a9fa9c27b06eec59d2c
def __call__(self, x, maximum_bits=20000): '\n Allows an object of this class to behave like a function. If\n ``floor`` is an instance of this class, we can do ``floor(n)`` to\n obtain the floor of ``n``.\n\n TESTS::\n\n sage: floor(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: floor(SR(10^50 - 10^(-50)))\n 99999999999999999999999999999999999999999999999999\n sage: floor(int(10^50))\n 100000000000000000000000000000000000000000000000000\n ' try: return x.floor() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.floor(x))) elif (type(x).__module__ == 'numpy'): import numpy return numpy.floor(x) x_original = x from sage.rings.all import RealIntervalField bits = 53 try: x_interval = RealIntervalField(bits)(x) upper_floor = x_interval.upper().floor() lower_floor = x_interval.lower().floor() while ((upper_floor != lower_floor) and (bits < maximum_bits)): bits += 100 x_interval = RealIntervalField(bits)(x) upper_floor = x_interval.upper().floor() lower_floor = x_interval.lower().floor() if (bits < maximum_bits): return lower_floor else: try: return floor(SR(x).full_simplify().simplify_radical()) except ValueError: pass raise ValueError(('x (= %s) requires more than %s bits of precision to compute its floor' % (x, maximum_bits))) except TypeError: return BuiltinFunction.__call__(self, SR(x_original))
Allows an object of this class to behave like a function. If ``floor`` is an instance of this class, we can do ``floor(n)`` to obtain the floor of ``n``. TESTS:: sage: floor(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: floor(SR(10^50 - 10^(-50))) 99999999999999999999999999999999999999999999999999 sage: floor(int(10^50)) 100000000000000000000000000000000000000000000000000
src/sage/functions/other.py
__call__
drvinceknight/sage
2
python
def __call__(self, x, maximum_bits=20000): '\n Allows an object of this class to behave like a function. If\n ``floor`` is an instance of this class, we can do ``floor(n)`` to\n obtain the floor of ``n``.\n\n TESTS::\n\n sage: floor(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: floor(SR(10^50 - 10^(-50)))\n 99999999999999999999999999999999999999999999999999\n sage: floor(int(10^50))\n 100000000000000000000000000000000000000000000000000\n ' try: return x.floor() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.floor(x))) elif (type(x).__module__ == 'numpy'): import numpy return numpy.floor(x) x_original = x from sage.rings.all import RealIntervalField bits = 53 try: x_interval = RealIntervalField(bits)(x) upper_floor = x_interval.upper().floor() lower_floor = x_interval.lower().floor() while ((upper_floor != lower_floor) and (bits < maximum_bits)): bits += 100 x_interval = RealIntervalField(bits)(x) upper_floor = x_interval.upper().floor() lower_floor = x_interval.lower().floor() if (bits < maximum_bits): return lower_floor else: try: return floor(SR(x).full_simplify().simplify_radical()) except ValueError: pass raise ValueError(('x (= %s) requires more than %s bits of precision to compute its floor' % (x, maximum_bits))) except TypeError: return BuiltinFunction.__call__(self, SR(x_original))
def __call__(self, x, maximum_bits=20000): '\n Allows an object of this class to behave like a function. If\n ``floor`` is an instance of this class, we can do ``floor(n)`` to\n obtain the floor of ``n``.\n\n TESTS::\n\n sage: floor(SR(10^50 + 10^(-50)))\n 100000000000000000000000000000000000000000000000000\n sage: floor(SR(10^50 - 10^(-50)))\n 99999999999999999999999999999999999999999999999999\n sage: floor(int(10^50))\n 100000000000000000000000000000000000000000000000000\n ' try: return x.floor() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.floor(x))) elif (type(x).__module__ == 'numpy'): import numpy return numpy.floor(x) x_original = x from sage.rings.all import RealIntervalField bits = 53 try: x_interval = RealIntervalField(bits)(x) upper_floor = x_interval.upper().floor() lower_floor = x_interval.lower().floor() while ((upper_floor != lower_floor) and (bits < maximum_bits)): bits += 100 x_interval = RealIntervalField(bits)(x) upper_floor = x_interval.upper().floor() lower_floor = x_interval.lower().floor() if (bits < maximum_bits): return lower_floor else: try: return floor(SR(x).full_simplify().simplify_radical()) except ValueError: pass raise ValueError(('x (= %s) requires more than %s bits of precision to compute its floor' % (x, maximum_bits))) except TypeError: return BuiltinFunction.__call__(self, SR(x_original))<|docstring|>Allows an object of this class to behave like a function. If ``floor`` is an instance of this class, we can do ``floor(n)`` to obtain the floor of ``n``. TESTS:: sage: floor(SR(10^50 + 10^(-50))) 100000000000000000000000000000000000000000000000000 sage: floor(SR(10^50 - 10^(-50))) 99999999999999999999999999999999999999999999999999 sage: floor(int(10^50)) 100000000000000000000000000000000000000000000000000<|endoftext|>
9ad90d1932ac45ec4493225ec8d9cc10ad907e9fc37b638b73913197137ac094
def _eval_(self, x): '\n EXAMPLES::\n\n sage: floor(x).subs(x==7.5)\n 7\n sage: floor(x)\n floor(x)\n ' try: return x.floor() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.floor(x))) return None
EXAMPLES:: sage: floor(x).subs(x==7.5) 7 sage: floor(x) floor(x)
src/sage/functions/other.py
_eval_
drvinceknight/sage
2
python
def _eval_(self, x): '\n EXAMPLES::\n\n sage: floor(x).subs(x==7.5)\n 7\n sage: floor(x)\n floor(x)\n ' try: return x.floor() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.floor(x))) return None
def _eval_(self, x): '\n EXAMPLES::\n\n sage: floor(x).subs(x==7.5)\n 7\n sage: floor(x)\n floor(x)\n ' try: return x.floor() except AttributeError: if isinstance(x, (int, long)): return Integer(x) elif isinstance(x, (float, complex)): return Integer(int(math.floor(x))) return None<|docstring|>EXAMPLES:: sage: floor(x).subs(x==7.5) 7 sage: floor(x) floor(x)<|endoftext|>
8d6ad702090f61f87ff8cd6734c19baebbc46b8be69d2d1e541b2e523adf8d47
def __init__(self): "\n The Gamma function. This is defined by\n\n .. math::\n\n \\Gamma(z) = \\int_0^\\infty t^{z-1}e^{-t} dt\n\n for complex input `z` with real part greater than zero, and by\n analytic continuation on the rest of the complex plane (except\n for negative integers, which are poles).\n\n It is computed by various libraries within Sage, depending on\n the input type.\n\n EXAMPLES::\n\n sage: from sage.functions.other import gamma1\n sage: gamma1(CDF(0.5,14))\n -4.05370307804e-10 - 5.77329983455e-10*I\n sage: gamma1(CDF(I))\n -0.154949828302 - 0.498015668118*I\n\n Recall that `\\Gamma(n)` is `n-1` factorial::\n\n sage: gamma1(11) == factorial(10)\n True\n sage: gamma1(6)\n 120\n sage: gamma1(1/2)\n sqrt(pi)\n sage: gamma1(-1)\n Infinity\n sage: gamma1(I)\n gamma(I)\n sage: gamma1(x/2)(x=5)\n 3/4*sqrt(pi)\n\n sage: gamma1(float(6)) # For ARM: rel tol 3e-16\n 120.0\n sage: gamma1(x)\n gamma(x)\n\n ::\n\n sage: gamma1(pi)\n gamma(pi)\n sage: gamma1(i)\n gamma(I)\n sage: gamma1(i).n()\n -0.154949828301811 - 0.498015668118356*I\n sage: gamma1(int(5))\n 24\n\n ::\n\n sage: conjugate(gamma(x))\n gamma(conjugate(x))\n\n ::\n\n sage: plot(gamma1(x),(x,1,5))\n\n To prevent automatic evaluation use the ``hold`` argument::\n\n sage: gamma1(1/2,hold=True)\n gamma(1/2)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: gamma1(1/2,hold=True).simplify()\n sqrt(pi)\n\n TESTS:\n\n We verify that we can convert this function to Maxima and\n convert back to Sage::\n\n sage: z = var('z')\n sage: maxima(gamma1(z)).sage()\n gamma(z)\n sage: latex(gamma1(z))\n \\Gamma\\left(z\\right)\n\n Test that Trac ticket 5556 is fixed::\n\n sage: gamma1(3/4)\n gamma(3/4)\n\n sage: gamma1(3/4).n(100)\n 1.2254167024651776451290983034\n\n Check that negative integer input works::\n\n sage: (-1).gamma()\n Infinity\n sage: (-1.).gamma()\n NaN\n sage: CC(-1).gamma()\n Infinity\n sage: RDF(-1).gamma()\n NaN\n sage: CDF(-1).gamma()\n Infinity\n\n Check if #8297 is fixed::\n\n sage: latex(gamma(1/4))\n \\Gamma\\left(\\frac{1}{4}\\right)\n\n Test pickling::\n\n sage: loads(dumps(gamma(x)))\n gamma(x)\n " GinacFunction.__init__(self, 'gamma', latex_name='\\Gamma', ginac_name='tgamma', conversions={'mathematica': 'Gamma', 'maple': 'GAMMA'})
The Gamma function. This is defined by .. math:: \Gamma(z) = \int_0^\infty t^{z-1}e^{-t} dt for complex input `z` with real part greater than zero, and by analytic continuation on the rest of the complex plane (except for negative integers, which are poles). It is computed by various libraries within Sage, depending on the input type. EXAMPLES:: sage: from sage.functions.other import gamma1 sage: gamma1(CDF(0.5,14)) -4.05370307804e-10 - 5.77329983455e-10*I sage: gamma1(CDF(I)) -0.154949828302 - 0.498015668118*I Recall that `\Gamma(n)` is `n-1` factorial:: sage: gamma1(11) == factorial(10) True sage: gamma1(6) 120 sage: gamma1(1/2) sqrt(pi) sage: gamma1(-1) Infinity sage: gamma1(I) gamma(I) sage: gamma1(x/2)(x=5) 3/4*sqrt(pi) sage: gamma1(float(6)) # For ARM: rel tol 3e-16 120.0 sage: gamma1(x) gamma(x) :: sage: gamma1(pi) gamma(pi) sage: gamma1(i) gamma(I) sage: gamma1(i).n() -0.154949828301811 - 0.498015668118356*I sage: gamma1(int(5)) 24 :: sage: conjugate(gamma(x)) gamma(conjugate(x)) :: sage: plot(gamma1(x),(x,1,5)) To prevent automatic evaluation use the ``hold`` argument:: sage: gamma1(1/2,hold=True) gamma(1/2) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: gamma1(1/2,hold=True).simplify() sqrt(pi) TESTS: We verify that we can convert this function to Maxima and convert back to Sage:: sage: z = var('z') sage: maxima(gamma1(z)).sage() gamma(z) sage: latex(gamma1(z)) \Gamma\left(z\right) Test that Trac ticket 5556 is fixed:: sage: gamma1(3/4) gamma(3/4) sage: gamma1(3/4).n(100) 1.2254167024651776451290983034 Check that negative integer input works:: sage: (-1).gamma() Infinity sage: (-1.).gamma() NaN sage: CC(-1).gamma() Infinity sage: RDF(-1).gamma() NaN sage: CDF(-1).gamma() Infinity Check if #8297 is fixed:: sage: latex(gamma(1/4)) \Gamma\left(\frac{1}{4}\right) Test pickling:: sage: loads(dumps(gamma(x))) gamma(x)
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n The Gamma function. This is defined by\n\n .. math::\n\n \\Gamma(z) = \\int_0^\\infty t^{z-1}e^{-t} dt\n\n for complex input `z` with real part greater than zero, and by\n analytic continuation on the rest of the complex plane (except\n for negative integers, which are poles).\n\n It is computed by various libraries within Sage, depending on\n the input type.\n\n EXAMPLES::\n\n sage: from sage.functions.other import gamma1\n sage: gamma1(CDF(0.5,14))\n -4.05370307804e-10 - 5.77329983455e-10*I\n sage: gamma1(CDF(I))\n -0.154949828302 - 0.498015668118*I\n\n Recall that `\\Gamma(n)` is `n-1` factorial::\n\n sage: gamma1(11) == factorial(10)\n True\n sage: gamma1(6)\n 120\n sage: gamma1(1/2)\n sqrt(pi)\n sage: gamma1(-1)\n Infinity\n sage: gamma1(I)\n gamma(I)\n sage: gamma1(x/2)(x=5)\n 3/4*sqrt(pi)\n\n sage: gamma1(float(6)) # For ARM: rel tol 3e-16\n 120.0\n sage: gamma1(x)\n gamma(x)\n\n ::\n\n sage: gamma1(pi)\n gamma(pi)\n sage: gamma1(i)\n gamma(I)\n sage: gamma1(i).n()\n -0.154949828301811 - 0.498015668118356*I\n sage: gamma1(int(5))\n 24\n\n ::\n\n sage: conjugate(gamma(x))\n gamma(conjugate(x))\n\n ::\n\n sage: plot(gamma1(x),(x,1,5))\n\n To prevent automatic evaluation use the ``hold`` argument::\n\n sage: gamma1(1/2,hold=True)\n gamma(1/2)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: gamma1(1/2,hold=True).simplify()\n sqrt(pi)\n\n TESTS:\n\n We verify that we can convert this function to Maxima and\n convert back to Sage::\n\n sage: z = var('z')\n sage: maxima(gamma1(z)).sage()\n gamma(z)\n sage: latex(gamma1(z))\n \\Gamma\\left(z\\right)\n\n Test that Trac ticket 5556 is fixed::\n\n sage: gamma1(3/4)\n gamma(3/4)\n\n sage: gamma1(3/4).n(100)\n 1.2254167024651776451290983034\n\n Check that negative integer input works::\n\n sage: (-1).gamma()\n Infinity\n sage: (-1.).gamma()\n NaN\n sage: CC(-1).gamma()\n Infinity\n sage: RDF(-1).gamma()\n NaN\n sage: CDF(-1).gamma()\n Infinity\n\n Check if #8297 is fixed::\n\n sage: latex(gamma(1/4))\n \\Gamma\\left(\\frac{1}{4}\\right)\n\n Test pickling::\n\n sage: loads(dumps(gamma(x)))\n gamma(x)\n " GinacFunction.__init__(self, 'gamma', latex_name='\\Gamma', ginac_name='tgamma', conversions={'mathematica': 'Gamma', 'maple': 'GAMMA'})
def __init__(self): "\n The Gamma function. This is defined by\n\n .. math::\n\n \\Gamma(z) = \\int_0^\\infty t^{z-1}e^{-t} dt\n\n for complex input `z` with real part greater than zero, and by\n analytic continuation on the rest of the complex plane (except\n for negative integers, which are poles).\n\n It is computed by various libraries within Sage, depending on\n the input type.\n\n EXAMPLES::\n\n sage: from sage.functions.other import gamma1\n sage: gamma1(CDF(0.5,14))\n -4.05370307804e-10 - 5.77329983455e-10*I\n sage: gamma1(CDF(I))\n -0.154949828302 - 0.498015668118*I\n\n Recall that `\\Gamma(n)` is `n-1` factorial::\n\n sage: gamma1(11) == factorial(10)\n True\n sage: gamma1(6)\n 120\n sage: gamma1(1/2)\n sqrt(pi)\n sage: gamma1(-1)\n Infinity\n sage: gamma1(I)\n gamma(I)\n sage: gamma1(x/2)(x=5)\n 3/4*sqrt(pi)\n\n sage: gamma1(float(6)) # For ARM: rel tol 3e-16\n 120.0\n sage: gamma1(x)\n gamma(x)\n\n ::\n\n sage: gamma1(pi)\n gamma(pi)\n sage: gamma1(i)\n gamma(I)\n sage: gamma1(i).n()\n -0.154949828301811 - 0.498015668118356*I\n sage: gamma1(int(5))\n 24\n\n ::\n\n sage: conjugate(gamma(x))\n gamma(conjugate(x))\n\n ::\n\n sage: plot(gamma1(x),(x,1,5))\n\n To prevent automatic evaluation use the ``hold`` argument::\n\n sage: gamma1(1/2,hold=True)\n gamma(1/2)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: gamma1(1/2,hold=True).simplify()\n sqrt(pi)\n\n TESTS:\n\n We verify that we can convert this function to Maxima and\n convert back to Sage::\n\n sage: z = var('z')\n sage: maxima(gamma1(z)).sage()\n gamma(z)\n sage: latex(gamma1(z))\n \\Gamma\\left(z\\right)\n\n Test that Trac ticket 5556 is fixed::\n\n sage: gamma1(3/4)\n gamma(3/4)\n\n sage: gamma1(3/4).n(100)\n 1.2254167024651776451290983034\n\n Check that negative integer input works::\n\n sage: (-1).gamma()\n Infinity\n sage: (-1.).gamma()\n NaN\n sage: CC(-1).gamma()\n Infinity\n sage: RDF(-1).gamma()\n NaN\n sage: CDF(-1).gamma()\n Infinity\n\n Check if #8297 is fixed::\n\n sage: latex(gamma(1/4))\n \\Gamma\\left(\\frac{1}{4}\\right)\n\n Test pickling::\n\n sage: loads(dumps(gamma(x)))\n gamma(x)\n " GinacFunction.__init__(self, 'gamma', latex_name='\\Gamma', ginac_name='tgamma', conversions={'mathematica': 'Gamma', 'maple': 'GAMMA'})<|docstring|>The Gamma function. This is defined by .. math:: \Gamma(z) = \int_0^\infty t^{z-1}e^{-t} dt for complex input `z` with real part greater than zero, and by analytic continuation on the rest of the complex plane (except for negative integers, which are poles). It is computed by various libraries within Sage, depending on the input type. EXAMPLES:: sage: from sage.functions.other import gamma1 sage: gamma1(CDF(0.5,14)) -4.05370307804e-10 - 5.77329983455e-10*I sage: gamma1(CDF(I)) -0.154949828302 - 0.498015668118*I Recall that `\Gamma(n)` is `n-1` factorial:: sage: gamma1(11) == factorial(10) True sage: gamma1(6) 120 sage: gamma1(1/2) sqrt(pi) sage: gamma1(-1) Infinity sage: gamma1(I) gamma(I) sage: gamma1(x/2)(x=5) 3/4*sqrt(pi) sage: gamma1(float(6)) # For ARM: rel tol 3e-16 120.0 sage: gamma1(x) gamma(x) :: sage: gamma1(pi) gamma(pi) sage: gamma1(i) gamma(I) sage: gamma1(i).n() -0.154949828301811 - 0.498015668118356*I sage: gamma1(int(5)) 24 :: sage: conjugate(gamma(x)) gamma(conjugate(x)) :: sage: plot(gamma1(x),(x,1,5)) To prevent automatic evaluation use the ``hold`` argument:: sage: gamma1(1/2,hold=True) gamma(1/2) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: gamma1(1/2,hold=True).simplify() sqrt(pi) TESTS: We verify that we can convert this function to Maxima and convert back to Sage:: sage: z = var('z') sage: maxima(gamma1(z)).sage() gamma(z) sage: latex(gamma1(z)) \Gamma\left(z\right) Test that Trac ticket 5556 is fixed:: sage: gamma1(3/4) gamma(3/4) sage: gamma1(3/4).n(100) 1.2254167024651776451290983034 Check that negative integer input works:: sage: (-1).gamma() Infinity sage: (-1.).gamma() NaN sage: CC(-1).gamma() Infinity sage: RDF(-1).gamma() NaN sage: CDF(-1).gamma() Infinity Check if #8297 is fixed:: sage: latex(gamma(1/4)) \Gamma\left(\frac{1}{4}\right) Test pickling:: sage: loads(dumps(gamma(x))) gamma(x)<|endoftext|>
c4fbf6f9b399c1d10cd37f1991323fbac4d012ccb18624195fe56f47e4448328
def __call__(self, x, prec=None, coerce=True, hold=False): '\n Note that the ``prec`` argument is deprecated. The precision for\n the result is deduced from the precision of the input. Convert\n the input to a higher precision explicitly if a result with higher\n precision is desired.::\n\n sage: t = gamma(RealField(100)(2.5)); t\n 1.3293403881791370204736256125\n sage: t.prec()\n 100\n\n sage: gamma(6, prec=53)\n doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.\n See http://trac.sagemath.org/7490 for details.\n 120.000000000000\n\n TESTS::\n\n sage: gamma(pi,prec=100)\n 2.2880377953400324179595889091\n\n sage: gamma(3/4,prec=100)\n 1.2254167024651776451290983034\n ' if (prec is not None): from sage.misc.superseded import deprecation deprecation(7490, 'The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.') import mpmath return mpmath_utils.call(mpmath.gamma, x, prec=prec) try: res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold) except TypeError as err: if (not str(err).startswith('cannot coerce')): raise from sage.misc.superseded import deprecation deprecation(7490, 'Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated.') parent = (RR if (prec is None) else RealField(prec)) try: x = parent(x) except (ValueError, TypeError): x = parent.complex_field()(x) res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold) return res
Note that the ``prec`` argument is deprecated. The precision for the result is deduced from the precision of the input. Convert the input to a higher precision explicitly if a result with higher precision is desired.:: sage: t = gamma(RealField(100)(2.5)); t 1.3293403881791370204736256125 sage: t.prec() 100 sage: gamma(6, prec=53) doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead. See http://trac.sagemath.org/7490 for details. 120.000000000000 TESTS:: sage: gamma(pi,prec=100) 2.2880377953400324179595889091 sage: gamma(3/4,prec=100) 1.2254167024651776451290983034
src/sage/functions/other.py
__call__
drvinceknight/sage
2
python
def __call__(self, x, prec=None, coerce=True, hold=False): '\n Note that the ``prec`` argument is deprecated. The precision for\n the result is deduced from the precision of the input. Convert\n the input to a higher precision explicitly if a result with higher\n precision is desired.::\n\n sage: t = gamma(RealField(100)(2.5)); t\n 1.3293403881791370204736256125\n sage: t.prec()\n 100\n\n sage: gamma(6, prec=53)\n doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.\n See http://trac.sagemath.org/7490 for details.\n 120.000000000000\n\n TESTS::\n\n sage: gamma(pi,prec=100)\n 2.2880377953400324179595889091\n\n sage: gamma(3/4,prec=100)\n 1.2254167024651776451290983034\n ' if (prec is not None): from sage.misc.superseded import deprecation deprecation(7490, 'The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.') import mpmath return mpmath_utils.call(mpmath.gamma, x, prec=prec) try: res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold) except TypeError as err: if (not str(err).startswith('cannot coerce')): raise from sage.misc.superseded import deprecation deprecation(7490, 'Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated.') parent = (RR if (prec is None) else RealField(prec)) try: x = parent(x) except (ValueError, TypeError): x = parent.complex_field()(x) res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold) return res
def __call__(self, x, prec=None, coerce=True, hold=False): '\n Note that the ``prec`` argument is deprecated. The precision for\n the result is deduced from the precision of the input. Convert\n the input to a higher precision explicitly if a result with higher\n precision is desired.::\n\n sage: t = gamma(RealField(100)(2.5)); t\n 1.3293403881791370204736256125\n sage: t.prec()\n 100\n\n sage: gamma(6, prec=53)\n doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.\n See http://trac.sagemath.org/7490 for details.\n 120.000000000000\n\n TESTS::\n\n sage: gamma(pi,prec=100)\n 2.2880377953400324179595889091\n\n sage: gamma(3/4,prec=100)\n 1.2254167024651776451290983034\n ' if (prec is not None): from sage.misc.superseded import deprecation deprecation(7490, 'The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.') import mpmath return mpmath_utils.call(mpmath.gamma, x, prec=prec) try: res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold) except TypeError as err: if (not str(err).startswith('cannot coerce')): raise from sage.misc.superseded import deprecation deprecation(7490, 'Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated.') parent = (RR if (prec is None) else RealField(prec)) try: x = parent(x) except (ValueError, TypeError): x = parent.complex_field()(x) res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold) return res<|docstring|>Note that the ``prec`` argument is deprecated. The precision for the result is deduced from the precision of the input. Convert the input to a higher precision explicitly if a result with higher precision is desired.:: sage: t = gamma(RealField(100)(2.5)); t 1.3293403881791370204736256125 sage: t.prec() 100 sage: gamma(6, prec=53) doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead. See http://trac.sagemath.org/7490 for details. 120.000000000000 TESTS:: sage: gamma(pi,prec=100) 2.2880377953400324179595889091 sage: gamma(3/4,prec=100) 1.2254167024651776451290983034<|endoftext|>
171a86fe1cbcac70aa8cbbd970537b6d02065a09eefd3872fd45b518676bc999
def __init__(self): "\n The principal branch of the logarithm of Gamma function.\n Gamma is defined for complex input `z` with real part greater\n than zero, and by analytic continuation on the rest of the\n complex plane (except for negative integers, which are poles).\n\n It is computed by the `log_gamma` function for the number type,\n or by `lgamma` in Ginac, failing that.\n\n EXAMPLES:\n\n Numerical evaluation happens when appropriate, to the\n appropriate accuracy (see #10072)::\n\n sage: log_gamma(6)\n log(120)\n sage: log_gamma(6.)\n 4.78749174278205\n sage: log_gamma(6).n()\n 4.78749174278205\n sage: log_gamma(RealField(100)(6))\n 4.7874917427820459942477009345\n sage: log_gamma(2.4+i)\n -0.0308566579348816 + 0.693427705955790*I\n sage: log_gamma(-3.1)\n 0.400311696703985\n\n Symbolic input works (see #10075)::\n\n sage: log_gamma(3*x)\n log_gamma(3*x)\n sage: log_gamma(3+i)\n log_gamma(I + 3)\n sage: log_gamma(3+i+x)\n log_gamma(x + I + 3)\n\n To get evaluation of input for which gamma\n is negative and the ceiling is even, we must\n explicitly make the input complex. This is\n a known issue, see #12521::\n\n sage: log_gamma(-2.1)\n NaN\n sage: log_gamma(CC(-2.1))\n 1.53171380819509 + 3.14159265358979*I\n\n In order to prevent evaluation, use the `hold` argument;\n to evaluate a held expression, use the `n()` numerical\n evaluation method::\n\n sage: log_gamma(SR(5),hold=True)\n log_gamma(5)\n sage: log_gamma(SR(5),hold=True).n()\n 3.17805383034795\n\n TESTS::\n\n sage: log_gamma(-2.1+i)\n -1.90373724496982 - 0.901638463592247*I\n sage: log_gamma(pari(6))\n 4.78749174278205\n sage: log_gamma(CC(6))\n 4.78749174278205\n sage: log_gamma(CC(-2.5))\n -0.0562437164976740 + 3.14159265358979*I\n\n ``conjugate(log_gamma(x))==log_gamma(conjugate(x))`` unless on the branch\n cut, which runs along the negative real axis.::\n\n sage: conjugate(log_gamma(x))\n conjugate(log_gamma(x))\n sage: var('y', domain='positive')\n y\n sage: conjugate(log_gamma(y))\n log_gamma(y)\n sage: conjugate(log_gamma(y+I))\n conjugate(log_gamma(y + I))\n sage: log_gamma(-2)\n +Infinity\n sage: conjugate(log_gamma(-2))\n +Infinity\n " GinacFunction.__init__(self, 'log_gamma', latex_name='\\log\\Gamma', conversions={'mathematica': 'LogGamma', 'maxima': 'log_gamma'})
The principal branch of the logarithm of Gamma function. Gamma is defined for complex input `z` with real part greater than zero, and by analytic continuation on the rest of the complex plane (except for negative integers, which are poles). It is computed by the `log_gamma` function for the number type, or by `lgamma` in Ginac, failing that. EXAMPLES: Numerical evaluation happens when appropriate, to the appropriate accuracy (see #10072):: sage: log_gamma(6) log(120) sage: log_gamma(6.) 4.78749174278205 sage: log_gamma(6).n() 4.78749174278205 sage: log_gamma(RealField(100)(6)) 4.7874917427820459942477009345 sage: log_gamma(2.4+i) -0.0308566579348816 + 0.693427705955790*I sage: log_gamma(-3.1) 0.400311696703985 Symbolic input works (see #10075):: sage: log_gamma(3*x) log_gamma(3*x) sage: log_gamma(3+i) log_gamma(I + 3) sage: log_gamma(3+i+x) log_gamma(x + I + 3) To get evaluation of input for which gamma is negative and the ceiling is even, we must explicitly make the input complex. This is a known issue, see #12521:: sage: log_gamma(-2.1) NaN sage: log_gamma(CC(-2.1)) 1.53171380819509 + 3.14159265358979*I In order to prevent evaluation, use the `hold` argument; to evaluate a held expression, use the `n()` numerical evaluation method:: sage: log_gamma(SR(5),hold=True) log_gamma(5) sage: log_gamma(SR(5),hold=True).n() 3.17805383034795 TESTS:: sage: log_gamma(-2.1+i) -1.90373724496982 - 0.901638463592247*I sage: log_gamma(pari(6)) 4.78749174278205 sage: log_gamma(CC(6)) 4.78749174278205 sage: log_gamma(CC(-2.5)) -0.0562437164976740 + 3.14159265358979*I ``conjugate(log_gamma(x))==log_gamma(conjugate(x))`` unless on the branch cut, which runs along the negative real axis.:: sage: conjugate(log_gamma(x)) conjugate(log_gamma(x)) sage: var('y', domain='positive') y sage: conjugate(log_gamma(y)) log_gamma(y) sage: conjugate(log_gamma(y+I)) conjugate(log_gamma(y + I)) sage: log_gamma(-2) +Infinity sage: conjugate(log_gamma(-2)) +Infinity
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n The principal branch of the logarithm of Gamma function.\n Gamma is defined for complex input `z` with real part greater\n than zero, and by analytic continuation on the rest of the\n complex plane (except for negative integers, which are poles).\n\n It is computed by the `log_gamma` function for the number type,\n or by `lgamma` in Ginac, failing that.\n\n EXAMPLES:\n\n Numerical evaluation happens when appropriate, to the\n appropriate accuracy (see #10072)::\n\n sage: log_gamma(6)\n log(120)\n sage: log_gamma(6.)\n 4.78749174278205\n sage: log_gamma(6).n()\n 4.78749174278205\n sage: log_gamma(RealField(100)(6))\n 4.7874917427820459942477009345\n sage: log_gamma(2.4+i)\n -0.0308566579348816 + 0.693427705955790*I\n sage: log_gamma(-3.1)\n 0.400311696703985\n\n Symbolic input works (see #10075)::\n\n sage: log_gamma(3*x)\n log_gamma(3*x)\n sage: log_gamma(3+i)\n log_gamma(I + 3)\n sage: log_gamma(3+i+x)\n log_gamma(x + I + 3)\n\n To get evaluation of input for which gamma\n is negative and the ceiling is even, we must\n explicitly make the input complex. This is\n a known issue, see #12521::\n\n sage: log_gamma(-2.1)\n NaN\n sage: log_gamma(CC(-2.1))\n 1.53171380819509 + 3.14159265358979*I\n\n In order to prevent evaluation, use the `hold` argument;\n to evaluate a held expression, use the `n()` numerical\n evaluation method::\n\n sage: log_gamma(SR(5),hold=True)\n log_gamma(5)\n sage: log_gamma(SR(5),hold=True).n()\n 3.17805383034795\n\n TESTS::\n\n sage: log_gamma(-2.1+i)\n -1.90373724496982 - 0.901638463592247*I\n sage: log_gamma(pari(6))\n 4.78749174278205\n sage: log_gamma(CC(6))\n 4.78749174278205\n sage: log_gamma(CC(-2.5))\n -0.0562437164976740 + 3.14159265358979*I\n\n ``conjugate(log_gamma(x))==log_gamma(conjugate(x))`` unless on the branch\n cut, which runs along the negative real axis.::\n\n sage: conjugate(log_gamma(x))\n conjugate(log_gamma(x))\n sage: var('y', domain='positive')\n y\n sage: conjugate(log_gamma(y))\n log_gamma(y)\n sage: conjugate(log_gamma(y+I))\n conjugate(log_gamma(y + I))\n sage: log_gamma(-2)\n +Infinity\n sage: conjugate(log_gamma(-2))\n +Infinity\n " GinacFunction.__init__(self, 'log_gamma', latex_name='\\log\\Gamma', conversions={'mathematica': 'LogGamma', 'maxima': 'log_gamma'})
def __init__(self): "\n The principal branch of the logarithm of Gamma function.\n Gamma is defined for complex input `z` with real part greater\n than zero, and by analytic continuation on the rest of the\n complex plane (except for negative integers, which are poles).\n\n It is computed by the `log_gamma` function for the number type,\n or by `lgamma` in Ginac, failing that.\n\n EXAMPLES:\n\n Numerical evaluation happens when appropriate, to the\n appropriate accuracy (see #10072)::\n\n sage: log_gamma(6)\n log(120)\n sage: log_gamma(6.)\n 4.78749174278205\n sage: log_gamma(6).n()\n 4.78749174278205\n sage: log_gamma(RealField(100)(6))\n 4.7874917427820459942477009345\n sage: log_gamma(2.4+i)\n -0.0308566579348816 + 0.693427705955790*I\n sage: log_gamma(-3.1)\n 0.400311696703985\n\n Symbolic input works (see #10075)::\n\n sage: log_gamma(3*x)\n log_gamma(3*x)\n sage: log_gamma(3+i)\n log_gamma(I + 3)\n sage: log_gamma(3+i+x)\n log_gamma(x + I + 3)\n\n To get evaluation of input for which gamma\n is negative and the ceiling is even, we must\n explicitly make the input complex. This is\n a known issue, see #12521::\n\n sage: log_gamma(-2.1)\n NaN\n sage: log_gamma(CC(-2.1))\n 1.53171380819509 + 3.14159265358979*I\n\n In order to prevent evaluation, use the `hold` argument;\n to evaluate a held expression, use the `n()` numerical\n evaluation method::\n\n sage: log_gamma(SR(5),hold=True)\n log_gamma(5)\n sage: log_gamma(SR(5),hold=True).n()\n 3.17805383034795\n\n TESTS::\n\n sage: log_gamma(-2.1+i)\n -1.90373724496982 - 0.901638463592247*I\n sage: log_gamma(pari(6))\n 4.78749174278205\n sage: log_gamma(CC(6))\n 4.78749174278205\n sage: log_gamma(CC(-2.5))\n -0.0562437164976740 + 3.14159265358979*I\n\n ``conjugate(log_gamma(x))==log_gamma(conjugate(x))`` unless on the branch\n cut, which runs along the negative real axis.::\n\n sage: conjugate(log_gamma(x))\n conjugate(log_gamma(x))\n sage: var('y', domain='positive')\n y\n sage: conjugate(log_gamma(y))\n log_gamma(y)\n sage: conjugate(log_gamma(y+I))\n conjugate(log_gamma(y + I))\n sage: log_gamma(-2)\n +Infinity\n sage: conjugate(log_gamma(-2))\n +Infinity\n " GinacFunction.__init__(self, 'log_gamma', latex_name='\\log\\Gamma', conversions={'mathematica': 'LogGamma', 'maxima': 'log_gamma'})<|docstring|>The principal branch of the logarithm of Gamma function. Gamma is defined for complex input `z` with real part greater than zero, and by analytic continuation on the rest of the complex plane (except for negative integers, which are poles). It is computed by the `log_gamma` function for the number type, or by `lgamma` in Ginac, failing that. EXAMPLES: Numerical evaluation happens when appropriate, to the appropriate accuracy (see #10072):: sage: log_gamma(6) log(120) sage: log_gamma(6.) 4.78749174278205 sage: log_gamma(6).n() 4.78749174278205 sage: log_gamma(RealField(100)(6)) 4.7874917427820459942477009345 sage: log_gamma(2.4+i) -0.0308566579348816 + 0.693427705955790*I sage: log_gamma(-3.1) 0.400311696703985 Symbolic input works (see #10075):: sage: log_gamma(3*x) log_gamma(3*x) sage: log_gamma(3+i) log_gamma(I + 3) sage: log_gamma(3+i+x) log_gamma(x + I + 3) To get evaluation of input for which gamma is negative and the ceiling is even, we must explicitly make the input complex. This is a known issue, see #12521:: sage: log_gamma(-2.1) NaN sage: log_gamma(CC(-2.1)) 1.53171380819509 + 3.14159265358979*I In order to prevent evaluation, use the `hold` argument; to evaluate a held expression, use the `n()` numerical evaluation method:: sage: log_gamma(SR(5),hold=True) log_gamma(5) sage: log_gamma(SR(5),hold=True).n() 3.17805383034795 TESTS:: sage: log_gamma(-2.1+i) -1.90373724496982 - 0.901638463592247*I sage: log_gamma(pari(6)) 4.78749174278205 sage: log_gamma(CC(6)) 4.78749174278205 sage: log_gamma(CC(-2.5)) -0.0562437164976740 + 3.14159265358979*I ``conjugate(log_gamma(x))==log_gamma(conjugate(x))`` unless on the branch cut, which runs along the negative real axis.:: sage: conjugate(log_gamma(x)) conjugate(log_gamma(x)) sage: var('y', domain='positive') y sage: conjugate(log_gamma(y)) log_gamma(y) sage: conjugate(log_gamma(y+I)) conjugate(log_gamma(y + I)) sage: log_gamma(-2) +Infinity sage: conjugate(log_gamma(-2)) +Infinity<|endoftext|>
c4506698b96ff4ffb932b8bd9e0f9c831a07717d255db93e349a1cb3adc65be2
def __init__(self): '\n The incomplete gamma function.\n\n EXAMPLES::\n\n sage: gamma_inc(CDF(0,1), 3)\n 0.00320857499337 + 0.0124061858119*I\n sage: gamma_inc(RDF(1), 3)\n 0.0497870683679\n sage: gamma_inc(3,2)\n gamma(3, 2)\n sage: gamma_inc(x,0)\n gamma(x)\n sage: latex(gamma_inc(3,2))\n \\Gamma\\left(3, 2\\right)\n sage: loads(dumps((gamma_inc(3,2))))\n gamma(3, 2)\n sage: i = ComplexField(30).0; gamma_inc(2, 1 + i)\n 0.70709210 - 0.42035364*I\n sage: gamma_inc(2., 5)\n 0.0404276819945128\n ' BuiltinFunction.__init__(self, 'gamma', nargs=2, latex_name='\\Gamma', conversions={'maxima': 'gamma_incomplete', 'mathematica': 'Gamma', 'maple': 'GAMMA'})
The incomplete gamma function. EXAMPLES:: sage: gamma_inc(CDF(0,1), 3) 0.00320857499337 + 0.0124061858119*I sage: gamma_inc(RDF(1), 3) 0.0497870683679 sage: gamma_inc(3,2) gamma(3, 2) sage: gamma_inc(x,0) gamma(x) sage: latex(gamma_inc(3,2)) \Gamma\left(3, 2\right) sage: loads(dumps((gamma_inc(3,2)))) gamma(3, 2) sage: i = ComplexField(30).0; gamma_inc(2, 1 + i) 0.70709210 - 0.42035364*I sage: gamma_inc(2., 5) 0.0404276819945128
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): '\n The incomplete gamma function.\n\n EXAMPLES::\n\n sage: gamma_inc(CDF(0,1), 3)\n 0.00320857499337 + 0.0124061858119*I\n sage: gamma_inc(RDF(1), 3)\n 0.0497870683679\n sage: gamma_inc(3,2)\n gamma(3, 2)\n sage: gamma_inc(x,0)\n gamma(x)\n sage: latex(gamma_inc(3,2))\n \\Gamma\\left(3, 2\\right)\n sage: loads(dumps((gamma_inc(3,2))))\n gamma(3, 2)\n sage: i = ComplexField(30).0; gamma_inc(2, 1 + i)\n 0.70709210 - 0.42035364*I\n sage: gamma_inc(2., 5)\n 0.0404276819945128\n ' BuiltinFunction.__init__(self, 'gamma', nargs=2, latex_name='\\Gamma', conversions={'maxima': 'gamma_incomplete', 'mathematica': 'Gamma', 'maple': 'GAMMA'})
def __init__(self): '\n The incomplete gamma function.\n\n EXAMPLES::\n\n sage: gamma_inc(CDF(0,1), 3)\n 0.00320857499337 + 0.0124061858119*I\n sage: gamma_inc(RDF(1), 3)\n 0.0497870683679\n sage: gamma_inc(3,2)\n gamma(3, 2)\n sage: gamma_inc(x,0)\n gamma(x)\n sage: latex(gamma_inc(3,2))\n \\Gamma\\left(3, 2\\right)\n sage: loads(dumps((gamma_inc(3,2))))\n gamma(3, 2)\n sage: i = ComplexField(30).0; gamma_inc(2, 1 + i)\n 0.70709210 - 0.42035364*I\n sage: gamma_inc(2., 5)\n 0.0404276819945128\n ' BuiltinFunction.__init__(self, 'gamma', nargs=2, latex_name='\\Gamma', conversions={'maxima': 'gamma_incomplete', 'mathematica': 'Gamma', 'maple': 'GAMMA'})<|docstring|>The incomplete gamma function. EXAMPLES:: sage: gamma_inc(CDF(0,1), 3) 0.00320857499337 + 0.0124061858119*I sage: gamma_inc(RDF(1), 3) 0.0497870683679 sage: gamma_inc(3,2) gamma(3, 2) sage: gamma_inc(x,0) gamma(x) sage: latex(gamma_inc(3,2)) \Gamma\left(3, 2\right) sage: loads(dumps((gamma_inc(3,2)))) gamma(3, 2) sage: i = ComplexField(30).0; gamma_inc(2, 1 + i) 0.70709210 - 0.42035364*I sage: gamma_inc(2., 5) 0.0404276819945128<|endoftext|>
637ab00a86776e5d06f11f7bb7c2ebe364130046981ff42908d34a91a7c659dc
def _eval_(self, x, y): '\n EXAMPLES::\n\n sage: gamma_inc(2.,0)\n 1.00000000000000\n sage: gamma_inc(2,0)\n 1\n sage: gamma_inc(1/2,2)\n -sqrt(pi)*(erf(sqrt(2)) - 1)\n sage: gamma_inc(1/2,1)\n -sqrt(pi)*(erf(1) - 1)\n sage: gamma_inc(1/2,0)\n sqrt(pi)\n sage: gamma_inc(x,0)\n gamma(x)\n sage: gamma_inc(1,2)\n e^(-2)\n sage: gamma_inc(0,2)\n -Ei(-2)\n ' if ((not isinstance(x, Expression)) and (not isinstance(y, Expression)) and (is_inexact(x) or is_inexact(y))): (x, y) = coercion_model.canonical_coercion(x, y) return self._evalf_(x, y, s_parent(x)) if (y == 0): return gamma(x) if (x == 1): return exp((- y)) if (x == 0): return (- Ei((- y))) if (x == (Rational(1) / 2)): return (sqrt(pi) * (1 - erf(sqrt(y)))) return None
EXAMPLES:: sage: gamma_inc(2.,0) 1.00000000000000 sage: gamma_inc(2,0) 1 sage: gamma_inc(1/2,2) -sqrt(pi)*(erf(sqrt(2)) - 1) sage: gamma_inc(1/2,1) -sqrt(pi)*(erf(1) - 1) sage: gamma_inc(1/2,0) sqrt(pi) sage: gamma_inc(x,0) gamma(x) sage: gamma_inc(1,2) e^(-2) sage: gamma_inc(0,2) -Ei(-2)
src/sage/functions/other.py
_eval_
drvinceknight/sage
2
python
def _eval_(self, x, y): '\n EXAMPLES::\n\n sage: gamma_inc(2.,0)\n 1.00000000000000\n sage: gamma_inc(2,0)\n 1\n sage: gamma_inc(1/2,2)\n -sqrt(pi)*(erf(sqrt(2)) - 1)\n sage: gamma_inc(1/2,1)\n -sqrt(pi)*(erf(1) - 1)\n sage: gamma_inc(1/2,0)\n sqrt(pi)\n sage: gamma_inc(x,0)\n gamma(x)\n sage: gamma_inc(1,2)\n e^(-2)\n sage: gamma_inc(0,2)\n -Ei(-2)\n ' if ((not isinstance(x, Expression)) and (not isinstance(y, Expression)) and (is_inexact(x) or is_inexact(y))): (x, y) = coercion_model.canonical_coercion(x, y) return self._evalf_(x, y, s_parent(x)) if (y == 0): return gamma(x) if (x == 1): return exp((- y)) if (x == 0): return (- Ei((- y))) if (x == (Rational(1) / 2)): return (sqrt(pi) * (1 - erf(sqrt(y)))) return None
def _eval_(self, x, y): '\n EXAMPLES::\n\n sage: gamma_inc(2.,0)\n 1.00000000000000\n sage: gamma_inc(2,0)\n 1\n sage: gamma_inc(1/2,2)\n -sqrt(pi)*(erf(sqrt(2)) - 1)\n sage: gamma_inc(1/2,1)\n -sqrt(pi)*(erf(1) - 1)\n sage: gamma_inc(1/2,0)\n sqrt(pi)\n sage: gamma_inc(x,0)\n gamma(x)\n sage: gamma_inc(1,2)\n e^(-2)\n sage: gamma_inc(0,2)\n -Ei(-2)\n ' if ((not isinstance(x, Expression)) and (not isinstance(y, Expression)) and (is_inexact(x) or is_inexact(y))): (x, y) = coercion_model.canonical_coercion(x, y) return self._evalf_(x, y, s_parent(x)) if (y == 0): return gamma(x) if (x == 1): return exp((- y)) if (x == 0): return (- Ei((- y))) if (x == (Rational(1) / 2)): return (sqrt(pi) * (1 - erf(sqrt(y)))) return None<|docstring|>EXAMPLES:: sage: gamma_inc(2.,0) 1.00000000000000 sage: gamma_inc(2,0) 1 sage: gamma_inc(1/2,2) -sqrt(pi)*(erf(sqrt(2)) - 1) sage: gamma_inc(1/2,1) -sqrt(pi)*(erf(1) - 1) sage: gamma_inc(1/2,0) sqrt(pi) sage: gamma_inc(x,0) gamma(x) sage: gamma_inc(1,2) e^(-2) sage: gamma_inc(0,2) -Ei(-2)<|endoftext|>
2f1208cb38e666ac9331613ab124be4e22de1dd51e568af54bfe22f89a3aebf4
def _evalf_(self, x, y, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: gamma_inc(0,2)\n -Ei(-2)\n sage: gamma_inc(0,2.)\n 0.0489005107080611\n sage: gamma_inc(3,2).n()\n 1.35335283236613\n ' try: return x.gamma_inc(y) except AttributeError: if (not is_ComplexNumber(x)): if is_ComplexNumber(y): C = y.parent() else: C = ComplexField() x = C(x) return x.gamma_inc(y)
EXAMPLES:: sage: gamma_inc(0,2) -Ei(-2) sage: gamma_inc(0,2.) 0.0489005107080611 sage: gamma_inc(3,2).n() 1.35335283236613
src/sage/functions/other.py
_evalf_
drvinceknight/sage
2
python
def _evalf_(self, x, y, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: gamma_inc(0,2)\n -Ei(-2)\n sage: gamma_inc(0,2.)\n 0.0489005107080611\n sage: gamma_inc(3,2).n()\n 1.35335283236613\n ' try: return x.gamma_inc(y) except AttributeError: if (not is_ComplexNumber(x)): if is_ComplexNumber(y): C = y.parent() else: C = ComplexField() x = C(x) return x.gamma_inc(y)
def _evalf_(self, x, y, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: gamma_inc(0,2)\n -Ei(-2)\n sage: gamma_inc(0,2.)\n 0.0489005107080611\n sage: gamma_inc(3,2).n()\n 1.35335283236613\n ' try: return x.gamma_inc(y) except AttributeError: if (not is_ComplexNumber(x)): if is_ComplexNumber(y): C = y.parent() else: C = ComplexField() x = C(x) return x.gamma_inc(y)<|docstring|>EXAMPLES:: sage: gamma_inc(0,2) -Ei(-2) sage: gamma_inc(0,2.) 0.0489005107080611 sage: gamma_inc(3,2).n() 1.35335283236613<|endoftext|>
b337bcc39c0db01fbfe610a55478717c5c3124675bcd74dac24b6ae764d6d8f5
def __init__(self): "\n The digamma function, `\\psi(x)`, is the logarithmic derivative of the\n gamma function.\n\n .. math::\n\n \\psi(x) = \\frac{d}{dx} \\log(\\Gamma(x)) = \\frac{\\Gamma'(x)}{\\Gamma(x)}\n\n EXAMPLES::\n\n sage: from sage.functions.other import psi1\n sage: psi1(x)\n psi(x)\n sage: psi1(x).derivative(x)\n psi(1, x)\n\n ::\n\n sage: psi1(3)\n -euler_gamma + 3/2\n\n ::\n\n sage: psi(.5)\n -1.96351002602142\n sage: psi(RealField(100)(.5))\n -1.9635100260214234794409763330\n\n TESTS::\n\n sage: latex(psi1(x))\n \\psi\\left(x\\right)\n sage: loads(dumps(psi1(x)+1))\n psi(x) + 1\n\n sage: t = psi1(x); t\n psi(x)\n sage: t.subs(x=.2)\n -5.28903989659219\n " GinacFunction.__init__(self, 'psi', nargs=1, latex_name='\\psi', conversions=dict(maxima='psi[0]', mathematica='PolyGamma'))
The digamma function, `\psi(x)`, is the logarithmic derivative of the gamma function. .. math:: \psi(x) = \frac{d}{dx} \log(\Gamma(x)) = \frac{\Gamma'(x)}{\Gamma(x)} EXAMPLES:: sage: from sage.functions.other import psi1 sage: psi1(x) psi(x) sage: psi1(x).derivative(x) psi(1, x) :: sage: psi1(3) -euler_gamma + 3/2 :: sage: psi(.5) -1.96351002602142 sage: psi(RealField(100)(.5)) -1.9635100260214234794409763330 TESTS:: sage: latex(psi1(x)) \psi\left(x\right) sage: loads(dumps(psi1(x)+1)) psi(x) + 1 sage: t = psi1(x); t psi(x) sage: t.subs(x=.2) -5.28903989659219
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n The digamma function, `\\psi(x)`, is the logarithmic derivative of the\n gamma function.\n\n .. math::\n\n \\psi(x) = \\frac{d}{dx} \\log(\\Gamma(x)) = \\frac{\\Gamma'(x)}{\\Gamma(x)}\n\n EXAMPLES::\n\n sage: from sage.functions.other import psi1\n sage: psi1(x)\n psi(x)\n sage: psi1(x).derivative(x)\n psi(1, x)\n\n ::\n\n sage: psi1(3)\n -euler_gamma + 3/2\n\n ::\n\n sage: psi(.5)\n -1.96351002602142\n sage: psi(RealField(100)(.5))\n -1.9635100260214234794409763330\n\n TESTS::\n\n sage: latex(psi1(x))\n \\psi\\left(x\\right)\n sage: loads(dumps(psi1(x)+1))\n psi(x) + 1\n\n sage: t = psi1(x); t\n psi(x)\n sage: t.subs(x=.2)\n -5.28903989659219\n " GinacFunction.__init__(self, 'psi', nargs=1, latex_name='\\psi', conversions=dict(maxima='psi[0]', mathematica='PolyGamma'))
def __init__(self): "\n The digamma function, `\\psi(x)`, is the logarithmic derivative of the\n gamma function.\n\n .. math::\n\n \\psi(x) = \\frac{d}{dx} \\log(\\Gamma(x)) = \\frac{\\Gamma'(x)}{\\Gamma(x)}\n\n EXAMPLES::\n\n sage: from sage.functions.other import psi1\n sage: psi1(x)\n psi(x)\n sage: psi1(x).derivative(x)\n psi(1, x)\n\n ::\n\n sage: psi1(3)\n -euler_gamma + 3/2\n\n ::\n\n sage: psi(.5)\n -1.96351002602142\n sage: psi(RealField(100)(.5))\n -1.9635100260214234794409763330\n\n TESTS::\n\n sage: latex(psi1(x))\n \\psi\\left(x\\right)\n sage: loads(dumps(psi1(x)+1))\n psi(x) + 1\n\n sage: t = psi1(x); t\n psi(x)\n sage: t.subs(x=.2)\n -5.28903989659219\n " GinacFunction.__init__(self, 'psi', nargs=1, latex_name='\\psi', conversions=dict(maxima='psi[0]', mathematica='PolyGamma'))<|docstring|>The digamma function, `\psi(x)`, is the logarithmic derivative of the gamma function. .. math:: \psi(x) = \frac{d}{dx} \log(\Gamma(x)) = \frac{\Gamma'(x)}{\Gamma(x)} EXAMPLES:: sage: from sage.functions.other import psi1 sage: psi1(x) psi(x) sage: psi1(x).derivative(x) psi(1, x) :: sage: psi1(3) -euler_gamma + 3/2 :: sage: psi(.5) -1.96351002602142 sage: psi(RealField(100)(.5)) -1.9635100260214234794409763330 TESTS:: sage: latex(psi1(x)) \psi\left(x\right) sage: loads(dumps(psi1(x)+1)) psi(x) + 1 sage: t = psi1(x); t psi(x) sage: t.subs(x=.2) -5.28903989659219<|endoftext|>
e31417cb0ecc57a6cabd11a765ebf0d2b76f7a3afa7d7d6286bf892ae6d12a0c
def __init__(self): "\n Derivatives of the digamma function `\\psi(x)`. T\n\n EXAMPLES::\n\n sage: from sage.functions.other import psi2\n sage: psi2(2, x)\n psi(2, x)\n sage: psi2(2, x).derivative(x)\n psi(3, x)\n sage: n = var('n')\n sage: psi2(n, x).derivative(x)\n psi(n + 1, x)\n\n ::\n\n sage: psi2(0, x)\n psi(x)\n sage: psi2(-1, x)\n log(gamma(x))\n sage: psi2(3, 1)\n 1/15*pi^4\n\n ::\n\n sage: psi2(2, .5).n()\n -16.8287966442343\n sage: psi2(2, .5).n(100)\n -16.828796644234319995596334261\n\n Tests::\n\n sage: psi2(n, x).derivative(n)\n Traceback (most recent call last):\n ...\n RuntimeError: cannot diff psi(n,x) with respect to n\n\n sage: latex(psi2(2,x))\n \\psi\\left(2, x\\right)\n sage: loads(dumps(psi2(2,x)+1))\n psi(2, x) + 1\n " GinacFunction.__init__(self, 'psi', nargs=2, latex_name='\\psi', conversions=dict(mathematica='PolyGamma'))
Derivatives of the digamma function `\psi(x)`. T EXAMPLES:: sage: from sage.functions.other import psi2 sage: psi2(2, x) psi(2, x) sage: psi2(2, x).derivative(x) psi(3, x) sage: n = var('n') sage: psi2(n, x).derivative(x) psi(n + 1, x) :: sage: psi2(0, x) psi(x) sage: psi2(-1, x) log(gamma(x)) sage: psi2(3, 1) 1/15*pi^4 :: sage: psi2(2, .5).n() -16.8287966442343 sage: psi2(2, .5).n(100) -16.828796644234319995596334261 Tests:: sage: psi2(n, x).derivative(n) Traceback (most recent call last): ... RuntimeError: cannot diff psi(n,x) with respect to n sage: latex(psi2(2,x)) \psi\left(2, x\right) sage: loads(dumps(psi2(2,x)+1)) psi(2, x) + 1
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n Derivatives of the digamma function `\\psi(x)`. T\n\n EXAMPLES::\n\n sage: from sage.functions.other import psi2\n sage: psi2(2, x)\n psi(2, x)\n sage: psi2(2, x).derivative(x)\n psi(3, x)\n sage: n = var('n')\n sage: psi2(n, x).derivative(x)\n psi(n + 1, x)\n\n ::\n\n sage: psi2(0, x)\n psi(x)\n sage: psi2(-1, x)\n log(gamma(x))\n sage: psi2(3, 1)\n 1/15*pi^4\n\n ::\n\n sage: psi2(2, .5).n()\n -16.8287966442343\n sage: psi2(2, .5).n(100)\n -16.828796644234319995596334261\n\n Tests::\n\n sage: psi2(n, x).derivative(n)\n Traceback (most recent call last):\n ...\n RuntimeError: cannot diff psi(n,x) with respect to n\n\n sage: latex(psi2(2,x))\n \\psi\\left(2, x\\right)\n sage: loads(dumps(psi2(2,x)+1))\n psi(2, x) + 1\n " GinacFunction.__init__(self, 'psi', nargs=2, latex_name='\\psi', conversions=dict(mathematica='PolyGamma'))
def __init__(self): "\n Derivatives of the digamma function `\\psi(x)`. T\n\n EXAMPLES::\n\n sage: from sage.functions.other import psi2\n sage: psi2(2, x)\n psi(2, x)\n sage: psi2(2, x).derivative(x)\n psi(3, x)\n sage: n = var('n')\n sage: psi2(n, x).derivative(x)\n psi(n + 1, x)\n\n ::\n\n sage: psi2(0, x)\n psi(x)\n sage: psi2(-1, x)\n log(gamma(x))\n sage: psi2(3, 1)\n 1/15*pi^4\n\n ::\n\n sage: psi2(2, .5).n()\n -16.8287966442343\n sage: psi2(2, .5).n(100)\n -16.828796644234319995596334261\n\n Tests::\n\n sage: psi2(n, x).derivative(n)\n Traceback (most recent call last):\n ...\n RuntimeError: cannot diff psi(n,x) with respect to n\n\n sage: latex(psi2(2,x))\n \\psi\\left(2, x\\right)\n sage: loads(dumps(psi2(2,x)+1))\n psi(2, x) + 1\n " GinacFunction.__init__(self, 'psi', nargs=2, latex_name='\\psi', conversions=dict(mathematica='PolyGamma'))<|docstring|>Derivatives of the digamma function `\psi(x)`. T EXAMPLES:: sage: from sage.functions.other import psi2 sage: psi2(2, x) psi(2, x) sage: psi2(2, x).derivative(x) psi(3, x) sage: n = var('n') sage: psi2(n, x).derivative(x) psi(n + 1, x) :: sage: psi2(0, x) psi(x) sage: psi2(-1, x) log(gamma(x)) sage: psi2(3, 1) 1/15*pi^4 :: sage: psi2(2, .5).n() -16.8287966442343 sage: psi2(2, .5).n(100) -16.828796644234319995596334261 Tests:: sage: psi2(n, x).derivative(n) Traceback (most recent call last): ... RuntimeError: cannot diff psi(n,x) with respect to n sage: latex(psi2(2,x)) \psi\left(2, x\right) sage: loads(dumps(psi2(2,x)+1)) psi(2, x) + 1<|endoftext|>
5f723f75a04e460531ea0cf2d431a8ceecfee28eeb2f0c1a0443c3952e92f80c
def _maxima_init_evaled_(self, *args): '\n EXAMPLES:\n\n These are indirect doctests for this function.::\n\n sage: from sage.functions.other import psi2\n sage: psi2(2, x)._maxima_()\n psi[2](_SAGE_VAR_x)\n sage: psi2(4, x)._maxima_()\n psi[4](_SAGE_VAR_x)\n ' args_maxima = [] for a in args: if isinstance(a, str): args_maxima.append(a) elif hasattr(a, '_maxima_init_'): args_maxima.append(a._maxima_init_()) else: args_maxima.append(str(a)) (n, x) = args_maxima return ('psi[%s](%s)' % (n, x))
EXAMPLES: These are indirect doctests for this function.:: sage: from sage.functions.other import psi2 sage: psi2(2, x)._maxima_() psi[2](_SAGE_VAR_x) sage: psi2(4, x)._maxima_() psi[4](_SAGE_VAR_x)
src/sage/functions/other.py
_maxima_init_evaled_
drvinceknight/sage
2
python
def _maxima_init_evaled_(self, *args): '\n EXAMPLES:\n\n These are indirect doctests for this function.::\n\n sage: from sage.functions.other import psi2\n sage: psi2(2, x)._maxima_()\n psi[2](_SAGE_VAR_x)\n sage: psi2(4, x)._maxima_()\n psi[4](_SAGE_VAR_x)\n ' args_maxima = [] for a in args: if isinstance(a, str): args_maxima.append(a) elif hasattr(a, '_maxima_init_'): args_maxima.append(a._maxima_init_()) else: args_maxima.append(str(a)) (n, x) = args_maxima return ('psi[%s](%s)' % (n, x))
def _maxima_init_evaled_(self, *args): '\n EXAMPLES:\n\n These are indirect doctests for this function.::\n\n sage: from sage.functions.other import psi2\n sage: psi2(2, x)._maxima_()\n psi[2](_SAGE_VAR_x)\n sage: psi2(4, x)._maxima_()\n psi[4](_SAGE_VAR_x)\n ' args_maxima = [] for a in args: if isinstance(a, str): args_maxima.append(a) elif hasattr(a, '_maxima_init_'): args_maxima.append(a._maxima_init_()) else: args_maxima.append(str(a)) (n, x) = args_maxima return ('psi[%s](%s)' % (n, x))<|docstring|>EXAMPLES: These are indirect doctests for this function.:: sage: from sage.functions.other import psi2 sage: psi2(2, x)._maxima_() psi[2](_SAGE_VAR_x) sage: psi2(4, x)._maxima_() psi[4](_SAGE_VAR_x)<|endoftext|>
934f665fd4a6f5e560945d12228f2685d0ec0e2b54fa6748549863d40fef2712
def __init__(self): "\n Returns the factorial of `n`.\n\n INPUT:\n\n - ``n`` - any complex argument (except negative\n integers) or any symbolic expression\n\n\n OUTPUT: an integer or symbolic expression\n\n EXAMPLES::\n\n sage: x = var('x')\n sage: factorial(0)\n 1\n sage: factorial(4)\n 24\n sage: factorial(10)\n 3628800\n sage: factorial(6) == 6*5*4*3*2\n True\n sage: f = factorial(x + factorial(x)); f\n factorial(x + factorial(x))\n sage: f(x=3)\n 362880\n sage: factorial(x)^2\n factorial(x)^2\n\n To prevent automatic evaluation use the ``hold`` argument::\n\n sage: factorial(5,hold=True)\n factorial(5)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: factorial(5,hold=True).simplify()\n 120\n\n We can also give input other than nonnegative integers. For\n other nonnegative numbers, the :func:`gamma` function is used::\n\n sage: factorial(1/2)\n 1/2*sqrt(pi)\n sage: factorial(3/4)\n gamma(7/4)\n sage: factorial(2.3)\n 2.68343738195577\n\n But negative input always fails::\n\n sage: factorial(-32)\n Traceback (most recent call last):\n ...\n ValueError: factorial -- self = (-32) must be nonnegative\n\n TESTS:\n\n We verify that we can convert this function to Maxima and\n bring it back into Sage.::\n\n sage: z = var('z')\n sage: factorial._maxima_init_()\n 'factorial'\n sage: maxima(factorial(z))\n factorial(_SAGE_VAR_z)\n sage: _.sage()\n factorial(z)\n sage: k = var('k')\n sage: factorial(k)\n factorial(k)\n\n sage: factorial(3.14)\n 7.173269190187...\n\n Test latex typesetting::\n\n sage: latex(factorial(x))\n x!\n sage: latex(factorial(2*x))\n \\left(2 \\, x\\right)!\n sage: latex(factorial(sin(x)))\n \\sin\\left(x\\right)!\n sage: latex(factorial(sqrt(x+1)))\n \\left(\\sqrt{x + 1}\\right)!\n sage: latex(factorial(sqrt(x)))\n \\sqrt{x}!\n sage: latex(factorial(x^(2/3)))\n \\left(x^{\\frac{2}{3}}\\right)!\n\n sage: latex(factorial)\n {\\rm factorial}\n\n Check that #11539 is fixed::\n\n sage: (factorial(x) == 0).simplify()\n factorial(x) == 0\n sage: maxima(factorial(x) == 0).sage()\n factorial(x) == 0\n sage: y = var('y')\n sage: (factorial(x) == y).solve(x)\n [factorial(x) == y]\n\n Test pickling::\n\n sage: loads(dumps(factorial))\n factorial\n " GinacFunction.__init__(self, 'factorial', latex_name='{\\rm factorial}', conversions=dict(maxima='factorial', mathematica='Factorial'))
Returns the factorial of `n`. INPUT: - ``n`` - any complex argument (except negative integers) or any symbolic expression OUTPUT: an integer or symbolic expression EXAMPLES:: sage: x = var('x') sage: factorial(0) 1 sage: factorial(4) 24 sage: factorial(10) 3628800 sage: factorial(6) == 6*5*4*3*2 True sage: f = factorial(x + factorial(x)); f factorial(x + factorial(x)) sage: f(x=3) 362880 sage: factorial(x)^2 factorial(x)^2 To prevent automatic evaluation use the ``hold`` argument:: sage: factorial(5,hold=True) factorial(5) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: factorial(5,hold=True).simplify() 120 We can also give input other than nonnegative integers. For other nonnegative numbers, the :func:`gamma` function is used:: sage: factorial(1/2) 1/2*sqrt(pi) sage: factorial(3/4) gamma(7/4) sage: factorial(2.3) 2.68343738195577 But negative input always fails:: sage: factorial(-32) Traceback (most recent call last): ... ValueError: factorial -- self = (-32) must be nonnegative TESTS: We verify that we can convert this function to Maxima and bring it back into Sage.:: sage: z = var('z') sage: factorial._maxima_init_() 'factorial' sage: maxima(factorial(z)) factorial(_SAGE_VAR_z) sage: _.sage() factorial(z) sage: k = var('k') sage: factorial(k) factorial(k) sage: factorial(3.14) 7.173269190187... Test latex typesetting:: sage: latex(factorial(x)) x! sage: latex(factorial(2*x)) \left(2 \, x\right)! sage: latex(factorial(sin(x))) \sin\left(x\right)! sage: latex(factorial(sqrt(x+1))) \left(\sqrt{x + 1}\right)! sage: latex(factorial(sqrt(x))) \sqrt{x}! sage: latex(factorial(x^(2/3))) \left(x^{\frac{2}{3}}\right)! sage: latex(factorial) {\rm factorial} Check that #11539 is fixed:: sage: (factorial(x) == 0).simplify() factorial(x) == 0 sage: maxima(factorial(x) == 0).sage() factorial(x) == 0 sage: y = var('y') sage: (factorial(x) == y).solve(x) [factorial(x) == y] Test pickling:: sage: loads(dumps(factorial)) factorial
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n Returns the factorial of `n`.\n\n INPUT:\n\n - ``n`` - any complex argument (except negative\n integers) or any symbolic expression\n\n\n OUTPUT: an integer or symbolic expression\n\n EXAMPLES::\n\n sage: x = var('x')\n sage: factorial(0)\n 1\n sage: factorial(4)\n 24\n sage: factorial(10)\n 3628800\n sage: factorial(6) == 6*5*4*3*2\n True\n sage: f = factorial(x + factorial(x)); f\n factorial(x + factorial(x))\n sage: f(x=3)\n 362880\n sage: factorial(x)^2\n factorial(x)^2\n\n To prevent automatic evaluation use the ``hold`` argument::\n\n sage: factorial(5,hold=True)\n factorial(5)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: factorial(5,hold=True).simplify()\n 120\n\n We can also give input other than nonnegative integers. For\n other nonnegative numbers, the :func:`gamma` function is used::\n\n sage: factorial(1/2)\n 1/2*sqrt(pi)\n sage: factorial(3/4)\n gamma(7/4)\n sage: factorial(2.3)\n 2.68343738195577\n\n But negative input always fails::\n\n sage: factorial(-32)\n Traceback (most recent call last):\n ...\n ValueError: factorial -- self = (-32) must be nonnegative\n\n TESTS:\n\n We verify that we can convert this function to Maxima and\n bring it back into Sage.::\n\n sage: z = var('z')\n sage: factorial._maxima_init_()\n 'factorial'\n sage: maxima(factorial(z))\n factorial(_SAGE_VAR_z)\n sage: _.sage()\n factorial(z)\n sage: k = var('k')\n sage: factorial(k)\n factorial(k)\n\n sage: factorial(3.14)\n 7.173269190187...\n\n Test latex typesetting::\n\n sage: latex(factorial(x))\n x!\n sage: latex(factorial(2*x))\n \\left(2 \\, x\\right)!\n sage: latex(factorial(sin(x)))\n \\sin\\left(x\\right)!\n sage: latex(factorial(sqrt(x+1)))\n \\left(\\sqrt{x + 1}\\right)!\n sage: latex(factorial(sqrt(x)))\n \\sqrt{x}!\n sage: latex(factorial(x^(2/3)))\n \\left(x^{\\frac{2}{3}}\\right)!\n\n sage: latex(factorial)\n {\\rm factorial}\n\n Check that #11539 is fixed::\n\n sage: (factorial(x) == 0).simplify()\n factorial(x) == 0\n sage: maxima(factorial(x) == 0).sage()\n factorial(x) == 0\n sage: y = var('y')\n sage: (factorial(x) == y).solve(x)\n [factorial(x) == y]\n\n Test pickling::\n\n sage: loads(dumps(factorial))\n factorial\n " GinacFunction.__init__(self, 'factorial', latex_name='{\\rm factorial}', conversions=dict(maxima='factorial', mathematica='Factorial'))
def __init__(self): "\n Returns the factorial of `n`.\n\n INPUT:\n\n - ``n`` - any complex argument (except negative\n integers) or any symbolic expression\n\n\n OUTPUT: an integer or symbolic expression\n\n EXAMPLES::\n\n sage: x = var('x')\n sage: factorial(0)\n 1\n sage: factorial(4)\n 24\n sage: factorial(10)\n 3628800\n sage: factorial(6) == 6*5*4*3*2\n True\n sage: f = factorial(x + factorial(x)); f\n factorial(x + factorial(x))\n sage: f(x=3)\n 362880\n sage: factorial(x)^2\n factorial(x)^2\n\n To prevent automatic evaluation use the ``hold`` argument::\n\n sage: factorial(5,hold=True)\n factorial(5)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: factorial(5,hold=True).simplify()\n 120\n\n We can also give input other than nonnegative integers. For\n other nonnegative numbers, the :func:`gamma` function is used::\n\n sage: factorial(1/2)\n 1/2*sqrt(pi)\n sage: factorial(3/4)\n gamma(7/4)\n sage: factorial(2.3)\n 2.68343738195577\n\n But negative input always fails::\n\n sage: factorial(-32)\n Traceback (most recent call last):\n ...\n ValueError: factorial -- self = (-32) must be nonnegative\n\n TESTS:\n\n We verify that we can convert this function to Maxima and\n bring it back into Sage.::\n\n sage: z = var('z')\n sage: factorial._maxima_init_()\n 'factorial'\n sage: maxima(factorial(z))\n factorial(_SAGE_VAR_z)\n sage: _.sage()\n factorial(z)\n sage: k = var('k')\n sage: factorial(k)\n factorial(k)\n\n sage: factorial(3.14)\n 7.173269190187...\n\n Test latex typesetting::\n\n sage: latex(factorial(x))\n x!\n sage: latex(factorial(2*x))\n \\left(2 \\, x\\right)!\n sage: latex(factorial(sin(x)))\n \\sin\\left(x\\right)!\n sage: latex(factorial(sqrt(x+1)))\n \\left(\\sqrt{x + 1}\\right)!\n sage: latex(factorial(sqrt(x)))\n \\sqrt{x}!\n sage: latex(factorial(x^(2/3)))\n \\left(x^{\\frac{2}{3}}\\right)!\n\n sage: latex(factorial)\n {\\rm factorial}\n\n Check that #11539 is fixed::\n\n sage: (factorial(x) == 0).simplify()\n factorial(x) == 0\n sage: maxima(factorial(x) == 0).sage()\n factorial(x) == 0\n sage: y = var('y')\n sage: (factorial(x) == y).solve(x)\n [factorial(x) == y]\n\n Test pickling::\n\n sage: loads(dumps(factorial))\n factorial\n " GinacFunction.__init__(self, 'factorial', latex_name='{\\rm factorial}', conversions=dict(maxima='factorial', mathematica='Factorial'))<|docstring|>Returns the factorial of `n`. INPUT: - ``n`` - any complex argument (except negative integers) or any symbolic expression OUTPUT: an integer or symbolic expression EXAMPLES:: sage: x = var('x') sage: factorial(0) 1 sage: factorial(4) 24 sage: factorial(10) 3628800 sage: factorial(6) == 6*5*4*3*2 True sage: f = factorial(x + factorial(x)); f factorial(x + factorial(x)) sage: f(x=3) 362880 sage: factorial(x)^2 factorial(x)^2 To prevent automatic evaluation use the ``hold`` argument:: sage: factorial(5,hold=True) factorial(5) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: factorial(5,hold=True).simplify() 120 We can also give input other than nonnegative integers. For other nonnegative numbers, the :func:`gamma` function is used:: sage: factorial(1/2) 1/2*sqrt(pi) sage: factorial(3/4) gamma(7/4) sage: factorial(2.3) 2.68343738195577 But negative input always fails:: sage: factorial(-32) Traceback (most recent call last): ... ValueError: factorial -- self = (-32) must be nonnegative TESTS: We verify that we can convert this function to Maxima and bring it back into Sage.:: sage: z = var('z') sage: factorial._maxima_init_() 'factorial' sage: maxima(factorial(z)) factorial(_SAGE_VAR_z) sage: _.sage() factorial(z) sage: k = var('k') sage: factorial(k) factorial(k) sage: factorial(3.14) 7.173269190187... Test latex typesetting:: sage: latex(factorial(x)) x! sage: latex(factorial(2*x)) \left(2 \, x\right)! sage: latex(factorial(sin(x))) \sin\left(x\right)! sage: latex(factorial(sqrt(x+1))) \left(\sqrt{x + 1}\right)! sage: latex(factorial(sqrt(x))) \sqrt{x}! sage: latex(factorial(x^(2/3))) \left(x^{\frac{2}{3}}\right)! sage: latex(factorial) {\rm factorial} Check that #11539 is fixed:: sage: (factorial(x) == 0).simplify() factorial(x) == 0 sage: maxima(factorial(x) == 0).sage() factorial(x) == 0 sage: y = var('y') sage: (factorial(x) == y).solve(x) [factorial(x) == y] Test pickling:: sage: loads(dumps(factorial)) factorial<|endoftext|>
85db1b7ab7f5acbe40b2ad5d424f3313495bbb52b76447a8957048260ce266d5
def _eval_(self, x): "\n Evaluate the factorial function.\n\n Note that this method overrides the eval method defined in GiNaC\n which calls numeric evaluation on all numeric input. We preserve\n exact results if the input is a rational number.\n\n EXAMPLES::\n\n sage: k = var('k')\n sage: k.factorial()\n factorial(k)\n sage: SR(1/2).factorial()\n 1/2*sqrt(pi)\n sage: SR(3/4).factorial()\n gamma(7/4)\n sage: SR(5).factorial()\n 120\n sage: SR(3245908723049857203948572398475r).factorial()\n factorial(3245908723049857203948572398475L)\n sage: SR(3245908723049857203948572398475).factorial()\n factorial(3245908723049857203948572398475)\n " if isinstance(x, Rational): return gamma((x + 1)) elif (isinstance(x, (Integer, int)) or ((not isinstance(x, Expression)) and is_inexact(x))): return py_factorial_py(x) return None
Evaluate the factorial function. Note that this method overrides the eval method defined in GiNaC which calls numeric evaluation on all numeric input. We preserve exact results if the input is a rational number. EXAMPLES:: sage: k = var('k') sage: k.factorial() factorial(k) sage: SR(1/2).factorial() 1/2*sqrt(pi) sage: SR(3/4).factorial() gamma(7/4) sage: SR(5).factorial() 120 sage: SR(3245908723049857203948572398475r).factorial() factorial(3245908723049857203948572398475L) sage: SR(3245908723049857203948572398475).factorial() factorial(3245908723049857203948572398475)
src/sage/functions/other.py
_eval_
drvinceknight/sage
2
python
def _eval_(self, x): "\n Evaluate the factorial function.\n\n Note that this method overrides the eval method defined in GiNaC\n which calls numeric evaluation on all numeric input. We preserve\n exact results if the input is a rational number.\n\n EXAMPLES::\n\n sage: k = var('k')\n sage: k.factorial()\n factorial(k)\n sage: SR(1/2).factorial()\n 1/2*sqrt(pi)\n sage: SR(3/4).factorial()\n gamma(7/4)\n sage: SR(5).factorial()\n 120\n sage: SR(3245908723049857203948572398475r).factorial()\n factorial(3245908723049857203948572398475L)\n sage: SR(3245908723049857203948572398475).factorial()\n factorial(3245908723049857203948572398475)\n " if isinstance(x, Rational): return gamma((x + 1)) elif (isinstance(x, (Integer, int)) or ((not isinstance(x, Expression)) and is_inexact(x))): return py_factorial_py(x) return None
def _eval_(self, x): "\n Evaluate the factorial function.\n\n Note that this method overrides the eval method defined in GiNaC\n which calls numeric evaluation on all numeric input. We preserve\n exact results if the input is a rational number.\n\n EXAMPLES::\n\n sage: k = var('k')\n sage: k.factorial()\n factorial(k)\n sage: SR(1/2).factorial()\n 1/2*sqrt(pi)\n sage: SR(3/4).factorial()\n gamma(7/4)\n sage: SR(5).factorial()\n 120\n sage: SR(3245908723049857203948572398475r).factorial()\n factorial(3245908723049857203948572398475L)\n sage: SR(3245908723049857203948572398475).factorial()\n factorial(3245908723049857203948572398475)\n " if isinstance(x, Rational): return gamma((x + 1)) elif (isinstance(x, (Integer, int)) or ((not isinstance(x, Expression)) and is_inexact(x))): return py_factorial_py(x) return None<|docstring|>Evaluate the factorial function. Note that this method overrides the eval method defined in GiNaC which calls numeric evaluation on all numeric input. We preserve exact results if the input is a rational number. EXAMPLES:: sage: k = var('k') sage: k.factorial() factorial(k) sage: SR(1/2).factorial() 1/2*sqrt(pi) sage: SR(3/4).factorial() gamma(7/4) sage: SR(5).factorial() 120 sage: SR(3245908723049857203948572398475r).factorial() factorial(3245908723049857203948572398475L) sage: SR(3245908723049857203948572398475).factorial() factorial(3245908723049857203948572398475)<|endoftext|>
bb5fe163b43d178d32df53af3e31fa668f839cf545e2fc9010a993a763a1d6d3
def __init__(self): "\n Return the binomial coefficient\n\n .. math::\n\n \\binom{x}{m} = x (x-1) \\cdots (x-m+1) / m!\n\n\n which is defined for `m \\in \\ZZ` and any\n `x`. We extend this definition to include cases when\n `x-m` is an integer but `m` is not by\n\n .. math::\n\n \\binom{x}{m}= \\binom{x}{x-m}\n\n If `m < 0`, return `0`.\n\n INPUT:\n\n - ``x``, ``m`` - numbers or symbolic expressions. Either ``m``\n or ``x-m`` must be an integer, else the output is symbolic.\n\n OUTPUT: number or symbolic expression (if input is symbolic)\n\n EXAMPLES::\n\n sage: binomial(5,2)\n 10\n sage: binomial(2,0)\n 1\n sage: binomial(1/2, 0)\n 1\n sage: binomial(3,-1)\n 0\n sage: binomial(20,10)\n 184756\n sage: binomial(-2, 5)\n -6\n sage: binomial(RealField()('2.5'), 2)\n 1.87500000000000\n sage: n=var('n'); binomial(n,2)\n 1/2*(n - 1)*n\n sage: n=var('n'); binomial(n,n)\n 1\n sage: n=var('n'); binomial(n,n-1)\n n\n sage: binomial(2^100, 2^100)\n 1\n\n ::\n\n sage: k, i = var('k,i')\n sage: binomial(k,i)\n binomial(k, i)\n\n We can use a ``hold`` parameter to prevent automatic evaluation::\n\n sage: SR(5).binomial(3, hold=True)\n binomial(5, 3)\n sage: SR(5).binomial(3, hold=True).simplify()\n 10\n\n TESTS: We verify that we can convert this function to Maxima and\n bring it back into Sage.\n\n ::\n\n sage: n,k = var('n,k')\n sage: maxima(binomial(n,k))\n binomial(_SAGE_VAR_n,_SAGE_VAR_k)\n sage: _.sage()\n binomial(n, k)\n sage: binomial._maxima_init_()\n 'binomial'\n\n Test pickling::\n\n sage: loads(dumps(binomial(n,k)))\n binomial(n, k)\n " GinacFunction.__init__(self, 'binomial', nargs=2, conversions=dict(maxima='binomial', mathematica='Binomial'))
Return the binomial coefficient .. math:: \binom{x}{m} = x (x-1) \cdots (x-m+1) / m! which is defined for `m \in \ZZ` and any `x`. We extend this definition to include cases when `x-m` is an integer but `m` is not by .. math:: \binom{x}{m}= \binom{x}{x-m} If `m < 0`, return `0`. INPUT: - ``x``, ``m`` - numbers or symbolic expressions. Either ``m`` or ``x-m`` must be an integer, else the output is symbolic. OUTPUT: number or symbolic expression (if input is symbolic) EXAMPLES:: sage: binomial(5,2) 10 sage: binomial(2,0) 1 sage: binomial(1/2, 0) 1 sage: binomial(3,-1) 0 sage: binomial(20,10) 184756 sage: binomial(-2, 5) -6 sage: binomial(RealField()('2.5'), 2) 1.87500000000000 sage: n=var('n'); binomial(n,2) 1/2*(n - 1)*n sage: n=var('n'); binomial(n,n) 1 sage: n=var('n'); binomial(n,n-1) n sage: binomial(2^100, 2^100) 1 :: sage: k, i = var('k,i') sage: binomial(k,i) binomial(k, i) We can use a ``hold`` parameter to prevent automatic evaluation:: sage: SR(5).binomial(3, hold=True) binomial(5, 3) sage: SR(5).binomial(3, hold=True).simplify() 10 TESTS: We verify that we can convert this function to Maxima and bring it back into Sage. :: sage: n,k = var('n,k') sage: maxima(binomial(n,k)) binomial(_SAGE_VAR_n,_SAGE_VAR_k) sage: _.sage() binomial(n, k) sage: binomial._maxima_init_() 'binomial' Test pickling:: sage: loads(dumps(binomial(n,k))) binomial(n, k)
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n Return the binomial coefficient\n\n .. math::\n\n \\binom{x}{m} = x (x-1) \\cdots (x-m+1) / m!\n\n\n which is defined for `m \\in \\ZZ` and any\n `x`. We extend this definition to include cases when\n `x-m` is an integer but `m` is not by\n\n .. math::\n\n \\binom{x}{m}= \\binom{x}{x-m}\n\n If `m < 0`, return `0`.\n\n INPUT:\n\n - ``x``, ``m`` - numbers or symbolic expressions. Either ``m``\n or ``x-m`` must be an integer, else the output is symbolic.\n\n OUTPUT: number or symbolic expression (if input is symbolic)\n\n EXAMPLES::\n\n sage: binomial(5,2)\n 10\n sage: binomial(2,0)\n 1\n sage: binomial(1/2, 0)\n 1\n sage: binomial(3,-1)\n 0\n sage: binomial(20,10)\n 184756\n sage: binomial(-2, 5)\n -6\n sage: binomial(RealField()('2.5'), 2)\n 1.87500000000000\n sage: n=var('n'); binomial(n,2)\n 1/2*(n - 1)*n\n sage: n=var('n'); binomial(n,n)\n 1\n sage: n=var('n'); binomial(n,n-1)\n n\n sage: binomial(2^100, 2^100)\n 1\n\n ::\n\n sage: k, i = var('k,i')\n sage: binomial(k,i)\n binomial(k, i)\n\n We can use a ``hold`` parameter to prevent automatic evaluation::\n\n sage: SR(5).binomial(3, hold=True)\n binomial(5, 3)\n sage: SR(5).binomial(3, hold=True).simplify()\n 10\n\n TESTS: We verify that we can convert this function to Maxima and\n bring it back into Sage.\n\n ::\n\n sage: n,k = var('n,k')\n sage: maxima(binomial(n,k))\n binomial(_SAGE_VAR_n,_SAGE_VAR_k)\n sage: _.sage()\n binomial(n, k)\n sage: binomial._maxima_init_()\n 'binomial'\n\n Test pickling::\n\n sage: loads(dumps(binomial(n,k)))\n binomial(n, k)\n " GinacFunction.__init__(self, 'binomial', nargs=2, conversions=dict(maxima='binomial', mathematica='Binomial'))
def __init__(self): "\n Return the binomial coefficient\n\n .. math::\n\n \\binom{x}{m} = x (x-1) \\cdots (x-m+1) / m!\n\n\n which is defined for `m \\in \\ZZ` and any\n `x`. We extend this definition to include cases when\n `x-m` is an integer but `m` is not by\n\n .. math::\n\n \\binom{x}{m}= \\binom{x}{x-m}\n\n If `m < 0`, return `0`.\n\n INPUT:\n\n - ``x``, ``m`` - numbers or symbolic expressions. Either ``m``\n or ``x-m`` must be an integer, else the output is symbolic.\n\n OUTPUT: number or symbolic expression (if input is symbolic)\n\n EXAMPLES::\n\n sage: binomial(5,2)\n 10\n sage: binomial(2,0)\n 1\n sage: binomial(1/2, 0)\n 1\n sage: binomial(3,-1)\n 0\n sage: binomial(20,10)\n 184756\n sage: binomial(-2, 5)\n -6\n sage: binomial(RealField()('2.5'), 2)\n 1.87500000000000\n sage: n=var('n'); binomial(n,2)\n 1/2*(n - 1)*n\n sage: n=var('n'); binomial(n,n)\n 1\n sage: n=var('n'); binomial(n,n-1)\n n\n sage: binomial(2^100, 2^100)\n 1\n\n ::\n\n sage: k, i = var('k,i')\n sage: binomial(k,i)\n binomial(k, i)\n\n We can use a ``hold`` parameter to prevent automatic evaluation::\n\n sage: SR(5).binomial(3, hold=True)\n binomial(5, 3)\n sage: SR(5).binomial(3, hold=True).simplify()\n 10\n\n TESTS: We verify that we can convert this function to Maxima and\n bring it back into Sage.\n\n ::\n\n sage: n,k = var('n,k')\n sage: maxima(binomial(n,k))\n binomial(_SAGE_VAR_n,_SAGE_VAR_k)\n sage: _.sage()\n binomial(n, k)\n sage: binomial._maxima_init_()\n 'binomial'\n\n Test pickling::\n\n sage: loads(dumps(binomial(n,k)))\n binomial(n, k)\n " GinacFunction.__init__(self, 'binomial', nargs=2, conversions=dict(maxima='binomial', mathematica='Binomial'))<|docstring|>Return the binomial coefficient .. math:: \binom{x}{m} = x (x-1) \cdots (x-m+1) / m! which is defined for `m \in \ZZ` and any `x`. We extend this definition to include cases when `x-m` is an integer but `m` is not by .. math:: \binom{x}{m}= \binom{x}{x-m} If `m < 0`, return `0`. INPUT: - ``x``, ``m`` - numbers or symbolic expressions. Either ``m`` or ``x-m`` must be an integer, else the output is symbolic. OUTPUT: number or symbolic expression (if input is symbolic) EXAMPLES:: sage: binomial(5,2) 10 sage: binomial(2,0) 1 sage: binomial(1/2, 0) 1 sage: binomial(3,-1) 0 sage: binomial(20,10) 184756 sage: binomial(-2, 5) -6 sage: binomial(RealField()('2.5'), 2) 1.87500000000000 sage: n=var('n'); binomial(n,2) 1/2*(n - 1)*n sage: n=var('n'); binomial(n,n) 1 sage: n=var('n'); binomial(n,n-1) n sage: binomial(2^100, 2^100) 1 :: sage: k, i = var('k,i') sage: binomial(k,i) binomial(k, i) We can use a ``hold`` parameter to prevent automatic evaluation:: sage: SR(5).binomial(3, hold=True) binomial(5, 3) sage: SR(5).binomial(3, hold=True).simplify() 10 TESTS: We verify that we can convert this function to Maxima and bring it back into Sage. :: sage: n,k = var('n,k') sage: maxima(binomial(n,k)) binomial(_SAGE_VAR_n,_SAGE_VAR_k) sage: _.sage() binomial(n, k) sage: binomial._maxima_init_() 'binomial' Test pickling:: sage: loads(dumps(binomial(n,k))) binomial(n, k)<|endoftext|>
7be0c68ed8156a2d355c92330c68700465953e77f6c9994e0d8c8c1d7d3f6664
def _binomial_sym(self, n, k): '\n Expand the binomial formula symbolically when the second argument\n is an integer.\n\n EXAMPLES::\n\n sage: binomial._binomial_sym(x, 3)\n 1/6*(x - 1)*(x - 2)*x\n sage: binomial._binomial_sym(x, x)\n Traceback (most recent call last):\n ...\n ValueError: second argument must be an integer\n sage: binomial._binomial_sym(x, SR(3))\n 1/6*(x - 1)*(x - 2)*x\n\n sage: binomial._binomial_sym(x, 0r)\n 1\n sage: binomial._binomial_sym(x, -1)\n 0\n ' if isinstance(k, Expression): if k.is_integer(): k = k.pyobject() else: raise ValueError('second argument must be an integer') if (k < 0): return s_parent(k)(0) if (k == 0): return s_parent(k)(1) if (k == 1): return n from sage.misc.misc import prod return (prod([(n - i) for i in xrange(k)]) / factorial(k))
Expand the binomial formula symbolically when the second argument is an integer. EXAMPLES:: sage: binomial._binomial_sym(x, 3) 1/6*(x - 1)*(x - 2)*x sage: binomial._binomial_sym(x, x) Traceback (most recent call last): ... ValueError: second argument must be an integer sage: binomial._binomial_sym(x, SR(3)) 1/6*(x - 1)*(x - 2)*x sage: binomial._binomial_sym(x, 0r) 1 sage: binomial._binomial_sym(x, -1) 0
src/sage/functions/other.py
_binomial_sym
drvinceknight/sage
2
python
def _binomial_sym(self, n, k): '\n Expand the binomial formula symbolically when the second argument\n is an integer.\n\n EXAMPLES::\n\n sage: binomial._binomial_sym(x, 3)\n 1/6*(x - 1)*(x - 2)*x\n sage: binomial._binomial_sym(x, x)\n Traceback (most recent call last):\n ...\n ValueError: second argument must be an integer\n sage: binomial._binomial_sym(x, SR(3))\n 1/6*(x - 1)*(x - 2)*x\n\n sage: binomial._binomial_sym(x, 0r)\n 1\n sage: binomial._binomial_sym(x, -1)\n 0\n ' if isinstance(k, Expression): if k.is_integer(): k = k.pyobject() else: raise ValueError('second argument must be an integer') if (k < 0): return s_parent(k)(0) if (k == 0): return s_parent(k)(1) if (k == 1): return n from sage.misc.misc import prod return (prod([(n - i) for i in xrange(k)]) / factorial(k))
def _binomial_sym(self, n, k): '\n Expand the binomial formula symbolically when the second argument\n is an integer.\n\n EXAMPLES::\n\n sage: binomial._binomial_sym(x, 3)\n 1/6*(x - 1)*(x - 2)*x\n sage: binomial._binomial_sym(x, x)\n Traceback (most recent call last):\n ...\n ValueError: second argument must be an integer\n sage: binomial._binomial_sym(x, SR(3))\n 1/6*(x - 1)*(x - 2)*x\n\n sage: binomial._binomial_sym(x, 0r)\n 1\n sage: binomial._binomial_sym(x, -1)\n 0\n ' if isinstance(k, Expression): if k.is_integer(): k = k.pyobject() else: raise ValueError('second argument must be an integer') if (k < 0): return s_parent(k)(0) if (k == 0): return s_parent(k)(1) if (k == 1): return n from sage.misc.misc import prod return (prod([(n - i) for i in xrange(k)]) / factorial(k))<|docstring|>Expand the binomial formula symbolically when the second argument is an integer. EXAMPLES:: sage: binomial._binomial_sym(x, 3) 1/6*(x - 1)*(x - 2)*x sage: binomial._binomial_sym(x, x) Traceback (most recent call last): ... ValueError: second argument must be an integer sage: binomial._binomial_sym(x, SR(3)) 1/6*(x - 1)*(x - 2)*x sage: binomial._binomial_sym(x, 0r) 1 sage: binomial._binomial_sym(x, -1) 0<|endoftext|>
71a2b9462c12fd755d22e9407b3e47321ba68173ab498ad1e01940d29c7fb0f7
def _eval_(self, n, k): "\n EXAMPLES::\n\n sage: binomial._eval_(5, 3)\n 10\n sage: type(binomial._eval_(5, 3))\n <type 'sage.rings.integer.Integer'>\n sage: type(binomial._eval_(5., 3))\n <type 'sage.rings.real_mpfr.RealNumber'>\n sage: binomial._eval_(x, 3)\n 1/6*(x - 1)*(x - 2)*x\n sage: binomial._eval_(x, x-2)\n 1/2*(x - 1)*x\n sage: n = var('n')\n sage: binomial._eval_(x, n) is None\n True\n " if (not isinstance(k, Expression)): if (not isinstance(n, Expression)): (n, k) = coercion_model.canonical_coercion(n, k) return self._evalf_(n, k, s_parent(n)) if (k in ZZ): return self._binomial_sym(n, k) if ((n - k) in ZZ): return self._binomial_sym(n, (n - k)) return None
EXAMPLES:: sage: binomial._eval_(5, 3) 10 sage: type(binomial._eval_(5, 3)) <type 'sage.rings.integer.Integer'> sage: type(binomial._eval_(5., 3)) <type 'sage.rings.real_mpfr.RealNumber'> sage: binomial._eval_(x, 3) 1/6*(x - 1)*(x - 2)*x sage: binomial._eval_(x, x-2) 1/2*(x - 1)*x sage: n = var('n') sage: binomial._eval_(x, n) is None True
src/sage/functions/other.py
_eval_
drvinceknight/sage
2
python
def _eval_(self, n, k): "\n EXAMPLES::\n\n sage: binomial._eval_(5, 3)\n 10\n sage: type(binomial._eval_(5, 3))\n <type 'sage.rings.integer.Integer'>\n sage: type(binomial._eval_(5., 3))\n <type 'sage.rings.real_mpfr.RealNumber'>\n sage: binomial._eval_(x, 3)\n 1/6*(x - 1)*(x - 2)*x\n sage: binomial._eval_(x, x-2)\n 1/2*(x - 1)*x\n sage: n = var('n')\n sage: binomial._eval_(x, n) is None\n True\n " if (not isinstance(k, Expression)): if (not isinstance(n, Expression)): (n, k) = coercion_model.canonical_coercion(n, k) return self._evalf_(n, k, s_parent(n)) if (k in ZZ): return self._binomial_sym(n, k) if ((n - k) in ZZ): return self._binomial_sym(n, (n - k)) return None
def _eval_(self, n, k): "\n EXAMPLES::\n\n sage: binomial._eval_(5, 3)\n 10\n sage: type(binomial._eval_(5, 3))\n <type 'sage.rings.integer.Integer'>\n sage: type(binomial._eval_(5., 3))\n <type 'sage.rings.real_mpfr.RealNumber'>\n sage: binomial._eval_(x, 3)\n 1/6*(x - 1)*(x - 2)*x\n sage: binomial._eval_(x, x-2)\n 1/2*(x - 1)*x\n sage: n = var('n')\n sage: binomial._eval_(x, n) is None\n True\n " if (not isinstance(k, Expression)): if (not isinstance(n, Expression)): (n, k) = coercion_model.canonical_coercion(n, k) return self._evalf_(n, k, s_parent(n)) if (k in ZZ): return self._binomial_sym(n, k) if ((n - k) in ZZ): return self._binomial_sym(n, (n - k)) return None<|docstring|>EXAMPLES:: sage: binomial._eval_(5, 3) 10 sage: type(binomial._eval_(5, 3)) <type 'sage.rings.integer.Integer'> sage: type(binomial._eval_(5., 3)) <type 'sage.rings.real_mpfr.RealNumber'> sage: binomial._eval_(x, 3) 1/6*(x - 1)*(x - 2)*x sage: binomial._eval_(x, x-2) 1/2*(x - 1)*x sage: n = var('n') sage: binomial._eval_(x, n) is None True<|endoftext|>
9a938ea4b498c00b8cc07b4ba49931dc5be7a014f4594c0c11e893ebe39e1519
def _evalf_(self, n, k, parent=None, algorithm=None): "\n EXAMPLES::\n\n sage: binomial._evalf_(5.r, 3)\n 10.0\n sage: type(binomial._evalf_(5.r, 3))\n <type 'float'>\n sage: binomial._evalf_(1/2,1/1)\n 1/2\n sage: binomial._evalf_(10^20+1/1,10^20)\n 100000000000000000001\n sage: binomial._evalf_(SR(10**7),10**7)\n 1\n sage: binomial._evalf_(3/2,SR(1/1))\n 3/2\n " return sage.rings.arith.binomial(n, k)
EXAMPLES:: sage: binomial._evalf_(5.r, 3) 10.0 sage: type(binomial._evalf_(5.r, 3)) <type 'float'> sage: binomial._evalf_(1/2,1/1) 1/2 sage: binomial._evalf_(10^20+1/1,10^20) 100000000000000000001 sage: binomial._evalf_(SR(10**7),10**7) 1 sage: binomial._evalf_(3/2,SR(1/1)) 3/2
src/sage/functions/other.py
_evalf_
drvinceknight/sage
2
python
def _evalf_(self, n, k, parent=None, algorithm=None): "\n EXAMPLES::\n\n sage: binomial._evalf_(5.r, 3)\n 10.0\n sage: type(binomial._evalf_(5.r, 3))\n <type 'float'>\n sage: binomial._evalf_(1/2,1/1)\n 1/2\n sage: binomial._evalf_(10^20+1/1,10^20)\n 100000000000000000001\n sage: binomial._evalf_(SR(10**7),10**7)\n 1\n sage: binomial._evalf_(3/2,SR(1/1))\n 3/2\n " return sage.rings.arith.binomial(n, k)
def _evalf_(self, n, k, parent=None, algorithm=None): "\n EXAMPLES::\n\n sage: binomial._evalf_(5.r, 3)\n 10.0\n sage: type(binomial._evalf_(5.r, 3))\n <type 'float'>\n sage: binomial._evalf_(1/2,1/1)\n 1/2\n sage: binomial._evalf_(10^20+1/1,10^20)\n 100000000000000000001\n sage: binomial._evalf_(SR(10**7),10**7)\n 1\n sage: binomial._evalf_(3/2,SR(1/1))\n 3/2\n " return sage.rings.arith.binomial(n, k)<|docstring|>EXAMPLES:: sage: binomial._evalf_(5.r, 3) 10.0 sage: type(binomial._evalf_(5.r, 3)) <type 'float'> sage: binomial._evalf_(1/2,1/1) 1/2 sage: binomial._evalf_(10^20+1/1,10^20) 100000000000000000001 sage: binomial._evalf_(SR(10**7),10**7) 1 sage: binomial._evalf_(3/2,SR(1/1)) 3/2<|endoftext|>
e6cb1496a62799cf3214e2b37db74add92cb7e1763f7cc4e60616f82e8de6bab
def __init__(self): '\n Return the beta function. This is defined by\n\n .. math::\n\n B(p,q) = \\int_0^1 t^{p-1}(1-t)^{1-q} dt\n\n for complex or symbolic input `p` and `q`.\n Note that the order of inputs does not matter: `B(p,q)=B(q,p)`.\n\n GiNaC is used to compute `B(p,q)`. However, complex inputs\n are not yet handled in general. When GiNaC raises an error on\n such inputs, we raise a NotImplementedError.\n\n If either input is 1, GiNaC returns the reciprocal of the\n other. In other cases, GiNaC uses one of the following\n formulas:\n\n .. math::\n\n B(p,q) = \\Gamma(p)\\Gamma(q)/\\Gamma(p+q)\n\n or\n\n .. math::\n\n B(p,q) = (-1)^q B(1-p-q, q).\n\n\n For numerical inputs, GiNaC uses the formula\n\n .. math::\n\n B(p,q) = \\exp[\\log\\Gamma(p)+\\log\\Gamma(q)-\\log\\Gamma(p+q)]\n\n\n INPUT:\n\n - ``p`` - number or symbolic expression\n\n - ``q`` - number or symbolic expression\n\n\n OUTPUT: number or symbolic expression (if input is symbolic)\n\n EXAMPLES::\n\n sage: beta(3,2)\n 1/12\n sage: beta(3,1)\n 1/3\n sage: beta(1/2,1/2)\n beta(1/2, 1/2)\n sage: beta(-1,1)\n -1\n sage: beta(-1/2,-1/2)\n 0\n sage: beta(x/2,3)\n beta(3, 1/2*x)\n sage: beta(.5,.5)\n 3.14159265358979\n sage: beta(1,2.0+I)\n 0.400000000000000 - 0.200000000000000*I\n sage: beta(3,x+I)\n beta(3, x + I)\n\n Note that the order of arguments does not matter::\n\n sage: beta(1/2,3*x)\n beta(1/2, 3*x)\n\n The result is symbolic if exact input is given::\n\n sage: beta(2,1+5*I)\n beta(2, 5*I + 1)\n sage: beta(2, 2.)\n 0.166666666666667\n sage: beta(I, 2.)\n -0.500000000000000 - 0.500000000000000*I\n sage: beta(2., 2)\n 0.166666666666667\n sage: beta(2., I)\n -0.500000000000000 - 0.500000000000000*I\n\n Test pickling::\n\n sage: loads(dumps(beta))\n beta\n ' GinacFunction.__init__(self, 'beta', nargs=2, conversions=dict(maxima='beta', mathematica='Beta'))
Return the beta function. This is defined by .. math:: B(p,q) = \int_0^1 t^{p-1}(1-t)^{1-q} dt for complex or symbolic input `p` and `q`. Note that the order of inputs does not matter: `B(p,q)=B(q,p)`. GiNaC is used to compute `B(p,q)`. However, complex inputs are not yet handled in general. When GiNaC raises an error on such inputs, we raise a NotImplementedError. If either input is 1, GiNaC returns the reciprocal of the other. In other cases, GiNaC uses one of the following formulas: .. math:: B(p,q) = \Gamma(p)\Gamma(q)/\Gamma(p+q) or .. math:: B(p,q) = (-1)^q B(1-p-q, q). For numerical inputs, GiNaC uses the formula .. math:: B(p,q) = \exp[\log\Gamma(p)+\log\Gamma(q)-\log\Gamma(p+q)] INPUT: - ``p`` - number or symbolic expression - ``q`` - number or symbolic expression OUTPUT: number or symbolic expression (if input is symbolic) EXAMPLES:: sage: beta(3,2) 1/12 sage: beta(3,1) 1/3 sage: beta(1/2,1/2) beta(1/2, 1/2) sage: beta(-1,1) -1 sage: beta(-1/2,-1/2) 0 sage: beta(x/2,3) beta(3, 1/2*x) sage: beta(.5,.5) 3.14159265358979 sage: beta(1,2.0+I) 0.400000000000000 - 0.200000000000000*I sage: beta(3,x+I) beta(3, x + I) Note that the order of arguments does not matter:: sage: beta(1/2,3*x) beta(1/2, 3*x) The result is symbolic if exact input is given:: sage: beta(2,1+5*I) beta(2, 5*I + 1) sage: beta(2, 2.) 0.166666666666667 sage: beta(I, 2.) -0.500000000000000 - 0.500000000000000*I sage: beta(2., 2) 0.166666666666667 sage: beta(2., I) -0.500000000000000 - 0.500000000000000*I Test pickling:: sage: loads(dumps(beta)) beta
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): '\n Return the beta function. This is defined by\n\n .. math::\n\n B(p,q) = \\int_0^1 t^{p-1}(1-t)^{1-q} dt\n\n for complex or symbolic input `p` and `q`.\n Note that the order of inputs does not matter: `B(p,q)=B(q,p)`.\n\n GiNaC is used to compute `B(p,q)`. However, complex inputs\n are not yet handled in general. When GiNaC raises an error on\n such inputs, we raise a NotImplementedError.\n\n If either input is 1, GiNaC returns the reciprocal of the\n other. In other cases, GiNaC uses one of the following\n formulas:\n\n .. math::\n\n B(p,q) = \\Gamma(p)\\Gamma(q)/\\Gamma(p+q)\n\n or\n\n .. math::\n\n B(p,q) = (-1)^q B(1-p-q, q).\n\n\n For numerical inputs, GiNaC uses the formula\n\n .. math::\n\n B(p,q) = \\exp[\\log\\Gamma(p)+\\log\\Gamma(q)-\\log\\Gamma(p+q)]\n\n\n INPUT:\n\n - ``p`` - number or symbolic expression\n\n - ``q`` - number or symbolic expression\n\n\n OUTPUT: number or symbolic expression (if input is symbolic)\n\n EXAMPLES::\n\n sage: beta(3,2)\n 1/12\n sage: beta(3,1)\n 1/3\n sage: beta(1/2,1/2)\n beta(1/2, 1/2)\n sage: beta(-1,1)\n -1\n sage: beta(-1/2,-1/2)\n 0\n sage: beta(x/2,3)\n beta(3, 1/2*x)\n sage: beta(.5,.5)\n 3.14159265358979\n sage: beta(1,2.0+I)\n 0.400000000000000 - 0.200000000000000*I\n sage: beta(3,x+I)\n beta(3, x + I)\n\n Note that the order of arguments does not matter::\n\n sage: beta(1/2,3*x)\n beta(1/2, 3*x)\n\n The result is symbolic if exact input is given::\n\n sage: beta(2,1+5*I)\n beta(2, 5*I + 1)\n sage: beta(2, 2.)\n 0.166666666666667\n sage: beta(I, 2.)\n -0.500000000000000 - 0.500000000000000*I\n sage: beta(2., 2)\n 0.166666666666667\n sage: beta(2., I)\n -0.500000000000000 - 0.500000000000000*I\n\n Test pickling::\n\n sage: loads(dumps(beta))\n beta\n ' GinacFunction.__init__(self, 'beta', nargs=2, conversions=dict(maxima='beta', mathematica='Beta'))
def __init__(self): '\n Return the beta function. This is defined by\n\n .. math::\n\n B(p,q) = \\int_0^1 t^{p-1}(1-t)^{1-q} dt\n\n for complex or symbolic input `p` and `q`.\n Note that the order of inputs does not matter: `B(p,q)=B(q,p)`.\n\n GiNaC is used to compute `B(p,q)`. However, complex inputs\n are not yet handled in general. When GiNaC raises an error on\n such inputs, we raise a NotImplementedError.\n\n If either input is 1, GiNaC returns the reciprocal of the\n other. In other cases, GiNaC uses one of the following\n formulas:\n\n .. math::\n\n B(p,q) = \\Gamma(p)\\Gamma(q)/\\Gamma(p+q)\n\n or\n\n .. math::\n\n B(p,q) = (-1)^q B(1-p-q, q).\n\n\n For numerical inputs, GiNaC uses the formula\n\n .. math::\n\n B(p,q) = \\exp[\\log\\Gamma(p)+\\log\\Gamma(q)-\\log\\Gamma(p+q)]\n\n\n INPUT:\n\n - ``p`` - number or symbolic expression\n\n - ``q`` - number or symbolic expression\n\n\n OUTPUT: number or symbolic expression (if input is symbolic)\n\n EXAMPLES::\n\n sage: beta(3,2)\n 1/12\n sage: beta(3,1)\n 1/3\n sage: beta(1/2,1/2)\n beta(1/2, 1/2)\n sage: beta(-1,1)\n -1\n sage: beta(-1/2,-1/2)\n 0\n sage: beta(x/2,3)\n beta(3, 1/2*x)\n sage: beta(.5,.5)\n 3.14159265358979\n sage: beta(1,2.0+I)\n 0.400000000000000 - 0.200000000000000*I\n sage: beta(3,x+I)\n beta(3, x + I)\n\n Note that the order of arguments does not matter::\n\n sage: beta(1/2,3*x)\n beta(1/2, 3*x)\n\n The result is symbolic if exact input is given::\n\n sage: beta(2,1+5*I)\n beta(2, 5*I + 1)\n sage: beta(2, 2.)\n 0.166666666666667\n sage: beta(I, 2.)\n -0.500000000000000 - 0.500000000000000*I\n sage: beta(2., 2)\n 0.166666666666667\n sage: beta(2., I)\n -0.500000000000000 - 0.500000000000000*I\n\n Test pickling::\n\n sage: loads(dumps(beta))\n beta\n ' GinacFunction.__init__(self, 'beta', nargs=2, conversions=dict(maxima='beta', mathematica='Beta'))<|docstring|>Return the beta function. This is defined by .. math:: B(p,q) = \int_0^1 t^{p-1}(1-t)^{1-q} dt for complex or symbolic input `p` and `q`. Note that the order of inputs does not matter: `B(p,q)=B(q,p)`. GiNaC is used to compute `B(p,q)`. However, complex inputs are not yet handled in general. When GiNaC raises an error on such inputs, we raise a NotImplementedError. If either input is 1, GiNaC returns the reciprocal of the other. In other cases, GiNaC uses one of the following formulas: .. math:: B(p,q) = \Gamma(p)\Gamma(q)/\Gamma(p+q) or .. math:: B(p,q) = (-1)^q B(1-p-q, q). For numerical inputs, GiNaC uses the formula .. math:: B(p,q) = \exp[\log\Gamma(p)+\log\Gamma(q)-\log\Gamma(p+q)] INPUT: - ``p`` - number or symbolic expression - ``q`` - number or symbolic expression OUTPUT: number or symbolic expression (if input is symbolic) EXAMPLES:: sage: beta(3,2) 1/12 sage: beta(3,1) 1/3 sage: beta(1/2,1/2) beta(1/2, 1/2) sage: beta(-1,1) -1 sage: beta(-1/2,-1/2) 0 sage: beta(x/2,3) beta(3, 1/2*x) sage: beta(.5,.5) 3.14159265358979 sage: beta(1,2.0+I) 0.400000000000000 - 0.200000000000000*I sage: beta(3,x+I) beta(3, x + I) Note that the order of arguments does not matter:: sage: beta(1/2,3*x) beta(1/2, 3*x) The result is symbolic if exact input is given:: sage: beta(2,1+5*I) beta(2, 5*I + 1) sage: beta(2, 2.) 0.166666666666667 sage: beta(I, 2.) -0.500000000000000 - 0.500000000000000*I sage: beta(2., 2) 0.166666666666667 sage: beta(2., I) -0.500000000000000 - 0.500000000000000*I Test pickling:: sage: loads(dumps(beta)) beta<|endoftext|>
a42a164081fedb91da8c4961cd41b6a10ec1c49c3a248af3537c8b79676dca36
def __init__(self): '\n The argument function for complex numbers.\n\n EXAMPLES::\n\n sage: arg(3+i)\n arctan(1/3)\n sage: arg(-1+i)\n 3/4*pi\n sage: arg(2+2*i)\n 1/4*pi\n sage: arg(2+x)\n arg(x + 2)\n sage: arg(2.0+i+x)\n arg(x + 2.00000000000000 + 1.00000000000000*I)\n sage: arg(-3)\n pi\n sage: arg(3)\n 0\n sage: arg(0)\n 0\n sage: latex(arg(x))\n {\\rm arg}\\left(x\\right)\n sage: maxima(arg(x))\n atan2(0,_SAGE_VAR_x)\n sage: maxima(arg(2+i))\n atan(1/2)\n sage: maxima(arg(sqrt(2)+i))\n atan(1/sqrt(2))\n sage: arg(2+i)\n arctan(1/2)\n sage: arg(sqrt(2)+i)\n arg(sqrt(2) + I)\n sage: arg(sqrt(2)+i).simplify()\n arctan(1/2*sqrt(2))\n\n TESTS::\n\n sage: arg(0.0)\n 0.000000000000000\n sage: arg(3.0)\n 0.000000000000000\n sage: arg(-2.5)\n 3.14159265358979\n sage: arg(2.0+3*i)\n 0.982793723247329\n ' BuiltinFunction.__init__(self, 'arg', conversions=dict(maxima='carg', mathematica='Arg'))
The argument function for complex numbers. EXAMPLES:: sage: arg(3+i) arctan(1/3) sage: arg(-1+i) 3/4*pi sage: arg(2+2*i) 1/4*pi sage: arg(2+x) arg(x + 2) sage: arg(2.0+i+x) arg(x + 2.00000000000000 + 1.00000000000000*I) sage: arg(-3) pi sage: arg(3) 0 sage: arg(0) 0 sage: latex(arg(x)) {\rm arg}\left(x\right) sage: maxima(arg(x)) atan2(0,_SAGE_VAR_x) sage: maxima(arg(2+i)) atan(1/2) sage: maxima(arg(sqrt(2)+i)) atan(1/sqrt(2)) sage: arg(2+i) arctan(1/2) sage: arg(sqrt(2)+i) arg(sqrt(2) + I) sage: arg(sqrt(2)+i).simplify() arctan(1/2*sqrt(2)) TESTS:: sage: arg(0.0) 0.000000000000000 sage: arg(3.0) 0.000000000000000 sage: arg(-2.5) 3.14159265358979 sage: arg(2.0+3*i) 0.982793723247329
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): '\n The argument function for complex numbers.\n\n EXAMPLES::\n\n sage: arg(3+i)\n arctan(1/3)\n sage: arg(-1+i)\n 3/4*pi\n sage: arg(2+2*i)\n 1/4*pi\n sage: arg(2+x)\n arg(x + 2)\n sage: arg(2.0+i+x)\n arg(x + 2.00000000000000 + 1.00000000000000*I)\n sage: arg(-3)\n pi\n sage: arg(3)\n 0\n sage: arg(0)\n 0\n sage: latex(arg(x))\n {\\rm arg}\\left(x\\right)\n sage: maxima(arg(x))\n atan2(0,_SAGE_VAR_x)\n sage: maxima(arg(2+i))\n atan(1/2)\n sage: maxima(arg(sqrt(2)+i))\n atan(1/sqrt(2))\n sage: arg(2+i)\n arctan(1/2)\n sage: arg(sqrt(2)+i)\n arg(sqrt(2) + I)\n sage: arg(sqrt(2)+i).simplify()\n arctan(1/2*sqrt(2))\n\n TESTS::\n\n sage: arg(0.0)\n 0.000000000000000\n sage: arg(3.0)\n 0.000000000000000\n sage: arg(-2.5)\n 3.14159265358979\n sage: arg(2.0+3*i)\n 0.982793723247329\n ' BuiltinFunction.__init__(self, 'arg', conversions=dict(maxima='carg', mathematica='Arg'))
def __init__(self): '\n The argument function for complex numbers.\n\n EXAMPLES::\n\n sage: arg(3+i)\n arctan(1/3)\n sage: arg(-1+i)\n 3/4*pi\n sage: arg(2+2*i)\n 1/4*pi\n sage: arg(2+x)\n arg(x + 2)\n sage: arg(2.0+i+x)\n arg(x + 2.00000000000000 + 1.00000000000000*I)\n sage: arg(-3)\n pi\n sage: arg(3)\n 0\n sage: arg(0)\n 0\n sage: latex(arg(x))\n {\\rm arg}\\left(x\\right)\n sage: maxima(arg(x))\n atan2(0,_SAGE_VAR_x)\n sage: maxima(arg(2+i))\n atan(1/2)\n sage: maxima(arg(sqrt(2)+i))\n atan(1/sqrt(2))\n sage: arg(2+i)\n arctan(1/2)\n sage: arg(sqrt(2)+i)\n arg(sqrt(2) + I)\n sage: arg(sqrt(2)+i).simplify()\n arctan(1/2*sqrt(2))\n\n TESTS::\n\n sage: arg(0.0)\n 0.000000000000000\n sage: arg(3.0)\n 0.000000000000000\n sage: arg(-2.5)\n 3.14159265358979\n sage: arg(2.0+3*i)\n 0.982793723247329\n ' BuiltinFunction.__init__(self, 'arg', conversions=dict(maxima='carg', mathematica='Arg'))<|docstring|>The argument function for complex numbers. EXAMPLES:: sage: arg(3+i) arctan(1/3) sage: arg(-1+i) 3/4*pi sage: arg(2+2*i) 1/4*pi sage: arg(2+x) arg(x + 2) sage: arg(2.0+i+x) arg(x + 2.00000000000000 + 1.00000000000000*I) sage: arg(-3) pi sage: arg(3) 0 sage: arg(0) 0 sage: latex(arg(x)) {\rm arg}\left(x\right) sage: maxima(arg(x)) atan2(0,_SAGE_VAR_x) sage: maxima(arg(2+i)) atan(1/2) sage: maxima(arg(sqrt(2)+i)) atan(1/sqrt(2)) sage: arg(2+i) arctan(1/2) sage: arg(sqrt(2)+i) arg(sqrt(2) + I) sage: arg(sqrt(2)+i).simplify() arctan(1/2*sqrt(2)) TESTS:: sage: arg(0.0) 0.000000000000000 sage: arg(3.0) 0.000000000000000 sage: arg(-2.5) 3.14159265358979 sage: arg(2.0+3*i) 0.982793723247329<|endoftext|>
ab4fa236a9aca7e064f5db3490d9ddcab2c71f5993dc1a9cbcb468192f6e2f9a
def _eval_(self, x): '\n EXAMPLES::\n\n sage: arg(3+i)\n arctan(1/3)\n sage: arg(-1+i)\n 3/4*pi\n sage: arg(2+2*i)\n 1/4*pi\n sage: arg(2+x)\n arg(x + 2)\n sage: arg(2.0+i+x)\n arg(x + 2.00000000000000 + 1.00000000000000*I)\n sage: arg(-3)\n pi\n sage: arg(3)\n 0\n sage: arg(0)\n 0\n sage: arg(sqrt(2)+i)\n arg(sqrt(2) + I)\n\n ' if (not isinstance(x, Expression)): if (s_parent(x)(0) == x): return s_parent(x)(0) elif is_inexact(x): return self._evalf_(x, s_parent(x)) else: return arctan2(imag_part(x), real_part(x)) else: return None
EXAMPLES:: sage: arg(3+i) arctan(1/3) sage: arg(-1+i) 3/4*pi sage: arg(2+2*i) 1/4*pi sage: arg(2+x) arg(x + 2) sage: arg(2.0+i+x) arg(x + 2.00000000000000 + 1.00000000000000*I) sage: arg(-3) pi sage: arg(3) 0 sage: arg(0) 0 sage: arg(sqrt(2)+i) arg(sqrt(2) + I)
src/sage/functions/other.py
_eval_
drvinceknight/sage
2
python
def _eval_(self, x): '\n EXAMPLES::\n\n sage: arg(3+i)\n arctan(1/3)\n sage: arg(-1+i)\n 3/4*pi\n sage: arg(2+2*i)\n 1/4*pi\n sage: arg(2+x)\n arg(x + 2)\n sage: arg(2.0+i+x)\n arg(x + 2.00000000000000 + 1.00000000000000*I)\n sage: arg(-3)\n pi\n sage: arg(3)\n 0\n sage: arg(0)\n 0\n sage: arg(sqrt(2)+i)\n arg(sqrt(2) + I)\n\n ' if (not isinstance(x, Expression)): if (s_parent(x)(0) == x): return s_parent(x)(0) elif is_inexact(x): return self._evalf_(x, s_parent(x)) else: return arctan2(imag_part(x), real_part(x)) else: return None
def _eval_(self, x): '\n EXAMPLES::\n\n sage: arg(3+i)\n arctan(1/3)\n sage: arg(-1+i)\n 3/4*pi\n sage: arg(2+2*i)\n 1/4*pi\n sage: arg(2+x)\n arg(x + 2)\n sage: arg(2.0+i+x)\n arg(x + 2.00000000000000 + 1.00000000000000*I)\n sage: arg(-3)\n pi\n sage: arg(3)\n 0\n sage: arg(0)\n 0\n sage: arg(sqrt(2)+i)\n arg(sqrt(2) + I)\n\n ' if (not isinstance(x, Expression)): if (s_parent(x)(0) == x): return s_parent(x)(0) elif is_inexact(x): return self._evalf_(x, s_parent(x)) else: return arctan2(imag_part(x), real_part(x)) else: return None<|docstring|>EXAMPLES:: sage: arg(3+i) arctan(1/3) sage: arg(-1+i) 3/4*pi sage: arg(2+2*i) 1/4*pi sage: arg(2+x) arg(x + 2) sage: arg(2.0+i+x) arg(x + 2.00000000000000 + 1.00000000000000*I) sage: arg(-3) pi sage: arg(3) 0 sage: arg(0) 0 sage: arg(sqrt(2)+i) arg(sqrt(2) + I)<|endoftext|>
a81382eb56f2ae8335f6b3f76716ccbc93197d8c73d2f5ce45b3e9779eaf02c1
def _evalf_(self, x, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: arg(0.0)\n 0.000000000000000\n sage: arg(3.0)\n 0.000000000000000\n sage: arg(3.00000000000000000000000000)\n 0.00000000000000000000000000\n sage: arg(3.00000000000000000000000000).prec()\n 90\n sage: arg(ComplexIntervalField(90)(3)).prec()\n 90\n sage: arg(ComplexIntervalField(90)(3)).parent()\n Real Interval Field with 90 bits of precision\n sage: arg(3.0r)\n 0.0\n sage: arg(RDF(3))\n 0.0\n sage: arg(RDF(3)).parent()\n Real Double Field\n sage: arg(-2.5)\n 3.14159265358979\n sage: arg(2.0+3*i)\n 0.982793723247329\n\n TESTS:\n\n Make sure that the ``_evalf_`` method works when it receives a\n keyword argument ``parent`` :trac:`12289`::\n\n sage: arg(5+I, hold=True).n()\n 0.197395559849881\n ' try: return x.arg() except AttributeError: pass if (parent is None): parent = s_parent(x) try: parent = parent.complex_field() except AttributeError: from sage.rings.complex_field import ComplexField try: parent = ComplexField(x.prec()) except AttributeError: parent = ComplexField() return parent(x).arg()
EXAMPLES:: sage: arg(0.0) 0.000000000000000 sage: arg(3.0) 0.000000000000000 sage: arg(3.00000000000000000000000000) 0.00000000000000000000000000 sage: arg(3.00000000000000000000000000).prec() 90 sage: arg(ComplexIntervalField(90)(3)).prec() 90 sage: arg(ComplexIntervalField(90)(3)).parent() Real Interval Field with 90 bits of precision sage: arg(3.0r) 0.0 sage: arg(RDF(3)) 0.0 sage: arg(RDF(3)).parent() Real Double Field sage: arg(-2.5) 3.14159265358979 sage: arg(2.0+3*i) 0.982793723247329 TESTS: Make sure that the ``_evalf_`` method works when it receives a keyword argument ``parent`` :trac:`12289`:: sage: arg(5+I, hold=True).n() 0.197395559849881
src/sage/functions/other.py
_evalf_
drvinceknight/sage
2
python
def _evalf_(self, x, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: arg(0.0)\n 0.000000000000000\n sage: arg(3.0)\n 0.000000000000000\n sage: arg(3.00000000000000000000000000)\n 0.00000000000000000000000000\n sage: arg(3.00000000000000000000000000).prec()\n 90\n sage: arg(ComplexIntervalField(90)(3)).prec()\n 90\n sage: arg(ComplexIntervalField(90)(3)).parent()\n Real Interval Field with 90 bits of precision\n sage: arg(3.0r)\n 0.0\n sage: arg(RDF(3))\n 0.0\n sage: arg(RDF(3)).parent()\n Real Double Field\n sage: arg(-2.5)\n 3.14159265358979\n sage: arg(2.0+3*i)\n 0.982793723247329\n\n TESTS:\n\n Make sure that the ``_evalf_`` method works when it receives a\n keyword argument ``parent`` :trac:`12289`::\n\n sage: arg(5+I, hold=True).n()\n 0.197395559849881\n ' try: return x.arg() except AttributeError: pass if (parent is None): parent = s_parent(x) try: parent = parent.complex_field() except AttributeError: from sage.rings.complex_field import ComplexField try: parent = ComplexField(x.prec()) except AttributeError: parent = ComplexField() return parent(x).arg()
def _evalf_(self, x, parent=None, algorithm=None): '\n EXAMPLES::\n\n sage: arg(0.0)\n 0.000000000000000\n sage: arg(3.0)\n 0.000000000000000\n sage: arg(3.00000000000000000000000000)\n 0.00000000000000000000000000\n sage: arg(3.00000000000000000000000000).prec()\n 90\n sage: arg(ComplexIntervalField(90)(3)).prec()\n 90\n sage: arg(ComplexIntervalField(90)(3)).parent()\n Real Interval Field with 90 bits of precision\n sage: arg(3.0r)\n 0.0\n sage: arg(RDF(3))\n 0.0\n sage: arg(RDF(3)).parent()\n Real Double Field\n sage: arg(-2.5)\n 3.14159265358979\n sage: arg(2.0+3*i)\n 0.982793723247329\n\n TESTS:\n\n Make sure that the ``_evalf_`` method works when it receives a\n keyword argument ``parent`` :trac:`12289`::\n\n sage: arg(5+I, hold=True).n()\n 0.197395559849881\n ' try: return x.arg() except AttributeError: pass if (parent is None): parent = s_parent(x) try: parent = parent.complex_field() except AttributeError: from sage.rings.complex_field import ComplexField try: parent = ComplexField(x.prec()) except AttributeError: parent = ComplexField() return parent(x).arg()<|docstring|>EXAMPLES:: sage: arg(0.0) 0.000000000000000 sage: arg(3.0) 0.000000000000000 sage: arg(3.00000000000000000000000000) 0.00000000000000000000000000 sage: arg(3.00000000000000000000000000).prec() 90 sage: arg(ComplexIntervalField(90)(3)).prec() 90 sage: arg(ComplexIntervalField(90)(3)).parent() Real Interval Field with 90 bits of precision sage: arg(3.0r) 0.0 sage: arg(RDF(3)) 0.0 sage: arg(RDF(3)).parent() Real Double Field sage: arg(-2.5) 3.14159265358979 sage: arg(2.0+3*i) 0.982793723247329 TESTS: Make sure that the ``_evalf_`` method works when it receives a keyword argument ``parent`` :trac:`12289`:: sage: arg(5+I, hold=True).n() 0.197395559849881<|endoftext|>
61a01c6a45c47e129e42995af3d1f664b4719ff884c5c481b17276c7aa2ab4ff
def __init__(self): "\n Returns the real part of the (possibly complex) input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: real_part(I,hold=True)\n real_part(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: real_part(I,hold=True).simplify()\n 0\n\n EXAMPLES::\n\n sage: z = 1+2*I\n sage: real(z)\n 1\n sage: real(5/3)\n 5/3\n sage: a = 2.5\n sage: real(a)\n 2.50000000000000\n sage: type(real(a))\n <type 'sage.rings.real_mpfr.RealLiteral'>\n sage: real(1.0r)\n 1.0\n sage: real(complex(3, 4))\n 3.0\n\n TESTS::\n\n sage: loads(dumps(real_part))\n real_part\n\n Check if #6401 is fixed::\n\n sage: latex(x.real())\n \\Re \\left( x \\right)\n\n sage: f(x) = function('f',x)\n sage: latex( f(x).real())\n \\Re \\left( f\\left(x\\right) \\right)\n " GinacFunction.__init__(self, 'real_part', conversions=dict(maxima='realpart'))
Returns the real part of the (possibly complex) input. It is possible to prevent automatic evaluation using the ``hold`` parameter:: sage: real_part(I,hold=True) real_part(I) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: real_part(I,hold=True).simplify() 0 EXAMPLES:: sage: z = 1+2*I sage: real(z) 1 sage: real(5/3) 5/3 sage: a = 2.5 sage: real(a) 2.50000000000000 sage: type(real(a)) <type 'sage.rings.real_mpfr.RealLiteral'> sage: real(1.0r) 1.0 sage: real(complex(3, 4)) 3.0 TESTS:: sage: loads(dumps(real_part)) real_part Check if #6401 is fixed:: sage: latex(x.real()) \Re \left( x \right) sage: f(x) = function('f',x) sage: latex( f(x).real()) \Re \left( f\left(x\right) \right)
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n Returns the real part of the (possibly complex) input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: real_part(I,hold=True)\n real_part(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: real_part(I,hold=True).simplify()\n 0\n\n EXAMPLES::\n\n sage: z = 1+2*I\n sage: real(z)\n 1\n sage: real(5/3)\n 5/3\n sage: a = 2.5\n sage: real(a)\n 2.50000000000000\n sage: type(real(a))\n <type 'sage.rings.real_mpfr.RealLiteral'>\n sage: real(1.0r)\n 1.0\n sage: real(complex(3, 4))\n 3.0\n\n TESTS::\n\n sage: loads(dumps(real_part))\n real_part\n\n Check if #6401 is fixed::\n\n sage: latex(x.real())\n \\Re \\left( x \\right)\n\n sage: f(x) = function('f',x)\n sage: latex( f(x).real())\n \\Re \\left( f\\left(x\\right) \\right)\n " GinacFunction.__init__(self, 'real_part', conversions=dict(maxima='realpart'))
def __init__(self): "\n Returns the real part of the (possibly complex) input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: real_part(I,hold=True)\n real_part(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: real_part(I,hold=True).simplify()\n 0\n\n EXAMPLES::\n\n sage: z = 1+2*I\n sage: real(z)\n 1\n sage: real(5/3)\n 5/3\n sage: a = 2.5\n sage: real(a)\n 2.50000000000000\n sage: type(real(a))\n <type 'sage.rings.real_mpfr.RealLiteral'>\n sage: real(1.0r)\n 1.0\n sage: real(complex(3, 4))\n 3.0\n\n TESTS::\n\n sage: loads(dumps(real_part))\n real_part\n\n Check if #6401 is fixed::\n\n sage: latex(x.real())\n \\Re \\left( x \\right)\n\n sage: f(x) = function('f',x)\n sage: latex( f(x).real())\n \\Re \\left( f\\left(x\\right) \\right)\n " GinacFunction.__init__(self, 'real_part', conversions=dict(maxima='realpart'))<|docstring|>Returns the real part of the (possibly complex) input. It is possible to prevent automatic evaluation using the ``hold`` parameter:: sage: real_part(I,hold=True) real_part(I) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: real_part(I,hold=True).simplify() 0 EXAMPLES:: sage: z = 1+2*I sage: real(z) 1 sage: real(5/3) 5/3 sage: a = 2.5 sage: real(a) 2.50000000000000 sage: type(real(a)) <type 'sage.rings.real_mpfr.RealLiteral'> sage: real(1.0r) 1.0 sage: real(complex(3, 4)) 3.0 TESTS:: sage: loads(dumps(real_part)) real_part Check if #6401 is fixed:: sage: latex(x.real()) \Re \left( x \right) sage: f(x) = function('f',x) sage: latex( f(x).real()) \Re \left( f\left(x\right) \right)<|endoftext|>
702ab631d7dfe8b0433d3c68b23183f4f0039473acd06793f2105b68c030a792
def __call__(self, x, **kwargs): "\n TESTS::\n\n sage: type(real(complex(3, 4)))\n <type 'float'>\n " if isinstance(x, complex): return x.real else: return GinacFunction.__call__(self, x, **kwargs)
TESTS:: sage: type(real(complex(3, 4))) <type 'float'>
src/sage/functions/other.py
__call__
drvinceknight/sage
2
python
def __call__(self, x, **kwargs): "\n TESTS::\n\n sage: type(real(complex(3, 4)))\n <type 'float'>\n " if isinstance(x, complex): return x.real else: return GinacFunction.__call__(self, x, **kwargs)
def __call__(self, x, **kwargs): "\n TESTS::\n\n sage: type(real(complex(3, 4)))\n <type 'float'>\n " if isinstance(x, complex): return x.real else: return GinacFunction.__call__(self, x, **kwargs)<|docstring|>TESTS:: sage: type(real(complex(3, 4))) <type 'float'><|endoftext|>
73356c0867c3fc265f5d81fed4e9660406766fd99c48a58419cb8c64baaa42a0
def _eval_numpy_(self, x): '\n EXAMPLES::\n\n sage: import numpy\n sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex)\n sage: real_part(a)\n array([ 1., -2.])\n ' import numpy return numpy.real(x)
EXAMPLES:: sage: import numpy sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex) sage: real_part(a) array([ 1., -2.])
src/sage/functions/other.py
_eval_numpy_
drvinceknight/sage
2
python
def _eval_numpy_(self, x): '\n EXAMPLES::\n\n sage: import numpy\n sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex)\n sage: real_part(a)\n array([ 1., -2.])\n ' import numpy return numpy.real(x)
def _eval_numpy_(self, x): '\n EXAMPLES::\n\n sage: import numpy\n sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex)\n sage: real_part(a)\n array([ 1., -2.])\n ' import numpy return numpy.real(x)<|docstring|>EXAMPLES:: sage: import numpy sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex) sage: real_part(a) array([ 1., -2.])<|endoftext|>
80f4172a026b45ef6380b224c1753f0deb1a8edc9a49f84ea1b7553b26ebcaa8
def __init__(self): "\n Returns the imaginary part of the (possibly complex) input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: imag_part(I,hold=True)\n imag_part(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: imag_part(I,hold=True).simplify()\n 1\n\n TESTS::\n\n sage: z = 1+2*I\n sage: imaginary(z)\n 2\n sage: imag(z)\n 2\n sage: imag(complex(3, 4))\n 4.0\n sage: loads(dumps(imag_part))\n imag_part\n\n Check if #6401 is fixed::\n\n sage: latex(x.imag())\n \\Im \\left( x \\right)\n\n sage: f(x) = function('f',x)\n sage: latex( f(x).imag())\n \\Im \\left( f\\left(x\\right) \\right)\n " GinacFunction.__init__(self, 'imag_part', conversions=dict(maxima='imagpart'))
Returns the imaginary part of the (possibly complex) input. It is possible to prevent automatic evaluation using the ``hold`` parameter:: sage: imag_part(I,hold=True) imag_part(I) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: imag_part(I,hold=True).simplify() 1 TESTS:: sage: z = 1+2*I sage: imaginary(z) 2 sage: imag(z) 2 sage: imag(complex(3, 4)) 4.0 sage: loads(dumps(imag_part)) imag_part Check if #6401 is fixed:: sage: latex(x.imag()) \Im \left( x \right) sage: f(x) = function('f',x) sage: latex( f(x).imag()) \Im \left( f\left(x\right) \right)
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n Returns the imaginary part of the (possibly complex) input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: imag_part(I,hold=True)\n imag_part(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: imag_part(I,hold=True).simplify()\n 1\n\n TESTS::\n\n sage: z = 1+2*I\n sage: imaginary(z)\n 2\n sage: imag(z)\n 2\n sage: imag(complex(3, 4))\n 4.0\n sage: loads(dumps(imag_part))\n imag_part\n\n Check if #6401 is fixed::\n\n sage: latex(x.imag())\n \\Im \\left( x \\right)\n\n sage: f(x) = function('f',x)\n sage: latex( f(x).imag())\n \\Im \\left( f\\left(x\\right) \\right)\n " GinacFunction.__init__(self, 'imag_part', conversions=dict(maxima='imagpart'))
def __init__(self): "\n Returns the imaginary part of the (possibly complex) input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: imag_part(I,hold=True)\n imag_part(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: imag_part(I,hold=True).simplify()\n 1\n\n TESTS::\n\n sage: z = 1+2*I\n sage: imaginary(z)\n 2\n sage: imag(z)\n 2\n sage: imag(complex(3, 4))\n 4.0\n sage: loads(dumps(imag_part))\n imag_part\n\n Check if #6401 is fixed::\n\n sage: latex(x.imag())\n \\Im \\left( x \\right)\n\n sage: f(x) = function('f',x)\n sage: latex( f(x).imag())\n \\Im \\left( f\\left(x\\right) \\right)\n " GinacFunction.__init__(self, 'imag_part', conversions=dict(maxima='imagpart'))<|docstring|>Returns the imaginary part of the (possibly complex) input. It is possible to prevent automatic evaluation using the ``hold`` parameter:: sage: imag_part(I,hold=True) imag_part(I) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: imag_part(I,hold=True).simplify() 1 TESTS:: sage: z = 1+2*I sage: imaginary(z) 2 sage: imag(z) 2 sage: imag(complex(3, 4)) 4.0 sage: loads(dumps(imag_part)) imag_part Check if #6401 is fixed:: sage: latex(x.imag()) \Im \left( x \right) sage: f(x) = function('f',x) sage: latex( f(x).imag()) \Im \left( f\left(x\right) \right)<|endoftext|>
63474507d20e16ef6009294699b40b184cdd4f4e2ddf29f19bac98e78a183b81
def __call__(self, x, **kwargs): "\n TESTS::\n\n sage: type(imag(complex(3, 4)))\n <type 'float'>\n " if isinstance(x, complex): return x.imag else: return GinacFunction.__call__(self, x, **kwargs)
TESTS:: sage: type(imag(complex(3, 4))) <type 'float'>
src/sage/functions/other.py
__call__
drvinceknight/sage
2
python
def __call__(self, x, **kwargs): "\n TESTS::\n\n sage: type(imag(complex(3, 4)))\n <type 'float'>\n " if isinstance(x, complex): return x.imag else: return GinacFunction.__call__(self, x, **kwargs)
def __call__(self, x, **kwargs): "\n TESTS::\n\n sage: type(imag(complex(3, 4)))\n <type 'float'>\n " if isinstance(x, complex): return x.imag else: return GinacFunction.__call__(self, x, **kwargs)<|docstring|>TESTS:: sage: type(imag(complex(3, 4))) <type 'float'><|endoftext|>
4b2b3ed23ca64be99573b32da30f90246c8b3538a1b1b5376176eb3466a1d527
def _eval_numpy_(self, x): '\n EXAMPLES::\n\n sage: import numpy\n sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex)\n sage: imag_part(a)\n array([ 2., -3.])\n ' import numpy return numpy.imag(x)
EXAMPLES:: sage: import numpy sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex) sage: imag_part(a) array([ 2., -3.])
src/sage/functions/other.py
_eval_numpy_
drvinceknight/sage
2
python
def _eval_numpy_(self, x): '\n EXAMPLES::\n\n sage: import numpy\n sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex)\n sage: imag_part(a)\n array([ 2., -3.])\n ' import numpy return numpy.imag(x)
def _eval_numpy_(self, x): '\n EXAMPLES::\n\n sage: import numpy\n sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex)\n sage: imag_part(a)\n array([ 2., -3.])\n ' import numpy return numpy.imag(x)<|docstring|>EXAMPLES:: sage: import numpy sage: a = numpy.array([1+2*I, -2-3*I], dtype=numpy.complex) sage: imag_part(a) array([ 2., -3.])<|endoftext|>
f736b8f4ab1fabbb3f212bb13b398e1d1f9c4719e6bb71b1d2d25933c6629f74
def __init__(self): "\n Returns the complex conjugate of the input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: conjugate(I,hold=True)\n conjugate(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: conjugate(I,hold=True).simplify()\n -I\n\n TESTS::\n\n sage: x,y = var('x,y')\n sage: x.conjugate()\n conjugate(x)\n sage: latex(conjugate(x))\n \\overline{x}\n sage: f = function('f')\n sage: latex(f(x).conjugate())\n \\overline{f\\left(x\\right)}\n sage: f = function('psi',x,y)\n sage: latex(f.conjugate())\n \\overline{\\psi\\left(x, y\\right)}\n sage: x.conjugate().conjugate()\n x\n sage: x.conjugate().operator()\n conjugate\n sage: x.conjugate().operator() == conjugate\n True\n\n Check if #8755 is fixed::\n\n sage: conjugate(sqrt(-3))\n conjugate(sqrt(-3))\n sage: conjugate(sqrt(3))\n sqrt(3)\n sage: conjugate(sqrt(x))\n conjugate(sqrt(x))\n sage: conjugate(x^2)\n conjugate(x)^2\n sage: var('y',domain='positive')\n y\n sage: conjugate(sqrt(y))\n sqrt(y)\n\n Check if #10964 is fixed::\n\n sage: z= I*sqrt(-3); z\n I*sqrt(-3)\n sage: conjugate(z)\n -I*conjugate(sqrt(-3))\n sage: var('a')\n a\n sage: conjugate(a*sqrt(-2)*sqrt(-3))\n conjugate(sqrt(-2))*conjugate(sqrt(-3))*conjugate(a)\n\n Test pickling::\n\n sage: loads(dumps(conjugate))\n conjugate\n " GinacFunction.__init__(self, 'conjugate')
Returns the complex conjugate of the input. It is possible to prevent automatic evaluation using the ``hold`` parameter:: sage: conjugate(I,hold=True) conjugate(I) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: conjugate(I,hold=True).simplify() -I TESTS:: sage: x,y = var('x,y') sage: x.conjugate() conjugate(x) sage: latex(conjugate(x)) \overline{x} sage: f = function('f') sage: latex(f(x).conjugate()) \overline{f\left(x\right)} sage: f = function('psi',x,y) sage: latex(f.conjugate()) \overline{\psi\left(x, y\right)} sage: x.conjugate().conjugate() x sage: x.conjugate().operator() conjugate sage: x.conjugate().operator() == conjugate True Check if #8755 is fixed:: sage: conjugate(sqrt(-3)) conjugate(sqrt(-3)) sage: conjugate(sqrt(3)) sqrt(3) sage: conjugate(sqrt(x)) conjugate(sqrt(x)) sage: conjugate(x^2) conjugate(x)^2 sage: var('y',domain='positive') y sage: conjugate(sqrt(y)) sqrt(y) Check if #10964 is fixed:: sage: z= I*sqrt(-3); z I*sqrt(-3) sage: conjugate(z) -I*conjugate(sqrt(-3)) sage: var('a') a sage: conjugate(a*sqrt(-2)*sqrt(-3)) conjugate(sqrt(-2))*conjugate(sqrt(-3))*conjugate(a) Test pickling:: sage: loads(dumps(conjugate)) conjugate
src/sage/functions/other.py
__init__
drvinceknight/sage
2
python
def __init__(self): "\n Returns the complex conjugate of the input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: conjugate(I,hold=True)\n conjugate(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: conjugate(I,hold=True).simplify()\n -I\n\n TESTS::\n\n sage: x,y = var('x,y')\n sage: x.conjugate()\n conjugate(x)\n sage: latex(conjugate(x))\n \\overline{x}\n sage: f = function('f')\n sage: latex(f(x).conjugate())\n \\overline{f\\left(x\\right)}\n sage: f = function('psi',x,y)\n sage: latex(f.conjugate())\n \\overline{\\psi\\left(x, y\\right)}\n sage: x.conjugate().conjugate()\n x\n sage: x.conjugate().operator()\n conjugate\n sage: x.conjugate().operator() == conjugate\n True\n\n Check if #8755 is fixed::\n\n sage: conjugate(sqrt(-3))\n conjugate(sqrt(-3))\n sage: conjugate(sqrt(3))\n sqrt(3)\n sage: conjugate(sqrt(x))\n conjugate(sqrt(x))\n sage: conjugate(x^2)\n conjugate(x)^2\n sage: var('y',domain='positive')\n y\n sage: conjugate(sqrt(y))\n sqrt(y)\n\n Check if #10964 is fixed::\n\n sage: z= I*sqrt(-3); z\n I*sqrt(-3)\n sage: conjugate(z)\n -I*conjugate(sqrt(-3))\n sage: var('a')\n a\n sage: conjugate(a*sqrt(-2)*sqrt(-3))\n conjugate(sqrt(-2))*conjugate(sqrt(-3))*conjugate(a)\n\n Test pickling::\n\n sage: loads(dumps(conjugate))\n conjugate\n " GinacFunction.__init__(self, 'conjugate')
def __init__(self): "\n Returns the complex conjugate of the input.\n\n It is possible to prevent automatic evaluation using the\n ``hold`` parameter::\n\n sage: conjugate(I,hold=True)\n conjugate(I)\n\n To then evaluate again, we currently must use Maxima via\n :meth:`sage.symbolic.expression.Expression.simplify`::\n\n sage: conjugate(I,hold=True).simplify()\n -I\n\n TESTS::\n\n sage: x,y = var('x,y')\n sage: x.conjugate()\n conjugate(x)\n sage: latex(conjugate(x))\n \\overline{x}\n sage: f = function('f')\n sage: latex(f(x).conjugate())\n \\overline{f\\left(x\\right)}\n sage: f = function('psi',x,y)\n sage: latex(f.conjugate())\n \\overline{\\psi\\left(x, y\\right)}\n sage: x.conjugate().conjugate()\n x\n sage: x.conjugate().operator()\n conjugate\n sage: x.conjugate().operator() == conjugate\n True\n\n Check if #8755 is fixed::\n\n sage: conjugate(sqrt(-3))\n conjugate(sqrt(-3))\n sage: conjugate(sqrt(3))\n sqrt(3)\n sage: conjugate(sqrt(x))\n conjugate(sqrt(x))\n sage: conjugate(x^2)\n conjugate(x)^2\n sage: var('y',domain='positive')\n y\n sage: conjugate(sqrt(y))\n sqrt(y)\n\n Check if #10964 is fixed::\n\n sage: z= I*sqrt(-3); z\n I*sqrt(-3)\n sage: conjugate(z)\n -I*conjugate(sqrt(-3))\n sage: var('a')\n a\n sage: conjugate(a*sqrt(-2)*sqrt(-3))\n conjugate(sqrt(-2))*conjugate(sqrt(-3))*conjugate(a)\n\n Test pickling::\n\n sage: loads(dumps(conjugate))\n conjugate\n " GinacFunction.__init__(self, 'conjugate')<|docstring|>Returns the complex conjugate of the input. It is possible to prevent automatic evaluation using the ``hold`` parameter:: sage: conjugate(I,hold=True) conjugate(I) To then evaluate again, we currently must use Maxima via :meth:`sage.symbolic.expression.Expression.simplify`:: sage: conjugate(I,hold=True).simplify() -I TESTS:: sage: x,y = var('x,y') sage: x.conjugate() conjugate(x) sage: latex(conjugate(x)) \overline{x} sage: f = function('f') sage: latex(f(x).conjugate()) \overline{f\left(x\right)} sage: f = function('psi',x,y) sage: latex(f.conjugate()) \overline{\psi\left(x, y\right)} sage: x.conjugate().conjugate() x sage: x.conjugate().operator() conjugate sage: x.conjugate().operator() == conjugate True Check if #8755 is fixed:: sage: conjugate(sqrt(-3)) conjugate(sqrt(-3)) sage: conjugate(sqrt(3)) sqrt(3) sage: conjugate(sqrt(x)) conjugate(sqrt(x)) sage: conjugate(x^2) conjugate(x)^2 sage: var('y',domain='positive') y sage: conjugate(sqrt(y)) sqrt(y) Check if #10964 is fixed:: sage: z= I*sqrt(-3); z I*sqrt(-3) sage: conjugate(z) -I*conjugate(sqrt(-3)) sage: var('a') a sage: conjugate(a*sqrt(-2)*sqrt(-3)) conjugate(sqrt(-2))*conjugate(sqrt(-3))*conjugate(a) Test pickling:: sage: loads(dumps(conjugate)) conjugate<|endoftext|>
54718ff523a6564405254348d1d6e70caad6670ab08a5f01b88608e68d61fe27
def process(self, notes): 'Process `notes`, which is a dict of {title: Note} representing all of the Notes loaded by BearNotes. Do not make any changes to the Note contents, because they might be overwritten if the contents need to be fetched from Bear. Instead, save the changes, and return a dict of {Note: changed (True/False)}, or None if no changes will be made.' raise NotImplementedError('Subclasses must implement process()')
Process `notes`, which is a dict of {title: Note} representing all of the Notes loaded by BearNotes. Do not make any changes to the Note contents, because they might be overwritten if the contents need to be fetched from Bear. Instead, save the changes, and return a dict of {Note: changed (True/False)}, or None if no changes will be made.
processors/notes_processor.py
process
anjiro/bearutils
13
python
def process(self, notes): raise NotImplementedError('Subclasses must implement process()')
def process(self, notes): raise NotImplementedError('Subclasses must implement process()')<|docstring|>Process `notes`, which is a dict of {title: Note} representing all of the Notes loaded by BearNotes. Do not make any changes to the Note contents, because they might be overwritten if the contents need to be fetched from Bear. Instead, save the changes, and return a dict of {Note: changed (True/False)}, or None if no changes will be made.<|endoftext|>
feb2b8e5e7cc86aff86e5e67bfcd377d4eb1244cc07b0b3dbaba70ea77052ba4
def render(self, note): 'This will be called once for each Note that process() indicates has changed. Return the new contents of the note.' raise NotImplementedError('Subclasses must implement render()')
This will be called once for each Note that process() indicates has changed. Return the new contents of the note.
processors/notes_processor.py
render
anjiro/bearutils
13
python
def render(self, note): raise NotImplementedError('Subclasses must implement render()')
def render(self, note): raise NotImplementedError('Subclasses must implement render()')<|docstring|>This will be called once for each Note that process() indicates has changed. Return the new contents of the note.<|endoftext|>
76fb6c88d5d12e06094ffbc528498dba4c64f835a025b4166261614afdc8de70
def findCircleNum(self, M): '\n :type M: List[List[int]]\n :rtype: int\n ' class UnionFind(object): def __init__(self, n): self.set = range(n) self.count = n def find_set(self, x): if (self.set[x] != x): self.set[x] = self.find_set(self.set[x]) return self.set[x] def union_set(self, x, y): (x_root, y_root) = map(self.find_set, (x, y)) if (x_root != y_root): self.set[min(x_root, y_root)] = max(x_root, y_root) self.count -= 1 circles = UnionFind(len(M)) for i in xrange(len(M)): for j in xrange(len(M)): if (M[i][j] and (i != j)): circles.union_set(i, j) return circles.count
:type M: List[List[int]] :rtype: int
Python/friend-circles.py
findCircleNum
donaldcao/LeetCode-Solutions
3,269
python
def findCircleNum(self, M): '\n :type M: List[List[int]]\n :rtype: int\n ' class UnionFind(object): def __init__(self, n): self.set = range(n) self.count = n def find_set(self, x): if (self.set[x] != x): self.set[x] = self.find_set(self.set[x]) return self.set[x] def union_set(self, x, y): (x_root, y_root) = map(self.find_set, (x, y)) if (x_root != y_root): self.set[min(x_root, y_root)] = max(x_root, y_root) self.count -= 1 circles = UnionFind(len(M)) for i in xrange(len(M)): for j in xrange(len(M)): if (M[i][j] and (i != j)): circles.union_set(i, j) return circles.count
def findCircleNum(self, M): '\n :type M: List[List[int]]\n :rtype: int\n ' class UnionFind(object): def __init__(self, n): self.set = range(n) self.count = n def find_set(self, x): if (self.set[x] != x): self.set[x] = self.find_set(self.set[x]) return self.set[x] def union_set(self, x, y): (x_root, y_root) = map(self.find_set, (x, y)) if (x_root != y_root): self.set[min(x_root, y_root)] = max(x_root, y_root) self.count -= 1 circles = UnionFind(len(M)) for i in xrange(len(M)): for j in xrange(len(M)): if (M[i][j] and (i != j)): circles.union_set(i, j) return circles.count<|docstring|>:type M: List[List[int]] :rtype: int<|endoftext|>
9b18c36fe92e7ce72fb50979e3a693739f69c8c8b408c5a8987794243b211405
def save_model(model, dir, filename, weights_only=False): '\n Save Keras model\n :param model:\n :param dir:\n :param filename:\n :param weights_only:\n :return:\n ' if (not os.path.exists(dir)): os.makedirs(dir) filepath = os.path.join(dir, filename) if weights_only: model.save_weights(filepath) print(('Model weights were saved to: ' + filepath)) else: model.save(filepath) print(('Model was saved to: ' + filepath))
Save Keras model :param model: :param dir: :param filename: :param weights_only: :return:
utils.py
save_model
shizhan1992/distributional-robustness
0
python
def save_model(model, dir, filename, weights_only=False): '\n Save Keras model\n :param model:\n :param dir:\n :param filename:\n :param weights_only:\n :return:\n ' if (not os.path.exists(dir)): os.makedirs(dir) filepath = os.path.join(dir, filename) if weights_only: model.save_weights(filepath) print(('Model weights were saved to: ' + filepath)) else: model.save(filepath) print(('Model was saved to: ' + filepath))
def save_model(model, dir, filename, weights_only=False): '\n Save Keras model\n :param model:\n :param dir:\n :param filename:\n :param weights_only:\n :return:\n ' if (not os.path.exists(dir)): os.makedirs(dir) filepath = os.path.join(dir, filename) if weights_only: model.save_weights(filepath) print(('Model weights were saved to: ' + filepath)) else: model.save(filepath) print(('Model was saved to: ' + filepath))<|docstring|>Save Keras model :param model: :param dir: :param filename: :param weights_only: :return:<|endoftext|>
14fe853d89c884379df2db1f6a4771785eaa9c7136f34647b5d87786cccf6509
def load_model(directory, filename, weights_only=False, model=None): '\n Loads Keras model\n :param directory:\n :param filename:\n :return:\n ' if weights_only: assert (model is not None) filepath = os.path.join(directory, filename) assert os.path.exists(filepath) if weights_only: result = model.load_weights(filepath) print(result) return model.load_weights(filepath) else: return tensorflow.python.keras.models.load_model(filepath)
Loads Keras model :param directory: :param filename: :return:
utils.py
load_model
shizhan1992/distributional-robustness
0
python
def load_model(directory, filename, weights_only=False, model=None): '\n Loads Keras model\n :param directory:\n :param filename:\n :return:\n ' if weights_only: assert (model is not None) filepath = os.path.join(directory, filename) assert os.path.exists(filepath) if weights_only: result = model.load_weights(filepath) print(result) return model.load_weights(filepath) else: return tensorflow.python.keras.models.load_model(filepath)
def load_model(directory, filename, weights_only=False, model=None): '\n Loads Keras model\n :param directory:\n :param filename:\n :return:\n ' if weights_only: assert (model is not None) filepath = os.path.join(directory, filename) assert os.path.exists(filepath) if weights_only: result = model.load_weights(filepath) print(result) return model.load_weights(filepath) else: return tensorflow.python.keras.models.load_model(filepath)<|docstring|>Loads Keras model :param directory: :param filename: :return:<|endoftext|>
4dd024f98b94d05c74d17086f08e5da7ff7fe79e5c03257940aa5d16c4184976
def batch_indices(batch_nb, data_length, batch_size): '\n This helper function computes a batch start and end index\n :param batch_nb: the batch number\n :param data_length: the total length of the data being parsed by batches\n :param batch_size: the number of inputs in each batch\n :return: pair of (start, end) indices\n ' start = int((batch_nb * batch_size)) end = int(((batch_nb + 1) * batch_size)) if (end > data_length): shift = (end - data_length) start -= shift end -= shift return (start, end)
This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (start, end) indices
utils.py
batch_indices
shizhan1992/distributional-robustness
0
python
def batch_indices(batch_nb, data_length, batch_size): '\n This helper function computes a batch start and end index\n :param batch_nb: the batch number\n :param data_length: the total length of the data being parsed by batches\n :param batch_size: the number of inputs in each batch\n :return: pair of (start, end) indices\n ' start = int((batch_nb * batch_size)) end = int(((batch_nb + 1) * batch_size)) if (end > data_length): shift = (end - data_length) start -= shift end -= shift return (start, end)
def batch_indices(batch_nb, data_length, batch_size): '\n This helper function computes a batch start and end index\n :param batch_nb: the batch number\n :param data_length: the total length of the data being parsed by batches\n :param batch_size: the number of inputs in each batch\n :return: pair of (start, end) indices\n ' start = int((batch_nb * batch_size)) end = int(((batch_nb + 1) * batch_size)) if (end > data_length): shift = (end - data_length) start -= shift end -= shift return (start, end)<|docstring|>This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (start, end) indices<|endoftext|>
7bd526999695f436cc5df2f43d9eb3601cccb4fc075af13271de904b9dbd4ea1
def other_classes(nb_classes, class_ind): '\n Heper function that returns a list of class indices without one class\n :param nb_classes: number of classes in total\n :param class_ind: the class index to be omitted\n :return: list of class indices without one class\n ' other_classes_list = list(range(nb_classes)) other_classes_list.remove(class_ind) return other_classes_list
Heper function that returns a list of class indices without one class :param nb_classes: number of classes in total :param class_ind: the class index to be omitted :return: list of class indices without one class
utils.py
other_classes
shizhan1992/distributional-robustness
0
python
def other_classes(nb_classes, class_ind): '\n Heper function that returns a list of class indices without one class\n :param nb_classes: number of classes in total\n :param class_ind: the class index to be omitted\n :return: list of class indices without one class\n ' other_classes_list = list(range(nb_classes)) other_classes_list.remove(class_ind) return other_classes_list
def other_classes(nb_classes, class_ind): '\n Heper function that returns a list of class indices without one class\n :param nb_classes: number of classes in total\n :param class_ind: the class index to be omitted\n :return: list of class indices without one class\n ' other_classes_list = list(range(nb_classes)) other_classes_list.remove(class_ind) return other_classes_list<|docstring|>Heper function that returns a list of class indices without one class :param nb_classes: number of classes in total :param class_ind: the class index to be omitted :return: list of class indices without one class<|endoftext|>
bc2bb11e3f00c51d234554d00a08169ac194bdb1574f44b513fd5f6f9290fbd1
def random_targets(gt, nb_classes): '\n Take in the correct labels for each sample and randomly choose target\n labels from the others\n :param gt: the correct labels\n :param nb_classes: The number of classes for this model\n :return: A numpy array holding the randomly-selected target classes\n ' if (len(gt.shape) > 1): gt = np.argmax(gt, axis=1) result = np.zeros(gt.shape) for class_ind in range(nb_classes): in_cl = (gt == class_ind) result[in_cl] = np.random.choice(other_classes(nb_classes, class_ind)) return to_categorical(np.asarray(result), nb_classes)
Take in the correct labels for each sample and randomly choose target labels from the others :param gt: the correct labels :param nb_classes: The number of classes for this model :return: A numpy array holding the randomly-selected target classes
utils.py
random_targets
shizhan1992/distributional-robustness
0
python
def random_targets(gt, nb_classes): '\n Take in the correct labels for each sample and randomly choose target\n labels from the others\n :param gt: the correct labels\n :param nb_classes: The number of classes for this model\n :return: A numpy array holding the randomly-selected target classes\n ' if (len(gt.shape) > 1): gt = np.argmax(gt, axis=1) result = np.zeros(gt.shape) for class_ind in range(nb_classes): in_cl = (gt == class_ind) result[in_cl] = np.random.choice(other_classes(nb_classes, class_ind)) return to_categorical(np.asarray(result), nb_classes)
def random_targets(gt, nb_classes): '\n Take in the correct labels for each sample and randomly choose target\n labels from the others\n :param gt: the correct labels\n :param nb_classes: The number of classes for this model\n :return: A numpy array holding the randomly-selected target classes\n ' if (len(gt.shape) > 1): gt = np.argmax(gt, axis=1) result = np.zeros(gt.shape) for class_ind in range(nb_classes): in_cl = (gt == class_ind) result[in_cl] = np.random.choice(other_classes(nb_classes, class_ind)) return to_categorical(np.asarray(result), nb_classes)<|docstring|>Take in the correct labels for each sample and randomly choose target labels from the others :param gt: the correct labels :param nb_classes: The number of classes for this model :return: A numpy array holding the randomly-selected target classes<|endoftext|>
f1b20d6a81d488fa4003ef86a20632d1ad97200592d90d695acd3ed2bd96cb40
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28, reg_scale=0.1, channels=1, nb_filters=64, nb_classes=10, activation='none', name='cnn'): '\n Defines a CNN model using Keras sequential model\n :param logits: If set to False, returns a Keras model, otherwise will also\n return logits tensor\n :param input_ph: The TensorFlow tensor for the input\n (needed if returning logits)\n ("ph" stands for placeholder but it need not actually be a\n placeholder)\n :param img_rows: number of row in the image\n :param img_cols: number of columns in the image\n :param channels: number of color channels (e.g., 1 for MNIST)\n :param nb_filters: number of convolutional filters per layer\n :param nb_classes: the number of output classes\n :return:\n ' model = Sequential(name=name) input_shape = (img_rows, img_cols, channels) input_shape1 = ([1] + list(input_shape)) output_shape = [1, ceil((img_rows / 2)), ceil((img_cols / 2)), nb_filters] layer_one_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='same', input_shape=input_shape1, output_shape=output_shape, weight_name='conv1') input_shape1 = output_shape output_shape = [1, ceil(((input_shape1[1] - ((6 - 1) * 1)) / 2)), ceil(((input_shape1[1] - ((6 - 1) * 1)) / 2)), (nb_filters * 2)] layer_two_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='valid', input_shape=input_shape1, output_shape=output_shape, weight_name='conv2') input_shape1 = output_shape output_shape = [1, ceil(((input_shape1[1] - ((5 - 1) * 1)) / 1)), ceil(((input_shape1[1] - ((5 - 1) * 1)) / 1)), (nb_filters * 2)] layer_three_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='valid', input_shape=input_shape1, output_shape=output_shape, weight_name='conv3') layers = [Conv2D(filters=nb_filters, kernel_size=(8, 8), strides=(2, 2), padding='same', input_shape=input_shape, name='conv1', kernel_regularizer=layer_one_reg), Activation(activation), Conv2D(filters=(nb_filters * 2), kernel_size=(6, 6), strides=(2, 2), padding='valid', name='conv2', kernel_regularizer=layer_two_reg), Activation(activation), Conv2D(filters=(nb_filters * 2), kernel_size=(5, 5), strides=(1, 1), padding='valid', name='conv3', kernel_regularizer=layer_three_reg), Activation(activation), Flatten(), Dense(nb_classes, name='dense1', kernel_regularizer=spectral_regularizer(scale=reg_scale, weight_name='dense', conv=False))] for layer in layers: model.add(layer) if logits: logits_tensor = model(input_ph) if logits: return (model, logits_tensor) else: return model
Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: The TensorFlow tensor for the input (needed if returning logits) ("ph" stands for placeholder but it need not actually be a placeholder) :param img_rows: number of row in the image :param img_cols: number of columns in the image :param channels: number of color channels (e.g., 1 for MNIST) :param nb_filters: number of convolutional filters per layer :param nb_classes: the number of output classes :return:
utils.py
cnn_model
shizhan1992/distributional-robustness
0
python
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28, reg_scale=0.1, channels=1, nb_filters=64, nb_classes=10, activation='none', name='cnn'): '\n Defines a CNN model using Keras sequential model\n :param logits: If set to False, returns a Keras model, otherwise will also\n return logits tensor\n :param input_ph: The TensorFlow tensor for the input\n (needed if returning logits)\n ("ph" stands for placeholder but it need not actually be a\n placeholder)\n :param img_rows: number of row in the image\n :param img_cols: number of columns in the image\n :param channels: number of color channels (e.g., 1 for MNIST)\n :param nb_filters: number of convolutional filters per layer\n :param nb_classes: the number of output classes\n :return:\n ' model = Sequential(name=name) input_shape = (img_rows, img_cols, channels) input_shape1 = ([1] + list(input_shape)) output_shape = [1, ceil((img_rows / 2)), ceil((img_cols / 2)), nb_filters] layer_one_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='same', input_shape=input_shape1, output_shape=output_shape, weight_name='conv1') input_shape1 = output_shape output_shape = [1, ceil(((input_shape1[1] - ((6 - 1) * 1)) / 2)), ceil(((input_shape1[1] - ((6 - 1) * 1)) / 2)), (nb_filters * 2)] layer_two_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='valid', input_shape=input_shape1, output_shape=output_shape, weight_name='conv2') input_shape1 = output_shape output_shape = [1, ceil(((input_shape1[1] - ((5 - 1) * 1)) / 1)), ceil(((input_shape1[1] - ((5 - 1) * 1)) / 1)), (nb_filters * 2)] layer_three_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='valid', input_shape=input_shape1, output_shape=output_shape, weight_name='conv3') layers = [Conv2D(filters=nb_filters, kernel_size=(8, 8), strides=(2, 2), padding='same', input_shape=input_shape, name='conv1', kernel_regularizer=layer_one_reg), Activation(activation), Conv2D(filters=(nb_filters * 2), kernel_size=(6, 6), strides=(2, 2), padding='valid', name='conv2', kernel_regularizer=layer_two_reg), Activation(activation), Conv2D(filters=(nb_filters * 2), kernel_size=(5, 5), strides=(1, 1), padding='valid', name='conv3', kernel_regularizer=layer_three_reg), Activation(activation), Flatten(), Dense(nb_classes, name='dense1', kernel_regularizer=spectral_regularizer(scale=reg_scale, weight_name='dense', conv=False))] for layer in layers: model.add(layer) if logits: logits_tensor = model(input_ph) if logits: return (model, logits_tensor) else: return model
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28, reg_scale=0.1, channels=1, nb_filters=64, nb_classes=10, activation='none', name='cnn'): '\n Defines a CNN model using Keras sequential model\n :param logits: If set to False, returns a Keras model, otherwise will also\n return logits tensor\n :param input_ph: The TensorFlow tensor for the input\n (needed if returning logits)\n ("ph" stands for placeholder but it need not actually be a\n placeholder)\n :param img_rows: number of row in the image\n :param img_cols: number of columns in the image\n :param channels: number of color channels (e.g., 1 for MNIST)\n :param nb_filters: number of convolutional filters per layer\n :param nb_classes: the number of output classes\n :return:\n ' model = Sequential(name=name) input_shape = (img_rows, img_cols, channels) input_shape1 = ([1] + list(input_shape)) output_shape = [1, ceil((img_rows / 2)), ceil((img_cols / 2)), nb_filters] layer_one_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='same', input_shape=input_shape1, output_shape=output_shape, weight_name='conv1') input_shape1 = output_shape output_shape = [1, ceil(((input_shape1[1] - ((6 - 1) * 1)) / 2)), ceil(((input_shape1[1] - ((6 - 1) * 1)) / 2)), (nb_filters * 2)] layer_two_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='valid', input_shape=input_shape1, output_shape=output_shape, weight_name='conv2') input_shape1 = output_shape output_shape = [1, ceil(((input_shape1[1] - ((5 - 1) * 1)) / 1)), ceil(((input_shape1[1] - ((5 - 1) * 1)) / 1)), (nb_filters * 2)] layer_three_reg = spectral_regularizer(scale=reg_scale, strides=2, padding='valid', input_shape=input_shape1, output_shape=output_shape, weight_name='conv3') layers = [Conv2D(filters=nb_filters, kernel_size=(8, 8), strides=(2, 2), padding='same', input_shape=input_shape, name='conv1', kernel_regularizer=layer_one_reg), Activation(activation), Conv2D(filters=(nb_filters * 2), kernel_size=(6, 6), strides=(2, 2), padding='valid', name='conv2', kernel_regularizer=layer_two_reg), Activation(activation), Conv2D(filters=(nb_filters * 2), kernel_size=(5, 5), strides=(1, 1), padding='valid', name='conv3', kernel_regularizer=layer_three_reg), Activation(activation), Flatten(), Dense(nb_classes, name='dense1', kernel_regularizer=spectral_regularizer(scale=reg_scale, weight_name='dense', conv=False))] for layer in layers: model.add(layer) if logits: logits_tensor = model(input_ph) if logits: return (model, logits_tensor) else: return model<|docstring|>Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: The TensorFlow tensor for the input (needed if returning logits) ("ph" stands for placeholder but it need not actually be a placeholder) :param img_rows: number of row in the image :param img_cols: number of columns in the image :param channels: number of color channels (e.g., 1 for MNIST) :param nb_filters: number of convolutional filters per layer :param nb_classes: the number of output classes :return:<|endoftext|>
e52d09e5f26f08beaffc13360f5676607d10c8b5333a313039afd6f9ff9c00b2
def spectral_regularizer(scale=0.5, strides=None, padding=None, input_shape=None, output_shape=None, num_iter=10, weight_name=None, method='power', conv=True, scope=None): 'Returns a function that can be used to apply spectral norm regularization to weights.\n Args:\n scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.\n scope: An optional scope name.\n method: method to compute spectral norm: svd or power iteration (default)\n Returns:\n A function with signature `spectral_norm(weights)` that apply spectral norm regularization.\n Raises:\n ValueError: If scale is negative or if scale is not a float.\n ' if (scale < 0.0): raise ValueError(('Setting a scale less than 0 on a regularizer: %g' % scale)) if (scale == 0.0): logging.info('Scale of 0 disables regularizer.') return (lambda _: None) def spectral_norm(weights, name=None): 'Applies spectral_norm regularization to weights.' with ops.name_scope(scope, 'spectral_regularizer', [weights]) as name: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') if (method == 'power'): if conv: s = power_iterate_conv(weights=weights, strides=strides, padding=padding.upper(), input_shape=input_shape, output_shape=output_shape, num_iter=num_iter, weight_name=weight_name) else: s = power_iterate(weights=weights, num_iter=num_iter, weight_name=weight_name) return standard_ops.multiply(my_scale, s, name=name) else: return standard_ops.multiply(my_scale, standard_ops.svd(weights, compute_uv=False)[(..., 0)], name=name) return spectral_norm
Returns a function that can be used to apply spectral norm regularization to weights. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. scope: An optional scope name. method: method to compute spectral norm: svd or power iteration (default) Returns: A function with signature `spectral_norm(weights)` that apply spectral norm regularization. Raises: ValueError: If scale is negative or if scale is not a float.
utils.py
spectral_regularizer
shizhan1992/distributional-robustness
0
python
def spectral_regularizer(scale=0.5, strides=None, padding=None, input_shape=None, output_shape=None, num_iter=10, weight_name=None, method='power', conv=True, scope=None): 'Returns a function that can be used to apply spectral norm regularization to weights.\n Args:\n scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.\n scope: An optional scope name.\n method: method to compute spectral norm: svd or power iteration (default)\n Returns:\n A function with signature `spectral_norm(weights)` that apply spectral norm regularization.\n Raises:\n ValueError: If scale is negative or if scale is not a float.\n ' if (scale < 0.0): raise ValueError(('Setting a scale less than 0 on a regularizer: %g' % scale)) if (scale == 0.0): logging.info('Scale of 0 disables regularizer.') return (lambda _: None) def spectral_norm(weights, name=None): 'Applies spectral_norm regularization to weights.' with ops.name_scope(scope, 'spectral_regularizer', [weights]) as name: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') if (method == 'power'): if conv: s = power_iterate_conv(weights=weights, strides=strides, padding=padding.upper(), input_shape=input_shape, output_shape=output_shape, num_iter=num_iter, weight_name=weight_name) else: s = power_iterate(weights=weights, num_iter=num_iter, weight_name=weight_name) return standard_ops.multiply(my_scale, s, name=name) else: return standard_ops.multiply(my_scale, standard_ops.svd(weights, compute_uv=False)[(..., 0)], name=name) return spectral_norm
def spectral_regularizer(scale=0.5, strides=None, padding=None, input_shape=None, output_shape=None, num_iter=10, weight_name=None, method='power', conv=True, scope=None): 'Returns a function that can be used to apply spectral norm regularization to weights.\n Args:\n scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.\n scope: An optional scope name.\n method: method to compute spectral norm: svd or power iteration (default)\n Returns:\n A function with signature `spectral_norm(weights)` that apply spectral norm regularization.\n Raises:\n ValueError: If scale is negative or if scale is not a float.\n ' if (scale < 0.0): raise ValueError(('Setting a scale less than 0 on a regularizer: %g' % scale)) if (scale == 0.0): logging.info('Scale of 0 disables regularizer.') return (lambda _: None) def spectral_norm(weights, name=None): 'Applies spectral_norm regularization to weights.' with ops.name_scope(scope, 'spectral_regularizer', [weights]) as name: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') if (method == 'power'): if conv: s = power_iterate_conv(weights=weights, strides=strides, padding=padding.upper(), input_shape=input_shape, output_shape=output_shape, num_iter=num_iter, weight_name=weight_name) else: s = power_iterate(weights=weights, num_iter=num_iter, weight_name=weight_name) return standard_ops.multiply(my_scale, s, name=name) else: return standard_ops.multiply(my_scale, standard_ops.svd(weights, compute_uv=False)[(..., 0)], name=name) return spectral_norm<|docstring|>Returns a function that can be used to apply spectral norm regularization to weights. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. scope: An optional scope name. method: method to compute spectral norm: svd or power iteration (default) Returns: A function with signature `spectral_norm(weights)` that apply spectral norm regularization. Raises: ValueError: If scale is negative or if scale is not a float.<|endoftext|>
7763c9963687951b57d1bc41a86ffeae28ec7cdd57645f85ed799d6183d112da
def power_iterate_conv(weights, strides, padding, input_shape, output_shape, num_iter, weight_name, u=None): 'Perform power iteration for a convolutional layer.' strides = [1, strides, strides, 1] with tf.name_scope(None, default_name='power_iteration_conv'): with tf.variable_scope(weight_name, reuse=tf.AUTO_REUSE): u_var = tf.get_variable('u_conv', ([1] + list(output_shape[1:])), initializer=tf.random_normal_initializer(), trainable=False) u = u_var v = None for _ in range(num_iter): v = tf.nn.conv2d_transpose(u, weights, ([1] + list(input_shape[1:])), strides, padding) v /= tf.sqrt(tf.maximum((2 * tf.nn.l2_loss(v)), 1e-12)) u = tf.nn.conv2d(v, weights, strides, padding) u /= tf.sqrt(tf.maximum((2 * tf.nn.l2_loss(u)), 1e-12)) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, tf.assign(u_var, u)) return tf.reduce_sum((u * tf.nn.conv2d(v, weights, strides, padding)))
Perform power iteration for a convolutional layer.
utils.py
power_iterate_conv
shizhan1992/distributional-robustness
0
python
def power_iterate_conv(weights, strides, padding, input_shape, output_shape, num_iter, weight_name, u=None): strides = [1, strides, strides, 1] with tf.name_scope(None, default_name='power_iteration_conv'): with tf.variable_scope(weight_name, reuse=tf.AUTO_REUSE): u_var = tf.get_variable('u_conv', ([1] + list(output_shape[1:])), initializer=tf.random_normal_initializer(), trainable=False) u = u_var v = None for _ in range(num_iter): v = tf.nn.conv2d_transpose(u, weights, ([1] + list(input_shape[1:])), strides, padding) v /= tf.sqrt(tf.maximum((2 * tf.nn.l2_loss(v)), 1e-12)) u = tf.nn.conv2d(v, weights, strides, padding) u /= tf.sqrt(tf.maximum((2 * tf.nn.l2_loss(u)), 1e-12)) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, tf.assign(u_var, u)) return tf.reduce_sum((u * tf.nn.conv2d(v, weights, strides, padding)))
def power_iterate_conv(weights, strides, padding, input_shape, output_shape, num_iter, weight_name, u=None): strides = [1, strides, strides, 1] with tf.name_scope(None, default_name='power_iteration_conv'): with tf.variable_scope(weight_name, reuse=tf.AUTO_REUSE): u_var = tf.get_variable('u_conv', ([1] + list(output_shape[1:])), initializer=tf.random_normal_initializer(), trainable=False) u = u_var v = None for _ in range(num_iter): v = tf.nn.conv2d_transpose(u, weights, ([1] + list(input_shape[1:])), strides, padding) v /= tf.sqrt(tf.maximum((2 * tf.nn.l2_loss(v)), 1e-12)) u = tf.nn.conv2d(v, weights, strides, padding) u /= tf.sqrt(tf.maximum((2 * tf.nn.l2_loss(u)), 1e-12)) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, tf.assign(u_var, u)) return tf.reduce_sum((u * tf.nn.conv2d(v, weights, strides, padding)))<|docstring|>Perform power iteration for a convolutional layer.<|endoftext|>
3697943f8165fc95153707f9e14b7ed7515bc2c62b29417b4a04c4bb6a2f65d3
def power_iterate(weights, num_iter, weight_name): 'Perform power iteration for a dense layer.' with tf.name_scope(None, default_name='power_iteration'): w_shape = weights.shape.as_list() w = tf.reshape(weights, [(- 1), w_shape[(- 1)]]) with tf.variable_scope(weight_name, reuse=tf.AUTO_REUSE): u_var = tf.get_variable('u', [1, w_shape[(- 1)]], initializer=tf.truncated_normal_initializer(), trainable=False) u = u_var v = None for i in range(num_iter): v = tf.matmul(u, tf.transpose(w)) v /= ((tf.reduce_sum((v ** 2)) ** 0.5) + 1e-12) u = tf.matmul(v, w) u /= ((tf.reduce_sum((u ** 2)) ** 0.5) + 1e-12) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, tf.assign(u_var, u)) sigma = tf.reduce_sum((tf.matmul(v, w) * tf.transpose(u))) return sigma
Perform power iteration for a dense layer.
utils.py
power_iterate
shizhan1992/distributional-robustness
0
python
def power_iterate(weights, num_iter, weight_name): with tf.name_scope(None, default_name='power_iteration'): w_shape = weights.shape.as_list() w = tf.reshape(weights, [(- 1), w_shape[(- 1)]]) with tf.variable_scope(weight_name, reuse=tf.AUTO_REUSE): u_var = tf.get_variable('u', [1, w_shape[(- 1)]], initializer=tf.truncated_normal_initializer(), trainable=False) u = u_var v = None for i in range(num_iter): v = tf.matmul(u, tf.transpose(w)) v /= ((tf.reduce_sum((v ** 2)) ** 0.5) + 1e-12) u = tf.matmul(v, w) u /= ((tf.reduce_sum((u ** 2)) ** 0.5) + 1e-12) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, tf.assign(u_var, u)) sigma = tf.reduce_sum((tf.matmul(v, w) * tf.transpose(u))) return sigma
def power_iterate(weights, num_iter, weight_name): with tf.name_scope(None, default_name='power_iteration'): w_shape = weights.shape.as_list() w = tf.reshape(weights, [(- 1), w_shape[(- 1)]]) with tf.variable_scope(weight_name, reuse=tf.AUTO_REUSE): u_var = tf.get_variable('u', [1, w_shape[(- 1)]], initializer=tf.truncated_normal_initializer(), trainable=False) u = u_var v = None for i in range(num_iter): v = tf.matmul(u, tf.transpose(w)) v /= ((tf.reduce_sum((v ** 2)) ** 0.5) + 1e-12) u = tf.matmul(v, w) u /= ((tf.reduce_sum((u ** 2)) ** 0.5) + 1e-12) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, tf.assign(u_var, u)) sigma = tf.reduce_sum((tf.matmul(v, w) * tf.transpose(u))) return sigma<|docstring|>Perform power iteration for a dense layer.<|endoftext|>
300108e6b6d905c933453aec62e9eb8c66408b7845f820638e5831177ef047e4
def spectral_norm(weights, name=None): 'Applies spectral_norm regularization to weights.' with ops.name_scope(scope, 'spectral_regularizer', [weights]) as name: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') if (method == 'power'): if conv: s = power_iterate_conv(weights=weights, strides=strides, padding=padding.upper(), input_shape=input_shape, output_shape=output_shape, num_iter=num_iter, weight_name=weight_name) else: s = power_iterate(weights=weights, num_iter=num_iter, weight_name=weight_name) return standard_ops.multiply(my_scale, s, name=name) else: return standard_ops.multiply(my_scale, standard_ops.svd(weights, compute_uv=False)[(..., 0)], name=name)
Applies spectral_norm regularization to weights.
utils.py
spectral_norm
shizhan1992/distributional-robustness
0
python
def spectral_norm(weights, name=None): with ops.name_scope(scope, 'spectral_regularizer', [weights]) as name: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') if (method == 'power'): if conv: s = power_iterate_conv(weights=weights, strides=strides, padding=padding.upper(), input_shape=input_shape, output_shape=output_shape, num_iter=num_iter, weight_name=weight_name) else: s = power_iterate(weights=weights, num_iter=num_iter, weight_name=weight_name) return standard_ops.multiply(my_scale, s, name=name) else: return standard_ops.multiply(my_scale, standard_ops.svd(weights, compute_uv=False)[(..., 0)], name=name)
def spectral_norm(weights, name=None): with ops.name_scope(scope, 'spectral_regularizer', [weights]) as name: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') if (method == 'power'): if conv: s = power_iterate_conv(weights=weights, strides=strides, padding=padding.upper(), input_shape=input_shape, output_shape=output_shape, num_iter=num_iter, weight_name=weight_name) else: s = power_iterate(weights=weights, num_iter=num_iter, weight_name=weight_name) return standard_ops.multiply(my_scale, s, name=name) else: return standard_ops.multiply(my_scale, standard_ops.svd(weights, compute_uv=False)[(..., 0)], name=name)<|docstring|>Applies spectral_norm regularization to weights.<|endoftext|>
096e2b0330b958cc8f6a0d8caeca22f984c5642cb0ad2b2c76dbb6ace4fc0756
@contextmanager def Logs(): 'ClickHouse and ODBC driver logs context manager.\n ' class _Logs(): def __init__(self, *args): self.logs = args def read(self, timeout=None): for l in self.logs: l.readlines(timeout=timeout) if (not settings.debug): (yield None) else: with Shell(name='clickhouse-server.log') as bash0, Shell(name='odbc-driver-trace.log') as bash1, Shell(name='odbc-driver-w-trace.log') as bash2, Shell(name='odbc-manager-trace.log') as bash3: bash1(f'touch {odbc_driver_trace_log_path}') bash2(f'touch {odbc_driver_w_trace_log_path}') bash3(f'touch {odbc_manager_trace_log_path}') with bash0(f'tail -f {clickhouse_log_path}', asyncronous=True, name='') as clickhouse_log, bash1(f'tail -f {odbc_driver_trace_log_path}', asyncronous=True, name='') as odbc_driver_log, bash2(f'tail -f {odbc_driver_w_trace_log_path}', asyncronous=True, name='') as odbc_driver_w_log, bash3(f'tail -f {odbc_manager_trace_log_path}', asyncronous=True, name='') as odbc_manager_log: logs = _Logs(clickhouse_log, odbc_driver_log, odbc_driver_w_log, odbc_manager_log) logs.read() (yield logs)
ClickHouse and ODBC driver logs context manager.
test/parameterized/utils/utils.py
Logs
MinimaJack/clickhouse-odbc
122
python
@contextmanager def Logs(): '\n ' class _Logs(): def __init__(self, *args): self.logs = args def read(self, timeout=None): for l in self.logs: l.readlines(timeout=timeout) if (not settings.debug): (yield None) else: with Shell(name='clickhouse-server.log') as bash0, Shell(name='odbc-driver-trace.log') as bash1, Shell(name='odbc-driver-w-trace.log') as bash2, Shell(name='odbc-manager-trace.log') as bash3: bash1(f'touch {odbc_driver_trace_log_path}') bash2(f'touch {odbc_driver_w_trace_log_path}') bash3(f'touch {odbc_manager_trace_log_path}') with bash0(f'tail -f {clickhouse_log_path}', asyncronous=True, name=) as clickhouse_log, bash1(f'tail -f {odbc_driver_trace_log_path}', asyncronous=True, name=) as odbc_driver_log, bash2(f'tail -f {odbc_driver_w_trace_log_path}', asyncronous=True, name=) as odbc_driver_w_log, bash3(f'tail -f {odbc_manager_trace_log_path}', asyncronous=True, name=) as odbc_manager_log: logs = _Logs(clickhouse_log, odbc_driver_log, odbc_driver_w_log, odbc_manager_log) logs.read() (yield logs)
@contextmanager def Logs(): '\n ' class _Logs(): def __init__(self, *args): self.logs = args def read(self, timeout=None): for l in self.logs: l.readlines(timeout=timeout) if (not settings.debug): (yield None) else: with Shell(name='clickhouse-server.log') as bash0, Shell(name='odbc-driver-trace.log') as bash1, Shell(name='odbc-driver-w-trace.log') as bash2, Shell(name='odbc-manager-trace.log') as bash3: bash1(f'touch {odbc_driver_trace_log_path}') bash2(f'touch {odbc_driver_w_trace_log_path}') bash3(f'touch {odbc_manager_trace_log_path}') with bash0(f'tail -f {clickhouse_log_path}', asyncronous=True, name=) as clickhouse_log, bash1(f'tail -f {odbc_driver_trace_log_path}', asyncronous=True, name=) as odbc_driver_log, bash2(f'tail -f {odbc_driver_w_trace_log_path}', asyncronous=True, name=) as odbc_driver_w_log, bash3(f'tail -f {odbc_manager_trace_log_path}', asyncronous=True, name=) as odbc_manager_log: logs = _Logs(clickhouse_log, odbc_driver_log, odbc_driver_w_log, odbc_manager_log) logs.read() (yield logs)<|docstring|>ClickHouse and ODBC driver logs context manager.<|endoftext|>
8e455440d40300145cc5399087d5d95c0dc77ff3fed3e02aa0f52b20449f94cd
@contextmanager def PyODBCConnection(encoding='utf-8', logs=None): 'PyODBC connector context manager.\n ' dsn = os.getenv('DSN', 'ClickHouse DSN (ANSI)') note(f'Using DNS={dsn}') connection = pyodbc.connect(f'DSN={dsn};') try: class _Connection(): def __init__(self, connection, encoding, logs=None): self.connection = connection self.logs = logs self.encoding = encoding self.connection.setencoding(encoding=self.encoding) if self.logs: self.logs.read() def query(self, q, params=[], fetch=True): try: note(f'query: {q}') cursor = self.connection.cursor() cursor.execute(q, *params) if fetch: rows = cursor.fetchall() for row in rows: note(row) return rows except pyodbc.Error as exc: exception() fail(str(exc)) finally: if (self.logs and settings.debug): time.sleep(0.5) self.logs.read(timeout=0.1) (yield _Connection(connection, encoding, logs=logs)) finally: connection.close()
PyODBC connector context manager.
test/parameterized/utils/utils.py
PyODBCConnection
MinimaJack/clickhouse-odbc
122
python
@contextmanager def PyODBCConnection(encoding='utf-8', logs=None): '\n ' dsn = os.getenv('DSN', 'ClickHouse DSN (ANSI)') note(f'Using DNS={dsn}') connection = pyodbc.connect(f'DSN={dsn};') try: class _Connection(): def __init__(self, connection, encoding, logs=None): self.connection = connection self.logs = logs self.encoding = encoding self.connection.setencoding(encoding=self.encoding) if self.logs: self.logs.read() def query(self, q, params=[], fetch=True): try: note(f'query: {q}') cursor = self.connection.cursor() cursor.execute(q, *params) if fetch: rows = cursor.fetchall() for row in rows: note(row) return rows except pyodbc.Error as exc: exception() fail(str(exc)) finally: if (self.logs and settings.debug): time.sleep(0.5) self.logs.read(timeout=0.1) (yield _Connection(connection, encoding, logs=logs)) finally: connection.close()
@contextmanager def PyODBCConnection(encoding='utf-8', logs=None): '\n ' dsn = os.getenv('DSN', 'ClickHouse DSN (ANSI)') note(f'Using DNS={dsn}') connection = pyodbc.connect(f'DSN={dsn};') try: class _Connection(): def __init__(self, connection, encoding, logs=None): self.connection = connection self.logs = logs self.encoding = encoding self.connection.setencoding(encoding=self.encoding) if self.logs: self.logs.read() def query(self, q, params=[], fetch=True): try: note(f'query: {q}') cursor = self.connection.cursor() cursor.execute(q, *params) if fetch: rows = cursor.fetchall() for row in rows: note(row) return rows except pyodbc.Error as exc: exception() fail(str(exc)) finally: if (self.logs and settings.debug): time.sleep(0.5) self.logs.read(timeout=0.1) (yield _Connection(connection, encoding, logs=logs)) finally: connection.close()<|docstring|>PyODBC connector context manager.<|endoftext|>
9e07b9728d72b46b116df234eddb3d2c621df330aefbc1df76db97ac3cf38c15
def extend_pandas(): "\n extends pandas by exposing methods to be used like:\n df.sharpe(), df.best('day'), ...\n " from pandas.core.base import PandasObject as _po _po.compsum = stats.compsum _po.comp = stats.comp _po.expected_return = stats.expected_return _po.geometric_mean = stats.geometric_mean _po.ghpr = stats.ghpr _po.outliers = stats.outliers _po.remove_outliers = stats.remove_outliers _po.best = stats.best _po.worst = stats.worst _po.consecutive_wins = stats.consecutive_wins _po.consecutive_losses = stats.consecutive_losses _po.exposure = stats.exposure _po.win_rate = stats.win_rate _po.avg_return = stats.avg_return _po.avg_win = stats.avg_win _po.avg_loss = stats.avg_loss _po.volatility = stats.volatility _po.implied_volatility = stats.implied_volatility _po.sharpe = stats.sharpe _po.sortino = stats.sortino _po.cagr = stats.cagr _po.rar = stats.rar _po.skew = stats.skew _po.kurtosis = stats.kurtosis _po.calmar = stats.calmar _po.ulcer_index = stats.ulcer_index _po.ulcer_performance_index = stats.ulcer_performance_index _po.upi = stats.upi _po.risk_of_ruin = stats.risk_of_ruin _po.ror = stats.ror _po.value_at_risk = stats.value_at_risk _po.var = stats.var _po.conditional_value_at_risk = stats.conditional_value_at_risk _po.cvar = stats.cvar _po.expected_shortfall = stats.expected_shortfall _po.tail_ratio = stats.tail_ratio _po.payoff_ratio = stats.payoff_ratio _po.win_loss_ratio = stats.win_loss_ratio _po.profit_ratio = stats.profit_ratio _po.profit_factor = stats.profit_factor _po.gain_to_pain_ratio = stats.gain_to_pain_ratio _po.cpc_index = stats.cpc_index _po.common_sense_ratio = stats.common_sense_ratio _po.outlier_win_ratio = stats.outlier_win_ratio _po.outlier_loss_ratio = stats.outlier_loss_ratio _po.recovery_factor = stats.recovery_factor _po.risk_return_ratio = stats.risk_return_ratio _po.max_drawdown = stats.max_drawdown _po.to_drawdown_series = stats.to_drawdown_series _po.kelly_criterion = stats.kelly_criterion _po.monthly_returns = stats.monthly_returns _po.pct_rank = stats.pct_rank _po.to_returns = utils.to_returns _po.to_prices = utils.to_prices _po.to_log_returns = utils.to_log_returns _po.log_returns = utils.log_returns _po.exponential_stdev = utils.exponential_stdev _po.rebase = utils.rebase _po.aggregate_returns = utils.aggregate_returns _po.to_excess_returns = utils.to_excess_returns _po.multi_shift = utils.multi_shift _po.curr_month = utils._pandas_current_month _po.date = utils._pandas_date _po.r_squared = stats.r_squared _po.r2 = stats.r2 _po.information_ratio = stats.information_ratio _po.greeks = stats.greeks _po.rolling_greeks = stats.rolling_greeks _po.compare = stats.compare _po.plot_snapshot = plots.snapshot _po.plot_earnings = plots.earnings _po.plot_daily_returns = plots.daily_returns _po.plot_distribution = plots.distribution _po.plot_drawdown = plots.drawdown _po.plot_drawdowns_periods = plots.drawdowns_periods _po.plot_histogram = plots.histogram _po.plot_log_returns = plots.log_returns _po.plot_returns = plots.returns _po.plot_rolling_beta = plots.rolling_beta _po.plot_rolling_sharpe = plots.rolling_sharpe _po.plot_rolling_sortino = plots.rolling_sortino _po.plot_rolling_volatility = plots.rolling_volatility _po.plot_yearly_returns = plots.yearly_returns _po.plot_monthly_heatmap = plots.monthly_heatmap _po.metrics = reports.metrics
extends pandas by exposing methods to be used like: df.sharpe(), df.best('day'), ...
quantstats/__init__.py
extend_pandas
hilsds/quantstats
1
python
def extend_pandas(): "\n extends pandas by exposing methods to be used like:\n df.sharpe(), df.best('day'), ...\n " from pandas.core.base import PandasObject as _po _po.compsum = stats.compsum _po.comp = stats.comp _po.expected_return = stats.expected_return _po.geometric_mean = stats.geometric_mean _po.ghpr = stats.ghpr _po.outliers = stats.outliers _po.remove_outliers = stats.remove_outliers _po.best = stats.best _po.worst = stats.worst _po.consecutive_wins = stats.consecutive_wins _po.consecutive_losses = stats.consecutive_losses _po.exposure = stats.exposure _po.win_rate = stats.win_rate _po.avg_return = stats.avg_return _po.avg_win = stats.avg_win _po.avg_loss = stats.avg_loss _po.volatility = stats.volatility _po.implied_volatility = stats.implied_volatility _po.sharpe = stats.sharpe _po.sortino = stats.sortino _po.cagr = stats.cagr _po.rar = stats.rar _po.skew = stats.skew _po.kurtosis = stats.kurtosis _po.calmar = stats.calmar _po.ulcer_index = stats.ulcer_index _po.ulcer_performance_index = stats.ulcer_performance_index _po.upi = stats.upi _po.risk_of_ruin = stats.risk_of_ruin _po.ror = stats.ror _po.value_at_risk = stats.value_at_risk _po.var = stats.var _po.conditional_value_at_risk = stats.conditional_value_at_risk _po.cvar = stats.cvar _po.expected_shortfall = stats.expected_shortfall _po.tail_ratio = stats.tail_ratio _po.payoff_ratio = stats.payoff_ratio _po.win_loss_ratio = stats.win_loss_ratio _po.profit_ratio = stats.profit_ratio _po.profit_factor = stats.profit_factor _po.gain_to_pain_ratio = stats.gain_to_pain_ratio _po.cpc_index = stats.cpc_index _po.common_sense_ratio = stats.common_sense_ratio _po.outlier_win_ratio = stats.outlier_win_ratio _po.outlier_loss_ratio = stats.outlier_loss_ratio _po.recovery_factor = stats.recovery_factor _po.risk_return_ratio = stats.risk_return_ratio _po.max_drawdown = stats.max_drawdown _po.to_drawdown_series = stats.to_drawdown_series _po.kelly_criterion = stats.kelly_criterion _po.monthly_returns = stats.monthly_returns _po.pct_rank = stats.pct_rank _po.to_returns = utils.to_returns _po.to_prices = utils.to_prices _po.to_log_returns = utils.to_log_returns _po.log_returns = utils.log_returns _po.exponential_stdev = utils.exponential_stdev _po.rebase = utils.rebase _po.aggregate_returns = utils.aggregate_returns _po.to_excess_returns = utils.to_excess_returns _po.multi_shift = utils.multi_shift _po.curr_month = utils._pandas_current_month _po.date = utils._pandas_date _po.r_squared = stats.r_squared _po.r2 = stats.r2 _po.information_ratio = stats.information_ratio _po.greeks = stats.greeks _po.rolling_greeks = stats.rolling_greeks _po.compare = stats.compare _po.plot_snapshot = plots.snapshot _po.plot_earnings = plots.earnings _po.plot_daily_returns = plots.daily_returns _po.plot_distribution = plots.distribution _po.plot_drawdown = plots.drawdown _po.plot_drawdowns_periods = plots.drawdowns_periods _po.plot_histogram = plots.histogram _po.plot_log_returns = plots.log_returns _po.plot_returns = plots.returns _po.plot_rolling_beta = plots.rolling_beta _po.plot_rolling_sharpe = plots.rolling_sharpe _po.plot_rolling_sortino = plots.rolling_sortino _po.plot_rolling_volatility = plots.rolling_volatility _po.plot_yearly_returns = plots.yearly_returns _po.plot_monthly_heatmap = plots.monthly_heatmap _po.metrics = reports.metrics
def extend_pandas(): "\n extends pandas by exposing methods to be used like:\n df.sharpe(), df.best('day'), ...\n " from pandas.core.base import PandasObject as _po _po.compsum = stats.compsum _po.comp = stats.comp _po.expected_return = stats.expected_return _po.geometric_mean = stats.geometric_mean _po.ghpr = stats.ghpr _po.outliers = stats.outliers _po.remove_outliers = stats.remove_outliers _po.best = stats.best _po.worst = stats.worst _po.consecutive_wins = stats.consecutive_wins _po.consecutive_losses = stats.consecutive_losses _po.exposure = stats.exposure _po.win_rate = stats.win_rate _po.avg_return = stats.avg_return _po.avg_win = stats.avg_win _po.avg_loss = stats.avg_loss _po.volatility = stats.volatility _po.implied_volatility = stats.implied_volatility _po.sharpe = stats.sharpe _po.sortino = stats.sortino _po.cagr = stats.cagr _po.rar = stats.rar _po.skew = stats.skew _po.kurtosis = stats.kurtosis _po.calmar = stats.calmar _po.ulcer_index = stats.ulcer_index _po.ulcer_performance_index = stats.ulcer_performance_index _po.upi = stats.upi _po.risk_of_ruin = stats.risk_of_ruin _po.ror = stats.ror _po.value_at_risk = stats.value_at_risk _po.var = stats.var _po.conditional_value_at_risk = stats.conditional_value_at_risk _po.cvar = stats.cvar _po.expected_shortfall = stats.expected_shortfall _po.tail_ratio = stats.tail_ratio _po.payoff_ratio = stats.payoff_ratio _po.win_loss_ratio = stats.win_loss_ratio _po.profit_ratio = stats.profit_ratio _po.profit_factor = stats.profit_factor _po.gain_to_pain_ratio = stats.gain_to_pain_ratio _po.cpc_index = stats.cpc_index _po.common_sense_ratio = stats.common_sense_ratio _po.outlier_win_ratio = stats.outlier_win_ratio _po.outlier_loss_ratio = stats.outlier_loss_ratio _po.recovery_factor = stats.recovery_factor _po.risk_return_ratio = stats.risk_return_ratio _po.max_drawdown = stats.max_drawdown _po.to_drawdown_series = stats.to_drawdown_series _po.kelly_criterion = stats.kelly_criterion _po.monthly_returns = stats.monthly_returns _po.pct_rank = stats.pct_rank _po.to_returns = utils.to_returns _po.to_prices = utils.to_prices _po.to_log_returns = utils.to_log_returns _po.log_returns = utils.log_returns _po.exponential_stdev = utils.exponential_stdev _po.rebase = utils.rebase _po.aggregate_returns = utils.aggregate_returns _po.to_excess_returns = utils.to_excess_returns _po.multi_shift = utils.multi_shift _po.curr_month = utils._pandas_current_month _po.date = utils._pandas_date _po.r_squared = stats.r_squared _po.r2 = stats.r2 _po.information_ratio = stats.information_ratio _po.greeks = stats.greeks _po.rolling_greeks = stats.rolling_greeks _po.compare = stats.compare _po.plot_snapshot = plots.snapshot _po.plot_earnings = plots.earnings _po.plot_daily_returns = plots.daily_returns _po.plot_distribution = plots.distribution _po.plot_drawdown = plots.drawdown _po.plot_drawdowns_periods = plots.drawdowns_periods _po.plot_histogram = plots.histogram _po.plot_log_returns = plots.log_returns _po.plot_returns = plots.returns _po.plot_rolling_beta = plots.rolling_beta _po.plot_rolling_sharpe = plots.rolling_sharpe _po.plot_rolling_sortino = plots.rolling_sortino _po.plot_rolling_volatility = plots.rolling_volatility _po.plot_yearly_returns = plots.yearly_returns _po.plot_monthly_heatmap = plots.monthly_heatmap _po.metrics = reports.metrics<|docstring|>extends pandas by exposing methods to be used like: df.sharpe(), df.best('day'), ...<|endoftext|>
e1b301d4a313a6664926b3fd86c8a2b1151cd5797f9e0f8e9525354b60526c8f
def authorize(): '\n docorator for authorize\n @parameter inSecurity: bool indicating whether incomming security need to check\n ' def validate(func, self, *args, **kwargs): ' function that calls authrozing function' isAuthEnabled = True isPkiEnabled = False authPassed = False try: appGlobal = config['pylons.app_globals'] isAuthEnabled = configutil.getConfigAsBool('basicauth.local') isPkiEnabled = (appGlobal.encryptedtokens and configutil.getConfigAsBool('pkiauth_enabled')) except BaseException as excep: LOG.error(('Error loading auth config %s - %s' % (str(excep), traceback.format_exc(2)))) if isAuthEnabled: if (('Authorization' not in request.headers) and ('authorization' not in request.headers)): return invalidAuthHandler('Authorization header missing', {}) message = None result = {} if (not isPkiEnabled): token = ('%s:%s' % (configutil.getConfig('username.local'), configutil.getConfig('password.local'))) try: isAuthenticated(token) authPassed = True except UnauthorizedException: message = 'Please provide valid username and password' result['scheme'] = 'base' if (not authPassed): token = appGlobal.authztoken try: isAuthenticated(token) authPassed = True except UnauthorizedException: if isPkiEnabled: result['scheme'] = 'pki' user = (request.headers['AuthorizationUser'] if ('AuthorizationUser' in request.headers) else 'agent') pubKey = ('%s.cert' % user) if (pubKey in appGlobal.encryptedtokens): message = appGlobal.encryptedtokens[pubKey] result['key'] = appGlobal.encryptedtokens[pubKey] else: message = ('Unknown AuthroizationUser %s' % user) return invalidAuthHandler(message, result) return func(self, *args, **kwargs) return decorator(validate)
docorator for authorize @parameter inSecurity: bool indicating whether incomming security need to check
agent/agent/lib/security/agentauth.py
authorize
isabella232/cronus-agent
7
python
def authorize(): '\n docorator for authorize\n @parameter inSecurity: bool indicating whether incomming security need to check\n ' def validate(func, self, *args, **kwargs): ' function that calls authrozing function' isAuthEnabled = True isPkiEnabled = False authPassed = False try: appGlobal = config['pylons.app_globals'] isAuthEnabled = configutil.getConfigAsBool('basicauth.local') isPkiEnabled = (appGlobal.encryptedtokens and configutil.getConfigAsBool('pkiauth_enabled')) except BaseException as excep: LOG.error(('Error loading auth config %s - %s' % (str(excep), traceback.format_exc(2)))) if isAuthEnabled: if (('Authorization' not in request.headers) and ('authorization' not in request.headers)): return invalidAuthHandler('Authorization header missing', {}) message = None result = {} if (not isPkiEnabled): token = ('%s:%s' % (configutil.getConfig('username.local'), configutil.getConfig('password.local'))) try: isAuthenticated(token) authPassed = True except UnauthorizedException: message = 'Please provide valid username and password' result['scheme'] = 'base' if (not authPassed): token = appGlobal.authztoken try: isAuthenticated(token) authPassed = True except UnauthorizedException: if isPkiEnabled: result['scheme'] = 'pki' user = (request.headers['AuthorizationUser'] if ('AuthorizationUser' in request.headers) else 'agent') pubKey = ('%s.cert' % user) if (pubKey in appGlobal.encryptedtokens): message = appGlobal.encryptedtokens[pubKey] result['key'] = appGlobal.encryptedtokens[pubKey] else: message = ('Unknown AuthroizationUser %s' % user) return invalidAuthHandler(message, result) return func(self, *args, **kwargs) return decorator(validate)
def authorize(): '\n docorator for authorize\n @parameter inSecurity: bool indicating whether incomming security need to check\n ' def validate(func, self, *args, **kwargs): ' function that calls authrozing function' isAuthEnabled = True isPkiEnabled = False authPassed = False try: appGlobal = config['pylons.app_globals'] isAuthEnabled = configutil.getConfigAsBool('basicauth.local') isPkiEnabled = (appGlobal.encryptedtokens and configutil.getConfigAsBool('pkiauth_enabled')) except BaseException as excep: LOG.error(('Error loading auth config %s - %s' % (str(excep), traceback.format_exc(2)))) if isAuthEnabled: if (('Authorization' not in request.headers) and ('authorization' not in request.headers)): return invalidAuthHandler('Authorization header missing', {}) message = None result = {} if (not isPkiEnabled): token = ('%s:%s' % (configutil.getConfig('username.local'), configutil.getConfig('password.local'))) try: isAuthenticated(token) authPassed = True except UnauthorizedException: message = 'Please provide valid username and password' result['scheme'] = 'base' if (not authPassed): token = appGlobal.authztoken try: isAuthenticated(token) authPassed = True except UnauthorizedException: if isPkiEnabled: result['scheme'] = 'pki' user = (request.headers['AuthorizationUser'] if ('AuthorizationUser' in request.headers) else 'agent') pubKey = ('%s.cert' % user) if (pubKey in appGlobal.encryptedtokens): message = appGlobal.encryptedtokens[pubKey] result['key'] = appGlobal.encryptedtokens[pubKey] else: message = ('Unknown AuthroizationUser %s' % user) return invalidAuthHandler(message, result) return func(self, *args, **kwargs) return decorator(validate)<|docstring|>docorator for authorize @parameter inSecurity: bool indicating whether incomming security need to check<|endoftext|>
6c720f6ba30e05f4dd532ac97e4f084bb1efddcecc903c487c17a7a62ad066a6
def isAuthenticated(token): ' check whether user name and password are right ' message = 'Please provide valid username and password' inHeader = None try: if ('authorization' in request.headers): inHeader = request.headers['authorization'] elif ('Authorization' in request.headers): inHeader = request.headers['Authorization'] if (inHeader is not None): base64string = base64.encodestring(token)[:(- 1)] match = re.match('\\s*Basic\\s*(?P<auth>\\S*)$', inHeader) if ((match is not None) and (match.group('auth') == base64string)): return True raise UnauthorizedException(((message + ' Header:') + str(request.headers))) except: raise UnauthorizedException(((message + ' Header:') + str(request.headers)))
check whether user name and password are right
agent/agent/lib/security/agentauth.py
isAuthenticated
isabella232/cronus-agent
7
python
def isAuthenticated(token): ' ' message = 'Please provide valid username and password' inHeader = None try: if ('authorization' in request.headers): inHeader = request.headers['authorization'] elif ('Authorization' in request.headers): inHeader = request.headers['Authorization'] if (inHeader is not None): base64string = base64.encodestring(token)[:(- 1)] match = re.match('\\s*Basic\\s*(?P<auth>\\S*)$', inHeader) if ((match is not None) and (match.group('auth') == base64string)): return True raise UnauthorizedException(((message + ' Header:') + str(request.headers))) except: raise UnauthorizedException(((message + ' Header:') + str(request.headers)))
def isAuthenticated(token): ' ' message = 'Please provide valid username and password' inHeader = None try: if ('authorization' in request.headers): inHeader = request.headers['authorization'] elif ('Authorization' in request.headers): inHeader = request.headers['Authorization'] if (inHeader is not None): base64string = base64.encodestring(token)[:(- 1)] match = re.match('\\s*Basic\\s*(?P<auth>\\S*)$', inHeader) if ((match is not None) and (match.group('auth') == base64string)): return True raise UnauthorizedException(((message + ' Header:') + str(request.headers))) except: raise UnauthorizedException(((message + ' Header:') + str(request.headers)))<|docstring|>check whether user name and password are right<|endoftext|>
e8adb93a256100768d3e1c9a3545dad32fd0f37722eb3fa4216e7c435cfb47af
def buildTokenCache(authztoken): ' build in memory cache for security tokens ' appGlobal = config['pylons.app_globals'] pubKeyDir = os.path.join(manifestutil.manifestPath('agent'), 'agent', 'cronus', 'keys') LOG.info(('key directory %s' % pubKeyDir)) if os.path.exists(pubKeyDir): try: import pki from M2Crypto import X509 pubKeyFiles = [f for f in os.listdir(pubKeyDir) if re.match('.*\\.cert', f)] LOG.info(('key files %s' % pubKeyFiles)) for pubKeyFile in pubKeyFiles: certf = open(os.path.join(pubKeyDir, pubKeyFile), 'r') ca_cert_content = certf.read() certf.close() cert = X509.load_cert_string(ca_cert_content) encryptedToken = pki.encrypt(cert.get_pubkey(), authztoken) appGlobal.encryptedtokens[pubKeyFile] = encryptedToken LOG.info(('token %s=%s' % (pubKeyFile, encryptedToken))) except BaseException as excep: LOG.error(('Error loading pki keys %s - %s' % (str(excep), traceback.format_exc(2))))
build in memory cache for security tokens
agent/agent/lib/security/agentauth.py
buildTokenCache
isabella232/cronus-agent
7
python
def buildTokenCache(authztoken): ' ' appGlobal = config['pylons.app_globals'] pubKeyDir = os.path.join(manifestutil.manifestPath('agent'), 'agent', 'cronus', 'keys') LOG.info(('key directory %s' % pubKeyDir)) if os.path.exists(pubKeyDir): try: import pki from M2Crypto import X509 pubKeyFiles = [f for f in os.listdir(pubKeyDir) if re.match('.*\\.cert', f)] LOG.info(('key files %s' % pubKeyFiles)) for pubKeyFile in pubKeyFiles: certf = open(os.path.join(pubKeyDir, pubKeyFile), 'r') ca_cert_content = certf.read() certf.close() cert = X509.load_cert_string(ca_cert_content) encryptedToken = pki.encrypt(cert.get_pubkey(), authztoken) appGlobal.encryptedtokens[pubKeyFile] = encryptedToken LOG.info(('token %s=%s' % (pubKeyFile, encryptedToken))) except BaseException as excep: LOG.error(('Error loading pki keys %s - %s' % (str(excep), traceback.format_exc(2))))
def buildTokenCache(authztoken): ' ' appGlobal = config['pylons.app_globals'] pubKeyDir = os.path.join(manifestutil.manifestPath('agent'), 'agent', 'cronus', 'keys') LOG.info(('key directory %s' % pubKeyDir)) if os.path.exists(pubKeyDir): try: import pki from M2Crypto import X509 pubKeyFiles = [f for f in os.listdir(pubKeyDir) if re.match('.*\\.cert', f)] LOG.info(('key files %s' % pubKeyFiles)) for pubKeyFile in pubKeyFiles: certf = open(os.path.join(pubKeyDir, pubKeyFile), 'r') ca_cert_content = certf.read() certf.close() cert = X509.load_cert_string(ca_cert_content) encryptedToken = pki.encrypt(cert.get_pubkey(), authztoken) appGlobal.encryptedtokens[pubKeyFile] = encryptedToken LOG.info(('token %s=%s' % (pubKeyFile, encryptedToken))) except BaseException as excep: LOG.error(('Error loading pki keys %s - %s' % (str(excep), traceback.format_exc(2))))<|docstring|>build in memory cache for security tokens<|endoftext|>
ec29ff40ccb3cf25327cecf182617eef09954ca2c571b810182a6297fdbce9e9
def validate(func, self, *args, **kwargs): ' function that calls authrozing function' isAuthEnabled = True isPkiEnabled = False authPassed = False try: appGlobal = config['pylons.app_globals'] isAuthEnabled = configutil.getConfigAsBool('basicauth.local') isPkiEnabled = (appGlobal.encryptedtokens and configutil.getConfigAsBool('pkiauth_enabled')) except BaseException as excep: LOG.error(('Error loading auth config %s - %s' % (str(excep), traceback.format_exc(2)))) if isAuthEnabled: if (('Authorization' not in request.headers) and ('authorization' not in request.headers)): return invalidAuthHandler('Authorization header missing', {}) message = None result = {} if (not isPkiEnabled): token = ('%s:%s' % (configutil.getConfig('username.local'), configutil.getConfig('password.local'))) try: isAuthenticated(token) authPassed = True except UnauthorizedException: message = 'Please provide valid username and password' result['scheme'] = 'base' if (not authPassed): token = appGlobal.authztoken try: isAuthenticated(token) authPassed = True except UnauthorizedException: if isPkiEnabled: result['scheme'] = 'pki' user = (request.headers['AuthorizationUser'] if ('AuthorizationUser' in request.headers) else 'agent') pubKey = ('%s.cert' % user) if (pubKey in appGlobal.encryptedtokens): message = appGlobal.encryptedtokens[pubKey] result['key'] = appGlobal.encryptedtokens[pubKey] else: message = ('Unknown AuthroizationUser %s' % user) return invalidAuthHandler(message, result) return func(self, *args, **kwargs)
function that calls authrozing function
agent/agent/lib/security/agentauth.py
validate
isabella232/cronus-agent
7
python
def validate(func, self, *args, **kwargs): ' ' isAuthEnabled = True isPkiEnabled = False authPassed = False try: appGlobal = config['pylons.app_globals'] isAuthEnabled = configutil.getConfigAsBool('basicauth.local') isPkiEnabled = (appGlobal.encryptedtokens and configutil.getConfigAsBool('pkiauth_enabled')) except BaseException as excep: LOG.error(('Error loading auth config %s - %s' % (str(excep), traceback.format_exc(2)))) if isAuthEnabled: if (('Authorization' not in request.headers) and ('authorization' not in request.headers)): return invalidAuthHandler('Authorization header missing', {}) message = None result = {} if (not isPkiEnabled): token = ('%s:%s' % (configutil.getConfig('username.local'), configutil.getConfig('password.local'))) try: isAuthenticated(token) authPassed = True except UnauthorizedException: message = 'Please provide valid username and password' result['scheme'] = 'base' if (not authPassed): token = appGlobal.authztoken try: isAuthenticated(token) authPassed = True except UnauthorizedException: if isPkiEnabled: result['scheme'] = 'pki' user = (request.headers['AuthorizationUser'] if ('AuthorizationUser' in request.headers) else 'agent') pubKey = ('%s.cert' % user) if (pubKey in appGlobal.encryptedtokens): message = appGlobal.encryptedtokens[pubKey] result['key'] = appGlobal.encryptedtokens[pubKey] else: message = ('Unknown AuthroizationUser %s' % user) return invalidAuthHandler(message, result) return func(self, *args, **kwargs)
def validate(func, self, *args, **kwargs): ' ' isAuthEnabled = True isPkiEnabled = False authPassed = False try: appGlobal = config['pylons.app_globals'] isAuthEnabled = configutil.getConfigAsBool('basicauth.local') isPkiEnabled = (appGlobal.encryptedtokens and configutil.getConfigAsBool('pkiauth_enabled')) except BaseException as excep: LOG.error(('Error loading auth config %s - %s' % (str(excep), traceback.format_exc(2)))) if isAuthEnabled: if (('Authorization' not in request.headers) and ('authorization' not in request.headers)): return invalidAuthHandler('Authorization header missing', {}) message = None result = {} if (not isPkiEnabled): token = ('%s:%s' % (configutil.getConfig('username.local'), configutil.getConfig('password.local'))) try: isAuthenticated(token) authPassed = True except UnauthorizedException: message = 'Please provide valid username and password' result['scheme'] = 'base' if (not authPassed): token = appGlobal.authztoken try: isAuthenticated(token) authPassed = True except UnauthorizedException: if isPkiEnabled: result['scheme'] = 'pki' user = (request.headers['AuthorizationUser'] if ('AuthorizationUser' in request.headers) else 'agent') pubKey = ('%s.cert' % user) if (pubKey in appGlobal.encryptedtokens): message = appGlobal.encryptedtokens[pubKey] result['key'] = appGlobal.encryptedtokens[pubKey] else: message = ('Unknown AuthroizationUser %s' % user) return invalidAuthHandler(message, result) return func(self, *args, **kwargs)<|docstring|>function that calls authrozing function<|endoftext|>
d1b7fa33477651e998f94f22a32044736ba25bd70e11f32a508bb9c4553ede17
def test_name(self): '\n Tests the outputting of the correct name if assigned one.\n ' field = models.CharField(max_length=65) (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, None) field.set_attributes_from_name('is_awesome_test') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, 'is_awesome_test') field = models.ForeignKey('some_fake.ModelName') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, None) field.set_attributes_from_name('author') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, 'author')
Tests the outputting of the correct name if assigned one.
tests/field_deconstruction/tests.py
test_name
pegler/django
1
python
def test_name(self): '\n \n ' field = models.CharField(max_length=65) (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, None) field.set_attributes_from_name('is_awesome_test') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, 'is_awesome_test') field = models.ForeignKey('some_fake.ModelName') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, None) field.set_attributes_from_name('author') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, 'author')
def test_name(self): '\n \n ' field = models.CharField(max_length=65) (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, None) field.set_attributes_from_name('is_awesome_test') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, 'is_awesome_test') field = models.ForeignKey('some_fake.ModelName') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, None) field.set_attributes_from_name('author') (name, path, args, kwargs) = field.deconstruct() self.assertEqual(name, 'author')<|docstring|>Tests the outputting of the correct name if assigned one.<|endoftext|>
fa505aacba718aafc1f3222b01fbd22dc5673e444786694fed688bd6edf45884
@staticmethod def _split_fqdn(fqdn): 'Split a FQDN into record_name and zone_name values' if (not fqdn): raise ValueError('Error: No valid FQDN given.') split_dns = fqdn.rstrip('.').rsplit('.', 2) return (''.join(split_dns[:(- 2)]), ('.'.join(split_dns[(- 2):]) + '.'))
Split a FQDN into record_name and zone_name values
kasserver/__init__.py
_split_fqdn
Lightweb-Media/kasserver
0
python
@staticmethod def _split_fqdn(fqdn): if (not fqdn): raise ValueError('Error: No valid FQDN given.') split_dns = fqdn.rstrip('.').rsplit('.', 2) return (.join(split_dns[:(- 2)]), ('.'.join(split_dns[(- 2):]) + '.'))
@staticmethod def _split_fqdn(fqdn): if (not fqdn): raise ValueError('Error: No valid FQDN given.') split_dns = fqdn.rstrip('.').rsplit('.', 2) return (.join(split_dns[:(- 2)]), ('.'.join(split_dns[(- 2):]) + '.'))<|docstring|>Split a FQDN into record_name and zone_name values<|endoftext|>
971aaf168ac25b02db098186bff77ffe1f1399e5ea04648164128feec2e6a265
def get_dns_records(self, fqdn): 'Get list of DNS records.' (_, zone_name) = self._split_fqdn(fqdn) res = self._request('get_dns_settings', {'zone_host': zone_name}) items = res[1]['value']['item'][2]['value']['_value_1'] result = [] for item in items: result.append({i['key'].split('_', 1)[(- 1)]: i['value'] for i in item['item']}) return result
Get list of DNS records.
kasserver/__init__.py
get_dns_records
Lightweb-Media/kasserver
0
python
def get_dns_records(self, fqdn): (_, zone_name) = self._split_fqdn(fqdn) res = self._request('get_dns_settings', {'zone_host': zone_name}) items = res[1]['value']['item'][2]['value']['_value_1'] result = [] for item in items: result.append({i['key'].split('_', 1)[(- 1)]: i['value'] for i in item['item']}) return result
def get_dns_records(self, fqdn): (_, zone_name) = self._split_fqdn(fqdn) res = self._request('get_dns_settings', {'zone_host': zone_name}) items = res[1]['value']['item'][2]['value']['_value_1'] result = [] for item in items: result.append({i['key'].split('_', 1)[(- 1)]: i['value'] for i in item['item']}) return result<|docstring|>Get list of DNS records.<|endoftext|>
1f55944a4daadeaff40cea4d416e37a82cccef9d7f5db1aa390a39628a5c96d2
def get_dns_record(self, fqdn, record_type): 'Get a specific DNS record for a FQDN and type' (record_name, zone_name) = self._split_fqdn(fqdn) result = self.get_dns_records(zone_name) for item in result: if ((item['name'] == record_name) and (item['type'] == record_type)): return item return None
Get a specific DNS record for a FQDN and type
kasserver/__init__.py
get_dns_record
Lightweb-Media/kasserver
0
python
def get_dns_record(self, fqdn, record_type): (record_name, zone_name) = self._split_fqdn(fqdn) result = self.get_dns_records(zone_name) for item in result: if ((item['name'] == record_name) and (item['type'] == record_type)): return item return None
def get_dns_record(self, fqdn, record_type): (record_name, zone_name) = self._split_fqdn(fqdn) result = self.get_dns_records(zone_name) for item in result: if ((item['name'] == record_name) and (item['type'] == record_type)): return item return None<|docstring|>Get a specific DNS record for a FQDN and type<|endoftext|>
e24c5ea817cfd13ea6b85bc2ee8b9e3677314c73a4fda98676187a429e422e95
def add_dns_record(self, fqdn, record_type, record_data, record_aux=None): 'Add or update an DNS record' (record_name, zone_name) = self._split_fqdn(fqdn) params = {'zone_host': zone_name, 'record_name': record_name, 'record_type': record_type, 'record_data': record_data, 'record_aux': (record_aux if record_aux else '0')} existing_record = self.get_dns_record(fqdn, record_type) if existing_record: params['record_id'] = existing_record['id'] self._request('update_dns_settings', params) else: self._request('add_dns_settings', params)
Add or update an DNS record
kasserver/__init__.py
add_dns_record
Lightweb-Media/kasserver
0
python
def add_dns_record(self, fqdn, record_type, record_data, record_aux=None): (record_name, zone_name) = self._split_fqdn(fqdn) params = {'zone_host': zone_name, 'record_name': record_name, 'record_type': record_type, 'record_data': record_data, 'record_aux': (record_aux if record_aux else '0')} existing_record = self.get_dns_record(fqdn, record_type) if existing_record: params['record_id'] = existing_record['id'] self._request('update_dns_settings', params) else: self._request('add_dns_settings', params)
def add_dns_record(self, fqdn, record_type, record_data, record_aux=None): (record_name, zone_name) = self._split_fqdn(fqdn) params = {'zone_host': zone_name, 'record_name': record_name, 'record_type': record_type, 'record_data': record_data, 'record_aux': (record_aux if record_aux else '0')} existing_record = self.get_dns_record(fqdn, record_type) if existing_record: params['record_id'] = existing_record['id'] self._request('update_dns_settings', params) else: self._request('add_dns_settings', params)<|docstring|>Add or update an DNS record<|endoftext|>