body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
33ca62360607871108cc7e39a66a2c2ad86197096c52410e3043643d1945e446
def test_rsync_to_builder(self): 'Ensure files are correctly synced to the remote.' with tempfile.TemporaryDirectory() as tmpdirname: source = (pathlib.Path(tmpdirname) / 'source') source.mkdir() subprocess.check_call(['git', 'init'], cwd=source) with open((source / '.gitignore'), 'w') as f: f.write('.*\n!.gitignore') with open((source / 'file'), 'w') as f: f.write('') (source / 'dir').mkdir() with open(((source / 'dir') / '.gitignore'), 'w') as f: f.write('.*\n!.gitignore') target = (pathlib.Path(tmpdirname) / 'target') target.mkdir() with open((target / 'does-not-exist'), 'w') as f: f.write('') remote.rsync_to_builder(str(source), str(target)) self.assertIsDir((source / 'dir')) self.assertNotIsDir((target / '.git')) self.assertIsFile((target / '.gitignore')) self.assertIsFile((target / 'file')) self.assertIsFile(((target / 'dir') / '.gitignore')) self.assertNotIsFile((target / 'does-not-exist'))
Ensure files are correctly synced to the remote.
outsource/test.py
test_rsync_to_builder
zhiiker/ic
941
python
def test_rsync_to_builder(self): with tempfile.TemporaryDirectory() as tmpdirname: source = (pathlib.Path(tmpdirname) / 'source') source.mkdir() subprocess.check_call(['git', 'init'], cwd=source) with open((source / '.gitignore'), 'w') as f: f.write('.*\n!.gitignore') with open((source / 'file'), 'w') as f: f.write() (source / 'dir').mkdir() with open(((source / 'dir') / '.gitignore'), 'w') as f: f.write('.*\n!.gitignore') target = (pathlib.Path(tmpdirname) / 'target') target.mkdir() with open((target / 'does-not-exist'), 'w') as f: f.write() remote.rsync_to_builder(str(source), str(target)) self.assertIsDir((source / 'dir')) self.assertNotIsDir((target / '.git')) self.assertIsFile((target / '.gitignore')) self.assertIsFile((target / 'file')) self.assertIsFile(((target / 'dir') / '.gitignore')) self.assertNotIsFile((target / 'does-not-exist'))
def test_rsync_to_builder(self): with tempfile.TemporaryDirectory() as tmpdirname: source = (pathlib.Path(tmpdirname) / 'source') source.mkdir() subprocess.check_call(['git', 'init'], cwd=source) with open((source / '.gitignore'), 'w') as f: f.write('.*\n!.gitignore') with open((source / 'file'), 'w') as f: f.write() (source / 'dir').mkdir() with open(((source / 'dir') / '.gitignore'), 'w') as f: f.write('.*\n!.gitignore') target = (pathlib.Path(tmpdirname) / 'target') target.mkdir() with open((target / 'does-not-exist'), 'w') as f: f.write() remote.rsync_to_builder(str(source), str(target)) self.assertIsDir((source / 'dir')) self.assertNotIsDir((target / '.git')) self.assertIsFile((target / '.gitignore')) self.assertIsFile((target / 'file')) self.assertIsFile(((target / 'dir') / '.gitignore')) self.assertNotIsFile((target / 'does-not-exist'))<|docstring|>Ensure files are correctly synced to the remote.<|endoftext|>
b88ad8b7536e0e5b999550f26f1735052e5029abdca9318a8cb85d32a9a8a44e
@click.group(cls=AliasedGroup, short_help='Create or update resources.', invoke_without_command=True) @click.option('-f', '--file', 'file_path', type=click.Path(exists=True), help='Select file or folder that contains the configuration to apply.') @click.option('-t', '--template', 'template_path', type=click.Path(exists=True), help='Select file or folder that contains the template configuration to apply.') @click.option('-e', '--env', 'envs', multiple=True, help='Load environment variable and apply to all object usage Jinja2 templates.') @click.option('--env-file', 'env_file', multiple=True, help='Load environment variable from file and apply to all object usage Jinja2 templates.') @click.option('--dry-run', is_flag=True, default=False, help='If true, only print the object that would be sent, without sending it') @click.option('--deploy', is_flag=True, default=False, help='During update task-definition also update service.') @click.option('-c', '--cluster', help='Specify cluster to execute command. Default usage cluster from context.') @click.pass_context def apply(ctx, file_path, template_path, dry_run, deploy, envs, env_file, cluster, **kwargs): '\n \x08\n # Apply yaml file with service definition\n cmd::ecsctl apply -f my-app/service.yaml\n\n \x08\n # Apply yaml file with task definition\n cmd::ecsctl apply -f my-app/task-definition.yaml\n\n \x08\n # Apply yaml template with task definition and set variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env image=my-image -e tag=1.0.0\n\n \x08\n # Apply yaml template with task definition and file with variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file dev.env\n\n \x08\n # Apply yaml template with task definition and file with variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file common.env --env-file dev.env\n\n \x08\n # Apply folder with configuration files\n cmd::ecsctl apply -f my-app/\n\n \x08\n # Apply yaml file with task definition and update service\n cmd::ecsctl apply -f my-app/task-definition.yaml --deploy\n\n \x08\n # Check yaml file with task definition\n cmd::ecsctl apply -f my-app/task-definition.yaml --dry-run\n\n \x08\n # Apply secret to SSM\n cmd::ecsctl apply -f my-app/secret.yaml\n ' bw = ctx.obj['bw'] if (not cluster): cluster = ctx.obj['cluster'] if (file_path and (not template_path)): (_type, f) = ('file', core.FileLoader(file_path)) elif (template_path and (not file_path)): (_type, f) = ('template', core.FileLoaderTemplate(template_path, envs, env_file)) else: click.echo(click.style(str('Usage only template or file to apply.'), fg='red')) return for doc in f.load(): object_type = core.ObjectType(cluster=cluster, item=doc) tmpl = object_type.get_template() click.echo(click.style(object_type.ID, fg='yellow')) if dry_run: tmpl.run_before(boto_wrapper=bw) param = display.de_unicode(tmpl.to_request()) tmpl.run_after(param, boto_wrapper=bw) click.echo(click.style(param, fg='blue')) click.echo('\n') else: try: resp = bw.apply_object(tmpl=tmpl, deploy=deploy) except Exception as err: click.echo(click.style(str(err), fg='red')) else: click.echo(click.style(object_type.show_response(resp), fg='green')) if resp.get('deploy'): ID = 'Service: {}'.format(resp['deploy']['service']['serviceName']) show_response = resp['deploy']['service']['serviceArn'] task_definition = resp['deploy']['service']['taskDefinition'] click.echo(click.style(ID, fg='yellow')) click.echo(click.style('{} -> {}'.format(show_response, task_definition), fg='green'))
 # Apply yaml file with service definition cmd::ecsctl apply -f my-app/service.yaml  # Apply yaml file with task definition cmd::ecsctl apply -f my-app/task-definition.yaml  # Apply yaml template with task definition and set variables cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env image=my-image -e tag=1.0.0  # Apply yaml template with task definition and file with variables cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file dev.env  # Apply yaml template with task definition and file with variables cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file common.env --env-file dev.env  # Apply folder with configuration files cmd::ecsctl apply -f my-app/  # Apply yaml file with task definition and update service cmd::ecsctl apply -f my-app/task-definition.yaml --deploy  # Check yaml file with task definition cmd::ecsctl apply -f my-app/task-definition.yaml --dry-run  # Apply secret to SSM cmd::ecsctl apply -f my-app/secret.yaml
ecsctl/commands/apply.py
apply
witold-gren/ecsctl
2
python
@click.group(cls=AliasedGroup, short_help='Create or update resources.', invoke_without_command=True) @click.option('-f', '--file', 'file_path', type=click.Path(exists=True), help='Select file or folder that contains the configuration to apply.') @click.option('-t', '--template', 'template_path', type=click.Path(exists=True), help='Select file or folder that contains the template configuration to apply.') @click.option('-e', '--env', 'envs', multiple=True, help='Load environment variable and apply to all object usage Jinja2 templates.') @click.option('--env-file', 'env_file', multiple=True, help='Load environment variable from file and apply to all object usage Jinja2 templates.') @click.option('--dry-run', is_flag=True, default=False, help='If true, only print the object that would be sent, without sending it') @click.option('--deploy', is_flag=True, default=False, help='During update task-definition also update service.') @click.option('-c', '--cluster', help='Specify cluster to execute command. Default usage cluster from context.') @click.pass_context def apply(ctx, file_path, template_path, dry_run, deploy, envs, env_file, cluster, **kwargs): '\n \x08\n # Apply yaml file with service definition\n cmd::ecsctl apply -f my-app/service.yaml\n\n \x08\n # Apply yaml file with task definition\n cmd::ecsctl apply -f my-app/task-definition.yaml\n\n \x08\n # Apply yaml template with task definition and set variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env image=my-image -e tag=1.0.0\n\n \x08\n # Apply yaml template with task definition and file with variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file dev.env\n\n \x08\n # Apply yaml template with task definition and file with variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file common.env --env-file dev.env\n\n \x08\n # Apply folder with configuration files\n cmd::ecsctl apply -f my-app/\n\n \x08\n # Apply yaml file with task definition and update service\n cmd::ecsctl apply -f my-app/task-definition.yaml --deploy\n\n \x08\n # Check yaml file with task definition\n cmd::ecsctl apply -f my-app/task-definition.yaml --dry-run\n\n \x08\n # Apply secret to SSM\n cmd::ecsctl apply -f my-app/secret.yaml\n ' bw = ctx.obj['bw'] if (not cluster): cluster = ctx.obj['cluster'] if (file_path and (not template_path)): (_type, f) = ('file', core.FileLoader(file_path)) elif (template_path and (not file_path)): (_type, f) = ('template', core.FileLoaderTemplate(template_path, envs, env_file)) else: click.echo(click.style(str('Usage only template or file to apply.'), fg='red')) return for doc in f.load(): object_type = core.ObjectType(cluster=cluster, item=doc) tmpl = object_type.get_template() click.echo(click.style(object_type.ID, fg='yellow')) if dry_run: tmpl.run_before(boto_wrapper=bw) param = display.de_unicode(tmpl.to_request()) tmpl.run_after(param, boto_wrapper=bw) click.echo(click.style(param, fg='blue')) click.echo('\n') else: try: resp = bw.apply_object(tmpl=tmpl, deploy=deploy) except Exception as err: click.echo(click.style(str(err), fg='red')) else: click.echo(click.style(object_type.show_response(resp), fg='green')) if resp.get('deploy'): ID = 'Service: {}'.format(resp['deploy']['service']['serviceName']) show_response = resp['deploy']['service']['serviceArn'] task_definition = resp['deploy']['service']['taskDefinition'] click.echo(click.style(ID, fg='yellow')) click.echo(click.style('{} -> {}'.format(show_response, task_definition), fg='green'))
@click.group(cls=AliasedGroup, short_help='Create or update resources.', invoke_without_command=True) @click.option('-f', '--file', 'file_path', type=click.Path(exists=True), help='Select file or folder that contains the configuration to apply.') @click.option('-t', '--template', 'template_path', type=click.Path(exists=True), help='Select file or folder that contains the template configuration to apply.') @click.option('-e', '--env', 'envs', multiple=True, help='Load environment variable and apply to all object usage Jinja2 templates.') @click.option('--env-file', 'env_file', multiple=True, help='Load environment variable from file and apply to all object usage Jinja2 templates.') @click.option('--dry-run', is_flag=True, default=False, help='If true, only print the object that would be sent, without sending it') @click.option('--deploy', is_flag=True, default=False, help='During update task-definition also update service.') @click.option('-c', '--cluster', help='Specify cluster to execute command. Default usage cluster from context.') @click.pass_context def apply(ctx, file_path, template_path, dry_run, deploy, envs, env_file, cluster, **kwargs): '\n \x08\n # Apply yaml file with service definition\n cmd::ecsctl apply -f my-app/service.yaml\n\n \x08\n # Apply yaml file with task definition\n cmd::ecsctl apply -f my-app/task-definition.yaml\n\n \x08\n # Apply yaml template with task definition and set variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env image=my-image -e tag=1.0.0\n\n \x08\n # Apply yaml template with task definition and file with variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file dev.env\n\n \x08\n # Apply yaml template with task definition and file with variables\n cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file common.env --env-file dev.env\n\n \x08\n # Apply folder with configuration files\n cmd::ecsctl apply -f my-app/\n\n \x08\n # Apply yaml file with task definition and update service\n cmd::ecsctl apply -f my-app/task-definition.yaml --deploy\n\n \x08\n # Check yaml file with task definition\n cmd::ecsctl apply -f my-app/task-definition.yaml --dry-run\n\n \x08\n # Apply secret to SSM\n cmd::ecsctl apply -f my-app/secret.yaml\n ' bw = ctx.obj['bw'] if (not cluster): cluster = ctx.obj['cluster'] if (file_path and (not template_path)): (_type, f) = ('file', core.FileLoader(file_path)) elif (template_path and (not file_path)): (_type, f) = ('template', core.FileLoaderTemplate(template_path, envs, env_file)) else: click.echo(click.style(str('Usage only template or file to apply.'), fg='red')) return for doc in f.load(): object_type = core.ObjectType(cluster=cluster, item=doc) tmpl = object_type.get_template() click.echo(click.style(object_type.ID, fg='yellow')) if dry_run: tmpl.run_before(boto_wrapper=bw) param = display.de_unicode(tmpl.to_request()) tmpl.run_after(param, boto_wrapper=bw) click.echo(click.style(param, fg='blue')) click.echo('\n') else: try: resp = bw.apply_object(tmpl=tmpl, deploy=deploy) except Exception as err: click.echo(click.style(str(err), fg='red')) else: click.echo(click.style(object_type.show_response(resp), fg='green')) if resp.get('deploy'): ID = 'Service: {}'.format(resp['deploy']['service']['serviceName']) show_response = resp['deploy']['service']['serviceArn'] task_definition = resp['deploy']['service']['taskDefinition'] click.echo(click.style(ID, fg='yellow')) click.echo(click.style('{} -> {}'.format(show_response, task_definition), fg='green'))<|docstring|> # Apply yaml file with service definition cmd::ecsctl apply -f my-app/service.yaml  # Apply yaml file with task definition cmd::ecsctl apply -f my-app/task-definition.yaml  # Apply yaml template with task definition and set variables cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env image=my-image -e tag=1.0.0  # Apply yaml template with task definition and file with variables cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file dev.env  # Apply yaml template with task definition and file with variables cmd::ecsctl apply -t my-app/task-definition.yaml.tpl --env-file common.env --env-file dev.env  # Apply folder with configuration files cmd::ecsctl apply -f my-app/  # Apply yaml file with task definition and update service cmd::ecsctl apply -f my-app/task-definition.yaml --deploy  # Check yaml file with task definition cmd::ecsctl apply -f my-app/task-definition.yaml --dry-run  # Apply secret to SSM cmd::ecsctl apply -f my-app/secret.yaml<|endoftext|>
84c417b460259554fb5ddcdbb766fcb5ca85fec6d6072cd3cc5bef1a5d1d70df
def head(self, n: int=2) -> List[Row]: 'return a list built from the first n elements' return [*islice(self, n)]
return a list built from the first n elements
src/pyngsild/source/__init__.py
head
Orange-OpenSource/pyngsild
0
python
def head(self, n: int=2) -> List[Row]: return [*islice(self, n)]
def head(self, n: int=2) -> List[Row]: return [*islice(self, n)]<|docstring|>return a list built from the first n elements<|endoftext|>
215d7f3e4f85a9dcac2437d493cf28b751eb058bcb17aca8afe6b37a72458761
def first(self) -> Row: 'return the first element' row: Row = None try: row = self.head(1)[0] except Exception: pass return row
return the first element
src/pyngsild/source/__init__.py
first
Orange-OpenSource/pyngsild
0
python
def first(self) -> Row: row: Row = None try: row = self.head(1)[0] except Exception: pass return row
def first(self) -> Row: row: Row = None try: row = self.head(1)[0] except Exception: pass return row<|docstring|>return the first element<|endoftext|>
1c2e79dab63dc8e001e704df8e58abf216a00621731d5ee8b0368d76aa9d6fce
def skip_header(self, lines: int=1): 'return a new Source with first n lines skipped, default is to skip only the first line' return Source(islice(self, lines, None))
return a new Source with first n lines skipped, default is to skip only the first line
src/pyngsild/source/__init__.py
skip_header
Orange-OpenSource/pyngsild
0
python
def skip_header(self, lines: int=1): return Source(islice(self, lines, None))
def skip_header(self, lines: int=1): return Source(islice(self, lines, None))<|docstring|>return a new Source with first n lines skipped, default is to skip only the first line<|endoftext|>
cd48ab8d62911fa3d164135142f0892bbe783e5ce1a423f7e5a5b37dd827b5a5
def limit(self, n: int=10): 'return a new Source limited to the first n elements' iterator = iter(self) return Source((next(iterator) for _ in range(n)))
return a new Source limited to the first n elements
src/pyngsild/source/__init__.py
limit
Orange-OpenSource/pyngsild
0
python
def limit(self, n: int=10): iterator = iter(self) return Source((next(iterator) for _ in range(n)))
def limit(self, n: int=10): iterator = iter(self) return Source((next(iterator) for _ in range(n)))<|docstring|>return a new Source limited to the first n elements<|endoftext|>
803877be8ebb78248e26340932211348c75d8ca7b79b2f2d02291b142d272956
@classmethod def from_stream(cls, stream: Iterable[Any], provider: str='user', fmt=RowFormat.TEXT, **kwargs): 'automatically create the Source from a stream' return SourceStream(stream, provider, fmt, **kwargs)
automatically create the Source from a stream
src/pyngsild/source/__init__.py
from_stream
Orange-OpenSource/pyngsild
0
python
@classmethod def from_stream(cls, stream: Iterable[Any], provider: str='user', fmt=RowFormat.TEXT, **kwargs): return SourceStream(stream, provider, fmt, **kwargs)
@classmethod def from_stream(cls, stream: Iterable[Any], provider: str='user', fmt=RowFormat.TEXT, **kwargs): return SourceStream(stream, provider, fmt, **kwargs)<|docstring|>automatically create the Source from a stream<|endoftext|>
dbdaa8a7f9837c7678d7e34fe0ecb7920e4a62e73c4a559a787534358832ae7e
@classmethod def from_stdin(cls, provider: str='user', **kwargs): 'automatically create the Source from the standard input' return SourceStream(sys.stdin, provider, **kwargs)
automatically create the Source from the standard input
src/pyngsild/source/__init__.py
from_stdin
Orange-OpenSource/pyngsild
0
python
@classmethod def from_stdin(cls, provider: str='user', **kwargs): return SourceStream(sys.stdin, provider, **kwargs)
@classmethod def from_stdin(cls, provider: str='user', **kwargs): return SourceStream(sys.stdin, provider, **kwargs)<|docstring|>automatically create the Source from the standard input<|endoftext|>
dbeb1b6f115e57132274bb6038339e3bdf03e8ef5f917150187d64f4c3e73f35
async def _broken_handler(_): 'Unable to properly handle cancel' try: (await asyncio.sleep(1)) except asyncio.CancelledError: raise Exception('This was unexpected')
Unable to properly handle cancel
tests/test_server_handler.py
_broken_handler
fundthmcalculus/grpclib
754
python
async def _broken_handler(_): try: (await asyncio.sleep(1)) except asyncio.CancelledError: raise Exception('This was unexpected')
async def _broken_handler(_): try: (await asyncio.sleep(1)) except asyncio.CancelledError: raise Exception('This was unexpected')<|docstring|>Unable to properly handle cancel<|endoftext|>
938748b76b75d9165009001e0c493c1ede51ebb339731c0df9fc05be7c59162b
def help_handler(event, context): '\n GET - Lambda que mostra o as informações do projeto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: Retorna a ajuda.\n ' return DOC_STRING
GET - Lambda que mostra o as informações do projeto :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: Retorna a ajuda.
handlers.py
help_handler
LeonardoGazziro/crawler_precos
0
python
def help_handler(event, context): '\n GET - Lambda que mostra o as informações do projeto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: Retorna a ajuda.\n ' return DOC_STRING
def help_handler(event, context): '\n GET - Lambda que mostra o as informações do projeto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: Retorna a ajuda.\n ' return DOC_STRING<|docstring|>GET - Lambda que mostra o as informações do projeto :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: Retorna a ajuda.<|endoftext|>
a233dcdf4b21405b71c271105e24a90635f5846f86235fa9451ea8042b975a57
def inserir_produto_handler(event, context): '\n POST - Insere um novo produto para pesquisa no Crawler\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a inserção do produto.\n ' body = event.get('body', {}) s3_bucket = getenv('S3_BUCKET', '') print(s3_bucket) if body: (json_valido, msg) = json_inserir_prod_valido(body) if json_valido: s3 = S3(s3_bucket) s3.create_s3_instance() (resp, msg) = s3.put_s3_obj('', body, body['product']) print(resp) print(msg) json_ret = {'status': 200, 'msg': 'Produto inserido com sucesso!'} else: json_ret = {'status': 500, 'msg': msg} else: json_ret = {'status': 500, 'msg': 'Json inválido!'} return json_ret
POST - Insere um novo produto para pesquisa no Crawler :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o status e a mensagem sobre a inserção do produto.
handlers.py
inserir_produto_handler
LeonardoGazziro/crawler_precos
0
python
def inserir_produto_handler(event, context): '\n POST - Insere um novo produto para pesquisa no Crawler\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a inserção do produto.\n ' body = event.get('body', {}) s3_bucket = getenv('S3_BUCKET', ) print(s3_bucket) if body: (json_valido, msg) = json_inserir_prod_valido(body) if json_valido: s3 = S3(s3_bucket) s3.create_s3_instance() (resp, msg) = s3.put_s3_obj(, body, body['product']) print(resp) print(msg) json_ret = {'status': 200, 'msg': 'Produto inserido com sucesso!'} else: json_ret = {'status': 500, 'msg': msg} else: json_ret = {'status': 500, 'msg': 'Json inválido!'} return json_ret
def inserir_produto_handler(event, context): '\n POST - Insere um novo produto para pesquisa no Crawler\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a inserção do produto.\n ' body = event.get('body', {}) s3_bucket = getenv('S3_BUCKET', ) print(s3_bucket) if body: (json_valido, msg) = json_inserir_prod_valido(body) if json_valido: s3 = S3(s3_bucket) s3.create_s3_instance() (resp, msg) = s3.put_s3_obj(, body, body['product']) print(resp) print(msg) json_ret = {'status': 200, 'msg': 'Produto inserido com sucesso!'} else: json_ret = {'status': 500, 'msg': msg} else: json_ret = {'status': 500, 'msg': 'Json inválido!'} return json_ret<|docstring|>POST - Insere um novo produto para pesquisa no Crawler :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o status e a mensagem sobre a inserção do produto.<|endoftext|>
4bd613171763b94b8dfc54d13a0a5f4dbe0197c1e7c0322e658e2dae69038780
def inserir_json_crawler_handler(event, context): '\n Quando um objeto de novo produto é criado, triggar está lambda para inserir o produto no JSON de coleta.\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a inserção do produto.\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', '') crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', '') s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj('', crawler_prod_file_name) if (crawler_json == False): body = {'scrap_time': 3600, 'os_notify': 'True', 'products_list': []} (resp, msg) = s3_crawler.put_s3_obj('', body, crawler_prod_file_name) if resp: (crawler_json, msg) = s3_crawler.get_s3_obj('', crawler_prod_file_name) for obj in event['Records']: bucket_name = obj['s3']['bucket']['name'] obj = obj['s3']['object']['key'] s3 = S3(bucket_name) s3.create_s3_instance() (obj_json, msg) = s3.get_s3_obj('', obj) obj_json['id'] = str(uuid.uuid4()) crawler_json['products_list'].append(obj_json) (resp, msg) = s3_crawler.put_s3_obj('', crawler_json, crawler_prod_file_name) if resp: print('Inserido com sucesso.') obj_json['last_crawled_price'] = 0 (resp, msg) = s3_crawler.put_s3_obj('', obj_json, obj_json['id'])
Quando um objeto de novo produto é criado, triggar está lambda para inserir o produto no JSON de coleta. :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o status e a mensagem sobre a inserção do produto.
handlers.py
inserir_json_crawler_handler
LeonardoGazziro/crawler_precos
0
python
def inserir_json_crawler_handler(event, context): '\n Quando um objeto de novo produto é criado, triggar está lambda para inserir o produto no JSON de coleta.\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a inserção do produto.\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) if (crawler_json == False): body = {'scrap_time': 3600, 'os_notify': 'True', 'products_list': []} (resp, msg) = s3_crawler.put_s3_obj(, body, crawler_prod_file_name) if resp: (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) for obj in event['Records']: bucket_name = obj['s3']['bucket']['name'] obj = obj['s3']['object']['key'] s3 = S3(bucket_name) s3.create_s3_instance() (obj_json, msg) = s3.get_s3_obj(, obj) obj_json['id'] = str(uuid.uuid4()) crawler_json['products_list'].append(obj_json) (resp, msg) = s3_crawler.put_s3_obj(, crawler_json, crawler_prod_file_name) if resp: print('Inserido com sucesso.') obj_json['last_crawled_price'] = 0 (resp, msg) = s3_crawler.put_s3_obj(, obj_json, obj_json['id'])
def inserir_json_crawler_handler(event, context): '\n Quando um objeto de novo produto é criado, triggar está lambda para inserir o produto no JSON de coleta.\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a inserção do produto.\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) if (crawler_json == False): body = {'scrap_time': 3600, 'os_notify': 'True', 'products_list': []} (resp, msg) = s3_crawler.put_s3_obj(, body, crawler_prod_file_name) if resp: (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) for obj in event['Records']: bucket_name = obj['s3']['bucket']['name'] obj = obj['s3']['object']['key'] s3 = S3(bucket_name) s3.create_s3_instance() (obj_json, msg) = s3.get_s3_obj(, obj) obj_json['id'] = str(uuid.uuid4()) crawler_json['products_list'].append(obj_json) (resp, msg) = s3_crawler.put_s3_obj(, crawler_json, crawler_prod_file_name) if resp: print('Inserido com sucesso.') obj_json['last_crawled_price'] = 0 (resp, msg) = s3_crawler.put_s3_obj(, obj_json, obj_json['id'])<|docstring|>Quando um objeto de novo produto é criado, triggar está lambda para inserir o produto no JSON de coleta. :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o status e a mensagem sobre a inserção do produto.<|endoftext|>
016ffa3fc5dfe7b72feb7e1ef31d1259781479f95dd24b6165d130d0ee58c172
def listar_produtos_handler(event, context): '\n GET - Retorna a lista de produtos que estão sendo pesquisados pelo crawler.\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna um JSON com a lista de produtos que estão sendo crawleados\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', '') crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', '') s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj('', crawler_prod_file_name) if crawler_json: return {'status': 200, 'products_list': crawler_json['products_list']} else: return {'status': 404, 'msg': 'Lista de produtos não encontrada'}
GET - Retorna a lista de produtos que estão sendo pesquisados pelo crawler. :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna um JSON com a lista de produtos que estão sendo crawleados
handlers.py
listar_produtos_handler
LeonardoGazziro/crawler_precos
0
python
def listar_produtos_handler(event, context): '\n GET - Retorna a lista de produtos que estão sendo pesquisados pelo crawler.\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna um JSON com a lista de produtos que estão sendo crawleados\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) if crawler_json: return {'status': 200, 'products_list': crawler_json['products_list']} else: return {'status': 404, 'msg': 'Lista de produtos não encontrada'}
def listar_produtos_handler(event, context): '\n GET - Retorna a lista de produtos que estão sendo pesquisados pelo crawler.\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna um JSON com a lista de produtos que estão sendo crawleados\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) if crawler_json: return {'status': 200, 'products_list': crawler_json['products_list']} else: return {'status': 404, 'msg': 'Lista de produtos não encontrada'}<|docstring|>GET - Retorna a lista de produtos que estão sendo pesquisados pelo crawler. :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna um JSON com a lista de produtos que estão sendo crawleados<|endoftext|>
15a597ecabc86441948b94ba4e94ad9e9017d10fd89f2344a3de6e9396257531
def alterar_preco_aviso_handler(event, context): '\n POST - altera o valor de aviso de um produto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a alteracao do preço de aviso\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', '') crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', '') resp = None body = event.get('body', {}) s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj('', crawler_prod_file_name) if (crawler_json and (body != {})): for prod in crawler_json['products_list']: if (prod['id'] == body['id']): prod['wanted_price'] = body['wanted_price'] (resp, msg) = s3_crawler.put_s3_obj('', crawler_json, crawler_prod_file_name) (prod_json, msg) = s3_crawler.get_s3_obj('', prod['id']) if prod_json: prod_json['wanted_price'] = body['wanted_price'] (resp, msg) = s3_crawler.put_s3_obj('', prod_json, prod['id']) break if resp: return {'status': 200, 'msg': 'Preço atualizado com sucesso!'} else: return {'status': 200, 'msg': 'Falha ao atualizar o preço do produto!'}
POST - altera o valor de aviso de um produto :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o status e a mensagem sobre a alteracao do preço de aviso
handlers.py
alterar_preco_aviso_handler
LeonardoGazziro/crawler_precos
0
python
def alterar_preco_aviso_handler(event, context): '\n POST - altera o valor de aviso de um produto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a alteracao do preço de aviso\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) resp = None body = event.get('body', {}) s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) if (crawler_json and (body != {})): for prod in crawler_json['products_list']: if (prod['id'] == body['id']): prod['wanted_price'] = body['wanted_price'] (resp, msg) = s3_crawler.put_s3_obj(, crawler_json, crawler_prod_file_name) (prod_json, msg) = s3_crawler.get_s3_obj(, prod['id']) if prod_json: prod_json['wanted_price'] = body['wanted_price'] (resp, msg) = s3_crawler.put_s3_obj(, prod_json, prod['id']) break if resp: return {'status': 200, 'msg': 'Preço atualizado com sucesso!'} else: return {'status': 200, 'msg': 'Falha ao atualizar o preço do produto!'}
def alterar_preco_aviso_handler(event, context): '\n POST - altera o valor de aviso de um produto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o status e a mensagem sobre a alteracao do preço de aviso\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) resp = None body = event.get('body', {}) s3_crawler = S3(s3_bucket_crawler) s3_crawler.create_s3_instance() (crawler_json, msg) = s3_crawler.get_s3_obj(, crawler_prod_file_name) if (crawler_json and (body != {})): for prod in crawler_json['products_list']: if (prod['id'] == body['id']): prod['wanted_price'] = body['wanted_price'] (resp, msg) = s3_crawler.put_s3_obj(, crawler_json, crawler_prod_file_name) (prod_json, msg) = s3_crawler.get_s3_obj(, prod['id']) if prod_json: prod_json['wanted_price'] = body['wanted_price'] (resp, msg) = s3_crawler.put_s3_obj(, prod_json, prod['id']) break if resp: return {'status': 200, 'msg': 'Preço atualizado com sucesso!'} else: return {'status': 200, 'msg': 'Falha ao atualizar o preço do produto!'}<|docstring|>POST - altera o valor de aviso de um produto :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o status e a mensagem sobre a alteracao do preço de aviso<|endoftext|>
ded371510e32a14e256a0527c32010cf8c7d3cc8873f78b51854732cbf86be85
def ver_info_produto_handler(event, context): '\n GET - retorna as informações de um produto, limite, nome e lista de links que estão sendo crawleadas\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna as informações de um produto, caso exista\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', '') (prod_json, msg) = (None, None) path = event.get('path', {}) if ('id' in path.keys()): s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (prod_json, msg) = s3.get_s3_obj('', path['id']) if prod_json: prod_json['status'] = 200 return prod_json else: return {'status': 404, 'msg': 'Produto não encontrado'}
GET - retorna as informações de um produto, limite, nome e lista de links que estão sendo crawleadas :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna as informações de um produto, caso exista
handlers.py
ver_info_produto_handler
LeonardoGazziro/crawler_precos
0
python
def ver_info_produto_handler(event, context): '\n GET - retorna as informações de um produto, limite, nome e lista de links que estão sendo crawleadas\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna as informações de um produto, caso exista\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) (prod_json, msg) = (None, None) path = event.get('path', {}) if ('id' in path.keys()): s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (prod_json, msg) = s3.get_s3_obj(, path['id']) if prod_json: prod_json['status'] = 200 return prod_json else: return {'status': 404, 'msg': 'Produto não encontrado'}
def ver_info_produto_handler(event, context): '\n GET - retorna as informações de um produto, limite, nome e lista de links que estão sendo crawleadas\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna as informações de um produto, caso exista\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) (prod_json, msg) = (None, None) path = event.get('path', {}) if ('id' in path.keys()): s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (prod_json, msg) = s3.get_s3_obj(, path['id']) if prod_json: prod_json['status'] = 200 return prod_json else: return {'status': 404, 'msg': 'Produto não encontrado'}<|docstring|>GET - retorna as informações de um produto, limite, nome e lista de links que estão sendo crawleadas :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna as informações de um produto, caso exista<|endoftext|>
d3e670c44ffd69d1839ccdd0c7e2a730c8221da45b1fa0918fdb6eadf52273fb
def ver_ultimos_precos_handler(event, context): '\n GET - Retorna o JSON com os ultimos preços crawleados\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna os ultimos preços que foram crawleados para cada produto\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', '') crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', '') (last_price_list, msg) = (list(), None) s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (list_files, msg) = s3.get_bucket_files(s3_bucket_crawler) for s3_file in list_files: if (s3_file['Key'] == f'{crawler_prod_file_name}.json'): continue else: (prod_json, msg) = s3.get_s3_obj('', s3_file['Key']) last_price_list.append({'id': prod_json['id'], 'product': prod_json['product'], 'last_crawled_price': prod_json['last_crawled_price']}) if (len(last_price_list) > 0): return {'status': 200, 'price_list': last_price_list} else: return {'status': 404, 'msg': 'Lista de preços não encontrada.'}
GET - Retorna o JSON com os ultimos preços crawleados :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna os ultimos preços que foram crawleados para cada produto
handlers.py
ver_ultimos_precos_handler
LeonardoGazziro/crawler_precos
0
python
def ver_ultimos_precos_handler(event, context): '\n GET - Retorna o JSON com os ultimos preços crawleados\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna os ultimos preços que foram crawleados para cada produto\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) (last_price_list, msg) = (list(), None) s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (list_files, msg) = s3.get_bucket_files(s3_bucket_crawler) for s3_file in list_files: if (s3_file['Key'] == f'{crawler_prod_file_name}.json'): continue else: (prod_json, msg) = s3.get_s3_obj(, s3_file['Key']) last_price_list.append({'id': prod_json['id'], 'product': prod_json['product'], 'last_crawled_price': prod_json['last_crawled_price']}) if (len(last_price_list) > 0): return {'status': 200, 'price_list': last_price_list} else: return {'status': 404, 'msg': 'Lista de preços não encontrada.'}
def ver_ultimos_precos_handler(event, context): '\n GET - Retorna o JSON com os ultimos preços crawleados\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna os ultimos preços que foram crawleados para cada produto\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) crawler_prod_file_name = getenv('S3_CRAWLER_PROD_LIST_FILE', ) (last_price_list, msg) = (list(), None) s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (list_files, msg) = s3.get_bucket_files(s3_bucket_crawler) for s3_file in list_files: if (s3_file['Key'] == f'{crawler_prod_file_name}.json'): continue else: (prod_json, msg) = s3.get_s3_obj(, s3_file['Key']) last_price_list.append({'id': prod_json['id'], 'product': prod_json['product'], 'last_crawled_price': prod_json['last_crawled_price']}) if (len(last_price_list) > 0): return {'status': 200, 'price_list': last_price_list} else: return {'status': 404, 'msg': 'Lista de preços não encontrada.'}<|docstring|>GET - Retorna o JSON com os ultimos preços crawleados :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna os ultimos preços que foram crawleados para cada produto<|endoftext|>
ec7922f38e5b08795367b1c61ec7bd56c1c9bf2cf32743cb6c671fa57836b610
def ver_ultimo_preco_prod_handler(event, context): '\n GET - retorna o ultimo preço de um produto utilizando o id do produto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o ultimo preço de um produto crawleado\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', '') (prod_json, msg) = (None, None) path = event.get('path', {}) if ('id' in path.keys()): s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (prod_json, msg) = s3.get_s3_obj('', path['id']) if prod_json: return {'status': 200, 'id': prod_json['id'], 'product': prod_json['product'], 'last_crawled_price': prod_json['last_crawled_price']} else: return {'status': 404, 'msg': 'Produto não encontrado'}
GET - retorna o ultimo preço de um produto utilizando o id do produto :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o ultimo preço de um produto crawleado
handlers.py
ver_ultimo_preco_prod_handler
LeonardoGazziro/crawler_precos
0
python
def ver_ultimo_preco_prod_handler(event, context): '\n GET - retorna o ultimo preço de um produto utilizando o id do produto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o ultimo preço de um produto crawleado\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) (prod_json, msg) = (None, None) path = event.get('path', {}) if ('id' in path.keys()): s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (prod_json, msg) = s3.get_s3_obj(, path['id']) if prod_json: return {'status': 200, 'id': prod_json['id'], 'product': prod_json['product'], 'last_crawled_price': prod_json['last_crawled_price']} else: return {'status': 404, 'msg': 'Produto não encontrado'}
def ver_ultimo_preco_prod_handler(event, context): '\n GET - retorna o ultimo preço de um produto utilizando o id do produto\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: retorna o ultimo preço de um produto crawleado\n ' s3_bucket_crawler = getenv('S3_BUCKET_CRAWLER', ) (prod_json, msg) = (None, None) path = event.get('path', {}) if ('id' in path.keys()): s3 = S3(s3_bucket_crawler) s3.create_s3_instance() (prod_json, msg) = s3.get_s3_obj(, path['id']) if prod_json: return {'status': 200, 'id': prod_json['id'], 'product': prod_json['product'], 'last_crawled_price': prod_json['last_crawled_price']} else: return {'status': 404, 'msg': 'Produto não encontrado'}<|docstring|>GET - retorna o ultimo preço de um produto utilizando o id do produto :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: retorna o ultimo preço de um produto crawleado<|endoftext|>
bf37be5f406d53f951865aa040ecdacbd149533465386a42c391155f3857b923
def crawler_prods_handler(event, context): '\n Coleta o valor dos produtos que estão na lista para ser crawleados\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: None\n ' crawler = Crawler() crawler.run()
Coleta o valor dos produtos que estão na lista para ser crawleados :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: None
handlers.py
crawler_prods_handler
LeonardoGazziro/crawler_precos
0
python
def crawler_prods_handler(event, context): '\n Coleta o valor dos produtos que estão na lista para ser crawleados\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: None\n ' crawler = Crawler() crawler.run()
def crawler_prods_handler(event, context): '\n Coleta o valor dos produtos que estão na lista para ser crawleados\n :param event: informações do Evento da Lambda\n :param context: informações do contexto da Lambda\n :return: None\n ' crawler = Crawler() crawler.run()<|docstring|>Coleta o valor dos produtos que estão na lista para ser crawleados :param event: informações do Evento da Lambda :param context: informações do contexto da Lambda :return: None<|endoftext|>
ef1977f81ee3b9127a9980aeab6f432b16a96f27ab5d01249b96ff08e6ece228
def test_update_customers(self): '\n Test retrieving list of customers from Stripe and creation of Django User and StripeUser instances.\n ' response = self._load_test_data('v1/api_customer_list_2_items.json') stripe_api_update_customers(test_data=response) user_1 = get_user_model().objects.get(email='example@example.com') stripe_user_1 = StripeUser.objects.get(user=user_1) self.assertEqual(stripe_user_1.customer_id, 'cus_tester') user_2 = get_user_model().objects.get(email='example@example.com') stripe_user_2 = StripeUser.objects.get(user=user_2) self.assertEqual(stripe_user_2.customer_id, 'cus_tester2') user_3 = get_user_model().objects.get(email='example@example.com') stripe_user_3 = StripeUser.objects.get(user=user_3) self.assertEqual(stripe_user_3.customer_id, 'cus_tester3')
Test retrieving list of customers from Stripe and creation of Django User and StripeUser instances.
tests/api/test_update_customers.py
test_update_customers
joshuakoh1/drf-stripe-subscription
33
python
def test_update_customers(self): '\n \n ' response = self._load_test_data('v1/api_customer_list_2_items.json') stripe_api_update_customers(test_data=response) user_1 = get_user_model().objects.get(email='example@example.com') stripe_user_1 = StripeUser.objects.get(user=user_1) self.assertEqual(stripe_user_1.customer_id, 'cus_tester') user_2 = get_user_model().objects.get(email='example@example.com') stripe_user_2 = StripeUser.objects.get(user=user_2) self.assertEqual(stripe_user_2.customer_id, 'cus_tester2') user_3 = get_user_model().objects.get(email='example@example.com') stripe_user_3 = StripeUser.objects.get(user=user_3) self.assertEqual(stripe_user_3.customer_id, 'cus_tester3')
def test_update_customers(self): '\n \n ' response = self._load_test_data('v1/api_customer_list_2_items.json') stripe_api_update_customers(test_data=response) user_1 = get_user_model().objects.get(email='example@example.com') stripe_user_1 = StripeUser.objects.get(user=user_1) self.assertEqual(stripe_user_1.customer_id, 'cus_tester') user_2 = get_user_model().objects.get(email='example@example.com') stripe_user_2 = StripeUser.objects.get(user=user_2) self.assertEqual(stripe_user_2.customer_id, 'cus_tester2') user_3 = get_user_model().objects.get(email='example@example.com') stripe_user_3 = StripeUser.objects.get(user=user_3) self.assertEqual(stripe_user_3.customer_id, 'cus_tester3')<|docstring|>Test retrieving list of customers from Stripe and creation of Django User and StripeUser instances.<|endoftext|>
f0e36b13db9825647653f5387012706aa9d6757a7523b5cb3552650c5912b001
def lastUpdateDate(dataset, date): "\n Given a Resource Watch dataset's API ID and a datetime,\n this function will update the dataset's 'last update date' on the API with the given datetime\n INPUT dataset: Resource Watch API dataset ID (string)\n date: date to set as the 'last update date' for the input dataset (datetime)\n " apiUrl = f'http://api.resourcewatch.org/v1/dataset/{dataset}' headers = {'Content-Type': 'application/json', 'Authorization': os.getenv('apiToken')} body = {'dataLastUpdated': date.isoformat()} try: r = requests.patch(url=apiUrl, json=body, headers=headers) logging.info(((('[lastUpdated]: SUCCESS, ' + date.isoformat()) + ' status code ') + str(r.status_code))) return 0 except Exception as e: logging.error(('[lastUpdated]: ' + str(e)))
Given a Resource Watch dataset's API ID and a datetime, this function will update the dataset's 'last update date' on the API with the given datetime INPUT dataset: Resource Watch API dataset ID (string) date: date to set as the 'last update date' for the input dataset (datetime)
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
lastUpdateDate
resource-watch/nrt-scripts
6
python
def lastUpdateDate(dataset, date): "\n Given a Resource Watch dataset's API ID and a datetime,\n this function will update the dataset's 'last update date' on the API with the given datetime\n INPUT dataset: Resource Watch API dataset ID (string)\n date: date to set as the 'last update date' for the input dataset (datetime)\n " apiUrl = f'http://api.resourcewatch.org/v1/dataset/{dataset}' headers = {'Content-Type': 'application/json', 'Authorization': os.getenv('apiToken')} body = {'dataLastUpdated': date.isoformat()} try: r = requests.patch(url=apiUrl, json=body, headers=headers) logging.info(((('[lastUpdated]: SUCCESS, ' + date.isoformat()) + ' status code ') + str(r.status_code))) return 0 except Exception as e: logging.error(('[lastUpdated]: ' + str(e)))
def lastUpdateDate(dataset, date): "\n Given a Resource Watch dataset's API ID and a datetime,\n this function will update the dataset's 'last update date' on the API with the given datetime\n INPUT dataset: Resource Watch API dataset ID (string)\n date: date to set as the 'last update date' for the input dataset (datetime)\n " apiUrl = f'http://api.resourcewatch.org/v1/dataset/{dataset}' headers = {'Content-Type': 'application/json', 'Authorization': os.getenv('apiToken')} body = {'dataLastUpdated': date.isoformat()} try: r = requests.patch(url=apiUrl, json=body, headers=headers) logging.info(((('[lastUpdated]: SUCCESS, ' + date.isoformat()) + ' status code ') + str(r.status_code))) return 0 except Exception as e: logging.error(('[lastUpdated]: ' + str(e)))<|docstring|>Given a Resource Watch dataset's API ID and a datetime, this function will update the dataset's 'last update date' on the API with the given datetime INPUT dataset: Resource Watch API dataset ID (string) date: date to set as the 'last update date' for the input dataset (datetime)<|endoftext|>
2788281155298e46332fa8d63878b784ee61df1320d3679b2235a587e81ceefb
def checkCreateTable(table, schema, id_field, time_field=''): "\n Create the table if it does not exist, and pull list of IDs already in the table if it does\n INPUT table: Carto table to check or create (string)\n schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary)\n id_field: name of column that we want to use as a unique ID for this table; this will be used to compare the\n source data to the our table each time we run the script so that we only have to pull data we\n haven't previously uploaded (string)\n time_field: optional, name of column that will store datetime information (string)\n RETURN list of existing IDs in the table, pulled from the id_field column (list of strings)\n " if cartosql.tableExists(table, user=CARTO_USER, key=CARTO_KEY): logging.info('Fetching existing IDs') r = cartosql.getFields(id_field, table, f='csv', post=True, user=CARTO_USER, key=CARTO_KEY) return r.text.split('\r\n')[1:(- 1)] else: logging.info('Table {} does not exist, creating'.format(table)) cartosql.createTable(table, schema, user=CARTO_USER, key=CARTO_KEY) if id_field: cartosql.createIndex(table, id_field, unique=True, user=CARTO_USER, key=CARTO_KEY) if time_field: cartosql.createIndex(table, time_field, user=CARTO_USER, key=CARTO_KEY) return []
Create the table if it does not exist, and pull list of IDs already in the table if it does INPUT table: Carto table to check or create (string) schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary) id_field: name of column that we want to use as a unique ID for this table; this will be used to compare the source data to the our table each time we run the script so that we only have to pull data we haven't previously uploaded (string) time_field: optional, name of column that will store datetime information (string) RETURN list of existing IDs in the table, pulled from the id_field column (list of strings)
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
checkCreateTable
resource-watch/nrt-scripts
6
python
def checkCreateTable(table, schema, id_field, time_field=): "\n Create the table if it does not exist, and pull list of IDs already in the table if it does\n INPUT table: Carto table to check or create (string)\n schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary)\n id_field: name of column that we want to use as a unique ID for this table; this will be used to compare the\n source data to the our table each time we run the script so that we only have to pull data we\n haven't previously uploaded (string)\n time_field: optional, name of column that will store datetime information (string)\n RETURN list of existing IDs in the table, pulled from the id_field column (list of strings)\n " if cartosql.tableExists(table, user=CARTO_USER, key=CARTO_KEY): logging.info('Fetching existing IDs') r = cartosql.getFields(id_field, table, f='csv', post=True, user=CARTO_USER, key=CARTO_KEY) return r.text.split('\r\n')[1:(- 1)] else: logging.info('Table {} does not exist, creating'.format(table)) cartosql.createTable(table, schema, user=CARTO_USER, key=CARTO_KEY) if id_field: cartosql.createIndex(table, id_field, unique=True, user=CARTO_USER, key=CARTO_KEY) if time_field: cartosql.createIndex(table, time_field, user=CARTO_USER, key=CARTO_KEY) return []
def checkCreateTable(table, schema, id_field, time_field=): "\n Create the table if it does not exist, and pull list of IDs already in the table if it does\n INPUT table: Carto table to check or create (string)\n schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary)\n id_field: name of column that we want to use as a unique ID for this table; this will be used to compare the\n source data to the our table each time we run the script so that we only have to pull data we\n haven't previously uploaded (string)\n time_field: optional, name of column that will store datetime information (string)\n RETURN list of existing IDs in the table, pulled from the id_field column (list of strings)\n " if cartosql.tableExists(table, user=CARTO_USER, key=CARTO_KEY): logging.info('Fetching existing IDs') r = cartosql.getFields(id_field, table, f='csv', post=True, user=CARTO_USER, key=CARTO_KEY) return r.text.split('\r\n')[1:(- 1)] else: logging.info('Table {} does not exist, creating'.format(table)) cartosql.createTable(table, schema, user=CARTO_USER, key=CARTO_KEY) if id_field: cartosql.createIndex(table, id_field, unique=True, user=CARTO_USER, key=CARTO_KEY) if time_field: cartosql.createIndex(table, time_field, user=CARTO_USER, key=CARTO_KEY) return []<|docstring|>Create the table if it does not exist, and pull list of IDs already in the table if it does INPUT table: Carto table to check or create (string) schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary) id_field: name of column that we want to use as a unique ID for this table; this will be used to compare the source data to the our table each time we run the script so that we only have to pull data we haven't previously uploaded (string) time_field: optional, name of column that will store datetime information (string) RETURN list of existing IDs in the table, pulled from the id_field column (list of strings)<|endoftext|>
4ee3784966cea479446c26c19f64c238b6147ca4f1b1e88f3058c98f4ba2a380
def delete_local(): "\n Delete all files and folders in Docker container's data directory\n " try: for f in os.listdir(DATA_DIR): try: logging.info('Removing {}'.format(f)) os.remove(((DATA_DIR + '/') + f)) except: shutil.rmtree(f, ignore_errors=True) except NameError: logging.info('No local files to clean.')
Delete all files and folders in Docker container's data directory
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
delete_local
resource-watch/nrt-scripts
6
python
def delete_local(): "\n \n " try: for f in os.listdir(DATA_DIR): try: logging.info('Removing {}'.format(f)) os.remove(((DATA_DIR + '/') + f)) except: shutil.rmtree(f, ignore_errors=True) except NameError: logging.info('No local files to clean.')
def delete_local(): "\n \n " try: for f in os.listdir(DATA_DIR): try: logging.info('Removing {}'.format(f)) os.remove(((DATA_DIR + '/') + f)) except: shutil.rmtree(f, ignore_errors=True) except NameError: logging.info('No local files to clean.')<|docstring|>Delete all files and folders in Docker container's data directory<|endoftext|>
eb363673ef5090717bde39e740240b48ee339f35637817e437fba2536aa538de
def fetch(): '\n download, unzip, and import the data as geopandas dataframes\n ' n_tries = 5 date = datetime.datetime.utcnow() fetch_exception = None for i in range(0, n_tries): try: date_str = date.strftime('%b%Y') raw_data_file = os.path.join(DATA_DIR, os.path.basename(SOURCE_URL.format(date_str))) urllib.request.urlretrieve(SOURCE_URL.format(date_str), raw_data_file) logging.info('Unzip the data folder') raw_data_file_unzipped = raw_data_file.split('.')[0] zip_ref = ZipFile(raw_data_file, 'r') zip_ref.extractall(raw_data_file_unzipped) zip_ref.close() logging.info('Data of {} successfully fetched.'.format(date_str)) except Exception as e: fetch_exception = e first = date.replace(day=1) date = (first - datetime.timedelta(days=1)) else: break else: logging.info('Failed to fetch data.') raise fetch_exception zipped_shp = glob.glob(os.path.join(raw_data_file_unzipped, '*shp*.zip')) for zipped in zipped_shp: zip_ref = ZipFile(zipped, 'r') zip_ref.extractall(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):])) zip_ref.close() DATA_DICT['point']['path'] = [glob.glob(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):], '*points.shp'))[0] for zipped in zipped_shp] DATA_DICT['polygon']['path'] = [glob.glob(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):], '*polygons.shp'))[0] for zipped in zipped_shp]
download, unzip, and import the data as geopandas dataframes
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
fetch
resource-watch/nrt-scripts
6
python
def fetch(): '\n \n ' n_tries = 5 date = datetime.datetime.utcnow() fetch_exception = None for i in range(0, n_tries): try: date_str = date.strftime('%b%Y') raw_data_file = os.path.join(DATA_DIR, os.path.basename(SOURCE_URL.format(date_str))) urllib.request.urlretrieve(SOURCE_URL.format(date_str), raw_data_file) logging.info('Unzip the data folder') raw_data_file_unzipped = raw_data_file.split('.')[0] zip_ref = ZipFile(raw_data_file, 'r') zip_ref.extractall(raw_data_file_unzipped) zip_ref.close() logging.info('Data of {} successfully fetched.'.format(date_str)) except Exception as e: fetch_exception = e first = date.replace(day=1) date = (first - datetime.timedelta(days=1)) else: break else: logging.info('Failed to fetch data.') raise fetch_exception zipped_shp = glob.glob(os.path.join(raw_data_file_unzipped, '*shp*.zip')) for zipped in zipped_shp: zip_ref = ZipFile(zipped, 'r') zip_ref.extractall(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):])) zip_ref.close() DATA_DICT['point']['path'] = [glob.glob(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):], '*points.shp'))[0] for zipped in zipped_shp] DATA_DICT['polygon']['path'] = [glob.glob(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):], '*polygons.shp'))[0] for zipped in zipped_shp]
def fetch(): '\n \n ' n_tries = 5 date = datetime.datetime.utcnow() fetch_exception = None for i in range(0, n_tries): try: date_str = date.strftime('%b%Y') raw_data_file = os.path.join(DATA_DIR, os.path.basename(SOURCE_URL.format(date_str))) urllib.request.urlretrieve(SOURCE_URL.format(date_str), raw_data_file) logging.info('Unzip the data folder') raw_data_file_unzipped = raw_data_file.split('.')[0] zip_ref = ZipFile(raw_data_file, 'r') zip_ref.extractall(raw_data_file_unzipped) zip_ref.close() logging.info('Data of {} successfully fetched.'.format(date_str)) except Exception as e: fetch_exception = e first = date.replace(day=1) date = (first - datetime.timedelta(days=1)) else: break else: logging.info('Failed to fetch data.') raise fetch_exception zipped_shp = glob.glob(os.path.join(raw_data_file_unzipped, '*shp*.zip')) for zipped in zipped_shp: zip_ref = ZipFile(zipped, 'r') zip_ref.extractall(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):])) zip_ref.close() DATA_DICT['point']['path'] = [glob.glob(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):], '*points.shp'))[0] for zipped in zipped_shp] DATA_DICT['polygon']['path'] = [glob.glob(os.path.join(raw_data_file_unzipped, zipped.split('.')[0][(- 5):], '*polygons.shp'))[0] for zipped in zipped_shp]<|docstring|>download, unzip, and import the data as geopandas dataframes<|endoftext|>
1afb3ff7e99ee33d7339b851682566ec950f881efe2b63668293008e7a7a5eca
def convert_geometry(geom): '\n Function to convert shapely geometries to geojsons\n INPUT geom: shapely geometry \n RETURN output: geojson \n ' if (geom.geom_type == 'Polygon'): return geom.__geo_interface__ elif ((geom.geom_type == 'MultiPoint') and (len(geom) == 1)): return geom[0].__geo_interface__ else: return geom.__geo_interface__
Function to convert shapely geometries to geojsons INPUT geom: shapely geometry RETURN output: geojson
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
convert_geometry
resource-watch/nrt-scripts
6
python
def convert_geometry(geom): '\n Function to convert shapely geometries to geojsons\n INPUT geom: shapely geometry \n RETURN output: geojson \n ' if (geom.geom_type == 'Polygon'): return geom.__geo_interface__ elif ((geom.geom_type == 'MultiPoint') and (len(geom) == 1)): return geom[0].__geo_interface__ else: return geom.__geo_interface__
def convert_geometry(geom): '\n Function to convert shapely geometries to geojsons\n INPUT geom: shapely geometry \n RETURN output: geojson \n ' if (geom.geom_type == 'Polygon'): return geom.__geo_interface__ elif ((geom.geom_type == 'MultiPoint') and (len(geom) == 1)): return geom[0].__geo_interface__ else: return geom.__geo_interface__<|docstring|>Function to convert shapely geometries to geojsons INPUT geom: shapely geometry RETURN output: geojson<|endoftext|>
4f8a139f296e27168aca5aec3b006c45f3d4c3c6c65230e5f5c5d9c593e55c36
def insert_carto(row, table, schema, session): '\n Function to upload data to the Carto table \n INPUT row: the geopandas dataframe of data we want to upload (geopandas dataframe)\n session: the request session initiated to send requests to Carto \n schema: fields and corresponding data types of the Carto table\n table: name of the Carto table\n ' row = row.where(row.notnull(), None) n_tries = 5 retry_wait_time = 6 insert_exception = None row['geometry'] = convert_geometry(row['geometry']) fields = schema.keys() values = cartosql._dumpRows([row.values.tolist()], tuple(schema.values())) sql = 'INSERT INTO "{}" ({}) VALUES {}'.format(table, ', '.join(fields), values) del values for i in range(n_tries): try: r = session.post('https://{}.carto.com/api/v2/sql'.format(CARTO_USER), json={'api_key': CARTO_KEY, 'q': sql}) r.raise_for_status() except Exception as e: insert_exception = e logging.warning('Attempt #{} to upload row #{} unsuccessful. Trying again after {} seconds'.format(i, row['WDPA_PID'], retry_wait_time)) logging.debug(('Exception encountered during upload attempt: ' + str(e))) time.sleep(retry_wait_time) else: break else: logging.error('Upload of row #{} has failed after {} attempts'.format(row['WDPA_PID'], n_tries)) logging.error(('Problematic row: ' + str(row))) logging.error('Raising exception encountered during last upload attempt') logging.error(insert_exception) raise insert_exception
Function to upload data to the Carto table INPUT row: the geopandas dataframe of data we want to upload (geopandas dataframe) session: the request session initiated to send requests to Carto schema: fields and corresponding data types of the Carto table table: name of the Carto table
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
insert_carto
resource-watch/nrt-scripts
6
python
def insert_carto(row, table, schema, session): '\n Function to upload data to the Carto table \n INPUT row: the geopandas dataframe of data we want to upload (geopandas dataframe)\n session: the request session initiated to send requests to Carto \n schema: fields and corresponding data types of the Carto table\n table: name of the Carto table\n ' row = row.where(row.notnull(), None) n_tries = 5 retry_wait_time = 6 insert_exception = None row['geometry'] = convert_geometry(row['geometry']) fields = schema.keys() values = cartosql._dumpRows([row.values.tolist()], tuple(schema.values())) sql = 'INSERT INTO "{}" ({}) VALUES {}'.format(table, ', '.join(fields), values) del values for i in range(n_tries): try: r = session.post('https://{}.carto.com/api/v2/sql'.format(CARTO_USER), json={'api_key': CARTO_KEY, 'q': sql}) r.raise_for_status() except Exception as e: insert_exception = e logging.warning('Attempt #{} to upload row #{} unsuccessful. Trying again after {} seconds'.format(i, row['WDPA_PID'], retry_wait_time)) logging.debug(('Exception encountered during upload attempt: ' + str(e))) time.sleep(retry_wait_time) else: break else: logging.error('Upload of row #{} has failed after {} attempts'.format(row['WDPA_PID'], n_tries)) logging.error(('Problematic row: ' + str(row))) logging.error('Raising exception encountered during last upload attempt') logging.error(insert_exception) raise insert_exception
def insert_carto(row, table, schema, session): '\n Function to upload data to the Carto table \n INPUT row: the geopandas dataframe of data we want to upload (geopandas dataframe)\n session: the request session initiated to send requests to Carto \n schema: fields and corresponding data types of the Carto table\n table: name of the Carto table\n ' row = row.where(row.notnull(), None) n_tries = 5 retry_wait_time = 6 insert_exception = None row['geometry'] = convert_geometry(row['geometry']) fields = schema.keys() values = cartosql._dumpRows([row.values.tolist()], tuple(schema.values())) sql = 'INSERT INTO "{}" ({}) VALUES {}'.format(table, ', '.join(fields), values) del values for i in range(n_tries): try: r = session.post('https://{}.carto.com/api/v2/sql'.format(CARTO_USER), json={'api_key': CARTO_KEY, 'q': sql}) r.raise_for_status() except Exception as e: insert_exception = e logging.warning('Attempt #{} to upload row #{} unsuccessful. Trying again after {} seconds'.format(i, row['WDPA_PID'], retry_wait_time)) logging.debug(('Exception encountered during upload attempt: ' + str(e))) time.sleep(retry_wait_time) else: break else: logging.error('Upload of row #{} has failed after {} attempts'.format(row['WDPA_PID'], n_tries)) logging.error(('Problematic row: ' + str(row))) logging.error('Raising exception encountered during last upload attempt') logging.error(insert_exception) raise insert_exception<|docstring|>Function to upload data to the Carto table INPUT row: the geopandas dataframe of data we want to upload (geopandas dataframe) session: the request session initiated to send requests to Carto schema: fields and corresponding data types of the Carto table table: name of the Carto table<|endoftext|>
e46c440811145dd246f0d7d22f1029d9101c855894de7d345dbb97d0e1c8461c
def processData(table, gdf, schema, session): '\n Upload new data\n INPUT table: Carto table to upload data to (string)\n gdf: data to be uploaded to the Carto table (geopandas dataframe)\n schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary)\n session: request session to send requests to Carto\n RETURN num_new: total number of rows of data sent to Carto table (integer)\n ' gdf.apply(insert_carto, args=(table, schema, session), axis=1) num_new = len(gdf.index) ' # change privacy of table on Carto\n # set up carto authentication using local variables for username and API key \n auth_client = APIKeyAuthClient(api_key=CARTO_KEY, base_url="https://{user}.carto.com/".format(user=CARTO_USER))\n # set up dataset manager with authentication\n dataset_manager = DatasetManager(auth_client)\n # set dataset privacy\n dataset = dataset_manager.get(value[\'CARTO_TABLE\'])\n dataset.privacy = \'LINK\'\n dataset.save() ' return num_new
Upload new data INPUT table: Carto table to upload data to (string) gdf: data to be uploaded to the Carto table (geopandas dataframe) schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary) session: request session to send requests to Carto RETURN num_new: total number of rows of data sent to Carto table (integer)
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
processData
resource-watch/nrt-scripts
6
python
def processData(table, gdf, schema, session): '\n Upload new data\n INPUT table: Carto table to upload data to (string)\n gdf: data to be uploaded to the Carto table (geopandas dataframe)\n schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary)\n session: request session to send requests to Carto\n RETURN num_new: total number of rows of data sent to Carto table (integer)\n ' gdf.apply(insert_carto, args=(table, schema, session), axis=1) num_new = len(gdf.index) ' # change privacy of table on Carto\n # set up carto authentication using local variables for username and API key \n auth_client = APIKeyAuthClient(api_key=CARTO_KEY, base_url="https://{user}.carto.com/".format(user=CARTO_USER))\n # set up dataset manager with authentication\n dataset_manager = DatasetManager(auth_client)\n # set dataset privacy\n dataset = dataset_manager.get(value[\'CARTO_TABLE\'])\n dataset.privacy = \'LINK\'\n dataset.save() ' return num_new
def processData(table, gdf, schema, session): '\n Upload new data\n INPUT table: Carto table to upload data to (string)\n gdf: data to be uploaded to the Carto table (geopandas dataframe)\n schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary)\n session: request session to send requests to Carto\n RETURN num_new: total number of rows of data sent to Carto table (integer)\n ' gdf.apply(insert_carto, args=(table, schema, session), axis=1) num_new = len(gdf.index) ' # change privacy of table on Carto\n # set up carto authentication using local variables for username and API key \n auth_client = APIKeyAuthClient(api_key=CARTO_KEY, base_url="https://{user}.carto.com/".format(user=CARTO_USER))\n # set up dataset manager with authentication\n dataset_manager = DatasetManager(auth_client)\n # set dataset privacy\n dataset = dataset_manager.get(value[\'CARTO_TABLE\'])\n dataset.privacy = \'LINK\'\n dataset.save() ' return num_new<|docstring|>Upload new data INPUT table: Carto table to upload data to (string) gdf: data to be uploaded to the Carto table (geopandas dataframe) schema: dictionary of column names and types, used if we are creating the table for the first time (dictionary) session: request session to send requests to Carto RETURN num_new: total number of rows of data sent to Carto table (integer)<|endoftext|>
0077d290d080b19a71fb78cdfb2a8edd3d0c9938ef92d3168a4f3eac29d2e43c
def updateResourceWatch(num_new): "\n This function should update Resource Watch to reflect the new data.\n This may include updating the 'last update date' and updating any dates on layers\n " if (num_new > 0): most_recent_date = datetime.datetime.utcnow() lastUpdateDate(DATASET_ID, most_recent_date)
This function should update Resource Watch to reflect the new data. This may include updating the 'last update date' and updating any dates on layers
bio_007b_nrt_rw0_marine_protected_areas/contents/src/__init__.py
updateResourceWatch
resource-watch/nrt-scripts
6
python
def updateResourceWatch(num_new): "\n This function should update Resource Watch to reflect the new data.\n This may include updating the 'last update date' and updating any dates on layers\n " if (num_new > 0): most_recent_date = datetime.datetime.utcnow() lastUpdateDate(DATASET_ID, most_recent_date)
def updateResourceWatch(num_new): "\n This function should update Resource Watch to reflect the new data.\n This may include updating the 'last update date' and updating any dates on layers\n " if (num_new > 0): most_recent_date = datetime.datetime.utcnow() lastUpdateDate(DATASET_ID, most_recent_date)<|docstring|>This function should update Resource Watch to reflect the new data. This may include updating the 'last update date' and updating any dates on layers<|endoftext|>
2d6414edfd7c540bc070c65021dea459eba653053b55b3cb979c980dcaa8dab3
def codeblock(self, code): '\n Literal code blocks are introduced by ending a paragraph with\n the special marker ::. The literal block must be indented\n (and, like all paragraphs, separated from the surrounding\n ones by blank lines).\n ' self.start_codeblock() self.doc.writeln(code) self.end_codeblock()
Literal code blocks are introduced by ending a paragraph with the special marker ::. The literal block must be indented (and, like all paragraphs, separated from the surrounding ones by blank lines).
venv/lib/python2.7/site-packages/bcdoc/style.py
codeblock
BlueMoon3000/election-2016
0
python
def codeblock(self, code): '\n Literal code blocks are introduced by ending a paragraph with\n the special marker ::. The literal block must be indented\n (and, like all paragraphs, separated from the surrounding\n ones by blank lines).\n ' self.start_codeblock() self.doc.writeln(code) self.end_codeblock()
def codeblock(self, code): '\n Literal code blocks are introduced by ending a paragraph with\n the special marker ::. The literal block must be indented\n (and, like all paragraphs, separated from the surrounding\n ones by blank lines).\n ' self.start_codeblock() self.doc.writeln(code) self.end_codeblock()<|docstring|>Literal code blocks are introduced by ending a paragraph with the special marker ::. The literal block must be indented (and, like all paragraphs, separated from the surrounding ones by blank lines).<|endoftext|>
af32ca3645be1fd1322772c1eb79a4fa6e44ce51fe4dadc904cb003a4b796e47
def add_column(self, width): '\n Return a |_Column| object of *width*, newly added rightmost to the\n table.\n ' tblGrid = self._tbl.tblGrid gridCol = tblGrid.add_gridCol() gridCol.w = width for tr in self._tbl.tr_lst: tc = tr.add_tc() tc.width = width return _Column(gridCol, self)
Return a |_Column| object of *width*, newly added rightmost to the table.
venv/Lib/site-packages/docx/table.py
add_column
michael-fourie/notebot
3,031
python
def add_column(self, width): '\n Return a |_Column| object of *width*, newly added rightmost to the\n table.\n ' tblGrid = self._tbl.tblGrid gridCol = tblGrid.add_gridCol() gridCol.w = width for tr in self._tbl.tr_lst: tc = tr.add_tc() tc.width = width return _Column(gridCol, self)
def add_column(self, width): '\n Return a |_Column| object of *width*, newly added rightmost to the\n table.\n ' tblGrid = self._tbl.tblGrid gridCol = tblGrid.add_gridCol() gridCol.w = width for tr in self._tbl.tr_lst: tc = tr.add_tc() tc.width = width return _Column(gridCol, self)<|docstring|>Return a |_Column| object of *width*, newly added rightmost to the table.<|endoftext|>
f3623dfd85dd09275fc7e838abc798266b8a4dda78454789169eacbc86da540d
def add_row(self): '\n Return a |_Row| instance, newly added bottom-most to the table.\n ' tbl = self._tbl tr = tbl.add_tr() for gridCol in tbl.tblGrid.gridCol_lst: tc = tr.add_tc() tc.width = gridCol.w return _Row(tr, self)
Return a |_Row| instance, newly added bottom-most to the table.
venv/Lib/site-packages/docx/table.py
add_row
michael-fourie/notebot
3,031
python
def add_row(self): '\n \n ' tbl = self._tbl tr = tbl.add_tr() for gridCol in tbl.tblGrid.gridCol_lst: tc = tr.add_tc() tc.width = gridCol.w return _Row(tr, self)
def add_row(self): '\n \n ' tbl = self._tbl tr = tbl.add_tr() for gridCol in tbl.tblGrid.gridCol_lst: tc = tr.add_tc() tc.width = gridCol.w return _Row(tr, self)<|docstring|>Return a |_Row| instance, newly added bottom-most to the table.<|endoftext|>
74a9d8e0748eae3e4255bb01138f79ffff13068bc860d9c1e51acdcf848777ef
@property def alignment(self): '\n Read/write. A member of :ref:`WdRowAlignment` or None, specifying the\n positioning of this table between the page margins. |None| if no\n setting is specified, causing the effective value to be inherited\n from the style hierarchy.\n ' return self._tblPr.alignment
Read/write. A member of :ref:`WdRowAlignment` or None, specifying the positioning of this table between the page margins. |None| if no setting is specified, causing the effective value to be inherited from the style hierarchy.
venv/Lib/site-packages/docx/table.py
alignment
michael-fourie/notebot
3,031
python
@property def alignment(self): '\n Read/write. A member of :ref:`WdRowAlignment` or None, specifying the\n positioning of this table between the page margins. |None| if no\n setting is specified, causing the effective value to be inherited\n from the style hierarchy.\n ' return self._tblPr.alignment
@property def alignment(self): '\n Read/write. A member of :ref:`WdRowAlignment` or None, specifying the\n positioning of this table between the page margins. |None| if no\n setting is specified, causing the effective value to be inherited\n from the style hierarchy.\n ' return self._tblPr.alignment<|docstring|>Read/write. A member of :ref:`WdRowAlignment` or None, specifying the positioning of this table between the page margins. |None| if no setting is specified, causing the effective value to be inherited from the style hierarchy.<|endoftext|>
e52e3e365ea56fb1ba288f5b61aeb0c0d3c6ada8f96f09f5fba5f2e62eac2457
@property def autofit(self): '\n |True| if column widths can be automatically adjusted to improve the\n fit of cell contents. |False| if table layout is fixed. Column widths\n are adjusted in either case if total column width exceeds page width.\n Read/write boolean.\n ' return self._tblPr.autofit
|True| if column widths can be automatically adjusted to improve the fit of cell contents. |False| if table layout is fixed. Column widths are adjusted in either case if total column width exceeds page width. Read/write boolean.
venv/Lib/site-packages/docx/table.py
autofit
michael-fourie/notebot
3,031
python
@property def autofit(self): '\n |True| if column widths can be automatically adjusted to improve the\n fit of cell contents. |False| if table layout is fixed. Column widths\n are adjusted in either case if total column width exceeds page width.\n Read/write boolean.\n ' return self._tblPr.autofit
@property def autofit(self): '\n |True| if column widths can be automatically adjusted to improve the\n fit of cell contents. |False| if table layout is fixed. Column widths\n are adjusted in either case if total column width exceeds page width.\n Read/write boolean.\n ' return self._tblPr.autofit<|docstring|>|True| if column widths can be automatically adjusted to improve the fit of cell contents. |False| if table layout is fixed. Column widths are adjusted in either case if total column width exceeds page width. Read/write boolean.<|endoftext|>
c0a8419e82cb0ad63c7fd013b83a7873a3c632962b6f006abcfd4d26e2996582
def cell(self, row_idx, col_idx): '\n Return |_Cell| instance correponding to table cell at *row_idx*,\n *col_idx* intersection, where (0, 0) is the top, left-most cell.\n ' cell_idx = (col_idx + (row_idx * self._column_count)) return self._cells[cell_idx]
Return |_Cell| instance correponding to table cell at *row_idx*, *col_idx* intersection, where (0, 0) is the top, left-most cell.
venv/Lib/site-packages/docx/table.py
cell
michael-fourie/notebot
3,031
python
def cell(self, row_idx, col_idx): '\n Return |_Cell| instance correponding to table cell at *row_idx*,\n *col_idx* intersection, where (0, 0) is the top, left-most cell.\n ' cell_idx = (col_idx + (row_idx * self._column_count)) return self._cells[cell_idx]
def cell(self, row_idx, col_idx): '\n Return |_Cell| instance correponding to table cell at *row_idx*,\n *col_idx* intersection, where (0, 0) is the top, left-most cell.\n ' cell_idx = (col_idx + (row_idx * self._column_count)) return self._cells[cell_idx]<|docstring|>Return |_Cell| instance correponding to table cell at *row_idx*, *col_idx* intersection, where (0, 0) is the top, left-most cell.<|endoftext|>
caadc1e5e0daa44f1b564ca441f7eaab00e19dd919c8a24ab5aea1bac60c9887
def column_cells(self, column_idx): '\n Sequence of cells in the column at *column_idx* in this table.\n ' cells = self._cells idxs = range(column_idx, len(cells), self._column_count) return [cells[idx] for idx in idxs]
Sequence of cells in the column at *column_idx* in this table.
venv/Lib/site-packages/docx/table.py
column_cells
michael-fourie/notebot
3,031
python
def column_cells(self, column_idx): '\n \n ' cells = self._cells idxs = range(column_idx, len(cells), self._column_count) return [cells[idx] for idx in idxs]
def column_cells(self, column_idx): '\n \n ' cells = self._cells idxs = range(column_idx, len(cells), self._column_count) return [cells[idx] for idx in idxs]<|docstring|>Sequence of cells in the column at *column_idx* in this table.<|endoftext|>
72e705762629cb2c6bd2daf9c92f876461e4e545b31b4dc9d0f7ea2d59d20ea0
@lazyproperty def columns(self): '\n |_Columns| instance representing the sequence of columns in this\n table.\n ' return _Columns(self._tbl, self)
|_Columns| instance representing the sequence of columns in this table.
venv/Lib/site-packages/docx/table.py
columns
michael-fourie/notebot
3,031
python
@lazyproperty def columns(self): '\n |_Columns| instance representing the sequence of columns in this\n table.\n ' return _Columns(self._tbl, self)
@lazyproperty def columns(self): '\n |_Columns| instance representing the sequence of columns in this\n table.\n ' return _Columns(self._tbl, self)<|docstring|>|_Columns| instance representing the sequence of columns in this table.<|endoftext|>
23f69604bcb7613d52ed9f5c6832fbcff3e4d9ba02d00a30a16046de58d37f46
def row_cells(self, row_idx): '\n Sequence of cells in the row at *row_idx* in this table.\n ' column_count = self._column_count start = (row_idx * column_count) end = (start + column_count) return self._cells[start:end]
Sequence of cells in the row at *row_idx* in this table.
venv/Lib/site-packages/docx/table.py
row_cells
michael-fourie/notebot
3,031
python
def row_cells(self, row_idx): '\n \n ' column_count = self._column_count start = (row_idx * column_count) end = (start + column_count) return self._cells[start:end]
def row_cells(self, row_idx): '\n \n ' column_count = self._column_count start = (row_idx * column_count) end = (start + column_count) return self._cells[start:end]<|docstring|>Sequence of cells in the row at *row_idx* in this table.<|endoftext|>
926a503dcf2691666b718bb0fc903ef34c862ba24a8170e78e5cce46374d906d
@lazyproperty def rows(self): '\n |_Rows| instance containing the sequence of rows in this table.\n ' return _Rows(self._tbl, self)
|_Rows| instance containing the sequence of rows in this table.
venv/Lib/site-packages/docx/table.py
rows
michael-fourie/notebot
3,031
python
@lazyproperty def rows(self): '\n \n ' return _Rows(self._tbl, self)
@lazyproperty def rows(self): '\n \n ' return _Rows(self._tbl, self)<|docstring|>|_Rows| instance containing the sequence of rows in this table.<|endoftext|>
409270c4535eddc95b0519d68007337b6c8655f659aeac8f3f27e87e8d93fa9d
@property def style(self): '\n Read/write. A |_TableStyle| object representing the style applied to\n this table. The default table style for the document (often `Normal\n Table`) is returned if the table has no directly-applied style.\n Assigning |None| to this property removes any directly-applied table\n style causing it to inherit the default table style of the document.\n Note that the style name of a table style differs slightly from that\n displayed in the user interface; a hyphen, if it appears, must be\n removed. For example, `Light Shading - Accent 1` becomes `Light\n Shading Accent 1`.\n ' style_id = self._tbl.tblStyle_val return self.part.get_style(style_id, WD_STYLE_TYPE.TABLE)
Read/write. A |_TableStyle| object representing the style applied to this table. The default table style for the document (often `Normal Table`) is returned if the table has no directly-applied style. Assigning |None| to this property removes any directly-applied table style causing it to inherit the default table style of the document. Note that the style name of a table style differs slightly from that displayed in the user interface; a hyphen, if it appears, must be removed. For example, `Light Shading - Accent 1` becomes `Light Shading Accent 1`.
venv/Lib/site-packages/docx/table.py
style
michael-fourie/notebot
3,031
python
@property def style(self): '\n Read/write. A |_TableStyle| object representing the style applied to\n this table. The default table style for the document (often `Normal\n Table`) is returned if the table has no directly-applied style.\n Assigning |None| to this property removes any directly-applied table\n style causing it to inherit the default table style of the document.\n Note that the style name of a table style differs slightly from that\n displayed in the user interface; a hyphen, if it appears, must be\n removed. For example, `Light Shading - Accent 1` becomes `Light\n Shading Accent 1`.\n ' style_id = self._tbl.tblStyle_val return self.part.get_style(style_id, WD_STYLE_TYPE.TABLE)
@property def style(self): '\n Read/write. A |_TableStyle| object representing the style applied to\n this table. The default table style for the document (often `Normal\n Table`) is returned if the table has no directly-applied style.\n Assigning |None| to this property removes any directly-applied table\n style causing it to inherit the default table style of the document.\n Note that the style name of a table style differs slightly from that\n displayed in the user interface; a hyphen, if it appears, must be\n removed. For example, `Light Shading - Accent 1` becomes `Light\n Shading Accent 1`.\n ' style_id = self._tbl.tblStyle_val return self.part.get_style(style_id, WD_STYLE_TYPE.TABLE)<|docstring|>Read/write. A |_TableStyle| object representing the style applied to this table. The default table style for the document (often `Normal Table`) is returned if the table has no directly-applied style. Assigning |None| to this property removes any directly-applied table style causing it to inherit the default table style of the document. Note that the style name of a table style differs slightly from that displayed in the user interface; a hyphen, if it appears, must be removed. For example, `Light Shading - Accent 1` becomes `Light Shading Accent 1`.<|endoftext|>
32d3e80060f5f848352244fae22c2076fdebebf14eb47d4fdaa49c9606e05999
@property def table(self): '\n Provide child objects with reference to the |Table| object they\n belong to, without them having to know their direct parent is\n a |Table| object. This is the terminus of a series of `parent._table`\n calls from an arbitrary child through its ancestors.\n ' return self
Provide child objects with reference to the |Table| object they belong to, without them having to know their direct parent is a |Table| object. This is the terminus of a series of `parent._table` calls from an arbitrary child through its ancestors.
venv/Lib/site-packages/docx/table.py
table
michael-fourie/notebot
3,031
python
@property def table(self): '\n Provide child objects with reference to the |Table| object they\n belong to, without them having to know their direct parent is\n a |Table| object. This is the terminus of a series of `parent._table`\n calls from an arbitrary child through its ancestors.\n ' return self
@property def table(self): '\n Provide child objects with reference to the |Table| object they\n belong to, without them having to know their direct parent is\n a |Table| object. This is the terminus of a series of `parent._table`\n calls from an arbitrary child through its ancestors.\n ' return self<|docstring|>Provide child objects with reference to the |Table| object they belong to, without them having to know their direct parent is a |Table| object. This is the terminus of a series of `parent._table` calls from an arbitrary child through its ancestors.<|endoftext|>
b7ee6a062cf2b0d4baeeeeccb3fbfbf960d57627ac3064b22caeb24d312df445
@property def table_direction(self): '\n A member of :ref:`WdTableDirection` indicating the direction in which\n the table cells are ordered, e.g. `WD_TABLE_DIRECTION.LTR`. |None|\n indicates the value is inherited from the style hierarchy.\n ' return self._element.bidiVisual_val
A member of :ref:`WdTableDirection` indicating the direction in which the table cells are ordered, e.g. `WD_TABLE_DIRECTION.LTR`. |None| indicates the value is inherited from the style hierarchy.
venv/Lib/site-packages/docx/table.py
table_direction
michael-fourie/notebot
3,031
python
@property def table_direction(self): '\n A member of :ref:`WdTableDirection` indicating the direction in which\n the table cells are ordered, e.g. `WD_TABLE_DIRECTION.LTR`. |None|\n indicates the value is inherited from the style hierarchy.\n ' return self._element.bidiVisual_val
@property def table_direction(self): '\n A member of :ref:`WdTableDirection` indicating the direction in which\n the table cells are ordered, e.g. `WD_TABLE_DIRECTION.LTR`. |None|\n indicates the value is inherited from the style hierarchy.\n ' return self._element.bidiVisual_val<|docstring|>A member of :ref:`WdTableDirection` indicating the direction in which the table cells are ordered, e.g. `WD_TABLE_DIRECTION.LTR`. |None| indicates the value is inherited from the style hierarchy.<|endoftext|>
dcf05f5e37a0dac0f61db32bc93eb80917ff080b9a510e6def14695233c2a9f5
@property def _cells(self): '\n A sequence of |_Cell| objects, one for each cell of the layout grid.\n If the table contains a span, one or more |_Cell| object references\n are repeated.\n ' col_count = self._column_count cells = [] for tc in self._tbl.iter_tcs(): for grid_span_idx in range(tc.grid_span): if (tc.vMerge == ST_Merge.CONTINUE): cells.append(cells[(- col_count)]) elif (grid_span_idx > 0): cells.append(cells[(- 1)]) else: cells.append(_Cell(tc, self)) return cells
A sequence of |_Cell| objects, one for each cell of the layout grid. If the table contains a span, one or more |_Cell| object references are repeated.
venv/Lib/site-packages/docx/table.py
_cells
michael-fourie/notebot
3,031
python
@property def _cells(self): '\n A sequence of |_Cell| objects, one for each cell of the layout grid.\n If the table contains a span, one or more |_Cell| object references\n are repeated.\n ' col_count = self._column_count cells = [] for tc in self._tbl.iter_tcs(): for grid_span_idx in range(tc.grid_span): if (tc.vMerge == ST_Merge.CONTINUE): cells.append(cells[(- col_count)]) elif (grid_span_idx > 0): cells.append(cells[(- 1)]) else: cells.append(_Cell(tc, self)) return cells
@property def _cells(self): '\n A sequence of |_Cell| objects, one for each cell of the layout grid.\n If the table contains a span, one or more |_Cell| object references\n are repeated.\n ' col_count = self._column_count cells = [] for tc in self._tbl.iter_tcs(): for grid_span_idx in range(tc.grid_span): if (tc.vMerge == ST_Merge.CONTINUE): cells.append(cells[(- col_count)]) elif (grid_span_idx > 0): cells.append(cells[(- 1)]) else: cells.append(_Cell(tc, self)) return cells<|docstring|>A sequence of |_Cell| objects, one for each cell of the layout grid. If the table contains a span, one or more |_Cell| object references are repeated.<|endoftext|>
1f95d45f21869e1471b22623c26d01d8d847435764f56142b7d46449cce70440
@property def _column_count(self): '\n The number of grid columns in this table.\n ' return self._tbl.col_count
The number of grid columns in this table.
venv/Lib/site-packages/docx/table.py
_column_count
michael-fourie/notebot
3,031
python
@property def _column_count(self): '\n \n ' return self._tbl.col_count
@property def _column_count(self): '\n \n ' return self._tbl.col_count<|docstring|>The number of grid columns in this table.<|endoftext|>
4c9e8f4fc63b1947049be94c17c9802ade82bc086af0ae72210b9b100bc6835e
def add_paragraph(self, text='', style=None): "\n Return a paragraph newly added to the end of the content in this\n cell. If present, *text* is added to the paragraph in a single run.\n If specified, the paragraph style *style* is applied. If *style* is\n not specified or is |None|, the result is as though the 'Normal'\n style was applied. Note that the formatting of text in a cell can be\n influenced by the table style. *text* can contain tab (``\\t``)\n characters, which are converted to the appropriate XML form for\n a tab. *text* can also include newline (``\\n``) or carriage return\n (``\\r``) characters, each of which is converted to a line break.\n " return super(_Cell, self).add_paragraph(text, style)
Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, the result is as though the 'Normal' style was applied. Note that the formatting of text in a cell can be influenced by the table style. *text* can contain tab (``\t``) characters, which are converted to the appropriate XML form for a tab. *text* can also include newline (``\n``) or carriage return (``\r``) characters, each of which is converted to a line break.
venv/Lib/site-packages/docx/table.py
add_paragraph
michael-fourie/notebot
3,031
python
def add_paragraph(self, text=, style=None): "\n Return a paragraph newly added to the end of the content in this\n cell. If present, *text* is added to the paragraph in a single run.\n If specified, the paragraph style *style* is applied. If *style* is\n not specified or is |None|, the result is as though the 'Normal'\n style was applied. Note that the formatting of text in a cell can be\n influenced by the table style. *text* can contain tab (``\\t``)\n characters, which are converted to the appropriate XML form for\n a tab. *text* can also include newline (``\\n``) or carriage return\n (``\\r``) characters, each of which is converted to a line break.\n " return super(_Cell, self).add_paragraph(text, style)
def add_paragraph(self, text=, style=None): "\n Return a paragraph newly added to the end of the content in this\n cell. If present, *text* is added to the paragraph in a single run.\n If specified, the paragraph style *style* is applied. If *style* is\n not specified or is |None|, the result is as though the 'Normal'\n style was applied. Note that the formatting of text in a cell can be\n influenced by the table style. *text* can contain tab (``\\t``)\n characters, which are converted to the appropriate XML form for\n a tab. *text* can also include newline (``\\n``) or carriage return\n (``\\r``) characters, each of which is converted to a line break.\n " return super(_Cell, self).add_paragraph(text, style)<|docstring|>Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, the result is as though the 'Normal' style was applied. Note that the formatting of text in a cell can be influenced by the table style. *text* can contain tab (``\t``) characters, which are converted to the appropriate XML form for a tab. *text* can also include newline (``\n``) or carriage return (``\r``) characters, each of which is converted to a line break.<|endoftext|>
b4f8522b9dc156e385e445e7a8363773f8c8fad72036397ffc227b81436ad71b
def add_table(self, rows, cols): '\n Return a table newly added to this cell after any existing cell\n content, having *rows* rows and *cols* columns. An empty paragraph is\n added after the table because Word requires a paragraph element as\n the last element in every cell.\n ' width = (self.width if (self.width is not None) else Inches(1)) table = super(_Cell, self).add_table(rows, cols, width) self.add_paragraph() return table
Return a table newly added to this cell after any existing cell content, having *rows* rows and *cols* columns. An empty paragraph is added after the table because Word requires a paragraph element as the last element in every cell.
venv/Lib/site-packages/docx/table.py
add_table
michael-fourie/notebot
3,031
python
def add_table(self, rows, cols): '\n Return a table newly added to this cell after any existing cell\n content, having *rows* rows and *cols* columns. An empty paragraph is\n added after the table because Word requires a paragraph element as\n the last element in every cell.\n ' width = (self.width if (self.width is not None) else Inches(1)) table = super(_Cell, self).add_table(rows, cols, width) self.add_paragraph() return table
def add_table(self, rows, cols): '\n Return a table newly added to this cell after any existing cell\n content, having *rows* rows and *cols* columns. An empty paragraph is\n added after the table because Word requires a paragraph element as\n the last element in every cell.\n ' width = (self.width if (self.width is not None) else Inches(1)) table = super(_Cell, self).add_table(rows, cols, width) self.add_paragraph() return table<|docstring|>Return a table newly added to this cell after any existing cell content, having *rows* rows and *cols* columns. An empty paragraph is added after the table because Word requires a paragraph element as the last element in every cell.<|endoftext|>
100fd566f10c953412ffa95f75d9f0c6e451a56040412d0d3bdf783fddad9489
def merge(self, other_cell): '\n Return a merged cell created by spanning the rectangular region\n having this cell and *other_cell* as diagonal corners. Raises\n |InvalidSpanError| if the cells do not define a rectangular region.\n ' (tc, tc_2) = (self._tc, other_cell._tc) merged_tc = tc.merge(tc_2) return _Cell(merged_tc, self._parent)
Return a merged cell created by spanning the rectangular region having this cell and *other_cell* as diagonal corners. Raises |InvalidSpanError| if the cells do not define a rectangular region.
venv/Lib/site-packages/docx/table.py
merge
michael-fourie/notebot
3,031
python
def merge(self, other_cell): '\n Return a merged cell created by spanning the rectangular region\n having this cell and *other_cell* as diagonal corners. Raises\n |InvalidSpanError| if the cells do not define a rectangular region.\n ' (tc, tc_2) = (self._tc, other_cell._tc) merged_tc = tc.merge(tc_2) return _Cell(merged_tc, self._parent)
def merge(self, other_cell): '\n Return a merged cell created by spanning the rectangular region\n having this cell and *other_cell* as diagonal corners. Raises\n |InvalidSpanError| if the cells do not define a rectangular region.\n ' (tc, tc_2) = (self._tc, other_cell._tc) merged_tc = tc.merge(tc_2) return _Cell(merged_tc, self._parent)<|docstring|>Return a merged cell created by spanning the rectangular region having this cell and *other_cell* as diagonal corners. Raises |InvalidSpanError| if the cells do not define a rectangular region.<|endoftext|>
1b4d9776b8c43234bc64dade1ee444dbe7c442e8709acd48430a60fcacaa32e9
@property def paragraphs(self): '\n List of paragraphs in the cell. A table cell is required to contain\n at least one block-level element and end with a paragraph. By\n default, a new cell contains a single paragraph. Read-only\n ' return super(_Cell, self).paragraphs
List of paragraphs in the cell. A table cell is required to contain at least one block-level element and end with a paragraph. By default, a new cell contains a single paragraph. Read-only
venv/Lib/site-packages/docx/table.py
paragraphs
michael-fourie/notebot
3,031
python
@property def paragraphs(self): '\n List of paragraphs in the cell. A table cell is required to contain\n at least one block-level element and end with a paragraph. By\n default, a new cell contains a single paragraph. Read-only\n ' return super(_Cell, self).paragraphs
@property def paragraphs(self): '\n List of paragraphs in the cell. A table cell is required to contain\n at least one block-level element and end with a paragraph. By\n default, a new cell contains a single paragraph. Read-only\n ' return super(_Cell, self).paragraphs<|docstring|>List of paragraphs in the cell. A table cell is required to contain at least one block-level element and end with a paragraph. By default, a new cell contains a single paragraph. Read-only<|endoftext|>
c2d7f6de3185bfd1d728f2540eee1620fe821cebbbd63f0427b02af3d299a078
@property def tables(self): '\n List of tables in the cell, in the order they appear. Read-only.\n ' return super(_Cell, self).tables
List of tables in the cell, in the order they appear. Read-only.
venv/Lib/site-packages/docx/table.py
tables
michael-fourie/notebot
3,031
python
@property def tables(self): '\n \n ' return super(_Cell, self).tables
@property def tables(self): '\n \n ' return super(_Cell, self).tables<|docstring|>List of tables in the cell, in the order they appear. Read-only.<|endoftext|>
bd13dc3e9abe3e4aaa72dcc828373b2dd549bccafd77830e7c48bbcf97cf9098
@property def text(self): '\n The entire contents of this cell as a string of text. Assigning\n a string to this property replaces all existing content with a single\n paragraph containing the assigned text in a single run.\n ' return '\n'.join((p.text for p in self.paragraphs))
The entire contents of this cell as a string of text. Assigning a string to this property replaces all existing content with a single paragraph containing the assigned text in a single run.
venv/Lib/site-packages/docx/table.py
text
michael-fourie/notebot
3,031
python
@property def text(self): '\n The entire contents of this cell as a string of text. Assigning\n a string to this property replaces all existing content with a single\n paragraph containing the assigned text in a single run.\n ' return '\n'.join((p.text for p in self.paragraphs))
@property def text(self): '\n The entire contents of this cell as a string of text. Assigning\n a string to this property replaces all existing content with a single\n paragraph containing the assigned text in a single run.\n ' return '\n'.join((p.text for p in self.paragraphs))<|docstring|>The entire contents of this cell as a string of text. Assigning a string to this property replaces all existing content with a single paragraph containing the assigned text in a single run.<|endoftext|>
20bf2eb032f64a0faf478eb0d409135b61f7df51866c3e445940ae3ce2e939c5
@text.setter def text(self, text): '\n Write-only. Set entire contents of cell to the string *text*. Any\n existing content or revisions are replaced.\n ' tc = self._tc tc.clear_content() p = tc.add_p() r = p.add_r() r.text = text
Write-only. Set entire contents of cell to the string *text*. Any existing content or revisions are replaced.
venv/Lib/site-packages/docx/table.py
text
michael-fourie/notebot
3,031
python
@text.setter def text(self, text): '\n Write-only. Set entire contents of cell to the string *text*. Any\n existing content or revisions are replaced.\n ' tc = self._tc tc.clear_content() p = tc.add_p() r = p.add_r() r.text = text
@text.setter def text(self, text): '\n Write-only. Set entire contents of cell to the string *text*. Any\n existing content or revisions are replaced.\n ' tc = self._tc tc.clear_content() p = tc.add_p() r = p.add_r() r.text = text<|docstring|>Write-only. Set entire contents of cell to the string *text*. Any existing content or revisions are replaced.<|endoftext|>
928da4a6bbcf2745abc1fa7c608c84c43ddbb927991ee439292c080be354083a
@property def vertical_alignment(self): 'Member of :ref:`WdCellVerticalAlignment` or None.\n\n A value of |None| indicates vertical alignment for this cell is\n inherited. Assigning |None| causes any explicitly defined vertical\n alignment to be removed, restoring inheritance.\n ' tcPr = self._element.tcPr if (tcPr is None): return None return tcPr.vAlign_val
Member of :ref:`WdCellVerticalAlignment` or None. A value of |None| indicates vertical alignment for this cell is inherited. Assigning |None| causes any explicitly defined vertical alignment to be removed, restoring inheritance.
venv/Lib/site-packages/docx/table.py
vertical_alignment
michael-fourie/notebot
3,031
python
@property def vertical_alignment(self): 'Member of :ref:`WdCellVerticalAlignment` or None.\n\n A value of |None| indicates vertical alignment for this cell is\n inherited. Assigning |None| causes any explicitly defined vertical\n alignment to be removed, restoring inheritance.\n ' tcPr = self._element.tcPr if (tcPr is None): return None return tcPr.vAlign_val
@property def vertical_alignment(self): 'Member of :ref:`WdCellVerticalAlignment` or None.\n\n A value of |None| indicates vertical alignment for this cell is\n inherited. Assigning |None| causes any explicitly defined vertical\n alignment to be removed, restoring inheritance.\n ' tcPr = self._element.tcPr if (tcPr is None): return None return tcPr.vAlign_val<|docstring|>Member of :ref:`WdCellVerticalAlignment` or None. A value of |None| indicates vertical alignment for this cell is inherited. Assigning |None| causes any explicitly defined vertical alignment to be removed, restoring inheritance.<|endoftext|>
defc9f2eb3509d3ccbdc08e2435b7d0e15cc4b0a1efb107022ef8b503b8323e0
@property def width(self): '\n The width of this cell in EMU, or |None| if no explicit width is set.\n ' return self._tc.width
The width of this cell in EMU, or |None| if no explicit width is set.
venv/Lib/site-packages/docx/table.py
width
michael-fourie/notebot
3,031
python
@property def width(self): '\n \n ' return self._tc.width
@property def width(self): '\n \n ' return self._tc.width<|docstring|>The width of this cell in EMU, or |None| if no explicit width is set.<|endoftext|>
c014e2866c499eccde9cccb4c5f0da71f655a70bfb83310e2f041ca5aea5f3f6
@property def cells(self): '\n Sequence of |_Cell| instances corresponding to cells in this column.\n ' return tuple(self.table.column_cells(self._index))
Sequence of |_Cell| instances corresponding to cells in this column.
venv/Lib/site-packages/docx/table.py
cells
michael-fourie/notebot
3,031
python
@property def cells(self): '\n \n ' return tuple(self.table.column_cells(self._index))
@property def cells(self): '\n \n ' return tuple(self.table.column_cells(self._index))<|docstring|>Sequence of |_Cell| instances corresponding to cells in this column.<|endoftext|>
f7c2bc4ad927a4fbc9e57c4e55f7d64247283c6489fe02a70a0a47cd52cc331a
@property def table(self): '\n Reference to the |Table| object this column belongs to.\n ' return self._parent.table
Reference to the |Table| object this column belongs to.
venv/Lib/site-packages/docx/table.py
table
michael-fourie/notebot
3,031
python
@property def table(self): '\n \n ' return self._parent.table
@property def table(self): '\n \n ' return self._parent.table<|docstring|>Reference to the |Table| object this column belongs to.<|endoftext|>
a696eab59db273a50ee85711f65017b3f96e6671ad873eb388572b61e1f41691
@property def width(self): '\n The width of this column in EMU, or |None| if no explicit width is\n set.\n ' return self._gridCol.w
The width of this column in EMU, or |None| if no explicit width is set.
venv/Lib/site-packages/docx/table.py
width
michael-fourie/notebot
3,031
python
@property def width(self): '\n The width of this column in EMU, or |None| if no explicit width is\n set.\n ' return self._gridCol.w
@property def width(self): '\n The width of this column in EMU, or |None| if no explicit width is\n set.\n ' return self._gridCol.w<|docstring|>The width of this column in EMU, or |None| if no explicit width is set.<|endoftext|>
960c13398a99c586a94d2ecdf49866b8dc58e63dae60717d29fe76f3aca20854
@property def _index(self): '\n Index of this column in its table, starting from zero.\n ' return self._gridCol.gridCol_idx
Index of this column in its table, starting from zero.
venv/Lib/site-packages/docx/table.py
_index
michael-fourie/notebot
3,031
python
@property def _index(self): '\n \n ' return self._gridCol.gridCol_idx
@property def _index(self): '\n \n ' return self._gridCol.gridCol_idx<|docstring|>Index of this column in its table, starting from zero.<|endoftext|>
693b592fc40e550bf88e36c6c4fc40f73777fafcb50b72cb6706e53e8e9144a8
def __getitem__(self, idx): "\n Provide indexed access, e.g. 'columns[0]'\n " try: gridCol = self._gridCol_lst[idx] except IndexError: msg = ('column index [%d] is out of range' % idx) raise IndexError(msg) return _Column(gridCol, self)
Provide indexed access, e.g. 'columns[0]'
venv/Lib/site-packages/docx/table.py
__getitem__
michael-fourie/notebot
3,031
python
def __getitem__(self, idx): "\n \n " try: gridCol = self._gridCol_lst[idx] except IndexError: msg = ('column index [%d] is out of range' % idx) raise IndexError(msg) return _Column(gridCol, self)
def __getitem__(self, idx): "\n \n " try: gridCol = self._gridCol_lst[idx] except IndexError: msg = ('column index [%d] is out of range' % idx) raise IndexError(msg) return _Column(gridCol, self)<|docstring|>Provide indexed access, e.g. 'columns[0]'<|endoftext|>
d74fb524f3018e0142f39f2ef4c2f4ebdf2d55cb392f89af7c6b303e8a3960f1
@property def table(self): '\n Reference to the |Table| object this column collection belongs to.\n ' return self._parent.table
Reference to the |Table| object this column collection belongs to.
venv/Lib/site-packages/docx/table.py
table
michael-fourie/notebot
3,031
python
@property def table(self): '\n \n ' return self._parent.table
@property def table(self): '\n \n ' return self._parent.table<|docstring|>Reference to the |Table| object this column collection belongs to.<|endoftext|>
a383e3d9307b4f1be4f665ed385532e3649cb68223498cf86a944eb2a7424c2a
@property def _gridCol_lst(self): '\n Sequence containing ``<w:gridCol>`` elements for this table, each\n representing a table column.\n ' tblGrid = self._tbl.tblGrid return tblGrid.gridCol_lst
Sequence containing ``<w:gridCol>`` elements for this table, each representing a table column.
venv/Lib/site-packages/docx/table.py
_gridCol_lst
michael-fourie/notebot
3,031
python
@property def _gridCol_lst(self): '\n Sequence containing ``<w:gridCol>`` elements for this table, each\n representing a table column.\n ' tblGrid = self._tbl.tblGrid return tblGrid.gridCol_lst
@property def _gridCol_lst(self): '\n Sequence containing ``<w:gridCol>`` elements for this table, each\n representing a table column.\n ' tblGrid = self._tbl.tblGrid return tblGrid.gridCol_lst<|docstring|>Sequence containing ``<w:gridCol>`` elements for this table, each representing a table column.<|endoftext|>
2911c34c6e559edd356e503688523bddea34a95e0a4ee45ec0a0b3468203b7d7
@property def cells(self): '\n Sequence of |_Cell| instances corresponding to cells in this row.\n ' return tuple(self.table.row_cells(self._index))
Sequence of |_Cell| instances corresponding to cells in this row.
venv/Lib/site-packages/docx/table.py
cells
michael-fourie/notebot
3,031
python
@property def cells(self): '\n \n ' return tuple(self.table.row_cells(self._index))
@property def cells(self): '\n \n ' return tuple(self.table.row_cells(self._index))<|docstring|>Sequence of |_Cell| instances corresponding to cells in this row.<|endoftext|>
a4c1aa8d6d86e20f9d0b5d4fcf4177fb2e14ad6f06f20c6d3e909fce49ad7398
@property def height(self): '\n Return a |Length| object representing the height of this cell, or\n |None| if no explicit height is set.\n ' return self._tr.trHeight_val
Return a |Length| object representing the height of this cell, or |None| if no explicit height is set.
venv/Lib/site-packages/docx/table.py
height
michael-fourie/notebot
3,031
python
@property def height(self): '\n Return a |Length| object representing the height of this cell, or\n |None| if no explicit height is set.\n ' return self._tr.trHeight_val
@property def height(self): '\n Return a |Length| object representing the height of this cell, or\n |None| if no explicit height is set.\n ' return self._tr.trHeight_val<|docstring|>Return a |Length| object representing the height of this cell, or |None| if no explicit height is set.<|endoftext|>
52de17258b583d8955924c8bf1d24ea73fab0e6085f04c5c4af0e9cf9f224d06
@property def height_rule(self): '\n Return the height rule of this cell as a member of the\n :ref:`WdRowHeightRule` enumeration, or |None| if no explicit\n height_rule is set.\n ' return self._tr.trHeight_hRule
Return the height rule of this cell as a member of the :ref:`WdRowHeightRule` enumeration, or |None| if no explicit height_rule is set.
venv/Lib/site-packages/docx/table.py
height_rule
michael-fourie/notebot
3,031
python
@property def height_rule(self): '\n Return the height rule of this cell as a member of the\n :ref:`WdRowHeightRule` enumeration, or |None| if no explicit\n height_rule is set.\n ' return self._tr.trHeight_hRule
@property def height_rule(self): '\n Return the height rule of this cell as a member of the\n :ref:`WdRowHeightRule` enumeration, or |None| if no explicit\n height_rule is set.\n ' return self._tr.trHeight_hRule<|docstring|>Return the height rule of this cell as a member of the :ref:`WdRowHeightRule` enumeration, or |None| if no explicit height_rule is set.<|endoftext|>
ecd143c505075cc30100eb7033747b32bee690ab6ad9a5ac45ace552a51535f1
@property def table(self): '\n Reference to the |Table| object this row belongs to.\n ' return self._parent.table
Reference to the |Table| object this row belongs to.
venv/Lib/site-packages/docx/table.py
table
michael-fourie/notebot
3,031
python
@property def table(self): '\n \n ' return self._parent.table
@property def table(self): '\n \n ' return self._parent.table<|docstring|>Reference to the |Table| object this row belongs to.<|endoftext|>
f92d93ce730eeea781c7fd9c2c4b96cd5b6e68a1a17e9a84217a0ee023bb1334
@property def _index(self): '\n Index of this row in its table, starting from zero.\n ' return self._tr.tr_idx
Index of this row in its table, starting from zero.
venv/Lib/site-packages/docx/table.py
_index
michael-fourie/notebot
3,031
python
@property def _index(self): '\n \n ' return self._tr.tr_idx
@property def _index(self): '\n \n ' return self._tr.tr_idx<|docstring|>Index of this row in its table, starting from zero.<|endoftext|>
c2e8f93224a4a5234276f54ed7f924ad172b0c787c82a465b56a051ed62d9326
def __getitem__(self, idx): "\n Provide indexed access, (e.g. 'rows[0]')\n " return list(self)[idx]
Provide indexed access, (e.g. 'rows[0]')
venv/Lib/site-packages/docx/table.py
__getitem__
michael-fourie/notebot
3,031
python
def __getitem__(self, idx): "\n \n " return list(self)[idx]
def __getitem__(self, idx): "\n \n " return list(self)[idx]<|docstring|>Provide indexed access, (e.g. 'rows[0]')<|endoftext|>
25ace2f0f12684a690d701045fdcbbd1d82ab685e3f3fb1fcd0105ef33665c03
@property def table(self): '\n Reference to the |Table| object this row collection belongs to.\n ' return self._parent.table
Reference to the |Table| object this row collection belongs to.
venv/Lib/site-packages/docx/table.py
table
michael-fourie/notebot
3,031
python
@property def table(self): '\n \n ' return self._parent.table
@property def table(self): '\n \n ' return self._parent.table<|docstring|>Reference to the |Table| object this row collection belongs to.<|endoftext|>
452ed7c57a74fbc0e2bbe7af3621b6b3c8aa531478055be9b7e7c6932d9ffbbf
def is_implicit(self): 'Tests if this authorization is implicit.\n\n return: (boolean) - ``true`` if this authorization is implicit,\n ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['implicit'])
Tests if this authorization is implicit. return: (boolean) - ``true`` if this authorization is implicit, ``false`` otherwise *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
is_implicit
UOC/dlkit
2
python
def is_implicit(self): 'Tests if this authorization is implicit.\n\n return: (boolean) - ``true`` if this authorization is implicit,\n ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['implicit'])
def is_implicit(self): 'Tests if this authorization is implicit.\n\n return: (boolean) - ``true`` if this authorization is implicit,\n ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['implicit'])<|docstring|>Tests if this authorization is implicit. return: (boolean) - ``true`` if this authorization is implicit, ``false`` otherwise *compliance: mandatory -- This method must be implemented.*<|endoftext|>
5050674bb7958b44a9d69de455dc58f5da4b176fa7bb7c9f23b2caba79e406cd
def has_resource(self): 'Tests if this authorization has a ``Resource``.\n\n return: (boolean) - ``true`` if this authorization has a\n ``Resource,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['resourceId'])
Tests if this authorization has a ``Resource``. return: (boolean) - ``true`` if this authorization has a ``Resource,`` ``false`` otherwise *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
has_resource
UOC/dlkit
2
python
def has_resource(self): 'Tests if this authorization has a ``Resource``.\n\n return: (boolean) - ``true`` if this authorization has a\n ``Resource,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['resourceId'])
def has_resource(self): 'Tests if this authorization has a ``Resource``.\n\n return: (boolean) - ``true`` if this authorization has a\n ``Resource,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['resourceId'])<|docstring|>Tests if this authorization has a ``Resource``. return: (boolean) - ``true`` if this authorization has a ``Resource,`` ``false`` otherwise *compliance: mandatory -- This method must be implemented.*<|endoftext|>
7f283793895a9d0e51d15fb1ae8509f57d5b16a4351f72a4a0bd30c28f69ca20
def get_resource_id(self): 'Gets the ``resource _id`` for this authorization.\n\n return: (osid.id.Id) - the ``Resource Id``\n raise: IllegalState - ``has_resource()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['resourceId'])): raise errors.IllegalState('this Authorization has no resource') else: return Id(self._my_map['resourceId'])
Gets the ``resource _id`` for this authorization. return: (osid.id.Id) - the ``Resource Id`` raise: IllegalState - ``has_resource()`` is ``false`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_resource_id
UOC/dlkit
2
python
def get_resource_id(self): 'Gets the ``resource _id`` for this authorization.\n\n return: (osid.id.Id) - the ``Resource Id``\n raise: IllegalState - ``has_resource()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['resourceId'])): raise errors.IllegalState('this Authorization has no resource') else: return Id(self._my_map['resourceId'])
def get_resource_id(self): 'Gets the ``resource _id`` for this authorization.\n\n return: (osid.id.Id) - the ``Resource Id``\n raise: IllegalState - ``has_resource()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['resourceId'])): raise errors.IllegalState('this Authorization has no resource') else: return Id(self._my_map['resourceId'])<|docstring|>Gets the ``resource _id`` for this authorization. return: (osid.id.Id) - the ``Resource Id`` raise: IllegalState - ``has_resource()`` is ``false`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
2de7df5485650bc3486641bf6b904a86ab6e33f201536151ad05ea07b69579dd
def get_resource(self): 'Gets the ``Resource`` for this authorization.\n\n return: (osid.resource.Resource) - the ``Resource``\n raise: IllegalState - ``has_resource()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['resourceId'])): raise errors.IllegalState('this Authorization has no resource') mgr = self._get_provider_manager('RESOURCE') if (not mgr.supports_resource_lookup()): raise errors.OperationFailed('Resource does not support Resource lookup') lookup_session = mgr.get_resource_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_bin_view() osid_object = lookup_session.get_resource(self.get_resource_id()) return osid_object
Gets the ``Resource`` for this authorization. return: (osid.resource.Resource) - the ``Resource`` raise: IllegalState - ``has_resource()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_resource
UOC/dlkit
2
python
def get_resource(self): 'Gets the ``Resource`` for this authorization.\n\n return: (osid.resource.Resource) - the ``Resource``\n raise: IllegalState - ``has_resource()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['resourceId'])): raise errors.IllegalState('this Authorization has no resource') mgr = self._get_provider_manager('RESOURCE') if (not mgr.supports_resource_lookup()): raise errors.OperationFailed('Resource does not support Resource lookup') lookup_session = mgr.get_resource_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_bin_view() osid_object = lookup_session.get_resource(self.get_resource_id()) return osid_object
def get_resource(self): 'Gets the ``Resource`` for this authorization.\n\n return: (osid.resource.Resource) - the ``Resource``\n raise: IllegalState - ``has_resource()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['resourceId'])): raise errors.IllegalState('this Authorization has no resource') mgr = self._get_provider_manager('RESOURCE') if (not mgr.supports_resource_lookup()): raise errors.OperationFailed('Resource does not support Resource lookup') lookup_session = mgr.get_resource_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_bin_view() osid_object = lookup_session.get_resource(self.get_resource_id()) return osid_object<|docstring|>Gets the ``Resource`` for this authorization. return: (osid.resource.Resource) - the ``Resource`` raise: IllegalState - ``has_resource()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
327867f0a024b925ad65b3ac64c97d98e016aae0257b644cf9d88d22644a8f04
def has_trust(self): 'Tests if this authorization has a ``Trust``.\n\n return: (boolean) - ``true`` if this authorization has a\n ``Trust,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['trustId'])
Tests if this authorization has a ``Trust``. return: (boolean) - ``true`` if this authorization has a ``Trust,`` ``false`` otherwise *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
has_trust
UOC/dlkit
2
python
def has_trust(self): 'Tests if this authorization has a ``Trust``.\n\n return: (boolean) - ``true`` if this authorization has a\n ``Trust,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['trustId'])
def has_trust(self): 'Tests if this authorization has a ``Trust``.\n\n return: (boolean) - ``true`` if this authorization has a\n ``Trust,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['trustId'])<|docstring|>Tests if this authorization has a ``Trust``. return: (boolean) - ``true`` if this authorization has a ``Trust,`` ``false`` otherwise *compliance: mandatory -- This method must be implemented.*<|endoftext|>
f671ae792ad18dc5b0dc06e176f377633bf4079c351ab13ba1c58a4656d529ef
def get_trust_id(self): 'Gets the ``Trust`` ``Id`` for this authorization.\n\n return: (osid.id.Id) - the trust ``Id``\n raise: IllegalState - ``has_trust()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['trustId'])): raise errors.IllegalState('this Authorization has no trust') else: return Id(self._my_map['trustId'])
Gets the ``Trust`` ``Id`` for this authorization. return: (osid.id.Id) - the trust ``Id`` raise: IllegalState - ``has_trust()`` is ``false`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_trust_id
UOC/dlkit
2
python
def get_trust_id(self): 'Gets the ``Trust`` ``Id`` for this authorization.\n\n return: (osid.id.Id) - the trust ``Id``\n raise: IllegalState - ``has_trust()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['trustId'])): raise errors.IllegalState('this Authorization has no trust') else: return Id(self._my_map['trustId'])
def get_trust_id(self): 'Gets the ``Trust`` ``Id`` for this authorization.\n\n return: (osid.id.Id) - the trust ``Id``\n raise: IllegalState - ``has_trust()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['trustId'])): raise errors.IllegalState('this Authorization has no trust') else: return Id(self._my_map['trustId'])<|docstring|>Gets the ``Trust`` ``Id`` for this authorization. return: (osid.id.Id) - the trust ``Id`` raise: IllegalState - ``has_trust()`` is ``false`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
edd0f1df3dd431e310f8d5f8f38195c0b186903faab75d121f08c494fb0010c7
def get_trust(self): 'Gets the ``Trust`` for this authorization.\n\n return: (osid.authentication.process.Trust) - the ``Trust``\n raise: IllegalState - ``has_trust()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['trustId'])): raise errors.IllegalState('this Authorization has no trust') mgr = self._get_provider_manager('AUTHENTICATION.PROCESS') if (not mgr.supports_trust_lookup()): raise errors.OperationFailed('Authentication.Process does not support Trust lookup') lookup_session = mgr.get_trust_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_agency_view() osid_object = lookup_session.get_trust(self.get_trust_id()) return osid_object
Gets the ``Trust`` for this authorization. return: (osid.authentication.process.Trust) - the ``Trust`` raise: IllegalState - ``has_trust()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_trust
UOC/dlkit
2
python
def get_trust(self): 'Gets the ``Trust`` for this authorization.\n\n return: (osid.authentication.process.Trust) - the ``Trust``\n raise: IllegalState - ``has_trust()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['trustId'])): raise errors.IllegalState('this Authorization has no trust') mgr = self._get_provider_manager('AUTHENTICATION.PROCESS') if (not mgr.supports_trust_lookup()): raise errors.OperationFailed('Authentication.Process does not support Trust lookup') lookup_session = mgr.get_trust_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_agency_view() osid_object = lookup_session.get_trust(self.get_trust_id()) return osid_object
def get_trust(self): 'Gets the ``Trust`` for this authorization.\n\n return: (osid.authentication.process.Trust) - the ``Trust``\n raise: IllegalState - ``has_trust()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['trustId'])): raise errors.IllegalState('this Authorization has no trust') mgr = self._get_provider_manager('AUTHENTICATION.PROCESS') if (not mgr.supports_trust_lookup()): raise errors.OperationFailed('Authentication.Process does not support Trust lookup') lookup_session = mgr.get_trust_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_agency_view() osid_object = lookup_session.get_trust(self.get_trust_id()) return osid_object<|docstring|>Gets the ``Trust`` for this authorization. return: (osid.authentication.process.Trust) - the ``Trust`` raise: IllegalState - ``has_trust()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
cd932e8fb4291e798a53d17d963920de7434d9cb1de0b9cc22f64ef83882928d
def has_agent(self): 'Tests if this authorization has an ``Agent``.\n\n An implied authorization may have an ``Agent`` in addition to a\n specified ``Resource``.\n\n return: (boolean) - ``true`` if this authorization has an\n ``Agent,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['agentId'])
Tests if this authorization has an ``Agent``. An implied authorization may have an ``Agent`` in addition to a specified ``Resource``. return: (boolean) - ``true`` if this authorization has an ``Agent,`` ``false`` otherwise *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
has_agent
UOC/dlkit
2
python
def has_agent(self): 'Tests if this authorization has an ``Agent``.\n\n An implied authorization may have an ``Agent`` in addition to a\n specified ``Resource``.\n\n return: (boolean) - ``true`` if this authorization has an\n ``Agent,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['agentId'])
def has_agent(self): 'Tests if this authorization has an ``Agent``.\n\n An implied authorization may have an ``Agent`` in addition to a\n specified ``Resource``.\n\n return: (boolean) - ``true`` if this authorization has an\n ``Agent,`` ``false`` otherwise\n *compliance: mandatory -- This method must be implemented.*\n\n ' return bool(self._my_map['agentId'])<|docstring|>Tests if this authorization has an ``Agent``. An implied authorization may have an ``Agent`` in addition to a specified ``Resource``. return: (boolean) - ``true`` if this authorization has an ``Agent,`` ``false`` otherwise *compliance: mandatory -- This method must be implemented.*<|endoftext|>
13e48f1a4f1ec371220504ffc69d74f94c5aa61fa0275bf71ba1902994c9d10f
def get_agent_id(self): 'Gets the ``Agent Id`` for this authorization.\n\n return: (osid.id.Id) - the ``Agent Id``\n raise: IllegalState - ``has_agent()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['agentId'])): raise errors.IllegalState('this Authorization has no agent') else: return Id(self._my_map['agentId'])
Gets the ``Agent Id`` for this authorization. return: (osid.id.Id) - the ``Agent Id`` raise: IllegalState - ``has_agent()`` is ``false`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_agent_id
UOC/dlkit
2
python
def get_agent_id(self): 'Gets the ``Agent Id`` for this authorization.\n\n return: (osid.id.Id) - the ``Agent Id``\n raise: IllegalState - ``has_agent()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['agentId'])): raise errors.IllegalState('this Authorization has no agent') else: return Id(self._my_map['agentId'])
def get_agent_id(self): 'Gets the ``Agent Id`` for this authorization.\n\n return: (osid.id.Id) - the ``Agent Id``\n raise: IllegalState - ``has_agent()`` is ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['agentId'])): raise errors.IllegalState('this Authorization has no agent') else: return Id(self._my_map['agentId'])<|docstring|>Gets the ``Agent Id`` for this authorization. return: (osid.id.Id) - the ``Agent Id`` raise: IllegalState - ``has_agent()`` is ``false`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
57a1d269584b39557cc8991f40fd50b8c4bc6a2bd6654894cd28c9d19f31456b
def get_agent(self): 'Gets the ``Agent`` for this authorization.\n\n return: (osid.authentication.Agent) - the ``Agent``\n raise: IllegalState - ``has_agent()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['agentId'])): raise errors.IllegalState('this Authorization has no agent') mgr = self._get_provider_manager('AUTHENTICATION') if (not mgr.supports_agent_lookup()): raise errors.OperationFailed('Authentication does not support Agent lookup') lookup_session = mgr.get_agent_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_agency_view() osid_object = lookup_session.get_agent(self.get_agent_id()) return osid_object
Gets the ``Agent`` for this authorization. return: (osid.authentication.Agent) - the ``Agent`` raise: IllegalState - ``has_agent()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_agent
UOC/dlkit
2
python
def get_agent(self): 'Gets the ``Agent`` for this authorization.\n\n return: (osid.authentication.Agent) - the ``Agent``\n raise: IllegalState - ``has_agent()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['agentId'])): raise errors.IllegalState('this Authorization has no agent') mgr = self._get_provider_manager('AUTHENTICATION') if (not mgr.supports_agent_lookup()): raise errors.OperationFailed('Authentication does not support Agent lookup') lookup_session = mgr.get_agent_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_agency_view() osid_object = lookup_session.get_agent(self.get_agent_id()) return osid_object
def get_agent(self): 'Gets the ``Agent`` for this authorization.\n\n return: (osid.authentication.Agent) - the ``Agent``\n raise: IllegalState - ``has_agent()`` is ``false``\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['agentId'])): raise errors.IllegalState('this Authorization has no agent') mgr = self._get_provider_manager('AUTHENTICATION') if (not mgr.supports_agent_lookup()): raise errors.OperationFailed('Authentication does not support Agent lookup') lookup_session = mgr.get_agent_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_agency_view() osid_object = lookup_session.get_agent(self.get_agent_id()) return osid_object<|docstring|>Gets the ``Agent`` for this authorization. return: (osid.authentication.Agent) - the ``Agent`` raise: IllegalState - ``has_agent()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
717144611c2595aa51ce65e2e34a4dbe0a12710bed665b2c70ba8377224c3429
def get_function_id(self): 'Gets the ``Function Id`` for this authorization.\n\n return: (osid.id.Id) - the function ``Id``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['functionId'])): raise errors.IllegalState('function empty') return Id(self._my_map['functionId'])
Gets the ``Function Id`` for this authorization. return: (osid.id.Id) - the function ``Id`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_function_id
UOC/dlkit
2
python
def get_function_id(self): 'Gets the ``Function Id`` for this authorization.\n\n return: (osid.id.Id) - the function ``Id``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['functionId'])): raise errors.IllegalState('function empty') return Id(self._my_map['functionId'])
def get_function_id(self): 'Gets the ``Function Id`` for this authorization.\n\n return: (osid.id.Id) - the function ``Id``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['functionId'])): raise errors.IllegalState('function empty') return Id(self._my_map['functionId'])<|docstring|>Gets the ``Function Id`` for this authorization. return: (osid.id.Id) - the function ``Id`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
2ff7fd0ccbc3a6fd28b9fe96e818f0d82afaac7f52fbf56ef52ffd566eea9b64
def get_function(self): 'Gets the ``Function`` for this authorization.\n\n return: (osid.authorization.Function) - the function\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['functionId'])): raise errors.IllegalState('function empty') mgr = self._get_provider_manager('AUTHORIZATION') if (not mgr.supports_function_lookup()): raise errors.OperationFailed('Authorization does not support Function lookup') lookup_session = mgr.get_function_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_vault_view() return lookup_session.get_function(self.get_function_id())
Gets the ``Function`` for this authorization. return: (osid.authorization.Function) - the function raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_function
UOC/dlkit
2
python
def get_function(self): 'Gets the ``Function`` for this authorization.\n\n return: (osid.authorization.Function) - the function\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['functionId'])): raise errors.IllegalState('function empty') mgr = self._get_provider_manager('AUTHORIZATION') if (not mgr.supports_function_lookup()): raise errors.OperationFailed('Authorization does not support Function lookup') lookup_session = mgr.get_function_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_vault_view() return lookup_session.get_function(self.get_function_id())
def get_function(self): 'Gets the ``Function`` for this authorization.\n\n return: (osid.authorization.Function) - the function\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['functionId'])): raise errors.IllegalState('function empty') mgr = self._get_provider_manager('AUTHORIZATION') if (not mgr.supports_function_lookup()): raise errors.OperationFailed('Authorization does not support Function lookup') lookup_session = mgr.get_function_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_vault_view() return lookup_session.get_function(self.get_function_id())<|docstring|>Gets the ``Function`` for this authorization. return: (osid.authorization.Function) - the function raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
60c68b4146a910ba8df8a07014eca6e0ce9766730ea0edae2852d030f67c9205
def get_qualifier_id(self): 'Gets the ``Qualifier Id`` for this authorization.\n\n return: (osid.id.Id) - the qualifier ``Id``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['qualifierId'])): raise errors.IllegalState('qualifier empty') return Id(self._my_map['qualifierId'])
Gets the ``Qualifier Id`` for this authorization. return: (osid.id.Id) - the qualifier ``Id`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_qualifier_id
UOC/dlkit
2
python
def get_qualifier_id(self): 'Gets the ``Qualifier Id`` for this authorization.\n\n return: (osid.id.Id) - the qualifier ``Id``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['qualifierId'])): raise errors.IllegalState('qualifier empty') return Id(self._my_map['qualifierId'])
def get_qualifier_id(self): 'Gets the ``Qualifier Id`` for this authorization.\n\n return: (osid.id.Id) - the qualifier ``Id``\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['qualifierId'])): raise errors.IllegalState('qualifier empty') return Id(self._my_map['qualifierId'])<|docstring|>Gets the ``Qualifier Id`` for this authorization. return: (osid.id.Id) - the qualifier ``Id`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
1a6ebf34d27015e54acf3fa248537ac8313c544633fd16725a0ba842eccdfb3e
def get_qualifier(self): 'Gets the qualifier for this authorization.\n\n return: (osid.authorization.Qualifier) - the qualifier\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['qualifierId'])): raise errors.IllegalState('qualifier empty') mgr = self._get_provider_manager('AUTHORIZATION') if (not mgr.supports_qualifier_lookup()): raise errors.OperationFailed('Authorization does not support Qualifier lookup') lookup_session = mgr.get_qualifier_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_vault_view() return lookup_session.get_qualifier(self.get_qualifier_id())
Gets the qualifier for this authorization. return: (osid.authorization.Qualifier) - the qualifier raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_qualifier
UOC/dlkit
2
python
def get_qualifier(self): 'Gets the qualifier for this authorization.\n\n return: (osid.authorization.Qualifier) - the qualifier\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['qualifierId'])): raise errors.IllegalState('qualifier empty') mgr = self._get_provider_manager('AUTHORIZATION') if (not mgr.supports_qualifier_lookup()): raise errors.OperationFailed('Authorization does not support Qualifier lookup') lookup_session = mgr.get_qualifier_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_vault_view() return lookup_session.get_qualifier(self.get_qualifier_id())
def get_qualifier(self): 'Gets the qualifier for this authorization.\n\n return: (osid.authorization.Qualifier) - the qualifier\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (not bool(self._my_map['qualifierId'])): raise errors.IllegalState('qualifier empty') mgr = self._get_provider_manager('AUTHORIZATION') if (not mgr.supports_qualifier_lookup()): raise errors.OperationFailed('Authorization does not support Qualifier lookup') lookup_session = mgr.get_qualifier_lookup_session(proxy=getattr(self, '_proxy', None)) lookup_session.use_federated_vault_view() return lookup_session.get_qualifier(self.get_qualifier_id())<|docstring|>Gets the qualifier for this authorization. return: (osid.authorization.Qualifier) - the qualifier raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
d31b0b80ce49d619498846b7e234e736e11f683b95dd043208f448a6f47ccd89
@utilities.arguments_not_none def get_authorization_record(self, authorization_record_type): 'Gets the authorization record corresponding to the given ``Authorization`` record ``Type``.\n\n This method is used to retrieve an object implementing the\n requested record. The ``authorization_record_type`` may be the\n ``Type`` returned in ``get_record_types()`` or any of its\n parents in a ``Type`` hierarchy where\n ``has_record_type(authorization_record_type)`` is ``true`` .\n\n arg: authorization_record_type (osid.type.Type): the type of\n the record to retrieve\n return: (osid.authorization.records.AuthorizationRecord) - the\n authorization record\n raise: NullArgument - ``authorization_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported -\n ``has_record_type(authorization_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_record(authorization_record_type)
Gets the authorization record corresponding to the given ``Authorization`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``authorization_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(authorization_record_type)`` is ``true`` . arg: authorization_record_type (osid.type.Type): the type of the record to retrieve return: (osid.authorization.records.AuthorizationRecord) - the authorization record raise: NullArgument - ``authorization_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(authorization_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_authorization_record
UOC/dlkit
2
python
@utilities.arguments_not_none def get_authorization_record(self, authorization_record_type): 'Gets the authorization record corresponding to the given ``Authorization`` record ``Type``.\n\n This method is used to retrieve an object implementing the\n requested record. The ``authorization_record_type`` may be the\n ``Type`` returned in ``get_record_types()`` or any of its\n parents in a ``Type`` hierarchy where\n ``has_record_type(authorization_record_type)`` is ``true`` .\n\n arg: authorization_record_type (osid.type.Type): the type of\n the record to retrieve\n return: (osid.authorization.records.AuthorizationRecord) - the\n authorization record\n raise: NullArgument - ``authorization_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported -\n ``has_record_type(authorization_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_record(authorization_record_type)
@utilities.arguments_not_none def get_authorization_record(self, authorization_record_type): 'Gets the authorization record corresponding to the given ``Authorization`` record ``Type``.\n\n This method is used to retrieve an object implementing the\n requested record. The ``authorization_record_type`` may be the\n ``Type`` returned in ``get_record_types()`` or any of its\n parents in a ``Type`` hierarchy where\n ``has_record_type(authorization_record_type)`` is ``true`` .\n\n arg: authorization_record_type (osid.type.Type): the type of\n the record to retrieve\n return: (osid.authorization.records.AuthorizationRecord) - the\n authorization record\n raise: NullArgument - ``authorization_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported -\n ``has_record_type(authorization_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_record(authorization_record_type)<|docstring|>Gets the authorization record corresponding to the given ``Authorization`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``authorization_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(authorization_record_type)`` is ``true`` . arg: authorization_record_type (osid.type.Type): the type of the record to retrieve return: (osid.authorization.records.AuthorizationRecord) - the authorization record raise: NullArgument - ``authorization_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(authorization_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
bfa9bde2293450cbb8d03505b445edf6f623528ab480bddf4334a23f5ec932cb
def _init_metadata(self, **kwargs): 'Initialize form metadata' osid_objects.OsidRelationshipForm._init_metadata(self, **kwargs)
Initialize form metadata
dlkit/json_/authorization/objects.py
_init_metadata
UOC/dlkit
2
python
def _init_metadata(self, **kwargs): osid_objects.OsidRelationshipForm._init_metadata(self, **kwargs)
def _init_metadata(self, **kwargs): osid_objects.OsidRelationshipForm._init_metadata(self, **kwargs)<|docstring|>Initialize form metadata<|endoftext|>
8a0be38c576bebfdc7e067a6a7b51f74d1a88d3a557dc5b7255385d5c404b605
def _init_map(self, record_types=None, **kwargs): 'Initialize form map' osid_objects.OsidRelationshipForm._init_map(self, record_types=record_types) self._my_map['assignedVaultIds'] = [str(kwargs['vault_id'])] self._my_map['functionId'] = str(kwargs['function_id']) self._my_map['qualifierId'] = str(kwargs['qualifier_id']) self._my_map['agentId'] = None self._my_map['resourceId'] = None self._my_map['trustId'] = None self._my_map['implicit'] = None if ('agent_id' in kwargs): self._my_map['agentId'] = str(kwargs['agent_id']) if ('resource_id' in kwargs): self._my_map['resourceId'] = str(kwargs['resource_id'])
Initialize form map
dlkit/json_/authorization/objects.py
_init_map
UOC/dlkit
2
python
def _init_map(self, record_types=None, **kwargs): osid_objects.OsidRelationshipForm._init_map(self, record_types=record_types) self._my_map['assignedVaultIds'] = [str(kwargs['vault_id'])] self._my_map['functionId'] = str(kwargs['function_id']) self._my_map['qualifierId'] = str(kwargs['qualifier_id']) self._my_map['agentId'] = None self._my_map['resourceId'] = None self._my_map['trustId'] = None self._my_map['implicit'] = None if ('agent_id' in kwargs): self._my_map['agentId'] = str(kwargs['agent_id']) if ('resource_id' in kwargs): self._my_map['resourceId'] = str(kwargs['resource_id'])
def _init_map(self, record_types=None, **kwargs): osid_objects.OsidRelationshipForm._init_map(self, record_types=record_types) self._my_map['assignedVaultIds'] = [str(kwargs['vault_id'])] self._my_map['functionId'] = str(kwargs['function_id']) self._my_map['qualifierId'] = str(kwargs['qualifier_id']) self._my_map['agentId'] = None self._my_map['resourceId'] = None self._my_map['trustId'] = None self._my_map['implicit'] = None if ('agent_id' in kwargs): self._my_map['agentId'] = str(kwargs['agent_id']) if ('resource_id' in kwargs): self._my_map['resourceId'] = str(kwargs['resource_id'])<|docstring|>Initialize form map<|endoftext|>
61c3436d94eb3fd8d96c44a77928b55c85e4cbd411af65fa63a5d776eb988c1f
@utilities.arguments_not_none def get_authorization_form_record(self, authorization_record_type): 'Gets the ``AuthorizationFormRecord`` corresponding to the given authorization record ``Type``.\n\n arg: authorization_record_type (osid.type.Type): the\n authorization record type\n return: (osid.authorization.records.AuthorizationFormRecord) -\n the authorization form record\n raise: NullArgument - ``authorization_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported -\n ``has_record_type(authorization_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_record(authorization_record_type)
Gets the ``AuthorizationFormRecord`` corresponding to the given authorization record ``Type``. arg: authorization_record_type (osid.type.Type): the authorization record type return: (osid.authorization.records.AuthorizationFormRecord) - the authorization form record raise: NullArgument - ``authorization_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(authorization_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_authorization_form_record
UOC/dlkit
2
python
@utilities.arguments_not_none def get_authorization_form_record(self, authorization_record_type): 'Gets the ``AuthorizationFormRecord`` corresponding to the given authorization record ``Type``.\n\n arg: authorization_record_type (osid.type.Type): the\n authorization record type\n return: (osid.authorization.records.AuthorizationFormRecord) -\n the authorization form record\n raise: NullArgument - ``authorization_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported -\n ``has_record_type(authorization_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_record(authorization_record_type)
@utilities.arguments_not_none def get_authorization_form_record(self, authorization_record_type): 'Gets the ``AuthorizationFormRecord`` corresponding to the given authorization record ``Type``.\n\n arg: authorization_record_type (osid.type.Type): the\n authorization record type\n return: (osid.authorization.records.AuthorizationFormRecord) -\n the authorization form record\n raise: NullArgument - ``authorization_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported -\n ``has_record_type(authorization_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_record(authorization_record_type)<|docstring|>Gets the ``AuthorizationFormRecord`` corresponding to the given authorization record ``Type``. arg: authorization_record_type (osid.type.Type): the authorization record type return: (osid.authorization.records.AuthorizationFormRecord) - the authorization form record raise: NullArgument - ``authorization_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(authorization_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
a75882f520bcf4922b89b0b034c1343a92c476c4f680c425e312dc1611ef9f6a
def get_next_authorization(self): 'Gets the next ``Authorization`` in this list.\n\n return: (osid.authorization.Authorization) - the next\n ``Authorization`` in this list. The ``has_next()``\n method should be used to test that a next\n ``Authorization`` is available before calling this\n method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)
Gets the next ``Authorization`` in this list. return: (osid.authorization.Authorization) - the next ``Authorization`` in this list. The ``has_next()`` method should be used to test that a next ``Authorization`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_next_authorization
UOC/dlkit
2
python
def get_next_authorization(self): 'Gets the next ``Authorization`` in this list.\n\n return: (osid.authorization.Authorization) - the next\n ``Authorization`` in this list. The ``has_next()``\n method should be used to test that a next\n ``Authorization`` is available before calling this\n method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)
def get_next_authorization(self): 'Gets the next ``Authorization`` in this list.\n\n return: (osid.authorization.Authorization) - the next\n ``Authorization`` in this list. The ``has_next()``\n method should be used to test that a next\n ``Authorization`` is available before calling this\n method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)<|docstring|>Gets the next ``Authorization`` in this list. return: (osid.authorization.Authorization) - the next ``Authorization`` in this list. The ``has_next()`` method should be used to test that a next ``Authorization`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
67fa84f6445a95bb85e6fe59f933e12f032ec03b31332063e22cc99b05a6327d
@utilities.arguments_not_none def get_next_authorizations(self, n): 'Gets the next set of ``Authorization`` elements in this list which must be less than or equal to the number returned from ``available()``.\n\n arg: n (cardinal): the number of ``Authorization`` elements\n requested which should be less than or equal to\n ``available()``\n return: (osid.authorization.Authorization) - an array of\n ``Authorization`` elements.The length of the array is\n less than or equal to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(AuthorizationList, number=n)
Gets the next set of ``Authorization`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``Authorization`` elements requested which should be less than or equal to ``available()`` return: (osid.authorization.Authorization) - an array of ``Authorization`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_next_authorizations
UOC/dlkit
2
python
@utilities.arguments_not_none def get_next_authorizations(self, n): 'Gets the next set of ``Authorization`` elements in this list which must be less than or equal to the number returned from ``available()``.\n\n arg: n (cardinal): the number of ``Authorization`` elements\n requested which should be less than or equal to\n ``available()``\n return: (osid.authorization.Authorization) - an array of\n ``Authorization`` elements.The length of the array is\n less than or equal to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(AuthorizationList, number=n)
@utilities.arguments_not_none def get_next_authorizations(self, n): 'Gets the next set of ``Authorization`` elements in this list which must be less than or equal to the number returned from ``available()``.\n\n arg: n (cardinal): the number of ``Authorization`` elements\n requested which should be less than or equal to\n ``available()``\n return: (osid.authorization.Authorization) - an array of\n ``Authorization`` elements.The length of the array is\n less than or equal to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(AuthorizationList, number=n)<|docstring|>Gets the next set of ``Authorization`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``Authorization`` elements requested which should be less than or equal to ``available()`` return: (osid.authorization.Authorization) - an array of ``Authorization`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
9a706c4c5bf2e9b9039c41c9536a225e742c0aed57d1bb625df4465084bbe8bb
@utilities.arguments_not_none def get_vault_record(self, vault_record_type): 'Gets the vault record corresponding to the given ``Vault`` record ``Type``.\n\n This method is used to retrieve an object implementing the\n requested record. The ``vault_record_type`` may be the ``Type``\n returned in ``get_record_types()`` or any of its parents in a\n ``Type`` hierarchy where ``has_record_type(vault_record_type)``\n is ``true`` .\n\n arg: vault_record_type (osid.type.Type): a vault record type\n return: (osid.authorization.records.VaultRecord) - the vault\n record\n raise: NullArgument - ``vault_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported - ``has_record_type(vault_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' raise errors.Unimplemented()
Gets the vault record corresponding to the given ``Vault`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``vault_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(vault_record_type)`` is ``true`` . arg: vault_record_type (osid.type.Type): a vault record type return: (osid.authorization.records.VaultRecord) - the vault record raise: NullArgument - ``vault_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(vault_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_vault_record
UOC/dlkit
2
python
@utilities.arguments_not_none def get_vault_record(self, vault_record_type): 'Gets the vault record corresponding to the given ``Vault`` record ``Type``.\n\n This method is used to retrieve an object implementing the\n requested record. The ``vault_record_type`` may be the ``Type``\n returned in ``get_record_types()`` or any of its parents in a\n ``Type`` hierarchy where ``has_record_type(vault_record_type)``\n is ``true`` .\n\n arg: vault_record_type (osid.type.Type): a vault record type\n return: (osid.authorization.records.VaultRecord) - the vault\n record\n raise: NullArgument - ``vault_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported - ``has_record_type(vault_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' raise errors.Unimplemented()
@utilities.arguments_not_none def get_vault_record(self, vault_record_type): 'Gets the vault record corresponding to the given ``Vault`` record ``Type``.\n\n This method is used to retrieve an object implementing the\n requested record. The ``vault_record_type`` may be the ``Type``\n returned in ``get_record_types()`` or any of its parents in a\n ``Type`` hierarchy where ``has_record_type(vault_record_type)``\n is ``true`` .\n\n arg: vault_record_type (osid.type.Type): a vault record type\n return: (osid.authorization.records.VaultRecord) - the vault\n record\n raise: NullArgument - ``vault_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported - ``has_record_type(vault_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' raise errors.Unimplemented()<|docstring|>Gets the vault record corresponding to the given ``Vault`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``vault_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(vault_record_type)`` is ``true`` . arg: vault_record_type (osid.type.Type): a vault record type return: (osid.authorization.records.VaultRecord) - the vault record raise: NullArgument - ``vault_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(vault_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
021fa8a44779c47b252746bf7127f8c00086010057a1f325774e1871e9fd609b
def _init_metadata(self, **kwargs): 'Initialize form metadata' osid_objects.OsidCatalogForm._init_metadata(self, **kwargs)
Initialize form metadata
dlkit/json_/authorization/objects.py
_init_metadata
UOC/dlkit
2
python
def _init_metadata(self, **kwargs): osid_objects.OsidCatalogForm._init_metadata(self, **kwargs)
def _init_metadata(self, **kwargs): osid_objects.OsidCatalogForm._init_metadata(self, **kwargs)<|docstring|>Initialize form metadata<|endoftext|>
592aec1148745a6b42566da73c4b128330291419f748a854f76f5935db8ea50c
def _init_map(self, record_types=None, **kwargs): 'Initialize form map' osid_objects.OsidCatalogForm._init_map(self, record_types, **kwargs)
Initialize form map
dlkit/json_/authorization/objects.py
_init_map
UOC/dlkit
2
python
def _init_map(self, record_types=None, **kwargs): osid_objects.OsidCatalogForm._init_map(self, record_types, **kwargs)
def _init_map(self, record_types=None, **kwargs): osid_objects.OsidCatalogForm._init_map(self, record_types, **kwargs)<|docstring|>Initialize form map<|endoftext|>
6dc1daa8a07d67840c64ea8fe962f9f44bfa67313aa34cbb4a169a264e506f0e
@utilities.arguments_not_none def get_vault_form_record(self, vault_record_type): 'Gets the ``VaultFormRecord`` corresponding to the given vault record ``Type``.\n\n arg: vault_record_type (osid.type.Type): a vault record type\n return: (osid.authorization.records.VaultFormRecord) - the vault\n form record\n raise: NullArgument - ``vault_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported - ``has_record_type(vault_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' raise errors.Unimplemented()
Gets the ``VaultFormRecord`` corresponding to the given vault record ``Type``. arg: vault_record_type (osid.type.Type): a vault record type return: (osid.authorization.records.VaultFormRecord) - the vault form record raise: NullArgument - ``vault_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(vault_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_vault_form_record
UOC/dlkit
2
python
@utilities.arguments_not_none def get_vault_form_record(self, vault_record_type): 'Gets the ``VaultFormRecord`` corresponding to the given vault record ``Type``.\n\n arg: vault_record_type (osid.type.Type): a vault record type\n return: (osid.authorization.records.VaultFormRecord) - the vault\n form record\n raise: NullArgument - ``vault_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported - ``has_record_type(vault_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' raise errors.Unimplemented()
@utilities.arguments_not_none def get_vault_form_record(self, vault_record_type): 'Gets the ``VaultFormRecord`` corresponding to the given vault record ``Type``.\n\n arg: vault_record_type (osid.type.Type): a vault record type\n return: (osid.authorization.records.VaultFormRecord) - the vault\n form record\n raise: NullArgument - ``vault_record_type`` is ``null``\n raise: OperationFailed - unable to complete request\n raise: Unsupported - ``has_record_type(vault_record_type)`` is\n ``false``\n *compliance: mandatory -- This method must be implemented.*\n\n ' raise errors.Unimplemented()<|docstring|>Gets the ``VaultFormRecord`` corresponding to the given vault record ``Type``. arg: vault_record_type (osid.type.Type): a vault record type return: (osid.authorization.records.VaultFormRecord) - the vault form record raise: NullArgument - ``vault_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(vault_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.*<|endoftext|>
1bf78fa54f673fadd2a6babdcc6ee9af9e0af1f2766a7d13517b691da6d58318
def get_next_vault(self): 'Gets the next ``Vault`` in this list.\n\n return: (osid.authorization.Vault) - the next ``Vault`` in this\n list. The ``has_next()`` method should be used to test\n that a next ``Vault`` is available before calling this\n method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)
Gets the next ``Vault`` in this list. return: (osid.authorization.Vault) - the next ``Vault`` in this list. The ``has_next()`` method should be used to test that a next ``Vault`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_next_vault
UOC/dlkit
2
python
def get_next_vault(self): 'Gets the next ``Vault`` in this list.\n\n return: (osid.authorization.Vault) - the next ``Vault`` in this\n list. The ``has_next()`` method should be used to test\n that a next ``Vault`` is available before calling this\n method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)
def get_next_vault(self): 'Gets the next ``Vault`` in this list.\n\n return: (osid.authorization.Vault) - the next ``Vault`` in this\n list. The ``has_next()`` method should be used to test\n that a next ``Vault`` is available before calling this\n method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)<|docstring|>Gets the next ``Vault`` in this list. return: (osid.authorization.Vault) - the next ``Vault`` in this list. The ``has_next()`` method should be used to test that a next ``Vault`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
c85b7a01834f6d86ef97e252c83bb1507b7626eeb2b810b8c60c28cacadb4d0c
@utilities.arguments_not_none def get_next_vaults(self, n): 'Gets the next set of ``Vault`` elements in this list which must be less than or equal to the return from ``available()``.\n\n arg: n (cardinal): the number of ``Vault`` elements requested\n which must be less than or equal to ``available()``\n return: (osid.authorization.Vault) - an array of ``Vault``\n elements.The length of the array is less than or equal\n to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(VaultList, number=n)
Gets the next set of ``Vault`` elements in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Vault`` elements requested which must be less than or equal to ``available()`` return: (osid.authorization.Vault) - an array of ``Vault`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_next_vaults
UOC/dlkit
2
python
@utilities.arguments_not_none def get_next_vaults(self, n): 'Gets the next set of ``Vault`` elements in this list which must be less than or equal to the return from ``available()``.\n\n arg: n (cardinal): the number of ``Vault`` elements requested\n which must be less than or equal to ``available()``\n return: (osid.authorization.Vault) - an array of ``Vault``\n elements.The length of the array is less than or equal\n to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(VaultList, number=n)
@utilities.arguments_not_none def get_next_vaults(self, n): 'Gets the next set of ``Vault`` elements in this list which must be less than or equal to the return from ``available()``.\n\n arg: n (cardinal): the number of ``Vault`` elements requested\n which must be less than or equal to ``available()``\n return: (osid.authorization.Vault) - an array of ``Vault``\n elements.The length of the array is less than or equal\n to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(VaultList, number=n)<|docstring|>Gets the next set of ``Vault`` elements in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Vault`` elements requested which must be less than or equal to ``available()`` return: (osid.authorization.Vault) - an array of ``Vault`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
bf105306c5100b4fc2c6280dd17082d12800ccc3255294c6c4de89cc886fcae4
def get_vault(self): 'Gets the ``Vault`` at this node.\n\n return: (osid.authorization.Vault) - the vault represented by\n this node\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (self._lookup_session is None): mgr = get_provider_manager('AUTHORIZATION', runtime=self._runtime, proxy=self._proxy) self._lookup_session = mgr.get_vault_lookup_session(proxy=getattr(self, '_proxy', None)) return self._lookup_session.get_vault(Id(self._my_map['id']))
Gets the ``Vault`` at this node. return: (osid.authorization.Vault) - the vault represented by this node *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_vault
UOC/dlkit
2
python
def get_vault(self): 'Gets the ``Vault`` at this node.\n\n return: (osid.authorization.Vault) - the vault represented by\n this node\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (self._lookup_session is None): mgr = get_provider_manager('AUTHORIZATION', runtime=self._runtime, proxy=self._proxy) self._lookup_session = mgr.get_vault_lookup_session(proxy=getattr(self, '_proxy', None)) return self._lookup_session.get_vault(Id(self._my_map['id']))
def get_vault(self): 'Gets the ``Vault`` at this node.\n\n return: (osid.authorization.Vault) - the vault represented by\n this node\n *compliance: mandatory -- This method must be implemented.*\n\n ' if (self._lookup_session is None): mgr = get_provider_manager('AUTHORIZATION', runtime=self._runtime, proxy=self._proxy) self._lookup_session = mgr.get_vault_lookup_session(proxy=getattr(self, '_proxy', None)) return self._lookup_session.get_vault(Id(self._my_map['id']))<|docstring|>Gets the ``Vault`` at this node. return: (osid.authorization.Vault) - the vault represented by this node *compliance: mandatory -- This method must be implemented.*<|endoftext|>
3b7eea09fe9ef33b6a590399b108270add04bf9e6b5158924c0e95feab0fb1f7
def get_parent_vault_nodes(self): 'Gets the parents of this vault.\n\n return: (osid.authorization.VaultNodeList) - the parents of this\n vault\n *compliance: mandatory -- This method must be implemented.*\n\n ' parent_vault_nodes = [] for node in self._my_map['parentNodes']: parent_vault_nodes.append(VaultNode(node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return VaultNodeList(parent_vault_nodes)
Gets the parents of this vault. return: (osid.authorization.VaultNodeList) - the parents of this vault *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_parent_vault_nodes
UOC/dlkit
2
python
def get_parent_vault_nodes(self): 'Gets the parents of this vault.\n\n return: (osid.authorization.VaultNodeList) - the parents of this\n vault\n *compliance: mandatory -- This method must be implemented.*\n\n ' parent_vault_nodes = [] for node in self._my_map['parentNodes']: parent_vault_nodes.append(VaultNode(node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return VaultNodeList(parent_vault_nodes)
def get_parent_vault_nodes(self): 'Gets the parents of this vault.\n\n return: (osid.authorization.VaultNodeList) - the parents of this\n vault\n *compliance: mandatory -- This method must be implemented.*\n\n ' parent_vault_nodes = [] for node in self._my_map['parentNodes']: parent_vault_nodes.append(VaultNode(node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return VaultNodeList(parent_vault_nodes)<|docstring|>Gets the parents of this vault. return: (osid.authorization.VaultNodeList) - the parents of this vault *compliance: mandatory -- This method must be implemented.*<|endoftext|>
9322d3bd4b77dfb1890b8a5537a414a45c9f1d67cd1bfc6691751fec49c7563b
def get_child_vault_nodes(self): 'Gets the children of this vault.\n\n return: (osid.authorization.VaultNodeList) - the children of\n this vault\n *compliance: mandatory -- This method must be implemented.*\n\n ' parent_vault_nodes = [] for node in self._my_map['childNodes']: parent_vault_nodes.append(VaultNode(node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return VaultNodeList(parent_vault_nodes)
Gets the children of this vault. return: (osid.authorization.VaultNodeList) - the children of this vault *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_child_vault_nodes
UOC/dlkit
2
python
def get_child_vault_nodes(self): 'Gets the children of this vault.\n\n return: (osid.authorization.VaultNodeList) - the children of\n this vault\n *compliance: mandatory -- This method must be implemented.*\n\n ' parent_vault_nodes = [] for node in self._my_map['childNodes']: parent_vault_nodes.append(VaultNode(node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return VaultNodeList(parent_vault_nodes)
def get_child_vault_nodes(self): 'Gets the children of this vault.\n\n return: (osid.authorization.VaultNodeList) - the children of\n this vault\n *compliance: mandatory -- This method must be implemented.*\n\n ' parent_vault_nodes = [] for node in self._my_map['childNodes']: parent_vault_nodes.append(VaultNode(node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return VaultNodeList(parent_vault_nodes)<|docstring|>Gets the children of this vault. return: (osid.authorization.VaultNodeList) - the children of this vault *compliance: mandatory -- This method must be implemented.*<|endoftext|>
4814689d0efe4033b42626777ac8ffcadd9d051e8b83d2e00056c72e4c016d2b
def get_next_vault_node(self): 'Gets the next ``VaultNode`` in this list.\n\n return: (osid.authorization.VaultNode) - the next ``VaultNode``\n in this list. The ``has_next()`` method should be used\n to test that a next ``VaultNode`` is available before\n calling this method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)
Gets the next ``VaultNode`` in this list. return: (osid.authorization.VaultNode) - the next ``VaultNode`` in this list. The ``has_next()`` method should be used to test that a next ``VaultNode`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_next_vault_node
UOC/dlkit
2
python
def get_next_vault_node(self): 'Gets the next ``VaultNode`` in this list.\n\n return: (osid.authorization.VaultNode) - the next ``VaultNode``\n in this list. The ``has_next()`` method should be used\n to test that a next ``VaultNode`` is available before\n calling this method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)
def get_next_vault_node(self): 'Gets the next ``VaultNode`` in this list.\n\n return: (osid.authorization.VaultNode) - the next ``VaultNode``\n in this list. The ``has_next()`` method should be used\n to test that a next ``VaultNode`` is available before\n calling this method.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return next(self)<|docstring|>Gets the next ``VaultNode`` in this list. return: (osid.authorization.VaultNode) - the next ``VaultNode`` in this list. The ``has_next()`` method should be used to test that a next ``VaultNode`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
91f18adc4a2769e87a264ce04a1b53b76478476bd65aff6f3f483705f58b600b
@utilities.arguments_not_none def get_next_vault_nodes(self, n): 'Gets the next set of ``VaultNode`` elements in this list which must be less than or equal to the return from ``available()``.\n\n arg: n (cardinal): the number of ``VaultNode`` elements\n requested which must be less than or equal to\n ``available()``\n return: (osid.authorization.VaultNode) - an array of\n ``VaultNode`` elements.The length of the array is less\n than or equal to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(VaultNodeList, number=n)
Gets the next set of ``VaultNode`` elements in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``VaultNode`` elements requested which must be less than or equal to ``available()`` return: (osid.authorization.VaultNode) - an array of ``VaultNode`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
dlkit/json_/authorization/objects.py
get_next_vault_nodes
UOC/dlkit
2
python
@utilities.arguments_not_none def get_next_vault_nodes(self, n): 'Gets the next set of ``VaultNode`` elements in this list which must be less than or equal to the return from ``available()``.\n\n arg: n (cardinal): the number of ``VaultNode`` elements\n requested which must be less than or equal to\n ``available()``\n return: (osid.authorization.VaultNode) - an array of\n ``VaultNode`` elements.The length of the array is less\n than or equal to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(VaultNodeList, number=n)
@utilities.arguments_not_none def get_next_vault_nodes(self, n): 'Gets the next set of ``VaultNode`` elements in this list which must be less than or equal to the return from ``available()``.\n\n arg: n (cardinal): the number of ``VaultNode`` elements\n requested which must be less than or equal to\n ``available()``\n return: (osid.authorization.VaultNode) - an array of\n ``VaultNode`` elements.The length of the array is less\n than or equal to the number specified.\n raise: IllegalState - no more elements available in this list\n raise: OperationFailed - unable to complete request\n *compliance: mandatory -- This method must be implemented.*\n\n ' return self._get_next_n(VaultNodeList, number=n)<|docstring|>Gets the next set of ``VaultNode`` elements in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``VaultNode`` elements requested which must be less than or equal to ``available()`` return: (osid.authorization.VaultNode) - an array of ``VaultNode`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*<|endoftext|>
0a82bb76ee1488586bf1b1734440fb273a2ffe7e7fc904e1d63eda37cfea489d
def transition(self): '\n In transition, the agent simply plays and record\n [current_state, action, reward, next_state, done]\n in the replay_buffer (or memory pool)\n\n Updating the weights of the neural network happens\n every single time the replay buffer size is reached.\n\n done: boolean, whether the game has end or not.\n ' for each_ep in range(self.episodes): current_state = self.envs.reset() print('Episode: {} Reward: {} Max_Reward: {}'.format(each_ep, self.check_model_improved, self.best_max)) print(('-' * 64)) self.check_model_improved = 0 for step in range(self.steps): (action_prob, _) = self.actor_network.predict(np.array(current_state).reshape((1, self.input_dim[0], self.input_dim[1]))) action_value = np.dot(np.array(action_prob), self.atoms) action = policies.epsilon_greedy(action_values=action_value[0], episode=each_ep, stop_explore=self.config.stop_explore, total_actions=self.config.action_dim) (next_state, reward, done, _) = self.envs.step(action=action) self.replay_buffer.append([current_state.reshape(self.input_dim).tolist(), action, next_state.reshape(self.input_dim).tolist(), reward, done]) if (len(self.replay_buffer) == self.replay_buffer_size): self.train_by_replay() self.replay_buffer.clear() if done: self.total_steps += 1 break else: current_state = next_state self.total_steps += 1 self.check_model_improved += reward if (self.check_model_improved > self.best_max): self.best_max = self.check_model_improved self.target_network.set_weights(self.actor_network.get_weights())
In transition, the agent simply plays and record [current_state, action, reward, next_state, done] in the replay_buffer (or memory pool) Updating the weights of the neural network happens every single time the replay buffer size is reached. done: boolean, whether the game has end or not.
src/agent/CategoricalDQN.py
transition
hsjharvey/DeepRL
3
python
def transition(self): '\n In transition, the agent simply plays and record\n [current_state, action, reward, next_state, done]\n in the replay_buffer (or memory pool)\n\n Updating the weights of the neural network happens\n every single time the replay buffer size is reached.\n\n done: boolean, whether the game has end or not.\n ' for each_ep in range(self.episodes): current_state = self.envs.reset() print('Episode: {} Reward: {} Max_Reward: {}'.format(each_ep, self.check_model_improved, self.best_max)) print(('-' * 64)) self.check_model_improved = 0 for step in range(self.steps): (action_prob, _) = self.actor_network.predict(np.array(current_state).reshape((1, self.input_dim[0], self.input_dim[1]))) action_value = np.dot(np.array(action_prob), self.atoms) action = policies.epsilon_greedy(action_values=action_value[0], episode=each_ep, stop_explore=self.config.stop_explore, total_actions=self.config.action_dim) (next_state, reward, done, _) = self.envs.step(action=action) self.replay_buffer.append([current_state.reshape(self.input_dim).tolist(), action, next_state.reshape(self.input_dim).tolist(), reward, done]) if (len(self.replay_buffer) == self.replay_buffer_size): self.train_by_replay() self.replay_buffer.clear() if done: self.total_steps += 1 break else: current_state = next_state self.total_steps += 1 self.check_model_improved += reward if (self.check_model_improved > self.best_max): self.best_max = self.check_model_improved self.target_network.set_weights(self.actor_network.get_weights())
def transition(self): '\n In transition, the agent simply plays and record\n [current_state, action, reward, next_state, done]\n in the replay_buffer (or memory pool)\n\n Updating the weights of the neural network happens\n every single time the replay buffer size is reached.\n\n done: boolean, whether the game has end or not.\n ' for each_ep in range(self.episodes): current_state = self.envs.reset() print('Episode: {} Reward: {} Max_Reward: {}'.format(each_ep, self.check_model_improved, self.best_max)) print(('-' * 64)) self.check_model_improved = 0 for step in range(self.steps): (action_prob, _) = self.actor_network.predict(np.array(current_state).reshape((1, self.input_dim[0], self.input_dim[1]))) action_value = np.dot(np.array(action_prob), self.atoms) action = policies.epsilon_greedy(action_values=action_value[0], episode=each_ep, stop_explore=self.config.stop_explore, total_actions=self.config.action_dim) (next_state, reward, done, _) = self.envs.step(action=action) self.replay_buffer.append([current_state.reshape(self.input_dim).tolist(), action, next_state.reshape(self.input_dim).tolist(), reward, done]) if (len(self.replay_buffer) == self.replay_buffer_size): self.train_by_replay() self.replay_buffer.clear() if done: self.total_steps += 1 break else: current_state = next_state self.total_steps += 1 self.check_model_improved += reward if (self.check_model_improved > self.best_max): self.best_max = self.check_model_improved self.target_network.set_weights(self.actor_network.get_weights())<|docstring|>In transition, the agent simply plays and record [current_state, action, reward, next_state, done] in the replay_buffer (or memory pool) Updating the weights of the neural network happens every single time the replay buffer size is reached. done: boolean, whether the game has end or not.<|endoftext|>
4718fb8259b302d82f67d5666e0c3137d87ccb6ddd159c3a6e09ad4250590a80
def train_by_replay(self): '\n TD update by replaying the history.\n Implementation of algorithm 1 in the paper.\n ' (current_states, actions, next_states, rewards, terminals) = replay_fn.uniform_random_replay(self.replay_buffer, self.batch_size) (prob_next, _) = self.target_network.predict(next_states) action_value_next = np.dot(np.array(prob_next), self.atoms) action_next = np.argmax(action_value_next, axis=1) prob_next = prob_next[(np.arange(self.batch_size), action_next, :)] rewards = np.tile(rewards.reshape(self.batch_size, 1), (1, self.n_atoms)) discount_rate = (self.config.discount_rate * (1 - terminals)) atoms_next = (rewards + np.dot(discount_rate.reshape(self.batch_size, 1), self.atoms.reshape(1, self.n_atoms))) atoms_next = np.clip(atoms_next, self.vmin, self.vmax) b = ((atoms_next - self.config.categorical_Vmin) / self.delta_z) (l, u) = (np.floor(b).astype(int), np.ceil(b).astype(int)) d_m_l = (((u + (l == u)) - b) * prob_next) d_m_u = ((b - l) * prob_next) target_histo = np.zeros(shape=(self.batch_size, self.n_atoms)) for i in range(self.batch_size): target_histo[i][action_next[i]] = 0.0 np.add.at(target_histo[i], l[i], d_m_l[i]) np.add.at(target_histo[i], l[i], d_m_u[i]) self.actor_network.fit(x=current_states, y=target_histo, verbose=2, callbacks=self.keras_check)
TD update by replaying the history. Implementation of algorithm 1 in the paper.
src/agent/CategoricalDQN.py
train_by_replay
hsjharvey/DeepRL
3
python
def train_by_replay(self): '\n TD update by replaying the history.\n Implementation of algorithm 1 in the paper.\n ' (current_states, actions, next_states, rewards, terminals) = replay_fn.uniform_random_replay(self.replay_buffer, self.batch_size) (prob_next, _) = self.target_network.predict(next_states) action_value_next = np.dot(np.array(prob_next), self.atoms) action_next = np.argmax(action_value_next, axis=1) prob_next = prob_next[(np.arange(self.batch_size), action_next, :)] rewards = np.tile(rewards.reshape(self.batch_size, 1), (1, self.n_atoms)) discount_rate = (self.config.discount_rate * (1 - terminals)) atoms_next = (rewards + np.dot(discount_rate.reshape(self.batch_size, 1), self.atoms.reshape(1, self.n_atoms))) atoms_next = np.clip(atoms_next, self.vmin, self.vmax) b = ((atoms_next - self.config.categorical_Vmin) / self.delta_z) (l, u) = (np.floor(b).astype(int), np.ceil(b).astype(int)) d_m_l = (((u + (l == u)) - b) * prob_next) d_m_u = ((b - l) * prob_next) target_histo = np.zeros(shape=(self.batch_size, self.n_atoms)) for i in range(self.batch_size): target_histo[i][action_next[i]] = 0.0 np.add.at(target_histo[i], l[i], d_m_l[i]) np.add.at(target_histo[i], l[i], d_m_u[i]) self.actor_network.fit(x=current_states, y=target_histo, verbose=2, callbacks=self.keras_check)
def train_by_replay(self): '\n TD update by replaying the history.\n Implementation of algorithm 1 in the paper.\n ' (current_states, actions, next_states, rewards, terminals) = replay_fn.uniform_random_replay(self.replay_buffer, self.batch_size) (prob_next, _) = self.target_network.predict(next_states) action_value_next = np.dot(np.array(prob_next), self.atoms) action_next = np.argmax(action_value_next, axis=1) prob_next = prob_next[(np.arange(self.batch_size), action_next, :)] rewards = np.tile(rewards.reshape(self.batch_size, 1), (1, self.n_atoms)) discount_rate = (self.config.discount_rate * (1 - terminals)) atoms_next = (rewards + np.dot(discount_rate.reshape(self.batch_size, 1), self.atoms.reshape(1, self.n_atoms))) atoms_next = np.clip(atoms_next, self.vmin, self.vmax) b = ((atoms_next - self.config.categorical_Vmin) / self.delta_z) (l, u) = (np.floor(b).astype(int), np.ceil(b).astype(int)) d_m_l = (((u + (l == u)) - b) * prob_next) d_m_u = ((b - l) * prob_next) target_histo = np.zeros(shape=(self.batch_size, self.n_atoms)) for i in range(self.batch_size): target_histo[i][action_next[i]] = 0.0 np.add.at(target_histo[i], l[i], d_m_l[i]) np.add.at(target_histo[i], l[i], d_m_u[i]) self.actor_network.fit(x=current_states, y=target_histo, verbose=2, callbacks=self.keras_check)<|docstring|>TD update by replaying the history. Implementation of algorithm 1 in the paper.<|endoftext|>
7190420e9af3fe6c3da7be2f97b6801c04f3d501927b504827fa357b22f3559d
def eval_step(self, render=True): '\n Evaluation using the trained target network, no training involved\n :param render: whether to visualize the evaluation or not\n ' for each_ep in range(self.config.evaluate_episodes): current_state = self.envs.reset() print('Episode: {} Reward: {} Training_Max_Reward: {}'.format(each_ep, self.check_model_improved, self.best_max)) print(('-' * 64)) self.check_model_improved = 0 for step in range(self.steps): (action_prob, _) = self.target_network.predict(np.array(current_state).reshape((1, self.input_dim[0], self.input_dim[1]))) action_value = np.dot(np.array(action_prob), self.atoms) action = np.argmax(action_value[0]) (next_state, reward, done, _) = self.envs.step(action=action) if render: self.envs.render(mode=['human']) if done: break else: current_state = next_state self.check_model_improved += 1
Evaluation using the trained target network, no training involved :param render: whether to visualize the evaluation or not
src/agent/CategoricalDQN.py
eval_step
hsjharvey/DeepRL
3
python
def eval_step(self, render=True): '\n Evaluation using the trained target network, no training involved\n :param render: whether to visualize the evaluation or not\n ' for each_ep in range(self.config.evaluate_episodes): current_state = self.envs.reset() print('Episode: {} Reward: {} Training_Max_Reward: {}'.format(each_ep, self.check_model_improved, self.best_max)) print(('-' * 64)) self.check_model_improved = 0 for step in range(self.steps): (action_prob, _) = self.target_network.predict(np.array(current_state).reshape((1, self.input_dim[0], self.input_dim[1]))) action_value = np.dot(np.array(action_prob), self.atoms) action = np.argmax(action_value[0]) (next_state, reward, done, _) = self.envs.step(action=action) if render: self.envs.render(mode=['human']) if done: break else: current_state = next_state self.check_model_improved += 1
def eval_step(self, render=True): '\n Evaluation using the trained target network, no training involved\n :param render: whether to visualize the evaluation or not\n ' for each_ep in range(self.config.evaluate_episodes): current_state = self.envs.reset() print('Episode: {} Reward: {} Training_Max_Reward: {}'.format(each_ep, self.check_model_improved, self.best_max)) print(('-' * 64)) self.check_model_improved = 0 for step in range(self.steps): (action_prob, _) = self.target_network.predict(np.array(current_state).reshape((1, self.input_dim[0], self.input_dim[1]))) action_value = np.dot(np.array(action_prob), self.atoms) action = np.argmax(action_value[0]) (next_state, reward, done, _) = self.envs.step(action=action) if render: self.envs.render(mode=['human']) if done: break else: current_state = next_state self.check_model_improved += 1<|docstring|>Evaluation using the trained target network, no training involved :param render: whether to visualize the evaluation or not<|endoftext|>
1f4f714b449eb62290eaf01781e35e5449750fe0177364eaa5586841270896ff
def test_bh_procedure1(): 'Test BH procedure' pvalues_str = '0.001 0.008 0.039 0.041 0.042 0.060 0.074 0.205 0.212 0.216 0.222 0.251 0.269 0.275 0.34 0.341 0.384 0.569 0.594 0.696 0.762 0.94 0.942 0.975 0.986'.split(' ') pvalues = [float(val) for val in pvalues_str] pairs = list(zip(range(len(pvalues)), pvalues)) random.shuffle(pairs) (idx, pvalues) = zip(*pairs) (adjusted_pvalues, rejected_hypotheses) = bh_procedure(pvalues, 0.25) zipped = sorted(zip(idx, adjusted_pvalues, rejected_hypotheses), key=(lambda elem: elem[0])) (_, adjusted_pvalues, rejected_hypotheses) = zip(*zipped) assert (rejected_hypotheses == tuple((([True] * 5) + ([False] * 20)))) assert (adjusted_pvalues[:5] == ((0.001 * 25), ((0.008 * 25) / 2), ((0.042 * 25) / 5), ((0.042 * 25) / 5), ((0.042 * 25) / 5)))
Test BH procedure
tests/test_unit.py
test_bh_procedure1
cloudbopper/anamod
1
python
def test_bh_procedure1(): pvalues_str = '0.001 0.008 0.039 0.041 0.042 0.060 0.074 0.205 0.212 0.216 0.222 0.251 0.269 0.275 0.34 0.341 0.384 0.569 0.594 0.696 0.762 0.94 0.942 0.975 0.986'.split(' ') pvalues = [float(val) for val in pvalues_str] pairs = list(zip(range(len(pvalues)), pvalues)) random.shuffle(pairs) (idx, pvalues) = zip(*pairs) (adjusted_pvalues, rejected_hypotheses) = bh_procedure(pvalues, 0.25) zipped = sorted(zip(idx, adjusted_pvalues, rejected_hypotheses), key=(lambda elem: elem[0])) (_, adjusted_pvalues, rejected_hypotheses) = zip(*zipped) assert (rejected_hypotheses == tuple((([True] * 5) + ([False] * 20)))) assert (adjusted_pvalues[:5] == ((0.001 * 25), ((0.008 * 25) / 2), ((0.042 * 25) / 5), ((0.042 * 25) / 5), ((0.042 * 25) / 5)))
def test_bh_procedure1(): pvalues_str = '0.001 0.008 0.039 0.041 0.042 0.060 0.074 0.205 0.212 0.216 0.222 0.251 0.269 0.275 0.34 0.341 0.384 0.569 0.594 0.696 0.762 0.94 0.942 0.975 0.986'.split(' ') pvalues = [float(val) for val in pvalues_str] pairs = list(zip(range(len(pvalues)), pvalues)) random.shuffle(pairs) (idx, pvalues) = zip(*pairs) (adjusted_pvalues, rejected_hypotheses) = bh_procedure(pvalues, 0.25) zipped = sorted(zip(idx, adjusted_pvalues, rejected_hypotheses), key=(lambda elem: elem[0])) (_, adjusted_pvalues, rejected_hypotheses) = zip(*zipped) assert (rejected_hypotheses == tuple((([True] * 5) + ([False] * 20)))) assert (adjusted_pvalues[:5] == ((0.001 * 25), ((0.008 * 25) / 2), ((0.042 * 25) / 5), ((0.042 * 25) / 5), ((0.042 * 25) / 5)))<|docstring|>Test BH procedure<|endoftext|>