Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals @pytest.mark.online def test_response(credentials): <|code_end|> , predict the immediate next line with the help of imports: import pytest import types from rakuten_ws.webservice import RakutenWebService from rakuten_ws.baseapi import ApiResponse and context (classes, functions, sometimes code) from other files: # Path: rakuten_ws/webservice.py # class RakutenWebService(BaseWebService): # # rms = RmsService() # # ichiba = IchibaAPI() # books = BooksAPI() # travel = TravelAPI() # auction = AuctionAPI() # kobo = KoboAPI() # gora = GoraAPI() # recipe = RecipeAPI() # other = OtherAPI() # # Path: rakuten_ws/baseapi.py # class ApiResponse(UserDict): # def __init__(self, session, url): # self.session = session # self.url = url # self.response = self.session.get(self.url).json() # self.data = self.response # # @property # def json(self): # return PrettyStringRepr(json.dumps(self.data, ensure_ascii=False, sort_keys=True, # indent=4, separators=(',', ': '))) # # def pages(self): # yield self.response # page_number = int(self.response['page']) + 1 # while page_number <= self.response['pageCount']: # api_request = furl(self.url) # api_request.args['page'] = page_number # page_number += 1 # yield self.session.get(api_request.url).json() . Output only the next line.
ws = RakutenWebService(**credentials)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals @pytest.mark.online def test_response(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") <|code_end|> using the current file's imports: import pytest import types from rakuten_ws.webservice import RakutenWebService from rakuten_ws.baseapi import ApiResponse and any relevant context from other files: # Path: rakuten_ws/webservice.py # class RakutenWebService(BaseWebService): # # rms = RmsService() # # ichiba = IchibaAPI() # books = BooksAPI() # travel = TravelAPI() # auction = AuctionAPI() # kobo = KoboAPI() # gora = GoraAPI() # recipe = RecipeAPI() # other = OtherAPI() # # Path: rakuten_ws/baseapi.py # class ApiResponse(UserDict): # def __init__(self, session, url): # self.session = session # self.url = url # self.response = self.session.get(self.url).json() # self.data = self.response # # @property # def json(self): # return PrettyStringRepr(json.dumps(self.data, ensure_ascii=False, sort_keys=True, # indent=4, separators=(',', ': '))) # # def pages(self): # yield self.response # page_number = int(self.response['page']) + 1 # while page_number <= self.response['pageCount']: # api_request = furl(self.url) # api_request.args['page'] = page_number # page_number += 1 # yield self.session.get(api_request.url).json() . Output only the next line.
assert isinstance(response, ApiResponse)
Given snippet: <|code_start|> return PrettyStringRepr(json.dumps(self.data, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))) def pages(self): yield self.response page_number = int(self.response['page']) + 1 while page_number <= self.response['pageCount']: api_request = furl(self.url) api_request.args['page'] = page_number page_number += 1 yield self.session.get(api_request.url).json() class ApiRequest(object): def __init__(self, endpoint, method): self.endpoint = endpoint self.method = method @property def application_id(self, *args, **kwargs): app_id = self.endpoint.service.webservice.application_id if app_id is None: raise Exception("An 'application_id' must be provided") return app_id def build_url(self, *args, **kwargs): # creating new instance of url request api_request = furl(self.endpoint.service.api_url) api_endpoint = self.endpoint.api_endpoint <|code_end|> , continue by predicting the next line. Consider current file imports: import json import requests from furl import furl from .utils import (camelize, camelize_dict, sorted_dict, clean_python_variable_name, PrettyStringRepr) from .compat import UserDict and context: # Path: rakuten_ws/utils.py # def camelize(string, uppercase_first_letter=True): # """ # Convert strings to CamelCase. # # From inflection package: https://github.com/jpvanhal/inflection # # Examples:: # # >>> camelize("device_type") # 'DeviceType' # >>> camelize("device_type", False) # 'deviceType' # """ # if not string.islower(): # return string # if uppercase_first_letter: # return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string) # else: # return string[0].lower() + camelize(string)[1:] # # def camelize_dict(data, uppercase_first_letter=False): # """ Returns a dict with camel case keys. # # >>> d = {'a_simple_key': '1', 'Another_key': '2', 'CamelKey': '3'} # >>> sorted(camelize_dict(d).keys()) # ['Another_key', 'CamelKey', 'aSimpleKey'] # >>> camelize_dict(d)['aSimpleKey'] # '1' # """ # new_dict = data.__class__() # for k, v in iteritems(data): # new_v = v # if isinstance(v, dict): # new_v = camelize_dict(v, uppercase_first_letter) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(camelize_dict(x, uppercase_first_letter)) # else: # camelize(k, uppercase_first_letter) # new_dict[camelize(k, uppercase_first_letter)] = new_v # return new_dict # # def sorted_dict(d, key=None): # """ Sort dict by keys. # # Examples:: # # >>> sorted_dict({'3': 3, '1': 10}) # OrderedDict([('1', 10), ('3', 3)]) # >>> sorted_dict({'1': 10, '3': 3}) # OrderedDict([('1', 10), ('3', 3)]) # """ # new_dict = OrderedDict() # for k, v in sorted(iteritems(d), key=key): # new_v = v # if isinstance(v, dict): # new_v = sorted_dict(v) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(sorted_dict(x)) # else: # new_v.append(x) # new_dict[k] = new_v # return new_dict # # def clean_python_variable_name(s): # """ Convert a string to a valid python variable name. # # Examples:: # # >>> clean_python_variable_name(" ") # '____' # >>> clean_python_variable_name("my 2@'(") # 'my_2___' # >>> clean_python_variable_name("my superS@---variable") # 'my_superS____variable' # """ # return re.sub('\W|^(?=\d)', '_', s) # # class PrettyStringRepr(str): # # Useful for debug # def __repr__(self): # if is_py2: # return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') # else: # return to_unicode(self.replace(' \n', '\n').strip()) # # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): which might include code, classes, or functions. Output only the next line.
method_endpoint = camelize(self.method.alias)
Given the following code snippet before the placeholder: <|code_start|> def __init__(self, endpoint, method): self.endpoint = endpoint self.method = method @property def application_id(self, *args, **kwargs): app_id = self.endpoint.service.webservice.application_id if app_id is None: raise Exception("An 'application_id' must be provided") return app_id def build_url(self, *args, **kwargs): # creating new instance of url request api_request = furl(self.endpoint.service.api_url) api_endpoint = self.endpoint.api_endpoint method_endpoint = camelize(self.method.alias) api_version = self.method.api_version or self.endpoint.api_version or self.endpoint.service.api_version api_request.path.segments.append(api_endpoint) api_request.path.segments.append(method_endpoint) api_request.path.segments.append(api_version) api_request.path.normalize() request_params = { 'applicationId': self.application_id, 'formatVersion': self.endpoint.service.format_version, } if 'page' in kwargs: request_params.update(page=kwargs['page']) <|code_end|> , predict the next line using imports from the current file: import json import requests from furl import furl from .utils import (camelize, camelize_dict, sorted_dict, clean_python_variable_name, PrettyStringRepr) from .compat import UserDict and context including class names, function names, and sometimes code from other files: # Path: rakuten_ws/utils.py # def camelize(string, uppercase_first_letter=True): # """ # Convert strings to CamelCase. # # From inflection package: https://github.com/jpvanhal/inflection # # Examples:: # # >>> camelize("device_type") # 'DeviceType' # >>> camelize("device_type", False) # 'deviceType' # """ # if not string.islower(): # return string # if uppercase_first_letter: # return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string) # else: # return string[0].lower() + camelize(string)[1:] # # def camelize_dict(data, uppercase_first_letter=False): # """ Returns a dict with camel case keys. # # >>> d = {'a_simple_key': '1', 'Another_key': '2', 'CamelKey': '3'} # >>> sorted(camelize_dict(d).keys()) # ['Another_key', 'CamelKey', 'aSimpleKey'] # >>> camelize_dict(d)['aSimpleKey'] # '1' # """ # new_dict = data.__class__() # for k, v in iteritems(data): # new_v = v # if isinstance(v, dict): # new_v = camelize_dict(v, uppercase_first_letter) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(camelize_dict(x, uppercase_first_letter)) # else: # camelize(k, uppercase_first_letter) # new_dict[camelize(k, uppercase_first_letter)] = new_v # return new_dict # # def sorted_dict(d, key=None): # """ Sort dict by keys. # # Examples:: # # >>> sorted_dict({'3': 3, '1': 10}) # OrderedDict([('1', 10), ('3', 3)]) # >>> sorted_dict({'1': 10, '3': 3}) # OrderedDict([('1', 10), ('3', 3)]) # """ # new_dict = OrderedDict() # for k, v in sorted(iteritems(d), key=key): # new_v = v # if isinstance(v, dict): # new_v = sorted_dict(v) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(sorted_dict(x)) # else: # new_v.append(x) # new_dict[k] = new_v # return new_dict # # def clean_python_variable_name(s): # """ Convert a string to a valid python variable name. # # Examples:: # # >>> clean_python_variable_name(" ") # '____' # >>> clean_python_variable_name("my 2@'(") # 'my_2___' # >>> clean_python_variable_name("my superS@---variable") # 'my_superS____variable' # """ # return re.sub('\W|^(?=\d)', '_', s) # # class PrettyStringRepr(str): # # Useful for debug # def __repr__(self): # if is_py2: # return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') # else: # return to_unicode(self.replace(' \n', '\n').strip()) # # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): . Output only the next line.
request_params.update(camelize_dict(kwargs))
Given snippet: <|code_start|> self.endpoint = endpoint self.method = method @property def application_id(self, *args, **kwargs): app_id = self.endpoint.service.webservice.application_id if app_id is None: raise Exception("An 'application_id' must be provided") return app_id def build_url(self, *args, **kwargs): # creating new instance of url request api_request = furl(self.endpoint.service.api_url) api_endpoint = self.endpoint.api_endpoint method_endpoint = camelize(self.method.alias) api_version = self.method.api_version or self.endpoint.api_version or self.endpoint.service.api_version api_request.path.segments.append(api_endpoint) api_request.path.segments.append(method_endpoint) api_request.path.segments.append(api_version) api_request.path.normalize() request_params = { 'applicationId': self.application_id, 'formatVersion': self.endpoint.service.format_version, } if 'page' in kwargs: request_params.update(page=kwargs['page']) request_params.update(camelize_dict(kwargs)) <|code_end|> , continue by predicting the next line. Consider current file imports: import json import requests from furl import furl from .utils import (camelize, camelize_dict, sorted_dict, clean_python_variable_name, PrettyStringRepr) from .compat import UserDict and context: # Path: rakuten_ws/utils.py # def camelize(string, uppercase_first_letter=True): # """ # Convert strings to CamelCase. # # From inflection package: https://github.com/jpvanhal/inflection # # Examples:: # # >>> camelize("device_type") # 'DeviceType' # >>> camelize("device_type", False) # 'deviceType' # """ # if not string.islower(): # return string # if uppercase_first_letter: # return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string) # else: # return string[0].lower() + camelize(string)[1:] # # def camelize_dict(data, uppercase_first_letter=False): # """ Returns a dict with camel case keys. # # >>> d = {'a_simple_key': '1', 'Another_key': '2', 'CamelKey': '3'} # >>> sorted(camelize_dict(d).keys()) # ['Another_key', 'CamelKey', 'aSimpleKey'] # >>> camelize_dict(d)['aSimpleKey'] # '1' # """ # new_dict = data.__class__() # for k, v in iteritems(data): # new_v = v # if isinstance(v, dict): # new_v = camelize_dict(v, uppercase_first_letter) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(camelize_dict(x, uppercase_first_letter)) # else: # camelize(k, uppercase_first_letter) # new_dict[camelize(k, uppercase_first_letter)] = new_v # return new_dict # # def sorted_dict(d, key=None): # """ Sort dict by keys. # # Examples:: # # >>> sorted_dict({'3': 3, '1': 10}) # OrderedDict([('1', 10), ('3', 3)]) # >>> sorted_dict({'1': 10, '3': 3}) # OrderedDict([('1', 10), ('3', 3)]) # """ # new_dict = OrderedDict() # for k, v in sorted(iteritems(d), key=key): # new_v = v # if isinstance(v, dict): # new_v = sorted_dict(v) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(sorted_dict(x)) # else: # new_v.append(x) # new_dict[k] = new_v # return new_dict # # def clean_python_variable_name(s): # """ Convert a string to a valid python variable name. # # Examples:: # # >>> clean_python_variable_name(" ") # '____' # >>> clean_python_variable_name("my 2@'(") # 'my_2___' # >>> clean_python_variable_name("my superS@---variable") # 'my_superS____variable' # """ # return re.sub('\W|^(?=\d)', '_', s) # # class PrettyStringRepr(str): # # Useful for debug # def __repr__(self): # if is_py2: # return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') # else: # return to_unicode(self.replace(' \n', '\n').strip()) # # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): which might include code, classes, or functions. Output only the next line.
api_request.add(sorted_dict(request_params))
Predict the next line for this snippet: <|code_start|> api_request.path.segments.append(method_endpoint) api_request.path.segments.append(api_version) api_request.path.normalize() request_params = { 'applicationId': self.application_id, 'formatVersion': self.endpoint.service.format_version, } if 'page' in kwargs: request_params.update(page=kwargs['page']) request_params.update(camelize_dict(kwargs)) api_request.add(sorted_dict(request_params)) return api_request.url def __call__(self, *args, **kwargs): url = self.build_url(*args, **kwargs) session = self.endpoint.service.webservice.session return ApiResponse(session, url) class ApiEndpoint(object): api_version = None def __init__(self, *methods, **kwargs): self.service = None self.name = kwargs.get('name', None) self.api_endpoint = kwargs.get('api_endpoint', None) for method in methods: <|code_end|> with the help of current file imports: import json import requests from furl import furl from .utils import (camelize, camelize_dict, sorted_dict, clean_python_variable_name, PrettyStringRepr) from .compat import UserDict and context from other files: # Path: rakuten_ws/utils.py # def camelize(string, uppercase_first_letter=True): # """ # Convert strings to CamelCase. # # From inflection package: https://github.com/jpvanhal/inflection # # Examples:: # # >>> camelize("device_type") # 'DeviceType' # >>> camelize("device_type", False) # 'deviceType' # """ # if not string.islower(): # return string # if uppercase_first_letter: # return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string) # else: # return string[0].lower() + camelize(string)[1:] # # def camelize_dict(data, uppercase_first_letter=False): # """ Returns a dict with camel case keys. # # >>> d = {'a_simple_key': '1', 'Another_key': '2', 'CamelKey': '3'} # >>> sorted(camelize_dict(d).keys()) # ['Another_key', 'CamelKey', 'aSimpleKey'] # >>> camelize_dict(d)['aSimpleKey'] # '1' # """ # new_dict = data.__class__() # for k, v in iteritems(data): # new_v = v # if isinstance(v, dict): # new_v = camelize_dict(v, uppercase_first_letter) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(camelize_dict(x, uppercase_first_letter)) # else: # camelize(k, uppercase_first_letter) # new_dict[camelize(k, uppercase_first_letter)] = new_v # return new_dict # # def sorted_dict(d, key=None): # """ Sort dict by keys. # # Examples:: # # >>> sorted_dict({'3': 3, '1': 10}) # OrderedDict([('1', 10), ('3', 3)]) # >>> sorted_dict({'1': 10, '3': 3}) # OrderedDict([('1', 10), ('3', 3)]) # """ # new_dict = OrderedDict() # for k, v in sorted(iteritems(d), key=key): # new_v = v # if isinstance(v, dict): # new_v = sorted_dict(v) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(sorted_dict(x)) # else: # new_v.append(x) # new_dict[k] = new_v # return new_dict # # def clean_python_variable_name(s): # """ Convert a string to a valid python variable name. # # Examples:: # # >>> clean_python_variable_name(" ") # '____' # >>> clean_python_variable_name("my 2@'(") # 'my_2___' # >>> clean_python_variable_name("my superS@---variable") # 'my_superS____variable' # """ # return re.sub('\W|^(?=\d)', '_', s) # # class PrettyStringRepr(str): # # Useful for debug # def __repr__(self): # if is_py2: # return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') # else: # return to_unicode(self.replace(' \n', '\n').strip()) # # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): , which may contain function names, class names, or code. Output only the next line.
method_name = clean_python_variable_name(method.name)
Next line prediction: <|code_start|># coding: utf-8 from __future__ import unicode_literals class ApiMethod(object): def __init__(self, name, alias=None, api_version=None): self.name = name self.alias = alias or name self.api_version = api_version class ApiResponse(UserDict): def __init__(self, session, url): self.session = session self.url = url self.response = self.session.get(self.url).json() self.data = self.response @property def json(self): <|code_end|> . Use current file imports: (import json import requests from furl import furl from .utils import (camelize, camelize_dict, sorted_dict, clean_python_variable_name, PrettyStringRepr) from .compat import UserDict) and context including class names, function names, or small code snippets from other files: # Path: rakuten_ws/utils.py # def camelize(string, uppercase_first_letter=True): # """ # Convert strings to CamelCase. # # From inflection package: https://github.com/jpvanhal/inflection # # Examples:: # # >>> camelize("device_type") # 'DeviceType' # >>> camelize("device_type", False) # 'deviceType' # """ # if not string.islower(): # return string # if uppercase_first_letter: # return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string) # else: # return string[0].lower() + camelize(string)[1:] # # def camelize_dict(data, uppercase_first_letter=False): # """ Returns a dict with camel case keys. # # >>> d = {'a_simple_key': '1', 'Another_key': '2', 'CamelKey': '3'} # >>> sorted(camelize_dict(d).keys()) # ['Another_key', 'CamelKey', 'aSimpleKey'] # >>> camelize_dict(d)['aSimpleKey'] # '1' # """ # new_dict = data.__class__() # for k, v in iteritems(data): # new_v = v # if isinstance(v, dict): # new_v = camelize_dict(v, uppercase_first_letter) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(camelize_dict(x, uppercase_first_letter)) # else: # camelize(k, uppercase_first_letter) # new_dict[camelize(k, uppercase_first_letter)] = new_v # return new_dict # # def sorted_dict(d, key=None): # """ Sort dict by keys. # # Examples:: # # >>> sorted_dict({'3': 3, '1': 10}) # OrderedDict([('1', 10), ('3', 3)]) # >>> sorted_dict({'1': 10, '3': 3}) # OrderedDict([('1', 10), ('3', 3)]) # """ # new_dict = OrderedDict() # for k, v in sorted(iteritems(d), key=key): # new_v = v # if isinstance(v, dict): # new_v = sorted_dict(v) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(sorted_dict(x)) # else: # new_v.append(x) # new_dict[k] = new_v # return new_dict # # def clean_python_variable_name(s): # """ Convert a string to a valid python variable name. # # Examples:: # # >>> clean_python_variable_name(" ") # '____' # >>> clean_python_variable_name("my 2@'(") # 'my_2___' # >>> clean_python_variable_name("my superS@---variable") # 'my_superS____variable' # """ # return re.sub('\W|^(?=\d)', '_', s) # # class PrettyStringRepr(str): # # Useful for debug # def __repr__(self): # if is_py2: # return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') # else: # return to_unicode(self.replace(' \n', '\n').strip()) # # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): . Output only the next line.
return PrettyStringRepr(json.dumps(self.data, ensure_ascii=False, sort_keys=True,
Next line prediction: <|code_start|># coding: utf-8 from __future__ import unicode_literals class ApiMethod(object): def __init__(self, name, alias=None, api_version=None): self.name = name self.alias = alias or name self.api_version = api_version <|code_end|> . Use current file imports: (import json import requests from furl import furl from .utils import (camelize, camelize_dict, sorted_dict, clean_python_variable_name, PrettyStringRepr) from .compat import UserDict) and context including class names, function names, or small code snippets from other files: # Path: rakuten_ws/utils.py # def camelize(string, uppercase_first_letter=True): # """ # Convert strings to CamelCase. # # From inflection package: https://github.com/jpvanhal/inflection # # Examples:: # # >>> camelize("device_type") # 'DeviceType' # >>> camelize("device_type", False) # 'deviceType' # """ # if not string.islower(): # return string # if uppercase_first_letter: # return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string) # else: # return string[0].lower() + camelize(string)[1:] # # def camelize_dict(data, uppercase_first_letter=False): # """ Returns a dict with camel case keys. # # >>> d = {'a_simple_key': '1', 'Another_key': '2', 'CamelKey': '3'} # >>> sorted(camelize_dict(d).keys()) # ['Another_key', 'CamelKey', 'aSimpleKey'] # >>> camelize_dict(d)['aSimpleKey'] # '1' # """ # new_dict = data.__class__() # for k, v in iteritems(data): # new_v = v # if isinstance(v, dict): # new_v = camelize_dict(v, uppercase_first_letter) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(camelize_dict(x, uppercase_first_letter)) # else: # camelize(k, uppercase_first_letter) # new_dict[camelize(k, uppercase_first_letter)] = new_v # return new_dict # # def sorted_dict(d, key=None): # """ Sort dict by keys. # # Examples:: # # >>> sorted_dict({'3': 3, '1': 10}) # OrderedDict([('1', 10), ('3', 3)]) # >>> sorted_dict({'1': 10, '3': 3}) # OrderedDict([('1', 10), ('3', 3)]) # """ # new_dict = OrderedDict() # for k, v in sorted(iteritems(d), key=key): # new_v = v # if isinstance(v, dict): # new_v = sorted_dict(v) # elif isinstance(v, list): # new_v = list() # for x in v: # if isinstance(x, dict): # new_v.append(sorted_dict(x)) # else: # new_v.append(x) # new_dict[k] = new_v # return new_dict # # def clean_python_variable_name(s): # """ Convert a string to a valid python variable name. # # Examples:: # # >>> clean_python_variable_name(" ") # '____' # >>> clean_python_variable_name("my 2@'(") # 'my_2___' # >>> clean_python_variable_name("my superS@---variable") # 'my_superS____variable' # """ # return re.sub('\W|^(?=\d)', '_', s) # # class PrettyStringRepr(str): # # Useful for debug # def __repr__(self): # if is_py2: # return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') # else: # return to_unicode(self.replace(' \n', '\n').strip()) # # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): . Output only the next line.
class ApiResponse(UserDict):
Given snippet: <|code_start|>from __future__ import unicode_literals parker = Parker(dict_type=dict) class PrettyStringRepr(str): # Useful for debug def __repr__(self): if is_py2: return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') else: return to_unicode(self.replace(' \n', '\n').strip()) def camelize_dict(data, uppercase_first_letter=False): """ Returns a dict with camel case keys. >>> d = {'a_simple_key': '1', 'Another_key': '2', 'CamelKey': '3'} >>> sorted(camelize_dict(d).keys()) ['Another_key', 'CamelKey', 'aSimpleKey'] >>> camelize_dict(d)['aSimpleKey'] '1' """ new_dict = data.__class__() <|code_end|> , continue by predicting the next line. Consider current file imports: import re import requests from collections import OrderedDict, MutableMapping from shutil import copyfileobj from mimetypes import guess_type from io import BytesIO, open from xmljson import Parker from lxml.etree import Element, fromstring, tostring from .compat import iteritems, to_unicode, is_py2, str, urlparse, pathname2url and context: # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): which might include code, classes, or functions. Output only the next line.
for k, v in iteritems(data):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals parker = Parker(dict_type=dict) class PrettyStringRepr(str): # Useful for debug def __repr__(self): if is_py2: <|code_end|> using the current file's imports: import re import requests from collections import OrderedDict, MutableMapping from shutil import copyfileobj from mimetypes import guess_type from io import BytesIO, open from xmljson import Parker from lxml.etree import Element, fromstring, tostring from .compat import iteritems, to_unicode, is_py2, str, urlparse, pathname2url and any relevant context from other files: # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): . Output only the next line.
return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8')
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals parker = Parker(dict_type=dict) class PrettyStringRepr(str): # Useful for debug def __repr__(self): <|code_end|> , predict the next line using imports from the current file: import re import requests from collections import OrderedDict, MutableMapping from shutil import copyfileobj from mimetypes import guess_type from io import BytesIO, open from xmljson import Parker from lxml.etree import Element, fromstring, tostring from .compat import iteritems, to_unicode, is_py2, str, urlparse, pathname2url and context including class names, function names, and sometimes code from other files: # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): . Output only the next line.
if is_py2:
Here is a snippet: <|code_start|> parts = key.split(".") d = unflat_dict for part in parts[:-1]: if part not in d: d[part] = dictionary.__class__() d = d[part] d[parts[-1]] = value def unflatten_list_dict(dictionary): unflat_list_dict = dictionary.__class__() for k, v in dictionary.items(): if isinstance(v, dict): unflat_dict = unflatten_list_dict(v) if sorted(unflat_dict.keys())[0] == '@0': unflat_list = [] for key in sorted(unflat_dict.keys()): unflat_list.append(unflat_dict[key]) new_value = unflat_list else: new_value = unflat_dict unflat_list_dict[k] = new_value else: unflat_list_dict[k] = v return unflat_list_dict return unflatten_list_dict(unflat_dict) def load_file(url, session=None, timeout=None): """Load the content from the given URL and return it as a `BytesIO`""" <|code_end|> . Write the next line using the current file imports: import re import requests from collections import OrderedDict, MutableMapping from shutil import copyfileobj from mimetypes import guess_type from io import BytesIO, open from xmljson import Parker from lxml.etree import Element, fromstring, tostring from .compat import iteritems, to_unicode, is_py2, str, urlparse, pathname2url and context from other files: # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): , which may include functions, classes, or code. Output only the next line.
scheme = urlparse(url).scheme
Given the code snippet: <|code_start|> unflat_list = [] for key in sorted(unflat_dict.keys()): unflat_list.append(unflat_dict[key]) new_value = unflat_list else: new_value = unflat_dict unflat_list_dict[k] = new_value else: unflat_list_dict[k] = v return unflat_list_dict return unflatten_list_dict(unflat_dict) def load_file(url, session=None, timeout=None): """Load the content from the given URL and return it as a `BytesIO`""" scheme = urlparse(url).scheme if scheme in ('http', 'https'): if session is None: session = requests.Session() response = session.get(url, timeout=timeout) response.raise_for_status() return BytesIO(response.content), response.headers['Content-Type'] elif scheme in ('', 'file'): if url.startswith('file://'): url = url[7:] fileobj = BytesIO() with open(url, 'rb') as fd: copyfileobj(fd, fileobj) fileobj.seek(0) <|code_end|> , generate the next line using the imports in this file: import re import requests from collections import OrderedDict, MutableMapping from shutil import copyfileobj from mimetypes import guess_type from io import BytesIO, open from xmljson import Parker from lxml.etree import Element, fromstring, tostring from .compat import iteritems, to_unicode, is_py2, str, urlparse, pathname2url and context (functions, classes, or occasionally code) from other files: # Path: rakuten_ws/compat.py # def iteritems(d): # def is_bytes(x): # def callable(obj): # def iteritems(d): # def is_bytes(x): # def to_unicode(obj, encoding='utf-8'): . Output only the next line.
return fileobj, guess_type(pathname2url(url))[0]
Given snippet: <|code_start|>#!/usr/bin/env python # coding: utf-8 credentials = { 'application_id': os.environ.get('RAKUTEN_APP_ID', ''), 'license_key': os.environ.get('RMS_LICENSE_KEY', ''), 'secret_service': os.environ.get('RMS_SECRET_SERVICE', ''), 'shop_url': os.environ.get('RMS_SHOP_URL', ''), } assert len(credentials['shop_url']) > 0 <|code_end|> , continue by predicting the next line. Consider current file imports: import os from rakuten_ws import RakutenWebService and context: # Path: rakuten_ws/webservice.py # class RakutenWebService(BaseWebService): # # rms = RmsService() # # ichiba = IchibaAPI() # books = BooksAPI() # travel = TravelAPI() # auction = AuctionAPI() # kobo = KoboAPI() # gora = GoraAPI() # recipe = RecipeAPI() # other = OtherAPI() which might include code, classes, or functions. Output only the next line.
ws = RakutenWebService(**credentials)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 <|code_end|> , determine the next line of code. You have imports: from rakuten_ws.baseapi import ApiService, ApiEndpoint, BaseWebService, ApiRequest, ApiMethod and context (class names, function names, or code) available: # Path: rakuten_ws/baseapi.py # class ApiService(object): # api_url = "https://app.rakuten.co.jp/services/api" # format_version = 2 # # def __new__(cls, *args, **kwargs): # instance = super(ApiService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiEndpoint): # if getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, name=None, **kwargs): # self.name = name # self.webservice = None # # def __get__(self, webservice, cls): # if webservice is not None: # self.webservice = webservice # return self # return self.__class__ # # class ApiEndpoint(object): # api_version = None # # def __init__(self, *methods, **kwargs): # self.service = None # self.name = kwargs.get('name', None) # self.api_endpoint = kwargs.get('api_endpoint', None) # # for method in methods: # method_name = clean_python_variable_name(method.name) # setattr(self, method_name, ApiRequest(self, method)) # # def __get__(self, service, cls): # if service is not None: # self.service = service # if getattr(self, 'api_endpoint', None) is None: # self.api_endpoint = camelize("%s_%s" % (self.service.name, self.name)) # return self # return self.__class__ # # class BaseWebService(object): # # def __new__(cls, *args, **kwargs): # instance = super(BaseWebService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiService) \ # and getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, application_id=None, license_key=None, secret_service=None, shop_url=None, debug=False): # self.application_id = application_id # self.license_key = license_key # self.secret_service = secret_service # self.shop_url = shop_url # self.debug = debug # self.session = requests.Session() # self.session.headers = {"User-Agent": self.session.headers['User-Agent']} # # class ApiRequest(object): # # def __init__(self, endpoint, method): # self.endpoint = endpoint # self.method = method # # @property # def application_id(self, *args, **kwargs): # app_id = self.endpoint.service.webservice.application_id # if app_id is None: # raise Exception("An 'application_id' must be provided") # return app_id # # def build_url(self, *args, **kwargs): # # creating new instance of url request # api_request = furl(self.endpoint.service.api_url) # api_endpoint = self.endpoint.api_endpoint # method_endpoint = camelize(self.method.alias) # api_version = self.method.api_version or self.endpoint.api_version or self.endpoint.service.api_version # # api_request.path.segments.append(api_endpoint) # api_request.path.segments.append(method_endpoint) # api_request.path.segments.append(api_version) # api_request.path.normalize() # # request_params = { # 'applicationId': self.application_id, # 'formatVersion': self.endpoint.service.format_version, # } # if 'page' in kwargs: # request_params.update(page=kwargs['page']) # # request_params.update(camelize_dict(kwargs)) # api_request.add(sorted_dict(request_params)) # return api_request.url # # def __call__(self, *args, **kwargs): # url = self.build_url(*args, **kwargs) # session = self.endpoint.service.webservice.session # return ApiResponse(session, url) # # class ApiMethod(object): # def __init__(self, name, alias=None, api_version=None): # self.name = name # self.alias = alias or name # self.api_version = api_version . Output only the next line.
item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking'))
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking')) product = ApiEndpoint(ApiMethod('get'), api_endpoint="Product") order = ApiEndpoint(ApiMethod('get'), name='orders') <|code_end|> . Write the next line using the current file imports: from rakuten_ws.baseapi import ApiService, ApiEndpoint, BaseWebService, ApiRequest, ApiMethod and context from other files: # Path: rakuten_ws/baseapi.py # class ApiService(object): # api_url = "https://app.rakuten.co.jp/services/api" # format_version = 2 # # def __new__(cls, *args, **kwargs): # instance = super(ApiService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiEndpoint): # if getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, name=None, **kwargs): # self.name = name # self.webservice = None # # def __get__(self, webservice, cls): # if webservice is not None: # self.webservice = webservice # return self # return self.__class__ # # class ApiEndpoint(object): # api_version = None # # def __init__(self, *methods, **kwargs): # self.service = None # self.name = kwargs.get('name', None) # self.api_endpoint = kwargs.get('api_endpoint', None) # # for method in methods: # method_name = clean_python_variable_name(method.name) # setattr(self, method_name, ApiRequest(self, method)) # # def __get__(self, service, cls): # if service is not None: # self.service = service # if getattr(self, 'api_endpoint', None) is None: # self.api_endpoint = camelize("%s_%s" % (self.service.name, self.name)) # return self # return self.__class__ # # class BaseWebService(object): # # def __new__(cls, *args, **kwargs): # instance = super(BaseWebService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiService) \ # and getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, application_id=None, license_key=None, secret_service=None, shop_url=None, debug=False): # self.application_id = application_id # self.license_key = license_key # self.secret_service = secret_service # self.shop_url = shop_url # self.debug = debug # self.session = requests.Session() # self.session.headers = {"User-Agent": self.session.headers['User-Agent']} # # class ApiRequest(object): # # def __init__(self, endpoint, method): # self.endpoint = endpoint # self.method = method # # @property # def application_id(self, *args, **kwargs): # app_id = self.endpoint.service.webservice.application_id # if app_id is None: # raise Exception("An 'application_id' must be provided") # return app_id # # def build_url(self, *args, **kwargs): # # creating new instance of url request # api_request = furl(self.endpoint.service.api_url) # api_endpoint = self.endpoint.api_endpoint # method_endpoint = camelize(self.method.alias) # api_version = self.method.api_version or self.endpoint.api_version or self.endpoint.service.api_version # # api_request.path.segments.append(api_endpoint) # api_request.path.segments.append(method_endpoint) # api_request.path.segments.append(api_version) # api_request.path.normalize() # # request_params = { # 'applicationId': self.application_id, # 'formatVersion': self.endpoint.service.format_version, # } # if 'page' in kwargs: # request_params.update(page=kwargs['page']) # # request_params.update(camelize_dict(kwargs)) # api_request.add(sorted_dict(request_params)) # return api_request.url # # def __call__(self, *args, **kwargs): # url = self.build_url(*args, **kwargs) # session = self.endpoint.service.webservice.session # return ApiResponse(session, url) # # class ApiMethod(object): # def __init__(self, name, alias=None, api_version=None): # self.name = name # self.alias = alias or name # self.api_version = api_version , which may include functions, classes, or code. Output only the next line.
class SimpleWebService(BaseWebService):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking')) product = ApiEndpoint(ApiMethod('get'), api_endpoint="Product") order = ApiEndpoint(ApiMethod('get'), name='orders') class SimpleWebService(BaseWebService): test_api = SimpleAPI() def test_class_api_description(): assert SimpleWebService.test_api == SimpleAPI assert SimpleAPI.item == ApiEndpoint ws = SimpleWebService(application_id="4K95553C260362") assert ws.test_api.name == "test_api" assert ws.test_api.api_version == "20140222" assert ws.test_api.api_url == "https://testapi" <|code_end|> using the current file's imports: from rakuten_ws.baseapi import ApiService, ApiEndpoint, BaseWebService, ApiRequest, ApiMethod and any relevant context from other files: # Path: rakuten_ws/baseapi.py # class ApiService(object): # api_url = "https://app.rakuten.co.jp/services/api" # format_version = 2 # # def __new__(cls, *args, **kwargs): # instance = super(ApiService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiEndpoint): # if getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, name=None, **kwargs): # self.name = name # self.webservice = None # # def __get__(self, webservice, cls): # if webservice is not None: # self.webservice = webservice # return self # return self.__class__ # # class ApiEndpoint(object): # api_version = None # # def __init__(self, *methods, **kwargs): # self.service = None # self.name = kwargs.get('name', None) # self.api_endpoint = kwargs.get('api_endpoint', None) # # for method in methods: # method_name = clean_python_variable_name(method.name) # setattr(self, method_name, ApiRequest(self, method)) # # def __get__(self, service, cls): # if service is not None: # self.service = service # if getattr(self, 'api_endpoint', None) is None: # self.api_endpoint = camelize("%s_%s" % (self.service.name, self.name)) # return self # return self.__class__ # # class BaseWebService(object): # # def __new__(cls, *args, **kwargs): # instance = super(BaseWebService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiService) \ # and getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, application_id=None, license_key=None, secret_service=None, shop_url=None, debug=False): # self.application_id = application_id # self.license_key = license_key # self.secret_service = secret_service # self.shop_url = shop_url # self.debug = debug # self.session = requests.Session() # self.session.headers = {"User-Agent": self.session.headers['User-Agent']} # # class ApiRequest(object): # # def __init__(self, endpoint, method): # self.endpoint = endpoint # self.method = method # # @property # def application_id(self, *args, **kwargs): # app_id = self.endpoint.service.webservice.application_id # if app_id is None: # raise Exception("An 'application_id' must be provided") # return app_id # # def build_url(self, *args, **kwargs): # # creating new instance of url request # api_request = furl(self.endpoint.service.api_url) # api_endpoint = self.endpoint.api_endpoint # method_endpoint = camelize(self.method.alias) # api_version = self.method.api_version or self.endpoint.api_version or self.endpoint.service.api_version # # api_request.path.segments.append(api_endpoint) # api_request.path.segments.append(method_endpoint) # api_request.path.segments.append(api_version) # api_request.path.normalize() # # request_params = { # 'applicationId': self.application_id, # 'formatVersion': self.endpoint.service.format_version, # } # if 'page' in kwargs: # request_params.update(page=kwargs['page']) # # request_params.update(camelize_dict(kwargs)) # api_request.add(sorted_dict(request_params)) # return api_request.url # # def __call__(self, *args, **kwargs): # url = self.build_url(*args, **kwargs) # session = self.endpoint.service.webservice.session # return ApiResponse(session, url) # # class ApiMethod(object): # def __init__(self, name, alias=None, api_version=None): # self.name = name # self.alias = alias or name # self.api_version = api_version . Output only the next line.
assert isinstance(ws.test_api.item.search, ApiRequest)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 <|code_end|> , determine the next line of code. You have imports: from rakuten_ws.baseapi import ApiService, ApiEndpoint, BaseWebService, ApiRequest, ApiMethod and context (class names, function names, or code) available: # Path: rakuten_ws/baseapi.py # class ApiService(object): # api_url = "https://app.rakuten.co.jp/services/api" # format_version = 2 # # def __new__(cls, *args, **kwargs): # instance = super(ApiService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiEndpoint): # if getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, name=None, **kwargs): # self.name = name # self.webservice = None # # def __get__(self, webservice, cls): # if webservice is not None: # self.webservice = webservice # return self # return self.__class__ # # class ApiEndpoint(object): # api_version = None # # def __init__(self, *methods, **kwargs): # self.service = None # self.name = kwargs.get('name', None) # self.api_endpoint = kwargs.get('api_endpoint', None) # # for method in methods: # method_name = clean_python_variable_name(method.name) # setattr(self, method_name, ApiRequest(self, method)) # # def __get__(self, service, cls): # if service is not None: # self.service = service # if getattr(self, 'api_endpoint', None) is None: # self.api_endpoint = camelize("%s_%s" % (self.service.name, self.name)) # return self # return self.__class__ # # class BaseWebService(object): # # def __new__(cls, *args, **kwargs): # instance = super(BaseWebService, cls).__new__(cls) # for name, attr in sorted(list(cls.__dict__.items())): # if isinstance(attr, ApiService) \ # and getattr(attr, 'name', None) is None: # setattr(attr, 'name', name) # return instance # # def __init__(self, application_id=None, license_key=None, secret_service=None, shop_url=None, debug=False): # self.application_id = application_id # self.license_key = license_key # self.secret_service = secret_service # self.shop_url = shop_url # self.debug = debug # self.session = requests.Session() # self.session.headers = {"User-Agent": self.session.headers['User-Agent']} # # class ApiRequest(object): # # def __init__(self, endpoint, method): # self.endpoint = endpoint # self.method = method # # @property # def application_id(self, *args, **kwargs): # app_id = self.endpoint.service.webservice.application_id # if app_id is None: # raise Exception("An 'application_id' must be provided") # return app_id # # def build_url(self, *args, **kwargs): # # creating new instance of url request # api_request = furl(self.endpoint.service.api_url) # api_endpoint = self.endpoint.api_endpoint # method_endpoint = camelize(self.method.alias) # api_version = self.method.api_version or self.endpoint.api_version or self.endpoint.service.api_version # # api_request.path.segments.append(api_endpoint) # api_request.path.segments.append(method_endpoint) # api_request.path.segments.append(api_version) # api_request.path.normalize() # # request_params = { # 'applicationId': self.application_id, # 'formatVersion': self.endpoint.service.format_version, # } # if 'page' in kwargs: # request_params.update(page=kwargs['page']) # # request_params.update(camelize_dict(kwargs)) # api_request.add(sorted_dict(request_params)) # return api_request.url # # def __call__(self, *args, **kwargs): # url = self.build_url(*args, **kwargs) # session = self.endpoint.service.webservice.session # return ApiResponse(session, url) # # class ApiMethod(object): # def __init__(self, name, alias=None, api_version=None): # self.name = name # self.alias = alias or name # self.api_version = api_version . Output only the next line.
item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking'))
Given snippet: <|code_start|> class Server(object): ''' The Server object owns the websocket connection and all attached channel information. ''' def __init__(self, token, connect=True, proxies=None): self.token = token self.username = None self.domain = None self.login_data = None self.websocket = None self.users = SearchDict() self.channels = SearchList() self.connected = False self.ws_url = None self.proxies = proxies <|code_end|> , continue by predicting the next line. Consider current file imports: from .slackrequest import SlackRequest from requests.packages.urllib3.util.url import parse_url from .channel import Channel from .user import User from .util import SearchList, SearchDict from ssl import SSLError from websocket import create_connection import json and context: # Path: slackclient/slackrequest.py # class SlackRequest(object): # def __init__(self, proxies=None): # # # __name__ returns 'slackclient.slackrequest', we only want 'slackclient' # client_name = __name__.split('.')[0] # client_version = __version__ # Version is returned from version.py # # # Construct the user-agent header with the package info, Python version and OS version. # self.default_user_agent = { # "client": "{0}/{1}".format(client_name, client_version), # "python": "Python/{v.major}.{v.minor}.{v.micro}".format(v=sys.version_info), # "system": "{0}/{1}".format(platform.system(), platform.release()) # } # # self.custom_user_agent = None # self.proxies = proxies # # def get_user_agent(self): # # Check for custom user-agent and append if found # if self.custom_user_agent: # custom_ua_list = ["/".join(client_info) for client_info in self.custom_user_agent] # custom_ua_string = " ".join(custom_ua_list) # self.default_user_agent['custom'] = custom_ua_string # # # Concatenate and format the user-agent string to be passed into request headers # ua_string = [] # for key, val in self.default_user_agent.items(): # ua_string.append(val) # # user_agent_string = " ".join(ua_string) # return user_agent_string # # def append_user_agent(self, name, version): # if self.custom_user_agent: # self.custom_user_agent.append([name.replace("/", ":"), version.replace("/", ":")]) # else: # self.custom_user_agent = [[name, version]] # # def do(self, token, request="?", post_data=None, domain="slack.com", timeout=None): # """ # Perform a POST request to the Slack Web API # # Args: # token (str): your authentication token # request (str): the method to call from the Slack API. For example: 'channels.list' # timeout (float): stop waiting for a response after a given number of seconds # post_data (dict): key/value arguments to pass for the request. For example: # {'channel': 'CABC12345'} # domain (str): if for some reason you want to send your request to something other # than slack.com # """ # # # Pull file out so it isn't JSON encoded like normal fields. # # Only do this for requests that are UPLOADING files; downloading files # # use the 'file' argument to point to a File ID. # post_data = post_data or {} # upload_requests = ['files.upload'] # files = None # if request in upload_requests: # files = {'file': post_data.pop('file')} if 'file' in post_data else None # # for k, v in six.iteritems(post_data): # if not isinstance(v, six.string_types): # post_data[k] = json.dumps(v) # # url = 'https://{0}/api/{1}'.format(domain, request) # post_data['token'] = token # headers = {'user-agent': self.get_user_agent()} # # return requests.post(url, # headers=headers, # data=post_data, # files=files, # timeout=timeout, # proxies=self.proxies) # # Path: slackclient/channel.py # class Channel(object): # ''' # A Channel represents a public or private Slack Channel instance # ''' # def __init__(self, server, name, channel_id, members=None): # self.server = server # self.name = name # self.id = channel_id # self.members = [] if members is None else members # # def __eq__(self, compare_str): # if self.name == compare_str or "#" + self.name == compare_str or self.id == compare_str: # return True # else: # return False # # def __hash__(self): # return hash(self.id) # # def __str__(self): # data = "" # for key in list(self.__dict__.keys()): # data += "{0} : {1}\n".format(key, str(self.__dict__[key])[:40]) # return data # # def __repr__(self): # return self.__str__() # # def send_message(self, message, thread=None, reply_broadcast=False): # ''' # Sends a message to a this Channel. # # Include the parent message's thread_ts value in `thread` # to send to a thread. # # :Args: # message (message) - the string you'd like to send to the channel # thread (str or None) - the parent message ID, if sending to a # thread # reply_broadcast (bool) - if messaging a thread, whether to # also send the message back to the channel # # :Returns: # None # ''' # self.server.rtm_send_message(self.id, message, thread, reply_broadcast) which might include code, classes, or functions. Output only the next line.
self.api_requester = SlackRequest(proxies=proxies)
Given the following code snippet before the placeholder: <|code_start|> return self.send_to_websocket({"type": "ping"}) def websocket_safe_read(self): """ Returns data if available, otherwise ''. Newlines indicate multiple messages """ data = "" while True: try: data += "{0}\n".format(self.websocket.recv()) except SSLError as e: if e.errno == 2: # errno 2 occurs when trying to read or write data, but more # data needs to be received on the underlying TCP transport # before the request can be fulfilled. # # Python 2.7.9+ and Python 3.3+ give this its own exception, # SSLWantReadError return '' raise return data.rstrip() def attach_user(self, name, user_id, real_name, tz): self.users.update({user_id: User(self, name, user_id, real_name, tz)}) def attach_channel(self, name, channel_id, members=None): if members is None: members = [] if self.channels.find(channel_id) is None: <|code_end|> , predict the next line using imports from the current file: from .slackrequest import SlackRequest from requests.packages.urllib3.util.url import parse_url from .channel import Channel from .user import User from .util import SearchList, SearchDict from ssl import SSLError from websocket import create_connection import json and context including class names, function names, and sometimes code from other files: # Path: slackclient/slackrequest.py # class SlackRequest(object): # def __init__(self, proxies=None): # # # __name__ returns 'slackclient.slackrequest', we only want 'slackclient' # client_name = __name__.split('.')[0] # client_version = __version__ # Version is returned from version.py # # # Construct the user-agent header with the package info, Python version and OS version. # self.default_user_agent = { # "client": "{0}/{1}".format(client_name, client_version), # "python": "Python/{v.major}.{v.minor}.{v.micro}".format(v=sys.version_info), # "system": "{0}/{1}".format(platform.system(), platform.release()) # } # # self.custom_user_agent = None # self.proxies = proxies # # def get_user_agent(self): # # Check for custom user-agent and append if found # if self.custom_user_agent: # custom_ua_list = ["/".join(client_info) for client_info in self.custom_user_agent] # custom_ua_string = " ".join(custom_ua_list) # self.default_user_agent['custom'] = custom_ua_string # # # Concatenate and format the user-agent string to be passed into request headers # ua_string = [] # for key, val in self.default_user_agent.items(): # ua_string.append(val) # # user_agent_string = " ".join(ua_string) # return user_agent_string # # def append_user_agent(self, name, version): # if self.custom_user_agent: # self.custom_user_agent.append([name.replace("/", ":"), version.replace("/", ":")]) # else: # self.custom_user_agent = [[name, version]] # # def do(self, token, request="?", post_data=None, domain="slack.com", timeout=None): # """ # Perform a POST request to the Slack Web API # # Args: # token (str): your authentication token # request (str): the method to call from the Slack API. For example: 'channels.list' # timeout (float): stop waiting for a response after a given number of seconds # post_data (dict): key/value arguments to pass for the request. For example: # {'channel': 'CABC12345'} # domain (str): if for some reason you want to send your request to something other # than slack.com # """ # # # Pull file out so it isn't JSON encoded like normal fields. # # Only do this for requests that are UPLOADING files; downloading files # # use the 'file' argument to point to a File ID. # post_data = post_data or {} # upload_requests = ['files.upload'] # files = None # if request in upload_requests: # files = {'file': post_data.pop('file')} if 'file' in post_data else None # # for k, v in six.iteritems(post_data): # if not isinstance(v, six.string_types): # post_data[k] = json.dumps(v) # # url = 'https://{0}/api/{1}'.format(domain, request) # post_data['token'] = token # headers = {'user-agent': self.get_user_agent()} # # return requests.post(url, # headers=headers, # data=post_data, # files=files, # timeout=timeout, # proxies=self.proxies) # # Path: slackclient/channel.py # class Channel(object): # ''' # A Channel represents a public or private Slack Channel instance # ''' # def __init__(self, server, name, channel_id, members=None): # self.server = server # self.name = name # self.id = channel_id # self.members = [] if members is None else members # # def __eq__(self, compare_str): # if self.name == compare_str or "#" + self.name == compare_str or self.id == compare_str: # return True # else: # return False # # def __hash__(self): # return hash(self.id) # # def __str__(self): # data = "" # for key in list(self.__dict__.keys()): # data += "{0} : {1}\n".format(key, str(self.__dict__[key])[:40]) # return data # # def __repr__(self): # return self.__str__() # # def send_message(self, message, thread=None, reply_broadcast=False): # ''' # Sends a message to a this Channel. # # Include the parent message's thread_ts value in `thread` # to send to a thread. # # :Args: # message (message) - the string you'd like to send to the channel # thread (str or None) - the parent message ID, if sending to a # thread # reply_broadcast (bool) - if messaging a thread, whether to # also send the message back to the channel # # :Returns: # None # ''' # self.server.rtm_send_message(self.id, message, thread, reply_broadcast) . Output only the next line.
self.channels.append(Channel(self, name, channel_id, members))
Continue the code snippet: <|code_start|> class SlackRequest(object): def __init__(self, proxies=None): # __name__ returns 'slackclient.slackrequest', we only want 'slackclient' client_name = __name__.split('.')[0] <|code_end|> . Use current file imports: import json import requests import six import sys import platform from .version import __version__ and context (classes, functions, or code) from other files: # Path: slackclient/version.py . Output only the next line.
client_version = __version__ # Version is returned from version.py
Here is a snippet: <|code_start|> return change_to_id(magnum.cluster_show(request, cluster_id).to_dict()) @rest_utils.ajax(data_required=True) def patch(self, request, cluster_id): """Update a Cluster. Returns the Cluster object on success. """ params = request.DATA updated_cluster = magnum.cluster_update( request, cluster_id, **params) return rest_utils.CreatedResponse( '/api/container_infra/cluster/%s' % cluster_id, updated_cluster.to_dict()) @urls.register class ClusterResize(generic.View): url_regex = r'container_infra/clusters/(?P<cluster_id>[^/]+)/resize$' @rest_utils.ajax() def get(self, request, cluster_id): """Get cluster details for resize""" try: cluster = magnum.cluster_show(request, cluster_id).to_dict() except AttributeError as e: print(e) return HttpResponseNotFound() <|code_end|> . Write the next line using the current file imports: import logging import re from collections import defaultdict from django.conf import settings from django.http import HttpResponse from django.http import HttpResponseNotFound from django.views import generic from magnum_ui.api import heat from magnum_ui.api import magnum from openstack_dashboard import api from openstack_dashboard.api import neutron from openstack_dashboard.api.rest import urls from openstack_dashboard.api.rest import utils as rest_utils and context from other files: # Path: magnum_ui/api/heat.py # LOG = logging.getLogger(__name__) # def heatclient(request, password=None): # def format_parameters(params): # def stack_get(request, stack_id): # # Path: magnum_ui/api/magnum.py # LOG = logging.getLogger(__name__) # CLUSTER_TEMPLATE_CREATE_ATTRS = cluster_templates.CREATION_ATTRIBUTES # CLUSTER_CREATE_ATTRS = clusters.CREATION_ATTRIBUTES # CERTIFICATE_CREATE_ATTRS = certificates.CREATION_ATTRIBUTES # QUOTA_CREATION_ATTRIBUTES = quotas.CREATION_ATTRIBUTES # CLUSTER_UPDATE_ALLOWED_PROPERTIES = set(['/node_count']) # DEFAULT_API_VERSION = '1.10' # def _cleanup_params(attrs, create, **params): # def _create_patches(old, new): # def magnumclient(request): # def cluster_template_create(request, **kwargs): # def cluster_template_update(request, id, **kwargs): # def cluster_template_delete(request, id): # def cluster_template_list(request, limit=None, marker=None, sort_key=None, # sort_dir=None, detail=True): # def cluster_template_show(request, id): # def cluster_create(request, **kwargs): # def cluster_update(request, id, **kwargs): # def cluster_delete(request, id): # def cluster_list(request, limit=None, marker=None, sort_key=None, # sort_dir=None, detail=True): # def cluster_show(request, id): # def cluster_resize(request, cluster_id, node_count, # nodes_to_remove=None, nodegroup=None): # def cluster_upgrade(request, cluster_uuid, cluster_template, # max_batch_size=1, nodegroup=None): # def certificate_create(request, **kwargs): # def certificate_show(request, id): # def certificate_rotate(request, id): # def stats_list(request, project_id=None): # def quotas_list(request, limit=None, marker=None, sort_key=None, # sort_dir=None, all_tenants=True): # def quotas_show(request, project_id, resource): # def quotas_create(request, **kwargs): # def quotas_update(request, project_id, resource, **kwargs): # def quotas_delete(request, project_id, resource): , which may include functions, classes, or code. Output only the next line.
stack = heat.stack_get(request, cluster["stack_id"])
Based on the snippet: <|code_start|> available_addons = [] configured_addons = getattr( settings, "MAGNUM_AVAILABLE_ADDONS", []) for configured_addon in configured_addons: addon = {} try: addon["name"] = configured_addon["name"] addon["selected"] = configured_addon["selected"] assert type(addon["selected"]) is bool addon["labels"] = configured_addon["labels"] assert type(addon["labels"]) is dict available_addons.append(addon) except KeyError as e: LOG.exception(e) except AssertionError as e: LOG.exception(e) return {"addons": available_addons} @urls.register class ClusterTemplate(generic.View): """API for retrieving a single cluster template""" url_regex = r'container_infra/cluster_templates/(?P<template_id>[^/]+)$' @rest_utils.ajax() def get(self, request, template_id): """Get a specific cluster template""" <|code_end|> , predict the immediate next line with the help of imports: import logging import re from collections import defaultdict from django.conf import settings from django.http import HttpResponse from django.http import HttpResponseNotFound from django.views import generic from magnum_ui.api import heat from magnum_ui.api import magnum from openstack_dashboard import api from openstack_dashboard.api import neutron from openstack_dashboard.api.rest import urls from openstack_dashboard.api.rest import utils as rest_utils and context (classes, functions, sometimes code) from other files: # Path: magnum_ui/api/heat.py # LOG = logging.getLogger(__name__) # def heatclient(request, password=None): # def format_parameters(params): # def stack_get(request, stack_id): # # Path: magnum_ui/api/magnum.py # LOG = logging.getLogger(__name__) # CLUSTER_TEMPLATE_CREATE_ATTRS = cluster_templates.CREATION_ATTRIBUTES # CLUSTER_CREATE_ATTRS = clusters.CREATION_ATTRIBUTES # CERTIFICATE_CREATE_ATTRS = certificates.CREATION_ATTRIBUTES # QUOTA_CREATION_ATTRIBUTES = quotas.CREATION_ATTRIBUTES # CLUSTER_UPDATE_ALLOWED_PROPERTIES = set(['/node_count']) # DEFAULT_API_VERSION = '1.10' # def _cleanup_params(attrs, create, **params): # def _create_patches(old, new): # def magnumclient(request): # def cluster_template_create(request, **kwargs): # def cluster_template_update(request, id, **kwargs): # def cluster_template_delete(request, id): # def cluster_template_list(request, limit=None, marker=None, sort_key=None, # sort_dir=None, detail=True): # def cluster_template_show(request, id): # def cluster_create(request, **kwargs): # def cluster_update(request, id, **kwargs): # def cluster_delete(request, id): # def cluster_list(request, limit=None, marker=None, sort_key=None, # sort_dir=None, detail=True): # def cluster_show(request, id): # def cluster_resize(request, cluster_id, node_count, # nodes_to_remove=None, nodegroup=None): # def cluster_upgrade(request, cluster_uuid, cluster_template, # max_batch_size=1, nodegroup=None): # def certificate_create(request, **kwargs): # def certificate_show(request, id): # def certificate_rotate(request, id): # def stats_list(request, project_id=None): # def quotas_list(request, limit=None, marker=None, sort_key=None, # sort_dir=None, all_tenants=True): # def quotas_show(request, project_id, resource): # def quotas_create(request, **kwargs): # def quotas_update(request, project_id, resource, **kwargs): # def quotas_delete(request, project_id, resource): . Output only the next line.
return change_to_id(magnum.cluster_template_show(request, template_id)
Given snippet: <|code_start|> user = User.query.get('123123') self.assertIsNone(user) User.from_facebook('oauth_234234') mock_graphapi.assert_called_with(access_token='oauth_234234') graph_instance.get_object.assert_called_with(id='me') user = User.query.get('123123') self.assertIsNotNone(user) self.assertEqual('123123', user.id) self.assertEqual('oauth_234234', user.OAuth) self.assertEqual('m', user.gender) self.assertEqual(datetime(2015, 1, 1), user.last_poll) self.assertEqual('bob', user.real_name) self.assertEqual('Fake Name', user.fake_name) self.assertEqual('', user.facebook_urls) @freeze_time('2015-01-01') @mock.patch('blindr.models.user.facebook.GraphAPI') def test_from_facebook_update_user(self, mock_graphapi): graph_instance = mock_graphapi.return_value graph_instance.get_object.return_value = { 'id': '123123', 'name': 'bob', 'gender': 'male' } <|code_end|> , continue by predicting the next line. Consider current file imports: from datetime import datetime from freezegun import freeze_time from unittest import mock from tests.blindrtest import BlindrTest from tests.factory_boy.user_factory import UserFactory from blindr.models.user import User and context: # Path: tests/blindrtest.py # class BlindrTest(TestCase): # def create_app(self): # return create_app('config.test') # # def setUp(self): # db.create_all() # self.auth_user = UserFactory( # id='auth_user', # fake_name='Foo Bar', # real_name='Auth User', # last_poll=datetime(2000,1,1) # ) # # def tearDown(self): # db.session.remove() # db.drop_all() # # def auth_post(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.post(*args, **kwargs) # # def auth_get(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.get(*args, **kwargs) # # def _add_header_auth_token(self, kwargs): # s = itsdangerous.Signer(self.app.config['AUTH_SECRET']) # token = s.sign(b'auth_user').decode('utf-8') # # if not 'headers' in kwargs: # kwargs['headers'] = {} # # kwargs['headers']['X-User-Token'] = token # # Path: tests/factory_boy/user_factory.py # class UserFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = User # sqlalchemy_session = db.session # # id = factory.Sequence(lambda n: str(n)) # # fake_name = 'Fakename' # real_name = 'Realname' # gender = 'm' # # Path: blindr/models/user.py # class User(db.Model): # __tablename__ = 'users' # # id = db.Column(db.String, primary_key=True) # # OAuth = db.Column(db.String) # fake_name = db.Column(db.String(50), nullable = False) # real_name = db.Column(db.String(50)) # gender = db.Column(db.CHAR, nullable = False) # looking_for = db.Column(db.String) # last_poll = db.Column(db.TIMESTAMP) # facebook_urls = db.Column(db.String) # # @staticmethod # def from_facebook(fb_token): # user = None # graph = facebook.GraphAPI(access_token=fb_token) # fb_user = graph.get_object(id='me') # # session = db.session # user = session.query(User).filter_by(id=fb_user['id']).first() # if not user: # user = User(id= fb_user['id'], # OAuth= fb_token, # fake_name= name_generator.generate_name(), # real_name= fb_user['name'], # gender= _fb_gender_map[fb_user['gender'] or 'male'], # last_poll= datetime.utcnow(), # facebook_urls= "", # looking_for="") # # session.add(user) # # else: # user.OAuth= fb_token # user.gender= _fb_gender_map[fb_user['gender'] or 'male'] # user.last_poll= datetime.utcnow() # user.real_name= fb_user['name'] # # session.commit() # return user which might include code, classes, or functions. Output only the next line.
UserFactory(
Given snippet: <|code_start|> class UserTests(BlindrTest): @freeze_time('2015-01-01') @mock.patch('blindr.models.user.name_generator.generate_name') @mock.patch('blindr.models.user.facebook.GraphAPI') def test_from_facebook_new_user(self, mock_graphapi, mock_generate_name): graph_instance = mock_graphapi.return_value graph_instance.get_object.return_value = { 'id': '123123', 'name': 'bob', 'gender': 'male' } mock_generate_name.return_value = 'Fake Name' <|code_end|> , continue by predicting the next line. Consider current file imports: from datetime import datetime from freezegun import freeze_time from unittest import mock from tests.blindrtest import BlindrTest from tests.factory_boy.user_factory import UserFactory from blindr.models.user import User and context: # Path: tests/blindrtest.py # class BlindrTest(TestCase): # def create_app(self): # return create_app('config.test') # # def setUp(self): # db.create_all() # self.auth_user = UserFactory( # id='auth_user', # fake_name='Foo Bar', # real_name='Auth User', # last_poll=datetime(2000,1,1) # ) # # def tearDown(self): # db.session.remove() # db.drop_all() # # def auth_post(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.post(*args, **kwargs) # # def auth_get(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.get(*args, **kwargs) # # def _add_header_auth_token(self, kwargs): # s = itsdangerous.Signer(self.app.config['AUTH_SECRET']) # token = s.sign(b'auth_user').decode('utf-8') # # if not 'headers' in kwargs: # kwargs['headers'] = {} # # kwargs['headers']['X-User-Token'] = token # # Path: tests/factory_boy/user_factory.py # class UserFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = User # sqlalchemy_session = db.session # # id = factory.Sequence(lambda n: str(n)) # # fake_name = 'Fakename' # real_name = 'Realname' # gender = 'm' # # Path: blindr/models/user.py # class User(db.Model): # __tablename__ = 'users' # # id = db.Column(db.String, primary_key=True) # # OAuth = db.Column(db.String) # fake_name = db.Column(db.String(50), nullable = False) # real_name = db.Column(db.String(50)) # gender = db.Column(db.CHAR, nullable = False) # looking_for = db.Column(db.String) # last_poll = db.Column(db.TIMESTAMP) # facebook_urls = db.Column(db.String) # # @staticmethod # def from_facebook(fb_token): # user = None # graph = facebook.GraphAPI(access_token=fb_token) # fb_user = graph.get_object(id='me') # # session = db.session # user = session.query(User).filter_by(id=fb_user['id']).first() # if not user: # user = User(id= fb_user['id'], # OAuth= fb_token, # fake_name= name_generator.generate_name(), # real_name= fb_user['name'], # gender= _fb_gender_map[fb_user['gender'] or 'male'], # last_poll= datetime.utcnow(), # facebook_urls= "", # looking_for="") # # session.add(user) # # else: # user.OAuth= fb_token # user.gender= _fb_gender_map[fb_user['gender'] or 'male'] # user.last_poll= datetime.utcnow() # user.real_name= fb_user['name'] # # session.commit() # return user which might include code, classes, or functions. Output only the next line.
user = User.query.get('123123')
Next line prediction: <|code_start|> class EventTests(unittest.TestCase): @freeze_time('2015-01-01') def test_create(self): events.put_item = MagicMock(return_value = 'put_item_ret') <|code_end|> . Use current file imports: (import tests.utils.fake_dynamodb import unittest import time import boto from unittest.mock import MagicMock from freezegun import freeze_time from blindr.models.event import Event, events) and context including class names, function names, or small code snippets from other files: # Path: blindr/models/event.py # _ADJUSTED_DELAY = 5 # class Event(object): # def create(data): # def fetch(user=None, city=None, since=60): # def fetch_history(user, other,since=0): . Output only the next line.
event = Event.create({'foo': 'bar'})
Given the following code snippet before the placeholder: <|code_start|> class EventTests(unittest.TestCase): @freeze_time('2015-01-01') def test_create(self): <|code_end|> , predict the next line using imports from the current file: import tests.utils.fake_dynamodb import unittest import time import boto from unittest.mock import MagicMock from freezegun import freeze_time from blindr.models.event import Event, events and context including class names, function names, and sometimes code from other files: # Path: blindr/models/event.py # _ADJUSTED_DELAY = 5 # class Event(object): # def create(data): # def fetch(user=None, city=None, since=60): # def fetch_history(user, other,since=0): . Output only the next line.
events.put_item = MagicMock(return_value = 'put_item_ret')
Here is a snippet: <|code_start|> def token_authentication(token): if not token: return False s = itsdangerous.Signer(current_app.config['AUTH_SECRET']) user_id = False try: user_id = s.unsign(token).decode('utf-8') except itsdangerous.BadSignature: pass <|code_end|> . Write the next line using the current file imports: import itsdangerous from flask import request, abort, current_app from functools import wraps from blindr.models.user import User and context from other files: # Path: blindr/models/user.py # class User(db.Model): # __tablename__ = 'users' # # id = db.Column(db.String, primary_key=True) # # OAuth = db.Column(db.String) # fake_name = db.Column(db.String(50), nullable = False) # real_name = db.Column(db.String(50)) # gender = db.Column(db.CHAR, nullable = False) # looking_for = db.Column(db.String) # last_poll = db.Column(db.TIMESTAMP) # facebook_urls = db.Column(db.String) # # @staticmethod # def from_facebook(fb_token): # user = None # graph = facebook.GraphAPI(access_token=fb_token) # fb_user = graph.get_object(id='me') # # session = db.session # user = session.query(User).filter_by(id=fb_user['id']).first() # if not user: # user = User(id= fb_user['id'], # OAuth= fb_token, # fake_name= name_generator.generate_name(), # real_name= fb_user['name'], # gender= _fb_gender_map[fb_user['gender'] or 'male'], # last_poll= datetime.utcnow(), # facebook_urls= "", # looking_for="") # # session.add(user) # # else: # user.OAuth= fb_token # user.gender= _fb_gender_map[fb_user['gender'] or 'male'] # user.last_poll= datetime.utcnow() # user.real_name= fb_user['name'] # # session.commit() # return user , which may include functions, classes, or code. Output only the next line.
return User.query.get(user_id)
Predict the next line for this snippet: <|code_start|> def post(self): dst_city = request.form.get('dst_city') dst_user = request.form.get('dst_user') message = request.form.get('message') dst = None if dst_city: dst = 'city:{}'.format(dst_city.lower()) elif dst_user: dst = 'user:{}'.format(dst_user) if dst is None: abort(422) if not message: abort(422) data = { 'type': 'message', 'dst': dst, 'src': self.user.id, 'src_gender': self.user.gender, 'message': message } if dst_user: data['participants'] = '{}:{}'.format(*sorted([self.user.id,dst_user])) data['src_real_name'] = self.user.real_name data['src_fake_name'] = self.user.fake_name <|code_end|> with the help of current file imports: from flask.ext import restful from blindr.common.authenticate import authenticate from flask import request, abort from blindr.models.event import Event from blindr.models.user import User import time import config and context from other files: # Path: blindr/common/authenticate.py # def authenticate(func): # @wraps(func) # def wrapper(*args, **kwargs): # user = token_authentication(request.headers.get('X-User-Token')) # if user: # func.__self__.user = user # return func(*args, **kwargs) # abort(401) # return wrapper # # Path: blindr/models/event.py # class Event(object): # # @staticmethod # def create(data): # data['sent_at'] = time.time() # data['event_id'] = str(uuid.uuid4()) # return events.put_item(data=data) # # @staticmethod # def fetch(user=None, city=None, since=60): # adjusted_since = since - 60 # dst = '' # # if user: # dst = 'user:{}'.format(user) # if city: # dst = 'city:{}'.format(city) # # resultset = events.query_2( # dst__eq=dst, # sent_at__gte=adjusted_since) # # items = [dict(item) for item in resultset] # for item in items: # item['sent_at'] = float(item['sent_at']) # # return items # # @staticmethod # def fetch_history(user, other,since=0): # resultset = events.query_2( # participants__eq= '{}:{}'.format(*sorted([user,other])), # index= 'participants-index', # sent_at__gte=since) # # items = [dict(item) for item in resultset] # for item in items: # item['sent_at'] = float(item['sent_at']) # # return list(items) # # Path: blindr/models/user.py # class User(db.Model): # __tablename__ = 'users' # # id = db.Column(db.String, primary_key=True) # # OAuth = db.Column(db.String) # fake_name = db.Column(db.String(50), nullable = False) # real_name = db.Column(db.String(50)) # gender = db.Column(db.CHAR, nullable = False) # looking_for = db.Column(db.String) # last_poll = db.Column(db.TIMESTAMP) # facebook_urls = db.Column(db.String) # # @staticmethod # def from_facebook(fb_token): # user = None # graph = facebook.GraphAPI(access_token=fb_token) # fb_user = graph.get_object(id='me') # # session = db.session # user = session.query(User).filter_by(id=fb_user['id']).first() # if not user: # user = User(id= fb_user['id'], # OAuth= fb_token, # fake_name= name_generator.generate_name(), # real_name= fb_user['name'], # gender= _fb_gender_map[fb_user['gender'] or 'male'], # last_poll= datetime.utcnow(), # facebook_urls= "", # looking_for="") # # session.add(user) # # else: # user.OAuth= fb_token # user.gender= _fb_gender_map[fb_user['gender'] or 'male'] # user.last_poll= datetime.utcnow() # user.real_name= fb_user['name'] # # session.commit() # return user , which may contain function names, class names, or code. Output only the next line.
success = Event.create(data)
Based on the snippet: <|code_start|> class LikeTest(BlindrTest): def test_post_first_like(self): UserFactory(id='user2') rv = self.auth_post('/events/like', data=dict(dst_user='user2')) rv_data = json.loads(rv.data.decode('utf-8')) self.assert_200(rv) match = Match.query.get((self.auth_user.id,'user2')) self.assertIsNotNone(match) self.assertFalse(match.mutual) @mock.patch('blindr.api.like.Event.create') def test_post_match(self, mock_create_event): <|code_end|> , predict the immediate next line with the help of imports: from tests.blindrtest import BlindrTest from tests.factory_boy.match_factory import MatchFactory from tests.factory_boy.user_factory import UserFactory from blindr.models.match import Match from unittest import mock import json and context (classes, functions, sometimes code) from other files: # Path: tests/blindrtest.py # class BlindrTest(TestCase): # def create_app(self): # return create_app('config.test') # # def setUp(self): # db.create_all() # self.auth_user = UserFactory( # id='auth_user', # fake_name='Foo Bar', # real_name='Auth User', # last_poll=datetime(2000,1,1) # ) # # def tearDown(self): # db.session.remove() # db.drop_all() # # def auth_post(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.post(*args, **kwargs) # # def auth_get(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.get(*args, **kwargs) # # def _add_header_auth_token(self, kwargs): # s = itsdangerous.Signer(self.app.config['AUTH_SECRET']) # token = s.sign(b'auth_user').decode('utf-8') # # if not 'headers' in kwargs: # kwargs['headers'] = {} # # kwargs['headers']['X-User-Token'] = token # # Path: tests/factory_boy/match_factory.py # class MatchFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = Match # sqlalchemy_session = db.session # # @staticmethod # def mutual_match(user1,user2): # MatchFactory( # match_to_id=user2.id, # match_from_id=user1.id, # mutual=True # ) # MatchFactory( # match_to_id=user1.id, # match_from_id=user2.id, # mutual=True # ) # # match_from_id = factory.SubFactory(UserFactory) # match_to_id = factory.SubFactory(UserFactory) # mutual = False # # Path: tests/factory_boy/user_factory.py # class UserFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = User # sqlalchemy_session = db.session # # id = factory.Sequence(lambda n: str(n)) # # fake_name = 'Fakename' # real_name = 'Realname' # gender = 'm' # # Path: blindr/models/match.py # class Match(db.Model): # __tablename__ = 'matches' # # match_from_id = db.Column(db.String, db.ForeignKey('users.id')) # match_to_id = db.Column(db.String, db.ForeignKey('users.id')) # mutual = db.Column(db.Boolean) # # __table_args__ = (db.PrimaryKeyConstraint('match_from_id', 'match_to_id'),) . Output only the next line.
MatchFactory(
Given the following code snippet before the placeholder: <|code_start|> class LikeTest(BlindrTest): def test_post_first_like(self): UserFactory(id='user2') rv = self.auth_post('/events/like', data=dict(dst_user='user2')) rv_data = json.loads(rv.data.decode('utf-8')) self.assert_200(rv) <|code_end|> , predict the next line using imports from the current file: from tests.blindrtest import BlindrTest from tests.factory_boy.match_factory import MatchFactory from tests.factory_boy.user_factory import UserFactory from blindr.models.match import Match from unittest import mock import json and context including class names, function names, and sometimes code from other files: # Path: tests/blindrtest.py # class BlindrTest(TestCase): # def create_app(self): # return create_app('config.test') # # def setUp(self): # db.create_all() # self.auth_user = UserFactory( # id='auth_user', # fake_name='Foo Bar', # real_name='Auth User', # last_poll=datetime(2000,1,1) # ) # # def tearDown(self): # db.session.remove() # db.drop_all() # # def auth_post(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.post(*args, **kwargs) # # def auth_get(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.get(*args, **kwargs) # # def _add_header_auth_token(self, kwargs): # s = itsdangerous.Signer(self.app.config['AUTH_SECRET']) # token = s.sign(b'auth_user').decode('utf-8') # # if not 'headers' in kwargs: # kwargs['headers'] = {} # # kwargs['headers']['X-User-Token'] = token # # Path: tests/factory_boy/match_factory.py # class MatchFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = Match # sqlalchemy_session = db.session # # @staticmethod # def mutual_match(user1,user2): # MatchFactory( # match_to_id=user2.id, # match_from_id=user1.id, # mutual=True # ) # MatchFactory( # match_to_id=user1.id, # match_from_id=user2.id, # mutual=True # ) # # match_from_id = factory.SubFactory(UserFactory) # match_to_id = factory.SubFactory(UserFactory) # mutual = False # # Path: tests/factory_boy/user_factory.py # class UserFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = User # sqlalchemy_session = db.session # # id = factory.Sequence(lambda n: str(n)) # # fake_name = 'Fakename' # real_name = 'Realname' # gender = 'm' # # Path: blindr/models/match.py # class Match(db.Model): # __tablename__ = 'matches' # # match_from_id = db.Column(db.String, db.ForeignKey('users.id')) # match_to_id = db.Column(db.String, db.ForeignKey('users.id')) # mutual = db.Column(db.Boolean) # # __table_args__ = (db.PrimaryKeyConstraint('match_from_id', 'match_to_id'),) . Output only the next line.
match = Match.query.get((self.auth_user.id,'user2'))
Continue the code snippet: <|code_start|> class NameGeneratorTest(unittest.TestCase): @mock.patch('blindr.common.name_generator.random.choice') def test_generate_name(self, mock_random_choice): mock_random_choice.side_effect = lambda x: x[0] <|code_end|> . Use current file imports: import unittest from unittest import mock from blindr.common import name_generator and context (classes, functions, or code) from other files: # Path: blindr/common/name_generator.py # def generate_name(): . Output only the next line.
name_generator.nouns = ('foo',)
Predict the next line for this snippet: <|code_start|> class History(restful.Resource): method_decorators=[authenticate] def get(self, other_id): sinceParam = int(request.args.get('since')) <|code_end|> with the help of current file imports: from flask.ext import restful from blindr.common.authenticate import authenticate from flask import request, abort from blindr.models.event import Event and context from other files: # Path: blindr/common/authenticate.py # def authenticate(func): # @wraps(func) # def wrapper(*args, **kwargs): # user = token_authentication(request.headers.get('X-User-Token')) # if user: # func.__self__.user = user # return func(*args, **kwargs) # abort(401) # return wrapper # # Path: blindr/models/event.py # class Event(object): # # @staticmethod # def create(data): # data['sent_at'] = time.time() # data['event_id'] = str(uuid.uuid4()) # return events.put_item(data=data) # # @staticmethod # def fetch(user=None, city=None, since=60): # adjusted_since = since - 60 # dst = '' # # if user: # dst = 'user:{}'.format(user) # if city: # dst = 'city:{}'.format(city) # # resultset = events.query_2( # dst__eq=dst, # sent_at__gte=adjusted_since) # # items = [dict(item) for item in resultset] # for item in items: # item['sent_at'] = float(item['sent_at']) # # return items # # @staticmethod # def fetch_history(user, other,since=0): # resultset = events.query_2( # participants__eq= '{}:{}'.format(*sorted([user,other])), # index= 'participants-index', # sent_at__gte=since) # # items = [dict(item) for item in resultset] # for item in items: # item['sent_at'] = float(item['sent_at']) # # return list(items) , which may contain function names, class names, or code. Output only the next line.
return Event.fetch_history(user= self.user.id,
Based on the snippet: <|code_start|> class DislikeTest(BlindrTest): def test_post_dislike(self): MatchFactory( match_from_id=self.auth_user.id, <|code_end|> , predict the immediate next line with the help of imports: from tests.blindrtest import BlindrTest from tests.factory_boy.match_factory import MatchFactory from tests.factory_boy.user_factory import UserFactory from blindr.models.match import Match from unittest import mock import json and context (classes, functions, sometimes code) from other files: # Path: tests/blindrtest.py # class BlindrTest(TestCase): # def create_app(self): # return create_app('config.test') # # def setUp(self): # db.create_all() # self.auth_user = UserFactory( # id='auth_user', # fake_name='Foo Bar', # real_name='Auth User', # last_poll=datetime(2000,1,1) # ) # # def tearDown(self): # db.session.remove() # db.drop_all() # # def auth_post(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.post(*args, **kwargs) # # def auth_get(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.get(*args, **kwargs) # # def _add_header_auth_token(self, kwargs): # s = itsdangerous.Signer(self.app.config['AUTH_SECRET']) # token = s.sign(b'auth_user').decode('utf-8') # # if not 'headers' in kwargs: # kwargs['headers'] = {} # # kwargs['headers']['X-User-Token'] = token # # Path: tests/factory_boy/match_factory.py # class MatchFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = Match # sqlalchemy_session = db.session # # @staticmethod # def mutual_match(user1,user2): # MatchFactory( # match_to_id=user2.id, # match_from_id=user1.id, # mutual=True # ) # MatchFactory( # match_to_id=user1.id, # match_from_id=user2.id, # mutual=True # ) # # match_from_id = factory.SubFactory(UserFactory) # match_to_id = factory.SubFactory(UserFactory) # mutual = False # # Path: tests/factory_boy/user_factory.py # class UserFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = User # sqlalchemy_session = db.session # # id = factory.Sequence(lambda n: str(n)) # # fake_name = 'Fakename' # real_name = 'Realname' # gender = 'm' # # Path: blindr/models/match.py # class Match(db.Model): # __tablename__ = 'matches' # # match_from_id = db.Column(db.String, db.ForeignKey('users.id')) # match_to_id = db.Column(db.String, db.ForeignKey('users.id')) # mutual = db.Column(db.Boolean) # # __table_args__ = (db.PrimaryKeyConstraint('match_from_id', 'match_to_id'),) . Output only the next line.
match_to_id=UserFactory(id='user2').id,
Based on the snippet: <|code_start|> class DislikeTest(BlindrTest): def test_post_dislike(self): MatchFactory( match_from_id=self.auth_user.id, match_to_id=UserFactory(id='user2').id, mutual=True ) rv = self.auth_post('/events/dislike', data=dict(dst_user='user2')) rv_data = json.loads(rv.data.decode('utf-8')) self.assert_200(rv) self.assertEqual('user2', rv_data['ignore']) <|code_end|> , predict the immediate next line with the help of imports: from tests.blindrtest import BlindrTest from tests.factory_boy.match_factory import MatchFactory from tests.factory_boy.user_factory import UserFactory from blindr.models.match import Match from unittest import mock import json and context (classes, functions, sometimes code) from other files: # Path: tests/blindrtest.py # class BlindrTest(TestCase): # def create_app(self): # return create_app('config.test') # # def setUp(self): # db.create_all() # self.auth_user = UserFactory( # id='auth_user', # fake_name='Foo Bar', # real_name='Auth User', # last_poll=datetime(2000,1,1) # ) # # def tearDown(self): # db.session.remove() # db.drop_all() # # def auth_post(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.post(*args, **kwargs) # # def auth_get(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.get(*args, **kwargs) # # def _add_header_auth_token(self, kwargs): # s = itsdangerous.Signer(self.app.config['AUTH_SECRET']) # token = s.sign(b'auth_user').decode('utf-8') # # if not 'headers' in kwargs: # kwargs['headers'] = {} # # kwargs['headers']['X-User-Token'] = token # # Path: tests/factory_boy/match_factory.py # class MatchFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = Match # sqlalchemy_session = db.session # # @staticmethod # def mutual_match(user1,user2): # MatchFactory( # match_to_id=user2.id, # match_from_id=user1.id, # mutual=True # ) # MatchFactory( # match_to_id=user1.id, # match_from_id=user2.id, # mutual=True # ) # # match_from_id = factory.SubFactory(UserFactory) # match_to_id = factory.SubFactory(UserFactory) # mutual = False # # Path: tests/factory_boy/user_factory.py # class UserFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = User # sqlalchemy_session = db.session # # id = factory.Sequence(lambda n: str(n)) # # fake_name = 'Fakename' # real_name = 'Realname' # gender = 'm' # # Path: blindr/models/match.py # class Match(db.Model): # __tablename__ = 'matches' # # match_from_id = db.Column(db.String, db.ForeignKey('users.id')) # match_to_id = db.Column(db.String, db.ForeignKey('users.id')) # mutual = db.Column(db.Boolean) # # __table_args__ = (db.PrimaryKeyConstraint('match_from_id', 'match_to_id'),) . Output only the next line.
self.assertIsNone(Match.query.get((self.auth_user.id,'user2')))
Using the snippet: <|code_start|> class Auth(restful.Resource): def post(self): fb_token = request.form.get('fb_token') <|code_end|> , determine the next line of code. You have imports: from flask.ext import restful from flask import current_app, request, abort from blindr.models.user import User import itsdangerous and context (class names, function names, or code) available: # Path: blindr/models/user.py # class User(db.Model): # __tablename__ = 'users' # # id = db.Column(db.String, primary_key=True) # # OAuth = db.Column(db.String) # fake_name = db.Column(db.String(50), nullable = False) # real_name = db.Column(db.String(50)) # gender = db.Column(db.CHAR, nullable = False) # looking_for = db.Column(db.String) # last_poll = db.Column(db.TIMESTAMP) # facebook_urls = db.Column(db.String) # # @staticmethod # def from_facebook(fb_token): # user = None # graph = facebook.GraphAPI(access_token=fb_token) # fb_user = graph.get_object(id='me') # # session = db.session # user = session.query(User).filter_by(id=fb_user['id']).first() # if not user: # user = User(id= fb_user['id'], # OAuth= fb_token, # fake_name= name_generator.generate_name(), # real_name= fb_user['name'], # gender= _fb_gender_map[fb_user['gender'] or 'male'], # last_poll= datetime.utcnow(), # facebook_urls= "", # looking_for="") # # session.add(user) # # else: # user.OAuth= fb_token # user.gender= _fb_gender_map[fb_user['gender'] or 'male'] # user.last_poll= datetime.utcnow() # user.real_name= fb_user['name'] # # session.commit() # return user . Output only the next line.
user = User.from_facebook(fb_token)
Based on the snippet: <|code_start|> class AuthTest(BlindrTest): @mock.patch('blindr.api.auth.User.from_facebook') def test_success_auth(self, mock_user): <|code_end|> , predict the immediate next line with the help of imports: from tests.blindrtest import BlindrTest from tests.factory_boy.user_factory import UserFactory from unittest import mock import json and context (classes, functions, sometimes code) from other files: # Path: tests/blindrtest.py # class BlindrTest(TestCase): # def create_app(self): # return create_app('config.test') # # def setUp(self): # db.create_all() # self.auth_user = UserFactory( # id='auth_user', # fake_name='Foo Bar', # real_name='Auth User', # last_poll=datetime(2000,1,1) # ) # # def tearDown(self): # db.session.remove() # db.drop_all() # # def auth_post(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.post(*args, **kwargs) # # def auth_get(self, *args, **kwargs): # self._add_header_auth_token(kwargs) # return self.client.get(*args, **kwargs) # # def _add_header_auth_token(self, kwargs): # s = itsdangerous.Signer(self.app.config['AUTH_SECRET']) # token = s.sign(b'auth_user').decode('utf-8') # # if not 'headers' in kwargs: # kwargs['headers'] = {} # # kwargs['headers']['X-User-Token'] = token # # Path: tests/factory_boy/user_factory.py # class UserFactory(factory.alchemy.SQLAlchemyModelFactory): # class Meta: # model = User # sqlalchemy_session = db.session # # id = factory.Sequence(lambda n: str(n)) # # fake_name = 'Fakename' # real_name = 'Realname' # gender = 'm' . Output only the next line.
user = UserFactory.create(id='123123')
Next line prediction: <|code_start|> previous = mo.retrieve("group", unique_id=test.prev_uid)[0] assert len(previous.items) == 2, repr(previous) def test_store_stubs(sqlite): test = mo.Group(items=[mo.Group(items=[mo.LcmsRun()]), mo.LcmsRun()]) mo.store(test) test = mo.retrieve("group", unique_id=test.unique_id)[0] assert isinstance(test.items[0], mo.Group) mo.store(test) def test_user_preserve(sqlite): run = mo.LcmsRun(username="foo") test = mo.Reference(name="hello", username="foo", lcms_run=run) orig_id = test.unique_id mo.store(test, _override=True) assert test.unique_id == orig_id mo.store(test) assert test.unique_id != orig_id items = mo.retrieve("reference", username="*", name="hello") username = getpass.getuser() assert items[-2].username == "foo" assert items[-1].username == username assert items[-2].lcms_run.username == "foo" assert items[-1].lcms_run.username == "foo" def test_store_all(sqlite): items = [] <|code_end|> . Use current file imports: (import getpass import dill from metatlas.datastructures import metatlas_objects as mo from metatlas.datastructures import object_helpers as metoh) and context including class names, function names, or small code snippets from other files: # Path: metatlas/datastructures/metatlas_objects.py # FETCH_STUBS = True # ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-','[2M+H]+','[2M-H]-','[M-H+Na]+','[M+K]+','[M+2Na]2+','[M-e]+','[M+acetate]-','[M+formate]-','[M-H+Cl]2-','[M-H+2Na]+') # POLARITY = ('positive', 'negative', 'alternating') # FRAGMENTATION_TECHNIQUE = ('hcd','cid','etd','ecd','irmpd') # ID_GRADES: Dict[str, IdentificationGrade] = dict() # FETCH_STUBS = False # FETCH_STUBS = True # FETCH_STUBS = True # def retrieve(object_type, **kwargs): # def remove(object_type, **kwargs): # def remove_objects(objects, all_versions=True, **kwargs): # def store(objects, **kwargs): # def __init__(self, **kwargs): # def _update(self, override_user=False): # def clone(self, recursive=False): # def show_diff(self, unique_id=None): # def _on_update(self, change): # def __str__(self): # def __repr__(self): # def __getattribute__(self, name): # def validate(self, obj, value): # def find_invalid_runs(**kwargs): # def to_dataframe(objects): # class MetatlasObject(HasTraits): # class Method(MetatlasObject): # class Sample(MetatlasObject): # class LcmsRun(MetatlasObject): # class FunctionalSet(MetatlasObject): # class Compound(MetatlasObject): # class Reference(MetatlasObject): # class IdentificationGrade(MetatlasObject): # class _IdGradeTrait(MetInstance): # class Group(MetatlasObject): # class MzIntensityPair(MetatlasObject): # class FragmentationReference(Reference): # class RtReference(Reference): # class MzReference(Reference): # class IntensityReference(Reference): # class CompoundIdentification(MetatlasObject): # class Atlas(MetatlasObject): # class MZMineTask(MetatlasObject): # # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
for klass in metoh.Workspace.get_instance().subclass_lut.values():
Given snippet: <|code_start|>def remove_objects(objects, all_versions=True, **kwargs): """Remove objects from the database. Parameters ---------- all_versions: boolean, optional If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, str): print('remove_objects() expects actual objects, use remove() to' 'remove objects by type.') workspace = Workspace.get_instance() workspace.remove_objects(objects, all_versions, **kwargs) workspace.close_connection() def store(objects, **kwargs): """Store Metatlas objects in the database. Parameters ---------- objects: Metatlas object or list of Metatlas Objects Object(s) to store in the database. """ workspace = Workspace.get_instance() workspace.save_objects(objects, **kwargs) workspace.close_connection() <|code_end|> , continue by predicting the next line. Consider current file imports: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): which might include code, classes, or functions. Output only the next line.
@set_docstring
Given the code snippet: <|code_start|># Whether to fetch stubs automatically, disabled when we want to display # a large number of objects. FETCH_STUBS = True ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-','[2M+H]+','[2M-H]-','[M-H+Na]+','[M+K]+','[M+2Na]2+','[M-e]+','[M+acetate]-','[M+formate]-','[M-H+Cl]2-','[M-H+2Na]+') POLARITY = ('positive', 'negative', 'alternating') FRAGMENTATION_TECHNIQUE = ('hcd','cid','etd','ecd','irmpd') def retrieve(object_type, **kwargs): """Get objects from the Metatlas object database. This will automatically select only objects created by the current user unless `username` is provided. Use `username='*'` to search against all users. Parameters ---------- object_type: string The type of object to search for (i.e. "Groups"). **kwargs Specific search queries (i.e. name="Sargasso"). Use '%' for wildcard patterns (i.e. description='Hello%'). If you want to match a '%' character, use '%%'. Returns ------- objects: list List of Metatlas Objects meeting the criteria. Will return the latest version of each object. """ <|code_end|> , generate the next line using the imports in this file: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context (functions, classes, or occasionally code) from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
workspace = Workspace.get_instance()
Given the following code snippet before the placeholder: <|code_start|> if val.unique_id != other.unique_id: msg.append((tname, other.unique_id, val.unique_id)) elif isinstance(trait, MetList): if not len(val) == len(other): msg.append((tname, '%s items' % len(other), '%s items' % len(val))) else: for (v, o) in zip(val, other): if not v.unique_id == o.unique_id: msg.append((tname, 'objects changed', '')) break elif val != other: msg.append((tname, str(other), str(val))) print((tabulate(msg))) def _on_update(self, change): """When the model changes, set the update fields. """ if self._loopback_guard or change['name'].startswith('_'): return self._changed = True def __str__(self): return self.__repr__() def __repr__(self): names = sorted(self.trait_names()) names.remove('name') names = ['name'] + [n for n in names if not n.startswith('_')] state = dict([(n, getattr(self, n)) for n in names]) <|code_end|> , predict the next line using imports from the current file: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
state['creation_time'] = format_timestamp(self.creation_time)
Here is a snippet: <|code_start|> self.last_modified = time.time() return True, None else: changed, prev_uid = self._changed, self.prev_uid if changed: self.last_modified = time.time() self.prev_uid = uuid.uuid4().hex self._changed = False self._loopback_guard = False return changed, prev_uid def clone(self, recursive=False): """Create a new version of this object. Parameters ---------- recursive: boolean, optional If true, clone all of the descendant objects as well. Returns ------- obj: MetatlasObject Cloned object. """ logger.debug('Cloning instance of %s with recursive=%s', self.__class__.__name__, recursive) obj = self.__class__() for (tname, trait) in self.traits().items(): if tname.startswith('_') or trait.metadata.get('readonly', False): continue val = getattr(self, tname) <|code_end|> . Write the next line using the current file imports: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): , which may include functions, classes, or code. Output only the next line.
if recursive and isinstance(trait, MetList):
Given the code snippet: <|code_start|> Parameters ---------- all_versions: boolean, optional If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, str): print('remove_objects() expects actual objects, use remove() to' 'remove objects by type.') workspace = Workspace.get_instance() workspace.remove_objects(objects, all_versions, **kwargs) workspace.close_connection() def store(objects, **kwargs): """Store Metatlas objects in the database. Parameters ---------- objects: Metatlas object or list of Metatlas Objects Object(s) to store in the database. """ workspace = Workspace.get_instance() workspace.save_objects(objects, **kwargs) workspace.close_connection() @set_docstring class MetatlasObject(HasTraits): <|code_end|> , generate the next line using the imports in this file: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context (functions, classes, or occasionally code) from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
name = MetUnicode('Untitled', help='Name of the object')
Given the following code snippet before the placeholder: <|code_start|># ctime = os.stat(fname).st_ctime # run = LcmsRun(name=filename, description=description, # created_by=user, # modified_by=user, # created=ctime, last_modified=ctime, # mzml_file=fname, hdf5_file=hdf_file) # runs.append(run) # except Exception as e: # print(e) # store(runs) # return runs @set_docstring class LcmsRun(MetatlasObject): """An LCMS run is the reference to a file prepared with liquid chromatography and mass spectrometry. The msconvert program is used to convert raw data (centroided is prefered) to mzML. Note: These objects are not intented to be created directly, but by putting the files in /project/projectdirs/metatlas/raw_data/<username> or by running `load_lcms_files()`. """ method = MetInstance(Method) experiment = MetUnicode(help='The name of the experiment') hdf5_file = MetUnicode(help='Path to the HDF5 file at NERSC') mzml_file = MetUnicode(help='Path to the MZML file at NERSC') acquisition_time = MetInt(help='Unix timestamp when data was acquired creation') <|code_end|> , predict the next line using imports from the current file: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
injection_volume = MetFloat()
Predict the next line for this snippet: <|code_start|> else: changed, prev_uid = self._changed, self.prev_uid if changed: self.last_modified = time.time() self.prev_uid = uuid.uuid4().hex self._changed = False self._loopback_guard = False return changed, prev_uid def clone(self, recursive=False): """Create a new version of this object. Parameters ---------- recursive: boolean, optional If true, clone all of the descendant objects as well. Returns ------- obj: MetatlasObject Cloned object. """ logger.debug('Cloning instance of %s with recursive=%s', self.__class__.__name__, recursive) obj = self.__class__() for (tname, trait) in self.traits().items(): if tname.startswith('_') or trait.metadata.get('readonly', False): continue val = getattr(self, tname) if recursive and isinstance(trait, MetList): val = [v.clone(True) for v in val] <|code_end|> with the help of current file imports: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): , which may contain function names, class names, or code. Output only the next line.
elif recursive and isinstance(trait, MetInstance) and val:
Continue the code snippet: <|code_start|> If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, str): print('remove_objects() expects actual objects, use remove() to' 'remove objects by type.') workspace = Workspace.get_instance() workspace.remove_objects(objects, all_versions, **kwargs) workspace.close_connection() def store(objects, **kwargs): """Store Metatlas objects in the database. Parameters ---------- objects: Metatlas object or list of Metatlas Objects Object(s) to store in the database. """ workspace = Workspace.get_instance() workspace.save_objects(objects, **kwargs) workspace.close_connection() @set_docstring class MetatlasObject(HasTraits): name = MetUnicode('Untitled', help='Name of the object') description = MetUnicode('No description', help='Description of the object') unique_id = MetUnicode(help='Unique identifier for the object').tag(readonly=True) <|code_end|> . Use current file imports: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context (classes, functions, or code) from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
creation_time = MetInt(help='Unix timestamp at object creation').tag(readonly=True)
Predict the next line for this snippet: <|code_start|> how the sample was prepared and LCMS data was collected. """ protocol_ref = MetUnicode(help='Reference to a published protocol: ' + 'identical to the protocol used.') quenching_method = MetUnicode(help='Description of the method used to ' + 'stop metabolism.') extraction_solvent = MetUnicode(help='Solvent or solvent mixture used to ' + 'extract metabolites.') reconstitution_method = MetUnicode(help='Solvent or solvent mixture ' + 'the extract is reconstituted in prior to injection for an LCMS Run.') mobile_phase_a = MetUnicode(help='Solvent or solvent mixture.') mobile_phase_b = MetUnicode(help='Solvent or solvent mixture.') temporal_parameters = MetUnicode('List of temporal changes to the' + 'mixing of mobile_phase_a and mobile_phase_b.') #Time = MetList() #Flow = MetList() #A_percent = MetList() #B_percent = MetList() #Chromatography Stack #Model #Serial Number #Modules column_model = MetUnicode(help='Brand and catalog number of the column') column_type = MetUnicode(help='Class of column used.') scan_mz_range = MetUnicode(help='Minimum and ' + 'maximum mz recorded for a run.') instrument = MetUnicode(help='Brand and catalog number for the ' + 'mass spectrometer.') ion_source = MetUnicode(help='Method for ionization.') mass_analyzer = MetUnicode(help='Method for detection.') <|code_end|> with the help of current file imports: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): , which may contain function names, class names, or code. Output only the next line.
polarity = MetEnum(POLARITY, 'positive', help='polarity for the run')
Predict the next line after this snippet: <|code_start|> 'remove objects by type.') workspace = Workspace.get_instance() workspace.remove_objects(objects, all_versions, **kwargs) workspace.close_connection() def store(objects, **kwargs): """Store Metatlas objects in the database. Parameters ---------- objects: Metatlas object or list of Metatlas Objects Object(s) to store in the database. """ workspace = Workspace.get_instance() workspace.save_objects(objects, **kwargs) workspace.close_connection() @set_docstring class MetatlasObject(HasTraits): name = MetUnicode('Untitled', help='Name of the object') description = MetUnicode('No description', help='Description of the object') unique_id = MetUnicode(help='Unique identifier for the object').tag(readonly=True) creation_time = MetInt(help='Unix timestamp at object creation').tag(readonly=True) username = MetUnicode(help='Username who created the object').tag(readonly=True) last_modified = MetInt(help='Unix timestamp at last object update').tag(readonly=True) prev_uid = MetUnicode(help='Unique id of previous version').tag(readonly=True) head_id = MetUnicode(help='Unique id of most recent version of this object').tag(readonly=True) <|code_end|> using the current file's imports: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and any relevant context from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
_loopback_guard = MetBool(False).tag(readonly=True)
Based on the snippet: <|code_start|> """Remove objects from the database. Parameters ---------- all_versions: boolean, optional If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, str): print('remove_objects() expects actual objects, use remove() to' 'remove objects by type.') workspace = Workspace.get_instance() workspace.remove_objects(objects, all_versions, **kwargs) workspace.close_connection() def store(objects, **kwargs): """Store Metatlas objects in the database. Parameters ---------- objects: Metatlas object or list of Metatlas Objects Object(s) to store in the database. """ workspace = Workspace.get_instance() workspace.save_objects(objects, **kwargs) workspace.close_connection() @set_docstring <|code_end|> , predict the immediate next line with the help of imports: import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip and context (classes, functions, sometimes code) from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
class MetatlasObject(HasTraits):
Next line prediction: <|code_start|> break elif val != other: msg.append((tname, str(other), str(val))) print((tabulate(msg))) def _on_update(self, change): """When the model changes, set the update fields. """ if self._loopback_guard or change['name'].startswith('_'): return self._changed = True def __str__(self): return self.__repr__() def __repr__(self): names = sorted(self.trait_names()) names.remove('name') names = ['name'] + [n for n in names if not n.startswith('_')] state = dict([(n, getattr(self, n)) for n in names]) state['creation_time'] = format_timestamp(self.creation_time) state['last_modified'] = format_timestamp(self.last_modified) return pprint.pformat(state) #str(state)# def __getattribute__(self, name): """Automatically resolve stubs on demand. """ # value = super(MetatlasObject, self).__getattribute__(name) value = super().__getattribute__(name) <|code_end|> . Use current file imports: (import getpass import logging import os import pprint import time import uuid import pandas as pd from typing import Dict from pwd import getpwuid from tabulate import tabulate from .object_helpers import ( set_docstring, Workspace, format_timestamp, MetList, MetUnicode, MetFloat, MetInstance, MetInt, MetEnum, MetBool, HasTraits, Stub ) from six.moves import zip) and context including class names, function names, or small code snippets from other files: # Path: metatlas/datastructures/object_helpers.py # ON_NERSC = 'METATLAS_LOCAL' not in os.environ # def callback_method(func): # def notify(self, *args, **kwargs): # def __getitem__(self, item): # def __init__(self, *args): # def register_callback(self, cb): # def unregister_callback(self, cbid): # def set_docstring(cls): # def _get_subclasses(cls): # def __init__(self): # def get_instance(cls): # def get_connection(self): # def close_connection(self): # def convert_to_double(self, table, entry): # def save_objects(self, objects, _override=False): # def create_link_tables(self, klass): # def _get_save_data(self, obj, override=False): # def fix_table(self, table_name): # def retrieve(self, object_type, **kwargs): # def remove(self, object_type, **kwargs): # def remove_objects(self, objects, all_versions=True, **kwargs): # def format_timestamp(tstamp): # def validate(self, obj, value): # def retrieve(self): # def __repr__(self): # def __str__(self): # def validate(self, obj, value): # def get_from_nersc(user, relative_path): # def rollback_and_log(db_connection, err): # class NotifyList(list): # class Workspace(object): # class MetList(List): # class MetUnicode(CUnicode): # class MetFloat(CFloat): # class MetInt(CInt): # class MetBool(CBool): # class Stub(HasTraits): # class MetInstance(Instance): # class MetEnum(Enum): . Output only the next line.
if isinstance(value, Stub) and FETCH_STUBS:
Predict the next line for this snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) output_type: OutputType = Unicode(read_only=True) polarity: Polarity = Unicode(default_value="positive", read_only=True) <|code_end|> with the help of current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default , which may contain function names, class names, or code. Output only the next line.
analysis_number: AnalysisNumber = Int(default_value=0, read_only=True)
Given the code snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) <|code_end|> , generate the next line using the imports in this file: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (functions, classes, or occasionally code) from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
experiment: Experiment = Unicode(read_only=True)
Using the snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) output_type: OutputType = Unicode(read_only=True) polarity: Polarity = Unicode(default_value="positive", read_only=True) analysis_number: AnalysisNumber = Int(default_value=0, read_only=True) google_folder: str = Unicode(read_only=True) source_atlas: Optional[AtlasName] = Unicode(allow_none=True, default_value=None, read_only=True) copy_atlas: bool = Bool(default_value=True, read_only=True) username: Username = Unicode(default_value=getpass.getuser(), read_only=True) <|code_end|> , determine the next line of code. You have imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (class names, function names, or code) available: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
exclude_files: FileMatchList = traitlets.List(trait=Unicode(), default_value=[], read_only=True)
Continue the code snippet: <|code_start|> logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) output_type: OutputType = Unicode(read_only=True) polarity: Polarity = Unicode(default_value="positive", read_only=True) analysis_number: AnalysisNumber = Int(default_value=0, read_only=True) google_folder: str = Unicode(read_only=True) source_atlas: Optional[AtlasName] = Unicode(allow_none=True, default_value=None, read_only=True) copy_atlas: bool = Bool(default_value=True, read_only=True) username: Username = Unicode(default_value=getpass.getuser(), read_only=True) exclude_files: FileMatchList = traitlets.List(trait=Unicode(), default_value=[], read_only=True) include_groups: GroupMatchList = traitlets.List(read_only=True) exclude_groups: GroupMatchList = traitlets.List(read_only=True) groups_controlled_vocab: GroupMatchList = traitlets.List( trait=Unicode(), default_value=DEFAULT_GROUPS_CONTROLLED_VOCAB, read_only=True ) _lcmsruns: LcmsRunsList = traitlets.List(allow_none=True, default_value=None, read_only=True) <|code_end|> . Use current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (classes, functions, or code) from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
_all_groups: GroupList = traitlets.List(allow_none=True, default_value=None, read_only=True)
Given snippet: <|code_start|> "short_samplename": [9, 12, 13, 14], } out = pd.DataFrame(columns=fields.keys()) for i, lcms_file in enumerate(self.lcmsruns): tokens = lcms_file.name.split(".")[0].split("_") for name, idxs in fields.items(): out.loc[i, name] = "_".join([tokens[n] for n in idxs]) out.loc[i, "last_modified"] = pd.to_datetime(lcms_file.last_modified, unit="s") if out.empty: return out out.sort_values(by="last_modified", inplace=True) out.drop(columns=["last_modified"], inplace=True) out.drop_duplicates(subset=["full_filename"], keep="last", inplace=True) out.set_index("full_filename", inplace=True) return out.sort_values(by="full_filename") lcmsruns_short_names: pd.DataFrame = property(get_lcmsruns_short_names) def write_lcmsruns_short_names(self) -> None: """Write short names and raise error if exists and differs from current data""" short_names = self.lcmsruns_short_names short_names["full_filename"] = short_names.index write_utils.export_dataframe_die_on_diff( short_names, os.path.join(self.output_dir, "short_names.csv"), "LCMS runs short names", index=False, ) @property <|code_end|> , continue by predicting the next line. Consider current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default which might include code, classes, or functions. Output only the next line.
def _files_dict(self) -> Dict[str, LcmsRunDict]:
Predict the next line for this snippet: <|code_start|> logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) output_type: OutputType = Unicode(read_only=True) polarity: Polarity = Unicode(default_value="positive", read_only=True) analysis_number: AnalysisNumber = Int(default_value=0, read_only=True) google_folder: str = Unicode(read_only=True) source_atlas: Optional[AtlasName] = Unicode(allow_none=True, default_value=None, read_only=True) copy_atlas: bool = Bool(default_value=True, read_only=True) username: Username = Unicode(default_value=getpass.getuser(), read_only=True) exclude_files: FileMatchList = traitlets.List(trait=Unicode(), default_value=[], read_only=True) include_groups: GroupMatchList = traitlets.List(read_only=True) exclude_groups: GroupMatchList = traitlets.List(read_only=True) groups_controlled_vocab: GroupMatchList = traitlets.List( trait=Unicode(), default_value=DEFAULT_GROUPS_CONTROLLED_VOCAB, read_only=True ) <|code_end|> with the help of current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default , which may contain function names, class names, or code. Output only the next line.
_lcmsruns: LcmsRunsList = traitlets.List(allow_none=True, default_value=None, read_only=True)
Given the following code snippet before the placeholder: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" <|code_end|> , predict the next line using imports from the current file: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
project_directory: PathString = Unicode(read_only=True)
Here is a snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) output_type: OutputType = Unicode(read_only=True) <|code_end|> . Write the next line using the current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default , which may include functions, classes, or code. Output only the next line.
polarity: Polarity = Unicode(default_value="positive", read_only=True)
Given the following code snippet before the placeholder: <|code_start|> self.set_trait("_lcmsruns", lcmsruns) self.set_trait("_all_groups", all_groups) logger.info( "IDs: source_atlas=%s, atlas=%s, short_experiment_analysis=%s, output_dir=%s", self.source_atlas, self.atlas, self.short_experiment_analysis, self.output_dir, ) self.store_all_groups(exist_ok=True) self.set_trait("exclude_groups", append_inverse(self.exclude_groups, self.polarity)) @property def _default_include_groups(self) -> GroupMatchList: if self.output_type == "data_QC": return ["QC"] return [] def _get_default_exclude_groups(self, polarity: Polarity) -> GroupMatchList: out: GroupMatchList = ["InjBl", "InjBL"] if self.output_type not in ["data_QC"]: out.append("QC") return append_inverse(out, polarity) @property def _default_exclude_groups(self) -> GroupMatchList: return self._get_default_exclude_groups(self.polarity) @validate("polarity") def _valid_polarity(self, proposal: Proposal) -> Polarity: <|code_end|> , predict the next line using imports from the current file: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
if proposal["value"] not in POLARITIES:
Given the code snippet: <|code_start|> ) self.set_trait("_lcmsruns", lcmsruns) self.set_trait("_all_groups", all_groups) logger.info( "IDs: source_atlas=%s, atlas=%s, short_experiment_analysis=%s, output_dir=%s", self.source_atlas, self.atlas, self.short_experiment_analysis, self.output_dir, ) self.store_all_groups(exist_ok=True) self.set_trait("exclude_groups", append_inverse(self.exclude_groups, self.polarity)) @property def _default_include_groups(self) -> GroupMatchList: if self.output_type == "data_QC": return ["QC"] return [] def _get_default_exclude_groups(self, polarity: Polarity) -> GroupMatchList: out: GroupMatchList = ["InjBl", "InjBL"] if self.output_type not in ["data_QC"]: out.append("QC") return append_inverse(out, polarity) @property def _default_exclude_groups(self) -> GroupMatchList: return self._get_default_exclude_groups(self.polarity) @validate("polarity") <|code_end|> , generate the next line using the imports in this file: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (functions, classes, or occasionally code) from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
def _valid_polarity(self, proposal: Proposal) -> Polarity:
Predict the next line for this snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) <|code_end|> with the help of current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default , which may contain function names, class names, or code. Output only the next line.
output_type: OutputType = Unicode(read_only=True)
Predict the next line for this snippet: <|code_start|> self.short_experiment_analysis, self.output_dir, ) self.store_all_groups(exist_ok=True) self.set_trait("exclude_groups", append_inverse(self.exclude_groups, self.polarity)) @property def _default_include_groups(self) -> GroupMatchList: if self.output_type == "data_QC": return ["QC"] return [] def _get_default_exclude_groups(self, polarity: Polarity) -> GroupMatchList: out: GroupMatchList = ["InjBl", "InjBL"] if self.output_type not in ["data_QC"]: out.append("QC") return append_inverse(out, polarity) @property def _default_exclude_groups(self) -> GroupMatchList: return self._get_default_exclude_groups(self.polarity) @validate("polarity") def _valid_polarity(self, proposal: Proposal) -> Polarity: if proposal["value"] not in POLARITIES: raise TraitError(f"Parameter polarity must be one of {', '.join(POLARITIES)}") return cast(Polarity, proposal["value"]) @validate("output_type") def _valid_output_type(self, proposal: Proposal) -> OutputType: <|code_end|> with the help of current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default , which may contain function names, class names, or code. Output only the next line.
if proposal["value"] not in OUTPUT_TYPES:
Given the following code snippet before the placeholder: <|code_start|> @property def _exp_tokens(self) -> List[str]: """Returns list of strings from the experiment name""" return self.experiment.split("_") @property def project(self) -> int: """Returns project number (proposal id)""" return int(self._exp_tokens[3]) @property def atlas(self) -> AtlasName: """Atlas identifier (name)""" if self.source_atlas is None or (self.copy_atlas and self.source_atlas is not None): return AtlasName( f"{'_'.join(self._exp_tokens[3:6])}_{self.output_type}_{self.short_polarity}_{self.analysis}" ) return self.source_atlas @property def analysis(self) -> str: """Analysis identifier""" return f"{self.username}{self.analysis_number}" @property def short_experiment_analysis(self) -> str: """Short experiment analysis identifier""" return f"{self._exp_tokens[0]}_{self._exp_tokens[3]}_{self.output_type}_{self.analysis}" @property <|code_end|> , predict the next line using imports from the current file: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
def short_polarity(self) -> ShortPolarity:
Using the snippet: <|code_start|> """Returns list of strings from the experiment name""" return self.experiment.split("_") @property def project(self) -> int: """Returns project number (proposal id)""" return int(self._exp_tokens[3]) @property def atlas(self) -> AtlasName: """Atlas identifier (name)""" if self.source_atlas is None or (self.copy_atlas and self.source_atlas is not None): return AtlasName( f"{'_'.join(self._exp_tokens[3:6])}_{self.output_type}_{self.short_polarity}_{self.analysis}" ) return self.source_atlas @property def analysis(self) -> str: """Analysis identifier""" return f"{self.username}{self.analysis_number}" @property def short_experiment_analysis(self) -> str: """Short experiment analysis identifier""" return f"{self._exp_tokens[0]}_{self._exp_tokens[3]}_{self.output_type}_{self.analysis}" @property def short_polarity(self) -> ShortPolarity: """Short polarity identifier: 3 letters, upper case""" <|code_end|> , determine the next line of code. You have imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (class names, function names, or code) available: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
return SHORT_POLARITIES[self.polarity]
Given snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) output_type: OutputType = Unicode(read_only=True) polarity: Polarity = Unicode(default_value="positive", read_only=True) analysis_number: AnalysisNumber = Int(default_value=0, read_only=True) google_folder: str = Unicode(read_only=True) <|code_end|> , continue by predicting the next line. Consider current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default which might include code, classes, or functions. Output only the next line.
source_atlas: Optional[AtlasName] = Unicode(allow_none=True, default_value=None, read_only=True)
Based on the snippet: <|code_start|> return ["QC"] return [] def _get_default_exclude_groups(self, polarity: Polarity) -> GroupMatchList: out: GroupMatchList = ["InjBl", "InjBL"] if self.output_type not in ["data_QC"]: out.append("QC") return append_inverse(out, polarity) @property def _default_exclude_groups(self) -> GroupMatchList: return self._get_default_exclude_groups(self.polarity) @validate("polarity") def _valid_polarity(self, proposal: Proposal) -> Polarity: if proposal["value"] not in POLARITIES: raise TraitError(f"Parameter polarity must be one of {', '.join(POLARITIES)}") return cast(Polarity, proposal["value"]) @validate("output_type") def _valid_output_type(self, proposal: Proposal) -> OutputType: if proposal["value"] not in OUTPUT_TYPES: raise TraitError(f"Parameter output_type must be one of {', '.join(OUTPUT_TYPES)}") return cast(OutputType, proposal["value"]) @validate("source_atlas") def _valid_source_atlas(self, proposal: Proposal) -> Optional[AtlasName]: if proposal["value"] is not None: proposed_name = cast(AtlasName, proposal["value"]) try: <|code_end|> , predict the immediate next line with the help of imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (classes, functions, sometimes code) from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
get_atlas(proposed_name, cast(Username, "*")) # raises error if not found or matches multiple
Given the code snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) experiment: Experiment = Unicode(read_only=True) output_type: OutputType = Unicode(read_only=True) polarity: Polarity = Unicode(default_value="positive", read_only=True) analysis_number: AnalysisNumber = Int(default_value=0, read_only=True) google_folder: str = Unicode(read_only=True) source_atlas: Optional[AtlasName] = Unicode(allow_none=True, default_value=None, read_only=True) copy_atlas: bool = Bool(default_value=True, read_only=True) <|code_end|> , generate the next line using the imports in this file: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (functions, classes, or occasionally code) from other files: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
username: Username = Unicode(default_value=getpass.getuser(), read_only=True)
Given snippet: <|code_start|> fields: optional dict with column names as key and list of lcms filename metadata fields positions as value """ if fields is None: fields = { "full_filename": list(range(16)), "sample_treatment": [12], "short_filename": [0, 2, 4, 5, 7, 9, 14], "short_samplename": [9, 12, 13, 14], } out = pd.DataFrame(columns=fields.keys()) for i, lcms_file in enumerate(self.lcmsruns): tokens = lcms_file.name.split(".")[0].split("_") for name, idxs in fields.items(): out.loc[i, name] = "_".join([tokens[n] for n in idxs]) out.loc[i, "last_modified"] = pd.to_datetime(lcms_file.last_modified, unit="s") if out.empty: return out out.sort_values(by="last_modified", inplace=True) out.drop(columns=["last_modified"], inplace=True) out.drop_duplicates(subset=["full_filename"], keep="last", inplace=True) out.set_index("full_filename", inplace=True) return out.sort_values(by="full_filename") lcmsruns_short_names: pd.DataFrame = property(get_lcmsruns_short_names) def write_lcmsruns_short_names(self) -> None: """Write short names and raise error if exists and differs from current data""" short_names = self.lcmsruns_short_names short_names["full_filename"] = short_names.index <|code_end|> , continue by predicting the next line. Consider current file imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default which might include code, classes, or functions. Output only the next line.
write_utils.export_dataframe_die_on_diff(
Using the snippet: <|code_start|> _groups: GroupList = traitlets.List(allow_none=True, default_value=None, read_only=True) # pylint: disable=no-self-use,too-many-arguments,too-many-locals def __init__( self, project_directory, experiment, output_type, polarity, analysis_number, google_folder, source_atlas=None, copy_atlas=True, username=None, exclude_files=None, include_groups=None, exclude_groups=None, groups_controlled_vocab=None, lcmsruns=None, all_groups=None, ) -> None: super().__init__() self.set_trait("project_directory", project_directory) self.set_trait("experiment", experiment) self.set_trait("output_type", output_type) self.set_trait("polarity", polarity) self.set_trait("analysis_number", analysis_number) self.set_trait("google_folder", google_folder) self.set_trait("source_atlas", source_atlas) self.set_trait("copy_atlas", copy_atlas) <|code_end|> , determine the next line of code. You have imports: import getpass import logging import os import pandas as pd import traitlets import metatlas.datastructures.metatlas_objects as metob import metatlas.plots.dill2plots as dp from typing import cast, Dict, List, Optional from traitlets import Bool, TraitError, observe, validate from traitlets import HasTraits, Int, Unicode from traitlets.traitlets import ObserveHandler from metatlas.datastructures.id_types import ( AnalysisNumber, Experiment, FileMatchList, GroupList, GroupMatchList, LcmsRunDict, LcmsRunsList, PathString, Polarity, POLARITIES, Proposal, OutputType, OUTPUT_TYPES, ShortPolarity, SHORT_POLARITIES, ) from metatlas.datastructures.utils import AtlasName, get_atlas, Username from metatlas.io import write_utils from metatlas.tools.util import or_default and context (class names, function names, or code) available: # Path: metatlas/datastructures/id_types.py # OUTPUT_TYPES = [ # OutputType("ISTDsEtc"), # OutputType("FinalEMA-HILIC"), # OutputType("FinalEMA-C18"), # OutputType("data_QC"), # OutputType("other"), # ] # POLARITIES = [Polarity("positive"), Polarity("negative"), Polarity("fast-polarity-switching")] # SHORT_POLARITIES = { # Polarity("positive"): ShortPolarity("POS"), # Polarity("negative"): ShortPolarity("NEG"), # Polarity("fast-polarity-switching"): ShortPolarity("FPS"), # } # class Proposal(TypedDict): # class LcmsRunDict(TypedDict): # # Path: metatlas/datastructures/utils.py # def get_atlas(name: AtlasName, username: Username) -> metob.Atlas: # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/tools/util.py # def or_default(none_or_value, default): # """ # inputs: # none_or_value: variable to test # default: value to return if none_or_value is None # """ # return none_or_value if none_or_value is not None else default . Output only the next line.
self.set_trait("username", or_default(username, getpass.getuser()))
Based on the snippet: <|code_start|> plt.rcParams.update({'font.weight': 'bold'}) plt.rcParams['axes.linewidth'] = 2 # set the value globally for i,name in enumerate(names): plot_chromatogram(my_data[i], name, ax=ax[i]) f.savefig(file_name) plt.close(f) def plot_compounds_and_files(output_dir, data, nCols = 8, share_y = False, pool=None, plot_types='both'): ''' Parameters ---------- output_dir location of saved pdf plots nCols number of columns per pdf file share_y subplots share/not share they y axis processes number of cores to use plot_types compounds per file or files per compound or both Returns ------- nothing ''' <|code_end|> , predict the immediate next line with the help of imports: import matplotlib import sys import os import numpy as np import warnings from matplotlib import pyplot as plt from textwrap import wrap from metatlas.io import metatlas_get_data_helper_fun as ma_data and context (classes, functions, sometimes code) from other files: # Path: metatlas/io/metatlas_get_data_helper_fun.py # def create_msms_dataframe(df): # def compare_EIC_to_BPC_for_file(metatlas_dataset,file_index,yscale = 'linear'): # def get_data_for_atlas_df_and_file(input_tuple): # def get_bpc(filename,dataset='ms1_pos',integration='bpc'): # def df_container_from_metatlas_file(my_file): # def fast_nearest_interp(xi, x, y): # def remove_ms1_data_not_in_atlas(atlas_df, data): # def extract(data, ids, default=None): # def set_nested(data, ids, value): # def make_atlas_df(atlas): # def transfer_identification_data_to_atlas(data, atlas, ids_list=None): # def get_data_for_mzrt(row, data_df_pos, data_df_neg, extra_time=0.5, use_mz='mz', extra_mz=0.0): # def get_ms1_summary(row): # def get_ms2_data(row): # def prefilter_ms1_dataframe_with_boundaries(data_df, rt_max, rt_min, mz_min, mz_max, extra_time=0.5, extra_mz=0.01): # def get_ms1_eic(row): # def retrieve_most_intense_msms_scan(data): # def get_data_for_atlas_and_lcmsrun(atlas_df, df_container, extra_time, extra_mz): # def get_feature_data(atlas_df, pos_df, neg_df, use_mz='mz'): # def get_ms2_dict(ms2_feature_data_df): # def get_ms1_summary_data(ms1_feature_data_df): # def get_eic_data(ms1_feature_data_df): # def get_unique_scan_data(data): # def get_non_redundant_precursor_list(prt,pmz,rt_cutoff,mz_cutoff): # def organize_msms_scan_data(data,list_of_prt,list_of_pmz,list_of_pintensity): # def get_data_for_a_compound(mz_ref,rt_ref,what_to_get,h5file,extra_time): # def get_dill_data(fname): # def get_group_names(data): # def get_group_shortnames(data): # def get_file_names(data,full_path=False): # def get_compound_names(data,use_labels=False): # def make_data_sources_tables(groups, myatlas, output_loc, polarity=None, overwrite=True): # D = defaultdict(list) # D = {k:v for k,v in D.items() if len(v)>1} . Output only the next line.
file_names = ma_data.get_file_names(data)
Next line prediction: <|code_start|> def convert(ind, fname): """Helper function, converts a single file""" logger.info("Converting file number %d: %s", ind + 1, fname) # Get relevant information about the file. username = _file_name_to_username(fname, DEFAULT_USERNAME) info = patt.match(os.path.abspath(fname)) if info: info = info.groupdict() else: logger.error("Invalid path name: %s", fname) return dirname = os.path.dirname(fname) # Convert to HDF and store the entry in the database. try: hdf5_file = fname.replace('mzML', 'h5') logger.info("Generating h5 file: %s", hdf5_file) mzml_to_hdf(fname, hdf5_file, True) os.chmod(hdf5_file, 0o640) # Add this to the database unless it is already there try: runs = retrieve('lcmsrun', username='*', mzml_file=fname) except Exception: runs = [] if not runs: ctime = os.stat(fname).st_ctime logger.info("LCMS run not in DB, inserting new entry.") <|code_end|> . Use current file imports: (import argparse import functools import logging import os import re import shutil import subprocess import sys import time import traceback from datetime import datetime from subprocess import check_output from metatlas.datastructures.metatlas_objects import LcmsRun, store, retrieve from metatlas.io.mzml_loader import mzml_to_hdf from metatlas.io.mzml_loader import VERSION_TIMESTAMP from metatlas.io.system_utils import send_mail ) and context including class names, function names, or small code snippets from other files: # Path: metatlas/datastructures/metatlas_objects.py # class LcmsRun(MetatlasObject): # """An LCMS run is the reference to a file prepared with liquid # chromatography and mass spectrometry. # # The msconvert program is used to convert raw data (centroided is prefered) # to mzML. # # Note: These objects are not intented to be created directly, but by putting # the files in /project/projectdirs/metatlas/raw_data/<username> or by # running `load_lcms_files()`. # """ # method = MetInstance(Method) # experiment = MetUnicode(help='The name of the experiment') # hdf5_file = MetUnicode(help='Path to the HDF5 file at NERSC') # mzml_file = MetUnicode(help='Path to the MZML file at NERSC') # acquisition_time = MetInt(help='Unix timestamp when data was acquired creation') # injection_volume = MetFloat() # injection_volume_units = MetEnum(('uL', 'nL'), 'uL') # pass_qc = MetBool(help= 'True/False for if the LCMS Run has passed a quality control assessment') # sample = MetInstance(Sample) # # def store(objects, **kwargs): # """Store Metatlas objects in the database. # # Parameters # ---------- # objects: Metatlas object or list of Metatlas Objects # Object(s) to store in the database. # """ # workspace = Workspace.get_instance() # workspace.save_objects(objects, **kwargs) # workspace.close_connection() # # def retrieve(object_type, **kwargs): # """Get objects from the Metatlas object database. # # This will automatically select only objects created by the current # user unless `username` is provided. Use `username='*'` to search # against all users. # # Parameters # ---------- # object_type: string # The type of object to search for (i.e. "Groups"). # **kwargs # Specific search queries (i.e. name="Sargasso"). # Use '%' for wildcard patterns (i.e. description='Hello%'). # If you want to match a '%' character, use '%%'. # # Returns # ------- # objects: list # List of Metatlas Objects meeting the criteria. Will return the # latest version of each object. # """ # workspace = Workspace.get_instance() # out = workspace.retrieve(object_type, **kwargs) # workspace.close_connection() # return out # # Path: metatlas/io/system_utils.py # def send_mail(subject, username, body, force=False): # """Send the mail only once per day.""" # # now = datetime.now() # if force or dtime(00, 00) <= now.time() <= dtime(00, 10): # sender = 'pasteur@nersc.gov' # receivers = [f"{username}@lbl.gov", "bpbowen@lbl.gov"] # message = """\ # From: %s # To: %s # Subject: %s # # %s # """ % (sender, ", ".join(receivers), subject, body) # try: # smtpObj = smtplib.SMTP('smtp.lbl.gov') # smtpObj.sendmail(sender, receivers, message) # sys.stdout.write("Successfully sent email to %s\n" % username) # sys.stdout.flush() # except smtplib.SMTPException: # sys.stderr.write("Error: unable to send email to %s\n" % username) # sys.stdout.flush() . Output only the next line.
run = LcmsRun(name=info['path'],
Given the following code snippet before the placeholder: <|code_start|> if info: info = info.groupdict() else: logger.error("Invalid path name: %s", fname) return dirname = os.path.dirname(fname) # Convert to HDF and store the entry in the database. try: hdf5_file = fname.replace('mzML', 'h5') logger.info("Generating h5 file: %s", hdf5_file) mzml_to_hdf(fname, hdf5_file, True) os.chmod(hdf5_file, 0o640) # Add this to the database unless it is already there try: runs = retrieve('lcmsrun', username='*', mzml_file=fname) except Exception: runs = [] if not runs: ctime = os.stat(fname).st_ctime logger.info("LCMS run not in DB, inserting new entry.") run = LcmsRun(name=info['path'], description=f"{info['experiment']} {info['path']}", username=username, experiment=info['experiment'], creation_time=ctime, last_modified=ctime, mzml_file=fname, hdf5_file=hdf5_file, acquisition_time=get_acqtime_from_mzml(fname)) <|code_end|> , predict the next line using imports from the current file: import argparse import functools import logging import os import re import shutil import subprocess import sys import time import traceback from datetime import datetime from subprocess import check_output from metatlas.datastructures.metatlas_objects import LcmsRun, store, retrieve from metatlas.io.mzml_loader import mzml_to_hdf from metatlas.io.mzml_loader import VERSION_TIMESTAMP from metatlas.io.system_utils import send_mail and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/metatlas_objects.py # class LcmsRun(MetatlasObject): # """An LCMS run is the reference to a file prepared with liquid # chromatography and mass spectrometry. # # The msconvert program is used to convert raw data (centroided is prefered) # to mzML. # # Note: These objects are not intented to be created directly, but by putting # the files in /project/projectdirs/metatlas/raw_data/<username> or by # running `load_lcms_files()`. # """ # method = MetInstance(Method) # experiment = MetUnicode(help='The name of the experiment') # hdf5_file = MetUnicode(help='Path to the HDF5 file at NERSC') # mzml_file = MetUnicode(help='Path to the MZML file at NERSC') # acquisition_time = MetInt(help='Unix timestamp when data was acquired creation') # injection_volume = MetFloat() # injection_volume_units = MetEnum(('uL', 'nL'), 'uL') # pass_qc = MetBool(help= 'True/False for if the LCMS Run has passed a quality control assessment') # sample = MetInstance(Sample) # # def store(objects, **kwargs): # """Store Metatlas objects in the database. # # Parameters # ---------- # objects: Metatlas object or list of Metatlas Objects # Object(s) to store in the database. # """ # workspace = Workspace.get_instance() # workspace.save_objects(objects, **kwargs) # workspace.close_connection() # # def retrieve(object_type, **kwargs): # """Get objects from the Metatlas object database. # # This will automatically select only objects created by the current # user unless `username` is provided. Use `username='*'` to search # against all users. # # Parameters # ---------- # object_type: string # The type of object to search for (i.e. "Groups"). # **kwargs # Specific search queries (i.e. name="Sargasso"). # Use '%' for wildcard patterns (i.e. description='Hello%'). # If you want to match a '%' character, use '%%'. # # Returns # ------- # objects: list # List of Metatlas Objects meeting the criteria. Will return the # latest version of each object. # """ # workspace = Workspace.get_instance() # out = workspace.retrieve(object_type, **kwargs) # workspace.close_connection() # return out # # Path: metatlas/io/system_utils.py # def send_mail(subject, username, body, force=False): # """Send the mail only once per day.""" # # now = datetime.now() # if force or dtime(00, 00) <= now.time() <= dtime(00, 10): # sender = 'pasteur@nersc.gov' # receivers = [f"{username}@lbl.gov", "bpbowen@lbl.gov"] # message = """\ # From: %s # To: %s # Subject: %s # # %s # """ % (sender, ", ".join(receivers), subject, body) # try: # smtpObj = smtplib.SMTP('smtp.lbl.gov') # smtpObj.sendmail(sender, receivers, message) # sys.stdout.write("Successfully sent email to %s\n" % username) # sys.stdout.flush() # except smtplib.SMTPException: # sys.stderr.write("Error: unable to send email to %s\n" % username) # sys.stdout.flush() . Output only the next line.
store(run)
Continue the code snippet: <|code_start|> if start_time is not None and '-infinity' not in start_time: date_object = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') utc_timestamp = int(time.mktime(date_object.timetuple())) else: utc_timestamp = int(0) return utc_timestamp def convert(ind, fname): """Helper function, converts a single file""" logger.info("Converting file number %d: %s", ind + 1, fname) # Get relevant information about the file. username = _file_name_to_username(fname, DEFAULT_USERNAME) info = patt.match(os.path.abspath(fname)) if info: info = info.groupdict() else: logger.error("Invalid path name: %s", fname) return dirname = os.path.dirname(fname) # Convert to HDF and store the entry in the database. try: hdf5_file = fname.replace('mzML', 'h5') logger.info("Generating h5 file: %s", hdf5_file) mzml_to_hdf(fname, hdf5_file, True) os.chmod(hdf5_file, 0o640) # Add this to the database unless it is already there try: <|code_end|> . Use current file imports: import argparse import functools import logging import os import re import shutil import subprocess import sys import time import traceback from datetime import datetime from subprocess import check_output from metatlas.datastructures.metatlas_objects import LcmsRun, store, retrieve from metatlas.io.mzml_loader import mzml_to_hdf from metatlas.io.mzml_loader import VERSION_TIMESTAMP from metatlas.io.system_utils import send_mail and context (classes, functions, or code) from other files: # Path: metatlas/datastructures/metatlas_objects.py # class LcmsRun(MetatlasObject): # """An LCMS run is the reference to a file prepared with liquid # chromatography and mass spectrometry. # # The msconvert program is used to convert raw data (centroided is prefered) # to mzML. # # Note: These objects are not intented to be created directly, but by putting # the files in /project/projectdirs/metatlas/raw_data/<username> or by # running `load_lcms_files()`. # """ # method = MetInstance(Method) # experiment = MetUnicode(help='The name of the experiment') # hdf5_file = MetUnicode(help='Path to the HDF5 file at NERSC') # mzml_file = MetUnicode(help='Path to the MZML file at NERSC') # acquisition_time = MetInt(help='Unix timestamp when data was acquired creation') # injection_volume = MetFloat() # injection_volume_units = MetEnum(('uL', 'nL'), 'uL') # pass_qc = MetBool(help= 'True/False for if the LCMS Run has passed a quality control assessment') # sample = MetInstance(Sample) # # def store(objects, **kwargs): # """Store Metatlas objects in the database. # # Parameters # ---------- # objects: Metatlas object or list of Metatlas Objects # Object(s) to store in the database. # """ # workspace = Workspace.get_instance() # workspace.save_objects(objects, **kwargs) # workspace.close_connection() # # def retrieve(object_type, **kwargs): # """Get objects from the Metatlas object database. # # This will automatically select only objects created by the current # user unless `username` is provided. Use `username='*'` to search # against all users. # # Parameters # ---------- # object_type: string # The type of object to search for (i.e. "Groups"). # **kwargs # Specific search queries (i.e. name="Sargasso"). # Use '%' for wildcard patterns (i.e. description='Hello%'). # If you want to match a '%' character, use '%%'. # # Returns # ------- # objects: list # List of Metatlas Objects meeting the criteria. Will return the # latest version of each object. # """ # workspace = Workspace.get_instance() # out = workspace.retrieve(object_type, **kwargs) # workspace.close_connection() # return out # # Path: metatlas/io/system_utils.py # def send_mail(subject, username, body, force=False): # """Send the mail only once per day.""" # # now = datetime.now() # if force or dtime(00, 00) <= now.time() <= dtime(00, 10): # sender = 'pasteur@nersc.gov' # receivers = [f"{username}@lbl.gov", "bpbowen@lbl.gov"] # message = """\ # From: %s # To: %s # Subject: %s # # %s # """ % (sender, ", ".join(receivers), subject, body) # try: # smtpObj = smtplib.SMTP('smtp.lbl.gov') # smtpObj.sendmail(sender, receivers, message) # sys.stdout.write("Successfully sent email to %s\n" % username) # sys.stdout.flush() # except smtplib.SMTPException: # sys.stderr.write("Error: unable to send email to %s\n" % username) # sys.stdout.flush() . Output only the next line.
runs = retrieve('lcmsrun', username='*', mzml_file=fname)
Based on the snippet: <|code_start|> move_file(fname, fail_path) try: os.remove(hdf5_file) except: pass def update_metatlas(directory): """ Converts all files to HDF in metatlas. Emails the user if there was any kind of error with converting a file. """ mzml_files = check_output(f'find {directory} -name "*.mzML"', shell=True) mzml_files = mzml_files.decode('utf-8').splitlines() # Find valid h5 files newer than the format version timestamp. delta = int((time.time() - VERSION_TIMESTAMP) / 60) check = f'find {directory} -name "*.h5" -mmin -{delta} -size +2k' valid_files = set(check_output(check, shell=True).decode('utf-8').splitlines()) new_files = [file for file in mzml_files if file.replace('.mzML', '.h5') not in valid_files] if new_files: logger.info("Found %d files", len(new_files)) for ind, ffff in enumerate(new_files): convert(ind, ffff) if readonly_files: for (username, dirnames) in readonly_files.items(): logger.info("Sending email to %s about inaccessible files.", username) body = ("Please log in to NERSC and run 'chmod g+rwXs' on the " "following directories:\n%s" % ('\n'.join(dirnames))) <|code_end|> , predict the immediate next line with the help of imports: import argparse import functools import logging import os import re import shutil import subprocess import sys import time import traceback from datetime import datetime from subprocess import check_output from metatlas.datastructures.metatlas_objects import LcmsRun, store, retrieve from metatlas.io.mzml_loader import mzml_to_hdf from metatlas.io.mzml_loader import VERSION_TIMESTAMP from metatlas.io.system_utils import send_mail and context (classes, functions, sometimes code) from other files: # Path: metatlas/datastructures/metatlas_objects.py # class LcmsRun(MetatlasObject): # """An LCMS run is the reference to a file prepared with liquid # chromatography and mass spectrometry. # # The msconvert program is used to convert raw data (centroided is prefered) # to mzML. # # Note: These objects are not intented to be created directly, but by putting # the files in /project/projectdirs/metatlas/raw_data/<username> or by # running `load_lcms_files()`. # """ # method = MetInstance(Method) # experiment = MetUnicode(help='The name of the experiment') # hdf5_file = MetUnicode(help='Path to the HDF5 file at NERSC') # mzml_file = MetUnicode(help='Path to the MZML file at NERSC') # acquisition_time = MetInt(help='Unix timestamp when data was acquired creation') # injection_volume = MetFloat() # injection_volume_units = MetEnum(('uL', 'nL'), 'uL') # pass_qc = MetBool(help= 'True/False for if the LCMS Run has passed a quality control assessment') # sample = MetInstance(Sample) # # def store(objects, **kwargs): # """Store Metatlas objects in the database. # # Parameters # ---------- # objects: Metatlas object or list of Metatlas Objects # Object(s) to store in the database. # """ # workspace = Workspace.get_instance() # workspace.save_objects(objects, **kwargs) # workspace.close_connection() # # def retrieve(object_type, **kwargs): # """Get objects from the Metatlas object database. # # This will automatically select only objects created by the current # user unless `username` is provided. Use `username='*'` to search # against all users. # # Parameters # ---------- # object_type: string # The type of object to search for (i.e. "Groups"). # **kwargs # Specific search queries (i.e. name="Sargasso"). # Use '%' for wildcard patterns (i.e. description='Hello%'). # If you want to match a '%' character, use '%%'. # # Returns # ------- # objects: list # List of Metatlas Objects meeting the criteria. Will return the # latest version of each object. # """ # workspace = Workspace.get_instance() # out = workspace.retrieve(object_type, **kwargs) # workspace.close_connection() # return out # # Path: metatlas/io/system_utils.py # def send_mail(subject, username, body, force=False): # """Send the mail only once per day.""" # # now = datetime.now() # if force or dtime(00, 00) <= now.time() <= dtime(00, 10): # sender = 'pasteur@nersc.gov' # receivers = [f"{username}@lbl.gov", "bpbowen@lbl.gov"] # message = """\ # From: %s # To: %s # Subject: %s # # %s # """ % (sender, ", ".join(receivers), subject, body) # try: # smtpObj = smtplib.SMTP('smtp.lbl.gov') # smtpObj.sendmail(sender, receivers, message) # sys.stdout.write("Successfully sent email to %s\n" % username) # sys.stdout.flush() # except smtplib.SMTPException: # sys.stderr.write("Error: unable to send email to %s\n" % username) # sys.stdout.flush() . Output only the next line.
send_mail('Metatlas Files are Inaccessible', username, body)
Based on the snippet: <|code_start|>""" Tests of RClone """ # pylint: disable=missing-function-docstring def has_rclone(): return os.system("rclone") == 256 def rclone_path(): result = subprocess.run(["which", "rclone"], stdout=subprocess.PIPE, check=True) return result.stdout.decode("utf-8").rstrip() def test_config_file01(): <|code_end|> , predict the immediate next line with the help of imports: import os import subprocess import pytest from metatlas.io import rclone and context (classes, functions, sometimes code) from other files: # Path: metatlas/io/rclone.py # class RClone: # def __init__(self, rclone_path: str) -> None: # def config_file(self) -> Optional[str]: # def get_name_for_id(self, identifier: str) -> Optional[str]: # def copy_to_drive(self, source: str, drive: str, dest_path: str = None, progress: bool = False) -> None: # def get_id_for_path(self, path_string: str) -> str: # def path_to_url(self, path_string: str) -> str: # def parse_path(path_string: str) -> Tuple[str, List[str]]: . Output only the next line.
rci = rclone.RClone("/bin/foobarz")
Given the following code snippet before the placeholder: <|code_start|> if lcmsruns is None: lcmsruns = get_lcmsrun_matrix() done_input_files = lcmsruns.loc[pd.notna(lcmsruns['%s_filename'%input_type]),'%s_filename'%input_type] done_output_files = lcmsruns.loc[pd.notna(lcmsruns['%s_filename'%output_type]),'%s_filename'%output_type] task_idx = file_conversion_tasks['task']==task inputfile_idx = file_conversion_tasks['input_file'].isin(done_input_files) outputfile_idx = file_conversion_tasks['output_file'].isin(done_output_files) # This finds where output file exists done_tasks_idx = (task_idx) & (outputfile_idx) if sum(done_tasks_idx)>0: update_table_in_lims(file_conversion_tasks.loc[done_tasks_idx,['Key']],'file_conversion_task',method='delete')#,labkey_server=labkey_server,project_name=project_name) print(('%s: There are %d tasks where output file exist and will be removed'%(task,file_conversion_tasks[done_tasks_idx].shape[0]))) # This finds where input file is missing done_tasks_idx = (task_idx) & (~inputfile_idx) if sum(done_tasks_idx)>0: update_table_in_lims(file_conversion_tasks.loc[done_tasks_idx,['Key']],'file_conversion_task',method='delete')#,labkey_server=labkey_server,project_name=project_name) print(('%s: There are %d tasks where input file is missing and will be removed'%(task,file_conversion_tasks[done_tasks_idx].shape[0]))) right_now_str = datetime.now().strftime("%Y%m%d %H:%M:%S") idx = (pd.notna(lcmsruns['%s_filename'%input_type])) & (pd.isna(lcmsruns['%s_filename'%output_type])) temp = pd.DataFrame() temp['input_file'] = lcmsruns.loc[idx,'%s_filename'%input_type] <|code_end|> , predict the next line using imports from the current file: import numpy as np import sys import json import pandas as pd import re import glob as glob import os import six import time import sys import os import pathlib import argparse import hashlib import requests import json import pandas as pd import numpy as np import re import time import math import collections import xmltodict import zipfile import gspread import subprocess import numpy as np import scipy.sparse as sp import subprocess import os.path from collections import defaultdict from xml.etree import cElementTree as ET from io import StringIO from metatlas.io.update_lcmsfiles_in_lims import EXTENSIONS from collections import Mapping from pathlib2 import PurePath from subprocess import call from labkey.api_wrapper import APIWrapper from datetime import datetime, time as dtime from subprocess import check_output from ast import literal_eval from copy import deepcopy from oauth2client.service_account import ServiceAccountCredentials from pyteomics import mgf and context including class names, function names, and sometimes code from other files: # Path: metatlas/io/update_lcmsfiles_in_lims.py # EXTENSIONS = {'mzml':'.mzML', # 'hdf5':'.h5', # 'spectralhits':'_spectral-hits.tab.gz', # 'pactolus':'.pactolus.gz', # 'raw':'.raw'} . Output only the next line.
temp['output_file'] = temp['input_file'].apply(lambda x: re.sub('\%s$'%EXTENSIONS[input_type],'%s'%EXTENSIONS[output_type],x))
Based on the snippet: <|code_start|>"""Jupyter notebook helper functions""" logger = logging.getLogger(__name__) def configure_environment(log_level: str) -> None: """ Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' """ <|code_end|> , predict the immediate next line with the help of imports: import json import logging import os import re import pandas as pd from typing import List, Optional from IPython.core.display import display, HTML from metatlas.tools.logging import activate_logging from metatlas.tools.logging import activate_module_logging from metatlas.tools.environment import get_commit_date from metatlas.tools.environment import get_repo_hash from metatlas.tools.environment import set_git_head and context (classes, functions, sometimes code) from other files: # Path: metatlas/tools/logging.py # def activate_logging(console_level="INFO", console_format=None, file_level="DEBUG", filename=None): # """ # inputs: # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # disable_jupyter_default_logging() # activate_module_logging("metatlas", console_level, console_format, file_level, filename) # # Path: metatlas/tools/logging.py # def activate_module_logging( # module, console_level="INFO", console_format=None, file_level="DEBUG", filename=None # ): # """ # inputs: # module: name of logger to capture messages from, often a module name # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # console_handler = get_console_handler(console_level, console_format) # file_handler = get_file_handler(file_level, filename) # # new_logger = logging.getLogger(module) # new_logger.handlers[:] = [] # new_logger.addHandler(console_handler) # new_logger.addHandler(file_handler) # new_logger.setLevel( # levels[file_level] if levels[file_level] < levels[console_level] else levels[console_level] # ) # return new_logger # # Path: metatlas/tools/environment.py # def get_commit_date() -> str: # """Returns a string describing when the HEAD commit was created""" # cmd = ["git", "show", "-s", "--format=%ci -- %cr", "HEAD"] # return subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True, text=True).stdout.rstrip() # # Path: metatlas/tools/environment.py # def get_repo_hash(): # """ # Returns the full hash for the current git commit or 'git not found, hash unknown' # """ # try: # result = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo_dir(), capture_output=True, check=True) # except FileNotFoundError: # return "git not found, hash unknown" # return result.stdout.strip() # # Path: metatlas/tools/environment.py # def set_git_head(source_code_version_id: str) -> None: # """Performs a git checkout""" # cmd = ["git", "checkout", source_code_version_id] # subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True) . Output only the next line.
activate_logging(console_level=log_level)
Predict the next line after this snippet: <|code_start|> def configure_notebook_display() -> None: """Configure output from Jupyter""" # set notebook to have minimal side margins display(HTML("<style>.container { width:100% !important; }</style>")) def setup(log_level: str, source_code_version_id: Optional[str] = None) -> None: """High level function to prepare the metatlas notebook""" configure_environment(log_level) if source_code_version_id is not None: set_git_head(source_code_version_id) logger.info("Running on git commit: %s from %s", get_repo_hash(), get_commit_date()) configure_notebook_display() configure_pandas_display() def activate_sql_logging(console_level="INFO", console_format=None, file_level="DEBUG", filename=None): """ Turns on logging from sqlalchemy. Level 'INFO' gets SQL statements and 'DEBUG' gets SQL statements and results. inputs: console_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' console_format: input to logging.setFormatter file_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' filename: logging destination """ logger.debug("Activaing SQL logging with console_level=%s and file_level=%s.", console_level, file_level) <|code_end|> using the current file's imports: import json import logging import os import re import pandas as pd from typing import List, Optional from IPython.core.display import display, HTML from metatlas.tools.logging import activate_logging from metatlas.tools.logging import activate_module_logging from metatlas.tools.environment import get_commit_date from metatlas.tools.environment import get_repo_hash from metatlas.tools.environment import set_git_head and any relevant context from other files: # Path: metatlas/tools/logging.py # def activate_logging(console_level="INFO", console_format=None, file_level="DEBUG", filename=None): # """ # inputs: # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # disable_jupyter_default_logging() # activate_module_logging("metatlas", console_level, console_format, file_level, filename) # # Path: metatlas/tools/logging.py # def activate_module_logging( # module, console_level="INFO", console_format=None, file_level="DEBUG", filename=None # ): # """ # inputs: # module: name of logger to capture messages from, often a module name # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # console_handler = get_console_handler(console_level, console_format) # file_handler = get_file_handler(file_level, filename) # # new_logger = logging.getLogger(module) # new_logger.handlers[:] = [] # new_logger.addHandler(console_handler) # new_logger.addHandler(file_handler) # new_logger.setLevel( # levels[file_level] if levels[file_level] < levels[console_level] else levels[console_level] # ) # return new_logger # # Path: metatlas/tools/environment.py # def get_commit_date() -> str: # """Returns a string describing when the HEAD commit was created""" # cmd = ["git", "show", "-s", "--format=%ci -- %cr", "HEAD"] # return subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True, text=True).stdout.rstrip() # # Path: metatlas/tools/environment.py # def get_repo_hash(): # """ # Returns the full hash for the current git commit or 'git not found, hash unknown' # """ # try: # result = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo_dir(), capture_output=True, check=True) # except FileNotFoundError: # return "git not found, hash unknown" # return result.stdout.strip() # # Path: metatlas/tools/environment.py # def set_git_head(source_code_version_id: str) -> None: # """Performs a git checkout""" # cmd = ["git", "checkout", source_code_version_id] # subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True) . Output only the next line.
activate_module_logging("sqlalchemy.engine", console_level, console_format, file_level, filename)
Based on the snippet: <|code_start|> Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' """ activate_logging(console_level=log_level) logger.debug("Running import and environment setup block of notebook.") logger.debug("Configuring notebook environment with console log level of %s.", log_level) os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" os.environ["OPENBLAS_NUM_THREADS"] = "1" def configure_pandas_display(max_rows: int = 5000, max_columns: int = 500, max_colwidth: int = 100) -> None: """Set pandas display options""" logger.debug("Settings pandas display options") pd.set_option("display.max_rows", max_rows) pd.set_option("display.max_columns", max_columns) pd.set_option("display.max_colwidth", max_colwidth) def configure_notebook_display() -> None: """Configure output from Jupyter""" # set notebook to have minimal side margins display(HTML("<style>.container { width:100% !important; }</style>")) def setup(log_level: str, source_code_version_id: Optional[str] = None) -> None: """High level function to prepare the metatlas notebook""" configure_environment(log_level) if source_code_version_id is not None: set_git_head(source_code_version_id) <|code_end|> , predict the immediate next line with the help of imports: import json import logging import os import re import pandas as pd from typing import List, Optional from IPython.core.display import display, HTML from metatlas.tools.logging import activate_logging from metatlas.tools.logging import activate_module_logging from metatlas.tools.environment import get_commit_date from metatlas.tools.environment import get_repo_hash from metatlas.tools.environment import set_git_head and context (classes, functions, sometimes code) from other files: # Path: metatlas/tools/logging.py # def activate_logging(console_level="INFO", console_format=None, file_level="DEBUG", filename=None): # """ # inputs: # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # disable_jupyter_default_logging() # activate_module_logging("metatlas", console_level, console_format, file_level, filename) # # Path: metatlas/tools/logging.py # def activate_module_logging( # module, console_level="INFO", console_format=None, file_level="DEBUG", filename=None # ): # """ # inputs: # module: name of logger to capture messages from, often a module name # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # console_handler = get_console_handler(console_level, console_format) # file_handler = get_file_handler(file_level, filename) # # new_logger = logging.getLogger(module) # new_logger.handlers[:] = [] # new_logger.addHandler(console_handler) # new_logger.addHandler(file_handler) # new_logger.setLevel( # levels[file_level] if levels[file_level] < levels[console_level] else levels[console_level] # ) # return new_logger # # Path: metatlas/tools/environment.py # def get_commit_date() -> str: # """Returns a string describing when the HEAD commit was created""" # cmd = ["git", "show", "-s", "--format=%ci -- %cr", "HEAD"] # return subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True, text=True).stdout.rstrip() # # Path: metatlas/tools/environment.py # def get_repo_hash(): # """ # Returns the full hash for the current git commit or 'git not found, hash unknown' # """ # try: # result = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo_dir(), capture_output=True, check=True) # except FileNotFoundError: # return "git not found, hash unknown" # return result.stdout.strip() # # Path: metatlas/tools/environment.py # def set_git_head(source_code_version_id: str) -> None: # """Performs a git checkout""" # cmd = ["git", "checkout", source_code_version_id] # subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True) . Output only the next line.
logger.info("Running on git commit: %s from %s", get_repo_hash(), get_commit_date())
Given snippet: <|code_start|> Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' """ activate_logging(console_level=log_level) logger.debug("Running import and environment setup block of notebook.") logger.debug("Configuring notebook environment with console log level of %s.", log_level) os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" os.environ["OPENBLAS_NUM_THREADS"] = "1" def configure_pandas_display(max_rows: int = 5000, max_columns: int = 500, max_colwidth: int = 100) -> None: """Set pandas display options""" logger.debug("Settings pandas display options") pd.set_option("display.max_rows", max_rows) pd.set_option("display.max_columns", max_columns) pd.set_option("display.max_colwidth", max_colwidth) def configure_notebook_display() -> None: """Configure output from Jupyter""" # set notebook to have minimal side margins display(HTML("<style>.container { width:100% !important; }</style>")) def setup(log_level: str, source_code_version_id: Optional[str] = None) -> None: """High level function to prepare the metatlas notebook""" configure_environment(log_level) if source_code_version_id is not None: set_git_head(source_code_version_id) <|code_end|> , continue by predicting the next line. Consider current file imports: import json import logging import os import re import pandas as pd from typing import List, Optional from IPython.core.display import display, HTML from metatlas.tools.logging import activate_logging from metatlas.tools.logging import activate_module_logging from metatlas.tools.environment import get_commit_date from metatlas.tools.environment import get_repo_hash from metatlas.tools.environment import set_git_head and context: # Path: metatlas/tools/logging.py # def activate_logging(console_level="INFO", console_format=None, file_level="DEBUG", filename=None): # """ # inputs: # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # disable_jupyter_default_logging() # activate_module_logging("metatlas", console_level, console_format, file_level, filename) # # Path: metatlas/tools/logging.py # def activate_module_logging( # module, console_level="INFO", console_format=None, file_level="DEBUG", filename=None # ): # """ # inputs: # module: name of logger to capture messages from, often a module name # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # console_handler = get_console_handler(console_level, console_format) # file_handler = get_file_handler(file_level, filename) # # new_logger = logging.getLogger(module) # new_logger.handlers[:] = [] # new_logger.addHandler(console_handler) # new_logger.addHandler(file_handler) # new_logger.setLevel( # levels[file_level] if levels[file_level] < levels[console_level] else levels[console_level] # ) # return new_logger # # Path: metatlas/tools/environment.py # def get_commit_date() -> str: # """Returns a string describing when the HEAD commit was created""" # cmd = ["git", "show", "-s", "--format=%ci -- %cr", "HEAD"] # return subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True, text=True).stdout.rstrip() # # Path: metatlas/tools/environment.py # def get_repo_hash(): # """ # Returns the full hash for the current git commit or 'git not found, hash unknown' # """ # try: # result = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo_dir(), capture_output=True, check=True) # except FileNotFoundError: # return "git not found, hash unknown" # return result.stdout.strip() # # Path: metatlas/tools/environment.py # def set_git_head(source_code_version_id: str) -> None: # """Performs a git checkout""" # cmd = ["git", "checkout", source_code_version_id] # subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True) which might include code, classes, or functions. Output only the next line.
logger.info("Running on git commit: %s from %s", get_repo_hash(), get_commit_date())
Based on the snippet: <|code_start|> """ Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' """ activate_logging(console_level=log_level) logger.debug("Running import and environment setup block of notebook.") logger.debug("Configuring notebook environment with console log level of %s.", log_level) os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" os.environ["OPENBLAS_NUM_THREADS"] = "1" def configure_pandas_display(max_rows: int = 5000, max_columns: int = 500, max_colwidth: int = 100) -> None: """Set pandas display options""" logger.debug("Settings pandas display options") pd.set_option("display.max_rows", max_rows) pd.set_option("display.max_columns", max_columns) pd.set_option("display.max_colwidth", max_colwidth) def configure_notebook_display() -> None: """Configure output from Jupyter""" # set notebook to have minimal side margins display(HTML("<style>.container { width:100% !important; }</style>")) def setup(log_level: str, source_code_version_id: Optional[str] = None) -> None: """High level function to prepare the metatlas notebook""" configure_environment(log_level) if source_code_version_id is not None: <|code_end|> , predict the immediate next line with the help of imports: import json import logging import os import re import pandas as pd from typing import List, Optional from IPython.core.display import display, HTML from metatlas.tools.logging import activate_logging from metatlas.tools.logging import activate_module_logging from metatlas.tools.environment import get_commit_date from metatlas.tools.environment import get_repo_hash from metatlas.tools.environment import set_git_head and context (classes, functions, sometimes code) from other files: # Path: metatlas/tools/logging.py # def activate_logging(console_level="INFO", console_format=None, file_level="DEBUG", filename=None): # """ # inputs: # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # disable_jupyter_default_logging() # activate_module_logging("metatlas", console_level, console_format, file_level, filename) # # Path: metatlas/tools/logging.py # def activate_module_logging( # module, console_level="INFO", console_format=None, file_level="DEBUG", filename=None # ): # """ # inputs: # module: name of logger to capture messages from, often a module name # console_level: string with desired logging level for messages on stdout (notebook) # file_level: string with desired logging level for message to log file # filename: file to send logs to # returns logger # # Call this function to activate logging to console and file # valid logging levels are 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' # """ # console_handler = get_console_handler(console_level, console_format) # file_handler = get_file_handler(file_level, filename) # # new_logger = logging.getLogger(module) # new_logger.handlers[:] = [] # new_logger.addHandler(console_handler) # new_logger.addHandler(file_handler) # new_logger.setLevel( # levels[file_level] if levels[file_level] < levels[console_level] else levels[console_level] # ) # return new_logger # # Path: metatlas/tools/environment.py # def get_commit_date() -> str: # """Returns a string describing when the HEAD commit was created""" # cmd = ["git", "show", "-s", "--format=%ci -- %cr", "HEAD"] # return subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True, text=True).stdout.rstrip() # # Path: metatlas/tools/environment.py # def get_repo_hash(): # """ # Returns the full hash for the current git commit or 'git not found, hash unknown' # """ # try: # result = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo_dir(), capture_output=True, check=True) # except FileNotFoundError: # return "git not found, hash unknown" # return result.stdout.strip() # # Path: metatlas/tools/environment.py # def set_git_head(source_code_version_id: str) -> None: # """Performs a git checkout""" # cmd = ["git", "checkout", source_code_version_id] # subprocess.run(cmd, cwd=repo_dir(), check=True, capture_output=True) . Output only the next line.
set_git_head(source_code_version_id)
Continue the code snippet: <|code_start|> r = my_session.get("https://newt.nersc.gov/newt/queue/%s/?user=%s"%(computer,usr)) my_jobs = r.json() # print my_jobs if do_print: print("You have",len(my_jobs),"jobs running or in the queue to run") for i,j in enumerate(my_jobs): print(i,'\t',j['status'], j['name'],j['memory'],j['nodes'], j['procs'], j['timeuse']) return my_jobs def create_pactolus_msms_data_container(myfiles,target_directory,min_intensity,min_rt = 1,max_rt = 22,make_container=True): # peak_arrayindex: This is a 2D array with the shape (num_spectra, 3). # The dataset contains an index that tells us: # i) the x location of each spectrum [:,0], # ii) the y location of each spectrum [:,1], and # iii) and the index where the spectrum starts in the peak_mz and peak_value array. # In item 1/2 I first fill the array with [0,i,0] values to define unique x/y locations # for each spectrum and in the second line I then create the last column with start index # of the spectra which is just the cumulative-sum of the length of the spectra. # when you create the start stop locations you will need to: # prepend [0] to the cummulative sums (the first spectrum starts at 0 not its length). # remove the last entry to make sure the array has the correct length # That is why I did the following: # np.cumsum([0] + [ ri['m/z array'].shape[0] for ri in good_list ])[:-1] if not os.path.exists(target_directory): try: os.makedirs(target_directory) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise for myfile in myfiles: <|code_end|> . Use current file imports: import sys import qgrid import pandas as pd import os import tables import pickle import h5py import dill import numpy as np import os.path import glob as glob import json import six import pickle import getpass import glob import getpass from metatlas import metatlas_objects as metob from metatlas.io import h5_query as h5q from metatlas.helpers import metatlas_get_data_helper_fun as mgd from matplotlib import pyplot as plt from matplotlib import colors as matcolors from matplotlib.widgets import RadioButtons, CheckButtons from requests import Session from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import Draw from rdkit.Chem import Descriptors from rdkit.Chem import rdMolDescriptors from rdkit.Chem import AllChem from rdkit.Chem import Draw from rdkit.Chem import rdDepictor from rdkit.Chem.Draw import rdMolDraw2D from rdkit.Chem.Draw import IPythonConsole from IPython.display import SVG,display from PIL import Image from six.moves import range from six.moves import zip from requests import Session from copy import deepcopy and context (classes, functions, or code) from other files: # Path: metatlas/io/h5_query.py # def get_data(h5file, **kwargs): # def get_chromatogram(h5file, min_mz, max_mz, aggregator=np.sum, **kwargs): # def get_heatmap(h5file, mz_bins, **kwargs): # def get_spectrogram(h5file, min_rt, max_rt, bins=2000, **kwargs): # def get_info(h5file): . Output only the next line.
finfo = h5q.get_info(myfile)
Given the following code snippet before the placeholder: <|code_start|>""" tests of parallel processing utilities """ # pylint: disable=missing-function-docstring def times_two(num): return num * 2 def error_on_zero(num): if num == 0: raise ValueError("Zero is illegal here!") return num def test_parallel_process01(): data = [0, 1, 2] <|code_end|> , predict the next line using imports from the current file: import pytest from metatlas.tools import parallel and context including class names, function names, and sometimes code from other files: # Path: metatlas/tools/parallel.py # def parallel_process(function, data, max_cpus, unit="it"): . Output only the next line.
assert sorted(parallel.parallel_process(times_two, data, len(data))) == [0, 2, 4]
Given snippet: <|code_start|># pylint: disable=missing-function-docstring, missing-module-docstring, line-too-long INCHI = "InChI=1S/C10H13N5O3/c11-9-8-10(13-3-12-9)15(4-14-8)7-1-5(17)6(2-16)18-7/h3-7,16-17H,1-2H2,(H2,11,12,13)/t5-,6+,7+/m0/s1" INCHI_KEY = "OLXZPDWKRNYJJZ-RRKCRQDMSA-N" SMILES = "C1[C@@H]([C@@H](CO)O[C@H]1n1cnc2c(N)ncnc12)O" def test_get_parent_mass01(): adducts = matchms.importing.load_adducts_dict() original_parent = 100 for name in adducts: <|code_end|> , continue by predicting the next line. Consider current file imports: import matchms from rdkit import Chem from metatlas.tools import cheminfo and context: # Path: metatlas/tools/cheminfo.py # def get_parent_mass(precursor_mz: float, adduct: str) -> float: # def get_precursor_mz(parent_mass: float, adduct: str) -> float: # def is_positive_mode(adduct: str) -> bool: # def is_valid_inchi_pair(test_inchi: str, test_inchi_key: str) -> bool: # def is_valid_inchi_smiles_pair(test_inchi: str, test_smiles: str) -> bool: # def inchi_to_smiles(inchi: str) -> str: # def smiles_to_inchi(smiles: str) -> str: # def inchi_or_smiles_to_molecule(molecule_id: str) -> Chem.rdchem.Mol: # def inchi_or_smiles_to_inchi(molecule_id: str) -> str: # def inchi_or_smiles_to_smiles(molecule_id: str) -> str: # def normalize_molecule(mol: Chem.rdchem.Mol) -> Chem.rdchem.Mol: # def are_equal(molecule1: Chem.rdchem.Mol, molecule2: Chem.rdchem.Mol) -> bool: # def is_synonym(name: str, synonym_string: str) -> bool: # def valid_adduct(value: str) -> bool: # def mol_to_image(mol: Chem.rdchem.Mol, **kwargs) -> widgets.Image: which might include code, classes, or functions. Output only the next line.
pre = cheminfo.get_precursor_mz(original_parent, name)
Predict the next line for this snippet: <|code_start|>"""Utility functions for working with metatlas data structures""" logger = logging.getLogger(__name__) AtlasName = NewType("AtlasName", str) Username = NewType("Username", str) <|code_end|> with the help of current file imports: import logging from typing import NewType from metatlas.datastructures import metatlas_objects as metob and context from other files: # Path: metatlas/datastructures/metatlas_objects.py # FETCH_STUBS = True # ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-','[2M+H]+','[2M-H]-','[M-H+Na]+','[M+K]+','[M+2Na]2+','[M-e]+','[M+acetate]-','[M+formate]-','[M-H+Cl]2-','[M-H+2Na]+') # POLARITY = ('positive', 'negative', 'alternating') # FRAGMENTATION_TECHNIQUE = ('hcd','cid','etd','ecd','irmpd') # ID_GRADES: Dict[str, IdentificationGrade] = dict() # FETCH_STUBS = False # FETCH_STUBS = True # FETCH_STUBS = True # def retrieve(object_type, **kwargs): # def remove(object_type, **kwargs): # def remove_objects(objects, all_versions=True, **kwargs): # def store(objects, **kwargs): # def __init__(self, **kwargs): # def _update(self, override_user=False): # def clone(self, recursive=False): # def show_diff(self, unique_id=None): # def _on_update(self, change): # def __str__(self): # def __repr__(self): # def __getattribute__(self, name): # def validate(self, obj, value): # def find_invalid_runs(**kwargs): # def to_dataframe(objects): # class MetatlasObject(HasTraits): # class Method(MetatlasObject): # class Sample(MetatlasObject): # class LcmsRun(MetatlasObject): # class FunctionalSet(MetatlasObject): # class Compound(MetatlasObject): # class Reference(MetatlasObject): # class IdentificationGrade(MetatlasObject): # class _IdGradeTrait(MetInstance): # class Group(MetatlasObject): # class MzIntensityPair(MetatlasObject): # class FragmentationReference(Reference): # class RtReference(Reference): # class MzReference(Reference): # class IntensityReference(Reference): # class CompoundIdentification(MetatlasObject): # class Atlas(MetatlasObject): # class MZMineTask(MetatlasObject): , which may contain function names, class names, or code. Output only the next line.
def get_atlas(name: AtlasName, username: Username) -> metob.Atlas:
Using the snippet: <|code_start|>@functools.lru_cache def inchi_or_smiles_to_molecule(molecule_id: str) -> Chem.rdchem.Mol: """Convert Inchi or smiles to rdkit Mol""" out = Chem.inchi.MolFromInchi(molecule_id) or Chem.MolFromSmiles(molecule_id) if out is None: raise ValueError(f"'{molecule_id}' is not a valid Inchi or smiles") return out @functools.lru_cache def inchi_or_smiles_to_inchi(molecule_id: str) -> str: """Inchi or smiles string to smiles string""" out = Chem.inchi.MolToInchi(inchi_or_smiles_to_molecule(molecule_id)) if out is None: raise ValueError(f"'{molecule_id}' is not a valid Inchi or smiles") return out @functools.lru_cache def inchi_or_smiles_to_smiles(molecule_id: str) -> str: """Inchi or smiles string to smiles string""" out = Chem.MolToSmiles(inchi_or_smiles_to_molecule(molecule_id)) if out is None: raise ValueError(f"'{molecule_id}' is not a valid Inchi or smiles") return out @functools.lru_cache def normalize_molecule(mol: Chem.rdchem.Mol) -> Chem.rdchem.Mol: """Removes salt and neutralizes charges""" <|code_end|> , determine the next line of code. You have imports: import functools import logging import ipywidgets as widgets import matchms import numpy as np from rdkit import Chem from metatlas.interfaces.compounds import structure_cleaning as cleaning and context (class names, function names, or code) available: # Path: metatlas/interfaces/compounds/structure_cleaning.py # def _InitialiseNeutralisationReactions(): # def neutralizeRadicals(mol): # def NeutraliseCharges(mol, reactions=None): # def desalt(mol): # def desalt_compounds_in_dataframe(x): # def neutralize_compounds_in_dataframe(x): # def calculate_num_radicals_in_dataframe(x): # def calculate_formula_in_dataframe(x): # def calculate_monoisotopic_mw_in_dataframe(x): # def calculate_inchi_in_dataframe(x): # def calculate_flattened_inchi_in_dataframe(x): # def calculate_inchikey_in_dataframe(x): # def calculate_charge_in_dataframe(x): . Output only the next line.
desalted, _ = cleaning.desalt(mol)
Given the code snippet: <|code_start|>"""Plot set of EIC plots for a compound. One sample per sub-plot""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods logger = logging.getLogger(__name__) MetatlasDataset = List[List[Any]] # avoiding a circular import class CompoundEic(plot_set.Plot): """EIC for one compound within a single sample""" def __init__(self, title: str, group_name: str, compound: Dict[str, Any], rt_buffer: float = 0.5): """ compound: Compound instance rt_buffer: amount of time in minutes to show to each side of rt_min/rt_max/rt_peak """ super().__init__(title, group_name) self.compound = compound <|code_end|> , generate the next line using the imports in this file: import logging import matplotlib import numpy as np from pathlib import Path from typing import Any, Dict, List, Sequence, Tuple from metatlas.datastructures import metatlas_objects as metob from metatlas.plots import plot_set from metatlas.plots import utils and context (functions, classes, or occasionally code) from other files: # Path: metatlas/datastructures/metatlas_objects.py # FETCH_STUBS = True # ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-','[2M+H]+','[2M-H]-','[M-H+Na]+','[M+K]+','[M+2Na]2+','[M-e]+','[M+acetate]-','[M+formate]-','[M-H+Cl]2-','[M-H+2Na]+') # POLARITY = ('positive', 'negative', 'alternating') # FRAGMENTATION_TECHNIQUE = ('hcd','cid','etd','ecd','irmpd') # ID_GRADES: Dict[str, IdentificationGrade] = dict() # FETCH_STUBS = False # FETCH_STUBS = True # FETCH_STUBS = True # def retrieve(object_type, **kwargs): # def remove(object_type, **kwargs): # def remove_objects(objects, all_versions=True, **kwargs): # def store(objects, **kwargs): # def __init__(self, **kwargs): # def _update(self, override_user=False): # def clone(self, recursive=False): # def show_diff(self, unique_id=None): # def _on_update(self, change): # def __str__(self): # def __repr__(self): # def __getattribute__(self, name): # def validate(self, obj, value): # def find_invalid_runs(**kwargs): # def to_dataframe(objects): # class MetatlasObject(HasTraits): # class Method(MetatlasObject): # class Sample(MetatlasObject): # class LcmsRun(MetatlasObject): # class FunctionalSet(MetatlasObject): # class Compound(MetatlasObject): # class Reference(MetatlasObject): # class IdentificationGrade(MetatlasObject): # class _IdGradeTrait(MetInstance): # class Group(MetatlasObject): # class MzIntensityPair(MetatlasObject): # class FragmentationReference(Reference): # class RtReference(Reference): # class MzReference(Reference): # class IntensityReference(Reference): # class CompoundIdentification(MetatlasObject): # class Atlas(MetatlasObject): # class MZMineTask(MetatlasObject): # # Path: metatlas/plots/plot_set.py # def restore_matplotlib_settings(func): # def wrapper(*args, **kwargs): # def __init__(self, title: str, group_name: str): # def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None: # def __init__( # self, # plots: Sequence[Plot], # max_plots_per_fig: int = 30, # x_min: Optional[float] = None, # x_max: Optional[float] = None, # y_min: Optional[float] = None, # y_max: Optional[float] = None, # sharey: bool = True, # font_scale: float = 2, # ): # def __enter__(self): # def __exit__(self, exc_type, exc_value, exc_tb): # def limit_axes( # self, # x_min: Optional[float], # x_max: Optional[float], # y_min: Optional[float], # y_max: Optional[float], # ) -> None: # def save_pdf(self, file_name: str, title: str, overwrite: bool = False) -> None: # def close(self): # def _get_xy(artist: matplotlib.artist.Artist) -> Tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: # def _autoscale(ax: matplotlib.axes.Axes, axis: str = "y", sides: str = "both", margin: float = 0.1) -> None: # def _update_limts( # low: float, # high: float, # fixed: npt.NDArray[np.float64], # dependent: npt.NDArray[np.float64], # fixed_limits: Tuple[float, float], # ) -> Tuple[float, float]: # def _calculate_new_limit( # fixed: npt.NDArray[np.float64], dependent: npt.NDArray[np.float64], fixed_limits: Tuple[float, float] # ) -> Tuple[float, float]: # class Plot(ABC): # class PlotSet(ABC): # # Path: metatlas/plots/utils.py # BACKGROUND_COLORS = ["white", "lightyellow", "whitesmoke", "lavenderblush"] # def colors() -> Generator: # def subplot_dimensions(num: int) -> Tuple[int, int]: # def wrap_subplots(num: int, **kwargs) -> Tuple[matplotlib.figure.Figure, List[matplotlib.axes.Axes]]: # def is_in_range(a: List[float], start: float, stop: float) -> List[bool]: # def fill_under( # ax: matplotlib.axes.Axes, # x: List[float], # y: List[float], # between: Optional[Tuple[float, float]] = None, # **kwargs, # ) -> None: # def pdf_with_text(text: str, file_name: str, size: int = 24): . Output only the next line.
rt_ref: metob.RtReference = compound["identification"].rt_references[0]
Based on the snippet: <|code_start|>"""Plot set of TIC plots. One sample per sub-plot""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods,too-many-locals logger = logging.getLogger(__name__) MetatlasDataset = List[List[Any]] # avoiding a circular import class Tic(plot_set.Plot): """TIC for a single sample""" def __init__(self, title: str, group_name: str, h5_file_name: str, polarity: str): super().__init__(title, group_name) self.h5_file_name = h5_file_name assert polarity in ["positive", "negative"] self.polarity = polarity def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None: """Draw plot of TIC on ax""" super().plot(ax, back_color) dataset = f"ms1_{self.polarity[:3]}" <|code_end|> , predict the immediate next line with the help of imports: import logging import matplotlib from pathlib import Path from typing import Any, List, Optional from matplotlib.ticker import MultipleLocator from metatlas.io.metatlas_get_data_helper_fun import get_bpc from metatlas.plots import plot_set from metatlas.plots import utils and context (classes, functions, sometimes code) from other files: # Path: metatlas/io/metatlas_get_data_helper_fun.py # def get_bpc(filename,dataset='ms1_pos',integration='bpc'): # """ # Gets the basepeak chromatogram for a file. # filename: File can be either a metatlas lcmsrun object or a full path to an hdf5file # dataset: ms1_pos, ms1_neg, ms2_pos, ms2_neg # # Returns: # A pandas dataframe with the value at the maximum intensity at each retention time # """ # df_container = df_container_from_metatlas_file(filename) # if integration=='bpc': # bpc = df_container[dataset].sort_values('i', ascending=False).groupby('rt', as_index=False).first().sort_values('rt',ascending=True) # return bpc # else: # tic = df_container[dataset][['rt','i']].groupby('rt',as_index=False).sum().sort_values('rt',ascending=True) # return tic # # Path: metatlas/plots/plot_set.py # def restore_matplotlib_settings(func): # def wrapper(*args, **kwargs): # def __init__(self, title: str, group_name: str): # def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None: # def __init__( # self, # plots: Sequence[Plot], # max_plots_per_fig: int = 30, # x_min: Optional[float] = None, # x_max: Optional[float] = None, # y_min: Optional[float] = None, # y_max: Optional[float] = None, # sharey: bool = True, # font_scale: float = 2, # ): # def __enter__(self): # def __exit__(self, exc_type, exc_value, exc_tb): # def limit_axes( # self, # x_min: Optional[float], # x_max: Optional[float], # y_min: Optional[float], # y_max: Optional[float], # ) -> None: # def save_pdf(self, file_name: str, title: str, overwrite: bool = False) -> None: # def close(self): # def _get_xy(artist: matplotlib.artist.Artist) -> Tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: # def _autoscale(ax: matplotlib.axes.Axes, axis: str = "y", sides: str = "both", margin: float = 0.1) -> None: # def _update_limts( # low: float, # high: float, # fixed: npt.NDArray[np.float64], # dependent: npt.NDArray[np.float64], # fixed_limits: Tuple[float, float], # ) -> Tuple[float, float]: # def _calculate_new_limit( # fixed: npt.NDArray[np.float64], dependent: npt.NDArray[np.float64], fixed_limits: Tuple[float, float] # ) -> Tuple[float, float]: # class Plot(ABC): # class PlotSet(ABC): # # Path: metatlas/plots/utils.py # BACKGROUND_COLORS = ["white", "lightyellow", "whitesmoke", "lavenderblush"] # def colors() -> Generator: # def subplot_dimensions(num: int) -> Tuple[int, int]: # def wrap_subplots(num: int, **kwargs) -> Tuple[matplotlib.figure.Figure, List[matplotlib.axes.Axes]]: # def is_in_range(a: List[float], start: float, stop: float) -> List[bool]: # def fill_under( # ax: matplotlib.axes.Axes, # x: List[float], # y: List[float], # between: Optional[Tuple[float, float]] = None, # **kwargs, # ) -> None: # def pdf_with_text(text: str, file_name: str, size: int = 24): . Output only the next line.
tic_df = get_bpc(self.h5_file_name, dataset=dataset, integration="tic")
Predict the next line after this snippet: <|code_start|>"""Plot set of TIC plots. One sample per sub-plot""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods,too-many-locals logger = logging.getLogger(__name__) MetatlasDataset = List[List[Any]] # avoiding a circular import class Tic(plot_set.Plot): """TIC for a single sample""" def __init__(self, title: str, group_name: str, h5_file_name: str, polarity: str): super().__init__(title, group_name) self.h5_file_name = h5_file_name assert polarity in ["positive", "negative"] self.polarity = polarity <|code_end|> using the current file's imports: import logging import matplotlib from pathlib import Path from typing import Any, List, Optional from matplotlib.ticker import MultipleLocator from metatlas.io.metatlas_get_data_helper_fun import get_bpc from metatlas.plots import plot_set from metatlas.plots import utils and any relevant context from other files: # Path: metatlas/io/metatlas_get_data_helper_fun.py # def get_bpc(filename,dataset='ms1_pos',integration='bpc'): # """ # Gets the basepeak chromatogram for a file. # filename: File can be either a metatlas lcmsrun object or a full path to an hdf5file # dataset: ms1_pos, ms1_neg, ms2_pos, ms2_neg # # Returns: # A pandas dataframe with the value at the maximum intensity at each retention time # """ # df_container = df_container_from_metatlas_file(filename) # if integration=='bpc': # bpc = df_container[dataset].sort_values('i', ascending=False).groupby('rt', as_index=False).first().sort_values('rt',ascending=True) # return bpc # else: # tic = df_container[dataset][['rt','i']].groupby('rt',as_index=False).sum().sort_values('rt',ascending=True) # return tic # # Path: metatlas/plots/plot_set.py # def restore_matplotlib_settings(func): # def wrapper(*args, **kwargs): # def __init__(self, title: str, group_name: str): # def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None: # def __init__( # self, # plots: Sequence[Plot], # max_plots_per_fig: int = 30, # x_min: Optional[float] = None, # x_max: Optional[float] = None, # y_min: Optional[float] = None, # y_max: Optional[float] = None, # sharey: bool = True, # font_scale: float = 2, # ): # def __enter__(self): # def __exit__(self, exc_type, exc_value, exc_tb): # def limit_axes( # self, # x_min: Optional[float], # x_max: Optional[float], # y_min: Optional[float], # y_max: Optional[float], # ) -> None: # def save_pdf(self, file_name: str, title: str, overwrite: bool = False) -> None: # def close(self): # def _get_xy(artist: matplotlib.artist.Artist) -> Tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: # def _autoscale(ax: matplotlib.axes.Axes, axis: str = "y", sides: str = "both", margin: float = 0.1) -> None: # def _update_limts( # low: float, # high: float, # fixed: npt.NDArray[np.float64], # dependent: npt.NDArray[np.float64], # fixed_limits: Tuple[float, float], # ) -> Tuple[float, float]: # def _calculate_new_limit( # fixed: npt.NDArray[np.float64], dependent: npt.NDArray[np.float64], fixed_limits: Tuple[float, float] # ) -> Tuple[float, float]: # class Plot(ABC): # class PlotSet(ABC): # # Path: metatlas/plots/utils.py # BACKGROUND_COLORS = ["white", "lightyellow", "whitesmoke", "lavenderblush"] # def colors() -> Generator: # def subplot_dimensions(num: int) -> Tuple[int, int]: # def wrap_subplots(num: int, **kwargs) -> Tuple[matplotlib.figure.Figure, List[matplotlib.axes.Axes]]: # def is_in_range(a: List[float], start: float, stop: float) -> List[bool]: # def fill_under( # ax: matplotlib.axes.Axes, # x: List[float], # y: List[float], # between: Optional[Tuple[float, float]] = None, # **kwargs, # ) -> None: # def pdf_with_text(text: str, file_name: str, size: int = 24): . Output only the next line.
def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None:
Based on the snippet: <|code_start|> and not a key name, make it a tuple with the attribute name string as the first member, such as: ('attribute_name',). If you want to make it more explict to the reader, you can add a second member to the tuple, which will not be used, such as ('attribute_name', 'as attribute') """ if len(ids) == 0: raise ValueError('ids cannot be empty') if len(ids) == 1: if isinstance(ids[0], tuple): setattr(data, ids[0][0], value) elif isinstance(ids[0], str) and hasattr(data, ids[0]): setattr(data, ids[0], value) else: data[ids[0]] = value # works for list or dict else: if isinstance(ids[0], tuple): set_nested(getattr(data, ids[0][0]), ids[1:], value) elif isinstance(ids[0], str) and hasattr(data, ids[0]): set_nested(getattr(data, ids[0]), ids[1:], value) else: set_nested(data[ids[0]], ids[1:], value) def make_atlas_df(atlas): """ inputs: atlas: metatlas.datastructures.metatlas_objects.Atlas output: pandas DataFrame with one row per CompoundIdentification in atlas and each row also includes the first RtReference, MzReference, and Compound from the CompoundIdentification """ <|code_end|> , predict the immediate next line with the help of imports: import copy import logging import math import os.path import re import sys import dill import matplotlib.pyplot as plt import numpy as np import pandas as pd import six import tables from collections import defaultdict from textwrap import wrap from metatlas.datastructures import metatlas_objects as metob from metatlas.io import h5_query as h5q from metatlas.io import write_utils and context (classes, functions, sometimes code) from other files: # Path: metatlas/datastructures/metatlas_objects.py # FETCH_STUBS = True # ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-','[2M+H]+','[2M-H]-','[M-H+Na]+','[M+K]+','[M+2Na]2+','[M-e]+','[M+acetate]-','[M+formate]-','[M-H+Cl]2-','[M-H+2Na]+') # POLARITY = ('positive', 'negative', 'alternating') # FRAGMENTATION_TECHNIQUE = ('hcd','cid','etd','ecd','irmpd') # ID_GRADES: Dict[str, IdentificationGrade] = dict() # FETCH_STUBS = False # FETCH_STUBS = True # FETCH_STUBS = True # def retrieve(object_type, **kwargs): # def remove(object_type, **kwargs): # def remove_objects(objects, all_versions=True, **kwargs): # def store(objects, **kwargs): # def __init__(self, **kwargs): # def _update(self, override_user=False): # def clone(self, recursive=False): # def show_diff(self, unique_id=None): # def _on_update(self, change): # def __str__(self): # def __repr__(self): # def __getattribute__(self, name): # def validate(self, obj, value): # def find_invalid_runs(**kwargs): # def to_dataframe(objects): # class MetatlasObject(HasTraits): # class Method(MetatlasObject): # class Sample(MetatlasObject): # class LcmsRun(MetatlasObject): # class FunctionalSet(MetatlasObject): # class Compound(MetatlasObject): # class Reference(MetatlasObject): # class IdentificationGrade(MetatlasObject): # class _IdGradeTrait(MetInstance): # class Group(MetatlasObject): # class MzIntensityPair(MetatlasObject): # class FragmentationReference(Reference): # class RtReference(Reference): # class MzReference(Reference): # class IntensityReference(Reference): # class CompoundIdentification(MetatlasObject): # class Atlas(MetatlasObject): # class MZMineTask(MetatlasObject): # # Path: metatlas/io/h5_query.py # def get_data(h5file, **kwargs): # def get_chromatogram(h5file, min_mz, max_mz, aggregator=np.sum, **kwargs): # def get_heatmap(h5file, mz_bins, **kwargs): # def get_spectrogram(h5file, min_rt, max_rt, bins=2000, **kwargs): # def get_info(h5file): # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): . Output only the next line.
mzs = [extract(aci, ['mz_references', 0], metob.MzReference()) for aci in atlas.compound_identifications]
Given the following code snippet before the placeholder: <|code_start|> polarity = 1 else: polarity = 0 mz_theor = mz_ref.mz if mz_ref.mz_tolerance_units == 'ppm': #convert to ppm ppm_uncertainty = mz_ref.mz_tolerance else: ppm_uncertainty = mz_ref.mz_tolerance / mz_ref.mz * 1e6 # if 'min' in rt_ref.rt_units: #convert to seconds # rt_min = rt_ref.rt_min / 60 # rt_max = rt_ref.rt_max / 60 # else: rt_min = rt_ref.rt_min rt_max = rt_ref.rt_max mz_min = mz_theor - mz_theor * ppm_uncertainty / 1e6 mz_max = mz_theor + mz_theor * ppm_uncertainty / 1e6 return_data = {} if 'ms1_summary' in what_to_get: #Get Summary Data #First get MS1 Raw Data ms_level=1 return_data['ms1_summary'] = {} try: <|code_end|> , predict the next line using imports from the current file: import copy import logging import math import os.path import re import sys import dill import matplotlib.pyplot as plt import numpy as np import pandas as pd import six import tables from collections import defaultdict from textwrap import wrap from metatlas.datastructures import metatlas_objects as metob from metatlas.io import h5_query as h5q from metatlas.io import write_utils and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/metatlas_objects.py # FETCH_STUBS = True # ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-','[2M+H]+','[2M-H]-','[M-H+Na]+','[M+K]+','[M+2Na]2+','[M-e]+','[M+acetate]-','[M+formate]-','[M-H+Cl]2-','[M-H+2Na]+') # POLARITY = ('positive', 'negative', 'alternating') # FRAGMENTATION_TECHNIQUE = ('hcd','cid','etd','ecd','irmpd') # ID_GRADES: Dict[str, IdentificationGrade] = dict() # FETCH_STUBS = False # FETCH_STUBS = True # FETCH_STUBS = True # def retrieve(object_type, **kwargs): # def remove(object_type, **kwargs): # def remove_objects(objects, all_versions=True, **kwargs): # def store(objects, **kwargs): # def __init__(self, **kwargs): # def _update(self, override_user=False): # def clone(self, recursive=False): # def show_diff(self, unique_id=None): # def _on_update(self, change): # def __str__(self): # def __repr__(self): # def __getattribute__(self, name): # def validate(self, obj, value): # def find_invalid_runs(**kwargs): # def to_dataframe(objects): # class MetatlasObject(HasTraits): # class Method(MetatlasObject): # class Sample(MetatlasObject): # class LcmsRun(MetatlasObject): # class FunctionalSet(MetatlasObject): # class Compound(MetatlasObject): # class Reference(MetatlasObject): # class IdentificationGrade(MetatlasObject): # class _IdGradeTrait(MetInstance): # class Group(MetatlasObject): # class MzIntensityPair(MetatlasObject): # class FragmentationReference(Reference): # class RtReference(Reference): # class MzReference(Reference): # class IntensityReference(Reference): # class CompoundIdentification(MetatlasObject): # class Atlas(MetatlasObject): # class MZMineTask(MetatlasObject): # # Path: metatlas/io/h5_query.py # def get_data(h5file, **kwargs): # def get_chromatogram(h5file, min_mz, max_mz, aggregator=np.sum, **kwargs): # def get_heatmap(h5file, mz_bins, **kwargs): # def get_spectrogram(h5file, min_rt, max_rt, bins=2000, **kwargs): # def get_info(h5file): # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): . Output only the next line.
ms1_data = h5q.get_data(fid,
Given the following code snippet before the placeholder: <|code_start|> newstr = re.sub(r'\.', 'p', newstr) # 2 or more in regexp newstr = re.sub(r'[\[\]]', '', newstr) newstr = re.sub('[^A-Za-z0-9+-]+', '_', newstr) newstr = re.sub('i_[A-Za-z]+_i_', '', newstr) if newstr[0] in ['_', '-']: newstr = newstr[1:] if newstr[-1] == '_': newstr = newstr[:-1] newstr = re.sub('[^A-Za-z0-9]{2,}', '', newstr) #2 or more in regexp compound_names.append(newstr) # If duplicate compound names exist, then append them with a number D = defaultdict(list) for i,item in enumerate(compound_names): D[item].append(i) D = {k:v for k,v in D.items() if len(v)>1} for k in D.keys(): for i,f in enumerate(D[k]): compound_names[f] = '%s%d'%(compound_names[f],i) return (compound_names, compound_objects) def make_data_sources_tables(groups, myatlas, output_loc, polarity=None, overwrite=True): """ polarity must be one of None, 'POS', 'NEG' or will throw ValueError """ if polarity not in [None, 'POS', 'NEG']: raise ValueError("Polarity parameter must be one of None, 'POS', or 'NEG'.") prefix = f"{polarity}_" if polarity else "" output_dir = os.path.join(output_loc, f"{prefix}data_sources") atlas_path = os.path.join(output_dir, f"{prefix}atlas_metadata.tab") <|code_end|> , predict the next line using imports from the current file: import copy import logging import math import os.path import re import sys import dill import matplotlib.pyplot as plt import numpy as np import pandas as pd import six import tables from collections import defaultdict from textwrap import wrap from metatlas.datastructures import metatlas_objects as metob from metatlas.io import h5_query as h5q from metatlas.io import write_utils and context including class names, function names, and sometimes code from other files: # Path: metatlas/datastructures/metatlas_objects.py # FETCH_STUBS = True # ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-','[2M+H]+','[2M-H]-','[M-H+Na]+','[M+K]+','[M+2Na]2+','[M-e]+','[M+acetate]-','[M+formate]-','[M-H+Cl]2-','[M-H+2Na]+') # POLARITY = ('positive', 'negative', 'alternating') # FRAGMENTATION_TECHNIQUE = ('hcd','cid','etd','ecd','irmpd') # ID_GRADES: Dict[str, IdentificationGrade] = dict() # FETCH_STUBS = False # FETCH_STUBS = True # FETCH_STUBS = True # def retrieve(object_type, **kwargs): # def remove(object_type, **kwargs): # def remove_objects(objects, all_versions=True, **kwargs): # def store(objects, **kwargs): # def __init__(self, **kwargs): # def _update(self, override_user=False): # def clone(self, recursive=False): # def show_diff(self, unique_id=None): # def _on_update(self, change): # def __str__(self): # def __repr__(self): # def __getattribute__(self, name): # def validate(self, obj, value): # def find_invalid_runs(**kwargs): # def to_dataframe(objects): # class MetatlasObject(HasTraits): # class Method(MetatlasObject): # class Sample(MetatlasObject): # class LcmsRun(MetatlasObject): # class FunctionalSet(MetatlasObject): # class Compound(MetatlasObject): # class Reference(MetatlasObject): # class IdentificationGrade(MetatlasObject): # class _IdGradeTrait(MetInstance): # class Group(MetatlasObject): # class MzIntensityPair(MetatlasObject): # class FragmentationReference(Reference): # class RtReference(Reference): # class MzReference(Reference): # class IntensityReference(Reference): # class CompoundIdentification(MetatlasObject): # class Atlas(MetatlasObject): # class MZMineTask(MetatlasObject): # # Path: metatlas/io/h5_query.py # def get_data(h5file, **kwargs): # def get_chromatogram(h5file, min_mz, max_mz, aggregator=np.sum, **kwargs): # def get_heatmap(h5file, mz_bins, **kwargs): # def get_spectrogram(h5file, min_rt, max_rt, bins=2000, **kwargs): # def get_info(h5file): # # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): . Output only the next line.
write_utils.export_dataframe(metob.to_dataframe([myatlas]), atlas_path, "atlas metadata",
Given snippet: <|code_start|> d_1 = yield_ppm(data, 'ppm', threshold, tolerance, mz_t, rt_max) # Looking through MS2, precursor data = dataset[ms2] data_filter = (abs(data['precursor_MZ'] - mz_t) * 1e6) <= tolerance * mz_t filtered = data[data_filter] thresh = filtered[filtered.i >= threshold] if rt_max != -1: thresh = thresh[abs(thresh.rt - rt_max) <= .5] uniques = thresh.drop_duplicates('precursor_MZ') d_2 = uniques.loc[:, list(uniques)] d_2['ppm'] = (abs(d_2['precursor_MZ'] - mz_t) * 1e6 / mz_t) # Double filter on mz and precursor_MZ # MS 2 d_3 = yield_ppm(filtered, 'ppm', threshold, tolerance, mz_t, rt_max) return (d_1.reset_index(), d_2.reset_index(), d_3.reset_index(), ms1_max_i, rt_max) def data_verify(file_name,tolerance=tolerance,std=std,std_neg=std_neg,threshold=threshold,rt_max=-1): if type(file_name) == str: hdf5_name = file_name else: #its a metatlas object hdf5_name = file_name.hdf5_file <|code_end|> , continue by predicting the next line. Consider current file imports: import smtplib import mimetypes import itertools import time import sys import os import glob import pandas as pd import metatlas.metatlas_objects.metatlas_objects as metob import multiprocessing as mp import numpy as np from typing import Any, Dict from datetime import datetime, time as dtime from collections import defaultdict from metatlas.io.mzml_loader import VERSION_TIMESTAMP from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email import encoders from subprocess import check_output from metatlas.io import metatlas_get_data_helper_fun as ma_data from metatlas.metatlas_objects.metatlas_objects import find_invalid_runs from metatlas.io.system_utils import send_mail and context: # Path: metatlas/io/metatlas_get_data_helper_fun.py # def create_msms_dataframe(df): # def compare_EIC_to_BPC_for_file(metatlas_dataset,file_index,yscale = 'linear'): # def get_data_for_atlas_df_and_file(input_tuple): # def get_bpc(filename,dataset='ms1_pos',integration='bpc'): # def df_container_from_metatlas_file(my_file): # def fast_nearest_interp(xi, x, y): # def remove_ms1_data_not_in_atlas(atlas_df, data): # def extract(data, ids, default=None): # def set_nested(data, ids, value): # def make_atlas_df(atlas): # def transfer_identification_data_to_atlas(data, atlas, ids_list=None): # def get_data_for_mzrt(row, data_df_pos, data_df_neg, extra_time=0.5, use_mz='mz', extra_mz=0.0): # def get_ms1_summary(row): # def get_ms2_data(row): # def prefilter_ms1_dataframe_with_boundaries(data_df, rt_max, rt_min, mz_min, mz_max, extra_time=0.5, extra_mz=0.01): # def get_ms1_eic(row): # def retrieve_most_intense_msms_scan(data): # def get_data_for_atlas_and_lcmsrun(atlas_df, df_container, extra_time, extra_mz): # def get_feature_data(atlas_df, pos_df, neg_df, use_mz='mz'): # def get_ms2_dict(ms2_feature_data_df): # def get_ms1_summary_data(ms1_feature_data_df): # def get_eic_data(ms1_feature_data_df): # def get_unique_scan_data(data): # def get_non_redundant_precursor_list(prt,pmz,rt_cutoff,mz_cutoff): # def organize_msms_scan_data(data,list_of_prt,list_of_pmz,list_of_pintensity): # def get_data_for_a_compound(mz_ref,rt_ref,what_to_get,h5file,extra_time): # def get_dill_data(fname): # def get_group_names(data): # def get_group_shortnames(data): # def get_file_names(data,full_path=False): # def get_compound_names(data,use_labels=False): # def make_data_sources_tables(groups, myatlas, output_loc, polarity=None, overwrite=True): # D = defaultdict(list) # D = {k:v for k,v in D.items() if len(v)>1} # # Path: metatlas/io/system_utils.py # def send_mail(subject, username, body, force=False): # """Send the mail only once per day.""" # # now = datetime.now() # if force or dtime(00, 00) <= now.time() <= dtime(00, 10): # sender = 'pasteur@nersc.gov' # receivers = [f"{username}@lbl.gov", "bpbowen@lbl.gov"] # message = """\ # From: %s # To: %s # Subject: %s # # %s # """ % (sender, ", ".join(receivers), subject, body) # try: # smtpObj = smtplib.SMTP('smtp.lbl.gov') # smtpObj.sendmail(sender, receivers, message) # sys.stdout.write("Successfully sent email to %s\n" % username) # sys.stdout.flush() # except smtplib.SMTPException: # sys.stderr.write("Error: unable to send email to %s\n" % username) # sys.stdout.flush() which might include code, classes, or functions. Output only the next line.
dataset = ma_data.df_container_from_metatlas_file(hdf5_name)
Predict the next line for this snippet: <|code_start|>std_name = 'ABMBA' rt_max = -1 run_times: Dict[str, Any] = {} save_path = '/project/projectdirs/metatlas/projects/istd_logs/' def check_metatlas(): """ Checks for invalid runs. """ invalid_runs = find_invalid_runs(_override=True) # Currently there exists a bug (?) where it shows empty files. # It could be a result of the database remembering invalid files # that were removed. Since there is no file associated with these runs, # there will not be any filename. # This can technically be fixed by running: # grouped = grouped.filter(False, str_list) # followed by a run to remove all usernames without any files, # but does not directly solve the problem. # Leaving this to someone in the future to resolve. if invalid_runs: grouped = defaultdict(list) for run in invalid_runs: grouped[run.username].append(run.mzml_file) for (username, filenames) in grouped.items(): body = 'You have runs that are not longer accessible\n' body += 'To remove them from the database, run the following on ipython.nersc.gov:\n\n' body += 'from metatlas.metatlas_objects import find_invalid_runs, remove_objects\n' body += 'remove_objects(find_invalid_runs())\n\n' body += 'The invalid runs are:\n%s' % ('\n'.join(filenames)) <|code_end|> with the help of current file imports: import smtplib import mimetypes import itertools import time import sys import os import glob import pandas as pd import metatlas.metatlas_objects.metatlas_objects as metob import multiprocessing as mp import numpy as np from typing import Any, Dict from datetime import datetime, time as dtime from collections import defaultdict from metatlas.io.mzml_loader import VERSION_TIMESTAMP from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email import encoders from subprocess import check_output from metatlas.io import metatlas_get_data_helper_fun as ma_data from metatlas.metatlas_objects.metatlas_objects import find_invalid_runs from metatlas.io.system_utils import send_mail and context from other files: # Path: metatlas/io/metatlas_get_data_helper_fun.py # def create_msms_dataframe(df): # def compare_EIC_to_BPC_for_file(metatlas_dataset,file_index,yscale = 'linear'): # def get_data_for_atlas_df_and_file(input_tuple): # def get_bpc(filename,dataset='ms1_pos',integration='bpc'): # def df_container_from_metatlas_file(my_file): # def fast_nearest_interp(xi, x, y): # def remove_ms1_data_not_in_atlas(atlas_df, data): # def extract(data, ids, default=None): # def set_nested(data, ids, value): # def make_atlas_df(atlas): # def transfer_identification_data_to_atlas(data, atlas, ids_list=None): # def get_data_for_mzrt(row, data_df_pos, data_df_neg, extra_time=0.5, use_mz='mz', extra_mz=0.0): # def get_ms1_summary(row): # def get_ms2_data(row): # def prefilter_ms1_dataframe_with_boundaries(data_df, rt_max, rt_min, mz_min, mz_max, extra_time=0.5, extra_mz=0.01): # def get_ms1_eic(row): # def retrieve_most_intense_msms_scan(data): # def get_data_for_atlas_and_lcmsrun(atlas_df, df_container, extra_time, extra_mz): # def get_feature_data(atlas_df, pos_df, neg_df, use_mz='mz'): # def get_ms2_dict(ms2_feature_data_df): # def get_ms1_summary_data(ms1_feature_data_df): # def get_eic_data(ms1_feature_data_df): # def get_unique_scan_data(data): # def get_non_redundant_precursor_list(prt,pmz,rt_cutoff,mz_cutoff): # def organize_msms_scan_data(data,list_of_prt,list_of_pmz,list_of_pintensity): # def get_data_for_a_compound(mz_ref,rt_ref,what_to_get,h5file,extra_time): # def get_dill_data(fname): # def get_group_names(data): # def get_group_shortnames(data): # def get_file_names(data,full_path=False): # def get_compound_names(data,use_labels=False): # def make_data_sources_tables(groups, myatlas, output_loc, polarity=None, overwrite=True): # D = defaultdict(list) # D = {k:v for k,v in D.items() if len(v)>1} # # Path: metatlas/io/system_utils.py # def send_mail(subject, username, body, force=False): # """Send the mail only once per day.""" # # now = datetime.now() # if force or dtime(00, 00) <= now.time() <= dtime(00, 10): # sender = 'pasteur@nersc.gov' # receivers = [f"{username}@lbl.gov", "bpbowen@lbl.gov"] # message = """\ # From: %s # To: %s # Subject: %s # # %s # """ % (sender, ", ".join(receivers), subject, body) # try: # smtpObj = smtplib.SMTP('smtp.lbl.gov') # smtpObj.sendmail(sender, receivers, message) # sys.stdout.write("Successfully sent email to %s\n" % username) # sys.stdout.flush() # except smtplib.SMTPException: # sys.stderr.write("Error: unable to send email to %s\n" % username) # sys.stdout.flush() , which may contain function names, class names, or code. Output only the next line.
send_mail('Metatlas Runs are Invalid', username, body)
Predict the next line after this snippet: <|code_start|>"""Test of notebook functions""" # pylint: disable=missing-function-docstring def test_create_notebook_with_parameters01(): orig_data = { "cells": [ { "metadata": {"tags": ["parameters"]}, "source": [ "# this is a comment\n", "param1 = 0\n", "\n", "param2 = []\n", 'param3 = "REPLACE ME"\n', ], }, ] } with open("test.json", "w", encoding="utf8") as out_fh: json.dump(orig_data, out_fh) <|code_end|> using the current file's imports: import json from metatlas.tools import notebook and any relevant context from other files: # Path: metatlas/tools/notebook.py # def configure_environment(log_level: str) -> None: # def configure_pandas_display(max_rows: int = 5000, max_columns: int = 500, max_colwidth: int = 100) -> None: # def configure_notebook_display() -> None: # def setup(log_level: str, source_code_version_id: Optional[str] = None) -> None: # def activate_sql_logging(console_level="INFO", console_format=None, file_level="DEBUG", filename=None): # def cells_matching_tags(data: dict, tags: List[str]) -> List[int]: # def has_intersection(one: List, two: List) -> bool: # def get_metadata_tags(cell: dict): # def create_notebook(source: str, dest: str, parameters: dict) -> None: # def replace_parameters(source: List[str], parameters: dict) -> List[str]: # def assignment_string(lhs, rhs): . Output only the next line.
notebook.create_notebook(
Given the following code snippet before the placeholder: <|code_start|> def __exit__(self, exc_type, exc_value, exc_tb): self.close() def limit_axes( self, x_min: Optional[float], x_max: Optional[float], y_min: Optional[float], y_max: Optional[float], ) -> None: """Update all plots to have the desired axes limits""" if x_min is None and x_max is None and y_min is None and y_max is None: return sides = None if x_min is not None or x_max is not None: if y_min is None and y_max is None: sides = "both" elif y_min is None and y_max is not None: sides = "min" elif y_min is not None and y_max is None: sides = "max" for fig in self.figures: for ax in fig.axes: ax.set_xlim(left=x_min, right=x_max) ax.set_ylim(bottom=y_min, top=y_max) if sides is not None: _autoscale(ax, axis="y", sides=sides) def save_pdf(self, file_name: str, title: str, overwrite: bool = False) -> None: """Create a PDF file containing one figure per page""" <|code_end|> , predict the next line using imports from the current file: import datetime import logging import math import matplotlib import matplotlib.pyplot as plt import numpy as np import numpy.typing as npt from abc import ABC from typing import Optional, Sequence, Tuple from matplotlib.backends.backend_pdf import PdfPages from metatlas.io import write_utils from metatlas.plots import utils and context including class names, function names, and sometimes code from other files: # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/plots/utils.py # BACKGROUND_COLORS = ["white", "lightyellow", "whitesmoke", "lavenderblush"] # def colors() -> Generator: # def subplot_dimensions(num: int) -> Tuple[int, int]: # def wrap_subplots(num: int, **kwargs) -> Tuple[matplotlib.figure.Figure, List[matplotlib.axes.Axes]]: # def is_in_range(a: List[float], start: float, stop: float) -> List[bool]: # def fill_under( # ax: matplotlib.axes.Axes, # x: List[float], # y: List[float], # between: Optional[Tuple[float, float]] = None, # **kwargs, # ) -> None: # def pdf_with_text(text: str, file_name: str, size: int = 24): . Output only the next line.
write_utils.check_existing_file(file_name, overwrite)
Based on the snippet: <|code_start|>"""Set of plots""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods logger = logging.getLogger(__name__) def restore_matplotlib_settings(func): """Stop function from permanently modifiying rcParams""" def wrapper(*args, **kwargs): original = matplotlib.rcParams out = func(*args, **kwargs) matplotlib.rcParams = original return out return wrapper class Plot(ABC): """A single plot""" def __init__(self, title: str, group_name: str): self.title = title self.group_name = group_name <|code_end|> , predict the immediate next line with the help of imports: import datetime import logging import math import matplotlib import matplotlib.pyplot as plt import numpy as np import numpy.typing as npt from abc import ABC from typing import Optional, Sequence, Tuple from matplotlib.backends.backend_pdf import PdfPages from metatlas.io import write_utils from metatlas.plots import utils and context (classes, functions, sometimes code) from other files: # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): # # Path: metatlas/plots/utils.py # BACKGROUND_COLORS = ["white", "lightyellow", "whitesmoke", "lavenderblush"] # def colors() -> Generator: # def subplot_dimensions(num: int) -> Tuple[int, int]: # def wrap_subplots(num: int, **kwargs) -> Tuple[matplotlib.figure.Figure, List[matplotlib.axes.Axes]]: # def is_in_range(a: List[float], start: float, stop: float) -> List[bool]: # def fill_under( # ax: matplotlib.axes.Axes, # x: List[float], # y: List[float], # between: Optional[Tuple[float, float]] = None, # **kwargs, # ) -> None: # def pdf_with_text(text: str, file_name: str, size: int = 24): . Output only the next line.
def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None:
Continue the code snippet: <|code_start|> self.ax.annotate(l, xy, ha='right', va='center', size = 8./(num_rows+.25)) # Y-scale label self.y_scale_coordinates = np.matmul(tso_transform, self.__make_y_scale_coordinates(is_subplot) )[:,0:2].transpose(0,2,1) for subplot_xy in self.y_scale_coordinates: for xy in subplot_xy: self.ax.annotate('1E%d'%int(self.intensity_scale), xy, ha='right', va='bottom', size = 8./(num_rows+.25), weight='bold') # Titles title_coordinates = np.matmul(tso_transform, self.__make_title_coordinates(is_subplot) )[:,0:2].transpose(0,2,1) for i,subplot_xy in enumerate(title_coordinates): if not isinstance(self.compound_eics[i], str): self.ax.annotate('\n'.join(wrap(self.compound_eics[i].file_name,48)), subplot_xy[0], ha='center', va='bottom', size = 8./(num_cols+.25), weight='bold') # Groups if self.group: group_label_coordinates = boxes = np.matmul(tso_transform, self.__make_group_label_coordinates(is_subplot) )[:,0:2].transpose(0,2,1) for i,subplot_xy in enumerate(group_label_coordinates): if isinstance(self.compound_eics[i], str): self.ax.annotate(self.compound_eics[i], subplot_xy[0], ha='center', va='center', size = 100./(num_cols+.25), weight='bold') <|code_end|> . Use current file imports: import logging import numpy as np from textwrap import wrap from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from matplotlib import collections as mc from scipy.interpolate import interp1d from six.moves import range from six.moves import zip from metatlas.io import write_utils and context (classes, functions, or code) from other files: # Path: metatlas/io/write_utils.py # def make_dir_for(file_path): # def check_existing_file(file_path, overwrite=False): # def export_dataframe(dataframe, file_path, description, overwrite=False, **kwargs): # def raise_on_diff(dataframe, file_path, description, **kwargs): # def export_dataframe_die_on_diff(dataframe, file_path, description, overwrite=False, **kwargs): . Output only the next line.
write_utils.check_existing_file(self.file_name, self.overwrite)
Continue the code snippet: <|code_start|> readonly_files[username].add(dirname) continue # Get a lock on the mzml file to prevent interference. try: fid = open(fname, 'r') fcntl.flock(fid, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: fid.close() msg = '%s already converting in another process\n' % fname sys.stderr.write(msg) sys.stderr.flush() continue # Convert to HDF and store the entry in the database. try: hdf5_file = fname.replace('mzML', 'h5') #Get Acquisition Time Here acquisition_time = get_acqtime_from_mzml(fname) mzml_to_hdf(fname, hdf5_file, True) os.chmod(hdf5_file, 0o660) description = info['experiment'] + ' ' + info['path'] ctime = os.stat(fname).st_ctime # Add this to the database unless it is already there try: runs = retrieve('lcmsrun', username='*', mzml_file=fname) except Exception: runs = list() if not len(runs): <|code_end|> . Use current file imports: import os import fcntl import pwd import re import shutil import sys import time import random import smtplib import traceback import time import argparse from collections import defaultdict from subprocess import check_output from datetime import datetime, time as dtime from metatlas.mzml_loader import VERSION_TIMESTAMP from metatlas.datastructures.metatlas_objects import LcmsRun, retrieve, store from metatlas.io.mzml_loader import mzml_to_hdf from metatlas.metatlas_objects import find_invalid_runs and context (classes, functions, or code) from other files: # Path: metatlas/datastructures/metatlas_objects.py # class LcmsRun(MetatlasObject): # """An LCMS run is the reference to a file prepared with liquid # chromatography and mass spectrometry. # # The msconvert program is used to convert raw data (centroided is prefered) # to mzML. # # Note: These objects are not intented to be created directly, but by putting # the files in /project/projectdirs/metatlas/raw_data/<username> or by # running `load_lcms_files()`. # """ # method = MetInstance(Method) # experiment = MetUnicode(help='The name of the experiment') # hdf5_file = MetUnicode(help='Path to the HDF5 file at NERSC') # mzml_file = MetUnicode(help='Path to the MZML file at NERSC') # acquisition_time = MetInt(help='Unix timestamp when data was acquired creation') # injection_volume = MetFloat() # injection_volume_units = MetEnum(('uL', 'nL'), 'uL') # pass_qc = MetBool(help= 'True/False for if the LCMS Run has passed a quality control assessment') # sample = MetInstance(Sample) # # def retrieve(object_type, **kwargs): # """Get objects from the Metatlas object database. # # This will automatically select only objects created by the current # user unless `username` is provided. Use `username='*'` to search # against all users. # # Parameters # ---------- # object_type: string # The type of object to search for (i.e. "Groups"). # **kwargs # Specific search queries (i.e. name="Sargasso"). # Use '%' for wildcard patterns (i.e. description='Hello%'). # If you want to match a '%' character, use '%%'. # # Returns # ------- # objects: list # List of Metatlas Objects meeting the criteria. Will return the # latest version of each object. # """ # workspace = Workspace.get_instance() # out = workspace.retrieve(object_type, **kwargs) # workspace.close_connection() # return out # # def store(objects, **kwargs): # """Store Metatlas objects in the database. # # Parameters # ---------- # objects: Metatlas object or list of Metatlas Objects # Object(s) to store in the database. # """ # workspace = Workspace.get_instance() # workspace.save_objects(objects, **kwargs) # workspace.close_connection() . Output only the next line.
run = LcmsRun(name=info['path'], description=description,
Predict the next line for this snippet: <|code_start|> os.makedirs(dname) try: shutil.copy(fname, pasteur_path) except IOError as e: readonly_files[username].add(dirname) continue # Get a lock on the mzml file to prevent interference. try: fid = open(fname, 'r') fcntl.flock(fid, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: fid.close() msg = '%s already converting in another process\n' % fname sys.stderr.write(msg) sys.stderr.flush() continue # Convert to HDF and store the entry in the database. try: hdf5_file = fname.replace('mzML', 'h5') #Get Acquisition Time Here acquisition_time = get_acqtime_from_mzml(fname) mzml_to_hdf(fname, hdf5_file, True) os.chmod(hdf5_file, 0o660) description = info['experiment'] + ' ' + info['path'] ctime = os.stat(fname).st_ctime # Add this to the database unless it is already there try: <|code_end|> with the help of current file imports: import os import fcntl import pwd import re import shutil import sys import time import random import smtplib import traceback import time import argparse from collections import defaultdict from subprocess import check_output from datetime import datetime, time as dtime from metatlas.mzml_loader import VERSION_TIMESTAMP from metatlas.datastructures.metatlas_objects import LcmsRun, retrieve, store from metatlas.io.mzml_loader import mzml_to_hdf from metatlas.metatlas_objects import find_invalid_runs and context from other files: # Path: metatlas/datastructures/metatlas_objects.py # class LcmsRun(MetatlasObject): # """An LCMS run is the reference to a file prepared with liquid # chromatography and mass spectrometry. # # The msconvert program is used to convert raw data (centroided is prefered) # to mzML. # # Note: These objects are not intented to be created directly, but by putting # the files in /project/projectdirs/metatlas/raw_data/<username> or by # running `load_lcms_files()`. # """ # method = MetInstance(Method) # experiment = MetUnicode(help='The name of the experiment') # hdf5_file = MetUnicode(help='Path to the HDF5 file at NERSC') # mzml_file = MetUnicode(help='Path to the MZML file at NERSC') # acquisition_time = MetInt(help='Unix timestamp when data was acquired creation') # injection_volume = MetFloat() # injection_volume_units = MetEnum(('uL', 'nL'), 'uL') # pass_qc = MetBool(help= 'True/False for if the LCMS Run has passed a quality control assessment') # sample = MetInstance(Sample) # # def retrieve(object_type, **kwargs): # """Get objects from the Metatlas object database. # # This will automatically select only objects created by the current # user unless `username` is provided. Use `username='*'` to search # against all users. # # Parameters # ---------- # object_type: string # The type of object to search for (i.e. "Groups"). # **kwargs # Specific search queries (i.e. name="Sargasso"). # Use '%' for wildcard patterns (i.e. description='Hello%'). # If you want to match a '%' character, use '%%'. # # Returns # ------- # objects: list # List of Metatlas Objects meeting the criteria. Will return the # latest version of each object. # """ # workspace = Workspace.get_instance() # out = workspace.retrieve(object_type, **kwargs) # workspace.close_connection() # return out # # def store(objects, **kwargs): # """Store Metatlas objects in the database. # # Parameters # ---------- # objects: Metatlas object or list of Metatlas Objects # Object(s) to store in the database. # """ # workspace = Workspace.get_instance() # workspace.save_objects(objects, **kwargs) # workspace.close_connection() , which may contain function names, class names, or code. Output only the next line.
runs = retrieve('lcmsrun', username='*', mzml_file=fname)