id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
6,200
foremast/foremast
src/foremast/s3/s3apps.py
S3Apps._put_bucket_encryption
def _put_bucket_encryption(self): """Adds bucket encryption configuration.""" if self.s3props['encryption']['enabled']: encryption_config = {'Rules': [{}]} encryption_config = { 'Rules': self.s3props['encryption']['encryption_rules'] } LOG.debug(encryption_config) _response = self.s3client.put_bucket_encryption(Bucket=self.bucket, ServerSideEncryptionConfiguration=encryption_config) else: _response = self.s3client.delete_bucket_encryption(Bucket=self.bucket) LOG.debug('Response setting up S3 encryption: %s', _response) LOG.info('S3 encryption configuration updated')
python
def _put_bucket_encryption(self): """Adds bucket encryption configuration.""" if self.s3props['encryption']['enabled']: encryption_config = {'Rules': [{}]} encryption_config = { 'Rules': self.s3props['encryption']['encryption_rules'] } LOG.debug(encryption_config) _response = self.s3client.put_bucket_encryption(Bucket=self.bucket, ServerSideEncryptionConfiguration=encryption_config) else: _response = self.s3client.delete_bucket_encryption(Bucket=self.bucket) LOG.debug('Response setting up S3 encryption: %s', _response) LOG.info('S3 encryption configuration updated')
[ "def", "_put_bucket_encryption", "(", "self", ")", ":", "if", "self", ".", "s3props", "[", "'encryption'", "]", "[", "'enabled'", "]", ":", "encryption_config", "=", "{", "'Rules'", ":", "[", "{", "}", "]", "}", "encryption_config", "=", "{", "'Rules'", ":", "self", ".", "s3props", "[", "'encryption'", "]", "[", "'encryption_rules'", "]", "}", "LOG", ".", "debug", "(", "encryption_config", ")", "_response", "=", "self", ".", "s3client", ".", "put_bucket_encryption", "(", "Bucket", "=", "self", ".", "bucket", ",", "ServerSideEncryptionConfiguration", "=", "encryption_config", ")", "else", ":", "_response", "=", "self", ".", "s3client", ".", "delete_bucket_encryption", "(", "Bucket", "=", "self", ".", "bucket", ")", "LOG", ".", "debug", "(", "'Response setting up S3 encryption: %s'", ",", "_response", ")", "LOG", ".", "info", "(", "'S3 encryption configuration updated'", ")" ]
Adds bucket encryption configuration.
[ "Adds", "bucket", "encryption", "configuration", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L177-L190
6,201
foremast/foremast
src/foremast/s3/s3apps.py
S3Apps._put_bucket_lifecycle
def _put_bucket_lifecycle(self): """Adds bucket lifecycle configuration.""" status = 'deleted' if self.s3props['lifecycle']['enabled']: lifecycle_config = { 'Rules': self.s3props['lifecycle']['lifecycle_rules'] } LOG.debug('Lifecycle Config: %s', lifecycle_config) _response = self.s3client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration=lifecycle_config) status = 'applied' else: _response = self.s3client.delete_bucket_lifecycle(Bucket=self.bucket) LOG.debug('Response setting up S3 lifecycle: %s', _response) LOG.info('S3 lifecycle configuration %s', status)
python
def _put_bucket_lifecycle(self): """Adds bucket lifecycle configuration.""" status = 'deleted' if self.s3props['lifecycle']['enabled']: lifecycle_config = { 'Rules': self.s3props['lifecycle']['lifecycle_rules'] } LOG.debug('Lifecycle Config: %s', lifecycle_config) _response = self.s3client.put_bucket_lifecycle_configuration(Bucket=self.bucket, LifecycleConfiguration=lifecycle_config) status = 'applied' else: _response = self.s3client.delete_bucket_lifecycle(Bucket=self.bucket) LOG.debug('Response setting up S3 lifecycle: %s', _response) LOG.info('S3 lifecycle configuration %s', status)
[ "def", "_put_bucket_lifecycle", "(", "self", ")", ":", "status", "=", "'deleted'", "if", "self", ".", "s3props", "[", "'lifecycle'", "]", "[", "'enabled'", "]", ":", "lifecycle_config", "=", "{", "'Rules'", ":", "self", ".", "s3props", "[", "'lifecycle'", "]", "[", "'lifecycle_rules'", "]", "}", "LOG", ".", "debug", "(", "'Lifecycle Config: %s'", ",", "lifecycle_config", ")", "_response", "=", "self", ".", "s3client", ".", "put_bucket_lifecycle_configuration", "(", "Bucket", "=", "self", ".", "bucket", ",", "LifecycleConfiguration", "=", "lifecycle_config", ")", "status", "=", "'applied'", "else", ":", "_response", "=", "self", ".", "s3client", ".", "delete_bucket_lifecycle", "(", "Bucket", "=", "self", ".", "bucket", ")", "LOG", ".", "debug", "(", "'Response setting up S3 lifecycle: %s'", ",", "_response", ")", "LOG", ".", "info", "(", "'S3 lifecycle configuration %s'", ",", "status", ")" ]
Adds bucket lifecycle configuration.
[ "Adds", "bucket", "lifecycle", "configuration", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L192-L206
6,202
foremast/foremast
src/foremast/s3/s3apps.py
S3Apps._put_bucket_logging
def _put_bucket_logging(self): """Adds bucket logging policy to bucket for s3 access requests""" logging_config = {} if self.s3props['logging']['enabled']: logging_config = { 'LoggingEnabled': { 'TargetBucket': self.s3props['logging']['logging_bucket'], 'TargetGrants': self.s3props['logging']['logging_grants'], 'TargetPrefix': self.s3props['logging']['logging_bucket_prefix'] } } _response = self.s3client.put_bucket_logging(Bucket=self.bucket, BucketLoggingStatus=logging_config) LOG.debug('Response setting up S3 logging: %s', _response) LOG.info('S3 logging configuration updated')
python
def _put_bucket_logging(self): """Adds bucket logging policy to bucket for s3 access requests""" logging_config = {} if self.s3props['logging']['enabled']: logging_config = { 'LoggingEnabled': { 'TargetBucket': self.s3props['logging']['logging_bucket'], 'TargetGrants': self.s3props['logging']['logging_grants'], 'TargetPrefix': self.s3props['logging']['logging_bucket_prefix'] } } _response = self.s3client.put_bucket_logging(Bucket=self.bucket, BucketLoggingStatus=logging_config) LOG.debug('Response setting up S3 logging: %s', _response) LOG.info('S3 logging configuration updated')
[ "def", "_put_bucket_logging", "(", "self", ")", ":", "logging_config", "=", "{", "}", "if", "self", ".", "s3props", "[", "'logging'", "]", "[", "'enabled'", "]", ":", "logging_config", "=", "{", "'LoggingEnabled'", ":", "{", "'TargetBucket'", ":", "self", ".", "s3props", "[", "'logging'", "]", "[", "'logging_bucket'", "]", ",", "'TargetGrants'", ":", "self", ".", "s3props", "[", "'logging'", "]", "[", "'logging_grants'", "]", ",", "'TargetPrefix'", ":", "self", ".", "s3props", "[", "'logging'", "]", "[", "'logging_bucket_prefix'", "]", "}", "}", "_response", "=", "self", ".", "s3client", ".", "put_bucket_logging", "(", "Bucket", "=", "self", ".", "bucket", ",", "BucketLoggingStatus", "=", "logging_config", ")", "LOG", ".", "debug", "(", "'Response setting up S3 logging: %s'", ",", "_response", ")", "LOG", ".", "info", "(", "'S3 logging configuration updated'", ")" ]
Adds bucket logging policy to bucket for s3 access requests
[ "Adds", "bucket", "logging", "policy", "to", "bucket", "for", "s3", "access", "requests" ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L208-L221
6,203
foremast/foremast
src/foremast/s3/s3apps.py
S3Apps._put_bucket_tagging
def _put_bucket_tagging(self): """Add bucket tags to bucket.""" all_tags = self.s3props['tagging']['tags'] all_tags.update({'app_group': self.group, 'app_name': self.app_name}) tag_set = generate_s3_tags.generated_tag_data(all_tags) tagging_config = {'TagSet': tag_set} self.s3client.put_bucket_tagging(Bucket=self.bucket, Tagging=tagging_config) LOG.info("Adding tagging %s for Bucket", tag_set)
python
def _put_bucket_tagging(self): """Add bucket tags to bucket.""" all_tags = self.s3props['tagging']['tags'] all_tags.update({'app_group': self.group, 'app_name': self.app_name}) tag_set = generate_s3_tags.generated_tag_data(all_tags) tagging_config = {'TagSet': tag_set} self.s3client.put_bucket_tagging(Bucket=self.bucket, Tagging=tagging_config) LOG.info("Adding tagging %s for Bucket", tag_set)
[ "def", "_put_bucket_tagging", "(", "self", ")", ":", "all_tags", "=", "self", ".", "s3props", "[", "'tagging'", "]", "[", "'tags'", "]", "all_tags", ".", "update", "(", "{", "'app_group'", ":", "self", ".", "group", ",", "'app_name'", ":", "self", ".", "app_name", "}", ")", "tag_set", "=", "generate_s3_tags", ".", "generated_tag_data", "(", "all_tags", ")", "tagging_config", "=", "{", "'TagSet'", ":", "tag_set", "}", "self", ".", "s3client", ".", "put_bucket_tagging", "(", "Bucket", "=", "self", ".", "bucket", ",", "Tagging", "=", "tagging_config", ")", "LOG", ".", "info", "(", "\"Adding tagging %s for Bucket\"", ",", "tag_set", ")" ]
Add bucket tags to bucket.
[ "Add", "bucket", "tags", "to", "bucket", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L223-L232
6,204
foremast/foremast
src/foremast/s3/s3apps.py
S3Apps._put_bucket_versioning
def _put_bucket_versioning(self): """Adds bucket versioning policy to bucket""" status = 'Suspended' if self.s3props['versioning']['enabled']: status = 'Enabled' versioning_config = { 'MFADelete': self.s3props['versioning']['mfa_delete'], 'Status': status } _response = self.s3client.put_bucket_versioning(Bucket=self.bucket, VersioningConfiguration=versioning_config) LOG.debug('Response setting up S3 versioning: %s', _response) LOG.info('S3 versioning configuration updated')
python
def _put_bucket_versioning(self): """Adds bucket versioning policy to bucket""" status = 'Suspended' if self.s3props['versioning']['enabled']: status = 'Enabled' versioning_config = { 'MFADelete': self.s3props['versioning']['mfa_delete'], 'Status': status } _response = self.s3client.put_bucket_versioning(Bucket=self.bucket, VersioningConfiguration=versioning_config) LOG.debug('Response setting up S3 versioning: %s', _response) LOG.info('S3 versioning configuration updated')
[ "def", "_put_bucket_versioning", "(", "self", ")", ":", "status", "=", "'Suspended'", "if", "self", ".", "s3props", "[", "'versioning'", "]", "[", "'enabled'", "]", ":", "status", "=", "'Enabled'", "versioning_config", "=", "{", "'MFADelete'", ":", "self", ".", "s3props", "[", "'versioning'", "]", "[", "'mfa_delete'", "]", ",", "'Status'", ":", "status", "}", "_response", "=", "self", ".", "s3client", ".", "put_bucket_versioning", "(", "Bucket", "=", "self", ".", "bucket", ",", "VersioningConfiguration", "=", "versioning_config", ")", "LOG", ".", "debug", "(", "'Response setting up S3 versioning: %s'", ",", "_response", ")", "LOG", ".", "info", "(", "'S3 versioning configuration updated'", ")" ]
Adds bucket versioning policy to bucket
[ "Adds", "bucket", "versioning", "policy", "to", "bucket" ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L234-L247
6,205
foremast/foremast
src/foremast/configs/prepare_configs.py
process_git_configs
def process_git_configs(git_short=''): """Retrieve _application.json_ files from GitLab. Args: git_short (str): Short Git representation of repository, e.g. forrest/core. Returns: collections.defaultdict: Configurations stored for each environment found. """ LOG.info('Processing application.json files from GitLab "%s".', git_short) file_lookup = FileLookup(git_short=git_short) app_configs = process_configs(file_lookup, RUNWAY_BASE_PATH + '/application-master-{env}.json', RUNWAY_BASE_PATH + '/pipeline.json') commit_obj = file_lookup.project.commits.get('master') config_commit = commit_obj.attributes['id'] LOG.info('Commit ID used: %s', config_commit) app_configs['pipeline']['config_commit'] = config_commit return app_configs
python
def process_git_configs(git_short=''): """Retrieve _application.json_ files from GitLab. Args: git_short (str): Short Git representation of repository, e.g. forrest/core. Returns: collections.defaultdict: Configurations stored for each environment found. """ LOG.info('Processing application.json files from GitLab "%s".', git_short) file_lookup = FileLookup(git_short=git_short) app_configs = process_configs(file_lookup, RUNWAY_BASE_PATH + '/application-master-{env}.json', RUNWAY_BASE_PATH + '/pipeline.json') commit_obj = file_lookup.project.commits.get('master') config_commit = commit_obj.attributes['id'] LOG.info('Commit ID used: %s', config_commit) app_configs['pipeline']['config_commit'] = config_commit return app_configs
[ "def", "process_git_configs", "(", "git_short", "=", "''", ")", ":", "LOG", ".", "info", "(", "'Processing application.json files from GitLab \"%s\".'", ",", "git_short", ")", "file_lookup", "=", "FileLookup", "(", "git_short", "=", "git_short", ")", "app_configs", "=", "process_configs", "(", "file_lookup", ",", "RUNWAY_BASE_PATH", "+", "'/application-master-{env}.json'", ",", "RUNWAY_BASE_PATH", "+", "'/pipeline.json'", ")", "commit_obj", "=", "file_lookup", ".", "project", ".", "commits", ".", "get", "(", "'master'", ")", "config_commit", "=", "commit_obj", ".", "attributes", "[", "'id'", "]", "LOG", ".", "info", "(", "'Commit ID used: %s'", ",", "config_commit", ")", "app_configs", "[", "'pipeline'", "]", "[", "'config_commit'", "]", "=", "config_commit", "return", "app_configs" ]
Retrieve _application.json_ files from GitLab. Args: git_short (str): Short Git representation of repository, e.g. forrest/core. Returns: collections.defaultdict: Configurations stored for each environment found.
[ "Retrieve", "_application", ".", "json_", "files", "from", "GitLab", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L26-L46
6,206
foremast/foremast
src/foremast/configs/prepare_configs.py
process_runway_configs
def process_runway_configs(runway_dir=''): """Read the _application.json_ files. Args: runway_dir (str): Name of runway directory with app.json files. Returns: collections.defaultdict: Configurations stored for each environment found. """ LOG.info('Processing application.json files from local directory "%s".', runway_dir) file_lookup = FileLookup(runway_dir=runway_dir) app_configs = process_configs(file_lookup, 'application-master-{env}.json', 'pipeline.json') return app_configs
python
def process_runway_configs(runway_dir=''): """Read the _application.json_ files. Args: runway_dir (str): Name of runway directory with app.json files. Returns: collections.defaultdict: Configurations stored for each environment found. """ LOG.info('Processing application.json files from local directory "%s".', runway_dir) file_lookup = FileLookup(runway_dir=runway_dir) app_configs = process_configs(file_lookup, 'application-master-{env}.json', 'pipeline.json') return app_configs
[ "def", "process_runway_configs", "(", "runway_dir", "=", "''", ")", ":", "LOG", ".", "info", "(", "'Processing application.json files from local directory \"%s\".'", ",", "runway_dir", ")", "file_lookup", "=", "FileLookup", "(", "runway_dir", "=", "runway_dir", ")", "app_configs", "=", "process_configs", "(", "file_lookup", ",", "'application-master-{env}.json'", ",", "'pipeline.json'", ")", "return", "app_configs" ]
Read the _application.json_ files. Args: runway_dir (str): Name of runway directory with app.json files. Returns: collections.defaultdict: Configurations stored for each environment found.
[ "Read", "the", "_application", ".", "json_", "files", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L49-L62
6,207
foremast/foremast
src/foremast/configs/prepare_configs.py
process_configs
def process_configs(file_lookup, app_config_format, pipeline_config): """Processes the configs from lookup sources. Args: file_lookup (FileLookup): Source to look for file/config app_config_format (str): The format for application config files. pipeline_config (str): Name/path of the pipeline config Returns: dict: Retreived application config """ app_configs = collections.defaultdict(dict) for env in ENVS: file_json = app_config_format.format(env=env) try: env_config = file_lookup.json(filename=file_json) app_configs[env] = apply_region_configs(env_config) except FileNotFoundError: LOG.critical('Application configuration not available for %s.', env) continue try: app_configs['pipeline'] = file_lookup.json(filename=pipeline_config) except FileNotFoundError: LOG.warning('Unable to process pipeline.json. Using defaults.') app_configs['pipeline'] = {'env': ['stage', 'prod']} LOG.debug('Application configs:\n%s', app_configs) return app_configs
python
def process_configs(file_lookup, app_config_format, pipeline_config): """Processes the configs from lookup sources. Args: file_lookup (FileLookup): Source to look for file/config app_config_format (str): The format for application config files. pipeline_config (str): Name/path of the pipeline config Returns: dict: Retreived application config """ app_configs = collections.defaultdict(dict) for env in ENVS: file_json = app_config_format.format(env=env) try: env_config = file_lookup.json(filename=file_json) app_configs[env] = apply_region_configs(env_config) except FileNotFoundError: LOG.critical('Application configuration not available for %s.', env) continue try: app_configs['pipeline'] = file_lookup.json(filename=pipeline_config) except FileNotFoundError: LOG.warning('Unable to process pipeline.json. Using defaults.') app_configs['pipeline'] = {'env': ['stage', 'prod']} LOG.debug('Application configs:\n%s', app_configs) return app_configs
[ "def", "process_configs", "(", "file_lookup", ",", "app_config_format", ",", "pipeline_config", ")", ":", "app_configs", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "env", "in", "ENVS", ":", "file_json", "=", "app_config_format", ".", "format", "(", "env", "=", "env", ")", "try", ":", "env_config", "=", "file_lookup", ".", "json", "(", "filename", "=", "file_json", ")", "app_configs", "[", "env", "]", "=", "apply_region_configs", "(", "env_config", ")", "except", "FileNotFoundError", ":", "LOG", ".", "critical", "(", "'Application configuration not available for %s.'", ",", "env", ")", "continue", "try", ":", "app_configs", "[", "'pipeline'", "]", "=", "file_lookup", ".", "json", "(", "filename", "=", "pipeline_config", ")", "except", "FileNotFoundError", ":", "LOG", ".", "warning", "(", "'Unable to process pipeline.json. Using defaults.'", ")", "app_configs", "[", "'pipeline'", "]", "=", "{", "'env'", ":", "[", "'stage'", ",", "'prod'", "]", "}", "LOG", ".", "debug", "(", "'Application configs:\\n%s'", ",", "app_configs", ")", "return", "app_configs" ]
Processes the configs from lookup sources. Args: file_lookup (FileLookup): Source to look for file/config app_config_format (str): The format for application config files. pipeline_config (str): Name/path of the pipeline config Returns: dict: Retreived application config
[ "Processes", "the", "configs", "from", "lookup", "sources", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L65-L93
6,208
foremast/foremast
src/foremast/configs/prepare_configs.py
apply_region_configs
def apply_region_configs(env_config): """Override default env configs with region specific configs and nest all values under a region Args: env_config (dict): The environment specific config. Return: dict: Newly updated dictionary with region overrides applied. """ new_config = env_config.copy() for region in env_config.get('regions', REGIONS): if isinstance(env_config.get('regions'), dict): region_specific_config = env_config['regions'][region] new_config[region] = dict(DeepChainMap(region_specific_config, env_config)) else: new_config[region] = env_config.copy() LOG.debug('Region Specific Config:\n%s', new_config) return new_config
python
def apply_region_configs(env_config): """Override default env configs with region specific configs and nest all values under a region Args: env_config (dict): The environment specific config. Return: dict: Newly updated dictionary with region overrides applied. """ new_config = env_config.copy() for region in env_config.get('regions', REGIONS): if isinstance(env_config.get('regions'), dict): region_specific_config = env_config['regions'][region] new_config[region] = dict(DeepChainMap(region_specific_config, env_config)) else: new_config[region] = env_config.copy() LOG.debug('Region Specific Config:\n%s', new_config) return new_config
[ "def", "apply_region_configs", "(", "env_config", ")", ":", "new_config", "=", "env_config", ".", "copy", "(", ")", "for", "region", "in", "env_config", ".", "get", "(", "'regions'", ",", "REGIONS", ")", ":", "if", "isinstance", "(", "env_config", ".", "get", "(", "'regions'", ")", ",", "dict", ")", ":", "region_specific_config", "=", "env_config", "[", "'regions'", "]", "[", "region", "]", "new_config", "[", "region", "]", "=", "dict", "(", "DeepChainMap", "(", "region_specific_config", ",", "env_config", ")", ")", "else", ":", "new_config", "[", "region", "]", "=", "env_config", ".", "copy", "(", ")", "LOG", ".", "debug", "(", "'Region Specific Config:\\n%s'", ",", "new_config", ")", "return", "new_config" ]
Override default env configs with region specific configs and nest all values under a region Args: env_config (dict): The environment specific config. Return: dict: Newly updated dictionary with region overrides applied.
[ "Override", "default", "env", "configs", "with", "region", "specific", "configs", "and", "nest", "all", "values", "under", "a", "region" ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L96-L114
6,209
foremast/foremast
src/foremast/iam/create_iam.py
create_iam_resources
def create_iam_resources(env='dev', app='', **_): """Create the IAM Resources for the application. Args: env (str): Deployment environment/account, i.e. dev, stage, prod. app (str): Spinnaker Application name. Returns: True upon successful completion. """ session = boto3.session.Session(profile_name=env) client = session.client('iam') app_properties = get_properties(env='pipeline') generated = get_details(env=env, app=app) generated_iam = generated.iam() app_details = collections.namedtuple('AppDetails', generated_iam.keys()) details = app_details(**generated_iam) LOG.debug('Application details: %s', details) deployment_type = app_properties['type'] role_trust_template = get_template( 'infrastructure/iam/trust/{0}_role.json.j2'.format(deployment_type), formats=generated) resource_action( client, action='create_role', log_format='Created Role: %(RoleName)s', RoleName=details.role, AssumeRolePolicyDocument=role_trust_template) resource_action( client, action='create_instance_profile', log_format='Created Instance Profile: %(InstanceProfileName)s', InstanceProfileName=details.profile) attach_profile_to_role(client, role_name=details.role, profile_name=details.profile) iam_policy = construct_policy(app=app, group=details.group, env=env, pipeline_settings=app_properties) if iam_policy: resource_action( client, action='put_role_policy', log_format='Added IAM Policy: %(PolicyName)s', RoleName=details.role, PolicyName=details.policy, PolicyDocument=iam_policy) resource_action(client, action='create_user', log_format='Created User: %(UserName)s', UserName=details.user) resource_action(client, action='create_group', log_format='Created Group: %(GroupName)s', GroupName=details.group) resource_action( client, action='add_user_to_group', log_format='Added User to Group: %(UserName)s -> %(GroupName)s', GroupName=details.group, UserName=details.user) return True
python
def create_iam_resources(env='dev', app='', **_): """Create the IAM Resources for the application. Args: env (str): Deployment environment/account, i.e. dev, stage, prod. app (str): Spinnaker Application name. Returns: True upon successful completion. """ session = boto3.session.Session(profile_name=env) client = session.client('iam') app_properties = get_properties(env='pipeline') generated = get_details(env=env, app=app) generated_iam = generated.iam() app_details = collections.namedtuple('AppDetails', generated_iam.keys()) details = app_details(**generated_iam) LOG.debug('Application details: %s', details) deployment_type = app_properties['type'] role_trust_template = get_template( 'infrastructure/iam/trust/{0}_role.json.j2'.format(deployment_type), formats=generated) resource_action( client, action='create_role', log_format='Created Role: %(RoleName)s', RoleName=details.role, AssumeRolePolicyDocument=role_trust_template) resource_action( client, action='create_instance_profile', log_format='Created Instance Profile: %(InstanceProfileName)s', InstanceProfileName=details.profile) attach_profile_to_role(client, role_name=details.role, profile_name=details.profile) iam_policy = construct_policy(app=app, group=details.group, env=env, pipeline_settings=app_properties) if iam_policy: resource_action( client, action='put_role_policy', log_format='Added IAM Policy: %(PolicyName)s', RoleName=details.role, PolicyName=details.policy, PolicyDocument=iam_policy) resource_action(client, action='create_user', log_format='Created User: %(UserName)s', UserName=details.user) resource_action(client, action='create_group', log_format='Created Group: %(GroupName)s', GroupName=details.group) resource_action( client, action='add_user_to_group', log_format='Added User to Group: %(UserName)s -> %(GroupName)s', GroupName=details.group, UserName=details.user) return True
[ "def", "create_iam_resources", "(", "env", "=", "'dev'", ",", "app", "=", "''", ",", "*", "*", "_", ")", ":", "session", "=", "boto3", ".", "session", ".", "Session", "(", "profile_name", "=", "env", ")", "client", "=", "session", ".", "client", "(", "'iam'", ")", "app_properties", "=", "get_properties", "(", "env", "=", "'pipeline'", ")", "generated", "=", "get_details", "(", "env", "=", "env", ",", "app", "=", "app", ")", "generated_iam", "=", "generated", ".", "iam", "(", ")", "app_details", "=", "collections", ".", "namedtuple", "(", "'AppDetails'", ",", "generated_iam", ".", "keys", "(", ")", ")", "details", "=", "app_details", "(", "*", "*", "generated_iam", ")", "LOG", ".", "debug", "(", "'Application details: %s'", ",", "details", ")", "deployment_type", "=", "app_properties", "[", "'type'", "]", "role_trust_template", "=", "get_template", "(", "'infrastructure/iam/trust/{0}_role.json.j2'", ".", "format", "(", "deployment_type", ")", ",", "formats", "=", "generated", ")", "resource_action", "(", "client", ",", "action", "=", "'create_role'", ",", "log_format", "=", "'Created Role: %(RoleName)s'", ",", "RoleName", "=", "details", ".", "role", ",", "AssumeRolePolicyDocument", "=", "role_trust_template", ")", "resource_action", "(", "client", ",", "action", "=", "'create_instance_profile'", ",", "log_format", "=", "'Created Instance Profile: %(InstanceProfileName)s'", ",", "InstanceProfileName", "=", "details", ".", "profile", ")", "attach_profile_to_role", "(", "client", ",", "role_name", "=", "details", ".", "role", ",", "profile_name", "=", "details", ".", "profile", ")", "iam_policy", "=", "construct_policy", "(", "app", "=", "app", ",", "group", "=", "details", ".", "group", ",", "env", "=", "env", ",", "pipeline_settings", "=", "app_properties", ")", "if", "iam_policy", ":", "resource_action", "(", "client", ",", "action", "=", "'put_role_policy'", ",", "log_format", "=", "'Added IAM Policy: %(PolicyName)s'", ",", "RoleName", "=", "details", ".", "role", ",", "PolicyName", "=", "details", ".", "policy", ",", "PolicyDocument", "=", "iam_policy", ")", "resource_action", "(", "client", ",", "action", "=", "'create_user'", ",", "log_format", "=", "'Created User: %(UserName)s'", ",", "UserName", "=", "details", ".", "user", ")", "resource_action", "(", "client", ",", "action", "=", "'create_group'", ",", "log_format", "=", "'Created Group: %(GroupName)s'", ",", "GroupName", "=", "details", ".", "group", ")", "resource_action", "(", "client", ",", "action", "=", "'add_user_to_group'", ",", "log_format", "=", "'Added User to Group: %(UserName)s -> %(GroupName)s'", ",", "GroupName", "=", "details", ".", "group", ",", "UserName", "=", "details", ".", "user", ")", "return", "True" ]
Create the IAM Resources for the application. Args: env (str): Deployment environment/account, i.e. dev, stage, prod. app (str): Spinnaker Application name. Returns: True upon successful completion.
[ "Create", "the", "IAM", "Resources", "for", "the", "application", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/iam/create_iam.py#L29-L87
6,210
foremast/foremast
src/foremast/iam/create_iam.py
attach_profile_to_role
def attach_profile_to_role(client, role_name='forrest_unicorn_role', profile_name='forrest_unicorn_profile'): """Attach an IAM Instance Profile _profile_name_ to Role _role_name_. Args: role_name (str): Name of Role. profile_name (str): Name of Instance Profile. Returns: True upon successful completion. """ current_instance_profiles = resource_action( client, action='list_instance_profiles_for_role', log_format='Found Instance Profiles for %(RoleName)s.', RoleName=role_name)['InstanceProfiles'] for profile in current_instance_profiles: if profile['InstanceProfileName'] == profile_name: LOG.info('Found Instance Profile attached to Role: %s -> %s', profile_name, role_name) break else: for remove_profile in current_instance_profiles: resource_action( client, action='remove_role_from_instance_profile', log_format='Removed Instance Profile from Role: ' '%(InstanceProfileName)s -> %(RoleName)s', InstanceProfileName=remove_profile['InstanceProfileName'], RoleName=role_name) resource_action( client, action='add_role_to_instance_profile', log_format='Added Instance Profile to Role: ' '%(InstanceProfileName)s -> %(RoleName)s', InstanceProfileName=profile_name, RoleName=role_name) return True
python
def attach_profile_to_role(client, role_name='forrest_unicorn_role', profile_name='forrest_unicorn_profile'): """Attach an IAM Instance Profile _profile_name_ to Role _role_name_. Args: role_name (str): Name of Role. profile_name (str): Name of Instance Profile. Returns: True upon successful completion. """ current_instance_profiles = resource_action( client, action='list_instance_profiles_for_role', log_format='Found Instance Profiles for %(RoleName)s.', RoleName=role_name)['InstanceProfiles'] for profile in current_instance_profiles: if profile['InstanceProfileName'] == profile_name: LOG.info('Found Instance Profile attached to Role: %s -> %s', profile_name, role_name) break else: for remove_profile in current_instance_profiles: resource_action( client, action='remove_role_from_instance_profile', log_format='Removed Instance Profile from Role: ' '%(InstanceProfileName)s -> %(RoleName)s', InstanceProfileName=remove_profile['InstanceProfileName'], RoleName=role_name) resource_action( client, action='add_role_to_instance_profile', log_format='Added Instance Profile to Role: ' '%(InstanceProfileName)s -> %(RoleName)s', InstanceProfileName=profile_name, RoleName=role_name) return True
[ "def", "attach_profile_to_role", "(", "client", ",", "role_name", "=", "'forrest_unicorn_role'", ",", "profile_name", "=", "'forrest_unicorn_profile'", ")", ":", "current_instance_profiles", "=", "resource_action", "(", "client", ",", "action", "=", "'list_instance_profiles_for_role'", ",", "log_format", "=", "'Found Instance Profiles for %(RoleName)s.'", ",", "RoleName", "=", "role_name", ")", "[", "'InstanceProfiles'", "]", "for", "profile", "in", "current_instance_profiles", ":", "if", "profile", "[", "'InstanceProfileName'", "]", "==", "profile_name", ":", "LOG", ".", "info", "(", "'Found Instance Profile attached to Role: %s -> %s'", ",", "profile_name", ",", "role_name", ")", "break", "else", ":", "for", "remove_profile", "in", "current_instance_profiles", ":", "resource_action", "(", "client", ",", "action", "=", "'remove_role_from_instance_profile'", ",", "log_format", "=", "'Removed Instance Profile from Role: '", "'%(InstanceProfileName)s -> %(RoleName)s'", ",", "InstanceProfileName", "=", "remove_profile", "[", "'InstanceProfileName'", "]", ",", "RoleName", "=", "role_name", ")", "resource_action", "(", "client", ",", "action", "=", "'add_role_to_instance_profile'", ",", "log_format", "=", "'Added Instance Profile to Role: '", "'%(InstanceProfileName)s -> %(RoleName)s'", ",", "InstanceProfileName", "=", "profile_name", ",", "RoleName", "=", "role_name", ")", "return", "True" ]
Attach an IAM Instance Profile _profile_name_ to Role _role_name_. Args: role_name (str): Name of Role. profile_name (str): Name of Instance Profile. Returns: True upon successful completion.
[ "Attach", "an", "IAM", "Instance", "Profile", "_profile_name_", "to", "Role", "_role_name_", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/iam/create_iam.py#L90-L128
6,211
foremast/foremast
src/foremast/utils/elb.py
find_elb
def find_elb(name='', env='', region=''): """Get an application's AWS elb dns name. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS record """ LOG.info('Find %s ELB in %s [%s].', name, env, region) url = '{0}/applications/{1}/loadBalancers'.format(API_URL, name) response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT) assert response.ok elb_dns = None accounts = response.json() for account in accounts: if account['account'] == env and account['region'] == region: elb_dns = account['dnsname'] break else: raise SpinnakerElbNotFound('Elb for "{0}" in region {1} not found'.format(name, region)) LOG.info('Found: %s', elb_dns) return elb_dns
python
def find_elb(name='', env='', region=''): """Get an application's AWS elb dns name. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS record """ LOG.info('Find %s ELB in %s [%s].', name, env, region) url = '{0}/applications/{1}/loadBalancers'.format(API_URL, name) response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT) assert response.ok elb_dns = None accounts = response.json() for account in accounts: if account['account'] == env and account['region'] == region: elb_dns = account['dnsname'] break else: raise SpinnakerElbNotFound('Elb for "{0}" in region {1} not found'.format(name, region)) LOG.info('Found: %s', elb_dns) return elb_dns
[ "def", "find_elb", "(", "name", "=", "''", ",", "env", "=", "''", ",", "region", "=", "''", ")", ":", "LOG", ".", "info", "(", "'Find %s ELB in %s [%s].'", ",", "name", ",", "env", ",", "region", ")", "url", "=", "'{0}/applications/{1}/loadBalancers'", ".", "format", "(", "API_URL", ",", "name", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "verify", "=", "GATE_CA_BUNDLE", ",", "cert", "=", "GATE_CLIENT_CERT", ")", "assert", "response", ".", "ok", "elb_dns", "=", "None", "accounts", "=", "response", ".", "json", "(", ")", "for", "account", "in", "accounts", ":", "if", "account", "[", "'account'", "]", "==", "env", "and", "account", "[", "'region'", "]", "==", "region", ":", "elb_dns", "=", "account", "[", "'dnsname'", "]", "break", "else", ":", "raise", "SpinnakerElbNotFound", "(", "'Elb for \"{0}\" in region {1} not found'", ".", "format", "(", "name", ",", "region", ")", ")", "LOG", ".", "info", "(", "'Found: %s'", ",", "elb_dns", ")", "return", "elb_dns" ]
Get an application's AWS elb dns name. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS record
[ "Get", "an", "application", "s", "AWS", "elb", "dns", "name", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/elb.py#L30-L58
6,212
foremast/foremast
src/foremast/utils/elb.py
find_elb_dns_zone_id
def find_elb_dns_zone_id(name='', env='dev', region='us-east-1'): """Get an application's AWS elb dns zone id. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS zone ID """ LOG.info('Find %s ELB DNS Zone ID in %s [%s].', name, env, region) client = boto3.Session(profile_name=env).client('elb', region_name=region) elbs = client.describe_load_balancers(LoadBalancerNames=[name]) return elbs['LoadBalancerDescriptions'][0]['CanonicalHostedZoneNameID']
python
def find_elb_dns_zone_id(name='', env='dev', region='us-east-1'): """Get an application's AWS elb dns zone id. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS zone ID """ LOG.info('Find %s ELB DNS Zone ID in %s [%s].', name, env, region) client = boto3.Session(profile_name=env).client('elb', region_name=region) elbs = client.describe_load_balancers(LoadBalancerNames=[name]) return elbs['LoadBalancerDescriptions'][0]['CanonicalHostedZoneNameID']
[ "def", "find_elb_dns_zone_id", "(", "name", "=", "''", ",", "env", "=", "'dev'", ",", "region", "=", "'us-east-1'", ")", ":", "LOG", ".", "info", "(", "'Find %s ELB DNS Zone ID in %s [%s].'", ",", "name", ",", "env", ",", "region", ")", "client", "=", "boto3", ".", "Session", "(", "profile_name", "=", "env", ")", ".", "client", "(", "'elb'", ",", "region_name", "=", "region", ")", "elbs", "=", "client", ".", "describe_load_balancers", "(", "LoadBalancerNames", "=", "[", "name", "]", ")", "return", "elbs", "[", "'LoadBalancerDescriptions'", "]", "[", "0", "]", "[", "'CanonicalHostedZoneNameID'", "]" ]
Get an application's AWS elb dns zone id. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS zone ID
[ "Get", "an", "application", "s", "AWS", "elb", "dns", "zone", "id", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/elb.py#L61-L76
6,213
foremast/foremast
src/foremast/version.py
get_version
def get_version(): """Retrieve package version.""" version = 'Not installed.' try: version = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: pass return version
python
def get_version(): """Retrieve package version.""" version = 'Not installed.' try: version = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: pass return version
[ "def", "get_version", "(", ")", ":", "version", "=", "'Not installed.'", "try", ":", "version", "=", "pkg_resources", ".", "get_distribution", "(", "__package__", ")", ".", "version", "except", "pkg_resources", ".", "DistributionNotFound", ":", "pass", "return", "version" ]
Retrieve package version.
[ "Retrieve", "package", "version", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/version.py#L5-L14
6,214
szastupov/aiotg
aiotg/bot.py
Bot.loop
async def loop(self): """ Return bot's main loop as coroutine. Use with asyncio. :Example: >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(bot.loop()) or >>> loop = asyncio.get_event_loop() >>> loop.create_task(bot.loop()) """ self._running = True while self._running: updates = await self.api_call( "getUpdates", offset=self._offset + 1, timeout=self.api_timeout ) self._process_updates(updates)
python
async def loop(self): """ Return bot's main loop as coroutine. Use with asyncio. :Example: >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(bot.loop()) or >>> loop = asyncio.get_event_loop() >>> loop.create_task(bot.loop()) """ self._running = True while self._running: updates = await self.api_call( "getUpdates", offset=self._offset + 1, timeout=self.api_timeout ) self._process_updates(updates)
[ "async", "def", "loop", "(", "self", ")", ":", "self", ".", "_running", "=", "True", "while", "self", ".", "_running", ":", "updates", "=", "await", "self", ".", "api_call", "(", "\"getUpdates\"", ",", "offset", "=", "self", ".", "_offset", "+", "1", ",", "timeout", "=", "self", ".", "api_timeout", ")", "self", ".", "_process_updates", "(", "updates", ")" ]
Return bot's main loop as coroutine. Use with asyncio. :Example: >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(bot.loop()) or >>> loop = asyncio.get_event_loop() >>> loop.create_task(bot.loop())
[ "Return", "bot", "s", "main", "loop", "as", "coroutine", ".", "Use", "with", "asyncio", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L134-L153
6,215
szastupov/aiotg
aiotg/bot.py
Bot.run
def run(self, debug=False, reload=None): """ Convenience method for running bots in getUpdates mode :param bool debug: Enable debug logging and automatic reloading :param bool reload: Automatically reload bot on code change :Example: >>> if __name__ == '__main__': >>> bot.run() """ loop = asyncio.get_event_loop() logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) if reload is None: reload = debug bot_loop = asyncio.ensure_future(self.loop()) try: if reload: loop.run_until_complete(run_with_reloader(loop, bot_loop, self.stop)) else: loop.run_until_complete(bot_loop) # User cancels except KeyboardInterrupt: logger.debug("User cancelled") bot_loop.cancel() self.stop() # Stop loop finally: if AIOHTTP_23: loop.run_until_complete(self.session.close()) logger.debug("Closing loop") loop.stop() loop.close()
python
def run(self, debug=False, reload=None): """ Convenience method for running bots in getUpdates mode :param bool debug: Enable debug logging and automatic reloading :param bool reload: Automatically reload bot on code change :Example: >>> if __name__ == '__main__': >>> bot.run() """ loop = asyncio.get_event_loop() logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) if reload is None: reload = debug bot_loop = asyncio.ensure_future(self.loop()) try: if reload: loop.run_until_complete(run_with_reloader(loop, bot_loop, self.stop)) else: loop.run_until_complete(bot_loop) # User cancels except KeyboardInterrupt: logger.debug("User cancelled") bot_loop.cancel() self.stop() # Stop loop finally: if AIOHTTP_23: loop.run_until_complete(self.session.close()) logger.debug("Closing loop") loop.stop() loop.close()
[ "def", "run", "(", "self", ",", "debug", "=", "False", ",", "reload", "=", "None", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", "if", "debug", "else", "logging", ".", "INFO", ")", "if", "reload", "is", "None", ":", "reload", "=", "debug", "bot_loop", "=", "asyncio", ".", "ensure_future", "(", "self", ".", "loop", "(", ")", ")", "try", ":", "if", "reload", ":", "loop", ".", "run_until_complete", "(", "run_with_reloader", "(", "loop", ",", "bot_loop", ",", "self", ".", "stop", ")", ")", "else", ":", "loop", ".", "run_until_complete", "(", "bot_loop", ")", "# User cancels", "except", "KeyboardInterrupt", ":", "logger", ".", "debug", "(", "\"User cancelled\"", ")", "bot_loop", ".", "cancel", "(", ")", "self", ".", "stop", "(", ")", "# Stop loop", "finally", ":", "if", "AIOHTTP_23", ":", "loop", ".", "run_until_complete", "(", "self", ".", "session", ".", "close", "(", ")", ")", "logger", ".", "debug", "(", "\"Closing loop\"", ")", "loop", ".", "stop", "(", ")", "loop", ".", "close", "(", ")" ]
Convenience method for running bots in getUpdates mode :param bool debug: Enable debug logging and automatic reloading :param bool reload: Automatically reload bot on code change :Example: >>> if __name__ == '__main__': >>> bot.run()
[ "Convenience", "method", "for", "running", "bots", "in", "getUpdates", "mode" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L155-L196
6,216
szastupov/aiotg
aiotg/bot.py
Bot.run_webhook
def run_webhook(self, webhook_url, **options): """ Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram.org/bots/api#setwebhook """ loop = asyncio.get_event_loop() loop.run_until_complete(self.set_webhook(webhook_url, **options)) if webhook_url: url = urlparse(webhook_url) app = self.create_webhook_app(url.path, loop) host = os.environ.get("HOST", "0.0.0.0") port = int(os.environ.get("PORT", 0)) or url.port if AIOHTTP_23: app.on_cleanup.append(lambda _: self.session.close()) web.run_app(app, host=host, port=port) else: loop.run_until_complete(self.session.close())
python
def run_webhook(self, webhook_url, **options): """ Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram.org/bots/api#setwebhook """ loop = asyncio.get_event_loop() loop.run_until_complete(self.set_webhook(webhook_url, **options)) if webhook_url: url = urlparse(webhook_url) app = self.create_webhook_app(url.path, loop) host = os.environ.get("HOST", "0.0.0.0") port = int(os.environ.get("PORT", 0)) or url.port if AIOHTTP_23: app.on_cleanup.append(lambda _: self.session.close()) web.run_app(app, host=host, port=port) else: loop.run_until_complete(self.session.close())
[ "def", "run_webhook", "(", "self", ",", "webhook_url", ",", "*", "*", "options", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "loop", ".", "run_until_complete", "(", "self", ".", "set_webhook", "(", "webhook_url", ",", "*", "*", "options", ")", ")", "if", "webhook_url", ":", "url", "=", "urlparse", "(", "webhook_url", ")", "app", "=", "self", ".", "create_webhook_app", "(", "url", ".", "path", ",", "loop", ")", "host", "=", "os", ".", "environ", ".", "get", "(", "\"HOST\"", ",", "\"0.0.0.0\"", ")", "port", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "\"PORT\"", ",", "0", ")", ")", "or", "url", ".", "port", "if", "AIOHTTP_23", ":", "app", ".", "on_cleanup", ".", "append", "(", "lambda", "_", ":", "self", ".", "session", ".", "close", "(", ")", ")", "web", ".", "run_app", "(", "app", ",", "host", "=", "host", ",", "port", "=", "port", ")", "else", ":", "loop", ".", "run_until_complete", "(", "self", ".", "session", ".", "close", "(", ")", ")" ]
Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram.org/bots/api#setwebhook
[ "Convenience", "method", "for", "running", "bots", "in", "webhook", "mode" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L198-L222
6,217
szastupov/aiotg
aiotg/bot.py
Bot.command
def command(self, regexp): """ Register a new command :param str regexp: Regular expression matching the command to register :Example: >>> @bot.command(r"/echo (.+)") >>> def echo(chat, match): >>> return chat.reply(match.group(1)) """ def decorator(fn): self.add_command(regexp, fn) return fn return decorator
python
def command(self, regexp): """ Register a new command :param str regexp: Regular expression matching the command to register :Example: >>> @bot.command(r"/echo (.+)") >>> def echo(chat, match): >>> return chat.reply(match.group(1)) """ def decorator(fn): self.add_command(regexp, fn) return fn return decorator
[ "def", "command", "(", "self", ",", "regexp", ")", ":", "def", "decorator", "(", "fn", ")", ":", "self", ".", "add_command", "(", "regexp", ",", "fn", ")", "return", "fn", "return", "decorator" ]
Register a new command :param str regexp: Regular expression matching the command to register :Example: >>> @bot.command(r"/echo (.+)") >>> def echo(chat, match): >>> return chat.reply(match.group(1))
[ "Register", "a", "new", "command" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L236-L253
6,218
szastupov/aiotg
aiotg/bot.py
Bot.inline
def inline(self, callback): """ Set callback for inline queries :Example: >>> @bot.inline >>> def echo(iq): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ]) >>> @bot.inline(r"myinline-(.+)") >>> def echo(chat, iq, match): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ]) """ if callable(callback): self._default_inline = callback return callback elif isinstance(callback, str): def decorator(fn): self.add_inline(callback, fn) return fn return decorator else: raise TypeError("str expected {} given".format(type(callback)))
python
def inline(self, callback): """ Set callback for inline queries :Example: >>> @bot.inline >>> def echo(iq): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ]) >>> @bot.inline(r"myinline-(.+)") >>> def echo(chat, iq, match): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ]) """ if callable(callback): self._default_inline = callback return callback elif isinstance(callback, str): def decorator(fn): self.add_inline(callback, fn) return fn return decorator else: raise TypeError("str expected {} given".format(type(callback)))
[ "def", "inline", "(", "self", ",", "callback", ")", ":", "if", "callable", "(", "callback", ")", ":", "self", ".", "_default_inline", "=", "callback", "return", "callback", "elif", "isinstance", "(", "callback", ",", "str", ")", ":", "def", "decorator", "(", "fn", ")", ":", "self", ".", "add_inline", "(", "callback", ",", "fn", ")", "return", "fn", "return", "decorator", "else", ":", "raise", "TypeError", "(", "\"str expected {} given\"", ".", "format", "(", "type", "(", "callback", ")", ")", ")" ]
Set callback for inline queries :Example: >>> @bot.inline >>> def echo(iq): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ]) >>> @bot.inline(r"myinline-(.+)") >>> def echo(chat, iq, match): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ])
[ "Set", "callback", "for", "inline", "queries" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L276-L305
6,219
szastupov/aiotg
aiotg/bot.py
Bot.callback
def callback(self, callback): """ Set callback for callback queries :Example: >>> @bot.callback >>> def echo(chat, cq): >>> return cq.answer() >>> @bot.callback(r"buttonclick-(.+)") >>> def echo(chat, cq, match): >>> return chat.reply(match.group(1)) """ if callable(callback): self._default_callback = callback return callback elif isinstance(callback, str): def decorator(fn): self.add_callback(callback, fn) return fn return decorator else: raise TypeError("str expected {} given".format(type(callback)))
python
def callback(self, callback): """ Set callback for callback queries :Example: >>> @bot.callback >>> def echo(chat, cq): >>> return cq.answer() >>> @bot.callback(r"buttonclick-(.+)") >>> def echo(chat, cq, match): >>> return chat.reply(match.group(1)) """ if callable(callback): self._default_callback = callback return callback elif isinstance(callback, str): def decorator(fn): self.add_callback(callback, fn) return fn return decorator else: raise TypeError("str expected {} given".format(type(callback)))
[ "def", "callback", "(", "self", ",", "callback", ")", ":", "if", "callable", "(", "callback", ")", ":", "self", ".", "_default_callback", "=", "callback", "return", "callback", "elif", "isinstance", "(", "callback", ",", "str", ")", ":", "def", "decorator", "(", "fn", ")", ":", "self", ".", "add_callback", "(", "callback", ",", "fn", ")", "return", "fn", "return", "decorator", "else", ":", "raise", "TypeError", "(", "\"str expected {} given\"", ".", "format", "(", "type", "(", "callback", ")", ")", ")" ]
Set callback for callback queries :Example: >>> @bot.callback >>> def echo(chat, cq): >>> return cq.answer() >>> @bot.callback(r"buttonclick-(.+)") >>> def echo(chat, cq, match): >>> return chat.reply(match.group(1))
[ "Set", "callback", "for", "callback", "queries" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L313-L338
6,220
szastupov/aiotg
aiotg/bot.py
Bot.handle
def handle(self, msg_type): """ Set handler for specific message type :Example: >>> @bot.handle("audio") >>> def handle(chat, audio): >>> pass """ def wrap(callback): self._handlers[msg_type] = callback return callback return wrap
python
def handle(self, msg_type): """ Set handler for specific message type :Example: >>> @bot.handle("audio") >>> def handle(chat, audio): >>> pass """ def wrap(callback): self._handlers[msg_type] = callback return callback return wrap
[ "def", "handle", "(", "self", ",", "msg_type", ")", ":", "def", "wrap", "(", "callback", ")", ":", "self", ".", "_handlers", "[", "msg_type", "]", "=", "callback", "return", "callback", "return", "wrap" ]
Set handler for specific message type :Example: >>> @bot.handle("audio") >>> def handle(chat, audio): >>> pass
[ "Set", "handler", "for", "specific", "message", "type" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L359-L374
6,221
szastupov/aiotg
aiotg/bot.py
Bot.api_call
def api_call(self, method, **params): """ Call Telegram API. See https://core.telegram.org/bots/api for reference. :param str method: Telegram API method :param params: Arguments for the method call """ coro = self._api_call(method, **params) # Explicitly ensure that API call is executed return asyncio.ensure_future(coro)
python
def api_call(self, method, **params): """ Call Telegram API. See https://core.telegram.org/bots/api for reference. :param str method: Telegram API method :param params: Arguments for the method call """ coro = self._api_call(method, **params) # Explicitly ensure that API call is executed return asyncio.ensure_future(coro)
[ "def", "api_call", "(", "self", ",", "method", ",", "*", "*", "params", ")", ":", "coro", "=", "self", ".", "_api_call", "(", "method", ",", "*", "*", "params", ")", "# Explicitly ensure that API call is executed", "return", "asyncio", ".", "ensure_future", "(", "coro", ")" ]
Call Telegram API. See https://core.telegram.org/bots/api for reference. :param str method: Telegram API method :param params: Arguments for the method call
[ "Call", "Telegram", "API", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L400-L411
6,222
szastupov/aiotg
aiotg/bot.py
Bot.send_message
def send_message(self, chat_id, text, **options): """ Send a text message to chat :param int chat_id: ID of the chat to send the message to :param str text: Text to send :param options: Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage) """ return self.api_call("sendMessage", chat_id=chat_id, text=text, **options)
python
def send_message(self, chat_id, text, **options): """ Send a text message to chat :param int chat_id: ID of the chat to send the message to :param str text: Text to send :param options: Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage) """ return self.api_call("sendMessage", chat_id=chat_id, text=text, **options)
[ "def", "send_message", "(", "self", ",", "chat_id", ",", "text", ",", "*", "*", "options", ")", ":", "return", "self", ".", "api_call", "(", "\"sendMessage\"", ",", "chat_id", "=", "chat_id", ",", "text", "=", "text", ",", "*", "*", "options", ")" ]
Send a text message to chat :param int chat_id: ID of the chat to send the message to :param str text: Text to send :param options: Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage)
[ "Send", "a", "text", "message", "to", "chat" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L461-L470
6,223
szastupov/aiotg
aiotg/bot.py
Bot.edit_message_text
def edit_message_text(self, chat_id, message_id, text, **options): """ Edit a text message in a chat :param int chat_id: ID of the chat the message to edit is in :param int message_id: ID of the message to edit :param str text: Text to edit the message to :param options: Additional API options """ return self.api_call( "editMessageText", chat_id=chat_id, message_id=message_id, text=text, **options )
python
def edit_message_text(self, chat_id, message_id, text, **options): """ Edit a text message in a chat :param int chat_id: ID of the chat the message to edit is in :param int message_id: ID of the message to edit :param str text: Text to edit the message to :param options: Additional API options """ return self.api_call( "editMessageText", chat_id=chat_id, message_id=message_id, text=text, **options )
[ "def", "edit_message_text", "(", "self", ",", "chat_id", ",", "message_id", ",", "text", ",", "*", "*", "options", ")", ":", "return", "self", ".", "api_call", "(", "\"editMessageText\"", ",", "chat_id", "=", "chat_id", ",", "message_id", "=", "message_id", ",", "text", "=", "text", ",", "*", "*", "options", ")" ]
Edit a text message in a chat :param int chat_id: ID of the chat the message to edit is in :param int message_id: ID of the message to edit :param str text: Text to edit the message to :param options: Additional API options
[ "Edit", "a", "text", "message", "in", "a", "chat" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L472-L487
6,224
szastupov/aiotg
aiotg/bot.py
Bot.edit_message_reply_markup
def edit_message_reply_markup(self, chat_id, message_id, reply_markup, **options): """ Edit a reply markup of message in a chat :param int chat_id: ID of the chat the message to edit is in :param int message_id: ID of the message to edit :param str reply_markup: New inline keyboard markup for the message :param options: Additional API options """ return self.api_call( "editMessageReplyMarkup", chat_id=chat_id, message_id=message_id, reply_markup=reply_markup, **options )
python
def edit_message_reply_markup(self, chat_id, message_id, reply_markup, **options): """ Edit a reply markup of message in a chat :param int chat_id: ID of the chat the message to edit is in :param int message_id: ID of the message to edit :param str reply_markup: New inline keyboard markup for the message :param options: Additional API options """ return self.api_call( "editMessageReplyMarkup", chat_id=chat_id, message_id=message_id, reply_markup=reply_markup, **options )
[ "def", "edit_message_reply_markup", "(", "self", ",", "chat_id", ",", "message_id", ",", "reply_markup", ",", "*", "*", "options", ")", ":", "return", "self", ".", "api_call", "(", "\"editMessageReplyMarkup\"", ",", "chat_id", "=", "chat_id", ",", "message_id", "=", "message_id", ",", "reply_markup", "=", "reply_markup", ",", "*", "*", "options", ")" ]
Edit a reply markup of message in a chat :param int chat_id: ID of the chat the message to edit is in :param int message_id: ID of the message to edit :param str reply_markup: New inline keyboard markup for the message :param options: Additional API options
[ "Edit", "a", "reply", "markup", "of", "message", "in", "a", "chat" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L489-L504
6,225
szastupov/aiotg
aiotg/bot.py
Bot.download_file
def download_file(self, file_path, range=None): """ Download a file from Telegram servers """ headers = {"range": range} if range else None url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path) return self.session.get( url, headers=headers, proxy=self.proxy, proxy_auth=self.proxy_auth )
python
def download_file(self, file_path, range=None): """ Download a file from Telegram servers """ headers = {"range": range} if range else None url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path) return self.session.get( url, headers=headers, proxy=self.proxy, proxy_auth=self.proxy_auth )
[ "def", "download_file", "(", "self", ",", "file_path", ",", "range", "=", "None", ")", ":", "headers", "=", "{", "\"range\"", ":", "range", "}", "if", "range", "else", "None", "url", "=", "\"{0}/file/bot{1}/{2}\"", ".", "format", "(", "API_URL", ",", "self", ".", "api_token", ",", "file_path", ")", "return", "self", ".", "session", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "proxy", "=", "self", ".", "proxy", ",", "proxy_auth", "=", "self", ".", "proxy_auth", ")" ]
Download a file from Telegram servers
[ "Download", "a", "file", "from", "Telegram", "servers" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L516-L524
6,226
szastupov/aiotg
aiotg/bot.py
Bot.get_user_profile_photos
def get_user_profile_photos(self, user_id, **options): """ Get a list of profile pictures for a user :param int user_id: Unique identifier of the target user :param options: Additional getUserProfilePhotos options (see https://core.telegram.org/bots/api#getuserprofilephotos) """ return self.api_call("getUserProfilePhotos", user_id=str(user_id), **options)
python
def get_user_profile_photos(self, user_id, **options): """ Get a list of profile pictures for a user :param int user_id: Unique identifier of the target user :param options: Additional getUserProfilePhotos options (see https://core.telegram.org/bots/api#getuserprofilephotos) """ return self.api_call("getUserProfilePhotos", user_id=str(user_id), **options)
[ "def", "get_user_profile_photos", "(", "self", ",", "user_id", ",", "*", "*", "options", ")", ":", "return", "self", ".", "api_call", "(", "\"getUserProfilePhotos\"", ",", "user_id", "=", "str", "(", "user_id", ")", ",", "*", "*", "options", ")" ]
Get a list of profile pictures for a user :param int user_id: Unique identifier of the target user :param options: Additional getUserProfilePhotos options (see https://core.telegram.org/bots/api#getuserprofilephotos)
[ "Get", "a", "list", "of", "profile", "pictures", "for", "a", "user" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L526-L534
6,227
szastupov/aiotg
aiotg/bot.py
Bot.webhook_handle
async def webhook_handle(self, request): """ aiohttp.web handle for processing web hooks :Example: >>> from aiohttp import web >>> app = web.Application() >>> app.router.add_route('/webhook') """ update = await request.json(loads=self.json_deserialize) self._process_update(update) return web.Response()
python
async def webhook_handle(self, request): """ aiohttp.web handle for processing web hooks :Example: >>> from aiohttp import web >>> app = web.Application() >>> app.router.add_route('/webhook') """ update = await request.json(loads=self.json_deserialize) self._process_update(update) return web.Response()
[ "async", "def", "webhook_handle", "(", "self", ",", "request", ")", ":", "update", "=", "await", "request", ".", "json", "(", "loads", "=", "self", ".", "json_deserialize", ")", "self", ".", "_process_update", "(", "update", ")", "return", "web", ".", "Response", "(", ")" ]
aiohttp.web handle for processing web hooks :Example: >>> from aiohttp import web >>> app = web.Application() >>> app.router.add_route('/webhook')
[ "aiohttp", ".", "web", "handle", "for", "processing", "web", "hooks" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L547-L559
6,228
szastupov/aiotg
aiotg/bot.py
Bot.create_webhook_app
def create_webhook_app(self, path, loop=None): """ Shorthand for creating aiohttp.web.Application with registered webhook hanlde """ app = web.Application(loop=loop) app.router.add_route("POST", path, self.webhook_handle) return app
python
def create_webhook_app(self, path, loop=None): """ Shorthand for creating aiohttp.web.Application with registered webhook hanlde """ app = web.Application(loop=loop) app.router.add_route("POST", path, self.webhook_handle) return app
[ "def", "create_webhook_app", "(", "self", ",", "path", ",", "loop", "=", "None", ")", ":", "app", "=", "web", ".", "Application", "(", "loop", "=", "loop", ")", "app", ".", "router", ".", "add_route", "(", "\"POST\"", ",", "path", ",", "self", ".", "webhook_handle", ")", "return", "app" ]
Shorthand for creating aiohttp.web.Application with registered webhook hanlde
[ "Shorthand", "for", "creating", "aiohttp", ".", "web", ".", "Application", "with", "registered", "webhook", "hanlde" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L561-L567
6,229
szastupov/aiotg
aiotg/chat.py
Chat.send_text
def send_text(self, text, **options): """ Send a text message to the chat. :param str text: Text of the message to send :param options: Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage """ return self.bot.send_message(self.id, text, **options)
python
def send_text(self, text, **options): """ Send a text message to the chat. :param str text: Text of the message to send :param options: Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage """ return self.bot.send_message(self.id, text, **options)
[ "def", "send_text", "(", "self", ",", "text", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "send_message", "(", "self", ".", "id", ",", "text", ",", "*", "*", "options", ")" ]
Send a text message to the chat. :param str text: Text of the message to send :param options: Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage
[ "Send", "a", "text", "message", "to", "the", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L11-L19
6,230
szastupov/aiotg
aiotg/chat.py
Chat.reply
def reply(self, text, markup=None, parse_mode=None): """ Reply to the message this `Chat` object is based on. :param str text: Text of the message to send :param dict markup: Markup options :param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or ``None``) """ if markup is None: markup = {} return self.send_text( text, reply_to_message_id=self.message["message_id"], disable_web_page_preview="true", reply_markup=self.bot.json_serialize(markup), parse_mode=parse_mode, )
python
def reply(self, text, markup=None, parse_mode=None): """ Reply to the message this `Chat` object is based on. :param str text: Text of the message to send :param dict markup: Markup options :param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or ``None``) """ if markup is None: markup = {} return self.send_text( text, reply_to_message_id=self.message["message_id"], disable_web_page_preview="true", reply_markup=self.bot.json_serialize(markup), parse_mode=parse_mode, )
[ "def", "reply", "(", "self", ",", "text", ",", "markup", "=", "None", ",", "parse_mode", "=", "None", ")", ":", "if", "markup", "is", "None", ":", "markup", "=", "{", "}", "return", "self", ".", "send_text", "(", "text", ",", "reply_to_message_id", "=", "self", ".", "message", "[", "\"message_id\"", "]", ",", "disable_web_page_preview", "=", "\"true\"", ",", "reply_markup", "=", "self", ".", "bot", ".", "json_serialize", "(", "markup", ")", ",", "parse_mode", "=", "parse_mode", ",", ")" ]
Reply to the message this `Chat` object is based on. :param str text: Text of the message to send :param dict markup: Markup options :param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or ``None``)
[ "Reply", "to", "the", "message", "this", "Chat", "object", "is", "based", "on", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L21-L39
6,231
szastupov/aiotg
aiotg/chat.py
Chat.edit_text
def edit_text(self, message_id, text, markup=None, parse_mode=None): """ Edit the message in this chat. :param int message_id: ID of the message to edit :param str text: Text to edit the message to :param dict markup: Markup options :param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or ``None``) """ if markup is None: markup = {} return self.bot.edit_message_text( self.id, message_id, text, reply_markup=self.bot.json_serialize(markup), parse_mode=parse_mode, )
python
def edit_text(self, message_id, text, markup=None, parse_mode=None): """ Edit the message in this chat. :param int message_id: ID of the message to edit :param str text: Text to edit the message to :param dict markup: Markup options :param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or ``None``) """ if markup is None: markup = {} return self.bot.edit_message_text( self.id, message_id, text, reply_markup=self.bot.json_serialize(markup), parse_mode=parse_mode, )
[ "def", "edit_text", "(", "self", ",", "message_id", ",", "text", ",", "markup", "=", "None", ",", "parse_mode", "=", "None", ")", ":", "if", "markup", "is", "None", ":", "markup", "=", "{", "}", "return", "self", ".", "bot", ".", "edit_message_text", "(", "self", ".", "id", ",", "message_id", ",", "text", ",", "reply_markup", "=", "self", ".", "bot", ".", "json_serialize", "(", "markup", ")", ",", "parse_mode", "=", "parse_mode", ",", ")" ]
Edit the message in this chat. :param int message_id: ID of the message to edit :param str text: Text to edit the message to :param dict markup: Markup options :param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or ``None``)
[ "Edit", "the", "message", "in", "this", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L41-L60
6,232
szastupov/aiotg
aiotg/chat.py
Chat.edit_reply_markup
def edit_reply_markup(self, message_id, markup): """ Edit only reply markup of the message in this chat. :param int message_id: ID of the message to edit :param dict markup: Markup options """ return self.bot.edit_message_reply_markup( self.id, message_id, reply_markup=self.bot.json_serialize(markup) )
python
def edit_reply_markup(self, message_id, markup): """ Edit only reply markup of the message in this chat. :param int message_id: ID of the message to edit :param dict markup: Markup options """ return self.bot.edit_message_reply_markup( self.id, message_id, reply_markup=self.bot.json_serialize(markup) )
[ "def", "edit_reply_markup", "(", "self", ",", "message_id", ",", "markup", ")", ":", "return", "self", ".", "bot", ".", "edit_message_reply_markup", "(", "self", ".", "id", ",", "message_id", ",", "reply_markup", "=", "self", ".", "bot", ".", "json_serialize", "(", "markup", ")", ")" ]
Edit only reply markup of the message in this chat. :param int message_id: ID of the message to edit :param dict markup: Markup options
[ "Edit", "only", "reply", "markup", "of", "the", "message", "in", "this", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L62-L71
6,233
szastupov/aiotg
aiotg/chat.py
Chat.get_chat_member
def get_chat_member(self, user_id): """ Get information about a member of a chat. :param int user_id: Unique identifier of the target user """ return self.bot.api_call( "getChatMember", chat_id=str(self.id), user_id=str(user_id) )
python
def get_chat_member(self, user_id): """ Get information about a member of a chat. :param int user_id: Unique identifier of the target user """ return self.bot.api_call( "getChatMember", chat_id=str(self.id), user_id=str(user_id) )
[ "def", "get_chat_member", "(", "self", ",", "user_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"getChatMember\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "user_id", "=", "str", "(", "user_id", ")", ")" ]
Get information about a member of a chat. :param int user_id: Unique identifier of the target user
[ "Get", "information", "about", "a", "member", "of", "a", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L91-L99
6,234
szastupov/aiotg
aiotg/chat.py
Chat.send_sticker
def send_sticker(self, sticker, **options): """ Send a sticker to the chat. :param sticker: Sticker to send (file or string) :param options: Additional sendSticker options (see https://core.telegram.org/bots/api#sendsticker) """ return self.bot.api_call( "sendSticker", chat_id=str(self.id), sticker=sticker, **options )
python
def send_sticker(self, sticker, **options): """ Send a sticker to the chat. :param sticker: Sticker to send (file or string) :param options: Additional sendSticker options (see https://core.telegram.org/bots/api#sendsticker) """ return self.bot.api_call( "sendSticker", chat_id=str(self.id), sticker=sticker, **options )
[ "def", "send_sticker", "(", "self", ",", "sticker", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendSticker\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "sticker", "=", "sticker", ",", "*", "*", "options", ")" ]
Send a sticker to the chat. :param sticker: Sticker to send (file or string) :param options: Additional sendSticker options (see https://core.telegram.org/bots/api#sendsticker)
[ "Send", "a", "sticker", "to", "the", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L101-L111
6,235
szastupov/aiotg
aiotg/chat.py
Chat.send_audio
def send_audio(self, audio, **options): """ Send an mp3 audio file to the chat. :param audio: Object containing the audio data :param options: Additional sendAudio options (see https://core.telegram.org/bots/api#sendaudio) :Example: >>> with open("foo.mp3", "rb") as f: >>> await chat.send_audio(f, performer="Foo", title="Eversong") """ return self.bot.api_call( "sendAudio", chat_id=str(self.id), audio=audio, **options )
python
def send_audio(self, audio, **options): """ Send an mp3 audio file to the chat. :param audio: Object containing the audio data :param options: Additional sendAudio options (see https://core.telegram.org/bots/api#sendaudio) :Example: >>> with open("foo.mp3", "rb") as f: >>> await chat.send_audio(f, performer="Foo", title="Eversong") """ return self.bot.api_call( "sendAudio", chat_id=str(self.id), audio=audio, **options )
[ "def", "send_audio", "(", "self", ",", "audio", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendAudio\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "audio", "=", "audio", ",", "*", "*", "options", ")" ]
Send an mp3 audio file to the chat. :param audio: Object containing the audio data :param options: Additional sendAudio options (see https://core.telegram.org/bots/api#sendaudio) :Example: >>> with open("foo.mp3", "rb") as f: >>> await chat.send_audio(f, performer="Foo", title="Eversong")
[ "Send", "an", "mp3", "audio", "file", "to", "the", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L113-L128
6,236
szastupov/aiotg
aiotg/chat.py
Chat.send_photo
def send_photo(self, photo, caption="", **options): """ Send a photo to the chat. :param photo: Object containing the photo data :param str caption: Photo caption (optional) :param options: Additional sendPhoto options (see https://core.telegram.org/bots/api#sendphoto) :Example: >>> with open("foo.png", "rb") as f: >>> await chat.send_photo(f, caption="Would you look at this!") """ return self.bot.api_call( "sendPhoto", chat_id=str(self.id), photo=photo, caption=caption, **options )
python
def send_photo(self, photo, caption="", **options): """ Send a photo to the chat. :param photo: Object containing the photo data :param str caption: Photo caption (optional) :param options: Additional sendPhoto options (see https://core.telegram.org/bots/api#sendphoto) :Example: >>> with open("foo.png", "rb") as f: >>> await chat.send_photo(f, caption="Would you look at this!") """ return self.bot.api_call( "sendPhoto", chat_id=str(self.id), photo=photo, caption=caption, **options )
[ "def", "send_photo", "(", "self", ",", "photo", ",", "caption", "=", "\"\"", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendPhoto\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "photo", "=", "photo", ",", "caption", "=", "caption", ",", "*", "*", "options", ")" ]
Send a photo to the chat. :param photo: Object containing the photo data :param str caption: Photo caption (optional) :param options: Additional sendPhoto options (see https://core.telegram.org/bots/api#sendphoto) :Example: >>> with open("foo.png", "rb") as f: >>> await chat.send_photo(f, caption="Would you look at this!")
[ "Send", "a", "photo", "to", "the", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L130-L146
6,237
szastupov/aiotg
aiotg/chat.py
Chat.send_video
def send_video(self, video, caption="", **options): """ Send an mp4 video file to the chat. :param video: Object containing the video data :param str caption: Video caption (optional) :param options: Additional sendVideo options (see https://core.telegram.org/bots/api#sendvideo) :Example: >>> with open("foo.mp4", "rb") as f: >>> await chat.send_video(f) """ return self.bot.api_call( "sendVideo", chat_id=str(self.id), video=video, caption=caption, **options )
python
def send_video(self, video, caption="", **options): """ Send an mp4 video file to the chat. :param video: Object containing the video data :param str caption: Video caption (optional) :param options: Additional sendVideo options (see https://core.telegram.org/bots/api#sendvideo) :Example: >>> with open("foo.mp4", "rb") as f: >>> await chat.send_video(f) """ return self.bot.api_call( "sendVideo", chat_id=str(self.id), video=video, caption=caption, **options )
[ "def", "send_video", "(", "self", ",", "video", ",", "caption", "=", "\"\"", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendVideo\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "video", "=", "video", ",", "caption", "=", "caption", ",", "*", "*", "options", ")" ]
Send an mp4 video file to the chat. :param video: Object containing the video data :param str caption: Video caption (optional) :param options: Additional sendVideo options (see https://core.telegram.org/bots/api#sendvideo) :Example: >>> with open("foo.mp4", "rb") as f: >>> await chat.send_video(f)
[ "Send", "an", "mp4", "video", "file", "to", "the", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L148-L164
6,238
szastupov/aiotg
aiotg/chat.py
Chat.send_document
def send_document(self, document, caption="", **options): """ Send a general file. :param document: Object containing the document data :param str caption: Document caption (optional) :param options: Additional sendDocument options (see https://core.telegram.org/bots/api#senddocument) :Example: >>> with open("file.doc", "rb") as f: >>> await chat.send_document(f) """ return self.bot.api_call( "sendDocument", chat_id=str(self.id), document=document, caption=caption, **options )
python
def send_document(self, document, caption="", **options): """ Send a general file. :param document: Object containing the document data :param str caption: Document caption (optional) :param options: Additional sendDocument options (see https://core.telegram.org/bots/api#senddocument) :Example: >>> with open("file.doc", "rb") as f: >>> await chat.send_document(f) """ return self.bot.api_call( "sendDocument", chat_id=str(self.id), document=document, caption=caption, **options )
[ "def", "send_document", "(", "self", ",", "document", ",", "caption", "=", "\"\"", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendDocument\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "document", "=", "document", ",", "caption", "=", "caption", ",", "*", "*", "options", ")" ]
Send a general file. :param document: Object containing the document data :param str caption: Document caption (optional) :param options: Additional sendDocument options (see https://core.telegram.org/bots/api#senddocument) :Example: >>> with open("file.doc", "rb") as f: >>> await chat.send_document(f)
[ "Send", "a", "general", "file", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L166-L186
6,239
szastupov/aiotg
aiotg/chat.py
Chat.send_voice
def send_voice(self, voice, **options): """ Send an OPUS-encoded .ogg audio file. :param voice: Object containing the audio data :param options: Additional sendVoice options (see https://core.telegram.org/bots/api#sendvoice) :Example: >>> with open("voice.ogg", "rb") as f: >>> await chat.send_voice(f) """ return self.bot.api_call( "sendVoice", chat_id=str(self.id), voice=voice, **options )
python
def send_voice(self, voice, **options): """ Send an OPUS-encoded .ogg audio file. :param voice: Object containing the audio data :param options: Additional sendVoice options (see https://core.telegram.org/bots/api#sendvoice) :Example: >>> with open("voice.ogg", "rb") as f: >>> await chat.send_voice(f) """ return self.bot.api_call( "sendVoice", chat_id=str(self.id), voice=voice, **options )
[ "def", "send_voice", "(", "self", ",", "voice", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendVoice\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "voice", "=", "voice", ",", "*", "*", "options", ")" ]
Send an OPUS-encoded .ogg audio file. :param voice: Object containing the audio data :param options: Additional sendVoice options (see https://core.telegram.org/bots/api#sendvoice) :Example: >>> with open("voice.ogg", "rb") as f: >>> await chat.send_voice(f)
[ "Send", "an", "OPUS", "-", "encoded", ".", "ogg", "audio", "file", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L188-L203
6,240
szastupov/aiotg
aiotg/chat.py
Chat.send_location
def send_location(self, latitude, longitude, **options): """ Send a point on the map. :param float latitude: Latitude of the location :param float longitude: Longitude of the location :param options: Additional sendLocation options (see https://core.telegram.org/bots/api#sendlocation) """ return self.bot.api_call( "sendLocation", chat_id=self.id, latitude=latitude, longitude=longitude, **options )
python
def send_location(self, latitude, longitude, **options): """ Send a point on the map. :param float latitude: Latitude of the location :param float longitude: Longitude of the location :param options: Additional sendLocation options (see https://core.telegram.org/bots/api#sendlocation) """ return self.bot.api_call( "sendLocation", chat_id=self.id, latitude=latitude, longitude=longitude, **options )
[ "def", "send_location", "(", "self", ",", "latitude", ",", "longitude", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendLocation\"", ",", "chat_id", "=", "self", ".", "id", ",", "latitude", "=", "latitude", ",", "longitude", "=", "longitude", ",", "*", "*", "options", ")" ]
Send a point on the map. :param float latitude: Latitude of the location :param float longitude: Longitude of the location :param options: Additional sendLocation options (see https://core.telegram.org/bots/api#sendlocation)
[ "Send", "a", "point", "on", "the", "map", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L205-L220
6,241
szastupov/aiotg
aiotg/chat.py
Chat.send_venue
def send_venue(self, latitude, longitude, title, address, **options): """ Send information about a venue. :param float latitude: Latitude of the location :param float longitude: Longitude of the location :param str title: Name of the venue :param str address: Address of the venue :param options: Additional sendVenue options (see https://core.telegram.org/bots/api#sendvenue) """ return self.bot.api_call( "sendVenue", chat_id=self.id, latitude=latitude, longitude=longitude, title=title, address=address, **options )
python
def send_venue(self, latitude, longitude, title, address, **options): """ Send information about a venue. :param float latitude: Latitude of the location :param float longitude: Longitude of the location :param str title: Name of the venue :param str address: Address of the venue :param options: Additional sendVenue options (see https://core.telegram.org/bots/api#sendvenue) """ return self.bot.api_call( "sendVenue", chat_id=self.id, latitude=latitude, longitude=longitude, title=title, address=address, **options )
[ "def", "send_venue", "(", "self", ",", "latitude", ",", "longitude", ",", "title", ",", "address", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendVenue\"", ",", "chat_id", "=", "self", ".", "id", ",", "latitude", "=", "latitude", ",", "longitude", "=", "longitude", ",", "title", "=", "title", ",", "address", "=", "address", ",", "*", "*", "options", ")" ]
Send information about a venue. :param float latitude: Latitude of the location :param float longitude: Longitude of the location :param str title: Name of the venue :param str address: Address of the venue :param options: Additional sendVenue options (see https://core.telegram.org/bots/api#sendvenue)
[ "Send", "information", "about", "a", "venue", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L222-L241
6,242
szastupov/aiotg
aiotg/chat.py
Chat.send_contact
def send_contact(self, phone_number, first_name, **options): """ Send phone contacts. :param str phone_number: Contact's phone number :param str first_name: Contact's first name :param options: Additional sendContact options (see https://core.telegram.org/bots/api#sendcontact) """ return self.bot.api_call( "sendContact", chat_id=self.id, phone_number=phone_number, first_name=first_name, **options )
python
def send_contact(self, phone_number, first_name, **options): """ Send phone contacts. :param str phone_number: Contact's phone number :param str first_name: Contact's first name :param options: Additional sendContact options (see https://core.telegram.org/bots/api#sendcontact) """ return self.bot.api_call( "sendContact", chat_id=self.id, phone_number=phone_number, first_name=first_name, **options )
[ "def", "send_contact", "(", "self", ",", "phone_number", ",", "first_name", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendContact\"", ",", "chat_id", "=", "self", ".", "id", ",", "phone_number", "=", "phone_number", ",", "first_name", "=", "first_name", ",", "*", "*", "options", ")" ]
Send phone contacts. :param str phone_number: Contact's phone number :param str first_name: Contact's first name :param options: Additional sendContact options (see https://core.telegram.org/bots/api#sendcontact)
[ "Send", "phone", "contacts", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L243-L258
6,243
szastupov/aiotg
aiotg/chat.py
Chat.send_chat_action
def send_chat_action(self, action): """ Send a chat action, to tell the user that something is happening on the bot's side. Available actions: * `typing` for text messages * `upload_photo` for photos * `record_video` and `upload_video` for videos * `record_audio` and `upload_audio` for audio files * `upload_document` for general files * `find_location` for location data :param str action: Type of action to broadcast """ return self.bot.api_call("sendChatAction", chat_id=self.id, action=action)
python
def send_chat_action(self, action): """ Send a chat action, to tell the user that something is happening on the bot's side. Available actions: * `typing` for text messages * `upload_photo` for photos * `record_video` and `upload_video` for videos * `record_audio` and `upload_audio` for audio files * `upload_document` for general files * `find_location` for location data :param str action: Type of action to broadcast """ return self.bot.api_call("sendChatAction", chat_id=self.id, action=action)
[ "def", "send_chat_action", "(", "self", ",", "action", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendChatAction\"", ",", "chat_id", "=", "self", ".", "id", ",", "action", "=", "action", ")" ]
Send a chat action, to tell the user that something is happening on the bot's side. Available actions: * `typing` for text messages * `upload_photo` for photos * `record_video` and `upload_video` for videos * `record_audio` and `upload_audio` for audio files * `upload_document` for general files * `find_location` for location data :param str action: Type of action to broadcast
[ "Send", "a", "chat", "action", "to", "tell", "the", "user", "that", "something", "is", "happening", "on", "the", "bot", "s", "side", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L260-L276
6,244
szastupov/aiotg
aiotg/chat.py
Chat.send_media_group
def send_media_group( self, media: str, disable_notification: bool = False, reply_to_message_id: int = None, **options ): """ Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :param reply_to_message_id: If the messages are a reply, ID of the original message :param options: Additional sendMediaGroup options (see https://core.telegram.org/bots/api#sendmediagroup) :Example: >>> from json import dumps >>> photos_urls = [ >>> "https://telegram.org/img/t_logo.png", >>> "https://telegram.org/img/SiteAndroid.jpg?1", >>> "https://telegram.org/img/SiteiOs.jpg?1", >>> "https://telegram.org/img/SiteWP.jpg?2" >>> ] >>> tg_album = [] >>> count = len(photos_urls) >>> for i, p in enumerate(photos_urls): >>> { >>> 'type': 'photo', >>> 'media': p, >>> 'caption': f'{i} of {count}' >>> } >>> await chat.send_media_group(dumps(tg_album)) """ return self.bot.api_call( "sendMediaGroup", chat_id=str(self.id), media=media, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, **options )
python
def send_media_group( self, media: str, disable_notification: bool = False, reply_to_message_id: int = None, **options ): """ Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :param reply_to_message_id: If the messages are a reply, ID of the original message :param options: Additional sendMediaGroup options (see https://core.telegram.org/bots/api#sendmediagroup) :Example: >>> from json import dumps >>> photos_urls = [ >>> "https://telegram.org/img/t_logo.png", >>> "https://telegram.org/img/SiteAndroid.jpg?1", >>> "https://telegram.org/img/SiteiOs.jpg?1", >>> "https://telegram.org/img/SiteWP.jpg?2" >>> ] >>> tg_album = [] >>> count = len(photos_urls) >>> for i, p in enumerate(photos_urls): >>> { >>> 'type': 'photo', >>> 'media': p, >>> 'caption': f'{i} of {count}' >>> } >>> await chat.send_media_group(dumps(tg_album)) """ return self.bot.api_call( "sendMediaGroup", chat_id=str(self.id), media=media, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, **options )
[ "def", "send_media_group", "(", "self", ",", "media", ":", "str", ",", "disable_notification", ":", "bool", "=", "False", ",", "reply_to_message_id", ":", "int", "=", "None", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendMediaGroup\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "media", "=", "media", ",", "disable_notification", "=", "disable_notification", ",", "reply_to_message_id", "=", "reply_to_message_id", ",", "*", "*", "options", ")" ]
Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :param reply_to_message_id: If the messages are a reply, ID of the original message :param options: Additional sendMediaGroup options (see https://core.telegram.org/bots/api#sendmediagroup) :Example: >>> from json import dumps >>> photos_urls = [ >>> "https://telegram.org/img/t_logo.png", >>> "https://telegram.org/img/SiteAndroid.jpg?1", >>> "https://telegram.org/img/SiteiOs.jpg?1", >>> "https://telegram.org/img/SiteWP.jpg?2" >>> ] >>> tg_album = [] >>> count = len(photos_urls) >>> for i, p in enumerate(photos_urls): >>> { >>> 'type': 'photo', >>> 'media': p, >>> 'caption': f'{i} of {count}' >>> } >>> await chat.send_media_group(dumps(tg_album))
[ "Send", "a", "group", "of", "photos", "or", "videos", "as", "an", "album" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L278-L322
6,245
szastupov/aiotg
aiotg/chat.py
Chat.forward_message
def forward_message(self, from_chat_id, message_id): """ Forward a message from another chat to this chat. :param int from_chat_id: ID of the chat to forward the message from :param int message_id: ID of the message to forward """ return self.bot.api_call( "forwardMessage", chat_id=self.id, from_chat_id=from_chat_id, message_id=message_id, )
python
def forward_message(self, from_chat_id, message_id): """ Forward a message from another chat to this chat. :param int from_chat_id: ID of the chat to forward the message from :param int message_id: ID of the message to forward """ return self.bot.api_call( "forwardMessage", chat_id=self.id, from_chat_id=from_chat_id, message_id=message_id, )
[ "def", "forward_message", "(", "self", ",", "from_chat_id", ",", "message_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"forwardMessage\"", ",", "chat_id", "=", "self", ".", "id", ",", "from_chat_id", "=", "from_chat_id", ",", "message_id", "=", "message_id", ",", ")" ]
Forward a message from another chat to this chat. :param int from_chat_id: ID of the chat to forward the message from :param int message_id: ID of the message to forward
[ "Forward", "a", "message", "from", "another", "chat", "to", "this", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L324-L336
6,246
szastupov/aiotg
aiotg/chat.py
Chat.kick_chat_member
def kick_chat_member(self, user_id): """ Use this method to kick a user from a group or a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("kickChatMember", chat_id=self.id, user_id=user_id)
python
def kick_chat_member(self, user_id): """ Use this method to kick a user from a group or a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("kickChatMember", chat_id=self.id, user_id=user_id)
[ "def", "kick_chat_member", "(", "self", ",", "user_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"kickChatMember\"", ",", "chat_id", "=", "self", ".", "id", ",", "user_id", "=", "user_id", ")" ]
Use this method to kick a user from a group or a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user
[ "Use", "this", "method", "to", "kick", "a", "user", "from", "a", "group", "or", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "group", "for", "this", "to", "work", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L338-L345
6,247
szastupov/aiotg
aiotg/chat.py
Chat.unban_chat_member
def unban_chat_member(self, user_id): """ Use this method to unban a previously kicked user in a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("unbanChatMember", chat_id=self.id, user_id=user_id)
python
def unban_chat_member(self, user_id): """ Use this method to unban a previously kicked user in a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("unbanChatMember", chat_id=self.id, user_id=user_id)
[ "def", "unban_chat_member", "(", "self", ",", "user_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"unbanChatMember\"", ",", "chat_id", "=", "self", ".", "id", ",", "user_id", "=", "user_id", ")" ]
Use this method to unban a previously kicked user in a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user
[ "Use", "this", "method", "to", "unban", "a", "previously", "kicked", "user", "in", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "group", "for", "this", "to", "work", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L347-L354
6,248
szastupov/aiotg
aiotg/chat.py
Chat.delete_message
def delete_message(self, message_id): """ Delete message from this chat :param int message_id: ID of the message """ return self.bot.api_call( "deleteMessage", chat_id=self.id, message_id=message_id )
python
def delete_message(self, message_id): """ Delete message from this chat :param int message_id: ID of the message """ return self.bot.api_call( "deleteMessage", chat_id=self.id, message_id=message_id )
[ "def", "delete_message", "(", "self", ",", "message_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"deleteMessage\"", ",", "chat_id", "=", "self", ".", "id", ",", "message_id", "=", "message_id", ")" ]
Delete message from this chat :param int message_id: ID of the message
[ "Delete", "message", "from", "this", "chat" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L356-L364
6,249
szastupov/aiotg
aiotg/chat.py
Chat.from_message
def from_message(bot, message): """ Create a ``Chat`` object from a message. :param Bot bot: ``Bot`` object the message and chat belong to :param dict message: Message to base the object on :return: A chat object based on the message """ chat = message["chat"] return Chat(bot, chat["id"], chat["type"], message)
python
def from_message(bot, message): """ Create a ``Chat`` object from a message. :param Bot bot: ``Bot`` object the message and chat belong to :param dict message: Message to base the object on :return: A chat object based on the message """ chat = message["chat"] return Chat(bot, chat["id"], chat["type"], message)
[ "def", "from_message", "(", "bot", ",", "message", ")", ":", "chat", "=", "message", "[", "\"chat\"", "]", "return", "Chat", "(", "bot", ",", "chat", "[", "\"id\"", "]", ",", "chat", "[", "\"type\"", "]", ",", "message", ")" ]
Create a ``Chat`` object from a message. :param Bot bot: ``Bot`` object the message and chat belong to :param dict message: Message to base the object on :return: A chat object based on the message
[ "Create", "a", "Chat", "object", "from", "a", "message", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L386-L395
6,250
mnubo/kubernetes-py
kubernetes_py/K8sCronJob.py
K8sCronJob.run
def run(self, timeout=POD_RUN_WAIT_TIMEOUT_SECONDS): """ Forces a K8sCronJob to run immediately. - Fail if the K8sCronJob is currently running on-schedule. - Suspend the K8sCronJob. - Spawn a K8sPod. - Unsuspend a K8sCronJob. :param timeout: The timeout, in seconds, after which to kill the K8sPod. :return: None. """ if not isinstance(timeout, int): raise SyntaxError("K8sCronJob.run() timeout: [ {} ] is invalid.") if len(self.active): raise CronJobAlreadyRunningException( "K8sCronJob.run() failed: CronJob: [ {} ] " "has [ {} ] active Jobs currently.".format(self.name, len(self.active))) self.suspend = True self.update() pod = self.pod if timeout: self.POD_RUN_WAIT_TIMEOUT_SECONDS = timeout try: pod.create() start_time = time.time() while pod.phase not in ['Succeeded', 'Failed']: pod.get() time.sleep(2) self._check_timeout(start_time) except Exception as err: raise CronJobRunException("K8sCronJob.run() failed: {}".format(err)) finally: pod.delete() self.suspend = False self.update()
python
def run(self, timeout=POD_RUN_WAIT_TIMEOUT_SECONDS): """ Forces a K8sCronJob to run immediately. - Fail if the K8sCronJob is currently running on-schedule. - Suspend the K8sCronJob. - Spawn a K8sPod. - Unsuspend a K8sCronJob. :param timeout: The timeout, in seconds, after which to kill the K8sPod. :return: None. """ if not isinstance(timeout, int): raise SyntaxError("K8sCronJob.run() timeout: [ {} ] is invalid.") if len(self.active): raise CronJobAlreadyRunningException( "K8sCronJob.run() failed: CronJob: [ {} ] " "has [ {} ] active Jobs currently.".format(self.name, len(self.active))) self.suspend = True self.update() pod = self.pod if timeout: self.POD_RUN_WAIT_TIMEOUT_SECONDS = timeout try: pod.create() start_time = time.time() while pod.phase not in ['Succeeded', 'Failed']: pod.get() time.sleep(2) self._check_timeout(start_time) except Exception as err: raise CronJobRunException("K8sCronJob.run() failed: {}".format(err)) finally: pod.delete() self.suspend = False self.update()
[ "def", "run", "(", "self", ",", "timeout", "=", "POD_RUN_WAIT_TIMEOUT_SECONDS", ")", ":", "if", "not", "isinstance", "(", "timeout", ",", "int", ")", ":", "raise", "SyntaxError", "(", "\"K8sCronJob.run() timeout: [ {} ] is invalid.\"", ")", "if", "len", "(", "self", ".", "active", ")", ":", "raise", "CronJobAlreadyRunningException", "(", "\"K8sCronJob.run() failed: CronJob: [ {} ] \"", "\"has [ {} ] active Jobs currently.\"", ".", "format", "(", "self", ".", "name", ",", "len", "(", "self", ".", "active", ")", ")", ")", "self", ".", "suspend", "=", "True", "self", ".", "update", "(", ")", "pod", "=", "self", ".", "pod", "if", "timeout", ":", "self", ".", "POD_RUN_WAIT_TIMEOUT_SECONDS", "=", "timeout", "try", ":", "pod", ".", "create", "(", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "pod", ".", "phase", "not", "in", "[", "'Succeeded'", ",", "'Failed'", "]", ":", "pod", ".", "get", "(", ")", "time", ".", "sleep", "(", "2", ")", "self", ".", "_check_timeout", "(", "start_time", ")", "except", "Exception", "as", "err", ":", "raise", "CronJobRunException", "(", "\"K8sCronJob.run() failed: {}\"", ".", "format", "(", "err", ")", ")", "finally", ":", "pod", ".", "delete", "(", ")", "self", ".", "suspend", "=", "False", "self", ".", "update", "(", ")" ]
Forces a K8sCronJob to run immediately. - Fail if the K8sCronJob is currently running on-schedule. - Suspend the K8sCronJob. - Spawn a K8sPod. - Unsuspend a K8sCronJob. :param timeout: The timeout, in seconds, after which to kill the K8sPod. :return: None.
[ "Forces", "a", "K8sCronJob", "to", "run", "immediately", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sCronJob.py#L319-L362
6,251
mnubo/kubernetes-py
kubernetes_py/K8sReplicationController.py
K8sReplicationController.scale
def scale(config=None, name=None, replicas=None): """ Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas: the desired number of replicas. :return: An instance of K8sReplicationController """ rc = K8sReplicationController(config=config, name=name).get() rc.desired_replicas = replicas rc.update() rc._wait_for_desired_replicas() return rc
python
def scale(config=None, name=None, replicas=None): """ Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas: the desired number of replicas. :return: An instance of K8sReplicationController """ rc = K8sReplicationController(config=config, name=name).get() rc.desired_replicas = replicas rc.update() rc._wait_for_desired_replicas() return rc
[ "def", "scale", "(", "config", "=", "None", ",", "name", "=", "None", ",", "replicas", "=", "None", ")", ":", "rc", "=", "K8sReplicationController", "(", "config", "=", "config", ",", "name", "=", "name", ")", ".", "get", "(", ")", "rc", ".", "desired_replicas", "=", "replicas", "rc", ".", "update", "(", ")", "rc", ".", "_wait_for_desired_replicas", "(", ")", "return", "rc" ]
Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas: the desired number of replicas. :return: An instance of K8sReplicationController
[ "Scales", "the", "number", "of", "pods", "in", "the", "specified", "K8sReplicationController", "to", "the", "desired", "replica", "count", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sReplicationController.py#L517-L534
6,252
mnubo/kubernetes-py
kubernetes_py/K8sReplicationController.py
K8sReplicationController.rolling_update
def rolling_update(config=None, name=None, image=None, container_name=None, rc_new=None): """ Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the same RC name between updates, which is not supported by default by kubectl. :param config: An instance of K8sConfig. If omitted, reads from ~/.kube/config. :param name: The name of the ReplicationController we want to update. :param image: The updated image version we want applied. :param container_name: The name of the container we're targeting for the update. Required if more than one container is present. :param rc_new: An instance of K8sReplicationController with the new configuration to apply. Mutually exclusive with [image, container_name] if specified. :return: """ if name is None: raise SyntaxError( 'K8sReplicationController: name: [ {0} ] cannot be None.'.format(name)) if image is None and rc_new is None: raise SyntaxError( "K8sReplicationController: please specify either 'image' or 'rc_new'") if container_name is not None and image is not None and rc_new is not None: raise SyntaxError( 'K8sReplicationController: rc_new is mutually exclusive with an (container_name, image) pair.') return K8sReplicationController._rolling_update_init( config=config, name=name, image=image, container_name=container_name, rc_new=rc_new)
python
def rolling_update(config=None, name=None, image=None, container_name=None, rc_new=None): """ Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the same RC name between updates, which is not supported by default by kubectl. :param config: An instance of K8sConfig. If omitted, reads from ~/.kube/config. :param name: The name of the ReplicationController we want to update. :param image: The updated image version we want applied. :param container_name: The name of the container we're targeting for the update. Required if more than one container is present. :param rc_new: An instance of K8sReplicationController with the new configuration to apply. Mutually exclusive with [image, container_name] if specified. :return: """ if name is None: raise SyntaxError( 'K8sReplicationController: name: [ {0} ] cannot be None.'.format(name)) if image is None and rc_new is None: raise SyntaxError( "K8sReplicationController: please specify either 'image' or 'rc_new'") if container_name is not None and image is not None and rc_new is not None: raise SyntaxError( 'K8sReplicationController: rc_new is mutually exclusive with an (container_name, image) pair.') return K8sReplicationController._rolling_update_init( config=config, name=name, image=image, container_name=container_name, rc_new=rc_new)
[ "def", "rolling_update", "(", "config", "=", "None", ",", "name", "=", "None", ",", "image", "=", "None", ",", "container_name", "=", "None", ",", "rc_new", "=", "None", ")", ":", "if", "name", "is", "None", ":", "raise", "SyntaxError", "(", "'K8sReplicationController: name: [ {0} ] cannot be None.'", ".", "format", "(", "name", ")", ")", "if", "image", "is", "None", "and", "rc_new", "is", "None", ":", "raise", "SyntaxError", "(", "\"K8sReplicationController: please specify either 'image' or 'rc_new'\"", ")", "if", "container_name", "is", "not", "None", "and", "image", "is", "not", "None", "and", "rc_new", "is", "not", "None", ":", "raise", "SyntaxError", "(", "'K8sReplicationController: rc_new is mutually exclusive with an (container_name, image) pair.'", ")", "return", "K8sReplicationController", ".", "_rolling_update_init", "(", "config", "=", "config", ",", "name", "=", "name", ",", "image", "=", "image", ",", "container_name", "=", "container_name", ",", "rc_new", "=", "rc_new", ")" ]
Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the same RC name between updates, which is not supported by default by kubectl. :param config: An instance of K8sConfig. If omitted, reads from ~/.kube/config. :param name: The name of the ReplicationController we want to update. :param image: The updated image version we want applied. :param container_name: The name of the container we're targeting for the update. Required if more than one container is present. :param rc_new: An instance of K8sReplicationController with the new configuration to apply. Mutually exclusive with [image, container_name] if specified. :return:
[ "Performs", "a", "simple", "rolling", "update", "of", "a", "ReplicationController", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sReplicationController.py#L539-L577
6,253
mnubo/kubernetes-py
kubernetes_py/K8sReplicationController.py
K8sReplicationController.restart
def restart(self): """ Restart will force a rolling update of the current ReplicationController to the current revision. This essentially spawns a fresh copy of the RC and its pods. Useful when something is misbehaving. """ rc_new = copy.deepcopy(self) return K8sReplicationController.rolling_update( config=self.config, name=self.name, rc_new=rc_new)
python
def restart(self): """ Restart will force a rolling update of the current ReplicationController to the current revision. This essentially spawns a fresh copy of the RC and its pods. Useful when something is misbehaving. """ rc_new = copy.deepcopy(self) return K8sReplicationController.rolling_update( config=self.config, name=self.name, rc_new=rc_new)
[ "def", "restart", "(", "self", ")", ":", "rc_new", "=", "copy", ".", "deepcopy", "(", "self", ")", "return", "K8sReplicationController", ".", "rolling_update", "(", "config", "=", "self", ".", "config", ",", "name", "=", "self", ".", "name", ",", "rc_new", "=", "rc_new", ")" ]
Restart will force a rolling update of the current ReplicationController to the current revision. This essentially spawns a fresh copy of the RC and its pods. Useful when something is misbehaving.
[ "Restart", "will", "force", "a", "rolling", "update", "of", "the", "current", "ReplicationController", "to", "the", "current", "revision", ".", "This", "essentially", "spawns", "a", "fresh", "copy", "of", "the", "RC", "and", "its", "pods", ".", "Useful", "when", "something", "is", "misbehaving", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sReplicationController.py#L711-L721
6,254
mnubo/kubernetes-py
kubernetes_py/K8sNode.py
K8sNode._has_local_storage
def _has_local_storage(self, pod=None): """ Determines if a K8sPod has any local storage susceptible to be lost. :param pod: The K8sPod we're interested in. :return: a boolean. """ for vol in pod.volumes: if vol.emptyDir is not None: return True return False
python
def _has_local_storage(self, pod=None): """ Determines if a K8sPod has any local storage susceptible to be lost. :param pod: The K8sPod we're interested in. :return: a boolean. """ for vol in pod.volumes: if vol.emptyDir is not None: return True return False
[ "def", "_has_local_storage", "(", "self", ",", "pod", "=", "None", ")", ":", "for", "vol", "in", "pod", ".", "volumes", ":", "if", "vol", ".", "emptyDir", "is", "not", "None", ":", "return", "True", "return", "False" ]
Determines if a K8sPod has any local storage susceptible to be lost. :param pod: The K8sPod we're interested in. :return: a boolean.
[ "Determines", "if", "a", "K8sPod", "has", "any", "local", "storage", "susceptible", "to", "be", "lost", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sNode.py#L268-L280
6,255
mnubo/kubernetes-py
kubernetes_py/K8sDeployment.py
K8sDeployment.rollback
def rollback(self, revision=None, annotations=None): """ Performs a rollback of the Deployment. If the 'revision' parameter is omitted, we fetch the Deployment's system-generated annotation containing the current revision, and revert to the version immediately preceding the current version. :param revision: The revision to rollback to. :param annotations: Annotations we'd like to update. :return: self """ rollback = DeploymentRollback() rollback.name = self.name rollback_config = RollbackConfig() # to the specified revision if revision is not None: rollback_config.revision = revision # to the revision immediately preceding the current revision else: current_revision = int(self.get_annotation(self.REVISION_ANNOTATION)) rev = max(current_revision - 1, 0) rollback_config.revision = rev rollback.rollback_to = rollback_config if annotations is not None: rollback.updated_annotations = annotations url = '{base}/{name}/rollback'.format(base=self.base_url, name=self.name) state = self.request( method='POST', url=url, data=rollback.serialize()) if not state.get('success'): status = state.get('status', '') reason = state.get('data', dict()).get('message', None) message = 'K8sDeployment: ROLLBACK failed : HTTP {0} : {1}'.format(status, reason) raise BadRequestException(message) time.sleep(0.2) self._wait_for_desired_replicas() self.get() return self
python
def rollback(self, revision=None, annotations=None): """ Performs a rollback of the Deployment. If the 'revision' parameter is omitted, we fetch the Deployment's system-generated annotation containing the current revision, and revert to the version immediately preceding the current version. :param revision: The revision to rollback to. :param annotations: Annotations we'd like to update. :return: self """ rollback = DeploymentRollback() rollback.name = self.name rollback_config = RollbackConfig() # to the specified revision if revision is not None: rollback_config.revision = revision # to the revision immediately preceding the current revision else: current_revision = int(self.get_annotation(self.REVISION_ANNOTATION)) rev = max(current_revision - 1, 0) rollback_config.revision = rev rollback.rollback_to = rollback_config if annotations is not None: rollback.updated_annotations = annotations url = '{base}/{name}/rollback'.format(base=self.base_url, name=self.name) state = self.request( method='POST', url=url, data=rollback.serialize()) if not state.get('success'): status = state.get('status', '') reason = state.get('data', dict()).get('message', None) message = 'K8sDeployment: ROLLBACK failed : HTTP {0} : {1}'.format(status, reason) raise BadRequestException(message) time.sleep(0.2) self._wait_for_desired_replicas() self.get() return self
[ "def", "rollback", "(", "self", ",", "revision", "=", "None", ",", "annotations", "=", "None", ")", ":", "rollback", "=", "DeploymentRollback", "(", ")", "rollback", ".", "name", "=", "self", ".", "name", "rollback_config", "=", "RollbackConfig", "(", ")", "# to the specified revision", "if", "revision", "is", "not", "None", ":", "rollback_config", ".", "revision", "=", "revision", "# to the revision immediately preceding the current revision", "else", ":", "current_revision", "=", "int", "(", "self", ".", "get_annotation", "(", "self", ".", "REVISION_ANNOTATION", ")", ")", "rev", "=", "max", "(", "current_revision", "-", "1", ",", "0", ")", "rollback_config", ".", "revision", "=", "rev", "rollback", ".", "rollback_to", "=", "rollback_config", "if", "annotations", "is", "not", "None", ":", "rollback", ".", "updated_annotations", "=", "annotations", "url", "=", "'{base}/{name}/rollback'", ".", "format", "(", "base", "=", "self", ".", "base_url", ",", "name", "=", "self", ".", "name", ")", "state", "=", "self", ".", "request", "(", "method", "=", "'POST'", ",", "url", "=", "url", ",", "data", "=", "rollback", ".", "serialize", "(", ")", ")", "if", "not", "state", ".", "get", "(", "'success'", ")", ":", "status", "=", "state", ".", "get", "(", "'status'", ",", "''", ")", "reason", "=", "state", ".", "get", "(", "'data'", ",", "dict", "(", ")", ")", ".", "get", "(", "'message'", ",", "None", ")", "message", "=", "'K8sDeployment: ROLLBACK failed : HTTP {0} : {1}'", ".", "format", "(", "status", ",", "reason", ")", "raise", "BadRequestException", "(", "message", ")", "time", ".", "sleep", "(", "0.2", ")", "self", ".", "_wait_for_desired_replicas", "(", ")", "self", ".", "get", "(", ")", "return", "self" ]
Performs a rollback of the Deployment. If the 'revision' parameter is omitted, we fetch the Deployment's system-generated annotation containing the current revision, and revert to the version immediately preceding the current version. :param revision: The revision to rollback to. :param annotations: Annotations we'd like to update. :return: self
[ "Performs", "a", "rollback", "of", "the", "Deployment", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sDeployment.py#L363-L411
6,256
area4lib/area4
extras/sum_roll_dice.py
roll_dice
def roll_dice(): """ Roll a die. :return: None """ sums = 0 # will return the sum of the roll calls. while True: roll = random.randint(1, 6) sums += roll if(input("Enter y or n to continue: ").upper()) == 'N': print(sums) # prints the sum of the roll calls break
python
def roll_dice(): """ Roll a die. :return: None """ sums = 0 # will return the sum of the roll calls. while True: roll = random.randint(1, 6) sums += roll if(input("Enter y or n to continue: ").upper()) == 'N': print(sums) # prints the sum of the roll calls break
[ "def", "roll_dice", "(", ")", ":", "sums", "=", "0", "# will return the sum of the roll calls.", "while", "True", ":", "roll", "=", "random", ".", "randint", "(", "1", ",", "6", ")", "sums", "+=", "roll", "if", "(", "input", "(", "\"Enter y or n to continue: \"", ")", ".", "upper", "(", ")", ")", "==", "'N'", ":", "print", "(", "sums", ")", "# prints the sum of the roll calls", "break" ]
Roll a die. :return: None
[ "Roll", "a", "die", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/extras/sum_roll_dice.py#L6-L18
6,257
area4lib/area4
area4/util.py
get_raw_file
def get_raw_file(): """ Get the raw divider file in a string array. :return: the array :rtype: str """ with open("{0}/dividers.txt".format( os.path.abspath( os.path.dirname(__file__) ) ), mode="r") as file_handler: lines = file_handler.readlines() lines[35] = str( random.randint(0, 999999999999) ) return lines
python
def get_raw_file(): """ Get the raw divider file in a string array. :return: the array :rtype: str """ with open("{0}/dividers.txt".format( os.path.abspath( os.path.dirname(__file__) ) ), mode="r") as file_handler: lines = file_handler.readlines() lines[35] = str( random.randint(0, 999999999999) ) return lines
[ "def", "get_raw_file", "(", ")", ":", "with", "open", "(", "\"{0}/dividers.txt\"", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ")", ",", "mode", "=", "\"r\"", ")", "as", "file_handler", ":", "lines", "=", "file_handler", ".", "readlines", "(", ")", "lines", "[", "35", "]", "=", "str", "(", "random", ".", "randint", "(", "0", ",", "999999999999", ")", ")", "return", "lines" ]
Get the raw divider file in a string array. :return: the array :rtype: str
[ "Get", "the", "raw", "divider", "file", "in", "a", "string", "array", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/util.py#L13-L29
6,258
area4lib/area4
area4/util.py
reduce_to_unit
def reduce_to_unit(divider): """ Reduce a repeating divider to the smallest repeating unit possible. Note: this function is used by make-div :param divider: the divider :return: smallest repeating unit possible :rtype: str :Example: 'XxXxXxX' -> 'Xx' """ for unit_size in range(1, len(divider) // 2 + 1): length = len(divider) unit = divider[:unit_size] # Ignores mismatches in final characters: divider_item = divider[:unit_size * (length // unit_size)] if unit * (length // unit_size) == divider_item: return unit return divider
python
def reduce_to_unit(divider): """ Reduce a repeating divider to the smallest repeating unit possible. Note: this function is used by make-div :param divider: the divider :return: smallest repeating unit possible :rtype: str :Example: 'XxXxXxX' -> 'Xx' """ for unit_size in range(1, len(divider) // 2 + 1): length = len(divider) unit = divider[:unit_size] # Ignores mismatches in final characters: divider_item = divider[:unit_size * (length // unit_size)] if unit * (length // unit_size) == divider_item: return unit return divider
[ "def", "reduce_to_unit", "(", "divider", ")", ":", "for", "unit_size", "in", "range", "(", "1", ",", "len", "(", "divider", ")", "//", "2", "+", "1", ")", ":", "length", "=", "len", "(", "divider", ")", "unit", "=", "divider", "[", ":", "unit_size", "]", "# Ignores mismatches in final characters:", "divider_item", "=", "divider", "[", ":", "unit_size", "*", "(", "length", "//", "unit_size", ")", "]", "if", "unit", "*", "(", "length", "//", "unit_size", ")", "==", "divider_item", ":", "return", "unit", "return", "divider" ]
Reduce a repeating divider to the smallest repeating unit possible. Note: this function is used by make-div :param divider: the divider :return: smallest repeating unit possible :rtype: str :Example: 'XxXxXxX' -> 'Xx'
[ "Reduce", "a", "repeating", "divider", "to", "the", "smallest", "repeating", "unit", "possible", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/util.py#L42-L62
6,259
area4lib/area4
area4/__init__.py
splitter
def splitter(div, *args): """ Split text with dividers easily. :return: newly made value :rtype: str :param div: the divider """ retstr = "" if type(div) is int: div = theArray()[div] if len(args) == 1: return args[0] for s in args: retstr += s retstr += "\n" retstr += div retstr += "\n" return retstr
python
def splitter(div, *args): """ Split text with dividers easily. :return: newly made value :rtype: str :param div: the divider """ retstr = "" if type(div) is int: div = theArray()[div] if len(args) == 1: return args[0] for s in args: retstr += s retstr += "\n" retstr += div retstr += "\n" return retstr
[ "def", "splitter", "(", "div", ",", "*", "args", ")", ":", "retstr", "=", "\"\"", "if", "type", "(", "div", ")", "is", "int", ":", "div", "=", "theArray", "(", ")", "[", "div", "]", "if", "len", "(", "args", ")", "==", "1", ":", "return", "args", "[", "0", "]", "for", "s", "in", "args", ":", "retstr", "+=", "s", "retstr", "+=", "\"\\n\"", "retstr", "+=", "div", "retstr", "+=", "\"\\n\"", "return", "retstr" ]
Split text with dividers easily. :return: newly made value :rtype: str :param div: the divider
[ "Split", "text", "with", "dividers", "easily", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/__init__.py#L54-L72
6,260
area4lib/area4
area4/__init__.py
area4info
def area4info(): """ Get some info about the package. :return: Package info :rtype: str """ # Info variables: name = "area4" author = "https://github.com/RDIL" author_email = rdillib.get_email() description = "Dividers in Python, the easy way!" return "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}".format( "Name:", name, "Author:", author, "Author Email:", author_email, "Description:", description )
python
def area4info(): """ Get some info about the package. :return: Package info :rtype: str """ # Info variables: name = "area4" author = "https://github.com/RDIL" author_email = rdillib.get_email() description = "Dividers in Python, the easy way!" return "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}".format( "Name:", name, "Author:", author, "Author Email:", author_email, "Description:", description )
[ "def", "area4info", "(", ")", ":", "# Info variables:", "name", "=", "\"area4\"", "author", "=", "\"https://github.com/RDIL\"", "author_email", "=", "rdillib", ".", "get_email", "(", ")", "description", "=", "\"Dividers in Python, the easy way!\"", "return", "\"{0}: {1}\\n{2}: {3}\\n{4}: {5}\\n{6}: {7}\"", ".", "format", "(", "\"Name:\"", ",", "name", ",", "\"Author:\"", ",", "author", ",", "\"Author Email:\"", ",", "author_email", ",", "\"Description:\"", ",", "description", ")" ]
Get some info about the package. :return: Package info :rtype: str
[ "Get", "some", "info", "about", "the", "package", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/__init__.py#L75-L92
6,261
area4lib/area4
area4/__init__.py
make_div
def make_div(unit, length=24, start='', end='', literal_unit=False): """ Generate and return a custom divider. :param unit: str containing a repeating unit :param length: The maximum length (won't be exceeded) (default: 24) :param start: optional starting string :param end: optional ending string :param literal_unit: if True will not try to break unit down into smaller repeating subunits :return: a custom created divider :rtype: str :Example: custom_div = make_div(unit='=-', length=40, start='<', end='=>') note:: The generated string will be terminated at the specified length regardless of whether all the input strings have been fully replicated. A unit > 1 length may not be able to be replicated to extend to the full length. In this situation, the string will be shorter than the specified length. Example: unit of 10 characters and a specified length of 25 will contain 2 units for a total length of 20 characters. """ # Reduce the size if possible to extend closer to full length: if not literal_unit: unit = utils.reduce_to_unit(unit) repeats = (length - len(start + end)) // len(unit) return (start + unit * repeats + end)[0:length]
python
def make_div(unit, length=24, start='', end='', literal_unit=False): """ Generate and return a custom divider. :param unit: str containing a repeating unit :param length: The maximum length (won't be exceeded) (default: 24) :param start: optional starting string :param end: optional ending string :param literal_unit: if True will not try to break unit down into smaller repeating subunits :return: a custom created divider :rtype: str :Example: custom_div = make_div(unit='=-', length=40, start='<', end='=>') note:: The generated string will be terminated at the specified length regardless of whether all the input strings have been fully replicated. A unit > 1 length may not be able to be replicated to extend to the full length. In this situation, the string will be shorter than the specified length. Example: unit of 10 characters and a specified length of 25 will contain 2 units for a total length of 20 characters. """ # Reduce the size if possible to extend closer to full length: if not literal_unit: unit = utils.reduce_to_unit(unit) repeats = (length - len(start + end)) // len(unit) return (start + unit * repeats + end)[0:length]
[ "def", "make_div", "(", "unit", ",", "length", "=", "24", ",", "start", "=", "''", ",", "end", "=", "''", ",", "literal_unit", "=", "False", ")", ":", "# Reduce the size if possible to extend closer to full length:", "if", "not", "literal_unit", ":", "unit", "=", "utils", ".", "reduce_to_unit", "(", "unit", ")", "repeats", "=", "(", "length", "-", "len", "(", "start", "+", "end", ")", ")", "//", "len", "(", "unit", ")", "return", "(", "start", "+", "unit", "*", "repeats", "+", "end", ")", "[", "0", ":", "length", "]" ]
Generate and return a custom divider. :param unit: str containing a repeating unit :param length: The maximum length (won't be exceeded) (default: 24) :param start: optional starting string :param end: optional ending string :param literal_unit: if True will not try to break unit down into smaller repeating subunits :return: a custom created divider :rtype: str :Example: custom_div = make_div(unit='=-', length=40, start='<', end='=>') note:: The generated string will be terminated at the specified length regardless of whether all the input strings have been fully replicated. A unit > 1 length may not be able to be replicated to extend to the full length. In this situation, the string will be shorter than the specified length. Example: unit of 10 characters and a specified length of 25 will contain 2 units for a total length of 20 characters.
[ "Generate", "and", "return", "a", "custom", "divider", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/__init__.py#L95-L127
6,262
capnproto/pycapnp
buildutils/bundle.py
localpath
def localpath(*args): """construct an absolute path from a list relative to the root pycapnp directory""" plist = [ROOT] + list(args) return os.path.abspath(pjoin(*plist))
python
def localpath(*args): """construct an absolute path from a list relative to the root pycapnp directory""" plist = [ROOT] + list(args) return os.path.abspath(pjoin(*plist))
[ "def", "localpath", "(", "*", "args", ")", ":", "plist", "=", "[", "ROOT", "]", "+", "list", "(", "args", ")", "return", "os", ".", "path", ".", "abspath", "(", "pjoin", "(", "*", "plist", ")", ")" ]
construct an absolute path from a list relative to the root pycapnp directory
[ "construct", "an", "absolute", "path", "from", "a", "list", "relative", "to", "the", "root", "pycapnp", "directory" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/bundle.py#L53-L56
6,263
capnproto/pycapnp
buildutils/bundle.py
fetch_libcapnp
def fetch_libcapnp(savedir, url=None): """download and extract libcapnp""" is_preconfigured = False if url is None: url = libcapnp_url is_preconfigured = True dest = pjoin(savedir, 'capnproto-c++') if os.path.exists(dest): info("already have %s" % dest) return fname = fetch_archive(savedir, url, libcapnp) tf = tarfile.open(fname) with_version = pjoin(savedir, tf.firstmember.path) tf.extractall(savedir) tf.close() # remove version suffix: if is_preconfigured: shutil.move(with_version, dest) else: cpp_dir = os.path.join(with_version, 'c++') conf = Popen(['autoreconf', '-i'], cwd=cpp_dir) returncode = conf.wait() if returncode != 0: raise RuntimeError('Autoreconf failed. Make sure autotools are installed on your system.') shutil.move(cpp_dir, dest)
python
def fetch_libcapnp(savedir, url=None): """download and extract libcapnp""" is_preconfigured = False if url is None: url = libcapnp_url is_preconfigured = True dest = pjoin(savedir, 'capnproto-c++') if os.path.exists(dest): info("already have %s" % dest) return fname = fetch_archive(savedir, url, libcapnp) tf = tarfile.open(fname) with_version = pjoin(savedir, tf.firstmember.path) tf.extractall(savedir) tf.close() # remove version suffix: if is_preconfigured: shutil.move(with_version, dest) else: cpp_dir = os.path.join(with_version, 'c++') conf = Popen(['autoreconf', '-i'], cwd=cpp_dir) returncode = conf.wait() if returncode != 0: raise RuntimeError('Autoreconf failed. Make sure autotools are installed on your system.') shutil.move(cpp_dir, dest)
[ "def", "fetch_libcapnp", "(", "savedir", ",", "url", "=", "None", ")", ":", "is_preconfigured", "=", "False", "if", "url", "is", "None", ":", "url", "=", "libcapnp_url", "is_preconfigured", "=", "True", "dest", "=", "pjoin", "(", "savedir", ",", "'capnproto-c++'", ")", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "info", "(", "\"already have %s\"", "%", "dest", ")", "return", "fname", "=", "fetch_archive", "(", "savedir", ",", "url", ",", "libcapnp", ")", "tf", "=", "tarfile", ".", "open", "(", "fname", ")", "with_version", "=", "pjoin", "(", "savedir", ",", "tf", ".", "firstmember", ".", "path", ")", "tf", ".", "extractall", "(", "savedir", ")", "tf", ".", "close", "(", ")", "# remove version suffix:", "if", "is_preconfigured", ":", "shutil", ".", "move", "(", "with_version", ",", "dest", ")", "else", ":", "cpp_dir", "=", "os", ".", "path", ".", "join", "(", "with_version", ",", "'c++'", ")", "conf", "=", "Popen", "(", "[", "'autoreconf'", ",", "'-i'", "]", ",", "cwd", "=", "cpp_dir", ")", "returncode", "=", "conf", ".", "wait", "(", ")", "if", "returncode", "!=", "0", ":", "raise", "RuntimeError", "(", "'Autoreconf failed. Make sure autotools are installed on your system.'", ")", "shutil", ".", "move", "(", "cpp_dir", ",", "dest", ")" ]
download and extract libcapnp
[ "download", "and", "extract", "libcapnp" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/bundle.py#L76-L100
6,264
capnproto/pycapnp
buildutils/bundle.py
stage_platform_hpp
def stage_platform_hpp(capnproot): """stage platform.hpp into libcapnp sources Tries ./configure first (except on Windows), then falls back on included platform.hpp previously generated. """ platform_hpp = pjoin(capnproot, 'src', 'platform.hpp') if os.path.exists(platform_hpp): info("already have platform.hpp") return if os.name == 'nt': # stage msvc platform header platform_dir = pjoin(capnproot, 'builds', 'msvc') else: info("attempting ./configure to generate platform.hpp") p = Popen('./configure', cwd=capnproot, shell=True, stdout=PIPE, stderr=PIPE, ) o,e = p.communicate() if p.returncode: warn("failed to configure libcapnp:\n%s" % e) if sys.platform == 'darwin': platform_dir = pjoin(HERE, 'include_darwin') elif sys.platform.startswith('freebsd'): platform_dir = pjoin(HERE, 'include_freebsd') elif sys.platform.startswith('linux-armv'): platform_dir = pjoin(HERE, 'include_linux-armv') else: platform_dir = pjoin(HERE, 'include_linux') else: return info("staging platform.hpp from: %s" % platform_dir) shutil.copy(pjoin(platform_dir, 'platform.hpp'), platform_hpp)
python
def stage_platform_hpp(capnproot): """stage platform.hpp into libcapnp sources Tries ./configure first (except on Windows), then falls back on included platform.hpp previously generated. """ platform_hpp = pjoin(capnproot, 'src', 'platform.hpp') if os.path.exists(platform_hpp): info("already have platform.hpp") return if os.name == 'nt': # stage msvc platform header platform_dir = pjoin(capnproot, 'builds', 'msvc') else: info("attempting ./configure to generate platform.hpp") p = Popen('./configure', cwd=capnproot, shell=True, stdout=PIPE, stderr=PIPE, ) o,e = p.communicate() if p.returncode: warn("failed to configure libcapnp:\n%s" % e) if sys.platform == 'darwin': platform_dir = pjoin(HERE, 'include_darwin') elif sys.platform.startswith('freebsd'): platform_dir = pjoin(HERE, 'include_freebsd') elif sys.platform.startswith('linux-armv'): platform_dir = pjoin(HERE, 'include_linux-armv') else: platform_dir = pjoin(HERE, 'include_linux') else: return info("staging platform.hpp from: %s" % platform_dir) shutil.copy(pjoin(platform_dir, 'platform.hpp'), platform_hpp)
[ "def", "stage_platform_hpp", "(", "capnproot", ")", ":", "platform_hpp", "=", "pjoin", "(", "capnproot", ",", "'src'", ",", "'platform.hpp'", ")", "if", "os", ".", "path", ".", "exists", "(", "platform_hpp", ")", ":", "info", "(", "\"already have platform.hpp\"", ")", "return", "if", "os", ".", "name", "==", "'nt'", ":", "# stage msvc platform header", "platform_dir", "=", "pjoin", "(", "capnproot", ",", "'builds'", ",", "'msvc'", ")", "else", ":", "info", "(", "\"attempting ./configure to generate platform.hpp\"", ")", "p", "=", "Popen", "(", "'./configure'", ",", "cwd", "=", "capnproot", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", ")", "o", ",", "e", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "warn", "(", "\"failed to configure libcapnp:\\n%s\"", "%", "e", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_darwin'", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'freebsd'", ")", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_freebsd'", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux-armv'", ")", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_linux-armv'", ")", "else", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_linux'", ")", "else", ":", "return", "info", "(", "\"staging platform.hpp from: %s\"", "%", "platform_dir", ")", "shutil", ".", "copy", "(", "pjoin", "(", "platform_dir", ",", "'platform.hpp'", ")", ",", "platform_hpp", ")" ]
stage platform.hpp into libcapnp sources Tries ./configure first (except on Windows), then falls back on included platform.hpp previously generated.
[ "stage", "platform", ".", "hpp", "into", "libcapnp", "sources" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/bundle.py#L103-L138
6,265
capnproto/pycapnp
buildutils/patch.py
_find_library
def _find_library(lib, path): """Find a library""" for d in path[::-1]: real_lib = os.path.join(d, lib) if os.path.exists(real_lib): return real_lib
python
def _find_library(lib, path): """Find a library""" for d in path[::-1]: real_lib = os.path.join(d, lib) if os.path.exists(real_lib): return real_lib
[ "def", "_find_library", "(", "lib", ",", "path", ")", ":", "for", "d", "in", "path", "[", ":", ":", "-", "1", "]", ":", "real_lib", "=", "os", ".", "path", ".", "join", "(", "d", ",", "lib", ")", "if", "os", ".", "path", ".", "exists", "(", "real_lib", ")", ":", "return", "real_lib" ]
Find a library
[ "Find", "a", "library" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/patch.py#L30-L35
6,266
capnproto/pycapnp
buildutils/misc.py
get_output_error
def get_output_error(cmd): """Return the exit status, stdout, stderr of a command""" if not isinstance(cmd, list): cmd = [cmd] logging.debug("Running: %s", ' '.join(map(quote, cmd))) try: result = Popen(cmd, stdout=PIPE, stderr=PIPE) except IOError as e: return -1, u(''), u('Failed to run %r: %r' % (cmd, e)) so, se = result.communicate() # unicode: so = so.decode('utf8', 'replace') se = se.decode('utf8', 'replace') return result.returncode, so, se
python
def get_output_error(cmd): """Return the exit status, stdout, stderr of a command""" if not isinstance(cmd, list): cmd = [cmd] logging.debug("Running: %s", ' '.join(map(quote, cmd))) try: result = Popen(cmd, stdout=PIPE, stderr=PIPE) except IOError as e: return -1, u(''), u('Failed to run %r: %r' % (cmd, e)) so, se = result.communicate() # unicode: so = so.decode('utf8', 'replace') se = se.decode('utf8', 'replace') return result.returncode, so, se
[ "def", "get_output_error", "(", "cmd", ")", ":", "if", "not", "isinstance", "(", "cmd", ",", "list", ")", ":", "cmd", "=", "[", "cmd", "]", "logging", ".", "debug", "(", "\"Running: %s\"", ",", "' '", ".", "join", "(", "map", "(", "quote", ",", "cmd", ")", ")", ")", "try", ":", "result", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "except", "IOError", "as", "e", ":", "return", "-", "1", ",", "u", "(", "''", ")", ",", "u", "(", "'Failed to run %r: %r'", "%", "(", "cmd", ",", "e", ")", ")", "so", ",", "se", "=", "result", ".", "communicate", "(", ")", "# unicode:", "so", "=", "so", ".", "decode", "(", "'utf8'", ",", "'replace'", ")", "se", "=", "se", ".", "decode", "(", "'utf8'", ",", "'replace'", ")", "return", "result", ".", "returncode", ",", "so", ",", "se" ]
Return the exit status, stdout, stderr of a command
[ "Return", "the", "exit", "status", "stdout", "stderr", "of", "a", "command" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/misc.py#L50-L64
6,267
capnproto/pycapnp
buildutils/config.py
load_config
def load_config(name, base='conf'): """Load config dict from JSON""" fname = pjoin(base, name + '.json') if not os.path.exists(fname): return {} try: with open(fname) as f: cfg = json.load(f) except Exception as e: warn("Couldn't load %s: %s" % (fname, e)) cfg = {} return cfg
python
def load_config(name, base='conf'): """Load config dict from JSON""" fname = pjoin(base, name + '.json') if not os.path.exists(fname): return {} try: with open(fname) as f: cfg = json.load(f) except Exception as e: warn("Couldn't load %s: %s" % (fname, e)) cfg = {} return cfg
[ "def", "load_config", "(", "name", ",", "base", "=", "'conf'", ")", ":", "fname", "=", "pjoin", "(", "base", ",", "name", "+", "'.json'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "{", "}", "try", ":", "with", "open", "(", "fname", ")", "as", "f", ":", "cfg", "=", "json", ".", "load", "(", "f", ")", "except", "Exception", "as", "e", ":", "warn", "(", "\"Couldn't load %s: %s\"", "%", "(", "fname", ",", "e", ")", ")", "cfg", "=", "{", "}", "return", "cfg" ]
Load config dict from JSON
[ "Load", "config", "dict", "from", "JSON" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L31-L42
6,268
capnproto/pycapnp
buildutils/config.py
save_config
def save_config(name, data, base='conf'): """Save config dict to JSON""" if not os.path.exists(base): os.mkdir(base) fname = pjoin(base, name+'.json') with open(fname, 'w') as f: json.dump(data, f, indent=2)
python
def save_config(name, data, base='conf'): """Save config dict to JSON""" if not os.path.exists(base): os.mkdir(base) fname = pjoin(base, name+'.json') with open(fname, 'w') as f: json.dump(data, f, indent=2)
[ "def", "save_config", "(", "name", ",", "data", ",", "base", "=", "'conf'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "base", ")", ":", "os", ".", "mkdir", "(", "base", ")", "fname", "=", "pjoin", "(", "base", ",", "name", "+", "'.json'", ")", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ",", "indent", "=", "2", ")" ]
Save config dict to JSON
[ "Save", "config", "dict", "to", "JSON" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L45-L51
6,269
capnproto/pycapnp
buildutils/config.py
get_eargs
def get_eargs(): """ Look for options in environment vars """ settings = {} zmq = os.environ.get("ZMQ_PREFIX", None) if zmq is not None: debug("Found environ var ZMQ_PREFIX=%s" % zmq) settings['zmq_prefix'] = zmq return settings
python
def get_eargs(): """ Look for options in environment vars """ settings = {} zmq = os.environ.get("ZMQ_PREFIX", None) if zmq is not None: debug("Found environ var ZMQ_PREFIX=%s" % zmq) settings['zmq_prefix'] = zmq return settings
[ "def", "get_eargs", "(", ")", ":", "settings", "=", "{", "}", "zmq", "=", "os", ".", "environ", ".", "get", "(", "\"ZMQ_PREFIX\"", ",", "None", ")", "if", "zmq", "is", "not", "None", ":", "debug", "(", "\"Found environ var ZMQ_PREFIX=%s\"", "%", "zmq", ")", "settings", "[", "'zmq_prefix'", "]", "=", "zmq", "return", "settings" ]
Look for options in environment vars
[ "Look", "for", "options", "in", "environment", "vars" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L58-L68
6,270
capnproto/pycapnp
buildutils/config.py
cfg2dict
def cfg2dict(cfg): """turn a ConfigParser into a nested dict because ConfigParser objects are dumb. """ d = {} for section in cfg.sections(): d[section] = dict(cfg.items(section)) return d
python
def cfg2dict(cfg): """turn a ConfigParser into a nested dict because ConfigParser objects are dumb. """ d = {} for section in cfg.sections(): d[section] = dict(cfg.items(section)) return d
[ "def", "cfg2dict", "(", "cfg", ")", ":", "d", "=", "{", "}", "for", "section", "in", "cfg", ".", "sections", "(", ")", ":", "d", "[", "section", "]", "=", "dict", "(", "cfg", ".", "items", "(", "section", ")", ")", "return", "d" ]
turn a ConfigParser into a nested dict because ConfigParser objects are dumb.
[ "turn", "a", "ConfigParser", "into", "a", "nested", "dict", "because", "ConfigParser", "objects", "are", "dumb", "." ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L70-L78
6,271
capnproto/pycapnp
buildutils/config.py
get_cfg_args
def get_cfg_args(): """ Look for options in setup.cfg """ if not os.path.exists('setup.cfg'): return {} cfg = ConfigParser() cfg.read('setup.cfg') cfg = cfg2dict(cfg) g = cfg.setdefault('global', {}) # boolean keys: for key in ['libzmq_extension', 'bundle_libzmq_dylib', 'no_libzmq_extension', 'have_sys_un_h', 'skip_check_zmq', ]: if key in g: g[key] = eval(g[key]) # globals go to top level cfg.update(cfg.pop('global')) return cfg
python
def get_cfg_args(): """ Look for options in setup.cfg """ if not os.path.exists('setup.cfg'): return {} cfg = ConfigParser() cfg.read('setup.cfg') cfg = cfg2dict(cfg) g = cfg.setdefault('global', {}) # boolean keys: for key in ['libzmq_extension', 'bundle_libzmq_dylib', 'no_libzmq_extension', 'have_sys_un_h', 'skip_check_zmq', ]: if key in g: g[key] = eval(g[key]) # globals go to top level cfg.update(cfg.pop('global')) return cfg
[ "def", "get_cfg_args", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "'setup.cfg'", ")", ":", "return", "{", "}", "cfg", "=", "ConfigParser", "(", ")", "cfg", ".", "read", "(", "'setup.cfg'", ")", "cfg", "=", "cfg2dict", "(", "cfg", ")", "g", "=", "cfg", ".", "setdefault", "(", "'global'", ",", "{", "}", ")", "# boolean keys:", "for", "key", "in", "[", "'libzmq_extension'", ",", "'bundle_libzmq_dylib'", ",", "'no_libzmq_extension'", ",", "'have_sys_un_h'", ",", "'skip_check_zmq'", ",", "]", ":", "if", "key", "in", "g", ":", "g", "[", "key", "]", "=", "eval", "(", "g", "[", "key", "]", ")", "# globals go to top level", "cfg", ".", "update", "(", "cfg", ".", "pop", "(", "'global'", ")", ")", "return", "cfg" ]
Look for options in setup.cfg
[ "Look", "for", "options", "in", "setup", ".", "cfg" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L80-L102
6,272
capnproto/pycapnp
buildutils/config.py
config_from_prefix
def config_from_prefix(prefix): """Get config from zmq prefix""" settings = {} if prefix.lower() in ('default', 'auto', ''): settings['zmq_prefix'] = '' settings['libzmq_extension'] = False settings['no_libzmq_extension'] = False elif prefix.lower() in ('bundled', 'extension'): settings['zmq_prefix'] = '' settings['libzmq_extension'] = True settings['no_libzmq_extension'] = False else: settings['zmq_prefix'] = prefix settings['libzmq_extension'] = False settings['no_libzmq_extension'] = True return settings
python
def config_from_prefix(prefix): """Get config from zmq prefix""" settings = {} if prefix.lower() in ('default', 'auto', ''): settings['zmq_prefix'] = '' settings['libzmq_extension'] = False settings['no_libzmq_extension'] = False elif prefix.lower() in ('bundled', 'extension'): settings['zmq_prefix'] = '' settings['libzmq_extension'] = True settings['no_libzmq_extension'] = False else: settings['zmq_prefix'] = prefix settings['libzmq_extension'] = False settings['no_libzmq_extension'] = True return settings
[ "def", "config_from_prefix", "(", "prefix", ")", ":", "settings", "=", "{", "}", "if", "prefix", ".", "lower", "(", ")", "in", "(", "'default'", ",", "'auto'", ",", "''", ")", ":", "settings", "[", "'zmq_prefix'", "]", "=", "''", "settings", "[", "'libzmq_extension'", "]", "=", "False", "settings", "[", "'no_libzmq_extension'", "]", "=", "False", "elif", "prefix", ".", "lower", "(", ")", "in", "(", "'bundled'", ",", "'extension'", ")", ":", "settings", "[", "'zmq_prefix'", "]", "=", "''", "settings", "[", "'libzmq_extension'", "]", "=", "True", "settings", "[", "'no_libzmq_extension'", "]", "=", "False", "else", ":", "settings", "[", "'zmq_prefix'", "]", "=", "prefix", "settings", "[", "'libzmq_extension'", "]", "=", "False", "settings", "[", "'no_libzmq_extension'", "]", "=", "True", "return", "settings" ]
Get config from zmq prefix
[ "Get", "config", "from", "zmq", "prefix" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L104-L119
6,273
capnproto/pycapnp
buildutils/config.py
merge
def merge(into, d): """merge two containers into is updated, d has priority """ if isinstance(into, dict): for key in d.keys(): if key not in into: into[key] = d[key] else: into[key] = merge(into[key], d[key]) return into elif isinstance(into, list): return into + d else: return d
python
def merge(into, d): """merge two containers into is updated, d has priority """ if isinstance(into, dict): for key in d.keys(): if key not in into: into[key] = d[key] else: into[key] = merge(into[key], d[key]) return into elif isinstance(into, list): return into + d else: return d
[ "def", "merge", "(", "into", ",", "d", ")", ":", "if", "isinstance", "(", "into", ",", "dict", ")", ":", "for", "key", "in", "d", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "into", ":", "into", "[", "key", "]", "=", "d", "[", "key", "]", "else", ":", "into", "[", "key", "]", "=", "merge", "(", "into", "[", "key", "]", ",", "d", "[", "key", "]", ")", "return", "into", "elif", "isinstance", "(", "into", ",", "list", ")", ":", "return", "into", "+", "d", "else", ":", "return", "d" ]
merge two containers into is updated, d has priority
[ "merge", "two", "containers", "into", "is", "updated", "d", "has", "priority" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L121-L136
6,274
capnproto/pycapnp
buildutils/config.py
discover_settings
def discover_settings(conf_base=None): """ Discover custom settings for ZMQ path""" settings = { 'zmq_prefix': '', 'libzmq_extension': False, 'no_libzmq_extension': False, 'skip_check_zmq': False, 'build_ext': {}, 'bdist_egg': {}, } if sys.platform.startswith('win'): settings['have_sys_un_h'] = False if conf_base: # lowest priority merge(settings, load_config('config', conf_base)) merge(settings, get_cfg_args()) merge(settings, get_eargs()) return settings
python
def discover_settings(conf_base=None): """ Discover custom settings for ZMQ path""" settings = { 'zmq_prefix': '', 'libzmq_extension': False, 'no_libzmq_extension': False, 'skip_check_zmq': False, 'build_ext': {}, 'bdist_egg': {}, } if sys.platform.startswith('win'): settings['have_sys_un_h'] = False if conf_base: # lowest priority merge(settings, load_config('config', conf_base)) merge(settings, get_cfg_args()) merge(settings, get_eargs()) return settings
[ "def", "discover_settings", "(", "conf_base", "=", "None", ")", ":", "settings", "=", "{", "'zmq_prefix'", ":", "''", ",", "'libzmq_extension'", ":", "False", ",", "'no_libzmq_extension'", ":", "False", ",", "'skip_check_zmq'", ":", "False", ",", "'build_ext'", ":", "{", "}", ",", "'bdist_egg'", ":", "{", "}", ",", "}", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "settings", "[", "'have_sys_un_h'", "]", "=", "False", "if", "conf_base", ":", "# lowest priority", "merge", "(", "settings", ",", "load_config", "(", "'config'", ",", "conf_base", ")", ")", "merge", "(", "settings", ",", "get_cfg_args", "(", ")", ")", "merge", "(", "settings", ",", "get_eargs", "(", ")", ")", "return", "settings" ]
Discover custom settings for ZMQ path
[ "Discover", "custom", "settings", "for", "ZMQ", "path" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L138-L157
6,275
capnproto/pycapnp
examples/calculator_server.py
FunctionImpl.call
def call(self, params, _context, **kwargs): '''Note that we're returning a Promise object here, and bypassing the helper functionality that normally sets the results struct from the returned object. Instead, we set _context.results directly inside of another promise''' assert len(params) == self.paramCount # using setattr because '=' is not allowed inside of lambdas return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
python
def call(self, params, _context, **kwargs): '''Note that we're returning a Promise object here, and bypassing the helper functionality that normally sets the results struct from the returned object. Instead, we set _context.results directly inside of another promise''' assert len(params) == self.paramCount # using setattr because '=' is not allowed inside of lambdas return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
[ "def", "call", "(", "self", ",", "params", ",", "_context", ",", "*", "*", "kwargs", ")", ":", "assert", "len", "(", "params", ")", "==", "self", ".", "paramCount", "# using setattr because '=' is not allowed inside of lambdas", "return", "evaluate_impl", "(", "self", ".", "body", ",", "params", ")", ".", "then", "(", "lambda", "value", ":", "setattr", "(", "_context", ".", "results", ",", "'value'", ",", "value", ")", ")" ]
Note that we're returning a Promise object here, and bypassing the helper functionality that normally sets the results struct from the returned object. Instead, we set _context.results directly inside of another promise
[ "Note", "that", "we", "re", "returning", "a", "Promise", "object", "here", "and", "bypassing", "the", "helper", "functionality", "that", "normally", "sets", "the", "results", "struct", "from", "the", "returned", "object", ".", "Instead", "we", "set", "_context", ".", "results", "directly", "inside", "of", "another", "promise" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/examples/calculator_server.py#L73-L81
6,276
capnproto/pycapnp
buildutils/detect.py
detect_version
def detect_version(basedir, compiler=None, **compiler_attrs): """Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compiled and run compiler : str The distutils compiler key (e.g. 'unix', 'msvc', or 'mingw32') **compiler_attrs : dict Any extra compiler attributes, which will be set via ``setattr(cc)``. Returns ------- A dict of properties for zmq compilation, with the following two keys: vers : tuple The ZMQ version as a tuple of ints, e.g. (2,2,0) settings : dict The compiler options used to compile the test function, e.g. `include_dirs`, `library_dirs`, `libs`, etc. """ if compiler is None: compiler = get_default_compiler() cfile = pjoin(basedir, 'vers.cpp') shutil.copy(pjoin(os.path.dirname(__file__), 'vers.cpp'), cfile) # check if we need to link against Realtime Extensions library if sys.platform.startswith('linux'): cc = ccompiler.new_compiler(compiler=compiler) cc.output_dir = basedir if not cc.has_function('timer_create'): if 'libraries' not in compiler_attrs: compiler_attrs['libraries'] = [] compiler_attrs['libraries'].append('rt') cc = get_compiler(compiler=compiler, **compiler_attrs) efile = test_compilation(cfile, compiler=cc) patch_lib_paths(efile, cc.library_dirs) rc, so, se = get_output_error([efile]) if rc: msg = "Error running version detection script:\n%s\n%s" % (so,se) logging.error(msg) raise IOError(msg) handlers = {'vers': lambda val: tuple(int(v) for v in val.split('.'))} props = {} for line in (x for x in so.split('\n') if x): key, val = line.split(':') props[key] = handlers[key](val) return props
python
def detect_version(basedir, compiler=None, **compiler_attrs): """Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compiled and run compiler : str The distutils compiler key (e.g. 'unix', 'msvc', or 'mingw32') **compiler_attrs : dict Any extra compiler attributes, which will be set via ``setattr(cc)``. Returns ------- A dict of properties for zmq compilation, with the following two keys: vers : tuple The ZMQ version as a tuple of ints, e.g. (2,2,0) settings : dict The compiler options used to compile the test function, e.g. `include_dirs`, `library_dirs`, `libs`, etc. """ if compiler is None: compiler = get_default_compiler() cfile = pjoin(basedir, 'vers.cpp') shutil.copy(pjoin(os.path.dirname(__file__), 'vers.cpp'), cfile) # check if we need to link against Realtime Extensions library if sys.platform.startswith('linux'): cc = ccompiler.new_compiler(compiler=compiler) cc.output_dir = basedir if not cc.has_function('timer_create'): if 'libraries' not in compiler_attrs: compiler_attrs['libraries'] = [] compiler_attrs['libraries'].append('rt') cc = get_compiler(compiler=compiler, **compiler_attrs) efile = test_compilation(cfile, compiler=cc) patch_lib_paths(efile, cc.library_dirs) rc, so, se = get_output_error([efile]) if rc: msg = "Error running version detection script:\n%s\n%s" % (so,se) logging.error(msg) raise IOError(msg) handlers = {'vers': lambda val: tuple(int(v) for v in val.split('.'))} props = {} for line in (x for x in so.split('\n') if x): key, val = line.split(':') props[key] = handlers[key](val) return props
[ "def", "detect_version", "(", "basedir", ",", "compiler", "=", "None", ",", "*", "*", "compiler_attrs", ")", ":", "if", "compiler", "is", "None", ":", "compiler", "=", "get_default_compiler", "(", ")", "cfile", "=", "pjoin", "(", "basedir", ",", "'vers.cpp'", ")", "shutil", ".", "copy", "(", "pjoin", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'vers.cpp'", ")", ",", "cfile", ")", "# check if we need to link against Realtime Extensions library", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "cc", "=", "ccompiler", ".", "new_compiler", "(", "compiler", "=", "compiler", ")", "cc", ".", "output_dir", "=", "basedir", "if", "not", "cc", ".", "has_function", "(", "'timer_create'", ")", ":", "if", "'libraries'", "not", "in", "compiler_attrs", ":", "compiler_attrs", "[", "'libraries'", "]", "=", "[", "]", "compiler_attrs", "[", "'libraries'", "]", ".", "append", "(", "'rt'", ")", "cc", "=", "get_compiler", "(", "compiler", "=", "compiler", ",", "*", "*", "compiler_attrs", ")", "efile", "=", "test_compilation", "(", "cfile", ",", "compiler", "=", "cc", ")", "patch_lib_paths", "(", "efile", ",", "cc", ".", "library_dirs", ")", "rc", ",", "so", ",", "se", "=", "get_output_error", "(", "[", "efile", "]", ")", "if", "rc", ":", "msg", "=", "\"Error running version detection script:\\n%s\\n%s\"", "%", "(", "so", ",", "se", ")", "logging", ".", "error", "(", "msg", ")", "raise", "IOError", "(", "msg", ")", "handlers", "=", "{", "'vers'", ":", "lambda", "val", ":", "tuple", "(", "int", "(", "v", ")", "for", "v", "in", "val", ".", "split", "(", "'.'", ")", ")", "}", "props", "=", "{", "}", "for", "line", "in", "(", "x", "for", "x", "in", "so", ".", "split", "(", "'\\n'", ")", "if", "x", ")", ":", "key", ",", "val", "=", "line", ".", "split", "(", "':'", ")", "props", "[", "key", "]", "=", "handlers", "[", "key", "]", "(", "val", ")", "return", "props" ]
Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compiled and run compiler : str The distutils compiler key (e.g. 'unix', 'msvc', or 'mingw32') **compiler_attrs : dict Any extra compiler attributes, which will be set via ``setattr(cc)``. Returns ------- A dict of properties for zmq compilation, with the following two keys: vers : tuple The ZMQ version as a tuple of ints, e.g. (2,2,0) settings : dict The compiler options used to compile the test function, e.g. `include_dirs`, `library_dirs`, `libs`, etc.
[ "Compile", "link", "&", "execute", "a", "test", "program", "in", "empty", "directory", "basedir", "." ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/detect.py#L87-L144
6,277
capnproto/pycapnp
buildutils/constants.py
generate_file
def generate_file(fname, ns_func, dest_dir="."): """generate a constants file from its template""" with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f: tpl = f.read() out = tpl.format(**ns_func()) dest = pjoin(dest_dir, fname) info("generating %s from template" % dest) with open(dest, 'w') as f: f.write(out)
python
def generate_file(fname, ns_func, dest_dir="."): """generate a constants file from its template""" with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f: tpl = f.read() out = tpl.format(**ns_func()) dest = pjoin(dest_dir, fname) info("generating %s from template" % dest) with open(dest, 'w') as f: f.write(out)
[ "def", "generate_file", "(", "fname", ",", "ns_func", ",", "dest_dir", "=", "\".\"", ")", ":", "with", "open", "(", "pjoin", "(", "root", ",", "'buildutils'", ",", "'templates'", ",", "'%s'", "%", "fname", ")", ",", "'r'", ")", "as", "f", ":", "tpl", "=", "f", ".", "read", "(", ")", "out", "=", "tpl", ".", "format", "(", "*", "*", "ns_func", "(", ")", ")", "dest", "=", "pjoin", "(", "dest_dir", ",", "fname", ")", "info", "(", "\"generating %s from template\"", "%", "dest", ")", "with", "open", "(", "dest", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "out", ")" ]
generate a constants file from its template
[ "generate", "a", "constants", "file", "from", "its", "template" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/constants.py#L66-L74
6,278
capnproto/pycapnp
buildutils/constants.py
render_constants
def render_constants(): """render generated constant files from templates""" generate_file("constant_enums.pxi", cython_enums, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("constants.pxi", constants_pyx, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("zmq_constants.h", ifndefs, pjoin(root, 'zmq', 'utils'))
python
def render_constants(): """render generated constant files from templates""" generate_file("constant_enums.pxi", cython_enums, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("constants.pxi", constants_pyx, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("zmq_constants.h", ifndefs, pjoin(root, 'zmq', 'utils'))
[ "def", "render_constants", "(", ")", ":", "generate_file", "(", "\"constant_enums.pxi\"", ",", "cython_enums", ",", "pjoin", "(", "root", ",", "'zmq'", ",", "'backend'", ",", "'cython'", ")", ")", "generate_file", "(", "\"constants.pxi\"", ",", "constants_pyx", ",", "pjoin", "(", "root", ",", "'zmq'", ",", "'backend'", ",", "'cython'", ")", ")", "generate_file", "(", "\"zmq_constants.h\"", ",", "ifndefs", ",", "pjoin", "(", "root", ",", "'zmq'", ",", "'utils'", ")", ")" ]
render generated constant files from templates
[ "render", "generated", "constant", "files", "from", "templates" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/constants.py#L76-L80
6,279
byroot/pysrt
pysrt/srttime.py
SubRipTime.from_time
def from_time(cls, source): """ datetime.time -> SubRipTime corresponding to time object """ return cls(hours=source.hour, minutes=source.minute, seconds=source.second, milliseconds=source.microsecond // 1000)
python
def from_time(cls, source): """ datetime.time -> SubRipTime corresponding to time object """ return cls(hours=source.hour, minutes=source.minute, seconds=source.second, milliseconds=source.microsecond // 1000)
[ "def", "from_time", "(", "cls", ",", "source", ")", ":", "return", "cls", "(", "hours", "=", "source", ".", "hour", ",", "minutes", "=", "source", ".", "minute", ",", "seconds", "=", "source", ".", "second", ",", "milliseconds", "=", "source", ".", "microsecond", "//", "1000", ")" ]
datetime.time -> SubRipTime corresponding to time object
[ "datetime", ".", "time", "-", ">", "SubRipTime", "corresponding", "to", "time", "object" ]
e23ca39de37d54e988f4726c311aee4d4770c2ca
https://github.com/byroot/pysrt/blob/e23ca39de37d54e988f4726c311aee4d4770c2ca/pysrt/srttime.py#L165-L170
6,280
byroot/pysrt
pysrt/srttime.py
SubRipTime.to_time
def to_time(self): """ Convert SubRipTime instance into a pure datetime.time object """ return time(self.hours, self.minutes, self.seconds, self.milliseconds * 1000)
python
def to_time(self): """ Convert SubRipTime instance into a pure datetime.time object """ return time(self.hours, self.minutes, self.seconds, self.milliseconds * 1000)
[ "def", "to_time", "(", "self", ")", ":", "return", "time", "(", "self", ".", "hours", ",", "self", ".", "minutes", ",", "self", ".", "seconds", ",", "self", ".", "milliseconds", "*", "1000", ")" ]
Convert SubRipTime instance into a pure datetime.time object
[ "Convert", "SubRipTime", "instance", "into", "a", "pure", "datetime", ".", "time", "object" ]
e23ca39de37d54e988f4726c311aee4d4770c2ca
https://github.com/byroot/pysrt/blob/e23ca39de37d54e988f4726c311aee4d4770c2ca/pysrt/srttime.py#L172-L177
6,281
torchbox/wagtail-import-export
wagtailimportexport/exporting.py
export_pages
def export_pages(root_page, export_unpublished=False): """ Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures that there are no orphan pages when the subtree is created in the destination site. If export_unpublished=True the root_page and all its descendants are included. """ pages = Page.objects.descendant_of(root_page, inclusive=True).order_by('path').specific() if not export_unpublished: pages = pages.filter(live=True) page_data = [] exported_paths = set() for (i, page) in enumerate(pages): parent_path = page.path[:-(Page.steplen)] # skip over pages whose parents haven't already been exported # (which means that export_unpublished is false and the parent was unpublished) if i == 0 or (parent_path in exported_paths): page_data.append({ 'content': json.loads(page.to_json()), 'model': page.content_type.model, 'app_label': page.content_type.app_label, }) exported_paths.add(page.path) return { 'pages': page_data }
python
def export_pages(root_page, export_unpublished=False): """ Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures that there are no orphan pages when the subtree is created in the destination site. If export_unpublished=True the root_page and all its descendants are included. """ pages = Page.objects.descendant_of(root_page, inclusive=True).order_by('path').specific() if not export_unpublished: pages = pages.filter(live=True) page_data = [] exported_paths = set() for (i, page) in enumerate(pages): parent_path = page.path[:-(Page.steplen)] # skip over pages whose parents haven't already been exported # (which means that export_unpublished is false and the parent was unpublished) if i == 0 or (parent_path in exported_paths): page_data.append({ 'content': json.loads(page.to_json()), 'model': page.content_type.model, 'app_label': page.content_type.app_label, }) exported_paths.add(page.path) return { 'pages': page_data }
[ "def", "export_pages", "(", "root_page", ",", "export_unpublished", "=", "False", ")", ":", "pages", "=", "Page", ".", "objects", ".", "descendant_of", "(", "root_page", ",", "inclusive", "=", "True", ")", ".", "order_by", "(", "'path'", ")", ".", "specific", "(", ")", "if", "not", "export_unpublished", ":", "pages", "=", "pages", ".", "filter", "(", "live", "=", "True", ")", "page_data", "=", "[", "]", "exported_paths", "=", "set", "(", ")", "for", "(", "i", ",", "page", ")", "in", "enumerate", "(", "pages", ")", ":", "parent_path", "=", "page", ".", "path", "[", ":", "-", "(", "Page", ".", "steplen", ")", "]", "# skip over pages whose parents haven't already been exported", "# (which means that export_unpublished is false and the parent was unpublished)", "if", "i", "==", "0", "or", "(", "parent_path", "in", "exported_paths", ")", ":", "page_data", ".", "append", "(", "{", "'content'", ":", "json", ".", "loads", "(", "page", ".", "to_json", "(", ")", ")", ",", "'model'", ":", "page", ".", "content_type", ".", "model", ",", "'app_label'", ":", "page", ".", "content_type", ".", "app_label", ",", "}", ")", "exported_paths", ".", "add", "(", "page", ".", "path", ")", "return", "{", "'pages'", ":", "page_data", "}" ]
Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures that there are no orphan pages when the subtree is created in the destination site. If export_unpublished=True the root_page and all its descendants are included.
[ "Create", "a", "JSON", "defintion", "of", "part", "of", "a", "site", "s", "page", "tree", "starting", "from", "root_page", "and", "descending", "into", "its", "descendants" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/exporting.py#L6-L40
6,282
torchbox/wagtail-import-export
wagtailimportexport/views.py
import_from_api
def import_from_api(request): """ Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromAPIForm(request.POST) if form.is_valid(): # remove trailing slash from base url base_url = re.sub(r'\/$', '', form.cleaned_data['source_site_base_url']) import_url = ( base_url + reverse('wagtailimportexport:export', args=[form.cleaned_data['source_page_id']]) ) r = requests.get(import_url) import_data = r.json() parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromAPIForm() return render(request, 'wagtailimportexport/import_from_api.html', { 'form': form, })
python
def import_from_api(request): """ Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromAPIForm(request.POST) if form.is_valid(): # remove trailing slash from base url base_url = re.sub(r'\/$', '', form.cleaned_data['source_site_base_url']) import_url = ( base_url + reverse('wagtailimportexport:export', args=[form.cleaned_data['source_page_id']]) ) r = requests.get(import_url) import_data = r.json() parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromAPIForm() return render(request, 'wagtailimportexport/import_from_api.html', { 'form': form, })
[ "def", "import_from_api", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "ImportFromAPIForm", "(", "request", ".", "POST", ")", "if", "form", ".", "is_valid", "(", ")", ":", "# remove trailing slash from base url", "base_url", "=", "re", ".", "sub", "(", "r'\\/$'", ",", "''", ",", "form", ".", "cleaned_data", "[", "'source_site_base_url'", "]", ")", "import_url", "=", "(", "base_url", "+", "reverse", "(", "'wagtailimportexport:export'", ",", "args", "=", "[", "form", ".", "cleaned_data", "[", "'source_page_id'", "]", "]", ")", ")", "r", "=", "requests", ".", "get", "(", "import_url", ")", "import_data", "=", "r", ".", "json", "(", ")", "parent_page", "=", "form", ".", "cleaned_data", "[", "'parent_page'", "]", "try", ":", "page_count", "=", "import_pages", "(", "import_data", ",", "parent_page", ")", "except", "LookupError", "as", "e", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "\"Import failed: %(reason)s\"", ")", "%", "{", "'reason'", ":", "e", "}", ")", "else", ":", "messages", ".", "success", "(", "request", ",", "ungettext", "(", "\"%(count)s page imported.\"", ",", "\"%(count)s pages imported.\"", ",", "page_count", ")", "%", "{", "'count'", ":", "page_count", "}", ")", "return", "redirect", "(", "'wagtailadmin_explore'", ",", "parent_page", ".", "pk", ")", "else", ":", "form", "=", "ImportFromAPIForm", "(", ")", "return", "render", "(", "request", ",", "'wagtailimportexport/import_from_api.html'", ",", "{", "'form'", ":", "form", ",", "}", ")" ]
Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to.
[ "Import", "a", "part", "of", "a", "source", "site", "s", "page", "tree", "via", "a", "direct", "API", "request", "from", "this", "Wagtail", "Admin", "to", "the", "source", "site" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L21-L60
6,283
torchbox/wagtail-import-export
wagtailimportexport/views.py
import_from_file
def import_from_file(request): """ Import a part of a source site's page tree via an import of a JSON file exported to a user's filesystem from the source site's Wagtail Admin The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromFileForm(request.POST, request.FILES) if form.is_valid(): import_data = json.loads(form.cleaned_data['file'].read().decode('utf-8-sig')) parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromFileForm() return render(request, 'wagtailimportexport/import_from_file.html', { 'form': form, })
python
def import_from_file(request): """ Import a part of a source site's page tree via an import of a JSON file exported to a user's filesystem from the source site's Wagtail Admin The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromFileForm(request.POST, request.FILES) if form.is_valid(): import_data = json.loads(form.cleaned_data['file'].read().decode('utf-8-sig')) parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromFileForm() return render(request, 'wagtailimportexport/import_from_file.html', { 'form': form, })
[ "def", "import_from_file", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "ImportFromFileForm", "(", "request", ".", "POST", ",", "request", ".", "FILES", ")", "if", "form", ".", "is_valid", "(", ")", ":", "import_data", "=", "json", ".", "loads", "(", "form", ".", "cleaned_data", "[", "'file'", "]", ".", "read", "(", ")", ".", "decode", "(", "'utf-8-sig'", ")", ")", "parent_page", "=", "form", ".", "cleaned_data", "[", "'parent_page'", "]", "try", ":", "page_count", "=", "import_pages", "(", "import_data", ",", "parent_page", ")", "except", "LookupError", "as", "e", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "\"Import failed: %(reason)s\"", ")", "%", "{", "'reason'", ":", "e", "}", ")", "else", ":", "messages", ".", "success", "(", "request", ",", "ungettext", "(", "\"%(count)s page imported.\"", ",", "\"%(count)s pages imported.\"", ",", "page_count", ")", "%", "{", "'count'", ":", "page_count", "}", ")", "return", "redirect", "(", "'wagtailadmin_explore'", ",", "parent_page", ".", "pk", ")", "else", ":", "form", "=", "ImportFromFileForm", "(", ")", "return", "render", "(", "request", ",", "'wagtailimportexport/import_from_file.html'", ",", "{", "'form'", ":", "form", ",", "}", ")" ]
Import a part of a source site's page tree via an import of a JSON file exported to a user's filesystem from the source site's Wagtail Admin The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to.
[ "Import", "a", "part", "of", "a", "source", "site", "s", "page", "tree", "via", "an", "import", "of", "a", "JSON", "file", "exported", "to", "a", "user", "s", "filesystem", "from", "the", "source", "site", "s", "Wagtail", "Admin" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L63-L96
6,284
torchbox/wagtail-import-export
wagtailimportexport/views.py
export_to_file
def export_to_file(request): """ Export a part of this source site's page tree to a JSON file on this user's filesystem for subsequent import in a destination site's Wagtail Admin """ if request.method == 'POST': form = ExportForm(request.POST) if form.is_valid(): payload = export_pages(form.cleaned_data['root_page'], export_unpublished=True) response = JsonResponse(payload) response['Content-Disposition'] = 'attachment; filename="export.json"' return response else: form = ExportForm() return render(request, 'wagtailimportexport/export_to_file.html', { 'form': form, })
python
def export_to_file(request): """ Export a part of this source site's page tree to a JSON file on this user's filesystem for subsequent import in a destination site's Wagtail Admin """ if request.method == 'POST': form = ExportForm(request.POST) if form.is_valid(): payload = export_pages(form.cleaned_data['root_page'], export_unpublished=True) response = JsonResponse(payload) response['Content-Disposition'] = 'attachment; filename="export.json"' return response else: form = ExportForm() return render(request, 'wagtailimportexport/export_to_file.html', { 'form': form, })
[ "def", "export_to_file", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "ExportForm", "(", "request", ".", "POST", ")", "if", "form", ".", "is_valid", "(", ")", ":", "payload", "=", "export_pages", "(", "form", ".", "cleaned_data", "[", "'root_page'", "]", ",", "export_unpublished", "=", "True", ")", "response", "=", "JsonResponse", "(", "payload", ")", "response", "[", "'Content-Disposition'", "]", "=", "'attachment; filename=\"export.json\"'", "return", "response", "else", ":", "form", "=", "ExportForm", "(", ")", "return", "render", "(", "request", ",", "'wagtailimportexport/export_to_file.html'", ",", "{", "'form'", ":", "form", ",", "}", ")" ]
Export a part of this source site's page tree to a JSON file on this user's filesystem for subsequent import in a destination site's Wagtail Admin
[ "Export", "a", "part", "of", "this", "source", "site", "s", "page", "tree", "to", "a", "JSON", "file", "on", "this", "user", "s", "filesystem", "for", "subsequent", "import", "in", "a", "destination", "site", "s", "Wagtail", "Admin" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L99-L117
6,285
torchbox/wagtail-import-export
wagtailimportexport/views.py
export
def export(request, page_id, export_unpublished=False): """ API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view. """ try: if export_unpublished: root_page = Page.objects.get(id=page_id) else: root_page = Page.objects.get(id=page_id, live=True) except Page.DoesNotExist: return JsonResponse({'error': _('page not found')}) payload = export_pages(root_page, export_unpublished=export_unpublished) return JsonResponse(payload)
python
def export(request, page_id, export_unpublished=False): """ API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view. """ try: if export_unpublished: root_page = Page.objects.get(id=page_id) else: root_page = Page.objects.get(id=page_id, live=True) except Page.DoesNotExist: return JsonResponse({'error': _('page not found')}) payload = export_pages(root_page, export_unpublished=export_unpublished) return JsonResponse(payload)
[ "def", "export", "(", "request", ",", "page_id", ",", "export_unpublished", "=", "False", ")", ":", "try", ":", "if", "export_unpublished", ":", "root_page", "=", "Page", ".", "objects", ".", "get", "(", "id", "=", "page_id", ")", "else", ":", "root_page", "=", "Page", ".", "objects", ".", "get", "(", "id", "=", "page_id", ",", "live", "=", "True", ")", "except", "Page", ".", "DoesNotExist", ":", "return", "JsonResponse", "(", "{", "'error'", ":", "_", "(", "'page not found'", ")", "}", ")", "payload", "=", "export_pages", "(", "root_page", ",", "export_unpublished", "=", "export_unpublished", ")", "return", "JsonResponse", "(", "payload", ")" ]
API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view.
[ "API", "endpoint", "of", "this", "source", "site", "to", "export", "a", "part", "of", "the", "page", "tree", "rooted", "at", "page_id" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L120-L137
6,286
torchbox/wagtail-import-export
wagtailimportexport/importing.py
import_pages
def import_pages(import_data, parent_page): """ Take a JSON export of part of a source site's page tree and create those pages under the parent page """ pages_by_original_path = {} pages_by_original_id = {} # First create the base Page records; these contain no foreign keys, so this allows us to # build a complete mapping from old IDs to new IDs before we go on to importing the # specific page models, which may require us to rewrite page IDs within foreign keys / rich # text / streamfields. page_content_type = ContentType.objects.get_for_model(Page) for (i, page_record) in enumerate(import_data['pages']): # build a base Page instance from the exported content (so that we pick up its title and other # core attributes) page = Page.from_serializable_data(page_record['content']) original_path = page.path original_id = page.id # clear id and treebeard-related fields so that they get reassigned when we save via add_child page.id = None page.path = None page.depth = None page.numchild = 0 page.url_path = None page.content_type = page_content_type if i == 0: parent_page.add_child(instance=page) else: # Child pages are created in the same sibling path order as the # source tree because the export is ordered by path parent_path = original_path[:-(Page.steplen)] pages_by_original_path[parent_path].add_child(instance=page) pages_by_original_path[original_path] = page pages_by_original_id[original_id] = page for (i, page_record) in enumerate(import_data['pages']): # Get the page model of the source page by app_label and model name # The content type ID of the source page is not in general the same # between the source and destination sites but the page model needs # to exist on both. # Raises LookupError exception if there is no matching model model = apps.get_model(page_record['app_label'], page_record['model']) specific_page = model.from_serializable_data(page_record['content'], check_fks=False, strict_fks=False) base_page = pages_by_original_id[specific_page.id] specific_page.page_ptr = base_page specific_page.__dict__.update(base_page.__dict__) specific_page.content_type = ContentType.objects.get_for_model(model) update_page_references(specific_page, pages_by_original_id) specific_page.save() return len(import_data['pages'])
python
def import_pages(import_data, parent_page): """ Take a JSON export of part of a source site's page tree and create those pages under the parent page """ pages_by_original_path = {} pages_by_original_id = {} # First create the base Page records; these contain no foreign keys, so this allows us to # build a complete mapping from old IDs to new IDs before we go on to importing the # specific page models, which may require us to rewrite page IDs within foreign keys / rich # text / streamfields. page_content_type = ContentType.objects.get_for_model(Page) for (i, page_record) in enumerate(import_data['pages']): # build a base Page instance from the exported content (so that we pick up its title and other # core attributes) page = Page.from_serializable_data(page_record['content']) original_path = page.path original_id = page.id # clear id and treebeard-related fields so that they get reassigned when we save via add_child page.id = None page.path = None page.depth = None page.numchild = 0 page.url_path = None page.content_type = page_content_type if i == 0: parent_page.add_child(instance=page) else: # Child pages are created in the same sibling path order as the # source tree because the export is ordered by path parent_path = original_path[:-(Page.steplen)] pages_by_original_path[parent_path].add_child(instance=page) pages_by_original_path[original_path] = page pages_by_original_id[original_id] = page for (i, page_record) in enumerate(import_data['pages']): # Get the page model of the source page by app_label and model name # The content type ID of the source page is not in general the same # between the source and destination sites but the page model needs # to exist on both. # Raises LookupError exception if there is no matching model model = apps.get_model(page_record['app_label'], page_record['model']) specific_page = model.from_serializable_data(page_record['content'], check_fks=False, strict_fks=False) base_page = pages_by_original_id[specific_page.id] specific_page.page_ptr = base_page specific_page.__dict__.update(base_page.__dict__) specific_page.content_type = ContentType.objects.get_for_model(model) update_page_references(specific_page, pages_by_original_id) specific_page.save() return len(import_data['pages'])
[ "def", "import_pages", "(", "import_data", ",", "parent_page", ")", ":", "pages_by_original_path", "=", "{", "}", "pages_by_original_id", "=", "{", "}", "# First create the base Page records; these contain no foreign keys, so this allows us to", "# build a complete mapping from old IDs to new IDs before we go on to importing the", "# specific page models, which may require us to rewrite page IDs within foreign keys / rich", "# text / streamfields.", "page_content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "Page", ")", "for", "(", "i", ",", "page_record", ")", "in", "enumerate", "(", "import_data", "[", "'pages'", "]", ")", ":", "# build a base Page instance from the exported content (so that we pick up its title and other", "# core attributes)", "page", "=", "Page", ".", "from_serializable_data", "(", "page_record", "[", "'content'", "]", ")", "original_path", "=", "page", ".", "path", "original_id", "=", "page", ".", "id", "# clear id and treebeard-related fields so that they get reassigned when we save via add_child", "page", ".", "id", "=", "None", "page", ".", "path", "=", "None", "page", ".", "depth", "=", "None", "page", ".", "numchild", "=", "0", "page", ".", "url_path", "=", "None", "page", ".", "content_type", "=", "page_content_type", "if", "i", "==", "0", ":", "parent_page", ".", "add_child", "(", "instance", "=", "page", ")", "else", ":", "# Child pages are created in the same sibling path order as the", "# source tree because the export is ordered by path", "parent_path", "=", "original_path", "[", ":", "-", "(", "Page", ".", "steplen", ")", "]", "pages_by_original_path", "[", "parent_path", "]", ".", "add_child", "(", "instance", "=", "page", ")", "pages_by_original_path", "[", "original_path", "]", "=", "page", "pages_by_original_id", "[", "original_id", "]", "=", "page", "for", "(", "i", ",", "page_record", ")", "in", "enumerate", "(", "import_data", "[", "'pages'", "]", ")", ":", "# Get the page model of the source page by app_label and model name", "# The content type ID of the source page is not in general the same", "# between the source and destination sites but the page model needs", "# to exist on both.", "# Raises LookupError exception if there is no matching model", "model", "=", "apps", ".", "get_model", "(", "page_record", "[", "'app_label'", "]", ",", "page_record", "[", "'model'", "]", ")", "specific_page", "=", "model", ".", "from_serializable_data", "(", "page_record", "[", "'content'", "]", ",", "check_fks", "=", "False", ",", "strict_fks", "=", "False", ")", "base_page", "=", "pages_by_original_id", "[", "specific_page", ".", "id", "]", "specific_page", ".", "page_ptr", "=", "base_page", "specific_page", ".", "__dict__", ".", "update", "(", "base_page", ".", "__dict__", ")", "specific_page", ".", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "model", ")", "update_page_references", "(", "specific_page", ",", "pages_by_original_id", ")", "specific_page", ".", "save", "(", ")", "return", "len", "(", "import_data", "[", "'pages'", "]", ")" ]
Take a JSON export of part of a source site's page tree and create those pages under the parent page
[ "Take", "a", "JSON", "export", "of", "part", "of", "a", "source", "site", "s", "page", "tree", "and", "create", "those", "pages", "under", "the", "parent", "page" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/importing.py#L10-L64
6,287
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.remove_all_filters
def remove_all_filters(self): """ Removes all filters """ # attitude: None = no attitude, True = positive, False = negative self.attitude_filter = self.source_filter = None self.question_filter = self.link_filter = False
python
def remove_all_filters(self): """ Removes all filters """ # attitude: None = no attitude, True = positive, False = negative self.attitude_filter = self.source_filter = None self.question_filter = self.link_filter = False
[ "def", "remove_all_filters", "(", "self", ")", ":", "# attitude: None = no attitude, True = positive, False = negative", "self", ".", "attitude_filter", "=", "self", ".", "source_filter", "=", "None", "self", ".", "question_filter", "=", "self", ".", "link_filter", "=", "False" ]
Removes all filters
[ "Removes", "all", "filters" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L71-L76
6,288
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_source_filter
def set_source_filter(self, source): """ Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException """ if isinstance(source, str if py3k else basestring) and len(source) >= 2: self.source_filter = source else: raise TwitterSearchException(1009)
python
def set_source_filter(self, source): """ Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException """ if isinstance(source, str if py3k else basestring) and len(source) >= 2: self.source_filter = source else: raise TwitterSearchException(1009)
[ "def", "set_source_filter", "(", "self", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "str", "if", "py3k", "else", "basestring", ")", "and", "len", "(", "source", ")", ">=", "2", ":", "self", ".", "source_filter", "=", "source", "else", ":", "raise", "TwitterSearchException", "(", "1009", ")" ]
Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException
[ "Only", "search", "for", "tweets", "entered", "via", "given", "source" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L78-L89
6,289
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.add_keyword
def add_keyword(self, word, or_operator=False): """ Adds a given string or list to the current keyword list :param word: String or list of at least 2 character long keyword(s) :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Is ignored is word is not a list. Thus it is \ possible to search for ``foo OR bar``. Default value is False \ which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if isinstance(word, str if py3k else basestring) and len(word) >= 2: self.searchterms.append(word if " " not in word else '"%s"' % word) elif isinstance(word, (tuple,list)): word = [ (i if " " not in i else '"%s"' % i) for i in word ] self.searchterms += [" OR ".join(word)] if or_operator else word else: raise TwitterSearchException(1000)
python
def add_keyword(self, word, or_operator=False): """ Adds a given string or list to the current keyword list :param word: String or list of at least 2 character long keyword(s) :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Is ignored is word is not a list. Thus it is \ possible to search for ``foo OR bar``. Default value is False \ which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if isinstance(word, str if py3k else basestring) and len(word) >= 2: self.searchterms.append(word if " " not in word else '"%s"' % word) elif isinstance(word, (tuple,list)): word = [ (i if " " not in i else '"%s"' % i) for i in word ] self.searchterms += [" OR ".join(word)] if or_operator else word else: raise TwitterSearchException(1000)
[ "def", "add_keyword", "(", "self", ",", "word", ",", "or_operator", "=", "False", ")", ":", "if", "isinstance", "(", "word", ",", "str", "if", "py3k", "else", "basestring", ")", "and", "len", "(", "word", ")", ">=", "2", ":", "self", ".", "searchterms", ".", "append", "(", "word", "if", "\" \"", "not", "in", "word", "else", "'\"%s\"'", "%", "word", ")", "elif", "isinstance", "(", "word", ",", "(", "tuple", ",", "list", ")", ")", ":", "word", "=", "[", "(", "i", "if", "\" \"", "not", "in", "i", "else", "'\"%s\"'", "%", "i", ")", "for", "i", "in", "word", "]", "self", ".", "searchterms", "+=", "[", "\" OR \"", ".", "join", "(", "word", ")", "]", "if", "or_operator", "else", "word", "else", ":", "raise", "TwitterSearchException", "(", "1000", ")" ]
Adds a given string or list to the current keyword list :param word: String or list of at least 2 character long keyword(s) :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Is ignored is word is not a list. Thus it is \ possible to search for ``foo OR bar``. Default value is False \ which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException
[ "Adds", "a", "given", "string", "or", "list", "to", "the", "current", "keyword", "list" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L132-L149
6,290
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_keywords
def set_keywords(self, words, or_operator=False): """ Sets a given list as the new keyword list :param words: A list of at least 2 character long new keywords :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Enables searches for ``foo OR bar``. Default value \ is False which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if not isinstance(words, (tuple,list)): raise TwitterSearchException(1001) words = [ (i if " " not in i else '"%s"' % i) for i in words ] self.searchterms = [" OR ".join(words)] if or_operator else words
python
def set_keywords(self, words, or_operator=False): """ Sets a given list as the new keyword list :param words: A list of at least 2 character long new keywords :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Enables searches for ``foo OR bar``. Default value \ is False which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if not isinstance(words, (tuple,list)): raise TwitterSearchException(1001) words = [ (i if " " not in i else '"%s"' % i) for i in words ] self.searchterms = [" OR ".join(words)] if or_operator else words
[ "def", "set_keywords", "(", "self", ",", "words", ",", "or_operator", "=", "False", ")", ":", "if", "not", "isinstance", "(", "words", ",", "(", "tuple", ",", "list", ")", ")", ":", "raise", "TwitterSearchException", "(", "1001", ")", "words", "=", "[", "(", "i", "if", "\" \"", "not", "in", "i", "else", "'\"%s\"'", "%", "i", ")", "for", "i", "in", "words", "]", "self", ".", "searchterms", "=", "[", "\" OR \"", ".", "join", "(", "words", ")", "]", "if", "or_operator", "else", "words" ]
Sets a given list as the new keyword list :param words: A list of at least 2 character long new keywords :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Enables searches for ``foo OR bar``. Default value \ is False which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException
[ "Sets", "a", "given", "list", "as", "the", "new", "keyword", "list" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L151-L164
6,291
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_language
def set_language(self, lang): """ Sets 'lang' parameter used to only fetch tweets within \ a certain language :param lang: A 2-letter language code string (ISO 6391 compatible) :raises: TwitterSearchException """ if lang in self.iso_6391: self.arguments.update({'lang': '%s' % lang}) else: raise TwitterSearchException(1002)
python
def set_language(self, lang): """ Sets 'lang' parameter used to only fetch tweets within \ a certain language :param lang: A 2-letter language code string (ISO 6391 compatible) :raises: TwitterSearchException """ if lang in self.iso_6391: self.arguments.update({'lang': '%s' % lang}) else: raise TwitterSearchException(1002)
[ "def", "set_language", "(", "self", ",", "lang", ")", ":", "if", "lang", "in", "self", ".", "iso_6391", ":", "self", ".", "arguments", ".", "update", "(", "{", "'lang'", ":", "'%s'", "%", "lang", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1002", ")" ]
Sets 'lang' parameter used to only fetch tweets within \ a certain language :param lang: A 2-letter language code string (ISO 6391 compatible) :raises: TwitterSearchException
[ "Sets", "lang", "parameter", "used", "to", "only", "fetch", "tweets", "within", "\\", "a", "certain", "language" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L254-L265
6,292
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_callback
def set_callback(self, func): """ Sets 'callback' parameter. If supplied, the response \ will use the JSONP format with a callback of the given name :param func: A string containing the name of the callback function :raises: TwitterSearchException """ if isinstance(func, str if py3k else basestring) and func: self.arguments.update({'callback': '%s' % func}) else: raise TwitterSearchException(1006)
python
def set_callback(self, func): """ Sets 'callback' parameter. If supplied, the response \ will use the JSONP format with a callback of the given name :param func: A string containing the name of the callback function :raises: TwitterSearchException """ if isinstance(func, str if py3k else basestring) and func: self.arguments.update({'callback': '%s' % func}) else: raise TwitterSearchException(1006)
[ "def", "set_callback", "(", "self", ",", "func", ")", ":", "if", "isinstance", "(", "func", ",", "str", "if", "py3k", "else", "basestring", ")", "and", "func", ":", "self", ".", "arguments", ".", "update", "(", "{", "'callback'", ":", "'%s'", "%", "func", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1006", ")" ]
Sets 'callback' parameter. If supplied, the response \ will use the JSONP format with a callback of the given name :param func: A string containing the name of the callback function :raises: TwitterSearchException
[ "Sets", "callback", "parameter", ".", "If", "supplied", "the", "response", "\\", "will", "use", "the", "JSONP", "format", "with", "a", "callback", "of", "the", "given", "name" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L333-L344
6,293
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_until
def set_until(self, date): """ Sets 'until' parameter used to return \ only tweets generated before the given date :param date: A datetime instance :raises: TwitterSearchException """ if isinstance(date, datetime.date) and date <= datetime.date.today(): self.arguments.update({'until': '%s' % date.strftime('%Y-%m-%d')}) else: raise TwitterSearchException(1007)
python
def set_until(self, date): """ Sets 'until' parameter used to return \ only tweets generated before the given date :param date: A datetime instance :raises: TwitterSearchException """ if isinstance(date, datetime.date) and date <= datetime.date.today(): self.arguments.update({'until': '%s' % date.strftime('%Y-%m-%d')}) else: raise TwitterSearchException(1007)
[ "def", "set_until", "(", "self", ",", "date", ")", ":", "if", "isinstance", "(", "date", ",", "datetime", ".", "date", ")", "and", "date", "<=", "datetime", ".", "date", ".", "today", "(", ")", ":", "self", ".", "arguments", ".", "update", "(", "{", "'until'", ":", "'%s'", "%", "date", ".", "strftime", "(", "'%Y-%m-%d'", ")", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1007", ")" ]
Sets 'until' parameter used to return \ only tweets generated before the given date :param date: A datetime instance :raises: TwitterSearchException
[ "Sets", "until", "parameter", "used", "to", "return", "\\", "only", "tweets", "generated", "before", "the", "given", "date" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L346-L357
6,294
ckoepp/TwitterSearch
TwitterSearch/TwitterSearch.py
TwitterSearch.set_proxy
def set_proxy(self, proxy): """ Sets a HTTPS proxy to query the Twitter API :param proxy: A string of containing a HTTPS proxy \ e.g. ``set_proxy("my.proxy.com:8080")``. :raises: TwitterSearchException """ if isinstance(proxy, str if py3k else basestring): self.__proxy = proxy else: raise TwitterSearchException(1009)
python
def set_proxy(self, proxy): """ Sets a HTTPS proxy to query the Twitter API :param proxy: A string of containing a HTTPS proxy \ e.g. ``set_proxy("my.proxy.com:8080")``. :raises: TwitterSearchException """ if isinstance(proxy, str if py3k else basestring): self.__proxy = proxy else: raise TwitterSearchException(1009)
[ "def", "set_proxy", "(", "self", ",", "proxy", ")", ":", "if", "isinstance", "(", "proxy", ",", "str", "if", "py3k", "else", "basestring", ")", ":", "self", ".", "__proxy", "=", "proxy", "else", ":", "raise", "TwitterSearchException", "(", "1009", ")" ]
Sets a HTTPS proxy to query the Twitter API :param proxy: A string of containing a HTTPS proxy \ e.g. ``set_proxy("my.proxy.com:8080")``. :raises: TwitterSearchException
[ "Sets", "a", "HTTPS", "proxy", "to", "query", "the", "Twitter", "API" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearch.py#L129-L140
6,295
ckoepp/TwitterSearch
TwitterSearch/TwitterSearch.py
TwitterSearch.get_minimal_id
def get_minimal_id(self): """ Returns the minimal tweet ID of the current response :returns: minimal tweet identification number :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return min( self.__response['content']['statuses'] if self.__order_is_search else self.__response['content'], key=lambda i: i['id'] )['id'] - 1
python
def get_minimal_id(self): """ Returns the minimal tweet ID of the current response :returns: minimal tweet identification number :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return min( self.__response['content']['statuses'] if self.__order_is_search else self.__response['content'], key=lambda i: i['id'] )['id'] - 1
[ "def", "get_minimal_id", "(", "self", ")", ":", "if", "not", "self", ".", "__response", ":", "raise", "TwitterSearchException", "(", "1013", ")", "return", "min", "(", "self", ".", "__response", "[", "'content'", "]", "[", "'statuses'", "]", "if", "self", ".", "__order_is_search", "else", "self", ".", "__response", "[", "'content'", "]", ",", "key", "=", "lambda", "i", ":", "i", "[", "'id'", "]", ")", "[", "'id'", "]", "-", "1" ]
Returns the minimal tweet ID of the current response :returns: minimal tweet identification number :raises: TwitterSearchException
[ "Returns", "the", "minimal", "tweet", "ID", "of", "the", "current", "response" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearch.py#L207-L221
6,296
ckoepp/TwitterSearch
TwitterSearch/TwitterSearch.py
TwitterSearch.get_amount_of_tweets
def get_amount_of_tweets(self): """ Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return (len(self.__response['content']['statuses']) if self.__order_is_search else len(self.__response['content']))
python
def get_amount_of_tweets(self): """ Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return (len(self.__response['content']['statuses']) if self.__order_is_search else len(self.__response['content']))
[ "def", "get_amount_of_tweets", "(", "self", ")", ":", "if", "not", "self", ".", "__response", ":", "raise", "TwitterSearchException", "(", "1013", ")", "return", "(", "len", "(", "self", ".", "__response", "[", "'content'", "]", "[", "'statuses'", "]", ")", "if", "self", ".", "__order_is_search", "else", "len", "(", "self", ".", "__response", "[", "'content'", "]", ")", ")" ]
Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException
[ "Returns", "current", "amount", "of", "tweets", "available", "within", "this", "instance" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearch.py#L367-L379
6,297
ckoepp/TwitterSearch
TwitterSearch/TwitterOrder.py
TwitterOrder.set_count
def set_count(self, cnt): """ Sets 'count' parameter used to define the number of \ tweets to return per page. Maximum and default value is 100 :param cnt: Integer containing the number of tweets per \ page within a range of 1 to 100 :raises: TwitterSearchException """ if isinstance(cnt, int) and cnt > 0 and cnt <= 100: self.arguments.update({'count': '%s' % cnt}) else: raise TwitterSearchException(1004)
python
def set_count(self, cnt): """ Sets 'count' parameter used to define the number of \ tweets to return per page. Maximum and default value is 100 :param cnt: Integer containing the number of tweets per \ page within a range of 1 to 100 :raises: TwitterSearchException """ if isinstance(cnt, int) and cnt > 0 and cnt <= 100: self.arguments.update({'count': '%s' % cnt}) else: raise TwitterSearchException(1004)
[ "def", "set_count", "(", "self", ",", "cnt", ")", ":", "if", "isinstance", "(", "cnt", ",", "int", ")", "and", "cnt", ">", "0", "and", "cnt", "<=", "100", ":", "self", ".", "arguments", ".", "update", "(", "{", "'count'", ":", "'%s'", "%", "cnt", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1004", ")" ]
Sets 'count' parameter used to define the number of \ tweets to return per page. Maximum and default value is 100 :param cnt: Integer containing the number of tweets per \ page within a range of 1 to 100 :raises: TwitterSearchException
[ "Sets", "count", "parameter", "used", "to", "define", "the", "number", "of", "\\", "tweets", "to", "return", "per", "page", ".", "Maximum", "and", "default", "value", "is", "100" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterOrder.py#L77-L89
6,298
ckoepp/TwitterSearch
TwitterSearch/TwitterOrder.py
TwitterOrder.set_include_entities
def set_include_entities(self, include): """ Sets 'include entities' parameter to either \ include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException """ if not isinstance(include, bool): raise TwitterSearchException(1008) self.arguments.update( {'include_entities': 'true' if include else 'false'} )
python
def set_include_entities(self, include): """ Sets 'include entities' parameter to either \ include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException """ if not isinstance(include, bool): raise TwitterSearchException(1008) self.arguments.update( {'include_entities': 'true' if include else 'false'} )
[ "def", "set_include_entities", "(", "self", ",", "include", ")", ":", "if", "not", "isinstance", "(", "include", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'include_entities'", ":", "'true'", "if", "include", "else", "'false'", "}", ")" ]
Sets 'include entities' parameter to either \ include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException
[ "Sets", "include", "entities", "parameter", "to", "either", "\\", "include", "or", "exclude", "the", "entities", "node", "within", "the", "results" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterOrder.py#L91-L103
6,299
ckoepp/TwitterSearch
TwitterSearch/TwitterUserOrder.py
TwitterUserOrder.set_trim_user
def set_trim_user(self, trim): """ Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(trim, bool): raise TwitterSearchException(1008) self.arguments.update({'trim_user': 'true' if trim else 'false'})
python
def set_trim_user(self, trim): """ Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(trim, bool): raise TwitterSearchException(1008) self.arguments.update({'trim_user': 'true' if trim else 'false'})
[ "def", "set_trim_user", "(", "self", ",", "trim", ")", ":", "if", "not", "isinstance", "(", "trim", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'trim_user'", ":", "'true'", "if", "trim", "else", "'false'", "}", ")" ]
Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException
[ "Sets", "trim_user", "parameter", ".", "When", "set", "to", "True", "\\", "each", "tweet", "returned", "in", "a", "timeline", "will", "include", "a", "\\", "user", "object", "including", "only", "the", "status", "authors", "numerical", "ID" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L55-L66