Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' class PickingTask(QtCore.QObject): """A class to handle an event picking/detection task. PickingTask objects are meant to be passed to a QThread instance that controls their execution. """ finished = QtCore.Signal() error = QtCore.Signal(str, str) def __init__(self, document, alg, threshold=None): super(PickingTask, self).__init__() self.document = document self.alg = alg self.threshold = threshold def run(self): <|code_end|> , generate the next line using the imports in this file: from PySide import QtCore from apasvo._version import _application_name from apasvo._version import _organization from apasvo.gui.models import eventcommands as commands import traceback import sys and context (functions, classes, or occasionally code) from other files: # Path: apasvo/_version.py # # Path: apasvo/_version.py # # Path: apasvo/gui/models/eventcommands.py # class AppendEvent(QtGui.QUndoCommand): # class DeleteEvents(QtGui.QUndoCommand): # class EditEvent(QtGui.QUndoCommand): # class ClearEventList(QtGui.QUndoCommand): # class SortEventList(QtGui.QUndoCommand): # class DetectEvents(QtGui.QUndoCommand): # class DetectStreamEvents(QtGui.QUndoCommand): # class OpenStream(QtGui.QUndoCommand): # class CloseTraces(QtGui.QUndoCommand): # def __init__(self, model, event): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, row_list): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, event, **kwargs): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, key, order): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, alg, **kwargs): # def undo(self): # def redo(self): # def id(self): # def __init__(self, trace_selector_widget, alg, trace_list=None, **kwargs): # def undo(self): # def redo(self): # def id(self): # def __init__(self, main_window, stream): # def undo(self): # def redo(self): # def id(self): # def __init__(self, main_window, trace_idx_list): # def undo(self): # def redo(self): # def id(self): . Output only the next line.
settings = QtCore.QSettings(_organization, _application_name)
Predict the next line for this snippet: <|code_start|> self.finished.emit() def abort(self): pass class PickingStreamTask(QtCore.QObject): """A class to handle an event picking/detection task. PickingTask objects are meant to be passed to a QThread instance that controls their execution. """ finished = QtCore.Signal() error = QtCore.Signal(str, str) def __init__(self, trace_selector_widget, alg, trace_list=None, threshold=None): super(PickingStreamTask, self).__init__() self.trace_selector = trace_selector_widget self.alg = alg self.trace_list = self.trace_selector.stream.traces if trace_list is None else trace_list self.threshold = threshold def run(self): try: settings = QtCore.QSettings(_organization, _application_name) takanami = int(settings.value('takanami_settings/takanami', False)) takanami_margin = float(settings.value('takanami_margin', 5.0)) <|code_end|> with the help of current file imports: from PySide import QtCore from apasvo._version import _application_name from apasvo._version import _organization from apasvo.gui.models import eventcommands as commands import traceback import sys and context from other files: # Path: apasvo/_version.py # # Path: apasvo/_version.py # # Path: apasvo/gui/models/eventcommands.py # class AppendEvent(QtGui.QUndoCommand): # class DeleteEvents(QtGui.QUndoCommand): # class EditEvent(QtGui.QUndoCommand): # class ClearEventList(QtGui.QUndoCommand): # class SortEventList(QtGui.QUndoCommand): # class DetectEvents(QtGui.QUndoCommand): # class DetectStreamEvents(QtGui.QUndoCommand): # class OpenStream(QtGui.QUndoCommand): # class CloseTraces(QtGui.QUndoCommand): # def __init__(self, model, event): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, row_list): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, event, **kwargs): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, key, order): # def undo(self): # def redo(self): # def id(self): # def __init__(self, model, alg, **kwargs): # def undo(self): # def redo(self): # def id(self): # def __init__(self, trace_selector_widget, alg, trace_list=None, **kwargs): # def undo(self): # def redo(self): # def id(self): # def __init__(self, main_window, stream): # def undo(self): # def redo(self): # def id(self): # def __init__(self, main_window, trace_idx_list): # def undo(self): # def redo(self): # def id(self): , which may contain function names, class names, or code. Output only the next line.
detect_command = commands.DetectStreamEvents(self.trace_selector,
Given snippet: <|code_start|> attribute = self.attributes[index.column()] data = None if attribute['type'] == 'event': data = self.record.events[index.row()].__getattribute__(attribute['attribute_name']) if attribute.get('attribute_type') == 'date': dateformat = attribute.get('dateformat') if dateformat is not None: data = data.strftime(dateformat) rep_format = attribute.get('format', '{}') return rep_format.format(data) elif role == QtCore.Qt.BackgroundRole: return self.calculateEventColor(index) else: return None def calculateEventColor(self, index): if index.isValid(): if self.color_key is not None: value = self.record.events[index.row()].__getattribute__(self.color_key) return self.color_map.get(value) return None def loadColorMap(self): settings = QtCore.QSettings(_organization, _application_name) self.color_map = {} # load color settings if "color_settings" in settings.childGroups(): settings.beginGroup("color_settings") for key in settings.childKeys(): if key == 'color_key': <|code_end|> , continue by predicting the next line. Consider current file imports: from PySide import QtCore from PySide import QtGui from apasvo.gui.views.settingsdialog import COLOR_KEYS from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_KEY from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_SCHEME from apasvo.picking import apasvotrace as rc from apasvo._version import _application_name from apasvo._version import _organization import obspy as op import eventcommands as commands and context: # Path: apasvo/gui/views/settingsdialog.py # COLOR_KEYS = ("method", "evaluation_mode", "evaluation_status") # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_KEY = "method" # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_SCHEME = ((rc.method_stalta, DEFAULT_STALTA_COLOR), # (rc.method_stalta_takanami, DEFAULT_STALTA_TAKANAMI_COLOR), # (rc.method_ampa, DEFAULT_AMPA_COLOR), # (rc.method_ampa_takanami, DEFAULT_AMPA_TAKANAMI_COLOR), # (rc.method_takanami, DEFAULT_TAKANAMI_COLOR), # (rc.method_other, DEFAULT_OTHER_COLOR)) # # Path: apasvo/picking/apasvotrace.py # ALLOWED_METHODS = ( # method_other, # method_takanami, # method_stalta, # method_stalta_takanami, # method_ampa, # method_ampa_takanami # ) # PHASE_VALUES = ( # "P", # "S", # "Other", # ) # DEFAULT_DTYPE = '=f8' # Set the default datatype as 8 bits floating point, native ordered # DEFAULT_DELTA = 0.02 # def generate_csv(records, fout, delimiter=',', lineterminator='\n'): # def __init__(self, # trace, # time, # name='', # comments='', # method=method_other, # phase_hint=None, # polarity='undecidable', # aic=None, # n0_aic=None, # *args, **kwargs): # def cf_value(self): # def _samples_to_seconds(self, value): # def _seconds_to_samples(self, value): # def __setattr__(self, key, value): # def __getattribute__(self, item): # def plot_aic(self, show_envelope=True, num=None, **kwargs): # def __init__(self, # data=None, # header=None, # label='', # description='', # filename='', # normalize=True, # use_filtered=False, # **kwargs): # def fs(self): # def delta(self): # def signal(self): # def starttime(self): # def endtime(self): # def short_name(self): # def name(self): # def detect(self, alg, threshold=None, peak_window=1.0, # takanami=False, takanami_margin=5.0, action='append', debug=False, **kwargs): # def sort_events(self, key='time', reverse=False): # def refine_events(self, events, t_start=None, t_end=None, takanami_margin=5.0): # def bandpass_filter(self, freqmin, freqmax, *args, **kwargs): # def save_cf(self, fname, fmt=rawfile.format_text, # dtype=rawfile.datatype_float64, # byteorder=rawfile.byteorder_native): # def plot_signal(self, t_start=0.0, t_end=np.inf, show_events=True, # show_x=True, show_cf=True, show_specgram=True, # show_envelope=True, threshold=None, num=None, **kwargs): # def add_event_from_copy(self, event): # def _detect(parameters): # def __init__(self, traces, description='', filename='', **kwargs): # def detect(self, alg, trace_list=None, allow_multiprocessing=True, **kwargs): # def export_picks(self, filename, trace_list=None, format="NLLOC_OBS", debug=False, **kwargs): # def read(filename, # format=None, # dtype='float64', # byteorder='native', # description='', # normalize=True, # *args, **kwargs): # class ApasvoEvent(Pick): # class ApasvoTrace(op.Trace): # class ApasvoStream(op.Stream): # # Path: apasvo/_version.py # # Path: apasvo/_version.py which might include code, classes, or functions. Output only the next line.
self.color_key = COLOR_KEYS[int(settings.value(key))]
Using the snippet: <|code_start|> if dateformat is not None: data = data.strftime(dateformat) rep_format = attribute.get('format', '{}') return rep_format.format(data) elif role == QtCore.Qt.BackgroundRole: return self.calculateEventColor(index) else: return None def calculateEventColor(self, index): if index.isValid(): if self.color_key is not None: value = self.record.events[index.row()].__getattribute__(self.color_key) return self.color_map.get(value) return None def loadColorMap(self): settings = QtCore.QSettings(_organization, _application_name) self.color_map = {} # load color settings if "color_settings" in settings.childGroups(): settings.beginGroup("color_settings") for key in settings.childKeys(): if key == 'color_key': self.color_key = COLOR_KEYS[int(settings.value(key))] else: self.color_map[key] = QtGui.QColor(settings.value(key)) settings.endGroup() # load default color scheme otherwise else: <|code_end|> , determine the next line of code. You have imports: from PySide import QtCore from PySide import QtGui from apasvo.gui.views.settingsdialog import COLOR_KEYS from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_KEY from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_SCHEME from apasvo.picking import apasvotrace as rc from apasvo._version import _application_name from apasvo._version import _organization import obspy as op import eventcommands as commands and context (class names, function names, or code) available: # Path: apasvo/gui/views/settingsdialog.py # COLOR_KEYS = ("method", "evaluation_mode", "evaluation_status") # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_KEY = "method" # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_SCHEME = ((rc.method_stalta, DEFAULT_STALTA_COLOR), # (rc.method_stalta_takanami, DEFAULT_STALTA_TAKANAMI_COLOR), # (rc.method_ampa, DEFAULT_AMPA_COLOR), # (rc.method_ampa_takanami, DEFAULT_AMPA_TAKANAMI_COLOR), # (rc.method_takanami, DEFAULT_TAKANAMI_COLOR), # (rc.method_other, DEFAULT_OTHER_COLOR)) # # Path: apasvo/picking/apasvotrace.py # ALLOWED_METHODS = ( # method_other, # method_takanami, # method_stalta, # method_stalta_takanami, # method_ampa, # method_ampa_takanami # ) # PHASE_VALUES = ( # "P", # "S", # "Other", # ) # DEFAULT_DTYPE = '=f8' # Set the default datatype as 8 bits floating point, native ordered # DEFAULT_DELTA = 0.02 # def generate_csv(records, fout, delimiter=',', lineterminator='\n'): # def __init__(self, # trace, # time, # name='', # comments='', # method=method_other, # phase_hint=None, # polarity='undecidable', # aic=None, # n0_aic=None, # *args, **kwargs): # def cf_value(self): # def _samples_to_seconds(self, value): # def _seconds_to_samples(self, value): # def __setattr__(self, key, value): # def __getattribute__(self, item): # def plot_aic(self, show_envelope=True, num=None, **kwargs): # def __init__(self, # data=None, # header=None, # label='', # description='', # filename='', # normalize=True, # use_filtered=False, # **kwargs): # def fs(self): # def delta(self): # def signal(self): # def starttime(self): # def endtime(self): # def short_name(self): # def name(self): # def detect(self, alg, threshold=None, peak_window=1.0, # takanami=False, takanami_margin=5.0, action='append', debug=False, **kwargs): # def sort_events(self, key='time', reverse=False): # def refine_events(self, events, t_start=None, t_end=None, takanami_margin=5.0): # def bandpass_filter(self, freqmin, freqmax, *args, **kwargs): # def save_cf(self, fname, fmt=rawfile.format_text, # dtype=rawfile.datatype_float64, # byteorder=rawfile.byteorder_native): # def plot_signal(self, t_start=0.0, t_end=np.inf, show_events=True, # show_x=True, show_cf=True, show_specgram=True, # show_envelope=True, threshold=None, num=None, **kwargs): # def add_event_from_copy(self, event): # def _detect(parameters): # def __init__(self, traces, description='', filename='', **kwargs): # def detect(self, alg, trace_list=None, allow_multiprocessing=True, **kwargs): # def export_picks(self, filename, trace_list=None, format="NLLOC_OBS", debug=False, **kwargs): # def read(filename, # format=None, # dtype='float64', # byteorder='native', # description='', # normalize=True, # *args, **kwargs): # class ApasvoEvent(Pick): # class ApasvoTrace(op.Trace): # class ApasvoStream(op.Stream): # # Path: apasvo/_version.py # # Path: apasvo/_version.py . Output only the next line.
self.color_key = DEFAULT_COLOR_KEY
Predict the next line for this snippet: <|code_start|> data = data.strftime(dateformat) rep_format = attribute.get('format', '{}') return rep_format.format(data) elif role == QtCore.Qt.BackgroundRole: return self.calculateEventColor(index) else: return None def calculateEventColor(self, index): if index.isValid(): if self.color_key is not None: value = self.record.events[index.row()].__getattribute__(self.color_key) return self.color_map.get(value) return None def loadColorMap(self): settings = QtCore.QSettings(_organization, _application_name) self.color_map = {} # load color settings if "color_settings" in settings.childGroups(): settings.beginGroup("color_settings") for key in settings.childKeys(): if key == 'color_key': self.color_key = COLOR_KEYS[int(settings.value(key))] else: self.color_map[key] = QtGui.QColor(settings.value(key)) settings.endGroup() # load default color scheme otherwise else: self.color_key = DEFAULT_COLOR_KEY <|code_end|> with the help of current file imports: from PySide import QtCore from PySide import QtGui from apasvo.gui.views.settingsdialog import COLOR_KEYS from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_KEY from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_SCHEME from apasvo.picking import apasvotrace as rc from apasvo._version import _application_name from apasvo._version import _organization import obspy as op import eventcommands as commands and context from other files: # Path: apasvo/gui/views/settingsdialog.py # COLOR_KEYS = ("method", "evaluation_mode", "evaluation_status") # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_KEY = "method" # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_SCHEME = ((rc.method_stalta, DEFAULT_STALTA_COLOR), # (rc.method_stalta_takanami, DEFAULT_STALTA_TAKANAMI_COLOR), # (rc.method_ampa, DEFAULT_AMPA_COLOR), # (rc.method_ampa_takanami, DEFAULT_AMPA_TAKANAMI_COLOR), # (rc.method_takanami, DEFAULT_TAKANAMI_COLOR), # (rc.method_other, DEFAULT_OTHER_COLOR)) # # Path: apasvo/picking/apasvotrace.py # ALLOWED_METHODS = ( # method_other, # method_takanami, # method_stalta, # method_stalta_takanami, # method_ampa, # method_ampa_takanami # ) # PHASE_VALUES = ( # "P", # "S", # "Other", # ) # DEFAULT_DTYPE = '=f8' # Set the default datatype as 8 bits floating point, native ordered # DEFAULT_DELTA = 0.02 # def generate_csv(records, fout, delimiter=',', lineterminator='\n'): # def __init__(self, # trace, # time, # name='', # comments='', # method=method_other, # phase_hint=None, # polarity='undecidable', # aic=None, # n0_aic=None, # *args, **kwargs): # def cf_value(self): # def _samples_to_seconds(self, value): # def _seconds_to_samples(self, value): # def __setattr__(self, key, value): # def __getattribute__(self, item): # def plot_aic(self, show_envelope=True, num=None, **kwargs): # def __init__(self, # data=None, # header=None, # label='', # description='', # filename='', # normalize=True, # use_filtered=False, # **kwargs): # def fs(self): # def delta(self): # def signal(self): # def starttime(self): # def endtime(self): # def short_name(self): # def name(self): # def detect(self, alg, threshold=None, peak_window=1.0, # takanami=False, takanami_margin=5.0, action='append', debug=False, **kwargs): # def sort_events(self, key='time', reverse=False): # def refine_events(self, events, t_start=None, t_end=None, takanami_margin=5.0): # def bandpass_filter(self, freqmin, freqmax, *args, **kwargs): # def save_cf(self, fname, fmt=rawfile.format_text, # dtype=rawfile.datatype_float64, # byteorder=rawfile.byteorder_native): # def plot_signal(self, t_start=0.0, t_end=np.inf, show_events=True, # show_x=True, show_cf=True, show_specgram=True, # show_envelope=True, threshold=None, num=None, **kwargs): # def add_event_from_copy(self, event): # def _detect(parameters): # def __init__(self, traces, description='', filename='', **kwargs): # def detect(self, alg, trace_list=None, allow_multiprocessing=True, **kwargs): # def export_picks(self, filename, trace_list=None, format="NLLOC_OBS", debug=False, **kwargs): # def read(filename, # format=None, # dtype='float64', # byteorder='native', # description='', # normalize=True, # *args, **kwargs): # class ApasvoEvent(Pick): # class ApasvoTrace(op.Trace): # class ApasvoStream(op.Stream): # # Path: apasvo/_version.py # # Path: apasvo/_version.py , which may contain function names, class names, or code. Output only the next line.
for key, color in DEFAULT_COLOR_SCHEME:
Given the code snippet: <|code_start|>@copyright: Copyright 2013-2014, Jose Emilio Romero Lopez. @license: GPL @contact: jemromerol@gmail.com This file is part of APASVO. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' class EventListModel(QtCore.QAbstractTableModel): """A Table Model class to handle a list of seismic events. """ emptyList = QtCore.Signal(bool) <|code_end|> , generate the next line using the imports in this file: from PySide import QtCore from PySide import QtGui from apasvo.gui.views.settingsdialog import COLOR_KEYS from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_KEY from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_SCHEME from apasvo.picking import apasvotrace as rc from apasvo._version import _application_name from apasvo._version import _organization import obspy as op import eventcommands as commands and context (functions, classes, or occasionally code) from other files: # Path: apasvo/gui/views/settingsdialog.py # COLOR_KEYS = ("method", "evaluation_mode", "evaluation_status") # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_KEY = "method" # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_SCHEME = ((rc.method_stalta, DEFAULT_STALTA_COLOR), # (rc.method_stalta_takanami, DEFAULT_STALTA_TAKANAMI_COLOR), # (rc.method_ampa, DEFAULT_AMPA_COLOR), # (rc.method_ampa_takanami, DEFAULT_AMPA_TAKANAMI_COLOR), # (rc.method_takanami, DEFAULT_TAKANAMI_COLOR), # (rc.method_other, DEFAULT_OTHER_COLOR)) # # Path: apasvo/picking/apasvotrace.py # ALLOWED_METHODS = ( # method_other, # method_takanami, # method_stalta, # method_stalta_takanami, # method_ampa, # method_ampa_takanami # ) # PHASE_VALUES = ( # "P", # "S", # "Other", # ) # DEFAULT_DTYPE = '=f8' # Set the default datatype as 8 bits floating point, native ordered # DEFAULT_DELTA = 0.02 # def generate_csv(records, fout, delimiter=',', lineterminator='\n'): # def __init__(self, # trace, # time, # name='', # comments='', # method=method_other, # phase_hint=None, # polarity='undecidable', # aic=None, # n0_aic=None, # *args, **kwargs): # def cf_value(self): # def _samples_to_seconds(self, value): # def _seconds_to_samples(self, value): # def __setattr__(self, key, value): # def __getattribute__(self, item): # def plot_aic(self, show_envelope=True, num=None, **kwargs): # def __init__(self, # data=None, # header=None, # label='', # description='', # filename='', # normalize=True, # use_filtered=False, # **kwargs): # def fs(self): # def delta(self): # def signal(self): # def starttime(self): # def endtime(self): # def short_name(self): # def name(self): # def detect(self, alg, threshold=None, peak_window=1.0, # takanami=False, takanami_margin=5.0, action='append', debug=False, **kwargs): # def sort_events(self, key='time', reverse=False): # def refine_events(self, events, t_start=None, t_end=None, takanami_margin=5.0): # def bandpass_filter(self, freqmin, freqmax, *args, **kwargs): # def save_cf(self, fname, fmt=rawfile.format_text, # dtype=rawfile.datatype_float64, # byteorder=rawfile.byteorder_native): # def plot_signal(self, t_start=0.0, t_end=np.inf, show_events=True, # show_x=True, show_cf=True, show_specgram=True, # show_envelope=True, threshold=None, num=None, **kwargs): # def add_event_from_copy(self, event): # def _detect(parameters): # def __init__(self, traces, description='', filename='', **kwargs): # def detect(self, alg, trace_list=None, allow_multiprocessing=True, **kwargs): # def export_picks(self, filename, trace_list=None, format="NLLOC_OBS", debug=False, **kwargs): # def read(filename, # format=None, # dtype='float64', # byteorder='native', # description='', # normalize=True, # *args, **kwargs): # class ApasvoEvent(Pick): # class ApasvoTrace(op.Trace): # class ApasvoStream(op.Stream): # # Path: apasvo/_version.py # # Path: apasvo/_version.py . Output only the next line.
eventCreated = QtCore.Signal(rc.ApasvoEvent)
Given the code snippet: <|code_start|> def columnCount(self, parent=QtCore.QModelIndex()): return len(self.attributes) def data(self, index, role=QtCore.Qt.DisplayRole): if not index.isValid(): return None elif role == QtCore.Qt.DisplayRole: attribute = self.attributes[index.column()] data = None if attribute['type'] == 'event': data = self.record.events[index.row()].__getattribute__(attribute['attribute_name']) if attribute.get('attribute_type') == 'date': dateformat = attribute.get('dateformat') if dateformat is not None: data = data.strftime(dateformat) rep_format = attribute.get('format', '{}') return rep_format.format(data) elif role == QtCore.Qt.BackgroundRole: return self.calculateEventColor(index) else: return None def calculateEventColor(self, index): if index.isValid(): if self.color_key is not None: value = self.record.events[index.row()].__getattribute__(self.color_key) return self.color_map.get(value) return None def loadColorMap(self): <|code_end|> , generate the next line using the imports in this file: from PySide import QtCore from PySide import QtGui from apasvo.gui.views.settingsdialog import COLOR_KEYS from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_KEY from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_SCHEME from apasvo.picking import apasvotrace as rc from apasvo._version import _application_name from apasvo._version import _organization import obspy as op import eventcommands as commands and context (functions, classes, or occasionally code) from other files: # Path: apasvo/gui/views/settingsdialog.py # COLOR_KEYS = ("method", "evaluation_mode", "evaluation_status") # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_KEY = "method" # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_SCHEME = ((rc.method_stalta, DEFAULT_STALTA_COLOR), # (rc.method_stalta_takanami, DEFAULT_STALTA_TAKANAMI_COLOR), # (rc.method_ampa, DEFAULT_AMPA_COLOR), # (rc.method_ampa_takanami, DEFAULT_AMPA_TAKANAMI_COLOR), # (rc.method_takanami, DEFAULT_TAKANAMI_COLOR), # (rc.method_other, DEFAULT_OTHER_COLOR)) # # Path: apasvo/picking/apasvotrace.py # ALLOWED_METHODS = ( # method_other, # method_takanami, # method_stalta, # method_stalta_takanami, # method_ampa, # method_ampa_takanami # ) # PHASE_VALUES = ( # "P", # "S", # "Other", # ) # DEFAULT_DTYPE = '=f8' # Set the default datatype as 8 bits floating point, native ordered # DEFAULT_DELTA = 0.02 # def generate_csv(records, fout, delimiter=',', lineterminator='\n'): # def __init__(self, # trace, # time, # name='', # comments='', # method=method_other, # phase_hint=None, # polarity='undecidable', # aic=None, # n0_aic=None, # *args, **kwargs): # def cf_value(self): # def _samples_to_seconds(self, value): # def _seconds_to_samples(self, value): # def __setattr__(self, key, value): # def __getattribute__(self, item): # def plot_aic(self, show_envelope=True, num=None, **kwargs): # def __init__(self, # data=None, # header=None, # label='', # description='', # filename='', # normalize=True, # use_filtered=False, # **kwargs): # def fs(self): # def delta(self): # def signal(self): # def starttime(self): # def endtime(self): # def short_name(self): # def name(self): # def detect(self, alg, threshold=None, peak_window=1.0, # takanami=False, takanami_margin=5.0, action='append', debug=False, **kwargs): # def sort_events(self, key='time', reverse=False): # def refine_events(self, events, t_start=None, t_end=None, takanami_margin=5.0): # def bandpass_filter(self, freqmin, freqmax, *args, **kwargs): # def save_cf(self, fname, fmt=rawfile.format_text, # dtype=rawfile.datatype_float64, # byteorder=rawfile.byteorder_native): # def plot_signal(self, t_start=0.0, t_end=np.inf, show_events=True, # show_x=True, show_cf=True, show_specgram=True, # show_envelope=True, threshold=None, num=None, **kwargs): # def add_event_from_copy(self, event): # def _detect(parameters): # def __init__(self, traces, description='', filename='', **kwargs): # def detect(self, alg, trace_list=None, allow_multiprocessing=True, **kwargs): # def export_picks(self, filename, trace_list=None, format="NLLOC_OBS", debug=False, **kwargs): # def read(filename, # format=None, # dtype='float64', # byteorder='native', # description='', # normalize=True, # *args, **kwargs): # class ApasvoEvent(Pick): # class ApasvoTrace(op.Trace): # class ApasvoStream(op.Stream): # # Path: apasvo/_version.py # # Path: apasvo/_version.py . Output only the next line.
settings = QtCore.QSettings(_organization, _application_name)
Predict the next line after this snippet: <|code_start|> def columnCount(self, parent=QtCore.QModelIndex()): return len(self.attributes) def data(self, index, role=QtCore.Qt.DisplayRole): if not index.isValid(): return None elif role == QtCore.Qt.DisplayRole: attribute = self.attributes[index.column()] data = None if attribute['type'] == 'event': data = self.record.events[index.row()].__getattribute__(attribute['attribute_name']) if attribute.get('attribute_type') == 'date': dateformat = attribute.get('dateformat') if dateformat is not None: data = data.strftime(dateformat) rep_format = attribute.get('format', '{}') return rep_format.format(data) elif role == QtCore.Qt.BackgroundRole: return self.calculateEventColor(index) else: return None def calculateEventColor(self, index): if index.isValid(): if self.color_key is not None: value = self.record.events[index.row()].__getattribute__(self.color_key) return self.color_map.get(value) return None def loadColorMap(self): <|code_end|> using the current file's imports: from PySide import QtCore from PySide import QtGui from apasvo.gui.views.settingsdialog import COLOR_KEYS from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_KEY from apasvo.gui.views.settingsdialog import DEFAULT_COLOR_SCHEME from apasvo.picking import apasvotrace as rc from apasvo._version import _application_name from apasvo._version import _organization import obspy as op import eventcommands as commands and any relevant context from other files: # Path: apasvo/gui/views/settingsdialog.py # COLOR_KEYS = ("method", "evaluation_mode", "evaluation_status") # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_KEY = "method" # # Path: apasvo/gui/views/settingsdialog.py # DEFAULT_COLOR_SCHEME = ((rc.method_stalta, DEFAULT_STALTA_COLOR), # (rc.method_stalta_takanami, DEFAULT_STALTA_TAKANAMI_COLOR), # (rc.method_ampa, DEFAULT_AMPA_COLOR), # (rc.method_ampa_takanami, DEFAULT_AMPA_TAKANAMI_COLOR), # (rc.method_takanami, DEFAULT_TAKANAMI_COLOR), # (rc.method_other, DEFAULT_OTHER_COLOR)) # # Path: apasvo/picking/apasvotrace.py # ALLOWED_METHODS = ( # method_other, # method_takanami, # method_stalta, # method_stalta_takanami, # method_ampa, # method_ampa_takanami # ) # PHASE_VALUES = ( # "P", # "S", # "Other", # ) # DEFAULT_DTYPE = '=f8' # Set the default datatype as 8 bits floating point, native ordered # DEFAULT_DELTA = 0.02 # def generate_csv(records, fout, delimiter=',', lineterminator='\n'): # def __init__(self, # trace, # time, # name='', # comments='', # method=method_other, # phase_hint=None, # polarity='undecidable', # aic=None, # n0_aic=None, # *args, **kwargs): # def cf_value(self): # def _samples_to_seconds(self, value): # def _seconds_to_samples(self, value): # def __setattr__(self, key, value): # def __getattribute__(self, item): # def plot_aic(self, show_envelope=True, num=None, **kwargs): # def __init__(self, # data=None, # header=None, # label='', # description='', # filename='', # normalize=True, # use_filtered=False, # **kwargs): # def fs(self): # def delta(self): # def signal(self): # def starttime(self): # def endtime(self): # def short_name(self): # def name(self): # def detect(self, alg, threshold=None, peak_window=1.0, # takanami=False, takanami_margin=5.0, action='append', debug=False, **kwargs): # def sort_events(self, key='time', reverse=False): # def refine_events(self, events, t_start=None, t_end=None, takanami_margin=5.0): # def bandpass_filter(self, freqmin, freqmax, *args, **kwargs): # def save_cf(self, fname, fmt=rawfile.format_text, # dtype=rawfile.datatype_float64, # byteorder=rawfile.byteorder_native): # def plot_signal(self, t_start=0.0, t_end=np.inf, show_events=True, # show_x=True, show_cf=True, show_specgram=True, # show_envelope=True, threshold=None, num=None, **kwargs): # def add_event_from_copy(self, event): # def _detect(parameters): # def __init__(self, traces, description='', filename='', **kwargs): # def detect(self, alg, trace_list=None, allow_multiprocessing=True, **kwargs): # def export_picks(self, filename, trace_list=None, format="NLLOC_OBS", debug=False, **kwargs): # def read(filename, # format=None, # dtype='float64', # byteorder='native', # description='', # normalize=True, # *args, **kwargs): # class ApasvoEvent(Pick): # class ApasvoTrace(op.Trace): # class ApasvoStream(op.Stream): # # Path: apasvo/_version.py # # Path: apasvo/_version.py . Output only the next line.
settings = QtCore.QSettings(_organization, _application_name)
Given the code snippet: <|code_start|> This file is part of APASVO. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' class Check_utils_plotting_reduce_data(unittest.TestCase): xdata = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ydata = [5, 0, -5, 0, 1, 2, 0, -1, -2, 5, 5] width = 3 xmin, xmax = 1, 10 xreduced = [1, 2, 4, 5, 7, 8, 9, 10] yreduced = [0, -5, 1, 2, -1, -2, 5, 5] def test_reduce_data_returns_correct_results(self): <|code_end|> , generate the next line using the imports in this file: import unittest import numpy as np from apasvo.utils import plotting and context (functions, classes, or occasionally code) from other files: # Path: apasvo/utils/plotting.py # SPECGRAM_WINDOWS = ("boxcar", "hamming", "hann", "bartlett", # 'blackman', "blackmanharris") # SPECGRAM_WINDOWS_NAMES = ("Rectangular", "Hamming", "Hann", "Bartlett", # "Blackman", "Blackman-Harris") # def plot_specgram(ax, data, fs, nfft=256, noverlap=128, window='hann', # cmap='jet', interpolation='bilinear', rasterized=True): # def reduce_data(x, y, width, xmin=0, xmax=None): # def adjust_axes_height(ax, max_value=None, min_value=None, margin=0.1): . Output only the next line.
xres, yres = plotting.reduce_data(self.xdata, self.ydata, self.width,
Continue the code snippet: <|code_start|> # Analytic signal y0 = np.sqrt((xa ** 2) + (xao ** 2)) # Fix a threshold to modify the energies in the channels thr = prctile(y0, noise_thr) # Here we modify the amplitudes of the analytic signal. The amplitudes # below the threshold are set to 1. the amplitudes above the threshold # are set to the number of times they are higher than the threshold z0 = (y0 / thr) * (y0 > thr) + (y0 <= thr) # In the variable z we save the analytic signals (modified by the # threshold processing) in a matrix structure. Each column corresponds # to one frequency channel z[i, :] = z0 # We sum the contribution of all the frequency channels in a single signal # Then we apply logarithm ztot = np.sum(z, 0) lztot = np.log10(ztot) - np.min(np.log10(ztot)) + 1e-2 # This total signal is passed through a non-linear filtering based # on a set of filters of different length. This is completely configurable Ztot = np.zeros((len(L), len(x))) for i in xrange(len(L)): l = int(L[i] * fs) B = np.zeros(2 * l) B[0:l] = range(1, l + 1) B[l:2 * l] = L_coef * (np.arange(1, l + 1) - (l + 1)) B = B / np.sum(np.abs(B)) Zt = signal.fftconvolve(lztot, B)[:len(x)] # Same as signal.lfilter(B, 1, lztot) Zt = Zt * (Zt > 0) Ztot[i, :-l] = np.roll(Zt, -l)[:-l] ZTOT = np.prod(Ztot, 0)[:-(np.max(L) * fs)] ZTOT = U + np.log10(np.abs(ZTOT) + (10 ** -U)) <|code_end|> . Use current file imports: import numpy as np import collections from scipy import signal from apasvo.picking import findpeaks and context (classes, functions, or code) from other files: # Path: apasvo/picking/findpeaks.py # def find_peaks(x, threshold=None, order=1): . Output only the next line.
event_t = findpeaks.find_peaks(ZTOT, threshold, order=peak_window * fs)
Continue the code snippet: <|code_start|> lta = min(len(x), lta_length * fs + 1) peak_window = int(peak_window * fs / 2.) x_norm = np.abs(x - np.mean(x)) cf = np.zeros(len(x)) if len(cf) > 0: if method == 'strides': sta_win = stride_tricks.as_strided(np.concatenate((x_norm, np.zeros(sta))), shape=(len(x), sta), strides=(1 * x_norm.dtype.itemsize, 1 * x_norm.dtype.itemsize)) lta_win = stride_tricks.as_strided(np.concatenate((x_norm, np.zeros(lta))), shape=(len(x), lta), strides=(1 * x_norm.dtype.itemsize, 1 * x_norm.dtype.itemsize)) sta_win_len = np.concatenate((np.ones(len(x) - sta) * sta, np.arange(sta, 0, -1))) lta_win_len = np.concatenate((np.ones(len(x) - lta) * lta, np.arange(lta, 0, -1))) cf = (sta_win.sum(axis=1) / sta_win_len) / (lta_win.sum(axis=1) / lta_win_len) elif method == 'convolution': sta_win = signal.fftconvolve(np.ones(sta), x_norm)[sta - 1:] lta_win = signal.fftconvolve(np.ones(lta), x_norm)[lta - 1:] sta_win_len = np.concatenate((np.ones(len(x) - sta) * sta, np.arange(sta, 0, -1))) lta_win_len = np.concatenate((np.ones(len(x) - lta) * lta, np.arange(lta, 0, -1))) cf = (sta_win / sta_win_len) / (lta_win / lta_win_len) elif method == 'iterative': for i in xrange(len(x)): cf[i] = np.mean(x_norm[i:i + sta]) / np.mean(x_norm[i:i + lta]) <|code_end|> . Use current file imports: import numpy as np from apasvo.picking import findpeaks from numpy.lib import stride_tricks from scipy import signal and context (classes, functions, or code) from other files: # Path: apasvo/picking/findpeaks.py # def find_peaks(x, threshold=None, order=1): . Output only the next line.
event_t = findpeaks.find_peaks(cf, threshold, order=peak_window * fs)
Predict the next line after this snippet: <|code_start|> but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' FORMATS = (rawfile.format_binary, rawfile.format_text) DEFAULT_FORMAT = 'Binary' FORMATS_LABELS = ('Binary', 'Text') DTYPES = (rawfile.datatype_int16, rawfile.datatype_int32, rawfile.datatype_int64, rawfile.datatype_float16, rawfile.datatype_float32, rawfile.datatype_float64, ) DTYPES_LABELS = ('16 bits, PCM', '32 bits, PCM', '64 bits, PCM', '16 bits, float', '32 bits, float', '64 bits, float', ) BYTEORDERS = (rawfile.byteorder_little_endian, rawfile.byteorder_big_endian) BYTEORDERS_LABELS = ('Little Endian (Intel)', 'Big Endian (Motorola)') <|code_end|> using the current file's imports: from PySide import QtGui from apasvo.gui.views.generated import ui_savedialog from apasvo.utils import futils from apasvo.utils.formats import rawfile and any relevant context from other files: # Path: apasvo/gui/views/generated/ui_savedialog.py # class Ui_SaveDialog(object): # def setupUi(self, SaveDialog): # def retranslateUi(self, SaveDialog): # # Path: apasvo/utils/futils.py # def istextfile(filename, blocksize=512): # def is_little_endian(): # def read_in_chunks(file_object, chunk_size=1024): # def read_txt_in_chunks(file_object, n=1024, comments='#'): # def getSize(f): # def get_delimiter(fileobject, lines=16): # def get_sample_rate(filename, max_header_lines=64, comments='#'): # def copytree(src, dst, symlinks=False, ignore=None): # # Path: apasvo/utils/formats/rawfile.py # class RawFile(object): # class BinFile(RawFile): # class TextFile(RawFile): # def __init__(self): # def read(self): # def read_in_blocks(self, block_size): # def write(self, array): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def get_file_handler(filename, fmt='', dtype='float64', byteorder='native', **kwargs): . Output only the next line.
class SaveDialog(QtGui.QDialog, ui_savedialog.Ui_SaveDialog):
Given the code snippet: <|code_start|> signal, i.e.: Format: Binary or text format. Data-type: PCM 16, PCM 32, PCM 64, Float16, Float32 or Float64, Endianness: Little-endian or big-endian. Attributes: fmt: Default file format. Available values are 'binary' and 'text'. Default: 'binary'. dtype: Default datatype. Available values are 'int16', 'int32', 'int64', 'float16', 'float32' and 'float64'. Default: 'float64'. byteorder: Default endianness. Available values are 'little-endian', 'big-endian' and 'native'. Default: 'native'. """ def __init__(self, parent, fmt=None, dtype='float64', byteorder='native'): fmt = fmt.title() if fmt is not None else DEFAULT_FORMAT super(SaveDialog, self).__init__(parent) self.setupUi(self) self.FileFormatComboBox.currentIndexChanged.connect(self.on_format_change) # init comboboxes self.FileFormatComboBox.addItems(FORMATS_LABELS) self.DataTypeComboBox.addItems(DTYPES_LABELS) self.ByteOrderComboBox.addItems(BYTEORDERS_LABELS) # Set defaults self.FileFormatComboBox.setCurrentIndex(FORMATS_LABELS.index(fmt)) self.DataTypeComboBox.setCurrentIndex(DTYPES.index(dtype)) # Detect endianness if 'native' byteorder is selected if byteorder == rawfile.byteorder_native: <|code_end|> , generate the next line using the imports in this file: from PySide import QtGui from apasvo.gui.views.generated import ui_savedialog from apasvo.utils import futils from apasvo.utils.formats import rawfile and context (functions, classes, or occasionally code) from other files: # Path: apasvo/gui/views/generated/ui_savedialog.py # class Ui_SaveDialog(object): # def setupUi(self, SaveDialog): # def retranslateUi(self, SaveDialog): # # Path: apasvo/utils/futils.py # def istextfile(filename, blocksize=512): # def is_little_endian(): # def read_in_chunks(file_object, chunk_size=1024): # def read_txt_in_chunks(file_object, n=1024, comments='#'): # def getSize(f): # def get_delimiter(fileobject, lines=16): # def get_sample_rate(filename, max_header_lines=64, comments='#'): # def copytree(src, dst, symlinks=False, ignore=None): # # Path: apasvo/utils/formats/rawfile.py # class RawFile(object): # class BinFile(RawFile): # class TextFile(RawFile): # def __init__(self): # def read(self): # def read_in_blocks(self, block_size): # def write(self, array): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def get_file_handler(filename, fmt='', dtype='float64', byteorder='native', **kwargs): . Output only the next line.
if futils.is_little_endian():
Given the following code snippet before the placeholder: <|code_start|># encoding: utf-8 ''' @author: Jose Emilio Romero Lopez @copyright: Copyright 2013-2014, Jose Emilio Romero Lopez. @license: GPL @contact: jemromerol@gmail.com This file is part of APASVO. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' <|code_end|> , predict the next line using imports from the current file: from PySide import QtGui from apasvo.gui.views.generated import ui_savedialog from apasvo.utils import futils from apasvo.utils.formats import rawfile and context including class names, function names, and sometimes code from other files: # Path: apasvo/gui/views/generated/ui_savedialog.py # class Ui_SaveDialog(object): # def setupUi(self, SaveDialog): # def retranslateUi(self, SaveDialog): # # Path: apasvo/utils/futils.py # def istextfile(filename, blocksize=512): # def is_little_endian(): # def read_in_chunks(file_object, chunk_size=1024): # def read_txt_in_chunks(file_object, n=1024, comments='#'): # def getSize(f): # def get_delimiter(fileobject, lines=16): # def get_sample_rate(filename, max_header_lines=64, comments='#'): # def copytree(src, dst, symlinks=False, ignore=None): # # Path: apasvo/utils/formats/rawfile.py # class RawFile(object): # class BinFile(RawFile): # class TextFile(RawFile): # def __init__(self): # def read(self): # def read_in_blocks(self, block_size): # def write(self, array): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def get_file_handler(filename, fmt='', dtype='float64', byteorder='native', **kwargs): . Output only the next line.
FORMATS = (rawfile.format_binary, rawfile.format_text)
Given the following code snippet before the placeholder: <|code_start|> self.label_text = label_text self.cancel_button_text = cancel_button_text self.cancel_label_text = cancel_label_text self._init_ui() def _init_ui(self): self.label = QtGui.QLabel(self.label_text) self.pbar_widget = QtGui.QWidget(self) self.pbar = QtGui.QProgressBar(self.pbar_widget) self.pbar.setMinimum(0) self.pbar.setMaximum(0) self.button_cancel = QtGui.QPushButton(self.cancel_button_text, self.pbar_widget) self.hlayout = QtGui.QHBoxLayout(self.pbar_widget) self.hlayout.addWidget(self.pbar) self.hlayout.addWidget(self.button_cancel) self.layout = QtGui.QVBoxLayout(self) self.layout.addWidget(self.label) self.layout.addWidget(self.pbar_widget) self.button_cancel.clicked.connect(self.reject) def run(self, task): self.label.setText(self.label_text) self._task = task self._thread = QtCore.QThread(self) self._task.moveToThread(self._thread) self._thread.started.connect(self._task.run) self._task.finished.connect(self._thread.quit) self._task.finished.connect(self.accept) self._task.finished.connect(self._task.deleteLater) <|code_end|> , predict the next line using imports from the current file: from PySide import QtCore from PySide import QtGui from apasvo.gui.views import error and context including class names, function names, and sometimes code from other files: # Path: apasvo/gui/views/error.py # def display_error_dlg(msg, additional_info=None, parent=None): . Output only the next line.
self._task.error.connect(self.on_error)
Given the code snippet: <|code_start|> def __init__(self, bfirls=None, fs=50.0, P_noise_db=0.0, low_period=50.0, high_period=10.0, bandwidth=4.0, overlap=1.0, f_low=2.0, f_high=18.0, low_amp=0.2, high_amp=0.1, **kwargs): super(EarthquakeGenerator, self).__init__() self.bfirls = bfirls self.fs = fs self.P_noise_db = P_noise_db self.low_period = low_period self.high_period = high_period self.bandwidth = bandwidth self.overlap = overlap self.f_low = f_low self.f_high = f_high self.low_amp = low_amp self.high_amp = high_amp def load_noise_coefficients(self, fileobj, dtype='float64', byteorder='native'): """Loads 'bfirls' attribute from a given file. File must be on binary or plain text format. Args: fileobj: A binary or text file object containing a list of numeric coefficients. dtype: Data-type of the numeric data stored into the file. byteorder: Byte-order of the numeric data stored into the file. """ <|code_end|> , generate the next line using the imports in this file: import numpy as np from scipy import signal from apasvo.utils.formats import rawfile and context (functions, classes, or occasionally code) from other files: # Path: apasvo/utils/formats/rawfile.py # class RawFile(object): # class BinFile(RawFile): # class TextFile(RawFile): # def __init__(self): # def read(self): # def read_in_blocks(self, block_size): # def write(self, array): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def __init__(self, filename, dtype='float64', byteorder='native'): # def read(self, **kwargs): # def read_in_blocks(self, block_size=1024): # def write(self, array, **kwargs): # def get_file_handler(filename, fmt='', dtype='float64', byteorder='native', **kwargs): . Output only the next line.
fhandler = rawfile.get_file_handler(fileobj, dtype=dtype,
Here is a snippet: <|code_start|> self.ax.grid(True, which='both') # Set event markers self.marker_select_color = 'r' self.marker_color = 'b' self.markers = {} self.update_markers() # Selection parameters self.selected = False self.selector = self.ax.axvspan(0, self.xmax, fc='LightCoral', ec='r', alpha=0.5, visible=False)#, animated=True) # Place legend at = AnchoredText(self.trace.short_name, prop=dict(size=12), frameon=True, loc=2) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") self.ax.add_artist(at) def on_xlim_change(self, ax): xmin, xmax = ax.get_xlim() if self.xmin <= xmin <= xmax <= self.xmax: # Update data self.update_data(ax) else: xmin = max(self.xmin, xmin) xmax = min(self.xmax, xmax) ax.set_xlim(xmin, xmax) def update_data(self, ax=None): ax = self.ax if ax is None else ax xmin, xmax = self.ax.get_xlim() xmin = int(max(0, self.xmin) * self.trace.fs) xmax = int(min(self.xmax, xmax) * self.trace.fs) pixel_width = np.ceil(self.fig.get_figwidth() * self.fig.get_dpi()) <|code_end|> . Write the next line using the current file imports: from PySide import QtGui from PySide import QtCore from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.ticker import FuncFormatter from mpl_toolkits.axes_grid.anchored_artists import AnchoredText from apasvo.utils import plotting from apasvo.utils import clt import numpy as np import matplotlib import matplotlib.pyplot as plt and context from other files: # Path: apasvo/utils/plotting.py # SPECGRAM_WINDOWS = ("boxcar", "hamming", "hann", "bartlett", # 'blackman', "blackmanharris") # SPECGRAM_WINDOWS_NAMES = ("Rectangular", "Hamming", "Hann", "Bartlett", # "Blackman", "Blackman-Harris") # def plot_specgram(ax, data, fs, nfft=256, noverlap=128, window='hann', # cmap='jet', interpolation='bilinear', rasterized=True): # def reduce_data(x, y, width, xmin=0, xmax=None): # def adjust_axes_height(ax, max_value=None, min_value=None, margin=0.1): # # Path: apasvo/utils/clt.py # def float_secs_2_string_date(x, starttime=datetime.datetime.utcfromtimestamp(0)): # def print_msg(msg): # def query_yes_no_all_quit(question, default="yes"): # def query_custom_answers(question, answers, default=None): # def __init__(self, name, data, align=ALIGN.RIGHT, fmt='%.6g'): # def __init__(self, *columns): # def get_row(self, i=None): # def get_line(self): # def join_n_wrap(self, char, elements): # def get_rows(self): # def __str__(self): # def __init__(self, minValue=0, maxValue=100, totalWidth=12): # def updateAmount(self, newAmount=0): # def __str__(self): # class ALIGN: # class Column(): # class Table: # class ProgressBar: # LEFT, RIGHT = '-', '' , which may include functions, classes, or code. Output only the next line.
x_data, y_data = plotting.reduce_data(self.time, self.trace.signal, pixel_width, xmin, xmax)
Given snippet: <|code_start|> You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' matplotlib.rcParams['backend'] = 'qt4agg' matplotlib.rcParams['backend.qt4'] = 'PySide' matplotlib.rcParams['patch.antialiased'] = False matplotlib.rcParams['figure.dpi'] = 65 matplotlib.rcParams['agg.path.chunksize'] = 80000 class TracePlot(QtCore.QObject): def __init__(self, parent, trace, fig_nrows=1, fig_ncols=1, ax_pos=1): super(TracePlot, self).__init__() self.parent = parent self.fig = parent.fig self.ax = self.fig.add_subplot(fig_nrows, fig_ncols, ax_pos, visible=False) self.trace = trace # Get trace dataseries self.signal = trace.signal self.time = np.linspace(0, len(self.signal) / trace.fs, num=len(self.signal), endpoint=False) self.xmin, self.xmax = 0, self.time[-1] # Plot current data self._plot_data = self.ax.plot(self.time, self.signal, color='black', rasterized=True)[0] self.ax.callbacks.connect('xlim_changed', self.on_xlim_change) self.ax.set_xlim(self.xmin, self.xmax) # Format axes <|code_end|> , continue by predicting the next line. Consider current file imports: from PySide import QtGui from PySide import QtCore from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.ticker import FuncFormatter from mpl_toolkits.axes_grid.anchored_artists import AnchoredText from apasvo.utils import plotting from apasvo.utils import clt import numpy as np import matplotlib import matplotlib.pyplot as plt and context: # Path: apasvo/utils/plotting.py # SPECGRAM_WINDOWS = ("boxcar", "hamming", "hann", "bartlett", # 'blackman', "blackmanharris") # SPECGRAM_WINDOWS_NAMES = ("Rectangular", "Hamming", "Hann", "Bartlett", # "Blackman", "Blackman-Harris") # def plot_specgram(ax, data, fs, nfft=256, noverlap=128, window='hann', # cmap='jet', interpolation='bilinear', rasterized=True): # def reduce_data(x, y, width, xmin=0, xmax=None): # def adjust_axes_height(ax, max_value=None, min_value=None, margin=0.1): # # Path: apasvo/utils/clt.py # def float_secs_2_string_date(x, starttime=datetime.datetime.utcfromtimestamp(0)): # def print_msg(msg): # def query_yes_no_all_quit(question, default="yes"): # def query_custom_answers(question, answers, default=None): # def __init__(self, name, data, align=ALIGN.RIGHT, fmt='%.6g'): # def __init__(self, *columns): # def get_row(self, i=None): # def get_line(self): # def join_n_wrap(self, char, elements): # def get_rows(self): # def __str__(self): # def __init__(self, minValue=0, maxValue=100, totalWidth=12): # def updateAmount(self, newAmount=0): # def __str__(self): # class ALIGN: # class Column(): # class Table: # class ProgressBar: # LEFT, RIGHT = '-', '' which might include code, classes, or functions. Output only the next line.
axes_formatter = FuncFormatter(lambda x, pos: clt.float_secs_2_string_date(x, trace.starttime))
Predict the next line for this snippet: <|code_start|> elif case ==3: conns = np.array([[0,1],[1,2],[1,3],[2,4], [3,4],[4,5]]) nodeTypes = getNodeTypes(conns) Np = np.shape(conns)[0] Nn = len(np.unique(conns)) Ls = [50,150,25,25,25,50] Ns = [Ls[k]*2 for k in range(Np)] Mrs = [0.007]*Np Ds = [0.1]*Np jt = nodeTypes bt = [1]*Nn #reflect everything except at inlet node r = [1]*Nn r[0]=0 bv = [0]*Nn #specify pressure here bv[0] = 0.015473914995245055 bt[0]=0 h0s = [0.01]*Np h0s[0]=1 #h0s = [1.,2.,3.,4.,5.,1.] q0s = [0.00]*Np T = 600 a = 10 elevs = [0]*Nn descrip= "pressurizing network with loop. specify pressure at inlet (nonconstant)" (xs,ys) = getCoordinates(conns) dx = [Ls[i]/float(Ns[i]) for i in range(Np)] M = int(T*a/(max(dx)*.8)) <|code_end|> with the help of current file imports: import time import numpy as np import pickle import sys import networkx as nx import os import matplotlib.colors as colors from scipy import stats from matplotlib import rc from matplotlib.mlab import find from matplotlib import pyplot as plt from allthethings import PyNetwork, PyPipe_ps from allthethings import PyBC_opt_dh from writeit import writePipes and context from other files: # Path: writeit.py # def writePipes(fn,conns, xs,ys, Ns, Ls, Mrs, Ds, jt, bt, bv, r, h0s, q0s, T, M, a, elevs): # '''write .inp and .config files from scratch--be careful that the input parameter conns is actually a valid network structure!''' # #conns is an array of size Nx2; each row represents two junctions connecting a single edge # Np = np.shape(conns)[0] # Nn = len(jt) # #first write a fake .inp to get network connectivity # ftemp = '../indata/fakeinp.inp' # with open(ftemp, 'w') as ft: # ft.write('[TITLE]\n\n\n[JUNCTIONS]\n;ID Elev Demand Pattern\n') # for k in range(Nn): # ft.write("%d %15s %2.3f %15s0 %30s ;\n"%(k," ",elevs[k]," "," ")) # ft.write('\n[PIPES]\n;ID Node1 Node2 Length Diameter Roughness MinorLoss Status\n') # for k in range(Np): # ft.write("%s %15s %s %15s %s %15s %4.1d %15s %2.2f %15s %1.4f\n" % \ # (k," ",conns[k,0]," ", conns[k,1]," ", Ls[k]," ", Ds[k]," ", Mrs[k])) # ft.write('\n[COORDINATES]\n;Node X-Coord Y-Coord\n') # for k in range(Nn): # ft.write('%d %15s %.2f %15s %.2f\n'%(k,' ', xs[k], ' ', ys[k])) # print ftemp # (fi, fc) = rewritePipes(fn, ftemp, Ns, Ls, Mrs, Ds, jt, bt, bv, r, h0s, q0s, T, M, a, elevs) # return (fi, fc) , which may contain function names, class names, or code. Output only the next line.
(fi, fc) = writePipes(fn,conns, xs,ys, Ns, Ls, Mrs, Ds, jt, bt, bv, r, h0s, q0s, T, M, a, elevs)
Given the code snippet: <|code_start|> class EmailRequestHandler(webapp2.RequestHandler): def post(self): inbound_message = mail.InboundEmailMessage(self.request.body) logging.info("Email request! Sent from %s with message subject %s" % (inbound_message.sender,inbound_message.subject)) body = inbound_message.subject logging.debug("email body arguments %s" % body) # ignore anything sent by ourselves to avoid an infinite loop if inbound_message.sender == config.EMAIL_SENDER_ADDRESS: self.response.set_status(200) return if body.lower().find('parking') > -1: logging.info('parking request via email') <|code_end|> , generate the next line using the imports in this file: import logging import webapp2 import config from google.appengine.api import mail from google.appengine.api.taskqueue import Task from apps import api_bridge and context (functions, classes, or occasionally code) from other files: # Path: apps/api_bridge.py # def getarrivals(request, result_count=3): # def getparking(): . Output only the next line.
response = api_bridge.getparking()
Predict the next line for this snippet: <|code_start|> class XmppHandler(webapp2.RequestHandler): def post(self): message = xmpp.Message(self.request.POST) logging.info("XMPP request! Sent form %s with message %s" % (message.sender,message.body)) # normalize the XMPP requests if message.sender.find('@'): caller = message.sender.split('/')[0] else: caller = message.sender.get('from') if message.body.lower().find('parking') > -1: logging.info('parking request via XMPP') <|code_end|> with the help of current file imports: import logging import webapp2 from google.appengine.api.taskqueue import Task from google.appengine.api import xmpp from apps import api_bridge from apps import meta and context from other files: # Path: apps/api_bridge.py # def getarrivals(request, result_count=3): # def getparking(): # # Path: apps/meta.py # def getStats(phone): , which may contain function names, class names, or code. Output only the next line.
response = api_bridge.getparking()
Given the code snippet: <|code_start|> class XmppHandler(webapp2.RequestHandler): def post(self): message = xmpp.Message(self.request.POST) logging.info("XMPP request! Sent form %s with message %s" % (message.sender,message.body)) # normalize the XMPP requests if message.sender.find('@'): caller = message.sender.split('/')[0] else: caller = message.sender.get('from') if message.body.lower().find('parking') > -1: logging.info('parking request via XMPP') response = api_bridge.getparking() elif message.body.lower().find('help') > -1: response = "Bus arrivals: stopID -or- routeID stopID Parking: 'parking' Stats: 'stats' Help: 'help'" elif message.body.lower().find('stats') > -1: <|code_end|> , generate the next line using the imports in this file: import logging import webapp2 from google.appengine.api.taskqueue import Task from google.appengine.api import xmpp from apps import api_bridge from apps import meta and context (functions, classes, or occasionally code) from other files: # Path: apps/api_bridge.py # def getarrivals(request, result_count=3): # def getparking(): # # Path: apps/meta.py # def getStats(phone): . Output only the next line.
response = meta.getStats(caller)
Given the code snippet: <|code_start|> class SMSRequestHandler(webapp2.RequestHandler): def post(self): # validate it is in fact coming from twilio if config.ACCOUNT_SID != self.request.get('AccountSid'): logging.error("Inbound request was NOT VALID. It might have been spoofed!") self.response.out.write(errorResponse("Illegal caller")) return # who called? and what did they ask for? phone = self.request.get("From") msg = self.request.get("Body") logging.info("New inbound request from %s with message, %s" % (self.request.get('From'),msg)) if paywall.isUserValid(phone) is False: if paywall.isUserVirgin(phone) is True: logging.info('Brand new caller - welcome them') paywall.welcomeSolicitor(phone) else: # ignore caller logging.info('We have seen this number before. Ignore this request') return # interrogate the message body to determine what to do if msg.lower().find('parking') > -1: <|code_end|> , generate the next line using the imports in this file: import logging import webapp2 import twilio import config import paywall from google.appengine.api.taskqueue import Task from apps import api_bridge from apps import meta and context (functions, classes, or occasionally code) from other files: # Path: apps/api_bridge.py # def getarrivals(request, result_count=3): # def getparking(): # # Path: apps/meta.py # def getStats(phone): . Output only the next line.
response = api_bridge.getparking()
Here is a snippet: <|code_start|>class SMSRequestHandler(webapp2.RequestHandler): def post(self): # validate it is in fact coming from twilio if config.ACCOUNT_SID != self.request.get('AccountSid'): logging.error("Inbound request was NOT VALID. It might have been spoofed!") self.response.out.write(errorResponse("Illegal caller")) return # who called? and what did they ask for? phone = self.request.get("From") msg = self.request.get("Body") logging.info("New inbound request from %s with message, %s" % (self.request.get('From'),msg)) if paywall.isUserValid(phone) is False: if paywall.isUserVirgin(phone) is True: logging.info('Brand new caller - welcome them') paywall.welcomeSolicitor(phone) else: # ignore caller logging.info('We have seen this number before. Ignore this request') return # interrogate the message body to determine what to do if msg.lower().find('parking') > -1: response = api_bridge.getparking() elif msg.lower().find('help') > -1: response = "Bus arrival requests are either, stopID -or- routeID stopID Send 'parking' to find parking details" elif msg.lower().find('stats') > -1: <|code_end|> . Write the next line using the current file imports: import logging import webapp2 import twilio import config import paywall from google.appengine.api.taskqueue import Task from apps import api_bridge from apps import meta and context from other files: # Path: apps/api_bridge.py # def getarrivals(request, result_count=3): # def getparking(): # # Path: apps/meta.py # def getStats(phone): , which may include functions, classes, or code. Output only the next line.
response = meta.getStats(phone)
Predict the next line for this snippet: <|code_start|> 'To' : friend.phone, 'Body' : self.request.get('text'), } try: account.request('/%s/Accounts/%s/SMS/Messages' % (config.API_VERSION, config.ACCOUNT_SID), 'POST', sms) except Exception, e: logging.error("Twilio REST error: %s" % e) self.response.out.write('success'); ## end class AdminHandler(webapp2.RequestHandler): def get(self): user = users.get_current_user() if user and users.is_current_user_admin(): greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" % (user.nickname(), users.create_logout_url("/"))) else: greeting = ("<a href=\"%s\">Sign in</a>." % users.create_login_url("/")) # do some analysis on the request history... total = 0 callers = dict() reqs = dict() cursor = None # Start a query for all Person entities. <|code_end|> with the help of current file imports: import os import logging import webapp2 import twilio import config import paywall from operator import itemgetter from datetime import date from datetime import timedelta from google.appengine.api.labs.taskqueue import Task from google.appengine.ext import db from google.appengine.ext.webapp import template from data_model import PhoneLog from data_model import Caller and context from other files: # Path: data_model.py # class PhoneLog(db.Model): # phone = db.StringProperty() # to = db.StringProperty(multiline=True) # date = db.DateTimeProperty(auto_now_add=True) # body = db.StringProperty(multiline=True,indexed=False) # smsID = db.StringProperty(indexed=False) # outboundSMS = db.StringProperty(multiline=True,indexed=False) # # Path: data_model.py # class Caller(db.Model): # # caller's phone number requests are sent from # phone = db.StringProperty(indexed=True) # # the SMB service number Caller has permission to use # service = db.StringProperty() # # created = db.DateProperty(auto_now_add=True) # expires = db.DateProperty() , which may contain function names, class names, or code. Output only the next line.
q = PhoneLog.all()
Given the following code snippet before the placeholder: <|code_start|> (self.request.get('sid'), self.request.get('phone'))) account = twilio.Account(config.ACCOUNT_SID, config.ACCOUNT_TOKEN) sms = { 'From' : config.CALLER_ID, 'To' : self.request.get('phone'), 'Body' : self.request.get('text'), } try: account.request('/%s/Accounts/%s/SMS/Messages' % (config.API_VERSION, config.ACCOUNT_SID), 'POST', sms) except Exception, e: logging.error("Twilio REST error: %s" % e) self.response.out.write('success'); ## end SendSMSHandler class AddUserHandler(webapp2.RequestHandler): def get(self): user_phone = self.request.get('phone') if( user_phone is None or user_phone == '' ): logging.error("Failed to create a new user. No phone number was provided") self.response.out.write('error. no phone number was provided - ?phone=') else: # prepend +1 on the number user_phone = '+1' + user_phone logging.info('Adding new user... %s' % user_phone) q = db.GqlQuery("select * from Caller where phone = :1", user_phone) new_user = q.get() if( new_user is None ): <|code_end|> , predict the next line using imports from the current file: import os import logging import webapp2 import twilio import config import paywall from operator import itemgetter from datetime import date from datetime import timedelta from google.appengine.api.labs.taskqueue import Task from google.appengine.ext import db from google.appengine.ext.webapp import template from data_model import PhoneLog from data_model import Caller and context including class names, function names, and sometimes code from other files: # Path: data_model.py # class PhoneLog(db.Model): # phone = db.StringProperty() # to = db.StringProperty(multiline=True) # date = db.DateTimeProperty(auto_now_add=True) # body = db.StringProperty(multiline=True,indexed=False) # smsID = db.StringProperty(indexed=False) # outboundSMS = db.StringProperty(multiline=True,indexed=False) # # Path: data_model.py # class Caller(db.Model): # # caller's phone number requests are sent from # phone = db.StringProperty(indexed=True) # # the SMB service number Caller has permission to use # service = db.StringProperty() # # created = db.DateProperty(auto_now_add=True) # expires = db.DateProperty() . Output only the next line.
new_user = Caller()
Predict the next line after this snippet: <|code_start|> class MainHandler(webapp2.RequestHandler): def post(self): # this handler should never get called logging.error("The MainHandler should never get called... %s" % self.request) self.error(204) def get(self): self.post() ## end MainHandler() class EventLoggingHandler(webapp2.RequestHandler): def post(self): # normalize the XMPP requests if self.request.get('from').find('@'): caller = self.request.get('from').split('/')[0] else: caller = self.request.get('from') # log this event... logging.debug('logging caller: %s' % caller) <|code_end|> using the current file's imports: import logging import urllib import webapp2 import config from google.appengine.api import memcache from data_model import PhoneLog and any relevant context from other files: # Path: data_model.py # class PhoneLog(db.Model): # phone = db.StringProperty() # to = db.StringProperty(multiline=True) # date = db.DateTimeProperty(auto_now_add=True) # body = db.StringProperty(multiline=True,indexed=False) # smsID = db.StringProperty(indexed=False) # outboundSMS = db.StringProperty(multiline=True,indexed=False) . Output only the next line.
log = PhoneLog()
Using the snippet: <|code_start|> ## end PhoneRequestBusHandler class PhoneRequestStopHandler(webapp2.RequestHandler): def get(self): # validate it is in fact coming from twilio if config.ACCOUNT_SID == self.request.get('AccountSid'): logging.debug("PHONE request was confirmed to have come from Twilio.") else: logging.error("was NOT VALID. It might have been spoofed!") self.response.out.write(errorResponse("Illegal caller")) return # pull the route and stopID out of the request body and # pad it with a zero on the front if the message forgot # to include it (that's how they are stored in the DB) routeID = memcache.get(self.request.get('AccountSid')) memcache.delete(self.request.get('AccountSid')) stopID = self.request.get('Digits') if len(stopID) == 3: stopID = "0" + stopID # hack - creating a string out of the details to conform to other interfaces requestArgs = "%s %s" % (routeID, stopID) ## magic ## logging.info('starting the magic... %s' % requestArgs) <|code_end|> , determine the next line of code. You have imports: import logging import webapp2 import twilio import config import paywall from google.appengine.api import memcache from google.appengine.api.labs.taskqueue import Task from apps import api_bridge and context (class names, function names, or code) available: # Path: apps/api_bridge.py # def getarrivals(request, result_count=3): # def getparking(): . Output only the next line.
textBody = api_bridge.getarrivals(requestArgs, 1)
Here is a snippet: <|code_start|> if study == 'brainpedia': this_study = meta['study'] subject = meta['name'].split('_')[-1] contrast = '_'.join(meta['task'].split('_')[1:]) task = meta['task'].split('_')[0] else: this_study = study subject = meta['name'].split('_')[0] contrast = meta['contrast_definition'] task = meta['task'] records.append([image, this_study, subject, task, contrast]) df = pd.DataFrame(records, columns=['z_map', 'study', 'subject', 'task', 'contrast']) return df def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): dfs = [] if studies == 'all': studies = nv_ids.keys() for study in studies: if study not in nv_ids: return ValueError('Wrong dataset.') data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, mode='download_new') dfs.append(_assemble(data['images'], data['images_meta'], study)) return pd.concat(dfs) def load_masked_contrasts(data_dir): Xs, ys = {}, {} <|code_end|> . Write the next line using the current file imports: from os.path import join from typing import List from joblib import load from nilearn.datasets import fetch_neurovault_ids from cogspaces.datasets.derivative import STUDY_LIST, add_study_contrast import pandas as pd and context from other files: # Path: cogspaces/datasets/derivative.py # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] # # def add_study_contrast(ys): # for study in ys: # ys[study]['study_contrast'] = ys[study]['study'] + '__' + ys[study]['task'] + '__' + \ # ys[study]['contrast'] # return ys , which may include functions, classes, or code. Output only the next line.
for study in STUDY_LIST:
Given the code snippet: <|code_start|> contrast = '_'.join(meta['task'].split('_')[1:]) task = meta['task'].split('_')[0] else: this_study = study subject = meta['name'].split('_')[0] contrast = meta['contrast_definition'] task = meta['task'] records.append([image, this_study, subject, task, contrast]) df = pd.DataFrame(records, columns=['z_map', 'study', 'subject', 'task', 'contrast']) return df def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): dfs = [] if studies == 'all': studies = nv_ids.keys() for study in studies: if study not in nv_ids: return ValueError('Wrong dataset.') data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, mode='download_new') dfs.append(_assemble(data['images'], data['images_meta'], study)) return pd.concat(dfs) def load_masked_contrasts(data_dir): Xs, ys = {}, {} for study in STUDY_LIST: Xs[study], ys[study] = load(join(data_dir, 'masked', 'data_%s.npy'), mmap_mode='r') <|code_end|> , generate the next line using the imports in this file: from os.path import join from typing import List from joblib import load from nilearn.datasets import fetch_neurovault_ids from cogspaces.datasets.derivative import STUDY_LIST, add_study_contrast import pandas as pd and context (functions, classes, or occasionally code) from other files: # Path: cogspaces/datasets/derivative.py # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] # # def add_study_contrast(ys): # for study in ys: # ys[study]['study_contrast'] = ys[study]['study'] + '__' + ys[study]['task'] + '__' + \ # ys[study]['contrast'] # return ys . Output only the next line.
ys = add_study_contrast(ys)
Continue the code snippet: <|code_start|> Takes a collection of datasets and split them into a test and train collection. Parameters ---------- data : Dict[str, np.ndarray] Collection of input data (one for each study) target : Dict[str, pd.DataFrame] Collection of targets (one for each study) test_size : float in [0, 1] or Dict[str, float] Test size for each study train_size : float in [0, 1] or Dict[str, float] Train size for each study random_state: int or None Seed for the split Returns ------- train_data : Dict[str, np.ndarray] test_data : Dict[str, np.ndarray] train_target : Dict[str, pd.DataFrame] test_target : Dict[str, pd.DataFrame] """ <|code_end|> . Use current file imports: import numpy as np from sklearn.model_selection import GroupShuffleSplit from cogspaces.utils import zip_data, unzip_data and context (classes, functions, or code) from other files: # Path: cogspaces/utils.py # def zip_data(data, target): # return {study: (data[study], target[study]) for study in data} # # def unzip_data(data): # return {study: data[study][0] for study in data}, \ # {study: data[study][1] for study in data} . Output only the next line.
data = zip_data(data, target)
Continue the code snippet: <|code_start|> train_data : Dict[str, np.ndarray] test_data : Dict[str, np.ndarray] train_target : Dict[str, pd.DataFrame] test_target : Dict[str, pd.DataFrame] """ data = zip_data(data, target) datasets = {'train': {}, 'test': {}} if isinstance(test_size, (float, int)): test_size = {study: test_size for study in data} if isinstance(train_size, (float, int)): train_size = {study: train_size for study in data} splits = {} for study, (this_data, this_target) in data.items(): if train_size[study] == 1.: train = np.arange(len(this_data)) test = [0] else: cv = GroupShuffleSplit(n_splits=1, test_size=test_size[study], train_size=train_size[study], random_state=random_state) train, test = next(cv.split(X=this_data, groups=this_target['subject'])) for fold, indices in [('train', train), ('test', test)]: datasets[fold][study] = this_data[indices], \ this_target.iloc[indices] <|code_end|> . Use current file imports: import numpy as np from sklearn.model_selection import GroupShuffleSplit from cogspaces.utils import zip_data, unzip_data and context (classes, functions, or code) from other files: # Path: cogspaces/utils.py # def zip_data(data, target): # return {study: (data[study], target[study]) for study in data} # # def unzip_data(data): # return {study: data[study][0] for study in data}, \ # {study: data[study][1] for study in data} . Output only the next line.
train_data, train_target = unzip_data(datasets['train'])
Using the snippet: <|code_start|> idx = pd.IndexSlice def single_mask(masker, imgs): return masker.transform(imgs) def single_reduce(components, data, lstsq=False): if not lstsq: return data.dot(components.T) else: X, _, _, _ = np.linalg.lstsq(components.T, data.T) return X.T def mask_contrasts(studies: Union[str, List[str]] = 'all', output_dir: str = 'masked', use_raw=False, n_jobs: int = 1): batch_size = 10 if not os.path.exists(output_dir): os.makedirs(output_dir) if use_raw and studies == 'all': data = fetch_all() else: <|code_end|> , determine the next line of code. You have imports: import os import numpy as np import pandas as pd from os.path import join from typing import List, Union from joblib import Parallel, delayed, dump, load from nilearn.input_data import NiftiMasker from sklearn.utils import gen_batches from cogspaces.datasets import fetch_mask, fetch_atlas_modl, \ fetch_contrasts, STUDY_LIST from cogspaces.datasets.utils import get_data_dir from cogspaces.raw_datasets.contrast import fetch_all and context (class names, function names, or code) available: # Path: cogspaces/datasets/contrast.py # def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): # dfs = [] # if studies == 'all': # studies = nv_ids.keys() # for study in studies: # if study not in nv_ids: # return ValueError('Wrong dataset.') # data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, # mode='download_new') # dfs.append(_assemble(data['images'], data['images_meta'], study)) # return pd.concat(dfs) # # Path: cogspaces/datasets/derivative.py # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] # # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] # # Path: cogspaces/datasets/utils.py # def get_data_dir(data_dir=None): # """ Returns the directories in which to look for data. # # Parameters # ---------- # data_dir: string, optional # Path of the utils directory. Used to force utils storage in a specified # location. Default: None # # Returns # ------- # path: string # Path of the data directory. # """ # # # Check data_dir which force storage in a specific location # if data_dir is not None: # assert (isinstance(data_dir, str)) # return data_dir # elif 'COGSPACES_DATA' in os.environ: # return os.environ['COGSPACES_DATA'] # else: # return os.path.expanduser('~/cogspaces_data') # # Path: cogspaces/raw_datasets/contrast.py # def fetch_all(data_dir=None): # dfs = [] # for study in ['archi', 'brainomics', 'camcan', 'hcp', # 'la5c', 'brainpedia']: # df = fetch_contrasts(study, data_dir=data_dir) # dfs.append(df) # df = pd.concat(dfs) # df = clean_targets(df) # return df . Output only the next line.
data = fetch_contrasts(studies)
Here is a snippet: <|code_start|> idx = pd.IndexSlice def single_mask(masker, imgs): return masker.transform(imgs) def single_reduce(components, data, lstsq=False): if not lstsq: return data.dot(components.T) else: X, _, _, _ = np.linalg.lstsq(components.T, data.T) return X.T def mask_contrasts(studies: Union[str, List[str]] = 'all', output_dir: str = 'masked', use_raw=False, n_jobs: int = 1): batch_size = 10 if not os.path.exists(output_dir): os.makedirs(output_dir) if use_raw and studies == 'all': <|code_end|> . Write the next line using the current file imports: import os import numpy as np import pandas as pd from os.path import join from typing import List, Union from joblib import Parallel, delayed, dump, load from nilearn.input_data import NiftiMasker from sklearn.utils import gen_batches from cogspaces.datasets import fetch_mask, fetch_atlas_modl, \ fetch_contrasts, STUDY_LIST from cogspaces.datasets.utils import get_data_dir from cogspaces.raw_datasets.contrast import fetch_all and context from other files: # Path: cogspaces/datasets/contrast.py # def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): # dfs = [] # if studies == 'all': # studies = nv_ids.keys() # for study in studies: # if study not in nv_ids: # return ValueError('Wrong dataset.') # data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, # mode='download_new') # dfs.append(_assemble(data['images'], data['images_meta'], study)) # return pd.concat(dfs) # # Path: cogspaces/datasets/derivative.py # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] # # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] # # Path: cogspaces/datasets/utils.py # def get_data_dir(data_dir=None): # """ Returns the directories in which to look for data. # # Parameters # ---------- # data_dir: string, optional # Path of the utils directory. Used to force utils storage in a specified # location. Default: None # # Returns # ------- # path: string # Path of the data directory. # """ # # # Check data_dir which force storage in a specific location # if data_dir is not None: # assert (isinstance(data_dir, str)) # return data_dir # elif 'COGSPACES_DATA' in os.environ: # return os.environ['COGSPACES_DATA'] # else: # return os.path.expanduser('~/cogspaces_data') # # Path: cogspaces/raw_datasets/contrast.py # def fetch_all(data_dir=None): # dfs = [] # for study in ['archi', 'brainomics', 'camcan', 'hcp', # 'la5c', 'brainpedia']: # df = fetch_contrasts(study, data_dir=data_dir) # dfs.append(df) # df = pd.concat(dfs) # df = clean_targets(df) # return df , which may include functions, classes, or code. Output only the next line.
data = fetch_all()
Predict the next line after this snippet: <|code_start|> 'contrast': contrast, 'z_map': join(subject_dir, this_map)}) df = pd.DataFrame(rec) df.set_index(['study', 'subject', 'task', 'contrast', 'direction'], inplace=True) if drop_some: df.drop('effects_of_interest', level=4, axis=0, inplace=True, errors='ignore') df.drop('pinel2007fast', level=0, axis=0, inplace=True, errors='ignore') df.drop('ds102', level=0, axis=0, inplace=True, errors='ignore') return df def fetch_hcp(data_dir=None, n_subjects=None, subjects=None, from_file=True): data_dir = get_data_dir(data_dir) BASE_CONTRASTS = ['FACES', 'SHAPES', 'PUNISH', 'REWARD', 'MATH', 'STORY', 'MATCH', 'REL', 'RANDOM', 'TOM', 'LF', 'RF', 'LH', 'RH', 'CUE', '0BK_BODY', '0BK_FACE', '0BK_PLACE', '0BK_TOOL', '2BK_BODY', '2BK_FACE', '2BK_PLACE', '2BK_TOOL', ] source_dir = join(data_dir, 'HCP900') if not os.path.exists(source_dir): raise ValueError( 'Please ensure that %s contains all required data.' % source_dir) <|code_end|> using the current file's imports: import glob import os import re import pandas as pd import yaml from os.path import join from sklearn.utils import Bunch from .hcp import fetch_hcp as hcp_builder_fetch_hcp from ..datasets.utils import get_data_dir and any relevant context from other files: # Path: cogspaces/raw_datasets/hcp.py # def fetch_hcp(data_dir=None, n_subjects=None, subjects=None, # from_file=False, # on_disk=True): # root = get_data_dirs(data_dir)[0] # mask = fetch_hcp_mask(data_dir) # if not from_file: # rest = fetch_hcp_timeseries(data_dir, data_type='rest', # n_subjects=n_subjects, subjects=subjects, # on_disk=on_disk) # task = fetch_hcp_timeseries(data_dir, data_type='task', # n_subjects=n_subjects, subjects=subjects, # on_disk=on_disk) # contrasts = fetch_hcp_contrasts(data_dir, # output='nistats', # n_subjects=n_subjects, # subjects=subjects, # on_disk=on_disk) # behavioral = fetch_behavioral_data(data_dir) # indices = [] # for df in rest, task, contrasts: # if not df.empty: # indices.append(df.index.get_level_values('subject'). # unique().values) # if indices: # index = indices[0] # for this_index in indices[1:]: # index = np.union1d(index, this_index) # behavioral = behavioral.loc[index] # else: # behavioral = pd.DataFrame([]) # else: # rest = pd.read_csv(join(root, 'parietal', 'rest.csv')) # task = pd.read_csv(join(root, 'parietal', 'task.csv')) # contrasts = pd.read_csv(join(root, 'parietal', # 'contrasts.csv')) # behavioral = pd.read_csv(join(root, 'parietal', # 'behavioral.csv')) # behavioral.set_index('subject', inplace=True) # rest.set_index(['subject', 'session', 'direction'], inplace=True) # task.set_index(['subject', 'task', 'direction'], inplace=True) # contrasts.set_index(['subject', 'task', 'contrast', 'direction'], # inplace=True) # if subjects is None: # subjects = fetch_subject_list(data_dir=data_dir, # n_subjects=n_subjects) # rest = rest.loc[subjects] # task = task.loc[subjects] # contrasts = contrasts.loc[subjects] # behavioral = behavioral.loc[subjects] # # return Bunch(rest=rest, # contrasts=contrasts, # task=task, # behavioral=behavioral, # mask=mask, # root=root) # # Path: cogspaces/datasets/utils.py # def get_data_dir(data_dir=None): # """ Returns the directories in which to look for data. # # Parameters # ---------- # data_dir: string, optional # Path of the utils directory. Used to force utils storage in a specified # location. Default: None # # Returns # ------- # path: string # Path of the data directory. # """ # # # Check data_dir which force storage in a specific location # if data_dir is not None: # assert (isinstance(data_dir, str)) # return data_dir # elif 'COGSPACES_DATA' in os.environ: # return os.environ['COGSPACES_DATA'] # else: # return os.path.expanduser('~/cogspaces_data') . Output only the next line.
res = hcp_builder_fetch_hcp(data_dir=source_dir, n_subjects=n_subjects,
Predict the next line for this snippet: <|code_start|> def fetch_contrasts(study, data_dir=None): if study == 'archi': return fetch_archi(data_dir=data_dir) elif study == 'brainomics': return fetch_brainomics(data_dir=data_dir) elif study == 'la5c': return fetch_la5c(data_dir=data_dir) elif study == 'camcan': return fetch_camcan(data_dir=data_dir) elif study == 'hcp': return fetch_hcp(data_dir=data_dir).contrasts elif study == 'brainpedia': return fetch_brainpedia(data_dir=data_dir) else: raise ValueError def fetch_all(data_dir=None): dfs = [] for study in ['archi', 'brainomics', 'camcan', 'hcp', 'la5c', 'brainpedia']: df = fetch_contrasts(study, data_dir=data_dir) dfs.append(df) df = pd.concat(dfs) df = clean_targets(df) return df def fetch_camcan(data_dir=None): <|code_end|> with the help of current file imports: import glob import os import re import pandas as pd import yaml from os.path import join from sklearn.utils import Bunch from .hcp import fetch_hcp as hcp_builder_fetch_hcp from ..datasets.utils import get_data_dir and context from other files: # Path: cogspaces/raw_datasets/hcp.py # def fetch_hcp(data_dir=None, n_subjects=None, subjects=None, # from_file=False, # on_disk=True): # root = get_data_dirs(data_dir)[0] # mask = fetch_hcp_mask(data_dir) # if not from_file: # rest = fetch_hcp_timeseries(data_dir, data_type='rest', # n_subjects=n_subjects, subjects=subjects, # on_disk=on_disk) # task = fetch_hcp_timeseries(data_dir, data_type='task', # n_subjects=n_subjects, subjects=subjects, # on_disk=on_disk) # contrasts = fetch_hcp_contrasts(data_dir, # output='nistats', # n_subjects=n_subjects, # subjects=subjects, # on_disk=on_disk) # behavioral = fetch_behavioral_data(data_dir) # indices = [] # for df in rest, task, contrasts: # if not df.empty: # indices.append(df.index.get_level_values('subject'). # unique().values) # if indices: # index = indices[0] # for this_index in indices[1:]: # index = np.union1d(index, this_index) # behavioral = behavioral.loc[index] # else: # behavioral = pd.DataFrame([]) # else: # rest = pd.read_csv(join(root, 'parietal', 'rest.csv')) # task = pd.read_csv(join(root, 'parietal', 'task.csv')) # contrasts = pd.read_csv(join(root, 'parietal', # 'contrasts.csv')) # behavioral = pd.read_csv(join(root, 'parietal', # 'behavioral.csv')) # behavioral.set_index('subject', inplace=True) # rest.set_index(['subject', 'session', 'direction'], inplace=True) # task.set_index(['subject', 'task', 'direction'], inplace=True) # contrasts.set_index(['subject', 'task', 'contrast', 'direction'], # inplace=True) # if subjects is None: # subjects = fetch_subject_list(data_dir=data_dir, # n_subjects=n_subjects) # rest = rest.loc[subjects] # task = task.loc[subjects] # contrasts = contrasts.loc[subjects] # behavioral = behavioral.loc[subjects] # # return Bunch(rest=rest, # contrasts=contrasts, # task=task, # behavioral=behavioral, # mask=mask, # root=root) # # Path: cogspaces/datasets/utils.py # def get_data_dir(data_dir=None): # """ Returns the directories in which to look for data. # # Parameters # ---------- # data_dir: string, optional # Path of the utils directory. Used to force utils storage in a specified # location. Default: None # # Returns # ------- # path: string # Path of the data directory. # """ # # # Check data_dir which force storage in a specific location # if data_dir is not None: # assert (isinstance(data_dir, str)) # return data_dir # elif 'COGSPACES_DATA' in os.environ: # return os.environ['COGSPACES_DATA'] # else: # return os.path.expanduser('~/cogspaces_data') , which may contain function names, class names, or code. Output only the next line.
data_dir = get_data_dir(data_dir)
Given the following code snippet before the placeholder: <|code_start|>""" Analyse a model trained on data provided by load_reduced_loadings(). """ # Note that 'components_453_gm' is currently hard-coded there def compute_components(estimator, config, return_type='img'): """Compute components from a FactoredClassifier estimator""" module = curate_module(estimator) components = module.embedder.linear.weight.detach().numpy() if config['data']['reduced']: mask = fetch_mask() masker = NiftiMasker(mask_img=mask).fit() <|code_end|> , predict the next line using imports from the current file: import numpy as np import torch from nilearn.input_data import NiftiMasker from cogspaces.datasets import fetch_atlas_modl, fetch_mask and context including class names, function names, and sometimes code from other files: # Path: cogspaces/datasets/derivative.py # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] . Output only the next line.
modl_atlas = fetch_atlas_modl()
Given snippet: <|code_start|>""" Analyse a model trained on data provided by load_reduced_loadings(). """ # Note that 'components_453_gm' is currently hard-coded there def compute_components(estimator, config, return_type='img'): """Compute components from a FactoredClassifier estimator""" module = curate_module(estimator) components = module.embedder.linear.weight.detach().numpy() if config['data']['reduced']: <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import torch from nilearn.input_data import NiftiMasker from cogspaces.datasets import fetch_atlas_modl, fetch_mask and context: # Path: cogspaces/datasets/derivative.py # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] which might include code, classes, or functions. Output only the next line.
mask = fetch_mask()
Continue the code snippet: <|code_start|> warnings.filterwarnings('ignore', category=FutureWarning, module='h5py') def fetch_atlas_modl(data_dir=None, url=None, resume=True, verbose=1): """Download and load a multi-scale atlas computed using MODL over HCP900. Parameters ---------- data_dir: string, optional Path of the data directory. Used to force data storage in a non- standard location. Default: None (meaning: default) url: string, optional Download URL of the dataset. Overwrite the default URL. """ if url is None: url = 'http://cogspaces.github.io/assets/data/modl/' <|code_end|> . Use current file imports: import os import re import warnings import pandas as pd from math import ceil from os.path import join from joblib import load from sklearn.utils import Bunch from cogspaces.datasets.utils import get_data_dir from nilearn.datasets.utils import _fetch_files, _get_dataset_dir and context (classes, functions, or code) from other files: # Path: cogspaces/datasets/utils.py # def get_data_dir(data_dir=None): # """ Returns the directories in which to look for data. # # Parameters # ---------- # data_dir: string, optional # Path of the utils directory. Used to force utils storage in a specified # location. Default: None # # Returns # ------- # path: string # Path of the data directory. # """ # # # Check data_dir which force storage in a specific location # if data_dir is not None: # assert (isinstance(data_dir, str)) # return data_dir # elif 'COGSPACES_DATA' in os.environ: # return os.environ['COGSPACES_DATA'] # else: # return os.path.expanduser('~/cogspaces_data') . Output only the next line.
data_dir = get_data_dir(data_dir)
Here is a snippet: <|code_start|> contrasts_metrics.to_pickle(join(save_dir, 'contrasts_metrics.pkl')) baseline = 'logistic' accuracies.set_index(['estimator', 'study', 'seed'], inplace=True) accuracies.sort_index(inplace=True) median = accuracies['accuracy'].loc[baseline].groupby( level='study').median() diffs = [] baseline_accuracy = accuracies['accuracy'].loc[baseline] estimators = accuracies.index.get_level_values('estimator').unique() baseline_accuracy = pd.concat([baseline_accuracy] * len(estimators), keys=estimators, names=['estimator']) accuracies['baseline'] = baseline_accuracy accuracies['diff_with_baseline'] = accuracies['accuracy'] - accuracies[ 'baseline'] accuracies['diff_with_baseline_median'] = accuracies['accuracy'].groupby( level='study').transform(lambda x: x - median) accuracies.to_pickle(join(save_dir, 'accuracies.pkl')) return accuracies, contrasts_metrics def plot_mean_accuracies(save_dir, split_by_task=False): accuracies = pd.read_pickle(join(save_dir, 'accuracies.pkl')) data = accuracies.groupby(level=['estimator', 'study']).aggregate( ['mean', 'std']) data = data.loc['multi_study'] data = data.sort_values(by=('diff_with_baseline', 'mean')) <|code_end|> . Write the next line using the current file imports: import os import re import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import json from os.path import join from matplotlib import gridspec, ticker from cogspaces.datasets.derivative import get_study_info from cogspaces.datasets.utils import get_output_dir and context from other files: # Path: cogspaces/datasets/derivative.py # def get_study_info(): # input_data, targets = load_reduced_loadings(data_dir=get_data_dir()) # targets = pd.concat(targets.values(), axis=0) # targets['#subjects'] = targets.groupby(by=['study', 'task', 'contrast'])['subject'].transform('nunique') # targets['#contrasts_per_task'] = targets.groupby(by=['study', 'task'])['contrast'].transform('nunique') # targets['#contrasts_per_study'] = targets.groupby(by='study')['contrast'].transform('nunique') # targets['chance_study'] = 1 / targets['#contrasts_per_study'] # targets['chance_task'] = 1 / targets['#contrasts_per_task'] # citations = _get_citations() # targets = pd.merge(targets, citations, on='study', how='left') # targets = targets.groupby(by=['study', 'task', 'contrast']).first().sort_index().drop(columns='index').reset_index() # # targets['study__task'] = targets.apply(lambda x: f'{x["study"]}__{x["task"]}', axis='columns') # targets['name_task'] = targets.apply(lambda x: f'[{x["bibkey"]}] {x["task"]}', axis='columns') # # def apply(x): # comment = x['comment'].iloc[0] # if comment != '': # tasks = comment # tasks_lim = comment # else: # tasks_list = x['task'].unique() # tasks = ' & '.join(tasks_list) # if len(tasks) > 50: # tasks_lim = tasks_list[0] + ' & ...' # else: # tasks_lim = tasks # name = f'[{x["bibkey"].iloc[0]}] {tasks_lim}' # latex_name = f'\cite{{{x["citekey"].iloc[0]}}} {tasks}'.replace('&', '\&') # name = pd.DataFrame(data={'name': name, # 'latex_name':latex_name}, index=x.index) # return name # name = targets.groupby(by='study').apply(apply) # targets = pd.concat([targets, name], axis=1) # return targets # # Path: cogspaces/datasets/utils.py # def get_output_dir(output_dir=None): # """ Returns the directories in which to save output. # # Parameters # ---------- # output_dir: string, optional # Path of the utils directory. Used to force utils storage in a specified # location. Default: None # # Returns # ------- # path: string # Path of the output directory. # """ # # # Check data_dir which force storage in a specific location # if output_dir is not None: # assert (isinstance(output_dir, str)) # return output_dir # elif 'COGSPACES_OUTPUT' in os.environ: # return os.environ['COGSPACES_OUTPUT'] # else: # return os.path.expanduser('~/cogspaces_data') , which may include functions, classes, or code. Output only the next line.
info = get_study_info()
Given the code snippet: <|code_start|> estimators = accuracies['estimator'].unique() y_labels = {} y_labels['multi_study'] = ('Decoding from\nmulti-study\ntask-optimized\n' 'networks') y_labels['ensemble'] = ('Decoding from\nmulti-study\ntask-optimized\n' 'networks (ensemble)') y_labels['logistic'] = ('Standard decoding\nfrom resting-state\n' 'loadings') for i, estimator in enumerate(estimators): if i == len(estimators) - 1: fontweight = 'bold' else: fontweight = 'normal' ax.annotate(y_labels[estimator], xy=(1, i), xytext=(10, 0), textcoords="offset points", fontweight=fontweight, xycoords=('axes fraction', 'data'), va='center', ha='left') sns.despine(fig) plt.setp(ax.legend(), visible=False) plt.savefig(join(save_dir, 'accuracies.pdf')) plt.close(fig) <|code_end|> , generate the next line using the imports in this file: import os import re import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import json from os.path import join from matplotlib import gridspec, ticker from cogspaces.datasets.derivative import get_study_info from cogspaces.datasets.utils import get_output_dir and context (functions, classes, or occasionally code) from other files: # Path: cogspaces/datasets/derivative.py # def get_study_info(): # input_data, targets = load_reduced_loadings(data_dir=get_data_dir()) # targets = pd.concat(targets.values(), axis=0) # targets['#subjects'] = targets.groupby(by=['study', 'task', 'contrast'])['subject'].transform('nunique') # targets['#contrasts_per_task'] = targets.groupby(by=['study', 'task'])['contrast'].transform('nunique') # targets['#contrasts_per_study'] = targets.groupby(by='study')['contrast'].transform('nunique') # targets['chance_study'] = 1 / targets['#contrasts_per_study'] # targets['chance_task'] = 1 / targets['#contrasts_per_task'] # citations = _get_citations() # targets = pd.merge(targets, citations, on='study', how='left') # targets = targets.groupby(by=['study', 'task', 'contrast']).first().sort_index().drop(columns='index').reset_index() # # targets['study__task'] = targets.apply(lambda x: f'{x["study"]}__{x["task"]}', axis='columns') # targets['name_task'] = targets.apply(lambda x: f'[{x["bibkey"]}] {x["task"]}', axis='columns') # # def apply(x): # comment = x['comment'].iloc[0] # if comment != '': # tasks = comment # tasks_lim = comment # else: # tasks_list = x['task'].unique() # tasks = ' & '.join(tasks_list) # if len(tasks) > 50: # tasks_lim = tasks_list[0] + ' & ...' # else: # tasks_lim = tasks # name = f'[{x["bibkey"].iloc[0]}] {tasks_lim}' # latex_name = f'\cite{{{x["citekey"].iloc[0]}}} {tasks}'.replace('&', '\&') # name = pd.DataFrame(data={'name': name, # 'latex_name':latex_name}, index=x.index) # return name # name = targets.groupby(by='study').apply(apply) # targets = pd.concat([targets, name], axis=1) # return targets # # Path: cogspaces/datasets/utils.py # def get_output_dir(output_dir=None): # """ Returns the directories in which to save output. # # Parameters # ---------- # output_dir: string, optional # Path of the utils directory. Used to force utils storage in a specified # location. Default: None # # Returns # ------- # path: string # Path of the output directory. # """ # # # Check data_dir which force storage in a specific location # if output_dir is not None: # assert (isinstance(output_dir, str)) # return output_dir # elif 'COGSPACES_OUTPUT' in os.environ: # return os.environ['COGSPACES_OUTPUT'] # else: # return os.path.expanduser('~/cogspaces_data') . Output only the next line.
output_dir = join(get_output_dir(output_dir=None), 'normalized', 'split_by_task')
Here is a snippet: <|code_start|> i = 0 while True: yield '%s_%i' % (name, i) i += 1 def plot_4d_image(img, names=None, output_dir=None, colors=None, view_types=['stat_map'], threshold=True, n_jobs=1, verbose=10): if not os.path.exists(output_dir): os.makedirs(output_dir) if colors is None: colors = repeat(None) if 'surf_stat_map_right' in view_types or 'surf_stat_map_left' in view_types: fetch_surf_fsaverage5() filename = img img = check_niimg(img, ensure_ndim=4) img.get_data() if names is None or isinstance(names, str): if names is None: dirname, filename = os.path.split(filename) names = filename.replace('.nii.gz', '') names = numbered_names(names) else: assert len(names) == img.get_shape()[3] <|code_end|> . Write the next line using the current file imports: import os import numpy as np from itertools import repeat from os.path import join from cogspaces.datasets import fetch_mask from joblib import Parallel, delayed from matplotlib.colors import LinearSegmentedColormap, rgb_to_hsv, hsv_to_rgb from nilearn._utils import check_niimg from nilearn.datasets import fetch_surf_fsaverage5 from nilearn.image import iter_img from nilearn.input_data import NiftiMasker from nilearn.plotting import plot_stat_map, find_xyz_cut_coords, plot_glass_brain and context from other files: # Path: cogspaces/datasets/derivative.py # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] , which may include functions, classes, or code. Output only the next line.
mask = fetch_mask()
Here is a snippet: <|code_start|> def test_atlas_modl(): """Download the dataset in default directory and check success. """ atlas = fetch_atlas_modl() keys = ['components_64', 'components_128', 'components_453_gm', ] assert all(os.path.exists(atlas[key]) for key in keys) def test_fetch_mask(): fetch_mask() def test_reduced_loadings(): loadings = fetch_reduced_loadings() keys = STUDY_LIST assert all(os.path.exists(loadings[key]) for key in keys) def test_statistics(): <|code_end|> . Write the next line using the current file imports: import os from cogspaces.datasets import fetch_atlas_modl, fetch_mask, \ fetch_reduced_loadings, STUDY_LIST, fetch_contrasts and context from other files: # Path: cogspaces/datasets/contrast.py # def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): # dfs = [] # if studies == 'all': # studies = nv_ids.keys() # for study in studies: # if study not in nv_ids: # return ValueError('Wrong dataset.') # data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, # mode='download_new') # dfs.append(_assemble(data['images'], data['images_meta'], study)) # return pd.concat(dfs) # # Path: cogspaces/datasets/derivative.py # def fetch_reduced_loadings(data_dir=None, url=None, verbose=False, # resume=True): # if url is None: # url = 'http://cogspaces.github.io/assets/data/loadings/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'loadings' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = STUDY_LIST # # paths = ['data_%s.pt' % key for key in keys] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = ( # "Z-statistic loadings over a dictionary of 453 components covering " # "grey-matter `modl_atlas['components_512_gm']` " # "for 35 different task fMRI studies.") # # params['description'] = fdescr # params['data_dir'] = data_dir # # return params # # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] # # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] , which may include functions, classes, or code. Output only the next line.
df = fetch_contrasts('brainpedia')
Given the following code snippet before the placeholder: <|code_start|> def test_atlas_modl(): """Download the dataset in default directory and check success. """ atlas = fetch_atlas_modl() keys = ['components_64', 'components_128', 'components_453_gm', ] assert all(os.path.exists(atlas[key]) for key in keys) def test_fetch_mask(): fetch_mask() def test_reduced_loadings(): <|code_end|> , predict the next line using imports from the current file: import os from cogspaces.datasets import fetch_atlas_modl, fetch_mask, \ fetch_reduced_loadings, STUDY_LIST, fetch_contrasts and context including class names, function names, and sometimes code from other files: # Path: cogspaces/datasets/contrast.py # def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): # dfs = [] # if studies == 'all': # studies = nv_ids.keys() # for study in studies: # if study not in nv_ids: # return ValueError('Wrong dataset.') # data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, # mode='download_new') # dfs.append(_assemble(data['images'], data['images_meta'], study)) # return pd.concat(dfs) # # Path: cogspaces/datasets/derivative.py # def fetch_reduced_loadings(data_dir=None, url=None, verbose=False, # resume=True): # if url is None: # url = 'http://cogspaces.github.io/assets/data/loadings/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'loadings' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = STUDY_LIST # # paths = ['data_%s.pt' % key for key in keys] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = ( # "Z-statistic loadings over a dictionary of 453 components covering " # "grey-matter `modl_atlas['components_512_gm']` " # "for 35 different task fMRI studies.") # # params['description'] = fdescr # params['data_dir'] = data_dir # # return params # # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] # # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] . Output only the next line.
loadings = fetch_reduced_loadings()
Predict the next line for this snippet: <|code_start|> def test_atlas_modl(): """Download the dataset in default directory and check success. """ atlas = fetch_atlas_modl() keys = ['components_64', 'components_128', 'components_453_gm', ] assert all(os.path.exists(atlas[key]) for key in keys) def test_fetch_mask(): <|code_end|> with the help of current file imports: import os from cogspaces.datasets import fetch_atlas_modl, fetch_mask, \ fetch_reduced_loadings, STUDY_LIST, fetch_contrasts and context from other files: # Path: cogspaces/datasets/contrast.py # def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): # dfs = [] # if studies == 'all': # studies = nv_ids.keys() # for study in studies: # if study not in nv_ids: # return ValueError('Wrong dataset.') # data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, # mode='download_new') # dfs.append(_assemble(data['images'], data['images_meta'], study)) # return pd.concat(dfs) # # Path: cogspaces/datasets/derivative.py # def fetch_reduced_loadings(data_dir=None, url=None, verbose=False, # resume=True): # if url is None: # url = 'http://cogspaces.github.io/assets/data/loadings/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'loadings' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = STUDY_LIST # # paths = ['data_%s.pt' % key for key in keys] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = ( # "Z-statistic loadings over a dictionary of 453 components covering " # "grey-matter `modl_atlas['components_512_gm']` " # "for 35 different task fMRI studies.") # # params['description'] = fdescr # params['data_dir'] = data_dir # # return params # # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] # # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] , which may contain function names, class names, or code. Output only the next line.
fetch_mask()
Given the following code snippet before the placeholder: <|code_start|> def test_atlas_modl(): """Download the dataset in default directory and check success. """ atlas = fetch_atlas_modl() keys = ['components_64', 'components_128', 'components_453_gm', ] assert all(os.path.exists(atlas[key]) for key in keys) def test_fetch_mask(): fetch_mask() def test_reduced_loadings(): loadings = fetch_reduced_loadings() <|code_end|> , predict the next line using imports from the current file: import os from cogspaces.datasets import fetch_atlas_modl, fetch_mask, \ fetch_reduced_loadings, STUDY_LIST, fetch_contrasts and context including class names, function names, and sometimes code from other files: # Path: cogspaces/datasets/contrast.py # def fetch_contrasts(studies: str or List[str] = 'all', data_dir=None): # dfs = [] # if studies == 'all': # studies = nv_ids.keys() # for study in studies: # if study not in nv_ids: # return ValueError('Wrong dataset.') # data = fetch_neurovault_ids([nv_ids[study]], data_dir=data_dir, verbose=10, # mode='download_new') # dfs.append(_assemble(data['images'], data['images_meta'], study)) # return pd.concat(dfs) # # Path: cogspaces/datasets/derivative.py # def fetch_reduced_loadings(data_dir=None, url=None, verbose=False, # resume=True): # if url is None: # url = 'http://cogspaces.github.io/assets/data/loadings/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'loadings' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = STUDY_LIST # # paths = ['data_%s.pt' % key for key in keys] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = ( # "Z-statistic loadings over a dictionary of 453 components covering " # "grey-matter `modl_atlas['components_512_gm']` " # "for 35 different task fMRI studies.") # # params['description'] = fdescr # params['data_dir'] = data_dir # # return params # # def fetch_atlas_modl(data_dir=None, # url=None, # resume=True, verbose=1): # """Download and load a multi-scale atlas computed using MODL over HCP900. # # Parameters # ---------- # data_dir: string, optional # Path of the data directory. Used to force data storage in a non- # standard location. Default: None (meaning: default) # url: string, optional # Download URL of the dataset. Overwrite the default URL. # """ # # if url is None: # url = 'http://cogspaces.github.io/assets/data/modl/' # # data_dir = get_data_dir(data_dir) # dataset_name = 'modl' # data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # # keys = ['components_64', # 'components_128', # 'components_453_gm', # 'loadings_128_gm' # ] # # paths = [ # 'components_64.nii.gz', # 'components_128.nii.gz', # 'components_453_gm.nii.gz', # 'loadings_128_gm.npy', # ] # urls = [url + path for path in paths] # files = [(path, url, {}) for path, url in zip(paths, urls)] # # files = _fetch_files(data_dir, files, resume=resume, # verbose=verbose) # # params = {key: file for key, file in zip(keys, files)} # # fdescr = 'Components computed using the MODL package, at various scale,' \ # 'from HCP900 data' # # params['description'] = fdescr # params['data_dir'] = data_dir # # return Bunch(**params) # # def fetch_mask(data_dir=None, url=None, resume=True, verbose=1): # if url is None: # url = 'http://cogspaces.github.io/assets/data/hcp_mask.nii.gz' # files = [('hcp_mask.nii.gz', url, {})] # # dataset_name = 'mask' # data_dir = get_data_dir(data_dir) # dataset_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, # verbose=verbose) # files = _fetch_files(dataset_dir, files, resume=resume, # verbose=verbose) # return files[0] # # STUDY_LIST = ['knops2009recruitment', 'ds009', 'gauthier2010resonance', # 'ds017B', 'ds110', 'vagharchakian2012temporal', 'ds001', # 'devauchelle2009sentence', 'camcan', 'archi', # 'henson2010faces', 'ds052', 'ds006A', 'ds109', 'ds108', 'la5c', # 'gauthier2009resonance', 'ds011', 'ds107', 'ds116', 'ds101', # 'ds002', 'ds003', 'ds051', 'ds008', 'pinel2009twins', 'ds017A', # 'ds105', 'ds007', 'ds005', 'amalric2012mathematicians', 'ds114', # 'brainomics', 'cauvet2009muslang', 'hcp'] . Output only the next line.
keys = STUDY_LIST
Given the code snippet: <|code_start|># # Copyright (C) 2013 Savoir-Faire Linux Inc. # # This file is part of Sageo # # Sageo is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sageo is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sageo. If not, see <http://www.gnu.org/licenses/> class FiltersManager(): """ A sort of proxy that facilitates filters usage. There is one FiltersManager per view display. """ def __init__(self): self.__filters = {} <|code_end|> , generate the next line using the imports in this file: from app.model.filters.filter import Filter from app.model.filters.filter_text import FilterText from app.model.filters.builtin import filters and context (functions, classes, or occasionally code) from other files: # Path: app/model/filters/filter.py # class Filter: # """ # Base class for all filters # """ # __metaclass__ = abc.ABCMeta # def __init__(self, name, title, descr=''): # self.name = name # self.descr = descr # self.title = title # # @abc.abstractmethod # def filter(self, value): # """ return filter string to be appended to the livestatus query """ # # @abc.abstractmethod # def get_col_def(self): # """ return list of sql_alchemy columns """ # # Path: app/model/filters/filter_text.py # class FilterText(Filter): # def __init__(self, name, title, descr, column_names, operation): # Filter.__init__(self, name, title, descr) # self.operation = operation # self.column_names = column_names # # def filter(self, column_value): # if column_value: # return "Filter: %s %s %s\n" % (self.column_names[0], self.operation, column_value) # else: # return "" # # def get_col_def(self): # return [Column(self.name, String(100), info={'label':self.title})] # # Path: app/model/filters/builtin.py # OP_EQUAL = '=' # OP_TILDE = '~~' # FILTER_HOSTREGEX = 'host_regex' # FILTER_HOST_EXACT_MATCH = 'host' # FILTER_SERVICE_EXACT_MATCH = 'service' # FILTER_HOST_STATE = 'host_state' # FILTER_SERVICE_STATE = 'service_state' # FILTER_IS_SUMMARY_HOST = 'is_summary_host' # FILTER_SITE = 'site' # FILTER_IS_HOST_ACKNOWLEDGED = 'is_host_acknowledged' # FILTER_IS_SERVICE_ACKNOWLEDGED = 'is_service_acknowledged' # FILTER_IS_HOST_IN_NOTIFICATION_PERIOD = 'is_host_in_notification_period' # FILTER_IS_SERVICE_IN_NOTIFICATION_PERIOD = 'is_service_in_notification_period' # FILTER_IS_HOST_SCHEDULED_DOWNTIME_DEPTH = 'is_host_scheduled_downtime_depth' # FILTER_IS_SERVICE_SCHEDULED_DOWNTIME_DEPTH = 'is_service_scheduled_downtime_depth' . Output only the next line.
def set_filters(self, filters):
Given the code snippet: <|code_start|> tablename = datasource["table"] add_headers += datasource.get("add_headers", "") merge_column = datasource.get("merge_by") if merge_column: columns = [merge_column] + columns # Most layouts need current state of object in order to # choose background color - even if no painter for state # is selected. Make sure those columns are fetched. This # must not be done for the table 'log' as it cannot correctly # distinguish between service_state and host_state if "log" not in datasource["infos"]: state_columns = [] if "service" in datasource["infos"]: state_columns += [ "service_has_been_checked", "service_state" ] if "host" in datasource["infos"]: state_columns += [ "host_has_been_checked", "host_state" ] for c in state_columns: if c not in columns: columns.append(c) # Remove columns which are implicitely added by the datasource if add_columns: columns = [ c for c in columns if c not in add_columns ] query = "GET %s\n" % tablename query += "Columns: %s\n" % " ".join(columns) query += add_headers query += filters_string <|code_end|> , generate the next line using the imports in this file: from app.lib.livestatusconnection import live from app.lib.datasources import multisite_datasources as datasources and context (functions, classes, or occasionally code) from other files: # Path: app/lib/livestatusconnection.py # # Path: app/lib/datasources.py . Output only the next line.
live.set_prepend_site(True)
Continue the code snippet: <|code_start|>migration = SQLALCHEMY_MIGRATE_REPO + '/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1) tmp_module = imp.new_module('old_model') old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) exec old_model in tmp_module.__dict__ <|code_end|> . Use current file imports: import imp from migrate.versioning import api from app.db_model.base import db_session, Base from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO and context (classes, functions, or code) from other files: # Path: app/db_model/base.py # def init_engine(db_uri): # def init_db(): # def create_default_users(): # def create_default_views(): # def __add_column(name, view, link=""): # def __add_sort_by(name, view, order=""): # def __add_group_by(name, view): # def clear_db(): . Output only the next line.
script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, tmp_module.meta, Base.metadata)
Given snippet: <|code_start|> context = {} host_query = \ "GET hosts\n" \ "Stats: state >= 0\n" \ "Stats: state > 0\n" \ "Stats: scheduled_downtime_depth = 0\n" \ "StatsAnd: 2\n" \ "Stats: state > 0\n" \ "Stats: scheduled_downtime_depth = 0\n" \ "Stats: acknowledged = 0\n" \ "StatsAnd: 3\n" \ "Filter: custom_variable_names < _REALNAME\n" service_query = \ "GET services\n" \ "Stats: state >= 0\n" \ "Stats: state > 0\n" \ "Stats: scheduled_downtime_depth = 0\n" \ "Stats: host_scheduled_downtime_depth = 0\n" \ "Stats: host_state = 0\n" \ "StatsAnd: 4\n" \ "Stats: state > 0\n" \ "Stats: scheduled_downtime_depth = 0\n" \ "Stats: host_scheduled_downtime_depth = 0\n" \ "Stats: acknowledged = 0\n" \ "Stats: host_state = 0\n" \ "StatsAnd: 5\n" \ "Filter: host_custom_variable_names < _REALNAME\n" context['toggle_url'] = "sidebar_openclose.py?name=%s&state=" % 'tactical_overview' <|code_end|> , continue by predicting the next line. Consider current file imports: from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Module, current_app from flask.ext.babelex import Domain, gettext, ngettext from ..snapin import SnapinBase from app.lib.livestatusconnection import live from os import path import abc and context: # Path: app/snapins/snapin.py # class SnapinBase(object): # __metaclass__ = abc.ABCMeta # title = "snapin title" # description = "snapin description" # version = "0.0" # name = "default snapin" # # @abc.abstractmethod # def context(self): # """Return some stuff to be used in the snapin template""" # return "" # # Path: app/lib/livestatusconnection.py which might include code, classes, or functions. Output only the next line.
context['hstdata'] = live.query_summed_stats(host_query)
Given snippet: <|code_start|> class Router(routers.DefaultRouter): root_view_name = "api.root" APIRootView = APIRoot router = Router() <|code_end|> , continue by predicting the next line. Consider current file imports: from rest_framework import routers from django.conf.urls import include from django.urls import re_path from .views import Actions, APIRoot, Cases, Labels, Partners and context: # Path: casepro/api/views.py # class Actions(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve an action # # Return the given case action by its id, e.g. `/api/v1/actions/123/`. # # # List actions # # Return a list of all the existing case actions ordered by last created, e.g. `/api/v1/actions/`. You can include `after` as a query parameter # to only return actions created after that time, e.g. `/api/v1/actions/?after=2017-12-18T00:57:59.217099Z`. # """ # # queryset = CaseAction.objects.all() # pagination_class = CreatedOnCursorPagination # serializer_class = CaseActionSerializer # # def get_queryset(self): # qs = super().get_queryset().filter(org=self.request.org).select_related("case", "label", "assignee") # # after = self.request.query_params.get("after") # if after: # qs = qs.filter(created_on__gt=iso8601.parse_date(after)) # # return qs # # class APIRoot(routers.APIRootView): # """ # This is a REST API which provides read-access to your organization's data. # # # Authentication # # The API uses standard token authentication. Each user has a token and if you are logged in, you will see your token # at the top of this page. That token should be sent as an `Authorization` header in each request, # e.g. `Authorization: Token 1234567890`. # # # Pagination # # The API uses cursor pagination for endpoints which can return multiple objects. Each request returns a `next` field # which provides the URL which should be used to request the next page of results. If there are no more results, then # the URL will be `null`. # # Below are the endpoints available in the API: # """ # # name = _("API v1") # # class Cases(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a case # # Return the given case by its id, e.g. `/api/v1/cases/123/`. # # # List cases # # Return a list of all the existing cases ordered by last opened, e.g. `/api/v1/cases/`. # """ # # class OpenedOnCursorPagination(pagination.CursorPagination): # ordering = ("-opened_on",) # # queryset = Case.objects.all() # pagination_class = OpenedOnCursorPagination # serializer_class = CaseSerializer # # def get_queryset(self): # return ( # super() # .get_queryset() # .filter(org=self.request.org) # .select_related("assignee", "contact", "initial_message") # .prefetch_related("labels") # ) # # class Labels(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a label # # Return the given label by its id, e.g. `/api/v1/labels/123/`. # # # List labels # # Return a list of all the existing labels, e.g. `/api/v1/labels/`. # """ # # queryset = Label.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = LabelSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org) # # class Partners(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a partner # # Return the given partner organization by its id, e.g. `/api/v1/partners/123/`. # # # List partners # # Return a list of all the existing partner organizations, e.g. `/api/v1/partners/`. # """ # # queryset = Partner.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = PartnerSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org).prefetch_related("labels") which might include code, classes, or functions. Output only the next line.
router.register("actions", Actions, basename="api.action")
Given snippet: <|code_start|> class Router(routers.DefaultRouter): root_view_name = "api.root" APIRootView = APIRoot router = Router() router.register("actions", Actions, basename="api.action") <|code_end|> , continue by predicting the next line. Consider current file imports: from rest_framework import routers from django.conf.urls import include from django.urls import re_path from .views import Actions, APIRoot, Cases, Labels, Partners and context: # Path: casepro/api/views.py # class Actions(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve an action # # Return the given case action by its id, e.g. `/api/v1/actions/123/`. # # # List actions # # Return a list of all the existing case actions ordered by last created, e.g. `/api/v1/actions/`. You can include `after` as a query parameter # to only return actions created after that time, e.g. `/api/v1/actions/?after=2017-12-18T00:57:59.217099Z`. # """ # # queryset = CaseAction.objects.all() # pagination_class = CreatedOnCursorPagination # serializer_class = CaseActionSerializer # # def get_queryset(self): # qs = super().get_queryset().filter(org=self.request.org).select_related("case", "label", "assignee") # # after = self.request.query_params.get("after") # if after: # qs = qs.filter(created_on__gt=iso8601.parse_date(after)) # # return qs # # class APIRoot(routers.APIRootView): # """ # This is a REST API which provides read-access to your organization's data. # # # Authentication # # The API uses standard token authentication. Each user has a token and if you are logged in, you will see your token # at the top of this page. That token should be sent as an `Authorization` header in each request, # e.g. `Authorization: Token 1234567890`. # # # Pagination # # The API uses cursor pagination for endpoints which can return multiple objects. Each request returns a `next` field # which provides the URL which should be used to request the next page of results. If there are no more results, then # the URL will be `null`. # # Below are the endpoints available in the API: # """ # # name = _("API v1") # # class Cases(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a case # # Return the given case by its id, e.g. `/api/v1/cases/123/`. # # # List cases # # Return a list of all the existing cases ordered by last opened, e.g. `/api/v1/cases/`. # """ # # class OpenedOnCursorPagination(pagination.CursorPagination): # ordering = ("-opened_on",) # # queryset = Case.objects.all() # pagination_class = OpenedOnCursorPagination # serializer_class = CaseSerializer # # def get_queryset(self): # return ( # super() # .get_queryset() # .filter(org=self.request.org) # .select_related("assignee", "contact", "initial_message") # .prefetch_related("labels") # ) # # class Labels(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a label # # Return the given label by its id, e.g. `/api/v1/labels/123/`. # # # List labels # # Return a list of all the existing labels, e.g. `/api/v1/labels/`. # """ # # queryset = Label.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = LabelSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org) # # class Partners(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a partner # # Return the given partner organization by its id, e.g. `/api/v1/partners/123/`. # # # List partners # # Return a list of all the existing partner organizations, e.g. `/api/v1/partners/`. # """ # # queryset = Partner.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = PartnerSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org).prefetch_related("labels") which might include code, classes, or functions. Output only the next line.
router.register("cases", Cases, basename="api.case")
Predict the next line after this snippet: <|code_start|> class Router(routers.DefaultRouter): root_view_name = "api.root" APIRootView = APIRoot router = Router() router.register("actions", Actions, basename="api.action") router.register("cases", Cases, basename="api.case") <|code_end|> using the current file's imports: from rest_framework import routers from django.conf.urls import include from django.urls import re_path from .views import Actions, APIRoot, Cases, Labels, Partners and any relevant context from other files: # Path: casepro/api/views.py # class Actions(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve an action # # Return the given case action by its id, e.g. `/api/v1/actions/123/`. # # # List actions # # Return a list of all the existing case actions ordered by last created, e.g. `/api/v1/actions/`. You can include `after` as a query parameter # to only return actions created after that time, e.g. `/api/v1/actions/?after=2017-12-18T00:57:59.217099Z`. # """ # # queryset = CaseAction.objects.all() # pagination_class = CreatedOnCursorPagination # serializer_class = CaseActionSerializer # # def get_queryset(self): # qs = super().get_queryset().filter(org=self.request.org).select_related("case", "label", "assignee") # # after = self.request.query_params.get("after") # if after: # qs = qs.filter(created_on__gt=iso8601.parse_date(after)) # # return qs # # class APIRoot(routers.APIRootView): # """ # This is a REST API which provides read-access to your organization's data. # # # Authentication # # The API uses standard token authentication. Each user has a token and if you are logged in, you will see your token # at the top of this page. That token should be sent as an `Authorization` header in each request, # e.g. `Authorization: Token 1234567890`. # # # Pagination # # The API uses cursor pagination for endpoints which can return multiple objects. Each request returns a `next` field # which provides the URL which should be used to request the next page of results. If there are no more results, then # the URL will be `null`. # # Below are the endpoints available in the API: # """ # # name = _("API v1") # # class Cases(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a case # # Return the given case by its id, e.g. `/api/v1/cases/123/`. # # # List cases # # Return a list of all the existing cases ordered by last opened, e.g. `/api/v1/cases/`. # """ # # class OpenedOnCursorPagination(pagination.CursorPagination): # ordering = ("-opened_on",) # # queryset = Case.objects.all() # pagination_class = OpenedOnCursorPagination # serializer_class = CaseSerializer # # def get_queryset(self): # return ( # super() # .get_queryset() # .filter(org=self.request.org) # .select_related("assignee", "contact", "initial_message") # .prefetch_related("labels") # ) # # class Labels(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a label # # Return the given label by its id, e.g. `/api/v1/labels/123/`. # # # List labels # # Return a list of all the existing labels, e.g. `/api/v1/labels/`. # """ # # queryset = Label.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = LabelSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org) # # class Partners(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a partner # # Return the given partner organization by its id, e.g. `/api/v1/partners/123/`. # # # List partners # # Return a list of all the existing partner organizations, e.g. `/api/v1/partners/`. # """ # # queryset = Partner.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = PartnerSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org).prefetch_related("labels") . Output only the next line.
router.register("labels", Labels, basename="api.label")
Here is a snippet: <|code_start|> class Router(routers.DefaultRouter): root_view_name = "api.root" APIRootView = APIRoot router = Router() router.register("actions", Actions, basename="api.action") router.register("cases", Cases, basename="api.case") router.register("labels", Labels, basename="api.label") <|code_end|> . Write the next line using the current file imports: from rest_framework import routers from django.conf.urls import include from django.urls import re_path from .views import Actions, APIRoot, Cases, Labels, Partners and context from other files: # Path: casepro/api/views.py # class Actions(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve an action # # Return the given case action by its id, e.g. `/api/v1/actions/123/`. # # # List actions # # Return a list of all the existing case actions ordered by last created, e.g. `/api/v1/actions/`. You can include `after` as a query parameter # to only return actions created after that time, e.g. `/api/v1/actions/?after=2017-12-18T00:57:59.217099Z`. # """ # # queryset = CaseAction.objects.all() # pagination_class = CreatedOnCursorPagination # serializer_class = CaseActionSerializer # # def get_queryset(self): # qs = super().get_queryset().filter(org=self.request.org).select_related("case", "label", "assignee") # # after = self.request.query_params.get("after") # if after: # qs = qs.filter(created_on__gt=iso8601.parse_date(after)) # # return qs # # class APIRoot(routers.APIRootView): # """ # This is a REST API which provides read-access to your organization's data. # # # Authentication # # The API uses standard token authentication. Each user has a token and if you are logged in, you will see your token # at the top of this page. That token should be sent as an `Authorization` header in each request, # e.g. `Authorization: Token 1234567890`. # # # Pagination # # The API uses cursor pagination for endpoints which can return multiple objects. Each request returns a `next` field # which provides the URL which should be used to request the next page of results. If there are no more results, then # the URL will be `null`. # # Below are the endpoints available in the API: # """ # # name = _("API v1") # # class Cases(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a case # # Return the given case by its id, e.g. `/api/v1/cases/123/`. # # # List cases # # Return a list of all the existing cases ordered by last opened, e.g. `/api/v1/cases/`. # """ # # class OpenedOnCursorPagination(pagination.CursorPagination): # ordering = ("-opened_on",) # # queryset = Case.objects.all() # pagination_class = OpenedOnCursorPagination # serializer_class = CaseSerializer # # def get_queryset(self): # return ( # super() # .get_queryset() # .filter(org=self.request.org) # .select_related("assignee", "contact", "initial_message") # .prefetch_related("labels") # ) # # class Labels(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a label # # Return the given label by its id, e.g. `/api/v1/labels/123/`. # # # List labels # # Return a list of all the existing labels, e.g. `/api/v1/labels/`. # """ # # queryset = Label.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = LabelSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org) # # class Partners(viewsets.ReadOnlyModelViewSet): # """ # # Retrieve a partner # # Return the given partner organization by its id, e.g. `/api/v1/partners/123/`. # # # List partners # # Return a list of all the existing partner organizations, e.g. `/api/v1/partners/`. # """ # # queryset = Partner.objects.filter(is_active=True) # pagination_class = IdCursorPagination # serializer_class = PartnerSerializer # # def get_queryset(self): # return super().get_queryset().filter(org=self.request.org).prefetch_related("labels") , which may include functions, classes, or code. Output only the next line.
router.register("partners", Partners, basename="api.partner")
Given the code snippet: <|code_start|> cleaned_data = super(UserForm, self).clean() # if a user is updating their own password, need to provide current password new_password = cleaned_data.get("new_password") if new_password and self.instance == self.user: current_password = cleaned_data.get("current_password", "") if not self.instance.check_password(current_password): self.add_error("current_password", _("Please enter your current password.")) # if creating new user with password or updating password of existing user, confirmation must match password = cleaned_data.get("password") or cleaned_data.get("new_password") if password: confirm_password = cleaned_data.get("confirm_password", "") if password != confirm_password: self.add_error("confirm_password", _("Passwords don't match.")) return cleaned_data class Meta: model = User exclude = () class OrgUserForm(UserForm): """ Form for user editing at org-level """ role = forms.ChoiceField(label=_("Role"), choices=ROLE_ORG_CHOICES, required=True) <|code_end|> , generate the next line using the imports in this file: from django import forms from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.utils.translation import gettext_lazy as _ from casepro.cases.models import Partner from .models import PARTNER_ROLES, ROLE_ORG_CHOICES, ROLE_PARTNER_CHOICES and context (functions, classes, or occasionally code) from other files: # Path: casepro/cases/models.py # class Partner(models.Model): # """ # Corresponds to a partner organization # """ # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="partners", on_delete=models.PROTECT) # # name = models.CharField(verbose_name=_("Name"), max_length=128, help_text=_("Name of this partner organization")) # # description = models.CharField(verbose_name=_("Description"), null=True, blank=True, max_length=255) # # primary_contact = models.ForeignKey( # User, # verbose_name=_("Primary Contact"), # related_name="partners_primary", # null=True, # blank=True, # on_delete=models.PROTECT, # ) # # is_restricted = models.BooleanField( # default=True, # verbose_name=_("Restricted Access"), # help_text=_("Whether this partner's access is restricted by labels"), # ) # # labels = models.ManyToManyField( # Label, verbose_name=_("Labels"), related_name="partners", help_text=_("Labels that this partner can access") # ) # # users = models.ManyToManyField(User, related_name="partners", help_text=_("Users that belong to this partner")) # # logo = models.ImageField(verbose_name=_("Logo"), upload_to="partner_logos", null=True, blank=True) # # is_active = models.BooleanField(default=True, help_text="Whether this partner is active") # # @classmethod # def create(cls, org, name, description, primary_contact, restricted, labels, logo=None): # if labels and not restricted: # raise ValueError("Can't specify labels for a partner which is not restricted") # # partner = cls.objects.create( # org=org, # name=name, # description=description, # primary_contact=primary_contact, # logo=logo, # is_restricted=restricted, # ) # # if restricted: # partner.labels.add(*labels) # # return partner # # @classmethod # def get_all(cls, org): # return cls.objects.filter(org=org, is_active=True) # # def get_labels(self): # return self.labels.filter(is_active=True) if self.is_restricted else Label.get_all(self.org) # # def get_users(self): # return self.users.all() # # def get_managers(self): # return self.get_users().filter(org_editors=self.org_id) # # def get_analysts(self): # return self.get_users().filter(org_viewers=self.org_id) # # def release(self): # self.is_active = False # self.save(update_fields=("is_active",)) # # def as_json(self, full=True): # result = {"id": self.pk, "name": self.name} # # if full: # result["restricted"] = self.is_restricted # # return result # # def __str__(self): # return self.name # # Path: casepro/profiles/models.py # PARTNER_ROLES = {ROLE_MANAGER, ROLE_ANALYST} # roles that are tied to a partner # # ROLE_ORG_CHOICES = ( # (ROLE_ADMIN, _("Administrator")), # (ROLE_MANAGER, _("Partner Manager")), # (ROLE_ANALYST, _("Partner Data Analyst")), # ) # # ROLE_PARTNER_CHOICES = ((ROLE_MANAGER, _("Manager")), (ROLE_ANALYST, _("Data Analyst"))) . Output only the next line.
partner = forms.ModelChoiceField(label=_("Partner Organization"), queryset=Partner.objects.none(), required=False)
Based on the snippet: <|code_start|> password = cleaned_data.get("password") or cleaned_data.get("new_password") if password: confirm_password = cleaned_data.get("confirm_password", "") if password != confirm_password: self.add_error("confirm_password", _("Passwords don't match.")) return cleaned_data class Meta: model = User exclude = () class OrgUserForm(UserForm): """ Form for user editing at org-level """ role = forms.ChoiceField(label=_("Role"), choices=ROLE_ORG_CHOICES, required=True) partner = forms.ModelChoiceField(label=_("Partner Organization"), queryset=Partner.objects.none(), required=False) def __init__(self, *args, **kwargs): super(OrgUserForm, self).__init__(*args, **kwargs) self.fields["partner"].queryset = Partner.get_all(self.org).order_by("name") def clean(self): cleaned_data = super(OrgUserForm, self).clean() <|code_end|> , predict the immediate next line with the help of imports: from django import forms from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.utils.translation import gettext_lazy as _ from casepro.cases.models import Partner from .models import PARTNER_ROLES, ROLE_ORG_CHOICES, ROLE_PARTNER_CHOICES and context (classes, functions, sometimes code) from other files: # Path: casepro/cases/models.py # class Partner(models.Model): # """ # Corresponds to a partner organization # """ # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="partners", on_delete=models.PROTECT) # # name = models.CharField(verbose_name=_("Name"), max_length=128, help_text=_("Name of this partner organization")) # # description = models.CharField(verbose_name=_("Description"), null=True, blank=True, max_length=255) # # primary_contact = models.ForeignKey( # User, # verbose_name=_("Primary Contact"), # related_name="partners_primary", # null=True, # blank=True, # on_delete=models.PROTECT, # ) # # is_restricted = models.BooleanField( # default=True, # verbose_name=_("Restricted Access"), # help_text=_("Whether this partner's access is restricted by labels"), # ) # # labels = models.ManyToManyField( # Label, verbose_name=_("Labels"), related_name="partners", help_text=_("Labels that this partner can access") # ) # # users = models.ManyToManyField(User, related_name="partners", help_text=_("Users that belong to this partner")) # # logo = models.ImageField(verbose_name=_("Logo"), upload_to="partner_logos", null=True, blank=True) # # is_active = models.BooleanField(default=True, help_text="Whether this partner is active") # # @classmethod # def create(cls, org, name, description, primary_contact, restricted, labels, logo=None): # if labels and not restricted: # raise ValueError("Can't specify labels for a partner which is not restricted") # # partner = cls.objects.create( # org=org, # name=name, # description=description, # primary_contact=primary_contact, # logo=logo, # is_restricted=restricted, # ) # # if restricted: # partner.labels.add(*labels) # # return partner # # @classmethod # def get_all(cls, org): # return cls.objects.filter(org=org, is_active=True) # # def get_labels(self): # return self.labels.filter(is_active=True) if self.is_restricted else Label.get_all(self.org) # # def get_users(self): # return self.users.all() # # def get_managers(self): # return self.get_users().filter(org_editors=self.org_id) # # def get_analysts(self): # return self.get_users().filter(org_viewers=self.org_id) # # def release(self): # self.is_active = False # self.save(update_fields=("is_active",)) # # def as_json(self, full=True): # result = {"id": self.pk, "name": self.name} # # if full: # result["restricted"] = self.is_restricted # # return result # # def __str__(self): # return self.name # # Path: casepro/profiles/models.py # PARTNER_ROLES = {ROLE_MANAGER, ROLE_ANALYST} # roles that are tied to a partner # # ROLE_ORG_CHOICES = ( # (ROLE_ADMIN, _("Administrator")), # (ROLE_MANAGER, _("Partner Manager")), # (ROLE_ANALYST, _("Partner Data Analyst")), # ) # # ROLE_PARTNER_CHOICES = ((ROLE_MANAGER, _("Manager")), (ROLE_ANALYST, _("Data Analyst"))) . Output only the next line.
if cleaned_data.get("role") in PARTNER_ROLES and not cleaned_data.get("partner"):
Here is a snippet: <|code_start|> def clean(self): cleaned_data = super(UserForm, self).clean() # if a user is updating their own password, need to provide current password new_password = cleaned_data.get("new_password") if new_password and self.instance == self.user: current_password = cleaned_data.get("current_password", "") if not self.instance.check_password(current_password): self.add_error("current_password", _("Please enter your current password.")) # if creating new user with password or updating password of existing user, confirmation must match password = cleaned_data.get("password") or cleaned_data.get("new_password") if password: confirm_password = cleaned_data.get("confirm_password", "") if password != confirm_password: self.add_error("confirm_password", _("Passwords don't match.")) return cleaned_data class Meta: model = User exclude = () class OrgUserForm(UserForm): """ Form for user editing at org-level """ <|code_end|> . Write the next line using the current file imports: from django import forms from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.utils.translation import gettext_lazy as _ from casepro.cases.models import Partner from .models import PARTNER_ROLES, ROLE_ORG_CHOICES, ROLE_PARTNER_CHOICES and context from other files: # Path: casepro/cases/models.py # class Partner(models.Model): # """ # Corresponds to a partner organization # """ # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="partners", on_delete=models.PROTECT) # # name = models.CharField(verbose_name=_("Name"), max_length=128, help_text=_("Name of this partner organization")) # # description = models.CharField(verbose_name=_("Description"), null=True, blank=True, max_length=255) # # primary_contact = models.ForeignKey( # User, # verbose_name=_("Primary Contact"), # related_name="partners_primary", # null=True, # blank=True, # on_delete=models.PROTECT, # ) # # is_restricted = models.BooleanField( # default=True, # verbose_name=_("Restricted Access"), # help_text=_("Whether this partner's access is restricted by labels"), # ) # # labels = models.ManyToManyField( # Label, verbose_name=_("Labels"), related_name="partners", help_text=_("Labels that this partner can access") # ) # # users = models.ManyToManyField(User, related_name="partners", help_text=_("Users that belong to this partner")) # # logo = models.ImageField(verbose_name=_("Logo"), upload_to="partner_logos", null=True, blank=True) # # is_active = models.BooleanField(default=True, help_text="Whether this partner is active") # # @classmethod # def create(cls, org, name, description, primary_contact, restricted, labels, logo=None): # if labels and not restricted: # raise ValueError("Can't specify labels for a partner which is not restricted") # # partner = cls.objects.create( # org=org, # name=name, # description=description, # primary_contact=primary_contact, # logo=logo, # is_restricted=restricted, # ) # # if restricted: # partner.labels.add(*labels) # # return partner # # @classmethod # def get_all(cls, org): # return cls.objects.filter(org=org, is_active=True) # # def get_labels(self): # return self.labels.filter(is_active=True) if self.is_restricted else Label.get_all(self.org) # # def get_users(self): # return self.users.all() # # def get_managers(self): # return self.get_users().filter(org_editors=self.org_id) # # def get_analysts(self): # return self.get_users().filter(org_viewers=self.org_id) # # def release(self): # self.is_active = False # self.save(update_fields=("is_active",)) # # def as_json(self, full=True): # result = {"id": self.pk, "name": self.name} # # if full: # result["restricted"] = self.is_restricted # # return result # # def __str__(self): # return self.name # # Path: casepro/profiles/models.py # PARTNER_ROLES = {ROLE_MANAGER, ROLE_ANALYST} # roles that are tied to a partner # # ROLE_ORG_CHOICES = ( # (ROLE_ADMIN, _("Administrator")), # (ROLE_MANAGER, _("Partner Manager")), # (ROLE_ANALYST, _("Partner Data Analyst")), # ) # # ROLE_PARTNER_CHOICES = ((ROLE_MANAGER, _("Manager")), (ROLE_ANALYST, _("Data Analyst"))) , which may include functions, classes, or code. Output only the next line.
role = forms.ChoiceField(label=_("Role"), choices=ROLE_ORG_CHOICES, required=True)
Next line prediction: <|code_start|> model = User exclude = () class OrgUserForm(UserForm): """ Form for user editing at org-level """ role = forms.ChoiceField(label=_("Role"), choices=ROLE_ORG_CHOICES, required=True) partner = forms.ModelChoiceField(label=_("Partner Organization"), queryset=Partner.objects.none(), required=False) def __init__(self, *args, **kwargs): super(OrgUserForm, self).__init__(*args, **kwargs) self.fields["partner"].queryset = Partner.get_all(self.org).order_by("name") def clean(self): cleaned_data = super(OrgUserForm, self).clean() if cleaned_data.get("role") in PARTNER_ROLES and not cleaned_data.get("partner"): self.add_error("partner", _("Required for role.")) class PartnerUserForm(UserForm): """ Form for user editing at partner-level """ <|code_end|> . Use current file imports: (from django import forms from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.utils.translation import gettext_lazy as _ from casepro.cases.models import Partner from .models import PARTNER_ROLES, ROLE_ORG_CHOICES, ROLE_PARTNER_CHOICES) and context including class names, function names, or small code snippets from other files: # Path: casepro/cases/models.py # class Partner(models.Model): # """ # Corresponds to a partner organization # """ # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="partners", on_delete=models.PROTECT) # # name = models.CharField(verbose_name=_("Name"), max_length=128, help_text=_("Name of this partner organization")) # # description = models.CharField(verbose_name=_("Description"), null=True, blank=True, max_length=255) # # primary_contact = models.ForeignKey( # User, # verbose_name=_("Primary Contact"), # related_name="partners_primary", # null=True, # blank=True, # on_delete=models.PROTECT, # ) # # is_restricted = models.BooleanField( # default=True, # verbose_name=_("Restricted Access"), # help_text=_("Whether this partner's access is restricted by labels"), # ) # # labels = models.ManyToManyField( # Label, verbose_name=_("Labels"), related_name="partners", help_text=_("Labels that this partner can access") # ) # # users = models.ManyToManyField(User, related_name="partners", help_text=_("Users that belong to this partner")) # # logo = models.ImageField(verbose_name=_("Logo"), upload_to="partner_logos", null=True, blank=True) # # is_active = models.BooleanField(default=True, help_text="Whether this partner is active") # # @classmethod # def create(cls, org, name, description, primary_contact, restricted, labels, logo=None): # if labels and not restricted: # raise ValueError("Can't specify labels for a partner which is not restricted") # # partner = cls.objects.create( # org=org, # name=name, # description=description, # primary_contact=primary_contact, # logo=logo, # is_restricted=restricted, # ) # # if restricted: # partner.labels.add(*labels) # # return partner # # @classmethod # def get_all(cls, org): # return cls.objects.filter(org=org, is_active=True) # # def get_labels(self): # return self.labels.filter(is_active=True) if self.is_restricted else Label.get_all(self.org) # # def get_users(self): # return self.users.all() # # def get_managers(self): # return self.get_users().filter(org_editors=self.org_id) # # def get_analysts(self): # return self.get_users().filter(org_viewers=self.org_id) # # def release(self): # self.is_active = False # self.save(update_fields=("is_active",)) # # def as_json(self, full=True): # result = {"id": self.pk, "name": self.name} # # if full: # result["restricted"] = self.is_restricted # # return result # # def __str__(self): # return self.name # # Path: casepro/profiles/models.py # PARTNER_ROLES = {ROLE_MANAGER, ROLE_ANALYST} # roles that are tied to a partner # # ROLE_ORG_CHOICES = ( # (ROLE_ADMIN, _("Administrator")), # (ROLE_MANAGER, _("Partner Manager")), # (ROLE_ANALYST, _("Partner Data Analyst")), # ) # # ROLE_PARTNER_CHOICES = ((ROLE_MANAGER, _("Manager")), (ROLE_ANALYST, _("Data Analyst"))) . Output only the next line.
role = forms.ChoiceField(label=_("Role"), choices=ROLE_PARTNER_CHOICES, required=True)
Predict the next line for this snippet: <|code_start|> widget=forms.Textarea, help_text=_("Banner text displayed to all users"), required=False, ) contact_fields = forms.MultipleChoiceField( choices=(), label=_("Contact fields"), help_text=_("Contact fields to display"), required=False ) suspend_groups = forms.MultipleChoiceField( choices=(), label=_("Suspend groups"), help_text=_("Groups to remove contacts from when creating cases"), required=False, ) followup_flow = forms.ChoiceField( choices=(), label=_("Follow-up Flow"), help_text=_("Flow to start after a case is closed"), required=False, ) def __init__(self, *args, **kwargs): org = kwargs.pop("org") super(OrgEditForm, self).__init__(*args, **kwargs) self.fields["banner_text"].initial = org.get_banner_text() field_choices = [] <|code_end|> with the help of current file imports: from dash.orgs.models import Org from timezone_field import TimeZoneFormField from django import forms from django.conf import settings from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from casepro.contacts.models import Field, Group and context from other files: # Path: casepro/contacts/models.py # class Field(models.Model): # """ # A custom contact field in RapidPro # """ # # TYPE_TEXT = "T" # TYPE_DECIMAL = "N" # TYPE_DATETIME = "D" # TYPE_STATE = "S" # TYPE_DISTRICT = "I" # # TEMBA_TYPES = { # "text": TYPE_TEXT, # "numeric": TYPE_DECIMAL, # "datetime": TYPE_DATETIME, # "state": TYPE_STATE, # "district": TYPE_DISTRICT, # } # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="fields", on_delete=models.PROTECT) # # key = models.CharField(verbose_name=_("Key"), max_length=36) # # label = models.CharField(verbose_name=_("Label"), max_length=36, null=True) # # value_type = models.CharField(verbose_name=_("Value data type"), max_length=1, default=TYPE_TEXT) # # is_active = models.BooleanField(default=True, help_text="Whether this field is active") # # is_visible = models.BooleanField(default=False, help_text=_("Whether this field is visible to partner users")) # # @classmethod # def get_all(cls, org, visible=None): # qs = cls.objects.filter(org=org, is_active=True) # if visible is not None: # qs = qs.filter(is_visible=visible) # return qs # # @classmethod # def lock(cls, org, key): # return get_redis_connection().lock(FIELD_LOCK_KEY % (org.pk, key), timeout=60) # # def __str__(self): # return self.key # # def as_json(self): # """ # Prepares a contact for JSON serialization # """ # return {"key": self.key, "label": self.label, "value_type": self.value_type} # # class Meta: # unique_together = ("org", "key") # # class Group(models.Model): # """ # A contact group in RapidPro # """ # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="groups", on_delete=models.PROTECT) # # uuid = models.CharField(max_length=36, unique=True) # # name = models.CharField(max_length=64) # # count = models.IntegerField(null=True) # # is_dynamic = models.BooleanField(default=False, help_text=_("Whether this group is dynamic")) # # created_on = models.DateTimeField(auto_now_add=True, help_text=_("When this group was created")) # # is_active = models.BooleanField(default=True, help_text=_("Whether this group is active")) # # is_visible = models.BooleanField(default=False, help_text=_("Whether this group is visible to partner users")) # # suspend_from = models.BooleanField( # default=False, help_text=_("Whether contacts should be suspended from this group during a case") # ) # # @classmethod # def get_all(cls, org, visible=None, dynamic=None): # qs = cls.objects.filter(org=org, is_active=True) # # if visible is not None: # qs = qs.filter(is_visible=visible) # if dynamic is not None: # qs = qs.filter(is_dynamic=dynamic) # # return qs # # @classmethod # def get_suspend_from(cls, org): # return cls.get_all(org, dynamic=False).filter(suspend_from=True) # # @classmethod # def lock(cls, org, uuid): # return get_redis_connection().lock(GROUP_LOCK_KEY % (org.pk, uuid), timeout=60) # # def as_json(self, full=True): # if full: # return {"id": self.pk, "name": self.name, "count": self.count, "is_dynamic": self.is_dynamic} # else: # return {"id": self.pk, "name": self.name} # # def __str__(self): # return self.name , which may contain function names, class names, or code. Output only the next line.
for field in Field.objects.filter(org=org, is_active=True).order_by("label"):
Predict the next line after this snippet: <|code_start|> ) suspend_groups = forms.MultipleChoiceField( choices=(), label=_("Suspend groups"), help_text=_("Groups to remove contacts from when creating cases"), required=False, ) followup_flow = forms.ChoiceField( choices=(), label=_("Follow-up Flow"), help_text=_("Flow to start after a case is closed"), required=False, ) def __init__(self, *args, **kwargs): org = kwargs.pop("org") super(OrgEditForm, self).__init__(*args, **kwargs) self.fields["banner_text"].initial = org.get_banner_text() field_choices = [] for field in Field.objects.filter(org=org, is_active=True).order_by("label"): field_choices.append((field.pk, "%s (%s)" % (field.label, field.key))) self.fields["contact_fields"].choices = field_choices self.fields["contact_fields"].initial = [f.pk for f in Field.get_all(org, visible=True)] group_choices = [] <|code_end|> using the current file's imports: from dash.orgs.models import Org from timezone_field import TimeZoneFormField from django import forms from django.conf import settings from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from casepro.contacts.models import Field, Group and any relevant context from other files: # Path: casepro/contacts/models.py # class Field(models.Model): # """ # A custom contact field in RapidPro # """ # # TYPE_TEXT = "T" # TYPE_DECIMAL = "N" # TYPE_DATETIME = "D" # TYPE_STATE = "S" # TYPE_DISTRICT = "I" # # TEMBA_TYPES = { # "text": TYPE_TEXT, # "numeric": TYPE_DECIMAL, # "datetime": TYPE_DATETIME, # "state": TYPE_STATE, # "district": TYPE_DISTRICT, # } # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="fields", on_delete=models.PROTECT) # # key = models.CharField(verbose_name=_("Key"), max_length=36) # # label = models.CharField(verbose_name=_("Label"), max_length=36, null=True) # # value_type = models.CharField(verbose_name=_("Value data type"), max_length=1, default=TYPE_TEXT) # # is_active = models.BooleanField(default=True, help_text="Whether this field is active") # # is_visible = models.BooleanField(default=False, help_text=_("Whether this field is visible to partner users")) # # @classmethod # def get_all(cls, org, visible=None): # qs = cls.objects.filter(org=org, is_active=True) # if visible is not None: # qs = qs.filter(is_visible=visible) # return qs # # @classmethod # def lock(cls, org, key): # return get_redis_connection().lock(FIELD_LOCK_KEY % (org.pk, key), timeout=60) # # def __str__(self): # return self.key # # def as_json(self): # """ # Prepares a contact for JSON serialization # """ # return {"key": self.key, "label": self.label, "value_type": self.value_type} # # class Meta: # unique_together = ("org", "key") # # class Group(models.Model): # """ # A contact group in RapidPro # """ # # org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="groups", on_delete=models.PROTECT) # # uuid = models.CharField(max_length=36, unique=True) # # name = models.CharField(max_length=64) # # count = models.IntegerField(null=True) # # is_dynamic = models.BooleanField(default=False, help_text=_("Whether this group is dynamic")) # # created_on = models.DateTimeField(auto_now_add=True, help_text=_("When this group was created")) # # is_active = models.BooleanField(default=True, help_text=_("Whether this group is active")) # # is_visible = models.BooleanField(default=False, help_text=_("Whether this group is visible to partner users")) # # suspend_from = models.BooleanField( # default=False, help_text=_("Whether contacts should be suspended from this group during a case") # ) # # @classmethod # def get_all(cls, org, visible=None, dynamic=None): # qs = cls.objects.filter(org=org, is_active=True) # # if visible is not None: # qs = qs.filter(is_visible=visible) # if dynamic is not None: # qs = qs.filter(is_dynamic=dynamic) # # return qs # # @classmethod # def get_suspend_from(cls, org): # return cls.get_all(org, dynamic=False).filter(suspend_from=True) # # @classmethod # def lock(cls, org, uuid): # return get_redis_connection().lock(GROUP_LOCK_KEY % (org.pk, uuid), timeout=60) # # def as_json(self, full=True): # if full: # return {"id": self.pk, "name": self.name, "count": self.count, "is_dynamic": self.is_dynamic} # else: # return {"id": self.pk, "name": self.name} # # def __str__(self): # return self.name . Output only the next line.
for group in Group.get_all(org, dynamic=False).order_by("name"):
Using the snippet: <|code_start|> urlpatterns = DailyCountExportCRUDL().as_urlpatterns() urlpatterns += [ re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"), re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="statistics.replies_chart"), re_path(r"^labels_pie_chart/$", MostUsedLabelsChart.as_view(), name="statistics.labels_pie_chart"), re_path(r"^cases_opened_chart/$", CasesOpenedPerMonthChart.as_view(), name="statistics.cases_opened_chart"), <|code_end|> , determine the next line of code. You have imports: from django.urls import re_path from .views import ( CasesClosedPerMonthChart, CasesOpenedPerMonthChart, DailyCountExportCRUDL, IncomingPerDayChart, MostUsedLabelsChart, RepliesPerMonthChart, ) and context (class names, function names, or code) available: # Path: casepro/statistics/views.py # class CasesClosedPerMonthChart(BasePerMonthChart): # """ # Chart of cases closed per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_CLOSED, since).month_totals() # # class CasesOpenedPerMonthChart(BasePerMonthChart): # """ # Chart of cases opened per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_OPENED, since).month_totals() # # class DailyCountExportCRUDL(SmartCRUDL): # model = DailyCountExport # actions = ("create", "read") # # class Create(NonAtomicMixin, OrgPermsMixin, SmartCreateView): # def post(self, request, *args, **kwargs): # of_type = request.json["type"] # # # parse dates and adjust max so it's exclusive # after = parse_iso8601(request.json["after"]).date() # before = parse_iso8601(request.json["before"]).date() + timedelta(days=1) # # export = DailyCountExport.create(self.request.org, self.request.user, of_type, after, before) # # daily_count_export.delay(export.pk) # # return JsonResponse({"export_id": export.pk}) # # class Read(BaseDownloadView): # title = _("Download Export") # filename = "daily_count_export.xls" # # class IncomingPerDayChart(BasePerDayChart): # """ # Chart of incoming per day for either the current org or a given label # """ # # def get_day_totals(self, request, since): # label_id = request.GET.get("label") # # if label_id: # label = Label.get_all(org=request.org).get(pk=label_id) # return DailyCount.get_by_label([label], DailyCount.TYPE_INCOMING, since).day_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_INCOMING, since).day_totals() # # class MostUsedLabelsChart(BaseChart): # """ # Pie chart of top 10 labels used in last 30 days # """ # # num_items = 10 # num_days = 30 # # def get_data(self, request): # since = timezone.now() - relativedelta(days=self.num_days) # labels = Label.get_all(request.org, request.user) # # counts_by_label = DailyCount.get_by_label(labels, DailyCount.TYPE_INCOMING, since).scope_totals() # # # sort by highest count DESC, label name ASC # by_usage = sorted(counts_by_label.items(), key=lambda c: (-c[1], c[0].name)) # by_usage = [c for c in by_usage if c[1]] # remove zero counts # # if len(by_usage) > self.num_items: # label_zones = by_usage[: self.num_items - 1] # others = by_usage[self.num_items - 1 :] # else: # label_zones = by_usage # others = [] # # series = [{"name": l[0].name, "y": l[1]} for l in label_zones] # # # if there are remaining items, merge into single "Other" zone # if others: # series.append({"name": str(_("Other")), "y": sum([o[1] for o in others])}) # # return {"series": series} # # class RepliesPerMonthChart(BasePerMonthChart): # """ # Chart of replies per month for either the current org, a given partner, or a given user # """ # # def get_month_totals(self, request, since): # partner_id = request.GET.get("partner") # user_id = request.GET.get("user") # # if partner_id: # partner = Partner.objects.get(org=request.org, pk=partner_id) # return DailyCount.get_by_partner([partner], DailyCount.TYPE_REPLIES, since).month_totals() # elif user_id: # user = request.org.get_users().get(pk=user_id) # return DailyCount.get_by_user(self.request.org, [user], DailyCount.TYPE_REPLIES, since).month_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_REPLIES, since).month_totals() . Output only the next line.
re_path(r"^cases_closed_chart/$", CasesClosedPerMonthChart.as_view(), name="statistics.cases_closed_chart"),
Continue the code snippet: <|code_start|> urlpatterns = DailyCountExportCRUDL().as_urlpatterns() urlpatterns += [ re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"), re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="statistics.replies_chart"), re_path(r"^labels_pie_chart/$", MostUsedLabelsChart.as_view(), name="statistics.labels_pie_chart"), <|code_end|> . Use current file imports: from django.urls import re_path from .views import ( CasesClosedPerMonthChart, CasesOpenedPerMonthChart, DailyCountExportCRUDL, IncomingPerDayChart, MostUsedLabelsChart, RepliesPerMonthChart, ) and context (classes, functions, or code) from other files: # Path: casepro/statistics/views.py # class CasesClosedPerMonthChart(BasePerMonthChart): # """ # Chart of cases closed per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_CLOSED, since).month_totals() # # class CasesOpenedPerMonthChart(BasePerMonthChart): # """ # Chart of cases opened per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_OPENED, since).month_totals() # # class DailyCountExportCRUDL(SmartCRUDL): # model = DailyCountExport # actions = ("create", "read") # # class Create(NonAtomicMixin, OrgPermsMixin, SmartCreateView): # def post(self, request, *args, **kwargs): # of_type = request.json["type"] # # # parse dates and adjust max so it's exclusive # after = parse_iso8601(request.json["after"]).date() # before = parse_iso8601(request.json["before"]).date() + timedelta(days=1) # # export = DailyCountExport.create(self.request.org, self.request.user, of_type, after, before) # # daily_count_export.delay(export.pk) # # return JsonResponse({"export_id": export.pk}) # # class Read(BaseDownloadView): # title = _("Download Export") # filename = "daily_count_export.xls" # # class IncomingPerDayChart(BasePerDayChart): # """ # Chart of incoming per day for either the current org or a given label # """ # # def get_day_totals(self, request, since): # label_id = request.GET.get("label") # # if label_id: # label = Label.get_all(org=request.org).get(pk=label_id) # return DailyCount.get_by_label([label], DailyCount.TYPE_INCOMING, since).day_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_INCOMING, since).day_totals() # # class MostUsedLabelsChart(BaseChart): # """ # Pie chart of top 10 labels used in last 30 days # """ # # num_items = 10 # num_days = 30 # # def get_data(self, request): # since = timezone.now() - relativedelta(days=self.num_days) # labels = Label.get_all(request.org, request.user) # # counts_by_label = DailyCount.get_by_label(labels, DailyCount.TYPE_INCOMING, since).scope_totals() # # # sort by highest count DESC, label name ASC # by_usage = sorted(counts_by_label.items(), key=lambda c: (-c[1], c[0].name)) # by_usage = [c for c in by_usage if c[1]] # remove zero counts # # if len(by_usage) > self.num_items: # label_zones = by_usage[: self.num_items - 1] # others = by_usage[self.num_items - 1 :] # else: # label_zones = by_usage # others = [] # # series = [{"name": l[0].name, "y": l[1]} for l in label_zones] # # # if there are remaining items, merge into single "Other" zone # if others: # series.append({"name": str(_("Other")), "y": sum([o[1] for o in others])}) # # return {"series": series} # # class RepliesPerMonthChart(BasePerMonthChart): # """ # Chart of replies per month for either the current org, a given partner, or a given user # """ # # def get_month_totals(self, request, since): # partner_id = request.GET.get("partner") # user_id = request.GET.get("user") # # if partner_id: # partner = Partner.objects.get(org=request.org, pk=partner_id) # return DailyCount.get_by_partner([partner], DailyCount.TYPE_REPLIES, since).month_totals() # elif user_id: # user = request.org.get_users().get(pk=user_id) # return DailyCount.get_by_user(self.request.org, [user], DailyCount.TYPE_REPLIES, since).month_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_REPLIES, since).month_totals() . Output only the next line.
re_path(r"^cases_opened_chart/$", CasesOpenedPerMonthChart.as_view(), name="statistics.cases_opened_chart"),
Given the following code snippet before the placeholder: <|code_start|> urlpatterns = DailyCountExportCRUDL().as_urlpatterns() urlpatterns += [ re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"), re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="statistics.replies_chart"), <|code_end|> , predict the next line using imports from the current file: from django.urls import re_path from .views import ( CasesClosedPerMonthChart, CasesOpenedPerMonthChart, DailyCountExportCRUDL, IncomingPerDayChart, MostUsedLabelsChart, RepliesPerMonthChart, ) and context including class names, function names, and sometimes code from other files: # Path: casepro/statistics/views.py # class CasesClosedPerMonthChart(BasePerMonthChart): # """ # Chart of cases closed per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_CLOSED, since).month_totals() # # class CasesOpenedPerMonthChart(BasePerMonthChart): # """ # Chart of cases opened per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_OPENED, since).month_totals() # # class DailyCountExportCRUDL(SmartCRUDL): # model = DailyCountExport # actions = ("create", "read") # # class Create(NonAtomicMixin, OrgPermsMixin, SmartCreateView): # def post(self, request, *args, **kwargs): # of_type = request.json["type"] # # # parse dates and adjust max so it's exclusive # after = parse_iso8601(request.json["after"]).date() # before = parse_iso8601(request.json["before"]).date() + timedelta(days=1) # # export = DailyCountExport.create(self.request.org, self.request.user, of_type, after, before) # # daily_count_export.delay(export.pk) # # return JsonResponse({"export_id": export.pk}) # # class Read(BaseDownloadView): # title = _("Download Export") # filename = "daily_count_export.xls" # # class IncomingPerDayChart(BasePerDayChart): # """ # Chart of incoming per day for either the current org or a given label # """ # # def get_day_totals(self, request, since): # label_id = request.GET.get("label") # # if label_id: # label = Label.get_all(org=request.org).get(pk=label_id) # return DailyCount.get_by_label([label], DailyCount.TYPE_INCOMING, since).day_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_INCOMING, since).day_totals() # # class MostUsedLabelsChart(BaseChart): # """ # Pie chart of top 10 labels used in last 30 days # """ # # num_items = 10 # num_days = 30 # # def get_data(self, request): # since = timezone.now() - relativedelta(days=self.num_days) # labels = Label.get_all(request.org, request.user) # # counts_by_label = DailyCount.get_by_label(labels, DailyCount.TYPE_INCOMING, since).scope_totals() # # # sort by highest count DESC, label name ASC # by_usage = sorted(counts_by_label.items(), key=lambda c: (-c[1], c[0].name)) # by_usage = [c for c in by_usage if c[1]] # remove zero counts # # if len(by_usage) > self.num_items: # label_zones = by_usage[: self.num_items - 1] # others = by_usage[self.num_items - 1 :] # else: # label_zones = by_usage # others = [] # # series = [{"name": l[0].name, "y": l[1]} for l in label_zones] # # # if there are remaining items, merge into single "Other" zone # if others: # series.append({"name": str(_("Other")), "y": sum([o[1] for o in others])}) # # return {"series": series} # # class RepliesPerMonthChart(BasePerMonthChart): # """ # Chart of replies per month for either the current org, a given partner, or a given user # """ # # def get_month_totals(self, request, since): # partner_id = request.GET.get("partner") # user_id = request.GET.get("user") # # if partner_id: # partner = Partner.objects.get(org=request.org, pk=partner_id) # return DailyCount.get_by_partner([partner], DailyCount.TYPE_REPLIES, since).month_totals() # elif user_id: # user = request.org.get_users().get(pk=user_id) # return DailyCount.get_by_user(self.request.org, [user], DailyCount.TYPE_REPLIES, since).month_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_REPLIES, since).month_totals() . Output only the next line.
re_path(r"^labels_pie_chart/$", MostUsedLabelsChart.as_view(), name="statistics.labels_pie_chart"),
Using the snippet: <|code_start|> urlpatterns = DailyCountExportCRUDL().as_urlpatterns() urlpatterns += [ re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"), <|code_end|> , determine the next line of code. You have imports: from django.urls import re_path from .views import ( CasesClosedPerMonthChart, CasesOpenedPerMonthChart, DailyCountExportCRUDL, IncomingPerDayChart, MostUsedLabelsChart, RepliesPerMonthChart, ) and context (class names, function names, or code) available: # Path: casepro/statistics/views.py # class CasesClosedPerMonthChart(BasePerMonthChart): # """ # Chart of cases closed per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_CLOSED, since).month_totals() # # class CasesOpenedPerMonthChart(BasePerMonthChart): # """ # Chart of cases opened per month for the current org # """ # # def get_month_totals(self, request, since): # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_CASE_OPENED, since).month_totals() # # class DailyCountExportCRUDL(SmartCRUDL): # model = DailyCountExport # actions = ("create", "read") # # class Create(NonAtomicMixin, OrgPermsMixin, SmartCreateView): # def post(self, request, *args, **kwargs): # of_type = request.json["type"] # # # parse dates and adjust max so it's exclusive # after = parse_iso8601(request.json["after"]).date() # before = parse_iso8601(request.json["before"]).date() + timedelta(days=1) # # export = DailyCountExport.create(self.request.org, self.request.user, of_type, after, before) # # daily_count_export.delay(export.pk) # # return JsonResponse({"export_id": export.pk}) # # class Read(BaseDownloadView): # title = _("Download Export") # filename = "daily_count_export.xls" # # class IncomingPerDayChart(BasePerDayChart): # """ # Chart of incoming per day for either the current org or a given label # """ # # def get_day_totals(self, request, since): # label_id = request.GET.get("label") # # if label_id: # label = Label.get_all(org=request.org).get(pk=label_id) # return DailyCount.get_by_label([label], DailyCount.TYPE_INCOMING, since).day_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_INCOMING, since).day_totals() # # class MostUsedLabelsChart(BaseChart): # """ # Pie chart of top 10 labels used in last 30 days # """ # # num_items = 10 # num_days = 30 # # def get_data(self, request): # since = timezone.now() - relativedelta(days=self.num_days) # labels = Label.get_all(request.org, request.user) # # counts_by_label = DailyCount.get_by_label(labels, DailyCount.TYPE_INCOMING, since).scope_totals() # # # sort by highest count DESC, label name ASC # by_usage = sorted(counts_by_label.items(), key=lambda c: (-c[1], c[0].name)) # by_usage = [c for c in by_usage if c[1]] # remove zero counts # # if len(by_usage) > self.num_items: # label_zones = by_usage[: self.num_items - 1] # others = by_usage[self.num_items - 1 :] # else: # label_zones = by_usage # others = [] # # series = [{"name": l[0].name, "y": l[1]} for l in label_zones] # # # if there are remaining items, merge into single "Other" zone # if others: # series.append({"name": str(_("Other")), "y": sum([o[1] for o in others])}) # # return {"series": series} # # class RepliesPerMonthChart(BasePerMonthChart): # """ # Chart of replies per month for either the current org, a given partner, or a given user # """ # # def get_month_totals(self, request, since): # partner_id = request.GET.get("partner") # user_id = request.GET.get("user") # # if partner_id: # partner = Partner.objects.get(org=request.org, pk=partner_id) # return DailyCount.get_by_partner([partner], DailyCount.TYPE_REPLIES, since).month_totals() # elif user_id: # user = request.org.get_users().get(pk=user_id) # return DailyCount.get_by_user(self.request.org, [user], DailyCount.TYPE_REPLIES, since).month_totals() # else: # return DailyCount.get_by_org([self.request.org], DailyCount.TYPE_REPLIES, since).month_totals() . Output only the next line.
re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="statistics.replies_chart"),
Next line prediction: <|code_start|> queue.appendleft(n) #search the relatives of the current node according to relative_fxn #for each relative, if we haven't traversed it, add it to the queue for n in relative_fxn(current): if n not in already_visited: already_visited.append(n) queue.appendleft(n) #if current has an external container, add it to the queue if current.external_parents and direction == "predecessors": for p in current.external_parents: if p not in already_visited: already_visited.append(p) queue.appendleft(p) elif current.external_childs and direction == "successors": for c in current.external_childs: if c not in already_visited: already_visited.append(c) queue.appendleft(c) #finally, add the current's container to the queue if not isinstance(current.container, Relational): if current.container not in queue and current.container not in already_visited: already_visited.append(current.container) queue.appendleft(current.container) return None class BasParser(object): basvars = dict() def build(self): return yacc.yacc(module=self) <|code_end|> . Use current file imports: (from baslexer import BasLexer from collections import deque from node import * import ply.yacc as yacc import itertools import gis import sdh_demo as sdh) and context including class names, function names, or small code snippets from other files: # Path: baslexer.py # class BasLexer(object): # def build(self,**kwargs): # self.lexer = lex.lex(module=self, **kwargs) # return self.lexer # # tokens = [ # 'NAME', 'UUID', 'VAR', 'TAG', 'SPATIAL', # 'UPSTREAM', 'DOWNSTREAM', 'EQUALS', 'LASTVALUE', # 'LPAREN', 'RPAREN', # 'UPSTREAMIMM', 'DOWNSTREAMIMM' # ] # # t_UPSTREAM = r'>' # t_DOWNSTREAM = r'<' # t_UPSTREAMIMM = r'>>' # t_DOWNSTREAMIMM = r'<<' # t_LPAREN = r'\(' # t_RPAREN = r'\)' # #t_LBRACK = r'\[' # #t_RBRACK = r'\]' # t_EQUALS = r'=' # t_ignore = ' \t' # # def t_NAME(self,t): # r'\$[^!][\w\-\:\_\s]+' # t.value = t.value.strip() # return t # # def t_TAG(self,t): # r'(\.|\#|\&)([^!]?[A-Z_ ]+)?[ ]?' # t.value = t.value.strip() # return t # # def t_SPATIAL(self,t): # r'!\#?([\w\-\:\_\s]+)?' # t.value = t.value.strip() # return t # # def t_UUID(self,t): # r'(\%|\^)[^!]?[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}[ ]?' # t.value = t.value.strip() # return t # # def t_VAR(self,t): # r'\@[^!]?[a-zA-Z_][a-zA-Z0-9_]*[ ]?' # t.value = t.value.strip() # return t # # def t_LASTVALUE(self,t): # r'\b\_\b' # t.value = t.value.strip() # return t # # def t_error(self, t): # print "Illegal character '%s'" % t.value[0] # t.lexer.skip(1) . Output only the next line.
tokens = BasLexer.tokens
Predict the next line after this snippet: <|code_start|> @coroutine def invoke(handler, parameters): def respond(params): sleep(0.1) return {'parameters': parameters} def return_true(): sleep(0.1) return True <|code_end|> using the current file's imports: from toto.invocation import * from toto.tasks import TaskQueue from time import sleep from tornado.gen import coroutine, Return, Task, Callback, Wait and any relevant context from other files: # Path: toto/tasks.py # class TaskQueue(): # '''Instances will run up to ``thread_count`` tasks at a time # whenever there are tasks in the queue. Theads will be killed # if unused for longer than ``idle_timeout`` seconds. # ''' # # def __init__(self, thread_count=1, idle_timeout=60, name='TaskQueue'): # self.tasks = deque() # self.running = False # self.condition = Condition() # self.threads = set() # self.idle_timeout = idle_timeout # self.thread_count = thread_count # self.name = name # # def add_task(self, fn, *args, **kwargs): # '''Add the function ``fn`` to the queue to be invoked with # ``args`` and ``kwargs`` as arguments. If the ``TaskQueue`` # is not currently running, it will be started now. # ''' # with self.condition: # self.tasks.append((fn, args, kwargs)) # self.condition.notify() # self.run() # # def yield_task(self, fn, *args, **kwargs): # '''Like add_task but will call the function as a coroutine, allowing you # to yield the return value from within a function decorated with ``@tornado.gen.coroutine`` # or ``@tornado.gen.engine``. # # Usage:: # # def add(arg1, arg2): # return arg1 + arg2 # # @tornado.gen.engine # def caller(): # value = yield TaskQueue.instance('myqueue').yield_task(add, 1, 2) # print value #prints 3 # # ''' # # ioloop = IOLoop.current() # future = Future() # def call(): # result = None # error = None # try: # result = fn(*args, **kwargs) # except Exception as e: # ioloop.add_callback(future.set_exc_info, exc_info()) # else: # # tornado future is not threadsafe # ioloop.add_callback(future.set_result, result) # self.add_task(call) # return future # # def run(self): # '''Start processing jobs in the queue. You should not need # to call this as ``add_task`` automatically starts the queue. # Processing threads will stop when there are no jobs available # in the queue for at least ``idle_timeout`` seconds. # ''' # with self.condition: # if len(self.threads) >= self.thread_count: # return # thread = self.__TaskLoop(self) # self.threads.add(thread) # thread.start() # # def __len__(self): # '''Returns the number of active threads plus the number of # queued tasks/''' # return len(self.threads) + len(self.tasks) # # @classmethod # def instance(cls, name, thread_count=1, idle_timeout=60): # '''A convenience method for accessing shared instances of ``TaskQueue``. # If ``name`` references an existing instance created with this method, # that instance will be returned. Otherwise, a new ``TaskQueue`` will be # instantiated with ``thread_count`` threads and the specified ``idle_timeout`` # then stored under ``name``. # # All arguments after name are ignored after the queue is created. # ''' # if not hasattr(cls, '_task_queues'): # cls._task_queues = {} # try: # return cls._task_queues[name] # except KeyError: # cls._task_queues[name] = cls(thread_count, idle_timeout, name) # return cls._task_queues[name] # # class __TaskLoop(Thread): # # thread_id = count() # # def __init__(self, queue): # Thread.__init__(self, name='%s-%d' % (queue.name, self.thread_id.next())) # self.daemon = True # self.queue = queue # self.condition = self.queue.condition # self.tasks = self.queue.tasks # self.idle_timeout = self.queue.idle_timeout # self.threads = self.queue.threads # self.in_use = True # # def run(self): # try: # while 1: # with self.condition: # if not len(self.tasks): # self.condition.wait(self.idle_timeout) # try: # task = self.tasks.popleft() # except IndexError: # logging.debug('Idle timeout: %s' % self.name) # self.threads.remove(self) # self.in_use = False # return # try: # task[0](*task[1], **task[2]) # except Exception as e: # logging.error(traceback.format_exc()) # finally: # with self.condition: # if self.in_use: # self.threads.remove(self) # self.in_use = False . Output only the next line.
response = TaskQueue.instance('test1').yield_task(respond, parameters)
Predict the next line after this snippet: <|code_start|> @coroutine def invoke(handler, parameters): def respond(params): sleep(0.1) raise TotoException(4242, 'Test Toto Exception') <|code_end|> using the current file's imports: from toto.invocation import * from toto.tasks import TaskQueue from time import sleep from tornado.gen import coroutine, Return, Task, Callback, Wait and any relevant context from other files: # Path: toto/tasks.py # class TaskQueue(): # '''Instances will run up to ``thread_count`` tasks at a time # whenever there are tasks in the queue. Theads will be killed # if unused for longer than ``idle_timeout`` seconds. # ''' # # def __init__(self, thread_count=1, idle_timeout=60, name='TaskQueue'): # self.tasks = deque() # self.running = False # self.condition = Condition() # self.threads = set() # self.idle_timeout = idle_timeout # self.thread_count = thread_count # self.name = name # # def add_task(self, fn, *args, **kwargs): # '''Add the function ``fn`` to the queue to be invoked with # ``args`` and ``kwargs`` as arguments. If the ``TaskQueue`` # is not currently running, it will be started now. # ''' # with self.condition: # self.tasks.append((fn, args, kwargs)) # self.condition.notify() # self.run() # # def yield_task(self, fn, *args, **kwargs): # '''Like add_task but will call the function as a coroutine, allowing you # to yield the return value from within a function decorated with ``@tornado.gen.coroutine`` # or ``@tornado.gen.engine``. # # Usage:: # # def add(arg1, arg2): # return arg1 + arg2 # # @tornado.gen.engine # def caller(): # value = yield TaskQueue.instance('myqueue').yield_task(add, 1, 2) # print value #prints 3 # # ''' # # ioloop = IOLoop.current() # future = Future() # def call(): # result = None # error = None # try: # result = fn(*args, **kwargs) # except Exception as e: # ioloop.add_callback(future.set_exc_info, exc_info()) # else: # # tornado future is not threadsafe # ioloop.add_callback(future.set_result, result) # self.add_task(call) # return future # # def run(self): # '''Start processing jobs in the queue. You should not need # to call this as ``add_task`` automatically starts the queue. # Processing threads will stop when there are no jobs available # in the queue for at least ``idle_timeout`` seconds. # ''' # with self.condition: # if len(self.threads) >= self.thread_count: # return # thread = self.__TaskLoop(self) # self.threads.add(thread) # thread.start() # # def __len__(self): # '''Returns the number of active threads plus the number of # queued tasks/''' # return len(self.threads) + len(self.tasks) # # @classmethod # def instance(cls, name, thread_count=1, idle_timeout=60): # '''A convenience method for accessing shared instances of ``TaskQueue``. # If ``name`` references an existing instance created with this method, # that instance will be returned. Otherwise, a new ``TaskQueue`` will be # instantiated with ``thread_count`` threads and the specified ``idle_timeout`` # then stored under ``name``. # # All arguments after name are ignored after the queue is created. # ''' # if not hasattr(cls, '_task_queues'): # cls._task_queues = {} # try: # return cls._task_queues[name] # except KeyError: # cls._task_queues[name] = cls(thread_count, idle_timeout, name) # return cls._task_queues[name] # # class __TaskLoop(Thread): # # thread_id = count() # # def __init__(self, queue): # Thread.__init__(self, name='%s-%d' % (queue.name, self.thread_id.next())) # self.daemon = True # self.queue = queue # self.condition = self.queue.condition # self.tasks = self.queue.tasks # self.idle_timeout = self.queue.idle_timeout # self.threads = self.queue.threads # self.in_use = True # # def run(self): # try: # while 1: # with self.condition: # if not len(self.tasks): # self.condition.wait(self.idle_timeout) # try: # task = self.tasks.popleft() # except IndexError: # logging.debug('Idle timeout: %s' % self.name) # self.threads.remove(self) # self.in_use = False # return # try: # task[0](*task[1], **task[2]) # except Exception as e: # logging.error(traceback.format_exc()) # finally: # with self.condition: # if self.in_use: # self.threads.remove(self) # self.in_use = False . Output only the next line.
raise Return((yield TaskQueue.instance('test1').yield_task(respond, parameters)))
Given the code snippet: <|code_start|> class TestSession(unittest.TestCase): def test_generate_id(self): session_id = TotoSession.generate_id() <|code_end|> , generate the next line using the imports in this file: import unittest import urllib2 import urllib import urlparse import json import os import signal import cPickle as pickle from uuid import uuid4 from toto.secret import * from multiprocessing import Process, active_children from toto.session import TotoSession, SESSION_ID_LENGTH from time import sleep, time and context (functions, classes, or occasionally code) from other files: # Path: toto/session.py # class TotoSession(object): # '''Instances of ``TotoSession`` provide dictionary-like access to current session variables, and the current # account (if authenticated). # ''' # # __serializer = pickle # # def __init__(self, db, session_data, session_cache=None, key=None): # self._db = db # self._session_cache = session_cache # self.user_id = session_data['user_id'] # self.expires = session_data['expires'] # self.session_id = session_data['session_id'] # self.state = session_data.get('state') and TotoSession.loads(session_data['state']) or {} # key = key or session_data.get('key') # self.key = key or None # # def get_account(self, *args): # '''Load the account associated with this session (if authenticated). Session properties are # serialized to a binary string and stored as the ``TotoSession.state`` property, so you don't need to configure your database to handle them in # advance. # ''' # raise Exception("Unimplemented operation: get_account") # # def session_data(self): # '''Return a session data ``dict`` that could be used to instantiate a session identical to the current one. # ''' # data = {'user_id': self.user_id, 'expires': self.expires, 'session_id': self.session_id, 'state': TotoSession.dumps(self.state)} # if self.key: # data['key'] = self.key # return data # # def __getitem__(self, key): # return key in self.state and self.state[key] or None # # def __setitem__(self, key, value): # self.state[key] = value # # def __delitem__(self, key): # if key in self.state: # del self.state[key] # # def __iter__(self): # return self.state.__iter__() # # def iterkeys(): # return self.__iter__() # # def __contains__(self, key): # return key in self.state # # def __str__(self): # return str({'user_id': self.user_id, 'expires': self.expires, 'id': self.session_id, 'state': self.state}) # # def _refresh_cache(self): # if self._session_cache: # return self._session_cache.load_session(self.session_id) # return None # # def refresh(self): # '''Refresh the current session to the state in the database. # ''' # raise Exception("Unimplemented operation: refresh") # # def _save_cache(self): # if self._session_cache: # updated_session_id = self._session_cache.store_session(self.session_data()) # if updated_session_id: # self.session_id = updated_session_id # return True # return False # # def save(self): # '''Save the session to the database. # ''' # raise Exception("Unimplemented operation: save") # # def verify(self, mac, signature): # '''Verify the mac and signature with this session's authenticated key. # ''' # if not self.key or not mac or not signature: # raise TotoException(ERROR_INVALID_HMAC, "Invalid HMAC") # if self.hmac(signature) != mac: # raise TotoException(ERROR_INVALID_HMAC, "Invalid HMAC") # return self # # def hmac(self, signature): # '''Return the hmac of the signature signed with the authenticated key. # ''' # return b64encode(hmac.new(self.key, signature, sha1).digest()) # # @classmethod # def set_serializer(cls, serializer): # '''Set the module that instances of ``TotoSession`` and ``TotoSessionCache`` will use to serialize session state. The module must implement ``loads`` and ``dumps`` # and support serialization and deserialization of any data you want to store in the session. # By default, ``cPickle`` is used. # ''' # cls.__serializer = serializer # # @classmethod # def loads(cls, data): # '''A convenience method to call ``serializer.loads()`` on the active serializer. # ''' # return cls.__serializer.loads(str(data)) # # @classmethod # def dumps(cls, data): # '''A convenience method to call ``serializer.dumps()`` on the active serializer. # ''' # return cls.__serializer.dumps(data) # # @classmethod # def generate_id(cls): # '''Generate a random 22 character url safe session ID string. # ''' # return b64encode(uuid4().bytes, '-_')[:-2] # # SESSION_ID_LENGTH = 22 . Output only the next line.
self.assertEqual(len(session_id), SESSION_ID_LENGTH)
Predict the next line after this snippet: <|code_start|> @coroutine def invoke(handler, parameters): def respond(params): sleep(0.1) raise Exception('Test Exception') <|code_end|> using the current file's imports: from toto.invocation import * from toto.tasks import TaskQueue from time import sleep from tornado.gen import coroutine, Return, Task, Callback, Wait and any relevant context from other files: # Path: toto/tasks.py # class TaskQueue(): # '''Instances will run up to ``thread_count`` tasks at a time # whenever there are tasks in the queue. Theads will be killed # if unused for longer than ``idle_timeout`` seconds. # ''' # # def __init__(self, thread_count=1, idle_timeout=60, name='TaskQueue'): # self.tasks = deque() # self.running = False # self.condition = Condition() # self.threads = set() # self.idle_timeout = idle_timeout # self.thread_count = thread_count # self.name = name # # def add_task(self, fn, *args, **kwargs): # '''Add the function ``fn`` to the queue to be invoked with # ``args`` and ``kwargs`` as arguments. If the ``TaskQueue`` # is not currently running, it will be started now. # ''' # with self.condition: # self.tasks.append((fn, args, kwargs)) # self.condition.notify() # self.run() # # def yield_task(self, fn, *args, **kwargs): # '''Like add_task but will call the function as a coroutine, allowing you # to yield the return value from within a function decorated with ``@tornado.gen.coroutine`` # or ``@tornado.gen.engine``. # # Usage:: # # def add(arg1, arg2): # return arg1 + arg2 # # @tornado.gen.engine # def caller(): # value = yield TaskQueue.instance('myqueue').yield_task(add, 1, 2) # print value #prints 3 # # ''' # # ioloop = IOLoop.current() # future = Future() # def call(): # result = None # error = None # try: # result = fn(*args, **kwargs) # except Exception as e: # ioloop.add_callback(future.set_exc_info, exc_info()) # else: # # tornado future is not threadsafe # ioloop.add_callback(future.set_result, result) # self.add_task(call) # return future # # def run(self): # '''Start processing jobs in the queue. You should not need # to call this as ``add_task`` automatically starts the queue. # Processing threads will stop when there are no jobs available # in the queue for at least ``idle_timeout`` seconds. # ''' # with self.condition: # if len(self.threads) >= self.thread_count: # return # thread = self.__TaskLoop(self) # self.threads.add(thread) # thread.start() # # def __len__(self): # '''Returns the number of active threads plus the number of # queued tasks/''' # return len(self.threads) + len(self.tasks) # # @classmethod # def instance(cls, name, thread_count=1, idle_timeout=60): # '''A convenience method for accessing shared instances of ``TaskQueue``. # If ``name`` references an existing instance created with this method, # that instance will be returned. Otherwise, a new ``TaskQueue`` will be # instantiated with ``thread_count`` threads and the specified ``idle_timeout`` # then stored under ``name``. # # All arguments after name are ignored after the queue is created. # ''' # if not hasattr(cls, '_task_queues'): # cls._task_queues = {} # try: # return cls._task_queues[name] # except KeyError: # cls._task_queues[name] = cls(thread_count, idle_timeout, name) # return cls._task_queues[name] # # class __TaskLoop(Thread): # # thread_id = count() # # def __init__(self, queue): # Thread.__init__(self, name='%s-%d' % (queue.name, self.thread_id.next())) # self.daemon = True # self.queue = queue # self.condition = self.queue.condition # self.tasks = self.queue.tasks # self.idle_timeout = self.queue.idle_timeout # self.threads = self.queue.threads # self.in_use = True # # def run(self): # try: # while 1: # with self.condition: # if not len(self.tasks): # self.condition.wait(self.idle_timeout) # try: # task = self.tasks.popleft() # except IndexError: # logging.debug('Idle timeout: %s' % self.name) # self.threads.remove(self) # self.in_use = False # return # try: # task[0](*task[1], **task[2]) # except Exception as e: # logging.error(traceback.format_exc()) # finally: # with self.condition: # if self.in_use: # self.threads.remove(self) # self.in_use = False . Output only the next line.
raise Return((yield TaskQueue.instance('test1').yield_task(respond, parameters)))
Next line prediction: <|code_start|> @asynchronous def invoke(handler, parameters): def respond(params): sleep(0.1) handler.respond({'parameters': parameters}) <|code_end|> . Use current file imports: (from toto.invocation import * from toto.tasks import TaskQueue from time import sleep) and context including class names, function names, or small code snippets from other files: # Path: toto/tasks.py # class TaskQueue(): # '''Instances will run up to ``thread_count`` tasks at a time # whenever there are tasks in the queue. Theads will be killed # if unused for longer than ``idle_timeout`` seconds. # ''' # # def __init__(self, thread_count=1, idle_timeout=60, name='TaskQueue'): # self.tasks = deque() # self.running = False # self.condition = Condition() # self.threads = set() # self.idle_timeout = idle_timeout # self.thread_count = thread_count # self.name = name # # def add_task(self, fn, *args, **kwargs): # '''Add the function ``fn`` to the queue to be invoked with # ``args`` and ``kwargs`` as arguments. If the ``TaskQueue`` # is not currently running, it will be started now. # ''' # with self.condition: # self.tasks.append((fn, args, kwargs)) # self.condition.notify() # self.run() # # def yield_task(self, fn, *args, **kwargs): # '''Like add_task but will call the function as a coroutine, allowing you # to yield the return value from within a function decorated with ``@tornado.gen.coroutine`` # or ``@tornado.gen.engine``. # # Usage:: # # def add(arg1, arg2): # return arg1 + arg2 # # @tornado.gen.engine # def caller(): # value = yield TaskQueue.instance('myqueue').yield_task(add, 1, 2) # print value #prints 3 # # ''' # # ioloop = IOLoop.current() # future = Future() # def call(): # result = None # error = None # try: # result = fn(*args, **kwargs) # except Exception as e: # ioloop.add_callback(future.set_exc_info, exc_info()) # else: # # tornado future is not threadsafe # ioloop.add_callback(future.set_result, result) # self.add_task(call) # return future # # def run(self): # '''Start processing jobs in the queue. You should not need # to call this as ``add_task`` automatically starts the queue. # Processing threads will stop when there are no jobs available # in the queue for at least ``idle_timeout`` seconds. # ''' # with self.condition: # if len(self.threads) >= self.thread_count: # return # thread = self.__TaskLoop(self) # self.threads.add(thread) # thread.start() # # def __len__(self): # '''Returns the number of active threads plus the number of # queued tasks/''' # return len(self.threads) + len(self.tasks) # # @classmethod # def instance(cls, name, thread_count=1, idle_timeout=60): # '''A convenience method for accessing shared instances of ``TaskQueue``. # If ``name`` references an existing instance created with this method, # that instance will be returned. Otherwise, a new ``TaskQueue`` will be # instantiated with ``thread_count`` threads and the specified ``idle_timeout`` # then stored under ``name``. # # All arguments after name are ignored after the queue is created. # ''' # if not hasattr(cls, '_task_queues'): # cls._task_queues = {} # try: # return cls._task_queues[name] # except KeyError: # cls._task_queues[name] = cls(thread_count, idle_timeout, name) # return cls._task_queues[name] # # class __TaskLoop(Thread): # # thread_id = count() # # def __init__(self, queue): # Thread.__init__(self, name='%s-%d' % (queue.name, self.thread_id.next())) # self.daemon = True # self.queue = queue # self.condition = self.queue.condition # self.tasks = self.queue.tasks # self.idle_timeout = self.queue.idle_timeout # self.threads = self.queue.threads # self.in_use = True # # def run(self): # try: # while 1: # with self.condition: # if not len(self.tasks): # self.condition.wait(self.idle_timeout) # try: # task = self.tasks.popleft() # except IndexError: # logging.debug('Idle timeout: %s' % self.name) # self.threads.remove(self) # self.in_use = False # return # try: # task[0](*task[1], **task[2]) # except Exception as e: # logging.error(traceback.format_exc()) # finally: # with self.condition: # if self.in_use: # self.threads.remove(self) # self.in_use = False . Output only the next line.
TaskQueue.instance('test').add_task(respond, parameters)
Using the snippet: <|code_start|> class _Request(object): def __init__(self, headers, body, timeout, retry_count, future, callback=None): self.headers = headers self.body = body self.timeout = timeout self.retry_count = retry_count self.callback = callback self.future = future self.request_id = uuid4() def request(self, url): return HTTPRequest(url=url, method='POST', headers=self.headers, body=self.body) def handle_response(self, response): self.callback(self, response) def run_request(self, url): client = AsyncHTTPClient() client.fetch(self.request(url), callback=self.handle_response, raise_error=False) <|code_end|> , determine the next line of code. You have imports: import toto import cPickle as pickle import zlib import logging from toto.exceptions import * from toto.workerconnection import WorkerConnection from threading import Thread, Lock from tornado.options import options from tornado.gen import coroutine, Return from tornado.ioloop import IOLoop from collections import deque from tornado.httpclient import HTTPRequest, AsyncHTTPClient, HTTPError from tornado.concurrent import Future from sys import exc_info from time import time from uuid import uuid4 from traceback import format_exc from toto.options import safe_define from random import shuffle and context (class names, function names, or code) available: # Path: toto/workerconnection.py # class WorkerConnection(object): # '''Use a ``WorkerConnection`` to make RPCs to the remote worker service(s) or worker/router specified by ``address``. # ``address`` may be either an enumerable of address strings or a string of comma separated addresses. RPC retries # and timeouts will happen by at most every ``abs(timeout)`` seconds when a periodic callback runs through all active # messages and checks for prolonged requests. This is also the default timeout for any new calls. ``timeout`` must not be # ``0``. # # Optionally pass any object or module with ``compress`` and ``decompress`` methods as the ``compression`` parameter to # compress messages. The module must implement the same algorithm used on the worker service. By default, messages are not # compressed. # # Optionally pass any object or module with ``dumps`` and ``loads`` methods that convert an ``object`` to and from a # ``str`` to replace the default ``cPickle`` serialization with a protocol of your choice. # # Use ``auto_retry`` to specify whether or not messages should be retried by default. Retrying messages can cause substantial # congestion in your worker service. Use with caution. # ''' # # def __getattr__(self, path): # return WorkerInvocation(path, self) # # def log_error(self, error): # logging.error(repr(error)) # # def enable_traceback_logging(self): # from new import instancemethod # from traceback import format_exc # def log_error(self, e): # logging.error(format_exc()) # self.log_error = instancemethod(log_error, self) # # @classmethod # def instance(cls): # '''Returns the default instance of ``WorkerConnection`` as configured by the options prefixed # with ``worker_``, instantiating it if necessary. Import the ``workerconnection`` module within # your ``TotoService`` and run it with ``--help`` to see all available options. # ''' # if not hasattr(cls, '_instance'): # if options.worker_transport == 'http': # from toto.httpworkerconnection import HTTPWorkerConnection # cls._instance = HTTPWorkerConnection.instance() # else: # from toto.zmqworkerconnection import ZMQWorkerConnection # cls._instance = ZMQWorkerConnection.instance() # return cls._instance # # Path: toto/options.py # def safe_define(*args, **kwargs): # try: # define(*args, **kwargs) # except Exception as e: # logging.error(str(e)) . Output only the next line.
class HTTPWorkerConnection(WorkerConnection):
Continue the code snippet: <|code_start|> 'The MIT License (MIT)', # The MIT License 'GNU LESSER GENERAL PUBLIC LICENSE', # GNU LGPL ( 'THE SOFTWARE IS PROVIDED \"AS IS\" AND THE ' 'AUTHOR DISCLAIMS ALL WARRANTIES' ), # ISC 'GNU GENERAL PUBLIC LICENSE', # GNU GPL 'Eclipse Public License', # Eclipse Public License ( 'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT ' 'HOLDERS AND CONTRIBUTORS \"AS IS\"' ), # BSD 3- and 2-clause 'Artistic License', # Artistic License 'http://www.apache.org/licenses', # Apache License 'GNU AFFERO GENERAL PUBLIC LICENSE', # GNU AGPL ] def run(project_id, repo_path, cursor, **options): cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() <|code_end|> . Use current file imports: from lib import utilities from lib.core import Tokenizer from lib.utilities import url_to_json and context (classes, functions, or code) from other files: # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
full_url = utilities.TOKENIZER.tokenize(record[0].rstrip())
Here is a snippet: <|code_start|> path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] self.database = database.Database(settings) def test_main(self): # Arrange project_id = 10868464 # andymeneely/squib options = { 'threshold': 1, 'minimumDurationInMonths': 1 } # Act try: self.database.connect() with self.database.cursor() as cursor: <|code_end|> . Write the next line using the current file imports: import json import os import unittest from attributes.history import main from lib import database and context from other files: # Path: attributes/history/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): , which may include functions, classes, or code. Output only the next line.
(result, value) = main.run(project_id, '', cursor, **options)
Predict the next line after this snippet: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] <|code_end|> using the current file's imports: import json import os import unittest from attributes.history import main from lib import database and any relevant context from other files: # Path: attributes/history/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): . Output only the next line.
self.database = database.Database(settings)
Continue the code snippet: <|code_start|> """ The documentation attribute measures the ratio of comment lines of code to non-blank lines of code (sloc + cloc) as determined by the `cloc` tool (http://cloc.sourceforge.net/). Even though GitHub determines the primary language of each repository, this module will consider source lines and comment lines of each language cloc reports. We may need to change this in the future, as one language may require fewer lines of code to express the same idea than another language. Author: Steven Kroh skk8768@rit.edu Updated: 16 May 2015 """ def run(project_id, repo_path, cursor, **options): ratio = 0 # Dictionary of language => metrics dictionary <|code_end|> . Use current file imports: from lib import utilities and context (classes, functions, or code) from other files: # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
util = utilities.get_loc(repo_path)
Predict the next line after this snippet: <|code_start|> 'authentication.' ) for token in tokens: self.available_tokens.put(token) def tokenize(self, url): if url.startswith('https://api.github.com'): if self.have_tokens: token = self.get_token() if token is not None: return '{0}?access_token={1}'.format(url, token) else: return url else: return url else: raise ValueError('url must be for the GitHub API') def get_token(self): while True: if not self.scheduler.get_jobs() and self.available_tokens.empty(): self.print_warning('No more valid OAuth tokens available.') return None token = self.available_tokens.get(block=True) rate_limit_url = ( 'https://api.github.com/rate_limit?access_token={0}' ).format(token) <|code_end|> using the current file's imports: import apscheduler.schedulers.background import datetime import queue import sys from lib.utilities import url_to_json and any relevant context from other files: # Path: lib/utilities.py # def url_to_json(url, headers={}): # """Returns the JSON response from the url. # # Args: # url (string): URL from which to GET the JSON resource. # # Returns: # dict: JSON of the response or empty dict on error. # """ # request = urllib.request.Request( # url, # headers=headers # ) # # try: # response = urllib.request.urlopen(request) # # raw_data = response.readall().decode('utf-8') # result = json.loads(raw_data) # except Exception as e: # # TODO: Properly handle error. For now, just return empty dictionary. # result = {} # # return result . Output only the next line.
status = url_to_json(rate_limit_url)
Using the snippet: <|code_start|>class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] self.database = database.Database(settings) def test_main(self): # Arrange project_id = 284 options = {'threshold': '6m'} expected = (True, 'active') # Act try: self.database.connect() with self.database.cursor() as cursor: <|code_end|> , determine the next line of code. You have imports: import json import os import unittest from attributes.state import main from lib import database, dateutil, utilities and context (class names, function names, or code) available: # Path: attributes/state/main.py # QUERY = ''' # SELECT MAX(c.created_at) # FROM commits c # JOIN project_commits pc ON pc.commit_id = c.id # WHERE pc.project_id = {0} and c.created_at > 0 # ''' # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): # # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
actual = main.run(project_id, '', cursor, **options)
Next line prediction: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] <|code_end|> . Use current file imports: (import json import os import unittest from attributes.state import main from lib import database, dateutil, utilities) and context including class names, function names, or small code snippets from other files: # Path: attributes/state/main.py # QUERY = ''' # SELECT MAX(c.created_at) # FROM commits c # JOIN project_commits pc ON pc.commit_id = c.id # WHERE pc.project_id = {0} and c.created_at > 0 # ''' # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): # # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
self.database = database.Database(settings)
Here is a snippet: <|code_start|> attribute.reference.global_init(cursor, samples) finally: self.database.disconnect() def run(self, project_id, repository_root): rresults = dict() repository_home = os.path.join(repository_root, str(project_id)) outq = multiprocessing.Queue(maxsize=1) try: self.database.connect() repository_path = None if self.requires_source: repository_path = self._init_repository( project_id, repository_home ) for attribute in self.attributes: bresult = False rresult = None if not attribute.enabled: continue with self.database.cursor() as cursor: if hasattr(attribute.reference, 'init'): attribute.reference.init(cursor) with self.database.cursor() as cursor: <|code_end|> . Write the next line using the current file imports: import distutils.spawn import importlib import multiprocessing import os import shutil import sys import types import traceback import attributes from datetime import datetime from lib import utilities and context from other files: # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): , which may include functions, classes, or code. Output only the next line.
timeout = utilities.parse_datetime_delta(attribute.timeout)
Using the snippet: <|code_start|> path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] self.database = database.Database(settings) def test_main(self): # Arrange project_id = 10868464 # andymeneely/squib options = { 'threshold': 1, 'today': '2015-04-01' } # Act try: self.database.connect() with self.database.cursor() as cursor: <|code_end|> , determine the next line of code. You have imports: import json import os import unittest from attributes.management import main from lib import database and context (class names, function names, or code) available: # Path: attributes/management/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): . Output only the next line.
(result, value) = main.run(project_id, '', cursor, **options)
Given the code snippet: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] <|code_end|> , generate the next line using the imports in this file: import json import os import unittest from attributes.management import main from lib import database and context (functions, classes, or occasionally code) from other files: # Path: attributes/management/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): . Output only the next line.
self.database = database.Database(settings)
Predict the next line for this snippet: <|code_start|> def run(project_id, repo_path, cursor, **options): threshold = options.get('threshold', 0) cursor.execute('SELECT url FROM projects WHERE id = {}'.format(project_id)) record = cursor.fetchone() <|code_end|> with the help of current file imports: import sys from lib import utilities and context from other files: # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): , which may contain function names, class names, or code. Output only the next line.
full_url = utilities.TOKENIZER.tokenize(record[0].rstrip())
Next line prediction: <|code_start|> path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) config = None with open(path, 'r') as file_: config = utilities.read(file_) self.database = database.Database(config['options']['datasource']) core.config = config utilities.TOKENIZER = core.Tokenizer() def test_main(self): # Arrange project_id = 24397 options = {'threshold': 0} expected = (True, 3660) # Act try: self.database.connect() with self.database.cursor() as cursor: <|code_end|> . Use current file imports: (import json import os import unittest from attributes.stars import main from lib import core, database, dateutil, utilities) and context including class names, function names, or small code snippets from other files: # Path: attributes/stars/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): # # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
actual = main.run(project_id, '', cursor, **options)
Here is a snippet: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) config = None with open(path, 'r') as file_: config = utilities.read(file_) self.database = database.Database(config['options']['datasource']) <|code_end|> . Write the next line using the current file imports: import json import os import unittest from attributes.stars import main from lib import core, database, dateutil, utilities and context from other files: # Path: attributes/stars/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): # # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): , which may include functions, classes, or code. Output only the next line.
core.config = config
Given the code snippet: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) config = None with open(path, 'r') as file_: config = utilities.read(file_) <|code_end|> , generate the next line using the imports in this file: import json import os import unittest from attributes.stars import main from lib import core, database, dateutil, utilities and context (functions, classes, or occasionally code) from other files: # Path: attributes/stars/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): # # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
self.database = database.Database(config['options']['datasource'])
Next line prediction: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) config = None with open(path, 'r') as file_: <|code_end|> . Use current file imports: (import json import os import unittest from attributes.stars import main from lib import core, database, dateutil, utilities) and context including class names, function names, or small code snippets from other files: # Path: attributes/stars/main.py # def run(project_id, repo_path, cursor, **options): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): # # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
config = utilities.read(file_)
Predict the next line after this snippet: <|code_start|> dest='plugins_dir', help='Path to the folder containing your set of attribute plugins.' ) parser.add_argument( 'repository_id', type=int, nargs=1, help='Identifier for a project as it appears in the \ GHTorrent database.' ) parser.add_argument( 'repository_path', type=is_dir, nargs=1, help='Path to the repository source code.' ) if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ args = process_arguments() config = process_configuration(args.config_file) <|code_end|> using the current file's imports: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and any relevant context from other files: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
connection = establish_database_connection(config['options']['datasource'])
Given the code snippet: <|code_start|> parser.add_argument( 'repository_id', type=int, nargs=1, help='Identifier for a project as it appears in the \ GHTorrent database.' ) parser.add_argument( 'repository_path', type=is_dir, nargs=1, help='Path to the repository source code.' ) if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ args = process_arguments() config = process_configuration(args.config_file) connection = establish_database_connection(config['options']['datasource']) attributes = config['attributes'] load_attribute_plugins(args.plugins_dir, attributes) <|code_end|> , generate the next line using the imports in this file: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and context (functions, classes, or occasionally code) from other files: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
init_attribute_plugins(attributes, connection)
Based on the snippet: <|code_start|> ) parser.add_argument( 'repository_id', type=int, nargs=1, help='Identifier for a project as it appears in the \ GHTorrent database.' ) parser.add_argument( 'repository_path', type=is_dir, nargs=1, help='Path to the repository source code.' ) if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ args = process_arguments() config = process_configuration(args.config_file) connection = establish_database_connection(config['options']['datasource']) attributes = config['attributes'] <|code_end|> , predict the immediate next line with the help of imports: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and context (classes, functions, sometimes code) from other files: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
load_attribute_plugins(args.plugins_dir, attributes)
Continue the code snippet: <|code_start|> default='attributes', dest='plugins_dir', help='Path to the folder containing your set of attribute plugins.' ) parser.add_argument( 'repository_id', type=int, nargs=1, help='Identifier for a project as it appears in the \ GHTorrent database.' ) parser.add_argument( 'repository_path', type=is_dir, nargs=1, help='Path to the repository source code.' ) if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ args = process_arguments() <|code_end|> . Use current file imports: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and context (classes, functions, or code) from other files: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
config = process_configuration(args.config_file)
Given snippet: <|code_start|> type=int, nargs=1, help='Identifier for a project as it appears in the \ GHTorrent database.' ) parser.add_argument( 'repository_path', type=is_dir, nargs=1, help='Path to the repository source code.' ) if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ args = process_arguments() config = process_configuration(args.config_file) connection = establish_database_connection(config['options']['datasource']) attributes = config['attributes'] load_attribute_plugins(args.plugins_dir, attributes) init_attribute_plugins(attributes, connection) <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and context: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): which might include code, classes, or functions. Output only the next line.
score, results = process_repository(
Given the code snippet: <|code_start|> if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ args = process_arguments() config = process_configuration(args.config_file) connection = establish_database_connection(config['options']['datasource']) attributes = config['attributes'] load_attribute_plugins(args.plugins_dir, attributes) init_attribute_plugins(attributes, connection) score, results = process_repository( args.repository_id[0], args.repository_path[0], attributes, connection ) if config['options'].get('persistResult', False): cursor = connection.cursor() run_id = get_run_id() <|code_end|> , generate the next line using the imports in this file: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and context (functions, classes, or occasionally code) from other files: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
save_result(run_id, args.repository_id, results, cursor)
Continue the code snippet: <|code_start|> ) if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ args = process_arguments() config = process_configuration(args.config_file) connection = establish_database_connection(config['options']['datasource']) attributes = config['attributes'] load_attribute_plugins(args.plugins_dir, attributes) init_attribute_plugins(attributes, connection) score, results = process_repository( args.repository_id[0], args.repository_path[0], attributes, connection ) if config['options'].get('persistResult', False): cursor = connection.cursor() <|code_end|> . Use current file imports: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and context (classes, functions, or code) from other files: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
run_id = get_run_id()
Continue the code snippet: <|code_start|>#!/usr/bin/env python3 def process_arguments(): """ Uses the argparse module to parse commandline arguments. Returns: Dictionary of parsed commandline arguments. """ parser = argparse.ArgumentParser( description='Calculate the score of a repository.' ) parser.add_argument( '-c', '--config', type=argparse.FileType('r'), default='config.json', dest='config_file', help='Path to the configuration file.' ) parser.add_argument( '-p', '--plugins', <|code_end|> . Use current file imports: import argparse import os import random import sys import threading import time from lib.core import establish_database_connection from lib.core import init_attribute_plugins from lib.core import load_attribute_plugins from lib.core import process_configuration from lib.core import process_repository from lib.core import save_result from lib.core import get_run_id from lib.utilities import is_dir and context (classes, functions, or code) from other files: # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/core.py # class Tokenizer(): # def __init__(self): # def tokenize(self, url): # def get_token(self): # def print_warning(self, message): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
type=is_dir,
Given the following code snippet before the placeholder: <|code_start|> jsondata = dict() try: if jsonfile: jsondata = json.load(jsonfile) return jsondata except: raise Exception('Failure in loading JSON data {0}'.format( jsonfile.name )) finally: jsonfile.close() def parse_datetime_delta(datetime_delta): """Parse specification of datetime delta of the form nynmndnHnMnS Parameters ---------- datetime_delta : str A string of the form nynmndnHnMnS. All components of the specification are optional. Note that the component specifiers are case-sensitive. Returns ------- relativedelta : lib.dateutil.relativedelta An instance of lib.dateutil.relativedelta representing the datetime delta specified in the argument to this function. A value of zero is set for each component that is not specfied in the argument. """ <|code_end|> , predict the next line using imports from the current file: import argparse import io import json import os import shlex import subprocess import urllib.request import re import tarfile from tempfile import NamedTemporaryFile from lib import dateutil and context including class names, function names, and sometimes code from other files: # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): . Output only the next line.
delta = dateutil.relativedelta()
Continue the code snippet: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] self.database = database.Database(settings) def test_main(self): # Arrange project_id = 10868464 # andymeneely/squib options = {'threshold': 1, 'cutoff': 0.8} # Act try: self.database.connect() with self.database.cursor() as cursor: <|code_end|> . Use current file imports: import json import os import unittest from attributes.community import main from lib import database and context (classes, functions, or code) from other files: # Path: attributes/community/main.py # QUERY = ''' # SELECT c.author_id, COUNT(*) # FROM commits c JOIN project_commits pc # ON pc.commit_id = c.id # WHERE pc.project_id = {0} # GROUP BY c.author_id # ORDER BY COUNT(*) DESC # ''' # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): . Output only the next line.
(result, value) = main.run(project_id, '', cursor, **options)
Here is a snippet: <|code_start|> class MainTestCase(unittest.TestCase): def setUp(self): path = ( os.path.join( os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir ) ), 'config.json' ) ) settings = None with open(path, 'r') as file_: settings = json.load(file_)['options']['datasource'] <|code_end|> . Write the next line using the current file imports: import json import os import unittest from attributes.community import main from lib import database and context from other files: # Path: attributes/community/main.py # QUERY = ''' # SELECT c.author_id, COUNT(*) # FROM commits c JOIN project_commits pc # ON pc.commit_id = c.id # WHERE pc.project_id = {0} # GROUP BY c.author_id # ORDER BY COUNT(*) DESC # ''' # def run(project_id, repo_path, cursor, **options): # # Path: lib/database.py # class DatabaseError(Exception): # class Database(object): # def __init__(self, value): # def __str__(self): # def __init__(self, settings): # def connect(self): # def disconnect(self): # def get(self, query): # def post(self, query, data=None): # def cursor(self): # def _connected(self): # def __getstate__(self): # def __setstate__(self, state): , which may include functions, classes, or code. Output only the next line.
self.database = database.Database(settings)
Given the code snippet: <|code_start|> MAP = { 'C': ['C', 'C/C++ Header'], 'C++': ['C++', 'C/C++ Header'], 'Objective C': ['Objective C', 'C/C++ Header'] } def run(project_id, repo_path, cursor, **options): threshold = options.get('threshold', 0) query = 'SELECT language FROM projects WHERE id = %d' % project_id cursor.execute(query) record = cursor.fetchone() language = record[0] languages = MAP[language] if language in MAP else [language] <|code_end|> , generate the next line using the imports in this file: import sys from lib import utilities and context (functions, classes, or occasionally code) from other files: # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
sloc = utilities.get_loc(repo_path)
Given snippet: <|code_start|> QUERY = ''' SELECT MAX(c.created_at) FROM commits c JOIN project_commits pc ON pc.commit_id = c.id WHERE pc.project_id = {0} and c.created_at > 0 ''' def run(project_id, repo_path, cursor, **options): bresult = False rresult = 'dormant' cursor.execute(QUERY.format(project_id)) result = cursor.fetchone() last_commit_date = result[0] if last_commit_date is not None: # Compute the delta between the last commit in the database and today. # Note: today may be the date the GHTorrent dump was published by # ghtorrent.org today = options.get('today', datetime.today().date()) if isinstance(today, str): today = datetime.strptime(today, '%Y-%m-%d') <|code_end|> , continue by predicting the next line. Consider current file imports: import sys from datetime import datetime from lib import dateutil from lib import utilities and context: # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): which might include code, classes, or functions. Output only the next line.
delta = dateutil.relativedelta(today, last_commit_date)
Predict the next line after this snippet: <|code_start|> QUERY = ''' SELECT MAX(c.created_at) FROM commits c JOIN project_commits pc ON pc.commit_id = c.id WHERE pc.project_id = {0} and c.created_at > 0 ''' def run(project_id, repo_path, cursor, **options): bresult = False rresult = 'dormant' cursor.execute(QUERY.format(project_id)) result = cursor.fetchone() last_commit_date = result[0] if last_commit_date is not None: # Compute the delta between the last commit in the database and today. # Note: today may be the date the GHTorrent dump was published by # ghtorrent.org today = options.get('today', datetime.today().date()) if isinstance(today, str): today = datetime.strptime(today, '%Y-%m-%d') delta = dateutil.relativedelta(today, last_commit_date) <|code_end|> using the current file's imports: import sys from datetime import datetime from lib import dateutil from lib import utilities and any relevant context from other files: # Path: lib/dateutil.py # class relativedelta(relativedelta.relativedelta): # def total_hours(self): # def total_minutes(self): # def total_seconds(self): # def __lt__(self, other): # def __gt__(self, other): # def __le__(self, other): # def __ge__(self, other): # # Path: lib/utilities.py # TOKENIZER = None # ACK_LANGUAGE_MAP = { # 'c': 'cc', # 'c++': 'cpp', # 'c#': 'csharp', # 'objective-c': 'objc', # 'ojective-c++': 'objcpp', # } # def get_cache_hits(): # def get_loc(path, files=None): # def search( # pattern, path, recursive=True, whole=False, ignorecase=False, include=None, # exclude=None # ): # def url_to_json(url, headers={}): # def get_repo_path(repo_id, repositories_dir): # def clone(owner, name, directory, date=None): # def read(jsonfile): # def parse_datetime_delta(datetime_delta): # def is_cloneable(owner, name): # def get_files(path, language): . Output only the next line.
threshold = utilities.parse_datetime_delta(options['threshold'])