repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
project-ncl/pnc-cli | pnc_cli/bpmbuildconfigurations.py | wait_for_repo_creation | def wait_for_repo_creation(task_id, retry=30):
"""
Using polling check if the task finished
"""
success_event_types = ("RC_CREATION_SUCCESS", )
error_event_types = ("RC_REPO_CREATION_ERROR", "RC_REPO_CLONE_ERROR", "RC_CREATION_ERROR")
while retry > 0:
bpm_task = get_bpm_task_by_id(task_id)
if contains_event_type(bpm_task.content.events, success_event_types):
break
if contains_event_type(bpm_task.content.events, error_event_types):
logging.error("Creation of Repository Configuration failed")
logging.error(bpm_task.content)
return False
logging.info("Waiting until Repository Configuration creation task "+str(task_id)+" finishes.")
time.sleep(10)
retry -= 1
return retry > 0 | python | def wait_for_repo_creation(task_id, retry=30):
"""
Using polling check if the task finished
"""
success_event_types = ("RC_CREATION_SUCCESS", )
error_event_types = ("RC_REPO_CREATION_ERROR", "RC_REPO_CLONE_ERROR", "RC_CREATION_ERROR")
while retry > 0:
bpm_task = get_bpm_task_by_id(task_id)
if contains_event_type(bpm_task.content.events, success_event_types):
break
if contains_event_type(bpm_task.content.events, error_event_types):
logging.error("Creation of Repository Configuration failed")
logging.error(bpm_task.content)
return False
logging.info("Waiting until Repository Configuration creation task "+str(task_id)+" finishes.")
time.sleep(10)
retry -= 1
return retry > 0 | [
"def",
"wait_for_repo_creation",
"(",
"task_id",
",",
"retry",
"=",
"30",
")",
":",
"success_event_types",
"=",
"(",
"\"RC_CREATION_SUCCESS\"",
",",
")",
"error_event_types",
"=",
"(",
"\"RC_REPO_CREATION_ERROR\"",
",",
"\"RC_REPO_CLONE_ERROR\"",
",",
"\"RC_CREATION_ERR... | Using polling check if the task finished | [
"Using",
"polling",
"check",
"if",
"the",
"task",
"finished"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/bpmbuildconfigurations.py#L91-L111 |
SmartTeleMax/iktomi | iktomi/utils/i18n.py | M_.count | def count(self):
'''
A count based on `count_field` and `format_args`.
'''
args = self.format_args
if args is None or \
(isinstance(args, dict) and self.count_field not in args):
raise TypeError("count is required")
return args[self.count_field] if isinstance(args, dict) else args | python | def count(self):
'''
A count based on `count_field` and `format_args`.
'''
args = self.format_args
if args is None or \
(isinstance(args, dict) and self.count_field not in args):
raise TypeError("count is required")
return args[self.count_field] if isinstance(args, dict) else args | [
"def",
"count",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"format_args",
"if",
"args",
"is",
"None",
"or",
"(",
"isinstance",
"(",
"args",
",",
"dict",
")",
"and",
"self",
".",
"count_field",
"not",
"in",
"args",
")",
":",
"raise",
"TypeError"... | A count based on `count_field` and `format_args`. | [
"A",
"count",
"based",
"on",
"count_field",
"and",
"format_args",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/i18n.py#L51-L59 |
project-ncl/pnc-cli | pnc_cli/archives.py | generate_sources_zip | def generate_sources_zip(milestone_id=None, output=None):
"""
Generate a sources archive for given milestone id.
"""
if not is_input_valid(milestone_id, output):
logging.error("invalid input")
return 1
create_work_dir(output)
download_sources_artifacts(milestone_id, output)
create_zip(output) | python | def generate_sources_zip(milestone_id=None, output=None):
"""
Generate a sources archive for given milestone id.
"""
if not is_input_valid(milestone_id, output):
logging.error("invalid input")
return 1
create_work_dir(output)
download_sources_artifacts(milestone_id, output)
create_zip(output) | [
"def",
"generate_sources_zip",
"(",
"milestone_id",
"=",
"None",
",",
"output",
"=",
"None",
")",
":",
"if",
"not",
"is_input_valid",
"(",
"milestone_id",
",",
"output",
")",
":",
"logging",
".",
"error",
"(",
"\"invalid input\"",
")",
"return",
"1",
"create... | Generate a sources archive for given milestone id. | [
"Generate",
"a",
"sources",
"archive",
"for",
"given",
"milestone",
"id",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/archives.py#L19-L28 |
project-ncl/pnc-cli | pnc_cli/repositoryconfigurations.py | get_repository_configuration | def get_repository_configuration(id):
"""
Retrieve a specific RepositoryConfiguration
"""
response = utils.checked_api_call(pnc_api.repositories, 'get_specific', id=id)
if response:
return response.content | python | def get_repository_configuration(id):
"""
Retrieve a specific RepositoryConfiguration
"""
response = utils.checked_api_call(pnc_api.repositories, 'get_specific', id=id)
if response:
return response.content | [
"def",
"get_repository_configuration",
"(",
"id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"repositories",
",",
"'get_specific'",
",",
"id",
"=",
"id",
")",
"if",
"response",
":",
"return",
"response",
".",
"content"
] | Retrieve a specific RepositoryConfiguration | [
"Retrieve",
"a",
"specific",
"RepositoryConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/repositoryconfigurations.py#L11-L18 |
project-ncl/pnc-cli | pnc_cli/repositoryconfigurations.py | update_repository_configuration | def update_repository_configuration(id, external_repository=None, prebuild_sync=None):
"""
Update an existing RepositoryConfiguration with new information
"""
to_update_id = id
rc_to_update = pnc_api.repositories.get_specific(id=to_update_id).content
if external_repository is None:
external_repository = rc_to_update.external_url
else:
rc_to_update.external_url = external_repository
if prebuild_sync is not None:
rc_to_update.pre_build_sync_enabled = prebuild_sync
if not external_repository and prebuild_sync:
logging.error("You cannot enable prebuild sync without external repository")
return
response = utils.checked_api_call(pnc_api.repositories, 'update', id=to_update_id, body=rc_to_update)
if response:
return response.content | python | def update_repository_configuration(id, external_repository=None, prebuild_sync=None):
"""
Update an existing RepositoryConfiguration with new information
"""
to_update_id = id
rc_to_update = pnc_api.repositories.get_specific(id=to_update_id).content
if external_repository is None:
external_repository = rc_to_update.external_url
else:
rc_to_update.external_url = external_repository
if prebuild_sync is not None:
rc_to_update.pre_build_sync_enabled = prebuild_sync
if not external_repository and prebuild_sync:
logging.error("You cannot enable prebuild sync without external repository")
return
response = utils.checked_api_call(pnc_api.repositories, 'update', id=to_update_id, body=rc_to_update)
if response:
return response.content | [
"def",
"update_repository_configuration",
"(",
"id",
",",
"external_repository",
"=",
"None",
",",
"prebuild_sync",
"=",
"None",
")",
":",
"to_update_id",
"=",
"id",
"rc_to_update",
"=",
"pnc_api",
".",
"repositories",
".",
"get_specific",
"(",
"id",
"=",
"to_up... | Update an existing RepositoryConfiguration with new information | [
"Update",
"an",
"existing",
"RepositoryConfiguration",
"with",
"new",
"information"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/repositoryconfigurations.py#L24-L46 |
project-ncl/pnc-cli | pnc_cli/repositoryconfigurations.py | list_repository_configurations | def list_repository_configurations(page_size=200, page_index=0, sort="", q=""):
"""
List all RepositoryConfigurations
"""
response = utils.checked_api_call(pnc_api.repositories, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(response.content) | python | def list_repository_configurations(page_size=200, page_index=0, sort="", q=""):
"""
List all RepositoryConfigurations
"""
response = utils.checked_api_call(pnc_api.repositories, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(response.content) | [
"def",
"list_repository_configurations",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"repositories",
",",
"'ge... | List all RepositoryConfigurations | [
"List",
"all",
"RepositoryConfigurations"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/repositoryconfigurations.py#L52-L58 |
project-ncl/pnc-cli | pnc_cli/repositoryconfigurations.py | search_repository_configuration | def search_repository_configuration(url, page_size=10, page_index=0, sort=""):
"""
Search for Repository Configurations based on internal or external url
"""
content = search_repository_configuration_raw(url, page_size, page_index, sort)
if content:
return utils.format_json_list(content) | python | def search_repository_configuration(url, page_size=10, page_index=0, sort=""):
"""
Search for Repository Configurations based on internal or external url
"""
content = search_repository_configuration_raw(url, page_size, page_index, sort)
if content:
return utils.format_json_list(content) | [
"def",
"search_repository_configuration",
"(",
"url",
",",
"page_size",
"=",
"10",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
")",
":",
"content",
"=",
"search_repository_configuration_raw",
"(",
"url",
",",
"page_size",
",",
"page_index",
",",
"so... | Search for Repository Configurations based on internal or external url | [
"Search",
"for",
"Repository",
"Configurations",
"based",
"on",
"internal",
"or",
"external",
"url"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/repositoryconfigurations.py#L64-L70 |
project-ncl/pnc-cli | pnc_cli/repositoryconfigurations.py | search_repository_configuration_raw | def search_repository_configuration_raw(url, page_size=10, page_index=0, sort=""):
"""
Search for Repository Configurations based on internal or external url
"""
response = utils.checked_api_call(pnc_api.repositories, 'search', page_size=page_size, page_index=page_index, sort=sort, search=url)
if response:
return response.content | python | def search_repository_configuration_raw(url, page_size=10, page_index=0, sort=""):
"""
Search for Repository Configurations based on internal or external url
"""
response = utils.checked_api_call(pnc_api.repositories, 'search', page_size=page_size, page_index=page_index, sort=sort, search=url)
if response:
return response.content | [
"def",
"search_repository_configuration_raw",
"(",
"url",
",",
"page_size",
"=",
"10",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"repositories",
",",
"'search'",
"... | Search for Repository Configurations based on internal or external url | [
"Search",
"for",
"Repository",
"Configurations",
"based",
"on",
"internal",
"or",
"external",
"url"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/repositoryconfigurations.py#L72-L78 |
project-ncl/pnc-cli | pnc_cli/repositoryconfigurations.py | match_repository_configuration | def match_repository_configuration(url, page_size=10, page_index=0, sort=""):
"""
Search for Repository Configurations based on internal or external url with exact match
"""
content = match_repository_configuration_raw(url, page_size, page_index, sort)
if content:
return utils.format_json_list(content) | python | def match_repository_configuration(url, page_size=10, page_index=0, sort=""):
"""
Search for Repository Configurations based on internal or external url with exact match
"""
content = match_repository_configuration_raw(url, page_size, page_index, sort)
if content:
return utils.format_json_list(content) | [
"def",
"match_repository_configuration",
"(",
"url",
",",
"page_size",
"=",
"10",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
")",
":",
"content",
"=",
"match_repository_configuration_raw",
"(",
"url",
",",
"page_size",
",",
"page_index",
",",
"sort... | Search for Repository Configurations based on internal or external url with exact match | [
"Search",
"for",
"Repository",
"Configurations",
"based",
"on",
"internal",
"or",
"external",
"url",
"with",
"exact",
"match"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/repositoryconfigurations.py#L84-L90 |
SmartTeleMax/iktomi | iktomi/forms/form.py | Form.render | def render(self):
'''Proxy method to form's environment render method'''
return self.env.template.render(self.template, form=self) | python | def render(self):
'''Proxy method to form's environment render method'''
return self.env.template.render(self.template, form=self) | [
"def",
"render",
"(",
"self",
")",
":",
"return",
"self",
".",
"env",
".",
"template",
".",
"render",
"(",
"self",
".",
"template",
",",
"form",
"=",
"self",
")"
] | Proxy method to form's environment render method | [
"Proxy",
"method",
"to",
"form",
"s",
"environment",
"render",
"method"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/form.py#L64-L66 |
SmartTeleMax/iktomi | iktomi/forms/form.py | Form.accept | def accept(self, data):
'''
Try to accpet MultiDict-like object and return if it is valid.
'''
self.raw_data = MultiDict(data)
self.errors = {}
for field in self.fields:
if field.writable:
self.python_data.update(field.accept())
else:
for name in field.field_names:
# readonly field
subfield = self.get_field(name)
value = self.python_data[subfield.name]
subfield.set_raw_value(self.raw_data, subfield.from_python(value))
return self.is_valid | python | def accept(self, data):
'''
Try to accpet MultiDict-like object and return if it is valid.
'''
self.raw_data = MultiDict(data)
self.errors = {}
for field in self.fields:
if field.writable:
self.python_data.update(field.accept())
else:
for name in field.field_names:
# readonly field
subfield = self.get_field(name)
value = self.python_data[subfield.name]
subfield.set_raw_value(self.raw_data, subfield.from_python(value))
return self.is_valid | [
"def",
"accept",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"raw_data",
"=",
"MultiDict",
"(",
"data",
")",
"self",
".",
"errors",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"if",
"field",
".",
"writable",
":",
"self",
... | Try to accpet MultiDict-like object and return if it is valid. | [
"Try",
"to",
"accpet",
"MultiDict",
"-",
"like",
"object",
"and",
"return",
"if",
"it",
"is",
"valid",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/form.py#L73-L88 |
SmartTeleMax/iktomi | iktomi/forms/form.py | Form.get_data | def get_data(self, compact=True):
'''
Returns data representing current state of the form. While
Form.raw_data may contain alien fields and invalid data, this method
returns only valid fields that belong to this form only. It's designed
to pass somewhere current state of the form (as query string or by
other means).
'''
data = MultiDict()
for field in self.fields:
raw_value = field.from_python(self.python_data[field.name])
field.set_raw_value(data, raw_value)
if compact:
data = MultiDict([(k, v) for k, v in data.items() if v])
return data | python | def get_data(self, compact=True):
'''
Returns data representing current state of the form. While
Form.raw_data may contain alien fields and invalid data, this method
returns only valid fields that belong to this form only. It's designed
to pass somewhere current state of the form (as query string or by
other means).
'''
data = MultiDict()
for field in self.fields:
raw_value = field.from_python(self.python_data[field.name])
field.set_raw_value(data, raw_value)
if compact:
data = MultiDict([(k, v) for k, v in data.items() if v])
return data | [
"def",
"get_data",
"(",
"self",
",",
"compact",
"=",
"True",
")",
":",
"data",
"=",
"MultiDict",
"(",
")",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"raw_value",
"=",
"field",
".",
"from_python",
"(",
"self",
".",
"python_data",
"[",
"field",
... | Returns data representing current state of the form. While
Form.raw_data may contain alien fields and invalid data, this method
returns only valid fields that belong to this form only. It's designed
to pass somewhere current state of the form (as query string or by
other means). | [
"Returns",
"data",
"representing",
"current",
"state",
"of",
"the",
"form",
".",
"While",
"Form",
".",
"raw_data",
"may",
"contain",
"alien",
"fields",
"and",
"invalid",
"data",
"this",
"method",
"returns",
"only",
"valid",
"fields",
"that",
"belong",
"to",
... | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/form.py#L106-L120 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.add_configuration | def add_configuration(self, id, **kwargs):
"""
Adds a configuration to the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_configuration(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param BuildConfigurationRest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_configuration_with_http_info(id, **kwargs)
else:
(data) = self.add_configuration_with_http_info(id, **kwargs)
return data | python | def add_configuration(self, id, **kwargs):
"""
Adds a configuration to the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_configuration(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param BuildConfigurationRest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_configuration_with_http_info(id, **kwargs)
else:
(data) = self.add_configuration_with_http_info(id, **kwargs)
return data | [
"def",
"add_configuration",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"add_configuration_with_http_i... | Adds a configuration to the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_configuration(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param BuildConfigurationRest body:
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Adds",
"a",
"configuration",
"to",
"the",
"Specified",
"Set",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L42-L67 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.build | def build(self, id, **kwargs):
"""
Builds the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild all the configurations in the set; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildConfigSetRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_with_http_info(id, **kwargs)
else:
(data) = self.build_with_http_info(id, **kwargs)
return data | python | def build(self, id, **kwargs):
"""
Builds the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild all the configurations in the set; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildConfigSetRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_with_http_info(id, **kwargs)
else:
(data) = self.build_with_http_info(id, **kwargs)
return data | [
"def",
"build",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"build_with_http_info",
"(",
"id",
"... | Builds the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild all the configurations in the set; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildConfigSetRecordSingleton
If the method is called asynchronously,
returns the request thread. | [
"Builds",
"the",
"Configurations",
"for",
"the",
"Specified",
"Set",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L152-L181 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.build_versioned | def build_versioned(self, id, **kwargs):
"""
Builds the configurations for the Specified Set with an option to specify exact revision of a BC
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build_versioned(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param BuildConfigurationSetWithAuditedBCsRest body:
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild all the configurations in the set; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildConfigSetRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_versioned_with_http_info(id, **kwargs)
else:
(data) = self.build_versioned_with_http_info(id, **kwargs)
return data | python | def build_versioned(self, id, **kwargs):
"""
Builds the configurations for the Specified Set with an option to specify exact revision of a BC
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build_versioned(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param BuildConfigurationSetWithAuditedBCsRest body:
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild all the configurations in the set; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildConfigSetRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_versioned_with_http_info(id, **kwargs)
else:
(data) = self.build_versioned_with_http_info(id, **kwargs)
return data | [
"def",
"build_versioned",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"build_versioned_with_http_info"... | Builds the configurations for the Specified Set with an option to specify exact revision of a BC
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build_versioned(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param BuildConfigurationSetWithAuditedBCsRest body:
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild all the configurations in the set; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildConfigSetRecordSingleton
If the method is called asynchronously,
returns the request thread. | [
"Builds",
"the",
"configurations",
"for",
"the",
"Specified",
"Set",
"with",
"an",
"option",
"to",
"specify",
"exact",
"revision",
"of",
"a",
"BC",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L278-L308 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.delete_specific | def delete_specific(self, id, **kwargs):
"""
Removes a specific Build Configuration Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_specific(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_specific_with_http_info(id, **kwargs)
else:
(data) = self.delete_specific_with_http_info(id, **kwargs)
return data | python | def delete_specific(self, id, **kwargs):
"""
Removes a specific Build Configuration Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_specific(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_specific_with_http_info(id, **kwargs)
else:
(data) = self.delete_specific_with_http_info(id, **kwargs)
return data | [
"def",
"delete_specific",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"delete_specific_with_http_info"... | Removes a specific Build Configuration Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_specific(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Removes",
"a",
"specific",
"Build",
"Configuration",
"Set",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L511-L535 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.get_all_build_config_set_records | def get_all_build_config_set_records(self, id, **kwargs):
"""
Get all build config set execution records associated with this build config set, returns empty list if none are found
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_build_config_set_records(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build config set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationSetRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_build_config_set_records_with_http_info(id, **kwargs)
else:
(data) = self.get_all_build_config_set_records_with_http_info(id, **kwargs)
return data | python | def get_all_build_config_set_records(self, id, **kwargs):
"""
Get all build config set execution records associated with this build config set, returns empty list if none are found
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_build_config_set_records(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build config set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationSetRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_build_config_set_records_with_http_info(id, **kwargs)
else:
(data) = self.get_all_build_config_set_records_with_http_info(id, **kwargs)
return data | [
"def",
"get_all_build_config_set_records",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_all_build_... | Get all build config set execution records associated with this build config set, returns empty list if none are found
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_build_config_set_records(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build config set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationSetRecordPage
If the method is called asynchronously,
returns the request thread. | [
"Get",
"all",
"build",
"config",
"set",
"execution",
"records",
"associated",
"with",
"this",
"build",
"config",
"set",
"returns",
"empty",
"list",
"if",
"none",
"are",
"found",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L732-L760 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.get_build_records | def get_build_records(self, id, **kwargs):
"""
Gets all build records associated with the contained build configurations
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_build_records(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_build_records_with_http_info(id, **kwargs)
else:
(data) = self.get_build_records_with_http_info(id, **kwargs)
return data | python | def get_build_records(self, id, **kwargs):
"""
Gets all build records associated with the contained build configurations
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_build_records(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_build_records_with_http_info(id, **kwargs)
else:
(data) = self.get_build_records_with_http_info(id, **kwargs)
return data | [
"def",
"get_build_records",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_build_records_with_http_i... | Gets all build records associated with the contained build configurations
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_build_records(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"all",
"build",
"records",
"associated",
"with",
"the",
"contained",
"build",
"configurations",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"defi... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L854-L882 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.get_configurations | def get_configurations(self, id, **kwargs):
"""
Gets the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_configurations(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_configurations_with_http_info(id, **kwargs)
else:
(data) = self.get_configurations_with_http_info(id, **kwargs)
return data | python | def get_configurations(self, id, **kwargs):
"""
Gets the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_configurations(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_configurations_with_http_info(id, **kwargs)
else:
(data) = self.get_configurations_with_http_info(id, **kwargs)
return data | [
"def",
"get_configurations",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_configurations_with_http... | Gets the Configurations for the Specified Set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_configurations(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"the",
"Configurations",
"for",
"the",
"Specified",
"Set",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L976-L1004 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.remove_configuration | def remove_configuration(self, id, config_id, **kwargs):
"""
Removes a configuration from the specified config set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.remove_configuration(id, config_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int config_id: Build configuration id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.remove_configuration_with_http_info(id, config_id, **kwargs)
else:
(data) = self.remove_configuration_with_http_info(id, config_id, **kwargs)
return data | python | def remove_configuration(self, id, config_id, **kwargs):
"""
Removes a configuration from the specified config set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.remove_configuration(id, config_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int config_id: Build configuration id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.remove_configuration_with_http_info(id, config_id, **kwargs)
else:
(data) = self.remove_configuration_with_http_info(id, config_id, **kwargs)
return data | [
"def",
"remove_configuration",
"(",
"self",
",",
"id",
",",
"config_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"remo... | Removes a configuration from the specified config set
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.remove_configuration(id, config_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int config_id: Build configuration id (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Removes",
"a",
"configuration",
"from",
"the",
"specified",
"config",
"set",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"f... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L1204-L1229 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurationsets_api.py | BuildconfigurationsetsApi.update_configurations | def update_configurations(self, id, **kwargs):
"""
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_configurations(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set Id (required)
:param list[BuildConfigurationRest] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_configurations_with_http_info(id, **kwargs)
else:
(data) = self.update_configurations_with_http_info(id, **kwargs)
return data | python | def update_configurations(self, id, **kwargs):
"""
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_configurations(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set Id (required)
:param list[BuildConfigurationRest] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_configurations_with_http_info(id, **kwargs)
else:
(data) = self.update_configurations_with_http_info(id, **kwargs)
return data | [
"def",
"update_configurations",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"update_configurations_wit... | This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_configurations(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set Id (required)
:param list[BuildConfigurationRest] body:
:return: None
If the method is called asynchronously,
returns the request thread. | [
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be",
"invoked",
"when",
"receiving",
"the",
"response",
".",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L1427-L1450 |
twisted/epsilon | epsilon/hotfixes/plugin_package_paths.py | pluginPackagePaths | def pluginPackagePaths(name):
"""
Return a list of additional directories which should be searched for
modules to be included as part of the named plugin package.
@type name: C{str}
@param name: The fully-qualified Python name of a plugin package, eg
C{'twisted.plugins'}.
@rtype: C{list} of C{str}
@return: The absolute paths to other directories which may contain plugin
modules for the named plugin package.
"""
package = name.split('.')
# Note that this may include directories which do not exist. It may be
# preferable to remove such directories at this point, rather than allow
# them to be searched later on.
#
# Note as well that only '__init__.py' will be considered to make a
# directory a package (and thus exclude it from this list). This means
# that if you create a master plugin package which has some other kind of
# __init__ (eg, __init__.pyc) it will be incorrectly treated as a
# supplementary plugin directory.
return [
os.path.abspath(os.path.join(x, *package))
for x
in sys.path
if
not os.path.exists(os.path.join(x, *package + ['__init__.py']))] | python | def pluginPackagePaths(name):
"""
Return a list of additional directories which should be searched for
modules to be included as part of the named plugin package.
@type name: C{str}
@param name: The fully-qualified Python name of a plugin package, eg
C{'twisted.plugins'}.
@rtype: C{list} of C{str}
@return: The absolute paths to other directories which may contain plugin
modules for the named plugin package.
"""
package = name.split('.')
# Note that this may include directories which do not exist. It may be
# preferable to remove such directories at this point, rather than allow
# them to be searched later on.
#
# Note as well that only '__init__.py' will be considered to make a
# directory a package (and thus exclude it from this list). This means
# that if you create a master plugin package which has some other kind of
# __init__ (eg, __init__.pyc) it will be incorrectly treated as a
# supplementary plugin directory.
return [
os.path.abspath(os.path.join(x, *package))
for x
in sys.path
if
not os.path.exists(os.path.join(x, *package + ['__init__.py']))] | [
"def",
"pluginPackagePaths",
"(",
"name",
")",
":",
"package",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"# Note that this may include directories which do not exist. It may be",
"# preferable to remove such directories at this point, rather than allow",
"# them to be searched lat... | Return a list of additional directories which should be searched for
modules to be included as part of the named plugin package.
@type name: C{str}
@param name: The fully-qualified Python name of a plugin package, eg
C{'twisted.plugins'}.
@rtype: C{list} of C{str}
@return: The absolute paths to other directories which may contain plugin
modules for the named plugin package. | [
"Return",
"a",
"list",
"of",
"additional",
"directories",
"which",
"should",
"be",
"searched",
"for",
"modules",
"to",
"be",
"included",
"as",
"part",
"of",
"the",
"named",
"plugin",
"package",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/plugin_package_paths.py#L9-L37 |
SmartTeleMax/iktomi | iktomi/utils/storage.py | storage_method | def storage_method(func):
'''Calls decorated method with VersionedStorage as self'''
def wrap(self, *args, **kwargs):
return func(self._root_storage, *args, **kwargs)
return wrap | python | def storage_method(func):
'''Calls decorated method with VersionedStorage as self'''
def wrap(self, *args, **kwargs):
return func(self._root_storage, *args, **kwargs)
return wrap | [
"def",
"storage_method",
"(",
"func",
")",
":",
"def",
"wrap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"func",
"(",
"self",
".",
"_root_storage",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrap"
] | Calls decorated method with VersionedStorage as self | [
"Calls",
"decorated",
"method",
"with",
"VersionedStorage",
"as",
"self"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/storage.py#L102-L106 |
SmartTeleMax/iktomi | iktomi/templates/jinja2/__init__.py | TemplateEngine.render | def render(self, template_name, **kw):
'Interface method called from `Template.render`'
return self.env.get_template(template_name).render(**kw) | python | def render(self, template_name, **kw):
'Interface method called from `Template.render`'
return self.env.get_template(template_name).render(**kw) | [
"def",
"render",
"(",
"self",
",",
"template_name",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"env",
".",
"get_template",
"(",
"template_name",
")",
".",
"render",
"(",
"*",
"*",
"kw",
")"
] | Interface method called from `Template.render` | [
"Interface",
"method",
"called",
"from",
"Template",
".",
"render"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/templates/jinja2/__init__.py#L36-L38 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/runningbuildrecords_api.py | RunningbuildrecordsApi.cancel_all_builds_in_group | def cancel_all_builds_in_group(self, id, **kwargs):
"""
Cancel all builds running in the build group
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_all_builds_in_group(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cancel_all_builds_in_group_with_http_info(id, **kwargs)
else:
(data) = self.cancel_all_builds_in_group_with_http_info(id, **kwargs)
return data | python | def cancel_all_builds_in_group(self, id, **kwargs):
"""
Cancel all builds running in the build group
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_all_builds_in_group(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cancel_all_builds_in_group_with_http_info(id, **kwargs)
else:
(data) = self.cancel_all_builds_in_group_with_http_info(id, **kwargs)
return data | [
"def",
"cancel_all_builds_in_group",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"cancel_all_builds_in... | Cancel all builds running in the build group
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_all_builds_in_group(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Cancel",
"all",
"builds",
"running",
"in",
"the",
"build",
"group",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/runningbuildrecords_api.py#L42-L66 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/runningbuildrecords_api.py | RunningbuildrecordsApi.get_all_for_bc | def get_all_for_bc(self, id, **kwargs):
"""
Gets running Build Records for a specific Build Configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_for_bc(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str search: Since this endpoint does not support queries, fulltext search is hard-coded for some predefined fields (record id, configuration name) and performed using this argument. Empty string leaves all data unfiltered.
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_for_bc_with_http_info(id, **kwargs)
else:
(data) = self.get_all_for_bc_with_http_info(id, **kwargs)
return data | python | def get_all_for_bc(self, id, **kwargs):
"""
Gets running Build Records for a specific Build Configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_for_bc(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str search: Since this endpoint does not support queries, fulltext search is hard-coded for some predefined fields (record id, configuration name) and performed using this argument. Empty string leaves all data unfiltered.
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_for_bc_with_http_info(id, **kwargs)
else:
(data) = self.get_all_for_bc_with_http_info(id, **kwargs)
return data | [
"def",
"get_all_for_bc",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_all_for_bc_with_http_info",
... | Gets running Build Records for a specific Build Configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_for_bc(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str search: Since this endpoint does not support queries, fulltext search is hard-coded for some predefined fields (record id, configuration name) and performed using this argument. Empty string leaves all data unfiltered.
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"running",
"Build",
"Records",
"for",
"a",
"specific",
"Build",
"Configuration",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/runningbuildrecords_api.py#L263-L290 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/runningbuildrecords_api.py | RunningbuildrecordsApi.get_all_for_bc_set_record | def get_all_for_bc_set_record(self, id, **kwargs):
"""
Gets running Build Records for a specific Build Configuration Set Record.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_for_bc_set_record(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str search: Since this endpoint does not support queries, fulltext search is hard-coded for some predefined fields (record id, configuration name) and performed using this argument. Empty string leaves all data unfiltered.
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_for_bc_set_record_with_http_info(id, **kwargs)
else:
(data) = self.get_all_for_bc_set_record_with_http_info(id, **kwargs)
return data | python | def get_all_for_bc_set_record(self, id, **kwargs):
"""
Gets running Build Records for a specific Build Configuration Set Record.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_for_bc_set_record(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str search: Since this endpoint does not support queries, fulltext search is hard-coded for some predefined fields (record id, configuration name) and performed using this argument. Empty string leaves all data unfiltered.
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_for_bc_set_record_with_http_info(id, **kwargs)
else:
(data) = self.get_all_for_bc_set_record_with_http_info(id, **kwargs)
return data | [
"def",
"get_all_for_bc_set_record",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_all_for_bc_set_re... | Gets running Build Records for a specific Build Configuration Set Record.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_all_for_bc_set_record(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration Set id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str search: Since this endpoint does not support queries, fulltext search is hard-coded for some predefined fields (record id, configuration name) and performed using this argument. Empty string leaves all data unfiltered.
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"running",
"Build",
"Records",
"for",
"a",
"specific",
"Build",
"Configuration",
"Set",
"Record",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"pleas... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/runningbuildrecords_api.py#L381-L408 |
scholrly/orcid-python | orcid/utils.py | dictmapper | def dictmapper(typename, mapping):
"""
A factory to create `namedtuple`-like classes from a field-to-dict-path
mapping::
Person = dictmapper({'person':('person','name')})
example_dict = {'person':{'name':'John'}}
john = Person(example_dict)
assert john.name == 'John'
If a function is specified as a mapping value instead of a dict "path", it
will be run with the backing dict as its first argument.
"""
def init(self, d, *args, **kwargs):
"""
Initialize `dictmapper` classes with a dict to back getters.
"""
self._original_dict = d
def getter_from_dict_path(path):
if not callable(path) and len(path) < 1:
raise ValueError('Dict paths should be iterables with at least one'
' key or callable objects that take one argument.')
def getter(self):
cur_dict = self._original_dict
if callable(path):
return path(cur_dict)
return dict_value_from_path(cur_dict, path)
return getter
prop_mapping = dict((k, property(getter_from_dict_path(v)))
for k, v in mapping.iteritems())
prop_mapping['__init__'] = init
return type(typename, tuple(), prop_mapping) | python | def dictmapper(typename, mapping):
"""
A factory to create `namedtuple`-like classes from a field-to-dict-path
mapping::
Person = dictmapper({'person':('person','name')})
example_dict = {'person':{'name':'John'}}
john = Person(example_dict)
assert john.name == 'John'
If a function is specified as a mapping value instead of a dict "path", it
will be run with the backing dict as its first argument.
"""
def init(self, d, *args, **kwargs):
"""
Initialize `dictmapper` classes with a dict to back getters.
"""
self._original_dict = d
def getter_from_dict_path(path):
if not callable(path) and len(path) < 1:
raise ValueError('Dict paths should be iterables with at least one'
' key or callable objects that take one argument.')
def getter(self):
cur_dict = self._original_dict
if callable(path):
return path(cur_dict)
return dict_value_from_path(cur_dict, path)
return getter
prop_mapping = dict((k, property(getter_from_dict_path(v)))
for k, v in mapping.iteritems())
prop_mapping['__init__'] = init
return type(typename, tuple(), prop_mapping) | [
"def",
"dictmapper",
"(",
"typename",
",",
"mapping",
")",
":",
"def",
"init",
"(",
"self",
",",
"d",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Initialize `dictmapper` classes with a dict to back getters.\n \"\"\"",
"self",
".",
... | A factory to create `namedtuple`-like classes from a field-to-dict-path
mapping::
Person = dictmapper({'person':('person','name')})
example_dict = {'person':{'name':'John'}}
john = Person(example_dict)
assert john.name == 'John'
If a function is specified as a mapping value instead of a dict "path", it
will be run with the backing dict as its first argument. | [
"A",
"factory",
"to",
"create",
"namedtuple",
"-",
"like",
"classes",
"from",
"a",
"field",
"-",
"to",
"-",
"dict",
"-",
"path",
"mapping",
"::"
] | train | https://github.com/scholrly/orcid-python/blob/71311ca708689740e99d447716d6f22f1291f6f8/orcid/utils.py#L7-L40 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.ctor_args | def ctor_args(self):
"""Return arguments for constructing a copy"""
return dict(
config=self._config,
search=self._search,
echo=self._echo,
read_only=self.read_only
) | python | def ctor_args(self):
"""Return arguments for constructing a copy"""
return dict(
config=self._config,
search=self._search,
echo=self._echo,
read_only=self.read_only
) | [
"def",
"ctor_args",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"config",
"=",
"self",
".",
"_config",
",",
"search",
"=",
"self",
".",
"_search",
",",
"echo",
"=",
"self",
".",
"_echo",
",",
"read_only",
"=",
"self",
".",
"read_only",
")"
] | Return arguments for constructing a copy | [
"Return",
"arguments",
"for",
"constructing",
"a",
"copy"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L116-L124 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.sync_config | def sync_config(self, force=False):
"""Sync the file config into the library proxy data in the root dataset """
from ambry.library.config import LibraryConfigSyncProxy
lcsp = LibraryConfigSyncProxy(self)
lcsp.sync(force=force) | python | def sync_config(self, force=False):
"""Sync the file config into the library proxy data in the root dataset """
from ambry.library.config import LibraryConfigSyncProxy
lcsp = LibraryConfigSyncProxy(self)
lcsp.sync(force=force) | [
"def",
"sync_config",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"from",
"ambry",
".",
"library",
".",
"config",
"import",
"LibraryConfigSyncProxy",
"lcsp",
"=",
"LibraryConfigSyncProxy",
"(",
"self",
")",
"lcsp",
".",
"sync",
"(",
"force",
"=",
"f... | Sync the file config into the library proxy data in the root dataset | [
"Sync",
"the",
"file",
"config",
"into",
"the",
"library",
"proxy",
"data",
"in",
"the",
"root",
"dataset"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L138-L142 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.init_debug | def init_debug(self):
"""Initialize debugging features, such as a handler for USR2 to print a trace"""
import signal
def debug_trace(sig, frame):
"""Interrupt running process, and provide a python prompt for interactive
debugging."""
self.log('Trace signal received')
self.log(''.join(traceback.format_stack(frame)))
signal.signal(signal.SIGUSR2, debug_trace) | python | def init_debug(self):
"""Initialize debugging features, such as a handler for USR2 to print a trace"""
import signal
def debug_trace(sig, frame):
"""Interrupt running process, and provide a python prompt for interactive
debugging."""
self.log('Trace signal received')
self.log(''.join(traceback.format_stack(frame)))
signal.signal(signal.SIGUSR2, debug_trace) | [
"def",
"init_debug",
"(",
"self",
")",
":",
"import",
"signal",
"def",
"debug_trace",
"(",
"sig",
",",
"frame",
")",
":",
"\"\"\"Interrupt running process, and provide a python prompt for interactive\n debugging.\"\"\"",
"self",
".",
"log",
"(",
"'Trace signal re... | Initialize debugging features, such as a handler for USR2 to print a trace | [
"Initialize",
"debugging",
"features",
"such",
"as",
"a",
"handler",
"for",
"USR2",
"to",
"print",
"a",
"trace"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L144-L155 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.resolve_object_number | def resolve_object_number(self, ref):
"""Resolve a variety of object numebrs to a dataset number"""
if not isinstance(ref, ObjectNumber):
on = ObjectNumber.parse(ref)
else:
on = ref
ds_on = on.as_dataset
return ds_on | python | def resolve_object_number(self, ref):
"""Resolve a variety of object numebrs to a dataset number"""
if not isinstance(ref, ObjectNumber):
on = ObjectNumber.parse(ref)
else:
on = ref
ds_on = on.as_dataset
return ds_on | [
"def",
"resolve_object_number",
"(",
"self",
",",
"ref",
")",
":",
"if",
"not",
"isinstance",
"(",
"ref",
",",
"ObjectNumber",
")",
":",
"on",
"=",
"ObjectNumber",
".",
"parse",
"(",
"ref",
")",
"else",
":",
"on",
"=",
"ref",
"ds_on",
"=",
"on",
".",... | Resolve a variety of object numebrs to a dataset number | [
"Resolve",
"a",
"variety",
"of",
"object",
"numebrs",
"to",
"a",
"dataset",
"number"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L157-L167 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.dataset | def dataset(self, ref, load_all=False, exception=True):
"""Return all datasets"""
return self.database.dataset(ref, load_all=load_all, exception=exception) | python | def dataset(self, ref, load_all=False, exception=True):
"""Return all datasets"""
return self.database.dataset(ref, load_all=load_all, exception=exception) | [
"def",
"dataset",
"(",
"self",
",",
"ref",
",",
"load_all",
"=",
"False",
",",
"exception",
"=",
"True",
")",
":",
"return",
"self",
".",
"database",
".",
"dataset",
"(",
"ref",
",",
"load_all",
"=",
"load_all",
",",
"exception",
"=",
"exception",
")"
... | Return all datasets | [
"Return",
"all",
"datasets"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L235-L237 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.new_bundle | def new_bundle(self, assignment_class=None, **kwargs):
"""
Create a new bundle, with the same arguments as creating a new dataset
:param assignment_class: String. assignment class to use for fetching a number, if one
is not specified in kwargs
:param kwargs:
:return:
"""
if not ('id' in kwargs and bool(kwargs['id'])) or assignment_class is not None:
kwargs['id'] = self.number(assignment_class)
ds = self._db.new_dataset(**kwargs)
self._db.commit()
b = self.bundle(ds.vid)
b.state = Bundle.STATES.NEW
b.set_last_access(Bundle.STATES.NEW)
b.set_file_system(source_url=self._fs.source(b.identity.source_path),
build_url=self._fs.build(b.identity.source_path))
bs_meta = b.build_source_files.file(File.BSFILE.META)
bs_meta.set_defaults()
bs_meta.record_to_objects()
bs_meta.objects_to_record()
b.commit()
self._db.commit()
return b | python | def new_bundle(self, assignment_class=None, **kwargs):
"""
Create a new bundle, with the same arguments as creating a new dataset
:param assignment_class: String. assignment class to use for fetching a number, if one
is not specified in kwargs
:param kwargs:
:return:
"""
if not ('id' in kwargs and bool(kwargs['id'])) or assignment_class is not None:
kwargs['id'] = self.number(assignment_class)
ds = self._db.new_dataset(**kwargs)
self._db.commit()
b = self.bundle(ds.vid)
b.state = Bundle.STATES.NEW
b.set_last_access(Bundle.STATES.NEW)
b.set_file_system(source_url=self._fs.source(b.identity.source_path),
build_url=self._fs.build(b.identity.source_path))
bs_meta = b.build_source_files.file(File.BSFILE.META)
bs_meta.set_defaults()
bs_meta.record_to_objects()
bs_meta.objects_to_record()
b.commit()
self._db.commit()
return b | [
"def",
"new_bundle",
"(",
"self",
",",
"assignment_class",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"'id'",
"in",
"kwargs",
"and",
"bool",
"(",
"kwargs",
"[",
"'id'",
"]",
")",
")",
"or",
"assignment_class",
"is",
"not",
"Non... | Create a new bundle, with the same arguments as creating a new dataset
:param assignment_class: String. assignment class to use for fetching a number, if one
is not specified in kwargs
:param kwargs:
:return: | [
"Create",
"a",
"new",
"bundle",
"with",
"the",
"same",
"arguments",
"as",
"creating",
"a",
"new",
"dataset"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L239-L270 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.new_from_bundle_config | def new_from_bundle_config(self, config):
"""
Create a new bundle, or link to an existing one, based on the identity in config data.
:param config: A Dict form of a bundle.yaml file
:return:
"""
identity = Identity.from_dict(config['identity'])
ds = self._db.dataset(identity.vid, exception=False)
if not ds:
ds = self._db.new_dataset(**identity.dict)
b = Bundle(ds, self)
b.commit()
b.state = Bundle.STATES.NEW
b.set_last_access(Bundle.STATES.NEW)
# b.set_file_system(source_url=self._fs.source(ds.name),
# build_url=self._fs.build(ds.name))
return b | python | def new_from_bundle_config(self, config):
"""
Create a new bundle, or link to an existing one, based on the identity in config data.
:param config: A Dict form of a bundle.yaml file
:return:
"""
identity = Identity.from_dict(config['identity'])
ds = self._db.dataset(identity.vid, exception=False)
if not ds:
ds = self._db.new_dataset(**identity.dict)
b = Bundle(ds, self)
b.commit()
b.state = Bundle.STATES.NEW
b.set_last_access(Bundle.STATES.NEW)
# b.set_file_system(source_url=self._fs.source(ds.name),
# build_url=self._fs.build(ds.name))
return b | [
"def",
"new_from_bundle_config",
"(",
"self",
",",
"config",
")",
":",
"identity",
"=",
"Identity",
".",
"from_dict",
"(",
"config",
"[",
"'identity'",
"]",
")",
"ds",
"=",
"self",
".",
"_db",
".",
"dataset",
"(",
"identity",
".",
"vid",
",",
"exception"... | Create a new bundle, or link to an existing one, based on the identity in config data.
:param config: A Dict form of a bundle.yaml file
:return: | [
"Create",
"a",
"new",
"bundle",
"or",
"link",
"to",
"an",
"existing",
"one",
"based",
"on",
"the",
"identity",
"in",
"config",
"data",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L272-L294 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.bundle | def bundle(self, ref, capture_exceptions=False):
"""Return a bundle build on a dataset, with the given vid or id reference"""
from ..orm.exc import NotFoundError
if isinstance(ref, Dataset):
ds = ref
else:
try:
ds = self._db.dataset(ref)
except NotFoundError:
ds = None
if not ds:
try:
p = self.partition(ref)
ds = p._bundle.dataset
except NotFoundError:
ds = None
if not ds:
raise NotFoundError('Failed to find dataset for ref: {}'.format(ref))
b = Bundle(ds, self)
b.capture_exceptions = capture_exceptions
return b | python | def bundle(self, ref, capture_exceptions=False):
"""Return a bundle build on a dataset, with the given vid or id reference"""
from ..orm.exc import NotFoundError
if isinstance(ref, Dataset):
ds = ref
else:
try:
ds = self._db.dataset(ref)
except NotFoundError:
ds = None
if not ds:
try:
p = self.partition(ref)
ds = p._bundle.dataset
except NotFoundError:
ds = None
if not ds:
raise NotFoundError('Failed to find dataset for ref: {}'.format(ref))
b = Bundle(ds, self)
b.capture_exceptions = capture_exceptions
return b | [
"def",
"bundle",
"(",
"self",
",",
"ref",
",",
"capture_exceptions",
"=",
"False",
")",
":",
"from",
".",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"if",
"isinstance",
"(",
"ref",
",",
"Dataset",
")",
":",
"ds",
"=",
"ref",
"else",
":",
"try... | Return a bundle build on a dataset, with the given vid or id reference | [
"Return",
"a",
"bundle",
"build",
"on",
"a",
"dataset",
"with",
"the",
"given",
"vid",
"or",
"id",
"reference"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L296-L321 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.partition | def partition(self, ref, localize=False):
""" Finds partition by ref and converts to bundle partition.
:param ref: A partition reference
:param localize: If True, copy a remote partition to local filesystem. Defaults to False
:raises: NotFoundError: if partition with given ref not found.
:return: orm.Partition: found partition.
"""
if not ref:
raise NotFoundError("No partition for empty ref")
try:
on = ObjectNumber.parse(ref)
ds_on = on.as_dataset
ds = self._db.dataset(ds_on) # Could do it in on SQL query, but this is easier.
# The refresh is required because in some places the dataset is loaded without the partitions,
# and if that persist, we won't have partitions in it until it is refreshed.
self.database.session.refresh(ds)
p = ds.partition(ref)
except NotObjectNumberError:
q = (self.database.session.query(Partition)
.filter(or_(Partition.name == str(ref), Partition.vname == str(ref)))
.order_by(Partition.vid.desc()))
p = q.first()
if not p:
raise NotFoundError("No partition for ref: '{}'".format(ref))
b = self.bundle(p.d_vid)
p = b.wrap_partition(p)
if localize:
p.localize()
return p | python | def partition(self, ref, localize=False):
""" Finds partition by ref and converts to bundle partition.
:param ref: A partition reference
:param localize: If True, copy a remote partition to local filesystem. Defaults to False
:raises: NotFoundError: if partition with given ref not found.
:return: orm.Partition: found partition.
"""
if not ref:
raise NotFoundError("No partition for empty ref")
try:
on = ObjectNumber.parse(ref)
ds_on = on.as_dataset
ds = self._db.dataset(ds_on) # Could do it in on SQL query, but this is easier.
# The refresh is required because in some places the dataset is loaded without the partitions,
# and if that persist, we won't have partitions in it until it is refreshed.
self.database.session.refresh(ds)
p = ds.partition(ref)
except NotObjectNumberError:
q = (self.database.session.query(Partition)
.filter(or_(Partition.name == str(ref), Partition.vname == str(ref)))
.order_by(Partition.vid.desc()))
p = q.first()
if not p:
raise NotFoundError("No partition for ref: '{}'".format(ref))
b = self.bundle(p.d_vid)
p = b.wrap_partition(p)
if localize:
p.localize()
return p | [
"def",
"partition",
"(",
"self",
",",
"ref",
",",
"localize",
"=",
"False",
")",
":",
"if",
"not",
"ref",
":",
"raise",
"NotFoundError",
"(",
"\"No partition for empty ref\"",
")",
"try",
":",
"on",
"=",
"ObjectNumber",
".",
"parse",
"(",
"ref",
")",
"ds... | Finds partition by ref and converts to bundle partition.
:param ref: A partition reference
:param localize: If True, copy a remote partition to local filesystem. Defaults to False
:raises: NotFoundError: if partition with given ref not found.
:return: orm.Partition: found partition. | [
"Finds",
"partition",
"by",
"ref",
"and",
"converts",
"to",
"bundle",
"partition",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L336-L377 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.table | def table(self, ref):
""" Finds table by ref and returns it.
Args:
ref (str): id, vid (versioned id) or name of the table
Raises:
NotFoundError: if table with given ref not found.
Returns:
orm.Table
"""
try:
obj_number = ObjectNumber.parse(ref)
ds_obj_number = obj_number.as_dataset
dataset = self._db.dataset(ds_obj_number) # Could do it in on SQL query, but this is easier.
table = dataset.table(ref)
except NotObjectNumberError:
q = self.database.session.query(Table)\
.filter(Table.name == str(ref))\
.order_by(Table.vid.desc())
table = q.first()
if not table:
raise NotFoundError("No table for ref: '{}'".format(ref))
return table | python | def table(self, ref):
""" Finds table by ref and returns it.
Args:
ref (str): id, vid (versioned id) or name of the table
Raises:
NotFoundError: if table with given ref not found.
Returns:
orm.Table
"""
try:
obj_number = ObjectNumber.parse(ref)
ds_obj_number = obj_number.as_dataset
dataset = self._db.dataset(ds_obj_number) # Could do it in on SQL query, but this is easier.
table = dataset.table(ref)
except NotObjectNumberError:
q = self.database.session.query(Table)\
.filter(Table.name == str(ref))\
.order_by(Table.vid.desc())
table = q.first()
if not table:
raise NotFoundError("No table for ref: '{}'".format(ref))
return table | [
"def",
"table",
"(",
"self",
",",
"ref",
")",
":",
"try",
":",
"obj_number",
"=",
"ObjectNumber",
".",
"parse",
"(",
"ref",
")",
"ds_obj_number",
"=",
"obj_number",
".",
"as_dataset",
"dataset",
"=",
"self",
".",
"_db",
".",
"dataset",
"(",
"ds_obj_numbe... | Finds table by ref and returns it.
Args:
ref (str): id, vid (versioned id) or name of the table
Raises:
NotFoundError: if table with given ref not found.
Returns:
orm.Table | [
"Finds",
"table",
"by",
"ref",
"and",
"returns",
"it",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L379-L409 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.remove | def remove(self, bundle):
""" Removes a bundle from the library and deletes the configuration for
it from the library database."""
from six import string_types
if isinstance(bundle, string_types):
bundle = self.bundle(bundle)
self.database.remove_dataset(bundle.dataset) | python | def remove(self, bundle):
""" Removes a bundle from the library and deletes the configuration for
it from the library database."""
from six import string_types
if isinstance(bundle, string_types):
bundle = self.bundle(bundle)
self.database.remove_dataset(bundle.dataset) | [
"def",
"remove",
"(",
"self",
",",
"bundle",
")",
":",
"from",
"six",
"import",
"string_types",
"if",
"isinstance",
"(",
"bundle",
",",
"string_types",
")",
":",
"bundle",
"=",
"self",
".",
"bundle",
"(",
"bundle",
")",
"self",
".",
"database",
".",
"r... | Removes a bundle from the library and deletes the configuration for
it from the library database. | [
"Removes",
"a",
"bundle",
"from",
"the",
"library",
"and",
"deletes",
"the",
"configuration",
"for",
"it",
"from",
"the",
"library",
"database",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L411-L419 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.duplicate | def duplicate(self, b):
"""Duplicate a bundle, with a higher version number.
This only copies the files, under the theory that the bundle can be rebuilt from them.
"""
on = b.identity.on
on.revision = on.revision + 1
try:
extant = self.bundle(str(on))
if extant:
raise ConflictError('Already have a bundle with vid: {}'.format(str(on)))
except NotFoundError:
pass
d = b.dataset.dict
d['revision'] = on.revision
d['vid'] = str(on)
del d['name']
del d['vname']
del d['version']
del d['fqname']
del d['cache_key']
ds = self.database.new_dataset(**d)
nb = self.bundle(ds.vid)
nb.set_file_system(source_url=b.source_fs.getsyspath('/'))
nb.state = Bundle.STATES.NEW
nb.commit()
# Copy all of the files.
for f in b.dataset.files:
assert f.major_type == f.MAJOR_TYPE.BUILDSOURCE
nb.dataset.files.append(nb.dataset.bsfile(f.minor_type, f.path).update(f))
# Load the metadata in to records, then back out again. The objects_to_record process will set the
# new identity object numbers in the metadata file
nb.build_source_files.file(File.BSFILE.META).record_to_objects()
nb.build_source_files.file(File.BSFILE.META).objects_to_record()
ds.commit()
return nb | python | def duplicate(self, b):
"""Duplicate a bundle, with a higher version number.
This only copies the files, under the theory that the bundle can be rebuilt from them.
"""
on = b.identity.on
on.revision = on.revision + 1
try:
extant = self.bundle(str(on))
if extant:
raise ConflictError('Already have a bundle with vid: {}'.format(str(on)))
except NotFoundError:
pass
d = b.dataset.dict
d['revision'] = on.revision
d['vid'] = str(on)
del d['name']
del d['vname']
del d['version']
del d['fqname']
del d['cache_key']
ds = self.database.new_dataset(**d)
nb = self.bundle(ds.vid)
nb.set_file_system(source_url=b.source_fs.getsyspath('/'))
nb.state = Bundle.STATES.NEW
nb.commit()
# Copy all of the files.
for f in b.dataset.files:
assert f.major_type == f.MAJOR_TYPE.BUILDSOURCE
nb.dataset.files.append(nb.dataset.bsfile(f.minor_type, f.path).update(f))
# Load the metadata in to records, then back out again. The objects_to_record process will set the
# new identity object numbers in the metadata file
nb.build_source_files.file(File.BSFILE.META).record_to_objects()
nb.build_source_files.file(File.BSFILE.META).objects_to_record()
ds.commit()
return nb | [
"def",
"duplicate",
"(",
"self",
",",
"b",
")",
":",
"on",
"=",
"b",
".",
"identity",
".",
"on",
"on",
".",
"revision",
"=",
"on",
".",
"revision",
"+",
"1",
"try",
":",
"extant",
"=",
"self",
".",
"bundle",
"(",
"str",
"(",
"on",
")",
")",
"... | Duplicate a bundle, with a higher version number.
This only copies the files, under the theory that the bundle can be rebuilt from them. | [
"Duplicate",
"a",
"bundle",
"with",
"a",
"higher",
"version",
"number",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L442-L488 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.checkin_bundle | def checkin_bundle(self, db_path, replace=True, cb=None):
"""Add a bundle, as a Sqlite file, to this library"""
from ambry.orm.exc import NotFoundError
db = Database('sqlite:///{}'.format(db_path))
db.open()
if len(db.datasets) == 0:
raise NotFoundError("Did not get a dataset in the {} bundle".format(db_path))
ds = db.dataset(db.datasets[0].vid) # There should only be one
assert ds is not None
assert ds._database
try:
b = self.bundle(ds.vid)
self.logger.info(
"Removing old bundle before checking in new one of same number: '{}'"
.format(ds.vid))
self.remove(b)
except NotFoundError:
pass
try:
self.dataset(ds.vid) # Skip loading bundles we already have
except NotFoundError:
self.database.copy_dataset(ds, cb=cb)
b = self.bundle(ds.vid) # It had better exist now.
# b.state = Bundle.STATES.INSTALLED
b.commit()
#self.search.index_library_datasets(tick)
self.search.index_bundle(b)
return b | python | def checkin_bundle(self, db_path, replace=True, cb=None):
"""Add a bundle, as a Sqlite file, to this library"""
from ambry.orm.exc import NotFoundError
db = Database('sqlite:///{}'.format(db_path))
db.open()
if len(db.datasets) == 0:
raise NotFoundError("Did not get a dataset in the {} bundle".format(db_path))
ds = db.dataset(db.datasets[0].vid) # There should only be one
assert ds is not None
assert ds._database
try:
b = self.bundle(ds.vid)
self.logger.info(
"Removing old bundle before checking in new one of same number: '{}'"
.format(ds.vid))
self.remove(b)
except NotFoundError:
pass
try:
self.dataset(ds.vid) # Skip loading bundles we already have
except NotFoundError:
self.database.copy_dataset(ds, cb=cb)
b = self.bundle(ds.vid) # It had better exist now.
# b.state = Bundle.STATES.INSTALLED
b.commit()
#self.search.index_library_datasets(tick)
self.search.index_bundle(b)
return b | [
"def",
"checkin_bundle",
"(",
"self",
",",
"db_path",
",",
"replace",
"=",
"True",
",",
"cb",
"=",
"None",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"db",
"=",
"Database",
"(",
"'sqlite:///{}'",
".",
"format",
"(",
"... | Add a bundle, as a Sqlite file, to this library | [
"Add",
"a",
"bundle",
"as",
"a",
"Sqlite",
"file",
"to",
"this",
"library"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L490-L528 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.send_to_remote | def send_to_remote(self, b, no_partitions=False):
"""
Copy a bundle to a new Sqlite file, then store the file on the remote.
:param b: The bundle
:return:
"""
raise DeprecationWarning("Don't use any more?")
from ambry.bundle.process import call_interval
remote_name = self.resolve_remote(b)
remote = self.remote(remote_name)
db_path = b.package()
with b.progress.start('checkin', 0, message='Check in bundle') as ps:
ps.add(message='Checking in bundle {} to {}'.format(b.identity.vname, remote))
db_ck = b.identity.cache_key + '.db'
ps.add(message='Upload bundle file', item_type='bytes', item_count=0)
total = [0]
@call_interval(5)
def upload_cb(n):
total[0] += n
ps.update(message='Upload bundle file', item_count=total[0])
with open(db_path) as f:
remote.makedir(os.path.dirname(db_ck), recursive=True, allow_recreate=True)
self.logger.info('Send bundle file {} '.format(db_path))
e = remote.setcontents_async(db_ck, f, progress_callback=upload_cb)
e.wait()
ps.update(state='done')
if not no_partitions:
for p in b.partitions:
ps.add(message='Upload partition', item_type='bytes', item_count=0, p_vid=p.vid)
with p.datafile.open(mode='rb') as fin:
total = [0]
@call_interval(5)
def progress(bytes):
total[0] += bytes
ps.update(
message='Upload partition'.format(p.identity.vname),
item_count=total[0])
remote.makedir(os.path.dirname(p.datafile.path), recursive=True, allow_recreate=True)
event = remote.setcontents_async(p.datafile.path, fin, progress_callback=progress)
event.wait()
ps.update(state='done')
ps.add(message='Setting metadata')
ident = json.dumps(b.identity.dict)
remote.setcontents(os.path.join('_meta', 'vid', b.identity.vid), ident)
remote.setcontents(os.path.join('_meta', 'id', b.identity.id_), ident)
remote.setcontents(os.path.join('_meta', 'vname', text_type(b.identity.vname)), ident)
remote.setcontents(os.path.join('_meta', 'name', text_type(b.identity.name)), ident)
ps.update(state='done')
b.dataset.commit()
return remote_name, db_ck | python | def send_to_remote(self, b, no_partitions=False):
"""
Copy a bundle to a new Sqlite file, then store the file on the remote.
:param b: The bundle
:return:
"""
raise DeprecationWarning("Don't use any more?")
from ambry.bundle.process import call_interval
remote_name = self.resolve_remote(b)
remote = self.remote(remote_name)
db_path = b.package()
with b.progress.start('checkin', 0, message='Check in bundle') as ps:
ps.add(message='Checking in bundle {} to {}'.format(b.identity.vname, remote))
db_ck = b.identity.cache_key + '.db'
ps.add(message='Upload bundle file', item_type='bytes', item_count=0)
total = [0]
@call_interval(5)
def upload_cb(n):
total[0] += n
ps.update(message='Upload bundle file', item_count=total[0])
with open(db_path) as f:
remote.makedir(os.path.dirname(db_ck), recursive=True, allow_recreate=True)
self.logger.info('Send bundle file {} '.format(db_path))
e = remote.setcontents_async(db_ck, f, progress_callback=upload_cb)
e.wait()
ps.update(state='done')
if not no_partitions:
for p in b.partitions:
ps.add(message='Upload partition', item_type='bytes', item_count=0, p_vid=p.vid)
with p.datafile.open(mode='rb') as fin:
total = [0]
@call_interval(5)
def progress(bytes):
total[0] += bytes
ps.update(
message='Upload partition'.format(p.identity.vname),
item_count=total[0])
remote.makedir(os.path.dirname(p.datafile.path), recursive=True, allow_recreate=True)
event = remote.setcontents_async(p.datafile.path, fin, progress_callback=progress)
event.wait()
ps.update(state='done')
ps.add(message='Setting metadata')
ident = json.dumps(b.identity.dict)
remote.setcontents(os.path.join('_meta', 'vid', b.identity.vid), ident)
remote.setcontents(os.path.join('_meta', 'id', b.identity.id_), ident)
remote.setcontents(os.path.join('_meta', 'vname', text_type(b.identity.vname)), ident)
remote.setcontents(os.path.join('_meta', 'name', text_type(b.identity.name)), ident)
ps.update(state='done')
b.dataset.commit()
return remote_name, db_ck | [
"def",
"send_to_remote",
"(",
"self",
",",
"b",
",",
"no_partitions",
"=",
"False",
")",
":",
"raise",
"DeprecationWarning",
"(",
"\"Don't use any more?\"",
")",
"from",
"ambry",
".",
"bundle",
".",
"process",
"import",
"call_interval",
"remote_name",
"=",
"self... | Copy a bundle to a new Sqlite file, then store the file on the remote.
:param b: The bundle
:return: | [
"Copy",
"a",
"bundle",
"to",
"a",
"new",
"Sqlite",
"file",
"then",
"store",
"the",
"file",
"on",
"the",
"remote",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L530-L602 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.checkin_remote_bundle | def checkin_remote_bundle(self, ref, remote=None):
""" Checkin a remote bundle to this library.
:param ref: Any bundle reference
:param remote: If specified, use this remote. If not, search for the reference
in cached directory listings
:param cb: A one argument progress callback
:return:
"""
if not remote:
remote, vname = self.find_remote_bundle(ref)
if vname:
ref = vname
else:
pass
if not remote:
raise NotFoundError("Failed to find bundle ref '{}' in any remote".format(ref))
self.logger.info("Load '{}' from '{}'".format(ref, remote))
vid = self._checkin_remote_bundle(remote, ref)
self.commit()
return vid | python | def checkin_remote_bundle(self, ref, remote=None):
""" Checkin a remote bundle to this library.
:param ref: Any bundle reference
:param remote: If specified, use this remote. If not, search for the reference
in cached directory listings
:param cb: A one argument progress callback
:return:
"""
if not remote:
remote, vname = self.find_remote_bundle(ref)
if vname:
ref = vname
else:
pass
if not remote:
raise NotFoundError("Failed to find bundle ref '{}' in any remote".format(ref))
self.logger.info("Load '{}' from '{}'".format(ref, remote))
vid = self._checkin_remote_bundle(remote, ref)
self.commit()
return vid | [
"def",
"checkin_remote_bundle",
"(",
"self",
",",
"ref",
",",
"remote",
"=",
"None",
")",
":",
"if",
"not",
"remote",
":",
"remote",
",",
"vname",
"=",
"self",
".",
"find_remote_bundle",
"(",
"ref",
")",
"if",
"vname",
":",
"ref",
"=",
"vname",
"else",... | Checkin a remote bundle to this library.
:param ref: Any bundle reference
:param remote: If specified, use this remote. If not, search for the reference
in cached directory listings
:param cb: A one argument progress callback
:return: | [
"Checkin",
"a",
"remote",
"bundle",
"to",
"this",
"library",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L627-L653 |
CivicSpleen/ambry | ambry/library/__init__.py | Library._checkin_remote_bundle | def _checkin_remote_bundle(self, remote, ref):
"""
Checkin a remote bundle from a remote
:param remote: a Remote object
:param ref: Any bundle reference
:return: The vid of the loaded bundle
"""
from ambry.bundle.process import call_interval
from ambry.orm.exc import NotFoundError
from ambry.orm import Remote
from ambry.util.flo import copy_file_or_flo
from tempfile import NamedTemporaryFile
assert isinstance(remote, Remote)
@call_interval(5)
def cb(r, total):
self.logger.info("{}: Downloaded {} bytes".format(ref, total))
b = None
try:
b = self.bundle(ref)
self.logger.info("{}: Already installed".format(ref))
vid = b.identity.vid
except NotFoundError:
self.logger.info("{}: Syncing".format(ref))
db_dir = self.filesystem.downloads('bundles')
db_f = os.path.join(db_dir, ref) #FIXME. Could get multiple versions of same file. ie vid and vname
if not os.path.exists(os.path.join(db_dir, db_f)):
self.logger.info("Downloading bundle '{}' to '{}".format(ref, db_f))
with open(db_f, 'wb') as f_out:
with remote.checkout(ref) as f:
copy_file_or_flo(f, f_out, cb=cb)
f_out.flush()
self.checkin_bundle(db_f)
b = self.bundle(ref) # Should exist now.
b.dataset.data['remote_name'] = remote.short_name
b.dataset.upstream = remote.url
b.dstate = b.STATES.CHECKEDOUT
b.commit()
finally:
if b:
b.progress.close()
vid = b.identity.vid
return vid | python | def _checkin_remote_bundle(self, remote, ref):
"""
Checkin a remote bundle from a remote
:param remote: a Remote object
:param ref: Any bundle reference
:return: The vid of the loaded bundle
"""
from ambry.bundle.process import call_interval
from ambry.orm.exc import NotFoundError
from ambry.orm import Remote
from ambry.util.flo import copy_file_or_flo
from tempfile import NamedTemporaryFile
assert isinstance(remote, Remote)
@call_interval(5)
def cb(r, total):
self.logger.info("{}: Downloaded {} bytes".format(ref, total))
b = None
try:
b = self.bundle(ref)
self.logger.info("{}: Already installed".format(ref))
vid = b.identity.vid
except NotFoundError:
self.logger.info("{}: Syncing".format(ref))
db_dir = self.filesystem.downloads('bundles')
db_f = os.path.join(db_dir, ref) #FIXME. Could get multiple versions of same file. ie vid and vname
if not os.path.exists(os.path.join(db_dir, db_f)):
self.logger.info("Downloading bundle '{}' to '{}".format(ref, db_f))
with open(db_f, 'wb') as f_out:
with remote.checkout(ref) as f:
copy_file_or_flo(f, f_out, cb=cb)
f_out.flush()
self.checkin_bundle(db_f)
b = self.bundle(ref) # Should exist now.
b.dataset.data['remote_name'] = remote.short_name
b.dataset.upstream = remote.url
b.dstate = b.STATES.CHECKEDOUT
b.commit()
finally:
if b:
b.progress.close()
vid = b.identity.vid
return vid | [
"def",
"_checkin_remote_bundle",
"(",
"self",
",",
"remote",
",",
"ref",
")",
":",
"from",
"ambry",
".",
"bundle",
".",
"process",
"import",
"call_interval",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"from",
"ambry",
".",
"orm",
"... | Checkin a remote bundle from a remote
:param remote: a Remote object
:param ref: Any bundle reference
:return: The vid of the loaded bundle | [
"Checkin",
"a",
"remote",
"bundle",
"from",
"a",
"remote",
":",
"param",
"remote",
":",
"a",
"Remote",
"object",
":",
"param",
"ref",
":",
"Any",
"bundle",
"reference",
":",
"return",
":",
"The",
"vid",
"of",
"the",
"loaded",
"bundle"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L655-L712 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.remotes | def remotes(self):
"""Return the names and URLs of the remotes"""
from ambry.orm import Remote
for r in self.database.session.query(Remote).all():
if not r.short_name:
continue
yield self.remote(r.short_name) | python | def remotes(self):
"""Return the names and URLs of the remotes"""
from ambry.orm import Remote
for r in self.database.session.query(Remote).all():
if not r.short_name:
continue
yield self.remote(r.short_name) | [
"def",
"remotes",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
"import",
"Remote",
"for",
"r",
"in",
"self",
".",
"database",
".",
"session",
".",
"query",
"(",
"Remote",
")",
".",
"all",
"(",
")",
":",
"if",
"not",
"r",
".",
"short_name",
... | Return the names and URLs of the remotes | [
"Return",
"the",
"names",
"and",
"URLs",
"of",
"the",
"remotes"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L715-L722 |
CivicSpleen/ambry | ambry/library/__init__.py | Library._remote | def _remote(self, name):
"""Return a remote for which 'name' matches the short_name or url """
from ambry.orm import Remote
from sqlalchemy import or_
from ambry.orm.exc import NotFoundError
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
if not name.strip():
raise NotFoundError("Empty remote name")
try:
try:
r = self.database.session.query(Remote).filter(Remote.short_name == name).one()
except NoResultFound as e:
r = None
if not r:
r = self.database.session.query(Remote).filter(Remote.url == name).one()
except NoResultFound as e:
raise NotFoundError(str(e)+'; '+name)
except MultipleResultsFound as e:
self.logger.error("Got multiple results for search for remote '{}': {}".format(name, e))
return None
return r | python | def _remote(self, name):
"""Return a remote for which 'name' matches the short_name or url """
from ambry.orm import Remote
from sqlalchemy import or_
from ambry.orm.exc import NotFoundError
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
if not name.strip():
raise NotFoundError("Empty remote name")
try:
try:
r = self.database.session.query(Remote).filter(Remote.short_name == name).one()
except NoResultFound as e:
r = None
if not r:
r = self.database.session.query(Remote).filter(Remote.url == name).one()
except NoResultFound as e:
raise NotFoundError(str(e)+'; '+name)
except MultipleResultsFound as e:
self.logger.error("Got multiple results for search for remote '{}': {}".format(name, e))
return None
return r | [
"def",
"_remote",
"(",
"self",
",",
"name",
")",
":",
"from",
"ambry",
".",
"orm",
"import",
"Remote",
"from",
"sqlalchemy",
"import",
"or_",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"from",
"sqlalchemy",
".",
"orm",
".",
"exc"... | Return a remote for which 'name' matches the short_name or url | [
"Return",
"a",
"remote",
"for",
"which",
"name",
"matches",
"the",
"short_name",
"or",
"url"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L724-L749 |
CivicSpleen/ambry | ambry/library/__init__.py | Library._find_remote_bundle | def _find_remote_bundle(self, ref, remote_service_type='s3'):
"""
Locate a bundle, by any reference, among the configured remotes. The routine will
only look in the cache directory lists stored in the remotes, which must
be updated to be current.
:param ref:
:return: (remote,vname) or (None,None) if the ref is not found
"""
for r in self.remotes:
if remote_service_type and r.service != remote_service_type:
continue
if 'list' not in r.data:
continue
for k, v in r.data['list'].items():
if ref in v.values():
return (r, v['vname'])
return None, None | python | def _find_remote_bundle(self, ref, remote_service_type='s3'):
"""
Locate a bundle, by any reference, among the configured remotes. The routine will
only look in the cache directory lists stored in the remotes, which must
be updated to be current.
:param ref:
:return: (remote,vname) or (None,None) if the ref is not found
"""
for r in self.remotes:
if remote_service_type and r.service != remote_service_type:
continue
if 'list' not in r.data:
continue
for k, v in r.data['list'].items():
if ref in v.values():
return (r, v['vname'])
return None, None | [
"def",
"_find_remote_bundle",
"(",
"self",
",",
"ref",
",",
"remote_service_type",
"=",
"'s3'",
")",
":",
"for",
"r",
"in",
"self",
".",
"remotes",
":",
"if",
"remote_service_type",
"and",
"r",
".",
"service",
"!=",
"remote_service_type",
":",
"continue",
"i... | Locate a bundle, by any reference, among the configured remotes. The routine will
only look in the cache directory lists stored in the remotes, which must
be updated to be current.
:param ref:
:return: (remote,vname) or (None,None) if the ref is not found | [
"Locate",
"a",
"bundle",
"by",
"any",
"reference",
"among",
"the",
"configured",
"remotes",
".",
"The",
"routine",
"will",
"only",
"look",
"in",
"the",
"cache",
"directory",
"lists",
"stored",
"in",
"the",
"remotes",
"which",
"must",
"be",
"updated",
"to",
... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L825-L847 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.find_remote_bundle | def find_remote_bundle(self, ref, try_harder=None):
"""
Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache
directory lists stored in the remotes, which must be updated to be current.
:param vid: A bundle or partition reference, vid, or name
:param try_harder: If the reference isn't found, try parsing for an object id, or subsets of the name
:return: (remote,vname) or (None,None) if the ref is not found
"""
from ambry.identity import ObjectNumber
remote, vid = self._find_remote_bundle(ref)
if remote:
return (remote, vid)
if try_harder:
on = ObjectNumber.parse(vid)
if on:
raise NotImplementedError()
don = on.as_dataset
return self._find_remote_bundle(vid)
# Try subsets of a name, assuming it is a name
parts = ref.split('-')
for i in range(len(parts) - 1, 2, -1):
remote, vid = self._find_remote_bundle('-'.join(parts[:i]))
if remote:
return (remote, vid)
return (None, None) | python | def find_remote_bundle(self, ref, try_harder=None):
"""
Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache
directory lists stored in the remotes, which must be updated to be current.
:param vid: A bundle or partition reference, vid, or name
:param try_harder: If the reference isn't found, try parsing for an object id, or subsets of the name
:return: (remote,vname) or (None,None) if the ref is not found
"""
from ambry.identity import ObjectNumber
remote, vid = self._find_remote_bundle(ref)
if remote:
return (remote, vid)
if try_harder:
on = ObjectNumber.parse(vid)
if on:
raise NotImplementedError()
don = on.as_dataset
return self._find_remote_bundle(vid)
# Try subsets of a name, assuming it is a name
parts = ref.split('-')
for i in range(len(parts) - 1, 2, -1):
remote, vid = self._find_remote_bundle('-'.join(parts[:i]))
if remote:
return (remote, vid)
return (None, None) | [
"def",
"find_remote_bundle",
"(",
"self",
",",
"ref",
",",
"try_harder",
"=",
"None",
")",
":",
"from",
"ambry",
".",
"identity",
"import",
"ObjectNumber",
"remote",
",",
"vid",
"=",
"self",
".",
"_find_remote_bundle",
"(",
"ref",
")",
"if",
"remote",
":",... | Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache
directory lists stored in the remotes, which must be updated to be current.
:param vid: A bundle or partition reference, vid, or name
:param try_harder: If the reference isn't found, try parsing for an object id, or subsets of the name
:return: (remote,vname) or (None,None) if the ref is not found | [
"Locate",
"a",
"bundle",
"by",
"any",
"reference",
"among",
"the",
"configured",
"remotes",
".",
"The",
"routine",
"will",
"only",
"look",
"in",
"the",
"cache",
"directory",
"lists",
"stored",
"in",
"the",
"remotes",
"which",
"must",
"be",
"updated",
"to",
... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L849-L882 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.account | def account(self, url):
"""
Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
"""
from sqlalchemy.orm.exc import NoResultFound
from ambry.orm.exc import NotFoundError
from ambry.util import parse_url_to_dict
from ambry.orm import Account
pd = parse_url_to_dict(url)
# Old method of storing account information.
try:
act = self.database.session.query(Account).filter(Account.account_id == pd['netloc']).one()
act.secret_password = self._account_password
return act
except NoResultFound:
pass
# Try the remotes.
for r in self.remotes:
if url.startswith(r.url):
return r
raise NotFoundError("Did not find account for url: '{}' ".format(url)) | python | def account(self, url):
"""
Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
"""
from sqlalchemy.orm.exc import NoResultFound
from ambry.orm.exc import NotFoundError
from ambry.util import parse_url_to_dict
from ambry.orm import Account
pd = parse_url_to_dict(url)
# Old method of storing account information.
try:
act = self.database.session.query(Account).filter(Account.account_id == pd['netloc']).one()
act.secret_password = self._account_password
return act
except NoResultFound:
pass
# Try the remotes.
for r in self.remotes:
if url.startswith(r.url):
return r
raise NotFoundError("Did not find account for url: '{}' ".format(url)) | [
"def",
"account",
"(",
"self",
",",
"url",
")",
":",
"from",
"sqlalchemy",
".",
"orm",
".",
"exc",
"import",
"NoResultFound",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"from",
"ambry",
".",
"util",
"import",
"parse_url_to_dict",
"... | Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return: | [
"Return",
"accounts",
"references",
"for",
"the",
"given",
"account",
"id",
".",
":",
"param",
"account_id",
":",
":",
"param",
"accounts_password",
":",
"The",
"password",
"for",
"decrypting",
"the",
"secret",
":",
"return",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L897-L925 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.accounts | def accounts(self):
"""
Return an account reference
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
"""
d = {}
if False and not self._account_password:
from ambry.dbexceptions import ConfigurationError
raise ConfigurationError(
"Can't access accounts without setting an account password"
" either in the accounts.password config, or in the AMBRY_ACCOUNT_PASSWORD"
" env var.")
for act in self.database.session.query(Account).all():
if self._account_password:
act.secret_password = self._account_password
e = act.dict
a_id = e['account_id']
d[a_id] = e
return d | python | def accounts(self):
"""
Return an account reference
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
"""
d = {}
if False and not self._account_password:
from ambry.dbexceptions import ConfigurationError
raise ConfigurationError(
"Can't access accounts without setting an account password"
" either in the accounts.password config, or in the AMBRY_ACCOUNT_PASSWORD"
" env var.")
for act in self.database.session.query(Account).all():
if self._account_password:
act.secret_password = self._account_password
e = act.dict
a_id = e['account_id']
d[a_id] = e
return d | [
"def",
"accounts",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"if",
"False",
"and",
"not",
"self",
".",
"_account_password",
":",
"from",
"ambry",
".",
"dbexceptions",
"import",
"ConfigurationError",
"raise",
"ConfigurationError",
"(",
"\"Can't access accounts w... | Return an account reference
:param account_id:
:param accounts_password: The password for decrypting the secret
:return: | [
"Return",
"an",
"account",
"reference",
":",
"param",
"account_id",
":",
":",
"param",
"accounts_password",
":",
"The",
"password",
"for",
"decrypting",
"the",
"secret",
":",
"return",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L937-L960 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.number | def number(self, assignment_class=None, namespace='d'):
"""
Return a new number.
:param assignment_class: Determines the length of the number. Possible values are 'authority' (3 characters) ,
'registered' (5) , 'unregistered' (7) and 'self' (9). Self assigned numbers are random and acquired locally,
while the other assignment classes use the number server defined in the configuration. If None,
then look in the number server configuration for one of the class keys, starting
with the longest class and working to the shortest.
:param namespace: The namespace character, the first character in the number. Can be one of 'd', 'x' or 'b'
:return:
"""
if assignment_class == 'self':
# When 'self' is explicit, don't look for number server config
return str(DatasetNumber())
elif assignment_class is None:
try:
nsconfig = self.services['numbers']
except ConfigurationError:
# A missing configuration is equivalent to 'self'
self.logger.error('No number server configuration; returning self assigned number')
return str(DatasetNumber())
for assignment_class in ('self', 'unregistered', 'registered', 'authority'):
if assignment_class+'-key' in nsconfig:
break
# For the case where the number configuratoin references a self-assigned key
if assignment_class == 'self':
return str(DatasetNumber())
else:
try:
nsconfig = self.services['numbers']
except ConfigurationError:
raise ConfigurationError('No number server configuration')
if assignment_class + '-key' not in nsconfig:
raise ConfigurationError(
'Assignment class {} not number server config'.format(assignment_class))
try:
key = nsconfig[assignment_class + '-key']
config = {
'key': key,
'host': nsconfig['host'],
'port': nsconfig.get('port', 80)
}
ns = NumberServer(**config)
n = str(next(ns))
self.logger.info('Got number from number server: {}'.format(n))
except HTTPError as e:
self.logger.error('Failed to get number from number server for key: {}'.format(key, e.message))
self.logger.error('Using self-generated number. There is no problem with this, '
'but they are longer than centrally generated numbers.')
n = str(DatasetNumber())
return n | python | def number(self, assignment_class=None, namespace='d'):
"""
Return a new number.
:param assignment_class: Determines the length of the number. Possible values are 'authority' (3 characters) ,
'registered' (5) , 'unregistered' (7) and 'self' (9). Self assigned numbers are random and acquired locally,
while the other assignment classes use the number server defined in the configuration. If None,
then look in the number server configuration for one of the class keys, starting
with the longest class and working to the shortest.
:param namespace: The namespace character, the first character in the number. Can be one of 'd', 'x' or 'b'
:return:
"""
if assignment_class == 'self':
# When 'self' is explicit, don't look for number server config
return str(DatasetNumber())
elif assignment_class is None:
try:
nsconfig = self.services['numbers']
except ConfigurationError:
# A missing configuration is equivalent to 'self'
self.logger.error('No number server configuration; returning self assigned number')
return str(DatasetNumber())
for assignment_class in ('self', 'unregistered', 'registered', 'authority'):
if assignment_class+'-key' in nsconfig:
break
# For the case where the number configuratoin references a self-assigned key
if assignment_class == 'self':
return str(DatasetNumber())
else:
try:
nsconfig = self.services['numbers']
except ConfigurationError:
raise ConfigurationError('No number server configuration')
if assignment_class + '-key' not in nsconfig:
raise ConfigurationError(
'Assignment class {} not number server config'.format(assignment_class))
try:
key = nsconfig[assignment_class + '-key']
config = {
'key': key,
'host': nsconfig['host'],
'port': nsconfig.get('port', 80)
}
ns = NumberServer(**config)
n = str(next(ns))
self.logger.info('Got number from number server: {}'.format(n))
except HTTPError as e:
self.logger.error('Failed to get number from number server for key: {}'.format(key, e.message))
self.logger.error('Using self-generated number. There is no problem with this, '
'but they are longer than centrally generated numbers.')
n = str(DatasetNumber())
return n | [
"def",
"number",
"(",
"self",
",",
"assignment_class",
"=",
"None",
",",
"namespace",
"=",
"'d'",
")",
":",
"if",
"assignment_class",
"==",
"'self'",
":",
"# When 'self' is explicit, don't look for number server config",
"return",
"str",
"(",
"DatasetNumber",
"(",
"... | Return a new number.
:param assignment_class: Determines the length of the number. Possible values are 'authority' (3 characters) ,
'registered' (5) , 'unregistered' (7) and 'self' (9). Self assigned numbers are random and acquired locally,
while the other assignment classes use the number server defined in the configuration. If None,
then look in the number server configuration for one of the class keys, starting
with the longest class and working to the shortest.
:param namespace: The namespace character, the first character in the number. Can be one of 'd', 'x' or 'b'
:return: | [
"Return",
"a",
"new",
"number",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L995-L1060 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.edit_history | def edit_history(self):
"""Return config record information about the most recent bundle accesses and operations"""
ret = self._db.session\
.query(Config)\
.filter(Config.type == 'buildstate')\
.filter(Config.group == 'access')\
.filter(Config.key == 'last')\
.order_by(Config.modified.desc())\
.all()
return ret | python | def edit_history(self):
"""Return config record information about the most recent bundle accesses and operations"""
ret = self._db.session\
.query(Config)\
.filter(Config.type == 'buildstate')\
.filter(Config.group == 'access')\
.filter(Config.key == 'last')\
.order_by(Config.modified.desc())\
.all()
return ret | [
"def",
"edit_history",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_db",
".",
"session",
".",
"query",
"(",
"Config",
")",
".",
"filter",
"(",
"Config",
".",
"type",
"==",
"'buildstate'",
")",
".",
"filter",
"(",
"Config",
".",
"group",
"==",
... | Return config record information about the most recent bundle accesses and operations | [
"Return",
"config",
"record",
"information",
"about",
"the",
"most",
"recent",
"bundle",
"accesses",
"and",
"operations"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L1062-L1072 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.import_bundles | def import_bundles(self, dir, detach=False, force=False):
"""
Import bundles from a directory
:param dir:
:return:
"""
import yaml
fs = fsopendir(dir)
bundles = []
for f in fs.walkfiles(wildcard='bundle.yaml'):
self.logger.info('Visiting {}'.format(f))
config = yaml.load(fs.getcontents(f))
if not config:
self.logger.error("Failed to get a valid bundle configuration from '{}'".format(f))
bid = config['identity']['id']
try:
b = self.bundle(bid)
except NotFoundError:
b = None
if not b:
b = self.new_from_bundle_config(config)
self.logger.info('{} Loading New'.format(b.identity.fqname))
else:
self.logger.info('{} Loading Existing'.format(b.identity.fqname))
source_url = os.path.dirname(fs.getsyspath(f))
b.set_file_system(source_url=source_url)
self.logger.info('{} Loading from {}'.format(b.identity.fqname, source_url))
b.sync_in()
if detach:
self.logger.info('{} Detaching'.format(b.identity.fqname))
b.set_file_system(source_url=None)
if force:
self.logger.info('{} Sync out'.format(b.identity.fqname))
# FIXME. It won't actually sync out until re-starting the bundle.
# The source_file_system is probably cached
b = self.bundle(bid)
b.sync_out()
bundles.append(b)
b.close()
return bundles | python | def import_bundles(self, dir, detach=False, force=False):
"""
Import bundles from a directory
:param dir:
:return:
"""
import yaml
fs = fsopendir(dir)
bundles = []
for f in fs.walkfiles(wildcard='bundle.yaml'):
self.logger.info('Visiting {}'.format(f))
config = yaml.load(fs.getcontents(f))
if not config:
self.logger.error("Failed to get a valid bundle configuration from '{}'".format(f))
bid = config['identity']['id']
try:
b = self.bundle(bid)
except NotFoundError:
b = None
if not b:
b = self.new_from_bundle_config(config)
self.logger.info('{} Loading New'.format(b.identity.fqname))
else:
self.logger.info('{} Loading Existing'.format(b.identity.fqname))
source_url = os.path.dirname(fs.getsyspath(f))
b.set_file_system(source_url=source_url)
self.logger.info('{} Loading from {}'.format(b.identity.fqname, source_url))
b.sync_in()
if detach:
self.logger.info('{} Detaching'.format(b.identity.fqname))
b.set_file_system(source_url=None)
if force:
self.logger.info('{} Sync out'.format(b.identity.fqname))
# FIXME. It won't actually sync out until re-starting the bundle.
# The source_file_system is probably cached
b = self.bundle(bid)
b.sync_out()
bundles.append(b)
b.close()
return bundles | [
"def",
"import_bundles",
"(",
"self",
",",
"dir",
",",
"detach",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"import",
"yaml",
"fs",
"=",
"fsopendir",
"(",
"dir",
")",
"bundles",
"=",
"[",
"]",
"for",
"f",
"in",
"fs",
".",
"walkfiles",
"(",... | Import bundles from a directory
:param dir:
:return: | [
"Import",
"bundles",
"from",
"a",
"directory"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L1106-L1161 |
CivicSpleen/ambry | ambry/library/__init__.py | Library.process_pool | def process_pool(self, limited_run=False):
"""Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value"""
from multiprocessing import cpu_count
from ambry.bundle.concurrent import Pool, init_library
if self.processes:
cpus = self.processes
else:
cpus = cpu_count()
self.logger.info('Starting MP pool with {} processors'.format(cpus))
return Pool(self, processes=cpus, initializer=init_library,
maxtasksperchild=1,
initargs=[self.database.dsn, self._account_password, limited_run]) | python | def process_pool(self, limited_run=False):
"""Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value"""
from multiprocessing import cpu_count
from ambry.bundle.concurrent import Pool, init_library
if self.processes:
cpus = self.processes
else:
cpus = cpu_count()
self.logger.info('Starting MP pool with {} processors'.format(cpus))
return Pool(self, processes=cpus, initializer=init_library,
maxtasksperchild=1,
initargs=[self.database.dsn, self._account_password, limited_run]) | [
"def",
"process_pool",
"(",
"self",
",",
"limited_run",
"=",
"False",
")",
":",
"from",
"multiprocessing",
"import",
"cpu_count",
"from",
"ambry",
".",
"bundle",
".",
"concurrent",
"import",
"Pool",
",",
"init_library",
"if",
"self",
".",
"processes",
":",
"... | Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value | [
"Return",
"a",
"pool",
"for",
"multiprocess",
"operations",
"sized",
"either",
"to",
"the",
"number",
"of",
"CPUS",
"or",
"a",
"configured",
"value"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/__init__.py#L1163-L1177 |
CivicSpleen/ambry | ambry/etl/codegen.py | file_loc | def file_loc():
"""Return file and line number"""
import sys
import inspect
try:
raise Exception
except:
file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:])
line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno
return "{}:{}".format(file_, line_) | python | def file_loc():
"""Return file and line number"""
import sys
import inspect
try:
raise Exception
except:
file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:])
line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno
return "{}:{}".format(file_, line_) | [
"def",
"file_loc",
"(",
")",
":",
"import",
"sys",
"import",
"inspect",
"try",
":",
"raise",
"Exception",
"except",
":",
"file_",
"=",
"'.../'",
"+",
"'/'",
".",
"join",
"(",
"(",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_code",
".",
"co_filena... | Return file and line number | [
"Return",
"file",
"and",
"line",
"number"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/codegen.py#L12-L21 |
CivicSpleen/ambry | ambry/etl/codegen.py | make_row_processors | def make_row_processors(bundle, source_headers, dest_table, env):
"""
Make multiple row processors for all of the columns in a table.
:param source_headers:
:return:
"""
dest_headers = [c.name for c in dest_table.columns]
row_processors = []
out = [file_header]
transforms = list(dest_table.transforms)
column_names = []
column_types = []
for i, segments in enumerate(transforms):
seg_funcs = []
for col_num, (segment, column) in enumerate(zip(segments, dest_table.columns), 1):
if not segment:
seg_funcs.append('row[{}]'.format(col_num - 1))
continue
assert column
assert column.name == segment['column'].name
col_name = column.name
preamble, try_lines, exception = make_stack(env, i, segment)
assert col_num == column.sequence_id, (dest_table.name, col_num, column.sequence_id)
column_names.append(col_name)
column_types.append(column.datatype)
f_name = "{table_name}_{column_name}_{stage}".format(
table_name=dest_table.name,
column_name=col_name,
stage=i
)
exception = (exception if exception else
('raise ValueError("Failed to cast column \'{}\', in '
'function {}, value \'{}\': {}".format(header_d,"') + f_name +
'", v.encode(\'ascii\', \'replace\'), exc) ) ')
try:
i_s = source_headers.index(column.name)
header_s = column.name
v = 'row[{}]'.format(i_s)
except ValueError as e:
i_s = 'None'
header_s = None
v = 'None' if col_num > 1 else 'row_n' # Give the id column the row number
i_d = column.sequence_id - 1
header_d = column.name
template_args = dict(
f_name=f_name,
table_name=dest_table.name,
column_name=col_name,
stage=i,
i_s=i_s,
i_d=i_d,
header_s=header_s,
header_d=header_d,
v=v,
exception=indent + exception,
stack='\n'.join(indent + l for l in try_lines),
col_args = '# col_args not implemented yet'
)
seg_funcs.append(f_name
+ ('({v}, {i_s}, {i_d}, {header_s}, \'{header_d}\', '
'row, row_n, errors, scratch, accumulator, pipe, bundle, source)')
.format(v=v, i_s=i_s, i_d=i_d, header_s="'" + header_s + "'" if header_s else 'None',
header_d=header_d))
out.append('\n'.join(preamble))
out.append(column_template.format(**template_args))
source_headers = dest_headers
stack = '\n'.join("{}{}, # {}".format(indent,l,cn)
for l,cn, dt in zip(seg_funcs, column_names, column_types))
out.append(row_template.format(
table=dest_table.name,
stage=i,
stack=stack
))
row_processors.append('row_{table}_{stage}'.format(stage=i, table=dest_table.name))
# Add the final datatype cast, which is done seperately to avoid an unecessary function call.
stack = '\n'.join("{}cast_{}(row[{}], '{}', errors),".format(indent, c.datatype, i, c.name)
for i, c in enumerate(dest_table.columns) )
out.append(row_template.format(
table=dest_table.name,
stage=len(transforms),
stack=stack
))
row_processors.append('row_{table}_{stage}'.format(stage=len(transforms), table=dest_table.name))
out.append('row_processors = [{}]'.format(','.join(row_processors)))
return '\n'.join(out) | python | def make_row_processors(bundle, source_headers, dest_table, env):
"""
Make multiple row processors for all of the columns in a table.
:param source_headers:
:return:
"""
dest_headers = [c.name for c in dest_table.columns]
row_processors = []
out = [file_header]
transforms = list(dest_table.transforms)
column_names = []
column_types = []
for i, segments in enumerate(transforms):
seg_funcs = []
for col_num, (segment, column) in enumerate(zip(segments, dest_table.columns), 1):
if not segment:
seg_funcs.append('row[{}]'.format(col_num - 1))
continue
assert column
assert column.name == segment['column'].name
col_name = column.name
preamble, try_lines, exception = make_stack(env, i, segment)
assert col_num == column.sequence_id, (dest_table.name, col_num, column.sequence_id)
column_names.append(col_name)
column_types.append(column.datatype)
f_name = "{table_name}_{column_name}_{stage}".format(
table_name=dest_table.name,
column_name=col_name,
stage=i
)
exception = (exception if exception else
('raise ValueError("Failed to cast column \'{}\', in '
'function {}, value \'{}\': {}".format(header_d,"') + f_name +
'", v.encode(\'ascii\', \'replace\'), exc) ) ')
try:
i_s = source_headers.index(column.name)
header_s = column.name
v = 'row[{}]'.format(i_s)
except ValueError as e:
i_s = 'None'
header_s = None
v = 'None' if col_num > 1 else 'row_n' # Give the id column the row number
i_d = column.sequence_id - 1
header_d = column.name
template_args = dict(
f_name=f_name,
table_name=dest_table.name,
column_name=col_name,
stage=i,
i_s=i_s,
i_d=i_d,
header_s=header_s,
header_d=header_d,
v=v,
exception=indent + exception,
stack='\n'.join(indent + l for l in try_lines),
col_args = '# col_args not implemented yet'
)
seg_funcs.append(f_name
+ ('({v}, {i_s}, {i_d}, {header_s}, \'{header_d}\', '
'row, row_n, errors, scratch, accumulator, pipe, bundle, source)')
.format(v=v, i_s=i_s, i_d=i_d, header_s="'" + header_s + "'" if header_s else 'None',
header_d=header_d))
out.append('\n'.join(preamble))
out.append(column_template.format(**template_args))
source_headers = dest_headers
stack = '\n'.join("{}{}, # {}".format(indent,l,cn)
for l,cn, dt in zip(seg_funcs, column_names, column_types))
out.append(row_template.format(
table=dest_table.name,
stage=i,
stack=stack
))
row_processors.append('row_{table}_{stage}'.format(stage=i, table=dest_table.name))
# Add the final datatype cast, which is done seperately to avoid an unecessary function call.
stack = '\n'.join("{}cast_{}(row[{}], '{}', errors),".format(indent, c.datatype, i, c.name)
for i, c in enumerate(dest_table.columns) )
out.append(row_template.format(
table=dest_table.name,
stage=len(transforms),
stack=stack
))
row_processors.append('row_{table}_{stage}'.format(stage=len(transforms), table=dest_table.name))
out.append('row_processors = [{}]'.format(','.join(row_processors)))
return '\n'.join(out) | [
"def",
"make_row_processors",
"(",
"bundle",
",",
"source_headers",
",",
"dest_table",
",",
"env",
")",
":",
"dest_headers",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"dest_table",
".",
"columns",
"]",
"row_processors",
"=",
"[",
"]",
"out",
"=",
"["... | Make multiple row processors for all of the columns in a table.
:param source_headers:
:return: | [
"Make",
"multiple",
"row",
"processors",
"for",
"all",
"of",
"the",
"columns",
"in",
"a",
"table",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/codegen.py#L84-L202 |
CivicSpleen/ambry | ambry/etl/codegen.py | calling_code | def calling_code(f, f_name=None, raise_for_missing=True):
"""Return the code string for calling a function. """
import inspect
from ambry.dbexceptions import ConfigurationError
if inspect.isclass(f):
try:
args = inspect.getargspec(f.__init__).args
except TypeError as e:
raise TypeError("Failed to inspect {}: {}".format(f, e))
else:
args = inspect.getargspec(f).args
if len(args) > 1 and args[0] == 'self':
args = args[1:]
for a in args:
if a not in all_args + ('exception',): # exception arg is only for exception handlers
if raise_for_missing:
raise ConfigurationError('Caster code {} has unknown argument '
'name: \'{}\'. Must be one of: {} '.format(f, a, ','.join(all_args)))
arg_map = {e: e for e in var_args}
args = [arg_map.get(a, a) for a in args]
return "{}({})".format(f_name if f_name else f.__name__, ','.join(args)) | python | def calling_code(f, f_name=None, raise_for_missing=True):
"""Return the code string for calling a function. """
import inspect
from ambry.dbexceptions import ConfigurationError
if inspect.isclass(f):
try:
args = inspect.getargspec(f.__init__).args
except TypeError as e:
raise TypeError("Failed to inspect {}: {}".format(f, e))
else:
args = inspect.getargspec(f).args
if len(args) > 1 and args[0] == 'self':
args = args[1:]
for a in args:
if a not in all_args + ('exception',): # exception arg is only for exception handlers
if raise_for_missing:
raise ConfigurationError('Caster code {} has unknown argument '
'name: \'{}\'. Must be one of: {} '.format(f, a, ','.join(all_args)))
arg_map = {e: e for e in var_args}
args = [arg_map.get(a, a) for a in args]
return "{}({})".format(f_name if f_name else f.__name__, ','.join(args)) | [
"def",
"calling_code",
"(",
"f",
",",
"f_name",
"=",
"None",
",",
"raise_for_missing",
"=",
"True",
")",
":",
"import",
"inspect",
"from",
"ambry",
".",
"dbexceptions",
"import",
"ConfigurationError",
"if",
"inspect",
".",
"isclass",
"(",
"f",
")",
":",
"t... | Return the code string for calling a function. | [
"Return",
"the",
"code",
"string",
"for",
"calling",
"a",
"function",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/codegen.py#L204-L231 |
CivicSpleen/ambry | ambry/etl/codegen.py | make_stack | def make_stack(env, stage, segment):
"""For each transform segment, create the code in the try/except block with the
assignements for pipes in the segment """
import string
import random
from ambry.valuetype import ValueType
column = segment['column']
def make_line(column, t):
preamble = []
line_t = "v = {} # {}"
if isinstance(t, type) and issubclass(t, ValueType): # A valuetype class, from the datatype column.
try:
cc, fl = calling_code(t, t.__name__), file_loc()
except TypeError:
cc, fl = "{}(v)".format(t.__name__), file_loc()
preamble.append("{} = resolve_value_type('{}') # {}".format(t.__name__, t.vt_code, fl))
elif isinstance(t, type): # A python type, from the datatype columns.
cc, fl= "parse_{}(v, header_d)".format(t.__name__), file_loc()
elif callable(env.get(t)): # Transform function
cc, fl = calling_code(env.get(t), t), file_loc()
else: # A transform generator, or python code.
rnd = (''.join(random.choice(string.ascii_lowercase) for _ in range(6)))
name = 'tg_{}_{}_{}'.format(column.name, stage, rnd)
try:
a, b, fl = rewrite_tg(env, name, t)
except CodeGenError as e:
raise CodeGenError("Failed to re-write pipe code '{}' in column '{}.{}': {} "
.format(t, column.table.name, column.name, e))
cc = str(a)
if b:
preamble.append("{} = {} # {}".format(name, b, fl))
line = line_t.format(cc, fl)
return line, preamble
preamble = []
try_lines = []
for t in [segment['init'], segment['datatype']] + segment['transforms']:
if not t:
continue
line, col_preamble = make_line(column, t)
preamble += col_preamble
try_lines.append(line)
exception = None
if segment['exception']:
exception, col_preamble = make_line(column, segment['exception'])
if len(try_lines) == 0:
try_lines.append('pass # Empty pipe segment')
assert len(try_lines) > 0, column.name
return preamble, try_lines, exception | python | def make_stack(env, stage, segment):
"""For each transform segment, create the code in the try/except block with the
assignements for pipes in the segment """
import string
import random
from ambry.valuetype import ValueType
column = segment['column']
def make_line(column, t):
preamble = []
line_t = "v = {} # {}"
if isinstance(t, type) and issubclass(t, ValueType): # A valuetype class, from the datatype column.
try:
cc, fl = calling_code(t, t.__name__), file_loc()
except TypeError:
cc, fl = "{}(v)".format(t.__name__), file_loc()
preamble.append("{} = resolve_value_type('{}') # {}".format(t.__name__, t.vt_code, fl))
elif isinstance(t, type): # A python type, from the datatype columns.
cc, fl= "parse_{}(v, header_d)".format(t.__name__), file_loc()
elif callable(env.get(t)): # Transform function
cc, fl = calling_code(env.get(t), t), file_loc()
else: # A transform generator, or python code.
rnd = (''.join(random.choice(string.ascii_lowercase) for _ in range(6)))
name = 'tg_{}_{}_{}'.format(column.name, stage, rnd)
try:
a, b, fl = rewrite_tg(env, name, t)
except CodeGenError as e:
raise CodeGenError("Failed to re-write pipe code '{}' in column '{}.{}': {} "
.format(t, column.table.name, column.name, e))
cc = str(a)
if b:
preamble.append("{} = {} # {}".format(name, b, fl))
line = line_t.format(cc, fl)
return line, preamble
preamble = []
try_lines = []
for t in [segment['init'], segment['datatype']] + segment['transforms']:
if not t:
continue
line, col_preamble = make_line(column, t)
preamble += col_preamble
try_lines.append(line)
exception = None
if segment['exception']:
exception, col_preamble = make_line(column, segment['exception'])
if len(try_lines) == 0:
try_lines.append('pass # Empty pipe segment')
assert len(try_lines) > 0, column.name
return preamble, try_lines, exception | [
"def",
"make_stack",
"(",
"env",
",",
"stage",
",",
"segment",
")",
":",
"import",
"string",
"import",
"random",
"from",
"ambry",
".",
"valuetype",
"import",
"ValueType",
"column",
"=",
"segment",
"[",
"'column'",
"]",
"def",
"make_line",
"(",
"column",
",... | For each transform segment, create the code in the try/except block with the
assignements for pipes in the segment | [
"For",
"each",
"transform",
"segment",
"create",
"the",
"code",
"in",
"the",
"try",
"/",
"except",
"block",
"with",
"the",
"assignements",
"for",
"pipes",
"in",
"the",
"segment"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/codegen.py#L234-L307 |
CivicSpleen/ambry | ambry/etl/codegen.py | rewrite_tg | def rewrite_tg(env, tg_name, code):
"""Re-write a transform generating function pipe specification by extracting the tranform generating part,
and replacing it with the generated transform. so:
tgen(a,b,c).foo.bar
becomes:
tg = tgen(a,b,c)
tg.foo.bar
"""
visitor = ReplaceTG(env, tg_name)
assert visitor.tg_name
tree = visitor.visit(ast.parse(code))
if visitor.loc:
loc = ' #' + visitor.loc
else:
loc = file_loc() # The AST visitor didn't match a call node
if visitor.trans_gen:
tg = meta.dump_python_source(visitor.trans_gen).strip()
else:
tg = None
return meta.dump_python_source(tree).strip(), tg, loc | python | def rewrite_tg(env, tg_name, code):
"""Re-write a transform generating function pipe specification by extracting the tranform generating part,
and replacing it with the generated transform. so:
tgen(a,b,c).foo.bar
becomes:
tg = tgen(a,b,c)
tg.foo.bar
"""
visitor = ReplaceTG(env, tg_name)
assert visitor.tg_name
tree = visitor.visit(ast.parse(code))
if visitor.loc:
loc = ' #' + visitor.loc
else:
loc = file_loc() # The AST visitor didn't match a call node
if visitor.trans_gen:
tg = meta.dump_python_source(visitor.trans_gen).strip()
else:
tg = None
return meta.dump_python_source(tree).strip(), tg, loc | [
"def",
"rewrite_tg",
"(",
"env",
",",
"tg_name",
",",
"code",
")",
":",
"visitor",
"=",
"ReplaceTG",
"(",
"env",
",",
"tg_name",
")",
"assert",
"visitor",
".",
"tg_name",
"tree",
"=",
"visitor",
".",
"visit",
"(",
"ast",
".",
"parse",
"(",
"code",
")... | Re-write a transform generating function pipe specification by extracting the tranform generating part,
and replacing it with the generated transform. so:
tgen(a,b,c).foo.bar
becomes:
tg = tgen(a,b,c)
tg.foo.bar | [
"Re",
"-",
"write",
"a",
"transform",
"generating",
"function",
"pipe",
"specification",
"by",
"extracting",
"the",
"tranform",
"generating",
"part",
"and",
"replacing",
"it",
"with",
"the",
"generated",
"transform",
".",
"so",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/codegen.py#L425-L454 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/utils.py | PriorityQueue.push | def push(self, el):
""" Put a new element in the queue. """
count = next(self.counter)
heapq.heappush(self._queue, (el, count)) | python | def push(self, el):
""" Put a new element in the queue. """
count = next(self.counter)
heapq.heappush(self._queue, (el, count)) | [
"def",
"push",
"(",
"self",
",",
"el",
")",
":",
"count",
"=",
"next",
"(",
"self",
".",
"counter",
")",
"heapq",
".",
"heappush",
"(",
"self",
".",
"_queue",
",",
"(",
"el",
",",
"count",
")",
")"
] | Put a new element in the queue. | [
"Put",
"a",
"new",
"element",
"in",
"the",
"queue",
"."
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/utils.py#L38-L41 |
CivicSpleen/ambry | ambry/orm/partition.py | PartitionDisplay.geo_description | def geo_description(self):
"""Return a description of the geographic extents, using the largest scale
space and grain coverages"""
sc = self._p.space_coverage
gc = self._p.grain_coverage
if sc and gc:
if parse_to_gvid(gc[0]).level == 'state' and parse_to_gvid(sc[0]).level == 'state':
return parse_to_gvid(sc[0]).geo_name
else:
return ("{} in {}".format(
parse_to_gvid(gc[0]).level_plural.title(),
parse_to_gvid(sc[0]).geo_name))
elif sc:
return parse_to_gvid(sc[0]).geo_name.title()
elif sc:
return parse_to_gvid(gc[0]).level_plural.title()
else:
return '' | python | def geo_description(self):
"""Return a description of the geographic extents, using the largest scale
space and grain coverages"""
sc = self._p.space_coverage
gc = self._p.grain_coverage
if sc and gc:
if parse_to_gvid(gc[0]).level == 'state' and parse_to_gvid(sc[0]).level == 'state':
return parse_to_gvid(sc[0]).geo_name
else:
return ("{} in {}".format(
parse_to_gvid(gc[0]).level_plural.title(),
parse_to_gvid(sc[0]).geo_name))
elif sc:
return parse_to_gvid(sc[0]).geo_name.title()
elif sc:
return parse_to_gvid(gc[0]).level_plural.title()
else:
return '' | [
"def",
"geo_description",
"(",
"self",
")",
":",
"sc",
"=",
"self",
".",
"_p",
".",
"space_coverage",
"gc",
"=",
"self",
".",
"_p",
".",
"grain_coverage",
"if",
"sc",
"and",
"gc",
":",
"if",
"parse_to_gvid",
"(",
"gc",
"[",
"0",
"]",
")",
".",
"lev... | Return a description of the geographic extents, using the largest scale
space and grain coverages | [
"Return",
"a",
"description",
"of",
"the",
"geographic",
"extents",
"using",
"the",
"largest",
"scale",
"space",
"and",
"grain",
"coverages"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L56-L75 |
CivicSpleen/ambry | ambry/orm/partition.py | PartitionDisplay.time_description | def time_description(self):
"""String description of the year or year range"""
tc = [t for t in self._p.time_coverage if t]
if not tc:
return ''
mn = min(tc)
mx = max(tc)
if not mn and not mx:
return ''
elif mn == mx:
return mn
else:
return "{} to {}".format(mn, mx) | python | def time_description(self):
"""String description of the year or year range"""
tc = [t for t in self._p.time_coverage if t]
if not tc:
return ''
mn = min(tc)
mx = max(tc)
if not mn and not mx:
return ''
elif mn == mx:
return mn
else:
return "{} to {}".format(mn, mx) | [
"def",
"time_description",
"(",
"self",
")",
":",
"tc",
"=",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"_p",
".",
"time_coverage",
"if",
"t",
"]",
"if",
"not",
"tc",
":",
"return",
"''",
"mn",
"=",
"min",
"(",
"tc",
")",
"mx",
"=",
"max",
"(",
... | String description of the year or year range | [
"String",
"description",
"of",
"the",
"year",
"or",
"year",
"range"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L78-L94 |
CivicSpleen/ambry | ambry/orm/partition.py | PartitionDisplay.sub_description | def sub_description(self):
"""Time and space dscription"""
gd = self.geo_description
td = self.time_description
if gd and td:
return '{}, {}. {} Rows.'.format(gd, td, self._p.count)
elif gd:
return '{}. {} Rows.'.format(gd, self._p.count)
elif td:
return '{}. {} Rows.'.format(td, self._p.count)
else:
return '{} Rows.'.format(self._p.count) | python | def sub_description(self):
"""Time and space dscription"""
gd = self.geo_description
td = self.time_description
if gd and td:
return '{}, {}. {} Rows.'.format(gd, td, self._p.count)
elif gd:
return '{}. {} Rows.'.format(gd, self._p.count)
elif td:
return '{}. {} Rows.'.format(td, self._p.count)
else:
return '{} Rows.'.format(self._p.count) | [
"def",
"sub_description",
"(",
"self",
")",
":",
"gd",
"=",
"self",
".",
"geo_description",
"td",
"=",
"self",
".",
"time_description",
"if",
"gd",
"and",
"td",
":",
"return",
"'{}, {}. {} Rows.'",
".",
"format",
"(",
"gd",
",",
"td",
",",
"self",
".",
... | Time and space dscription | [
"Time",
"and",
"space",
"dscription"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L97-L109 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.identity | def identity(self):
"""Return this partition information as a PartitionId."""
if self.dataset is None:
# The relationship will be null until the object is committed
s = object_session(self)
ds = s.query(Dataset).filter(Dataset.id_ == self.d_id).one()
else:
ds = self.dataset
d = {
'id': self.id,
'vid': self.vid,
'name': self.name,
'vname': self.vname,
'ref': self.ref,
'space': self.space,
'time': self.time,
'table': self.table_name,
'grain': self.grain,
'variant': self.variant,
'segment': self.segment,
'format': self.format if self.format else 'db'
}
return PartitionIdentity.from_dict(dict(list(ds.dict.items()) + list(d.items()))) | python | def identity(self):
"""Return this partition information as a PartitionId."""
if self.dataset is None:
# The relationship will be null until the object is committed
s = object_session(self)
ds = s.query(Dataset).filter(Dataset.id_ == self.d_id).one()
else:
ds = self.dataset
d = {
'id': self.id,
'vid': self.vid,
'name': self.name,
'vname': self.vname,
'ref': self.ref,
'space': self.space,
'time': self.time,
'table': self.table_name,
'grain': self.grain,
'variant': self.variant,
'segment': self.segment,
'format': self.format if self.format else 'db'
}
return PartitionIdentity.from_dict(dict(list(ds.dict.items()) + list(d.items()))) | [
"def",
"identity",
"(",
"self",
")",
":",
"if",
"self",
".",
"dataset",
"is",
"None",
":",
"# The relationship will be null until the object is committed",
"s",
"=",
"object_session",
"(",
"self",
")",
"ds",
"=",
"s",
".",
"query",
"(",
"Dataset",
")",
".",
... | Return this partition information as a PartitionId. | [
"Return",
"this",
"partition",
"information",
"as",
"a",
"PartitionId",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L202-L228 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.set_coverage | def set_coverage(self, stats):
""""Extract time space and grain coverage from the stats and store them in the partition"""
from ambry.util.datestimes import expand_to_years
scov = set()
tcov = set()
grains = set()
def summarize_maybe(gvid):
try:
return parse_to_gvid(gvid).summarize()
except:
return None
def simplifiy_maybe(values, column):
parsed = []
for gvid in values:
# The gvid should not be a st
if gvid is None or gvid == 'None':
continue
try:
parsed.append(parse_to_gvid(gvid))
except ValueError as e:
if self._bundle:
self._bundle.warn("While analyzing geo coverage in final partition stage, " +
"Failed to parse gvid '{}' in {}.{}: {}"
.format(str(gvid), column.table.name, column.name, e))
try:
return isimplify(parsed)
except:
return None
def int_maybe(year):
try:
return int(year)
except:
return None
for c in self.table.columns:
if c.name not in stats:
continue
try:
if stats[c.name].is_gvid or stats[c.name].is_geoid:
scov |= set(x for x in simplifiy_maybe(stats[c.name].uniques, c))
grains |= set(summarize_maybe(gvid) for gvid in stats[c.name].uniques)
elif stats[c.name].is_year:
tcov |= set(int_maybe(x) for x in stats[c.name].uniques)
elif stats[c.name].is_date:
# The fuzzy=True argument allows ignoring the '-' char in dates produced by .isoformat()
try:
tcov |= set(parser.parse(x, fuzzy=True).year if isinstance(x, string_types) else x.year for x in
stats[c.name].uniques)
except ValueError:
pass
except Exception as e:
self._bundle.error("Failed to set coverage for column '{}', partition '{}': {}"
.format(c.name, self.identity.vname, e))
raise
# Space Coverage
if 'source_data' in self.data:
for source_name, source in list(self.data['source_data'].items()):
scov.add(self.parse_gvid_or_place(source['space']))
if self.identity.space: # And from the partition name
try:
scov.add(self.parse_gvid_or_place(self.identity.space))
except ValueError:
# Couldn't parse the space as a GVid
pass
# For geo_coverage, only includes the higher level summary levels, counties, states,
# places and urban areas.
self.space_coverage = sorted([str(x) for x in scov if bool(x) and x.sl
in (10, 40, 50, 60, 160, 400)])
#
# Time Coverage
# From the source
# If there was a time value in the source that this partition was created from, then
# add it to the years.
if 'source_data' in self.data:
for source_name, source in list(self.data['source_data'].items()):
if 'time' in source:
for year in expand_to_years(source['time']):
if year:
tcov.add(year)
# From the partition name
if self.identity.name.time:
for year in expand_to_years(self.identity.name.time):
if year:
tcov.add(year)
self.time_coverage = [t for t in tcov if t]
#
# Grains
if 'source_data' in self.data:
for source_name, source in list(self.data['source_data'].items()):
if 'grain' in source:
grains.add(source['grain'])
self.grain_coverage = sorted(str(g) for g in grains if g) | python | def set_coverage(self, stats):
""""Extract time space and grain coverage from the stats and store them in the partition"""
from ambry.util.datestimes import expand_to_years
scov = set()
tcov = set()
grains = set()
def summarize_maybe(gvid):
try:
return parse_to_gvid(gvid).summarize()
except:
return None
def simplifiy_maybe(values, column):
parsed = []
for gvid in values:
# The gvid should not be a st
if gvid is None or gvid == 'None':
continue
try:
parsed.append(parse_to_gvid(gvid))
except ValueError as e:
if self._bundle:
self._bundle.warn("While analyzing geo coverage in final partition stage, " +
"Failed to parse gvid '{}' in {}.{}: {}"
.format(str(gvid), column.table.name, column.name, e))
try:
return isimplify(parsed)
except:
return None
def int_maybe(year):
try:
return int(year)
except:
return None
for c in self.table.columns:
if c.name not in stats:
continue
try:
if stats[c.name].is_gvid or stats[c.name].is_geoid:
scov |= set(x for x in simplifiy_maybe(stats[c.name].uniques, c))
grains |= set(summarize_maybe(gvid) for gvid in stats[c.name].uniques)
elif stats[c.name].is_year:
tcov |= set(int_maybe(x) for x in stats[c.name].uniques)
elif stats[c.name].is_date:
# The fuzzy=True argument allows ignoring the '-' char in dates produced by .isoformat()
try:
tcov |= set(parser.parse(x, fuzzy=True).year if isinstance(x, string_types) else x.year for x in
stats[c.name].uniques)
except ValueError:
pass
except Exception as e:
self._bundle.error("Failed to set coverage for column '{}', partition '{}': {}"
.format(c.name, self.identity.vname, e))
raise
# Space Coverage
if 'source_data' in self.data:
for source_name, source in list(self.data['source_data'].items()):
scov.add(self.parse_gvid_or_place(source['space']))
if self.identity.space: # And from the partition name
try:
scov.add(self.parse_gvid_or_place(self.identity.space))
except ValueError:
# Couldn't parse the space as a GVid
pass
# For geo_coverage, only includes the higher level summary levels, counties, states,
# places and urban areas.
self.space_coverage = sorted([str(x) for x in scov if bool(x) and x.sl
in (10, 40, 50, 60, 160, 400)])
#
# Time Coverage
# From the source
# If there was a time value in the source that this partition was created from, then
# add it to the years.
if 'source_data' in self.data:
for source_name, source in list(self.data['source_data'].items()):
if 'time' in source:
for year in expand_to_years(source['time']):
if year:
tcov.add(year)
# From the partition name
if self.identity.name.time:
for year in expand_to_years(self.identity.name.time):
if year:
tcov.add(year)
self.time_coverage = [t for t in tcov if t]
#
# Grains
if 'source_data' in self.data:
for source_name, source in list(self.data['source_data'].items()):
if 'grain' in source:
grains.add(source['grain'])
self.grain_coverage = sorted(str(g) for g in grains if g) | [
"def",
"set_coverage",
"(",
"self",
",",
"stats",
")",
":",
"from",
"ambry",
".",
"util",
".",
"datestimes",
"import",
"expand_to_years",
"scov",
"=",
"set",
"(",
")",
"tcov",
"=",
"set",
"(",
")",
"grains",
"=",
"set",
"(",
")",
"def",
"summarize_mayb... | Extract time space and grain coverage from the stats and store them in the partition | [
"Extract",
"time",
"space",
"and",
"grain",
"coverage",
"from",
"the",
"stats",
"and",
"store",
"them",
"in",
"the",
"partition"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L282-L397 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.detail_dict | def detail_dict(self):
"""A more detailed dict that includes the descriptions, sub descriptions, table
and columns."""
d = self.dict
def aug_col(c):
d = c.dict
d['stats'] = [s.dict for s in c.stats]
return d
d['table'] = self.table.dict
d['table']['columns'] = [aug_col(c) for c in self.table.columns]
return d | python | def detail_dict(self):
"""A more detailed dict that includes the descriptions, sub descriptions, table
and columns."""
d = self.dict
def aug_col(c):
d = c.dict
d['stats'] = [s.dict for s in c.stats]
return d
d['table'] = self.table.dict
d['table']['columns'] = [aug_col(c) for c in self.table.columns]
return d | [
"def",
"detail_dict",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"dict",
"def",
"aug_col",
"(",
"c",
")",
":",
"d",
"=",
"c",
".",
"dict",
"d",
"[",
"'stats'",
"]",
"=",
"[",
"s",
".",
"dict",
"for",
"s",
"in",
"c",
".",
"stats",
"]",
"r... | A more detailed dict that includes the descriptions, sub descriptions, table
and columns. | [
"A",
"more",
"detailed",
"dict",
"that",
"includes",
"the",
"descriptions",
"sub",
"descriptions",
"table",
"and",
"columns",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L420-L434 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.local_datafile | def local_datafile(self):
"""Return the datafile for this partition, from the build directory, the remote, or the warehouse"""
from ambry_sources import MPRowsFile
from fs.errors import ResourceNotFoundError
from ambry.orm.exc import NotFoundError
try:
return MPRowsFile(self._bundle.build_fs, self.cache_key)
except ResourceNotFoundError:
raise NotFoundError(
'Could not locate data file for partition {} (local)'.format(self.identity.fqname)) | python | def local_datafile(self):
"""Return the datafile for this partition, from the build directory, the remote, or the warehouse"""
from ambry_sources import MPRowsFile
from fs.errors import ResourceNotFoundError
from ambry.orm.exc import NotFoundError
try:
return MPRowsFile(self._bundle.build_fs, self.cache_key)
except ResourceNotFoundError:
raise NotFoundError(
'Could not locate data file for partition {} (local)'.format(self.identity.fqname)) | [
"def",
"local_datafile",
"(",
"self",
")",
":",
"from",
"ambry_sources",
"import",
"MPRowsFile",
"from",
"fs",
".",
"errors",
"import",
"ResourceNotFoundError",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"try",
":",
"return",
"MPRowsFile... | Return the datafile for this partition, from the build directory, the remote, or the warehouse | [
"Return",
"the",
"datafile",
"for",
"this",
"partition",
"from",
"the",
"build",
"directory",
"the",
"remote",
"or",
"the",
"warehouse"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L598-L609 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.remote | def remote(self):
"""
Return the remote for this partition
:return:
"""
from ambry.exc import NotFoundError
ds = self.dataset
if 'remote_name' not in ds.data:
raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.fqname))
return self._bundle.library.remote(ds.data['remote_name']) | python | def remote(self):
"""
Return the remote for this partition
:return:
"""
from ambry.exc import NotFoundError
ds = self.dataset
if 'remote_name' not in ds.data:
raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.fqname))
return self._bundle.library.remote(ds.data['remote_name']) | [
"def",
"remote",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"exc",
"import",
"NotFoundError",
"ds",
"=",
"self",
".",
"dataset",
"if",
"'remote_name'",
"not",
"in",
"ds",
".",
"data",
":",
"raise",
"NotFoundError",
"(",
"'Could not determine remote for parti... | Return the remote for this partition
:return: | [
"Return",
"the",
"remote",
"for",
"this",
"partition"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L612-L626 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.is_local | def is_local(self):
"""Return true is the partition file is local"""
from ambry.orm.exc import NotFoundError
try:
if self.local_datafile.exists:
return True
except NotFoundError:
pass
return False | python | def is_local(self):
"""Return true is the partition file is local"""
from ambry.orm.exc import NotFoundError
try:
if self.local_datafile.exists:
return True
except NotFoundError:
pass
return False | [
"def",
"is_local",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"try",
":",
"if",
"self",
".",
"local_datafile",
".",
"exists",
":",
"return",
"True",
"except",
"NotFoundError",
":",
"pass",
"return",
"False"
] | Return true is the partition file is local | [
"Return",
"true",
"is",
"the",
"partition",
"file",
"is",
"local"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L659-L668 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.localize | def localize(self, ps=None):
"""Copy a non-local partition file to the local build directory"""
from filelock import FileLock
from ambry.util import ensure_dir_exists
from ambry_sources import MPRowsFile
from fs.errors import ResourceNotFoundError
if self.is_local:
return
local = self._bundle.build_fs
b = self._bundle.library.bundle(self.identity.as_dataset().vid)
remote = self._bundle.library.remote(b)
lock_path = local.getsyspath(self.cache_key + '.lock')
ensure_dir_exists(lock_path)
lock = FileLock(lock_path)
if ps:
ps.add_update(message='Localizing {}'.format(self.identity.name),
partition=self,
item_type='bytes',
state='downloading')
if ps:
def progress(bts):
if ps.rec.item_total is None:
ps.rec.item_count = 0
if not ps.rec.data:
ps.rec.data = {} # Should not need to do this.
return self
item_count = ps.rec.item_count + bts
ps.rec.data['updates'] = ps.rec.data.get('updates', 0) + 1
if ps.rec.data['updates'] % 32 == 1:
ps.update(message='Localizing {}'.format(self.identity.name),
item_count=item_count)
else:
from ambry.bundle.process import call_interval
@call_interval(5)
def progress(bts):
self._bundle.log("Localizing {}. {} bytes downloaded".format(self.vname, bts))
def exception_cb(e):
raise e
with lock:
# FIXME! This won't work with remote ( http) API, only FS ( s3:, file:)
if self.is_local:
return self
try:
with remote.fs.open(self.cache_key + MPRowsFile.EXTENSION, 'rb') as f:
event = local.setcontents_async(self.cache_key + MPRowsFile.EXTENSION,
f,
progress_callback=progress,
error_callback=exception_cb)
event.wait()
if ps:
ps.update_done()
except ResourceNotFoundError as e:
from ambry.orm.exc import NotFoundError
raise NotFoundError("Failed to get MPRfile '{}' from {}: {} "
.format(self.cache_key, remote.fs, e))
return self | python | def localize(self, ps=None):
"""Copy a non-local partition file to the local build directory"""
from filelock import FileLock
from ambry.util import ensure_dir_exists
from ambry_sources import MPRowsFile
from fs.errors import ResourceNotFoundError
if self.is_local:
return
local = self._bundle.build_fs
b = self._bundle.library.bundle(self.identity.as_dataset().vid)
remote = self._bundle.library.remote(b)
lock_path = local.getsyspath(self.cache_key + '.lock')
ensure_dir_exists(lock_path)
lock = FileLock(lock_path)
if ps:
ps.add_update(message='Localizing {}'.format(self.identity.name),
partition=self,
item_type='bytes',
state='downloading')
if ps:
def progress(bts):
if ps.rec.item_total is None:
ps.rec.item_count = 0
if not ps.rec.data:
ps.rec.data = {} # Should not need to do this.
return self
item_count = ps.rec.item_count + bts
ps.rec.data['updates'] = ps.rec.data.get('updates', 0) + 1
if ps.rec.data['updates'] % 32 == 1:
ps.update(message='Localizing {}'.format(self.identity.name),
item_count=item_count)
else:
from ambry.bundle.process import call_interval
@call_interval(5)
def progress(bts):
self._bundle.log("Localizing {}. {} bytes downloaded".format(self.vname, bts))
def exception_cb(e):
raise e
with lock:
# FIXME! This won't work with remote ( http) API, only FS ( s3:, file:)
if self.is_local:
return self
try:
with remote.fs.open(self.cache_key + MPRowsFile.EXTENSION, 'rb') as f:
event = local.setcontents_async(self.cache_key + MPRowsFile.EXTENSION,
f,
progress_callback=progress,
error_callback=exception_cb)
event.wait()
if ps:
ps.update_done()
except ResourceNotFoundError as e:
from ambry.orm.exc import NotFoundError
raise NotFoundError("Failed to get MPRfile '{}' from {}: {} "
.format(self.cache_key, remote.fs, e))
return self | [
"def",
"localize",
"(",
"self",
",",
"ps",
"=",
"None",
")",
":",
"from",
"filelock",
"import",
"FileLock",
"from",
"ambry",
".",
"util",
"import",
"ensure_dir_exists",
"from",
"ambry_sources",
"import",
"MPRowsFile",
"from",
"fs",
".",
"errors",
"import",
"... | Copy a non-local partition file to the local build directory | [
"Copy",
"a",
"non",
"-",
"local",
"partition",
"file",
"to",
"the",
"local",
"build",
"directory"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L670-L742 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.reader | def reader(self):
from ambry.orm.exc import NotFoundError
from fs.errors import ResourceNotFoundError
"""The reader for the datafile"""
try:
return self.datafile.reader
except ResourceNotFoundError:
raise NotFoundError("Failed to find partition file, '{}' "
.format(self.datafile.path)) | python | def reader(self):
from ambry.orm.exc import NotFoundError
from fs.errors import ResourceNotFoundError
"""The reader for the datafile"""
try:
return self.datafile.reader
except ResourceNotFoundError:
raise NotFoundError("Failed to find partition file, '{}' "
.format(self.datafile.path)) | [
"def",
"reader",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"from",
"fs",
".",
"errors",
"import",
"ResourceNotFoundError",
"try",
":",
"return",
"self",
".",
"datafile",
".",
"reader",
"except",
"ResourceNotFo... | The reader for the datafile | [
"The",
"reader",
"for",
"the",
"datafile"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L745-L754 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.select | def select(self, predicate=None, headers=None):
"""
Select rows from the reader using a predicate to select rows and and itemgetter to return a
subset of elements
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param headers: If defined, a list or tuple of header names to return from each row
:return: iterable of results
WARNING: This routine works from the reader iterator, which returns RowProxy objects. RowProxy objects
are reused, so if you construct a list directly from the output from this method, the list will have
multiple copies of a single RowProxy, which will have as an inner row the last result row. If you will
be directly constructing a list, use a getter that extracts the inner row, or which converts the RowProxy
to a dict:
list(s.datafile.select(lambda r: r.stusab == 'CA', lambda r: r.dict ))
"""
# FIXME; in Python 3, use yield from
with self.reader as r:
for row in r.select(predicate, headers):
yield row | python | def select(self, predicate=None, headers=None):
"""
Select rows from the reader using a predicate to select rows and and itemgetter to return a
subset of elements
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param headers: If defined, a list or tuple of header names to return from each row
:return: iterable of results
WARNING: This routine works from the reader iterator, which returns RowProxy objects. RowProxy objects
are reused, so if you construct a list directly from the output from this method, the list will have
multiple copies of a single RowProxy, which will have as an inner row the last result row. If you will
be directly constructing a list, use a getter that extracts the inner row, or which converts the RowProxy
to a dict:
list(s.datafile.select(lambda r: r.stusab == 'CA', lambda r: r.dict ))
"""
# FIXME; in Python 3, use yield from
with self.reader as r:
for row in r.select(predicate, headers):
yield row | [
"def",
"select",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"# FIXME; in Python 3, use yield from",
"with",
"self",
".",
"reader",
"as",
"r",
":",
"for",
"row",
"in",
"r",
".",
"select",
"(",
"predicate",
",",
"hea... | Select rows from the reader using a predicate to select rows and and itemgetter to return a
subset of elements
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param headers: If defined, a list or tuple of header names to return from each row
:return: iterable of results
WARNING: This routine works from the reader iterator, which returns RowProxy objects. RowProxy objects
are reused, so if you construct a list directly from the output from this method, the list will have
multiple copies of a single RowProxy, which will have as an inner row the last result row. If you will
be directly constructing a list, use a getter that extracts the inner row, or which converts the RowProxy
to a dict:
list(s.datafile.select(lambda r: r.stusab == 'CA', lambda r: r.dict )) | [
"Select",
"rows",
"from",
"the",
"reader",
"using",
"a",
"predicate",
"to",
"select",
"rows",
"and",
"and",
"itemgetter",
"to",
"return",
"a",
"subset",
"of",
"elements",
":",
"param",
"predicate",
":",
"If",
"defined",
"a",
"callable",
"that",
"is",
"call... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L756-L778 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.analysis | def analysis(self):
"""Return an AnalysisPartition proxy, which wraps this partition to provide acess to
dataframes, shapely shapes and other analysis services"""
if isinstance(self, PartitionProxy):
return AnalysisPartition(self._obj)
else:
return AnalysisPartition(self) | python | def analysis(self):
"""Return an AnalysisPartition proxy, which wraps this partition to provide acess to
dataframes, shapely shapes and other analysis services"""
if isinstance(self, PartitionProxy):
return AnalysisPartition(self._obj)
else:
return AnalysisPartition(self) | [
"def",
"analysis",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"PartitionProxy",
")",
":",
"return",
"AnalysisPartition",
"(",
"self",
".",
"_obj",
")",
"else",
":",
"return",
"AnalysisPartition",
"(",
"self",
")"
] | Return an AnalysisPartition proxy, which wraps this partition to provide acess to
dataframes, shapely shapes and other analysis services | [
"Return",
"an",
"AnalysisPartition",
"proxy",
"which",
"wraps",
"this",
"partition",
"to",
"provide",
"acess",
"to",
"dataframes",
"shapely",
"shapes",
"and",
"other",
"analysis",
"services"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L790-L796 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.measuredim | def measuredim(self):
"""Return a MeasureDimension proxy, which wraps the partition to provide access to
columns in terms of measures and dimensions"""
if isinstance(self, PartitionProxy):
return MeasureDimensionPartition(self._obj)
else:
return MeasureDimensionPartition(self) | python | def measuredim(self):
"""Return a MeasureDimension proxy, which wraps the partition to provide access to
columns in terms of measures and dimensions"""
if isinstance(self, PartitionProxy):
return MeasureDimensionPartition(self._obj)
else:
return MeasureDimensionPartition(self) | [
"def",
"measuredim",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"PartitionProxy",
")",
":",
"return",
"MeasureDimensionPartition",
"(",
"self",
".",
"_obj",
")",
"else",
":",
"return",
"MeasureDimensionPartition",
"(",
"self",
")"
] | Return a MeasureDimension proxy, which wraps the partition to provide access to
columns in terms of measures and dimensions | [
"Return",
"a",
"MeasureDimension",
"proxy",
"which",
"wraps",
"the",
"partition",
"to",
"provide",
"access",
"to",
"columns",
"in",
"terms",
"of",
"measures",
"and",
"dimensions"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L799-L806 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.update_id | def update_id(self, sequence_id=None):
"""Alter the sequence id, and all of the names and ids derived from it. This
often needs to be done after an IntegrityError in a multiprocessing run"""
if sequence_id:
self.sequence_id = sequence_id
self._set_ids(force=True)
if self.dataset:
self._update_names() | python | def update_id(self, sequence_id=None):
"""Alter the sequence id, and all of the names and ids derived from it. This
often needs to be done after an IntegrityError in a multiprocessing run"""
if sequence_id:
self.sequence_id = sequence_id
self._set_ids(force=True)
if self.dataset:
self._update_names() | [
"def",
"update_id",
"(",
"self",
",",
"sequence_id",
"=",
"None",
")",
":",
"if",
"sequence_id",
":",
"self",
".",
"sequence_id",
"=",
"sequence_id",
"self",
".",
"_set_ids",
"(",
"force",
"=",
"True",
")",
"if",
"self",
".",
"dataset",
":",
"self",
".... | Alter the sequence id, and all of the names and ids derived from it. This
often needs to be done after an IntegrityError in a multiprocessing run | [
"Alter",
"the",
"sequence",
"id",
"and",
"all",
"of",
"the",
"names",
"and",
"ids",
"derived",
"from",
"it",
".",
"This",
"often",
"needs",
"to",
"be",
"done",
"after",
"an",
"IntegrityError",
"in",
"a",
"multiprocessing",
"run"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L810-L820 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition._update_names | def _update_names(self):
"""Update the derived names"""
d = dict(
table=self.table_name,
time=self.time,
space=self.space,
grain=self.grain,
variant=self.variant,
segment=self.segment
)
assert self.dataset
name = PartialPartitionName(**d).promote(self.dataset.identity.name)
self.name = str(name.name)
self.vname = str(name.vname)
self.cache_key = name.cache_key
self.fqname = str(self.identity.fqname) | python | def _update_names(self):
"""Update the derived names"""
d = dict(
table=self.table_name,
time=self.time,
space=self.space,
grain=self.grain,
variant=self.variant,
segment=self.segment
)
assert self.dataset
name = PartialPartitionName(**d).promote(self.dataset.identity.name)
self.name = str(name.name)
self.vname = str(name.vname)
self.cache_key = name.cache_key
self.fqname = str(self.identity.fqname) | [
"def",
"_update_names",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"table",
"=",
"self",
".",
"table_name",
",",
"time",
"=",
"self",
".",
"time",
",",
"space",
"=",
"self",
".",
"space",
",",
"grain",
"=",
"self",
".",
"grain",
",",
"variant",
... | Update the derived names | [
"Update",
"the",
"derived",
"names"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L841-L860 |
CivicSpleen/ambry | ambry/orm/partition.py | Partition.before_insert | def before_insert(mapper, conn, target):
"""event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_"""
target._set_ids()
if target.name and target.vname and target.cache_key and target.fqname and not target.dataset:
return
Partition.before_update(mapper, conn, target) | python | def before_insert(mapper, conn, target):
"""event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_"""
target._set_ids()
if target.name and target.vname and target.cache_key and target.fqname and not target.dataset:
return
Partition.before_update(mapper, conn, target) | [
"def",
"before_insert",
"(",
"mapper",
",",
"conn",
",",
"target",
")",
":",
"target",
".",
"_set_ids",
"(",
")",
"if",
"target",
".",
"name",
"and",
"target",
".",
"vname",
"and",
"target",
".",
"cache_key",
"and",
"target",
".",
"fqname",
"and",
"not... | event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_ | [
"event",
".",
"listen",
"method",
"for",
"Sqlalchemy",
"to",
"set",
"the",
"sequence",
"for",
"this",
"object",
"and",
"create",
"an",
"ObjectNumber",
"value",
"for",
"the",
"id_"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L863-L872 |
CivicSpleen/ambry | ambry/orm/partition.py | AnalysisPartition.dataframe | def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None):
"""Return the partition as a Pandas dataframe
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param filtered_columns: If defined, the value is a dict of column names and
associated values. Only rows where all of the named columms have the given values will be returned.
Setting the argument will overwrite any value set for the predicate
:param columns: A list or tuple of column names to return
:return: Pandas dataframe
"""
from operator import itemgetter
from ambry.pands import AmbryDataFrame
df_class = df_class or AmbryDataFrame
if columns:
ig = itemgetter(*columns)
else:
ig = None
columns = self.table.header
if filtered_columns:
def maybe_quote(v):
from six import string_types
if isinstance(v, string_types):
return '"{}"'.format(v)
else:
return v
code = ' and '.join("row.{} == {}".format(k, maybe_quote(v))
for k, v in filtered_columns.items())
predicate = eval('lambda row: {}'.format(code))
if predicate:
def yielder():
for row in self.reader:
if predicate(row):
if ig:
yield ig(row)
else:
yield row.dict
df = df_class(yielder(), columns=columns, partition=self.measuredim)
return df
else:
def yielder():
for row in self.reader:
yield row.values()
# Put column names in header order
columns = [c for c in self.table.header if c in columns]
return df_class(yielder(), columns=columns, partition=self.measuredim) | python | def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None):
"""Return the partition as a Pandas dataframe
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param filtered_columns: If defined, the value is a dict of column names and
associated values. Only rows where all of the named columms have the given values will be returned.
Setting the argument will overwrite any value set for the predicate
:param columns: A list or tuple of column names to return
:return: Pandas dataframe
"""
from operator import itemgetter
from ambry.pands import AmbryDataFrame
df_class = df_class or AmbryDataFrame
if columns:
ig = itemgetter(*columns)
else:
ig = None
columns = self.table.header
if filtered_columns:
def maybe_quote(v):
from six import string_types
if isinstance(v, string_types):
return '"{}"'.format(v)
else:
return v
code = ' and '.join("row.{} == {}".format(k, maybe_quote(v))
for k, v in filtered_columns.items())
predicate = eval('lambda row: {}'.format(code))
if predicate:
def yielder():
for row in self.reader:
if predicate(row):
if ig:
yield ig(row)
else:
yield row.dict
df = df_class(yielder(), columns=columns, partition=self.measuredim)
return df
else:
def yielder():
for row in self.reader:
yield row.values()
# Put column names in header order
columns = [c for c in self.table.header if c in columns]
return df_class(yielder(), columns=columns, partition=self.measuredim) | [
"def",
"dataframe",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"filtered_columns",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"df_class",
"=",
"None",
")",
":",
"from",
"operator",
"import",
"itemgetter",
"from",
"ambry",
".",
"pands",
"import",
... | Return the partition as a Pandas dataframe
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param filtered_columns: If defined, the value is a dict of column names and
associated values. Only rows where all of the named columms have the given values will be returned.
Setting the argument will overwrite any value set for the predicate
:param columns: A list or tuple of column names to return
:return: Pandas dataframe | [
"Return",
"the",
"partition",
"as",
"a",
"Pandas",
"dataframe"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L923-L985 |
CivicSpleen/ambry | ambry/orm/partition.py | AnalysisPartition.shapes | def shapes(self, simplify=None, predicate=None):
"""
Return geodata as a list of Shapely shapes
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:return: A list of Shapely objects
"""
from shapely.wkt import loads
if not predicate:
predicate = lambda row: True
if simplify:
return [loads(row.geometry).simplify(simplify) for row in self if predicate(row)]
else:
return [loads(row.geometry) for row in self if predicate(row)] | python | def shapes(self, simplify=None, predicate=None):
"""
Return geodata as a list of Shapely shapes
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:return: A list of Shapely objects
"""
from shapely.wkt import loads
if not predicate:
predicate = lambda row: True
if simplify:
return [loads(row.geometry).simplify(simplify) for row in self if predicate(row)]
else:
return [loads(row.geometry) for row in self if predicate(row)] | [
"def",
"shapes",
"(",
"self",
",",
"simplify",
"=",
"None",
",",
"predicate",
"=",
"None",
")",
":",
"from",
"shapely",
".",
"wkt",
"import",
"loads",
"if",
"not",
"predicate",
":",
"predicate",
"=",
"lambda",
"row",
":",
"True",
"if",
"simplify",
":",... | Return geodata as a list of Shapely shapes
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:return: A list of Shapely objects | [
"Return",
"geodata",
"as",
"a",
"list",
"of",
"Shapely",
"shapes"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1022-L1040 |
CivicSpleen/ambry | ambry/orm/partition.py | AnalysisPartition.patches | def patches(self, basemap, simplify=None, predicate=None, args_f=None, **kwargs):
"""
Return geodata as a list of Matplotlib patches
:param basemap: A mpl_toolkits.basemap.Basemap
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:param args_f: A function that takes a row and returns a dict of additional args for the Patch constructor
:param kwargs: Additional args to be passed to the descartes Path constructor
:return: A list of patch objects
"""
from descartes import PolygonPatch
from shapely.wkt import loads
from shapely.ops import transform
if not predicate:
predicate = lambda row: True
def map_xform(x, y, z=None):
return basemap(x, y)
def make_patch(shape, row):
args = dict(kwargs.items())
if args_f:
args.update(args_f(row))
return PolygonPatch(transform(map_xform, shape), **args)
def yield_patches(row):
if simplify:
shape = loads(row.geometry).simplify(simplify)
else:
shape = loads(row.geometry)
if shape.geom_type == 'MultiPolygon':
for subshape in shape.geoms:
yield make_patch(subshape, row)
else:
yield make_patch(shape, row)
return [patch for row in self if predicate(row)
for patch in yield_patches(row)] | python | def patches(self, basemap, simplify=None, predicate=None, args_f=None, **kwargs):
"""
Return geodata as a list of Matplotlib patches
:param basemap: A mpl_toolkits.basemap.Basemap
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:param args_f: A function that takes a row and returns a dict of additional args for the Patch constructor
:param kwargs: Additional args to be passed to the descartes Path constructor
:return: A list of patch objects
"""
from descartes import PolygonPatch
from shapely.wkt import loads
from shapely.ops import transform
if not predicate:
predicate = lambda row: True
def map_xform(x, y, z=None):
return basemap(x, y)
def make_patch(shape, row):
args = dict(kwargs.items())
if args_f:
args.update(args_f(row))
return PolygonPatch(transform(map_xform, shape), **args)
def yield_patches(row):
if simplify:
shape = loads(row.geometry).simplify(simplify)
else:
shape = loads(row.geometry)
if shape.geom_type == 'MultiPolygon':
for subshape in shape.geoms:
yield make_patch(subshape, row)
else:
yield make_patch(shape, row)
return [patch for row in self if predicate(row)
for patch in yield_patches(row)] | [
"def",
"patches",
"(",
"self",
",",
"basemap",
",",
"simplify",
"=",
"None",
",",
"predicate",
"=",
"None",
",",
"args_f",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"descartes",
"import",
"PolygonPatch",
"from",
"shapely",
".",
"wkt",
"im... | Return geodata as a list of Matplotlib patches
:param basemap: A mpl_toolkits.basemap.Basemap
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:param args_f: A function that takes a row and returns a dict of additional args for the Patch constructor
:param kwargs: Additional args to be passed to the descartes Path constructor
:return: A list of patch objects | [
"Return",
"geodata",
"as",
"a",
"list",
"of",
"Matplotlib",
"patches"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1042-L1087 |
CivicSpleen/ambry | ambry/orm/partition.py | MeasureDimensionPartition.measures | def measures(self):
"""Iterate over all measures"""
from ambry.valuetype.core import ROLE
return [c for c in self.columns if c.role == ROLE.MEASURE] | python | def measures(self):
"""Iterate over all measures"""
from ambry.valuetype.core import ROLE
return [c for c in self.columns if c.role == ROLE.MEASURE] | [
"def",
"measures",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"columns",
"if",
"c",
".",
"role",
"==",
"ROLE",
".",
"MEASURE",
"]"
] | Iterate over all measures | [
"Iterate",
"over",
"all",
"measures"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1133-L1137 |
CivicSpleen/ambry | ambry/orm/partition.py | MeasureDimensionPartition.measure | def measure(self, vid):
"""Return a measure, given its vid or another reference"""
from ambry.orm import Column
if isinstance(vid, PartitionColumn):
return vid
elif isinstance(vid, Column):
return PartitionColumn(vid)
else:
return PartitionColumn(self.table.column(vid), self) | python | def measure(self, vid):
"""Return a measure, given its vid or another reference"""
from ambry.orm import Column
if isinstance(vid, PartitionColumn):
return vid
elif isinstance(vid, Column):
return PartitionColumn(vid)
else:
return PartitionColumn(self.table.column(vid), self) | [
"def",
"measure",
"(",
"self",
",",
"vid",
")",
":",
"from",
"ambry",
".",
"orm",
"import",
"Column",
"if",
"isinstance",
"(",
"vid",
",",
"PartitionColumn",
")",
":",
"return",
"vid",
"elif",
"isinstance",
"(",
"vid",
",",
"Column",
")",
":",
"return"... | Return a measure, given its vid or another reference | [
"Return",
"a",
"measure",
"given",
"its",
"vid",
"or",
"another",
"reference"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1139-L1149 |
CivicSpleen/ambry | ambry/orm/partition.py | MeasureDimensionPartition.dataframe | def dataframe(self, measure, p_dim, s_dim=None, filters={}, df_class=None):
"""
Return a dataframe with a sumse of the columns of the partition, including a measure and one
or two dimensions. FOr dimensions that have labels, the labels are included
The returned dataframe will have extra properties to describe the conversion:
* plot_axes: List of dimension names for the first and second axis
* labels: THe names of the label columns for the axes
* filtered: The `filters` dict
* floating: The names of primary dimensions that are not axes nor filtered
THere is also an iterator, `rows`, which returns the header and then all of the rows.
:param measure: The column names of one or more measures
:param p_dim: The primary dimension. This will be the index of the dataframe.
:param s_dim: a secondary dimension. The returned frame will be unstacked on this dimension
:param filters: A dict of column names, mapped to a column value, indicating rows to select. a
row that passes the filter must have the values for all given rows; the entries are ANDED
:param df_class:
:return: a Dataframe, with extra properties
"""
import numpy as np
measure = self.measure(measure)
p_dim = self.dimension(p_dim)
assert p_dim
if s_dim:
s_dim = self.dimension(s_dim)
columns = set([measure.name, p_dim.name])
if p_dim.label:
# For geographic datasets, also need the gvid
if p_dim.geoid:
columns.add(p_dim.geoid.name)
columns.add(p_dim.label.name)
if s_dim:
columns.add(s_dim.name)
if s_dim.label:
columns.add(s_dim.label.name)
def maybe_quote(v):
from six import string_types
if isinstance(v, string_types):
return '"{}"'.format(v)
else:
return v
# Create the predicate to filter out the filtered dimensions
if filters:
selected_filters = []
for k, v in filters.items():
if isinstance(v, dict):
# The filter is actually the whole set of possible options, so
# just select the first one
v = v.keys()[0]
selected_filters.append("row.{} == {}".format(k, maybe_quote(v)))
code = ' and '.join(selected_filters)
predicate = eval('lambda row: {}'.format(code))
else:
code = None
def predicate(row):
return True
df = self.analysis.dataframe(predicate, columns=columns, df_class=df_class)
if df is None or df.empty or len(df) == 0:
return None
# So we can track how many records were aggregated into each output row
df['_count'] = 1
def aggregate_string(x):
return ', '.join(set(str(e) for e in x))
agg = {
'_count': 'count',
}
for col_name in columns:
c = self.column(col_name)
# The primary and secondary dimensions are put into the index by groupby
if c.name == p_dim.name or (s_dim and c.name == s_dim.name):
continue
# FIXME! This will only work if the child is only level from the parent. Should
# have an acessor for the top level.
if c.parent and (c.parent == p_dim.name or (s_dim and c.parent == s_dim.name)):
continue
if c.is_measure:
agg[c.name] = np.mean
if c.is_dimension:
agg[c.name] = aggregate_string
plot_axes = [p_dim.name]
if s_dim:
plot_axes.append(s_dim.name)
df = df.groupby(list(columns - set([measure.name]))).agg(agg).reset_index()
df._metadata = ['plot_axes', 'filtered', 'floating', 'labels', 'dimension_set', 'measure']
df.plot_axes = [c for c in plot_axes]
df.filtered = filters
# Dimensions that are not specified as axes nor filtered
df.floating = list(set(c.name for c in self.primary_dimensions) -
set(df.filtered.keys()) -
set(df.plot_axes))
df.labels = [self.column(c).label.name if self.column(c).label else c for c in df.plot_axes]
df.dimension_set = self.dimension_set(p_dim, s_dim=s_dim)
df.measure = measure.name
def rows(self):
yield ['id'] + list(df.columns)
for t in df.itertuples():
yield list(t)
# Really should not do this, but I don't want to re-build the dataframe with another
# class
df.__class__.rows = property(rows)
return df | python | def dataframe(self, measure, p_dim, s_dim=None, filters={}, df_class=None):
"""
Return a dataframe with a sumse of the columns of the partition, including a measure and one
or two dimensions. FOr dimensions that have labels, the labels are included
The returned dataframe will have extra properties to describe the conversion:
* plot_axes: List of dimension names for the first and second axis
* labels: THe names of the label columns for the axes
* filtered: The `filters` dict
* floating: The names of primary dimensions that are not axes nor filtered
THere is also an iterator, `rows`, which returns the header and then all of the rows.
:param measure: The column names of one or more measures
:param p_dim: The primary dimension. This will be the index of the dataframe.
:param s_dim: a secondary dimension. The returned frame will be unstacked on this dimension
:param filters: A dict of column names, mapped to a column value, indicating rows to select. a
row that passes the filter must have the values for all given rows; the entries are ANDED
:param df_class:
:return: a Dataframe, with extra properties
"""
import numpy as np
measure = self.measure(measure)
p_dim = self.dimension(p_dim)
assert p_dim
if s_dim:
s_dim = self.dimension(s_dim)
columns = set([measure.name, p_dim.name])
if p_dim.label:
# For geographic datasets, also need the gvid
if p_dim.geoid:
columns.add(p_dim.geoid.name)
columns.add(p_dim.label.name)
if s_dim:
columns.add(s_dim.name)
if s_dim.label:
columns.add(s_dim.label.name)
def maybe_quote(v):
from six import string_types
if isinstance(v, string_types):
return '"{}"'.format(v)
else:
return v
# Create the predicate to filter out the filtered dimensions
if filters:
selected_filters = []
for k, v in filters.items():
if isinstance(v, dict):
# The filter is actually the whole set of possible options, so
# just select the first one
v = v.keys()[0]
selected_filters.append("row.{} == {}".format(k, maybe_quote(v)))
code = ' and '.join(selected_filters)
predicate = eval('lambda row: {}'.format(code))
else:
code = None
def predicate(row):
return True
df = self.analysis.dataframe(predicate, columns=columns, df_class=df_class)
if df is None or df.empty or len(df) == 0:
return None
# So we can track how many records were aggregated into each output row
df['_count'] = 1
def aggregate_string(x):
return ', '.join(set(str(e) for e in x))
agg = {
'_count': 'count',
}
for col_name in columns:
c = self.column(col_name)
# The primary and secondary dimensions are put into the index by groupby
if c.name == p_dim.name or (s_dim and c.name == s_dim.name):
continue
# FIXME! This will only work if the child is only level from the parent. Should
# have an acessor for the top level.
if c.parent and (c.parent == p_dim.name or (s_dim and c.parent == s_dim.name)):
continue
if c.is_measure:
agg[c.name] = np.mean
if c.is_dimension:
agg[c.name] = aggregate_string
plot_axes = [p_dim.name]
if s_dim:
plot_axes.append(s_dim.name)
df = df.groupby(list(columns - set([measure.name]))).agg(agg).reset_index()
df._metadata = ['plot_axes', 'filtered', 'floating', 'labels', 'dimension_set', 'measure']
df.plot_axes = [c for c in plot_axes]
df.filtered = filters
# Dimensions that are not specified as axes nor filtered
df.floating = list(set(c.name for c in self.primary_dimensions) -
set(df.filtered.keys()) -
set(df.plot_axes))
df.labels = [self.column(c).label.name if self.column(c).label else c for c in df.plot_axes]
df.dimension_set = self.dimension_set(p_dim, s_dim=s_dim)
df.measure = measure.name
def rows(self):
yield ['id'] + list(df.columns)
for t in df.itertuples():
yield list(t)
# Really should not do this, but I don't want to re-build the dataframe with another
# class
df.__class__.rows = property(rows)
return df | [
"def",
"dataframe",
"(",
"self",
",",
"measure",
",",
"p_dim",
",",
"s_dim",
"=",
"None",
",",
"filters",
"=",
"{",
"}",
",",
"df_class",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"measure",
"=",
"self",
".",
"measure",
"(",
"measure",
... | Return a dataframe with a sumse of the columns of the partition, including a measure and one
or two dimensions. FOr dimensions that have labels, the labels are included
The returned dataframe will have extra properties to describe the conversion:
* plot_axes: List of dimension names for the first and second axis
* labels: THe names of the label columns for the axes
* filtered: The `filters` dict
* floating: The names of primary dimensions that are not axes nor filtered
THere is also an iterator, `rows`, which returns the header and then all of the rows.
:param measure: The column names of one or more measures
:param p_dim: The primary dimension. This will be the index of the dataframe.
:param s_dim: a secondary dimension. The returned frame will be unstacked on this dimension
:param filters: A dict of column names, mapped to a column value, indicating rows to select. a
row that passes the filter must have the values for all given rows; the entries are ANDED
:param df_class:
:return: a Dataframe, with extra properties | [
"Return",
"a",
"dataframe",
"with",
"a",
"sumse",
"of",
"the",
"columns",
"of",
"the",
"partition",
"including",
"a",
"measure",
"and",
"one",
"or",
"two",
"dimensions",
".",
"FOr",
"dimensions",
"that",
"have",
"labels",
"the",
"labels",
"are",
"included"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1178-L1328 |
CivicSpleen/ambry | ambry/orm/partition.py | MeasureDimensionPartition.dimension_set | def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set()):
"""
Return a dict that describes the combination of one or two dimensions, for a plot
:param p_dim:
:param s_dim:
:param dimensions:
:param extant:
:return:
"""
if not dimensions:
dimensions = self.primary_dimensions
key = p_dim.name
if s_dim:
key += '/' + s_dim.name
# Ignore if the key already exists or the primary and secondary dims are the same
if key in extant or p_dim == s_dim:
return
# Don't allow geography to be a secondary dimension. It must either be a primary dimension
# ( to make a map ) or a filter, or a small-multiple
if s_dim and s_dim.valuetype_class.is_geo():
return
extant.add(key)
filtered = {}
for d in dimensions:
if d != p_dim and d != s_dim:
filtered[d.name] = d.pstats.uvalues.keys()
if p_dim.valuetype_class.is_time():
value_type = 'time'
chart_type = 'line'
elif p_dim.valuetype_class.is_geo():
value_type = 'geo'
chart_type = 'map'
else:
value_type = 'general'
chart_type = 'bar'
return dict(
key=key,
p_dim=p_dim.name,
p_dim_type=value_type,
p_label=p_dim.label_or_self.name,
s_dim=s_dim.name if s_dim else None,
s_label=s_dim.label_or_self.name if s_dim else None,
filters=filtered,
chart_type=chart_type
) | python | def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set()):
"""
Return a dict that describes the combination of one or two dimensions, for a plot
:param p_dim:
:param s_dim:
:param dimensions:
:param extant:
:return:
"""
if not dimensions:
dimensions = self.primary_dimensions
key = p_dim.name
if s_dim:
key += '/' + s_dim.name
# Ignore if the key already exists or the primary and secondary dims are the same
if key in extant or p_dim == s_dim:
return
# Don't allow geography to be a secondary dimension. It must either be a primary dimension
# ( to make a map ) or a filter, or a small-multiple
if s_dim and s_dim.valuetype_class.is_geo():
return
extant.add(key)
filtered = {}
for d in dimensions:
if d != p_dim and d != s_dim:
filtered[d.name] = d.pstats.uvalues.keys()
if p_dim.valuetype_class.is_time():
value_type = 'time'
chart_type = 'line'
elif p_dim.valuetype_class.is_geo():
value_type = 'geo'
chart_type = 'map'
else:
value_type = 'general'
chart_type = 'bar'
return dict(
key=key,
p_dim=p_dim.name,
p_dim_type=value_type,
p_label=p_dim.label_or_self.name,
s_dim=s_dim.name if s_dim else None,
s_label=s_dim.label_or_self.name if s_dim else None,
filters=filtered,
chart_type=chart_type
) | [
"def",
"dimension_set",
"(",
"self",
",",
"p_dim",
",",
"s_dim",
"=",
"None",
",",
"dimensions",
"=",
"None",
",",
"extant",
"=",
"set",
"(",
")",
")",
":",
"if",
"not",
"dimensions",
":",
"dimensions",
"=",
"self",
".",
"primary_dimensions",
"key",
"=... | Return a dict that describes the combination of one or two dimensions, for a plot
:param p_dim:
:param s_dim:
:param dimensions:
:param extant:
:return: | [
"Return",
"a",
"dict",
"that",
"describes",
"the",
"combination",
"of",
"one",
"or",
"two",
"dimensions",
"for",
"a",
"plot"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1330-L1385 |
CivicSpleen/ambry | ambry/orm/partition.py | PartitionColumn.label | def label(self):
""""Return first child that of the column that is marked as a label"""
for c in self.table.columns:
if c.parent == self.name and 'label' in c.valuetype:
return PartitionColumn(c, self._partition) | python | def label(self):
""""Return first child that of the column that is marked as a label"""
for c in self.table.columns:
if c.parent == self.name and 'label' in c.valuetype:
return PartitionColumn(c, self._partition) | [
"def",
"label",
"(",
"self",
")",
":",
"for",
"c",
"in",
"self",
".",
"table",
".",
"columns",
":",
"if",
"c",
".",
"parent",
"==",
"self",
".",
"name",
"and",
"'label'",
"in",
"c",
".",
"valuetype",
":",
"return",
"PartitionColumn",
"(",
"c",
",",... | Return first child that of the column that is marked as a label | [
"Return",
"first",
"child",
"that",
"of",
"the",
"column",
"that",
"is",
"marked",
"as",
"a",
"label"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1440-L1444 |
CivicSpleen/ambry | ambry/orm/partition.py | PartitionColumn.value_labels | def value_labels(self):
"""Return a map of column code values mapped to labels, for columns that have a label column
If the column is not assocaited with a label column, it returns an identity map.
WARNING! This reads the whole partition, so it is really slow
"""
from operator import itemgetter
card = self.pstats.nuniques
if self.label:
ig = itemgetter(self.name, self.label.name)
elif self.pstats.nuniques < MAX_LABELS:
ig = itemgetter(self.name, self.name)
else:
return {}
label_set = set()
for row in self._partition:
label_set.add(ig(row))
if len(label_set) >= card:
break
d = dict(label_set)
assert len(d) == len(label_set) # Else the label set has multiple values per key
return d | python | def value_labels(self):
"""Return a map of column code values mapped to labels, for columns that have a label column
If the column is not assocaited with a label column, it returns an identity map.
WARNING! This reads the whole partition, so it is really slow
"""
from operator import itemgetter
card = self.pstats.nuniques
if self.label:
ig = itemgetter(self.name, self.label.name)
elif self.pstats.nuniques < MAX_LABELS:
ig = itemgetter(self.name, self.name)
else:
return {}
label_set = set()
for row in self._partition:
label_set.add(ig(row))
if len(label_set) >= card:
break
d = dict(label_set)
assert len(d) == len(label_set) # Else the label set has multiple values per key
return d | [
"def",
"value_labels",
"(",
"self",
")",
":",
"from",
"operator",
"import",
"itemgetter",
"card",
"=",
"self",
".",
"pstats",
".",
"nuniques",
"if",
"self",
".",
"label",
":",
"ig",
"=",
"itemgetter",
"(",
"self",
".",
"name",
",",
"self",
".",
"label"... | Return a map of column code values mapped to labels, for columns that have a label column
If the column is not assocaited with a label column, it returns an identity map.
WARNING! This reads the whole partition, so it is really slow | [
"Return",
"a",
"map",
"of",
"column",
"code",
"values",
"mapped",
"to",
"labels",
"for",
"columns",
"that",
"have",
"a",
"label",
"column"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L1447-L1478 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | list_build_configuration_sets | def list_build_configuration_sets(page_size=200, page_index=0, sort="", q=""):
"""
List all build configuration sets
"""
data = list_build_configuration_sets_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | def list_build_configuration_sets(page_size=200, page_index=0, sort="", q=""):
"""
List all build configuration sets
"""
data = list_build_configuration_sets_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_build_configuration_sets",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_build_configuration_sets_raw",
"(",
"page_size",
",",
"page_index",
",",
"sort",
... | List all build configuration sets | [
"List",
"all",
"build",
"configuration",
"sets"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L35-L41 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | create_build_configuration_set_raw | def create_build_configuration_set_raw(**kwargs):
"""
Create a new BuildConfigurationSet.
"""
config_set = _create_build_config_set_object(**kwargs)
response = utils.checked_api_call(pnc_api.build_group_configs, 'create_new', body=config_set)
if response:
return response.content | python | def create_build_configuration_set_raw(**kwargs):
"""
Create a new BuildConfigurationSet.
"""
config_set = _create_build_config_set_object(**kwargs)
response = utils.checked_api_call(pnc_api.build_group_configs, 'create_new', body=config_set)
if response:
return response.content | [
"def",
"create_build_configuration_set_raw",
"(",
"*",
"*",
"kwargs",
")",
":",
"config_set",
"=",
"_create_build_config_set_object",
"(",
"*",
"*",
"kwargs",
")",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"build_group_configs",
",",
... | Create a new BuildConfigurationSet. | [
"Create",
"a",
"new",
"BuildConfigurationSet",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L44-L51 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | get_build_configuration_set_raw | def get_build_configuration_set_raw(id=None, name=None):
"""
Get a specific BuildConfigurationSet by name or ID
"""
found_id = common.set_id(pnc_api.build_group_configs, id, name)
response = utils.checked_api_call(pnc_api.build_group_configs, 'get_specific', id=found_id)
if response:
return response.content | python | def get_build_configuration_set_raw(id=None, name=None):
"""
Get a specific BuildConfigurationSet by name or ID
"""
found_id = common.set_id(pnc_api.build_group_configs, id, name)
response = utils.checked_api_call(pnc_api.build_group_configs, 'get_specific', id=found_id)
if response:
return response.content | [
"def",
"get_build_configuration_set_raw",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"found_id",
"=",
"common",
".",
"set_id",
"(",
"pnc_api",
".",
"build_group_configs",
",",
"id",
",",
"name",
")",
"response",
"=",
"utils",
".",
"checked... | Get a specific BuildConfigurationSet by name or ID | [
"Get",
"a",
"specific",
"BuildConfigurationSet",
"by",
"name",
"or",
"ID"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L69-L76 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | get_build_configuration_set | def get_build_configuration_set(id=None, name=None):
"""
Get a specific BuildConfigurationSet by name or ID
"""
content = get_build_configuration_set_raw(id, name)
if content:
return utils.format_json(content) | python | def get_build_configuration_set(id=None, name=None):
"""
Get a specific BuildConfigurationSet by name or ID
"""
content = get_build_configuration_set_raw(id, name)
if content:
return utils.format_json(content) | [
"def",
"get_build_configuration_set",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"content",
"=",
"get_build_configuration_set_raw",
"(",
"id",
",",
"name",
")",
"if",
"content",
":",
"return",
"utils",
".",
"format_json",
"(",
"content",
")"... | Get a specific BuildConfigurationSet by name or ID | [
"Get",
"a",
"specific",
"BuildConfigurationSet",
"by",
"name",
"or",
"ID"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L80-L86 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | update_build_configuration_set | def update_build_configuration_set(id, **kwargs):
"""
Update a BuildConfigurationSet
"""
data = update_build_configuration_set_raw(id, **kwargs)
if data:
return utils.format_json(data) | python | def update_build_configuration_set(id, **kwargs):
"""
Update a BuildConfigurationSet
"""
data = update_build_configuration_set_raw(id, **kwargs)
if data:
return utils.format_json(data) | [
"def",
"update_build_configuration_set",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"update_build_configuration_set_raw",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"data",
":",
"return",
"utils",
".",
"format_json",
"(",
"data",
")"
] | Update a BuildConfigurationSet | [
"Update",
"a",
"BuildConfigurationSet"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L107-L113 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | build_set_raw | def build_set_raw(id=None, name=None,
tempbuild=False, timestamp_alignment=False,
force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT,
**kwargs):
"""
Start a build of the given BuildConfigurationSet
"""
logging.debug("temp_build: " + str(tempbuild))
logging.debug("timestamp_alignment: " + str(timestamp_alignment))
logging.debug("force: " + str(force))
if tempbuild is False and timestamp_alignment is True:
logging.error("You can only activate timestamp alignment with the temporary build flag!")
sys.exit(1)
found_id = common.set_id(pnc_api.build_group_configs, id, name)
revisions = kwargs.get("id_revisions")
if revisions:
id_revs = map(__parse_revision, revisions)
bcsRest = common.get_entity(pnc_api.build_group_configs, found_id)
body = swagger_client.BuildConfigurationSetWithAuditedBCsRest()
body = __fill_BCSWithAuditedBCs_body(body, bcsRest, id_revs)
response = utils.checked_api_call(pnc_api.build_group_configs, 'build_versioned', id=found_id,
temporary_build=tempbuild,
timestamp_alignment=timestamp_alignment,
force_rebuild=force,
rebuild_mode=rebuild_mode,
body=body)
else:
response = utils.checked_api_call(pnc_api.build_group_configs, 'build', id=found_id,
temporary_build=tempbuild,
timestamp_alignment=timestamp_alignment,
force_rebuild=force,
rebuild_mode=rebuild_mode)
if response:
return response.content | python | def build_set_raw(id=None, name=None,
tempbuild=False, timestamp_alignment=False,
force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT,
**kwargs):
"""
Start a build of the given BuildConfigurationSet
"""
logging.debug("temp_build: " + str(tempbuild))
logging.debug("timestamp_alignment: " + str(timestamp_alignment))
logging.debug("force: " + str(force))
if tempbuild is False and timestamp_alignment is True:
logging.error("You can only activate timestamp alignment with the temporary build flag!")
sys.exit(1)
found_id = common.set_id(pnc_api.build_group_configs, id, name)
revisions = kwargs.get("id_revisions")
if revisions:
id_revs = map(__parse_revision, revisions)
bcsRest = common.get_entity(pnc_api.build_group_configs, found_id)
body = swagger_client.BuildConfigurationSetWithAuditedBCsRest()
body = __fill_BCSWithAuditedBCs_body(body, bcsRest, id_revs)
response = utils.checked_api_call(pnc_api.build_group_configs, 'build_versioned', id=found_id,
temporary_build=tempbuild,
timestamp_alignment=timestamp_alignment,
force_rebuild=force,
rebuild_mode=rebuild_mode,
body=body)
else:
response = utils.checked_api_call(pnc_api.build_group_configs, 'build', id=found_id,
temporary_build=tempbuild,
timestamp_alignment=timestamp_alignment,
force_rebuild=force,
rebuild_mode=rebuild_mode)
if response:
return response.content | [
"def",
"build_set_raw",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"tempbuild",
"=",
"False",
",",
"timestamp_alignment",
"=",
"False",
",",
"force",
"=",
"False",
",",
"rebuild_mode",
"=",
"common",
".",
"REBUILD_MODES_DEFAULT",
",",
"*",
"*",... | Start a build of the given BuildConfigurationSet | [
"Start",
"a",
"build",
"of",
"the",
"given",
"BuildConfigurationSet"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L134-L171 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | build_set | def build_set(id=None, name=None, temporary_build=False, timestamp_alignment=False,
force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT, **kwargs):
"""
Start a build of the given BuildConfigurationSet
"""
content = build_set_raw(id, name,
temporary_build, timestamp_alignment, force, rebuild_mode, **kwargs)
if content:
return utils.format_json(content) | python | def build_set(id=None, name=None, temporary_build=False, timestamp_alignment=False,
force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT, **kwargs):
"""
Start a build of the given BuildConfigurationSet
"""
content = build_set_raw(id, name,
temporary_build, timestamp_alignment, force, rebuild_mode, **kwargs)
if content:
return utils.format_json(content) | [
"def",
"build_set",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"temporary_build",
"=",
"False",
",",
"timestamp_alignment",
"=",
"False",
",",
"force",
"=",
"False",
",",
"rebuild_mode",
"=",
"common",
".",
"REBUILD_MODES_DEFAULT",
",",
"*",
"*... | Start a build of the given BuildConfigurationSet | [
"Start",
"a",
"build",
"of",
"the",
"given",
"BuildConfigurationSet"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L182-L190 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | list_build_configurations_for_set | def list_build_configurations_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all build configurations in a given BuildConfigurationSet.
"""
content = list_build_configurations_for_set_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | python | def list_build_configurations_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all build configurations in a given BuildConfigurationSet.
"""
content = list_build_configurations_for_set_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | [
"def",
"list_build_configurations_for_set",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"content",
"=",
"list_build_configurations_f... | List all build configurations in a given BuildConfigurationSet. | [
"List",
"all",
"build",
"configurations",
"in",
"a",
"given",
"BuildConfigurationSet",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L206-L212 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | add_build_configuration_to_set | def add_build_configuration_to_set(
set_id=None, set_name=None, config_id=None, config_name=None):
"""
Add a build configuration to an existing BuildConfigurationSet
"""
content = add_build_configuration_to_set_raw(set_id, set_name, config_id, config_name)
if content:
return utils.format_json(content) | python | def add_build_configuration_to_set(
set_id=None, set_name=None, config_id=None, config_name=None):
"""
Add a build configuration to an existing BuildConfigurationSet
"""
content = add_build_configuration_to_set_raw(set_id, set_name, config_id, config_name)
if content:
return utils.format_json(content) | [
"def",
"add_build_configuration_to_set",
"(",
"set_id",
"=",
"None",
",",
"set_name",
"=",
"None",
",",
"config_id",
"=",
"None",
",",
"config_name",
"=",
"None",
")",
":",
"content",
"=",
"add_build_configuration_to_set_raw",
"(",
"set_id",
",",
"set_name",
","... | Add a build configuration to an existing BuildConfigurationSet | [
"Add",
"a",
"build",
"configuration",
"to",
"an",
"existing",
"BuildConfigurationSet"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L235-L242 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | list_build_records_for_set | def list_build_records_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all build records for a BuildConfigurationSet
"""
content = list_build_records_for_set_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | python | def list_build_records_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all build records for a BuildConfigurationSet
"""
content = list_build_records_for_set_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | [
"def",
"list_build_records_for_set",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"content",
"=",
"list_build_records_for_set_raw",
... | List all build records for a BuildConfigurationSet | [
"List",
"all",
"build",
"records",
"for",
"a",
"BuildConfigurationSet"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L282-L288 |
project-ncl/pnc-cli | pnc_cli/buildconfigurationsets.py | list_build_set_records | def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all build set records for a BuildConfigurationSet
"""
content = list_build_set_records_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | python | def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all build set records for a BuildConfigurationSet
"""
content = list_build_set_records_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | [
"def",
"list_build_set_records",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"content",
"=",
"list_build_set_records_raw",
"(",
... | List all build set records for a BuildConfigurationSet | [
"List",
"all",
"build",
"set",
"records",
"for",
"a",
"BuildConfigurationSet"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurationsets.py#L304-L310 |
twisted/epsilon | epsilon/react.py | react | def react(reactor, main, argv):
"""
Call C{main} and run the reactor until the L{Deferred} it returns fires.
@param reactor: An unstarted L{IReactorCore} provider which will be run and
later stopped.
@param main: A callable which returns a L{Deferred}. It should take as
many arguments as there are elements in the list C{argv}.
@param argv: A list of arguments to pass to C{main}.
@return: C{None}
"""
stopping = []
reactor.addSystemEventTrigger('before', 'shutdown', stopping.append, True)
finished = main(reactor, *argv)
finished.addErrback(err, "main function encountered error")
def cbFinish(ignored):
if not stopping:
reactor.callWhenRunning(reactor.stop)
finished.addCallback(cbFinish)
reactor.run() | python | def react(reactor, main, argv):
"""
Call C{main} and run the reactor until the L{Deferred} it returns fires.
@param reactor: An unstarted L{IReactorCore} provider which will be run and
later stopped.
@param main: A callable which returns a L{Deferred}. It should take as
many arguments as there are elements in the list C{argv}.
@param argv: A list of arguments to pass to C{main}.
@return: C{None}
"""
stopping = []
reactor.addSystemEventTrigger('before', 'shutdown', stopping.append, True)
finished = main(reactor, *argv)
finished.addErrback(err, "main function encountered error")
def cbFinish(ignored):
if not stopping:
reactor.callWhenRunning(reactor.stop)
finished.addCallback(cbFinish)
reactor.run() | [
"def",
"react",
"(",
"reactor",
",",
"main",
",",
"argv",
")",
":",
"stopping",
"=",
"[",
"]",
"reactor",
".",
"addSystemEventTrigger",
"(",
"'before'",
",",
"'shutdown'",
",",
"stopping",
".",
"append",
",",
"True",
")",
"finished",
"=",
"main",
"(",
... | Call C{main} and run the reactor until the L{Deferred} it returns fires.
@param reactor: An unstarted L{IReactorCore} provider which will be run and
later stopped.
@param main: A callable which returns a L{Deferred}. It should take as
many arguments as there are elements in the list C{argv}.
@param argv: A list of arguments to pass to C{main}.
@return: C{None} | [
"Call",
"C",
"{",
"main",
"}",
"and",
"run",
"the",
"reactor",
"until",
"the",
"L",
"{",
"Deferred",
"}",
"it",
"returns",
"fires",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/react.py#L11-L33 |
edoburu/django-any-urlfield | any_urlfield/models/fields.py | AnyUrlField.register_model | def register_model(cls, ModelClass, form_field=None, widget=None, title=None, prefix=None):
"""
Register a model to use in the URL field.
This function needs to be called once for every model
that should be selectable in the URL field.
:param ModelClass: The model to register.
:param form_field: The form field class used to render the field. This can be a lambda for lazy evaluation.
:param widget: The widget class, can be used instead of the form field.
:param title: The title of the model, by default it uses the models ``verbose_name``.
:param prefix: A custom prefix for the model in the serialized database format. By default it uses "appname.modelname".
"""
cls._static_registry.register(ModelClass, form_field, widget, title, prefix) | python | def register_model(cls, ModelClass, form_field=None, widget=None, title=None, prefix=None):
"""
Register a model to use in the URL field.
This function needs to be called once for every model
that should be selectable in the URL field.
:param ModelClass: The model to register.
:param form_field: The form field class used to render the field. This can be a lambda for lazy evaluation.
:param widget: The widget class, can be used instead of the form field.
:param title: The title of the model, by default it uses the models ``verbose_name``.
:param prefix: A custom prefix for the model in the serialized database format. By default it uses "appname.modelname".
"""
cls._static_registry.register(ModelClass, form_field, widget, title, prefix) | [
"def",
"register_model",
"(",
"cls",
",",
"ModelClass",
",",
"form_field",
"=",
"None",
",",
"widget",
"=",
"None",
",",
"title",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"cls",
".",
"_static_registry",
".",
"register",
"(",
"ModelClass",
",",
... | Register a model to use in the URL field.
This function needs to be called once for every model
that should be selectable in the URL field.
:param ModelClass: The model to register.
:param form_field: The form field class used to render the field. This can be a lambda for lazy evaluation.
:param widget: The widget class, can be used instead of the form field.
:param title: The title of the model, by default it uses the models ``verbose_name``.
:param prefix: A custom prefix for the model in the serialized database format. By default it uses "appname.modelname". | [
"Register",
"a",
"model",
"to",
"use",
"in",
"the",
"URL",
"field",
"."
] | train | https://github.com/edoburu/django-any-urlfield/blob/8d7d36c8a1fc251930f6dbdcc8b5b5151d20e3ab/any_urlfield/models/fields.py#L59-L72 |
edoburu/django-any-urlfield | any_urlfield/models/fields.py | AnyUrlField.resolve_objects | def resolve_objects(cls, objects, skip_cached_urls=False):
"""
Make sure all AnyUrlValue objects from a set of objects is resolved in bulk.
This avoids making a query per item.
:param objects: A list or queryset of models.
:param skip_cached_urls: Whether to avoid prefetching data that has it's URL cached.
"""
# Allow the queryset or list to consist of multiple models.
# This supports querysets from django-polymorphic too.
queryset = list(objects)
any_url_values = []
for obj in queryset:
model = obj.__class__
for field in _any_url_fields_by_model[model]:
any_url_value = getattr(obj, field)
if any_url_value and any_url_value.url_type.has_id_value:
any_url_values.append(any_url_value)
AnyUrlValue.resolve_values(any_url_values, skip_cached_urls=skip_cached_urls) | python | def resolve_objects(cls, objects, skip_cached_urls=False):
"""
Make sure all AnyUrlValue objects from a set of objects is resolved in bulk.
This avoids making a query per item.
:param objects: A list or queryset of models.
:param skip_cached_urls: Whether to avoid prefetching data that has it's URL cached.
"""
# Allow the queryset or list to consist of multiple models.
# This supports querysets from django-polymorphic too.
queryset = list(objects)
any_url_values = []
for obj in queryset:
model = obj.__class__
for field in _any_url_fields_by_model[model]:
any_url_value = getattr(obj, field)
if any_url_value and any_url_value.url_type.has_id_value:
any_url_values.append(any_url_value)
AnyUrlValue.resolve_values(any_url_values, skip_cached_urls=skip_cached_urls) | [
"def",
"resolve_objects",
"(",
"cls",
",",
"objects",
",",
"skip_cached_urls",
"=",
"False",
")",
":",
"# Allow the queryset or list to consist of multiple models.",
"# This supports querysets from django-polymorphic too.",
"queryset",
"=",
"list",
"(",
"objects",
")",
"any_u... | Make sure all AnyUrlValue objects from a set of objects is resolved in bulk.
This avoids making a query per item.
:param objects: A list or queryset of models.
:param skip_cached_urls: Whether to avoid prefetching data that has it's URL cached. | [
"Make",
"sure",
"all",
"AnyUrlValue",
"objects",
"from",
"a",
"set",
"of",
"objects",
"is",
"resolved",
"in",
"bulk",
".",
"This",
"avoids",
"making",
"a",
"query",
"per",
"item",
"."
] | train | https://github.com/edoburu/django-any-urlfield/blob/8d7d36c8a1fc251930f6dbdcc8b5b5151d20e3ab/any_urlfield/models/fields.py#L137-L157 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.