Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> # Non-market-aware mode requires a timedelta. else: assert self.delta and not self.window_length, \ "Non-market-aware mode requires a timedelta." # No way to pass arguments to the defaultdict factory, so we # need to define a method to generate the correct EventWindows. self.sid_windows = defaultdict(self.create_window) def create_window(self): """Factory method for self.sid_windows.""" return VWAPEventWindow( self.market_aware, window_length=self.window_length, delta=self.delta ) def update(self, event): """ Update the event window for this event's sid. Returns the current vwap for the sid. """ # This will create a new EventWindow if this is the first # message for this sid. window = self.sid_windows[event.sid] window.update(event) return window.get_vwap() <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import defaultdict from alephnull.errors import WrongDataForTransform from alephnull.transforms.utils import EventWindow, TransformMeta and context: # Path: alephnull/transforms/utils.py # class EventWindow(object): # """ # Abstract base class for transform classes that calculate iterative # metrics on events within a given timedelta. Maintains a list of # events that are within a certain timedelta of the most recent # tick. Calls self.handle_add(event) for each event added to the # window. Calls self.handle_remove(event) for each event removed # from the window. Subclass these methods along with init(*args, # **kwargs) to calculate metrics over the window. # # If the market_aware flag is True, the EventWindow drops old events # based on the number of elapsed trading days between newest and oldest. # Otherwise old events are dropped based on a raw timedelta. # # See zipline/transforms/mavg.py and zipline/transforms/vwap.py for example # implementations of moving average and volume-weighted average # price. # """ # # Mark this as an abstract base class. # __metaclass__ = ABCMeta # # def __init__(self, market_aware=True, window_length=None, delta=None): # # check_window_length(window_length) # self.window_length = window_length # # self.ticks = deque() # # # Only Market-aware mode is now supported. # if not market_aware: # raise UnsupportedEventWindowFlagValue( # "Non-'market aware' mode is no longer supported." # ) # if delta: # raise UnsupportedEventWindowFlagValue( # "delta values are no longer supported." # ) # # Set the behavior for dropping events from the back of the # # event window. # self.drop_condition = self.out_of_market_window # # @abstractmethod # def handle_add(self, event): # raise NotImplementedError() # # @abstractmethod # def handle_remove(self, event): # raise NotImplementedError() # # def __len__(self): # return len(self.ticks) # # def update(self, event): # # if (hasattr(event, 'type') # and event.type not in ( # DATASOURCE_TYPE.TRADE, # DATASOURCE_TYPE.CUSTOM)): # return # # self.assert_well_formed(event) # # Add new event and increment totals. # self.ticks.append(event) # # # Subclasses should override handle_add to define behavior for # # adding new ticks. # self.handle_add(event) # # Clear out any expired events. # # # # oldest newest # # | | # # V V # while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt): # # # popleft removes and returns the oldest tick in self.ticks # popped = self.ticks.popleft() # # # Subclasses should override handle_remove to define # # behavior for removing ticks. # self.handle_remove(popped) # # def out_of_market_window(self, oldest, newest): # oldest_index = \ # trading.environment.trading_days.searchsorted(oldest) # newest_index = \ # trading.environment.trading_days.searchsorted(newest) # # trading_days_between = newest_index - oldest_index # # # "Put back" a day if oldest is earlier in its day than newest, # # reflecting the fact that we haven't yet completed the last # # day in the window. # if oldest.time() > newest.time(): # trading_days_between -= 1 # # return trading_days_between >= self.window_length # # # All event windows expect to receive events with datetime fields # # that arrive in sorted order. # def assert_well_formed(self, event): # assert isinstance(event.dt, datetime), \ # "Bad dt in EventWindow:%s" % event # if len(self.ticks) > 0: # # Something is wrong if new event is older than previous. # assert event.dt >= self.ticks[-1].dt, \ # "Events arrived out of order in EventWindow: %s -> %s" % \ # (event, self.ticks[0]) # # class TransformMeta(type): # """ # Metaclass that automatically packages a class inside of # StatefulTransform on initialization. Specifically, if Foo is a # class with its __metaclass__ attribute set to TransformMeta, then # calling Foo(*args, **kwargs) will return StatefulTransform(Foo, # *args, **kwargs) instead of an instance of Foo. (Note that you can # still recover an instance of a "raw" Foo by introspecting the # resulting StatefulTransform's 'state' field.) # """ # # def __call__(cls, *args, **kwargs): # return StatefulTransform(cls, *args, **kwargs) which might include code, classes, or functions. Output only the next line.
class VWAPEventWindow(EventWindow):
Given the code snippet: <|code_start|> """ There should only ever be one TSC in the system, so we don't bother passing args into the hash. """ return self.__class__.__name__ + hash_args() def __init__(self, algo, sim_params): # ============== # Simulation # Param Setup # ============== self.sim_params = sim_params # ============== # Algo Setup # ============== self.algo = algo self.algo_start = self.sim_params.first_open self.algo_start = self.algo_start.replace(hour=0, minute=0, second=0, microsecond=0) # ============== # Snapshot Setup # ============== # The algorithm's data as of our most recent event. # We want an object that will have empty objects as default # values on missing keys. <|code_end|> , generate the next line using the imports in this file: from logbook import Logger, Processor from alephnull.protocol import ( BarData, SIDData, DATASOURCE_TYPE ) from alephnull.gens.utils import hash_args import alephnull.finance.trading as trading and context (functions, classes, or occasionally code) from other files: # Path: alephnull/protocol.py # class BarData(object): # """ # Holds the event data for all sids for a given dt. # # This is what is passed as `data` to the `handle_data` function. # # Note: Many methods are analogues of dictionary because of historical # usage of what this replaced as a dictionary subclass. # """ # # def __init__(self): # self._data = {} # self._contains_override = None # # def __contains__(self, name): # if self._contains_override: # if self._contains_override(name): # return name in self._data # else: # return False # else: # return name in self._data # # def has_key(self, name): # """ # DEPRECATED: __contains__ is preferred, but this method is for # compatibility with existing algorithms. # """ # return name in self # # def __setitem__(self, name, value): # self._data[name] = value # # def __getitem__(self, name): # return self._data[name] # # def __delitem__(self, name): # del self._data[name] # # def __iter__(self): # for sid, data in self._data.iteritems(): # # Allow contains override to filter out sids. # if sid in self: # if len(data): # yield sid # # def iterkeys(self): # # Allow contains override to filter out sids. # return (sid for sid in self._data.iterkeys() if sid in self) # # def keys(self): # # Allow contains override to filter out sids. # return list(self.iterkeys()) # # def itervalues(self): # return (value for sid, value in self.iteritems()) # # def values(self): # return list(self.itervalues()) # # def iteritems(self): # return ((sid, value) for sid, value # in self._data.iteritems() # if sid in self) # # def items(self): # return list(self.iteritems()) # # def __len__(self): # return len(self.keys()) # # class SIDData(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return self.__dict__[name] # # def __setitem__(self, name, value): # self.__dict__[name] = value # # def __len__(self): # return len(self.__dict__) # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "SIDData({0})".format(self.__dict__) # # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() . Output only the next line.
self.current_data = BarData()
Given the code snippet: <|code_start|> trading.environment.next_open_and_close( mkt_close ) self.algo.perf_tracker.handle_intraday_close() risk_message = self.algo.perf_tracker.handle_simulation_end() yield risk_message def get_message(self, date): rvars = self.algo.recorded_vars if self.algo.perf_tracker.emission_rate == 'daily': perf_message = \ self.algo.perf_tracker.handle_market_close() perf_message['daily_perf']['recorded_vars'] = rvars return perf_message elif self.algo.perf_tracker.emission_rate == 'minute': self.algo.perf_tracker.handle_minute_close(date) perf_message = self.algo.perf_tracker.to_dict() perf_message['minute_perf']['recorded_vars'] = rvars return perf_message def update_universe(self, event): """ Update the universe with new event information. """ # Update our knowledge of this event's sid if hasattr(event, 'contract'): if event.sid not in self.current_data.__dict__['_data']: <|code_end|> , generate the next line using the imports in this file: from logbook import Logger, Processor from alephnull.protocol import ( BarData, SIDData, DATASOURCE_TYPE ) from alephnull.gens.utils import hash_args import alephnull.finance.trading as trading and context (functions, classes, or occasionally code) from other files: # Path: alephnull/protocol.py # class BarData(object): # """ # Holds the event data for all sids for a given dt. # # This is what is passed as `data` to the `handle_data` function. # # Note: Many methods are analogues of dictionary because of historical # usage of what this replaced as a dictionary subclass. # """ # # def __init__(self): # self._data = {} # self._contains_override = None # # def __contains__(self, name): # if self._contains_override: # if self._contains_override(name): # return name in self._data # else: # return False # else: # return name in self._data # # def has_key(self, name): # """ # DEPRECATED: __contains__ is preferred, but this method is for # compatibility with existing algorithms. # """ # return name in self # # def __setitem__(self, name, value): # self._data[name] = value # # def __getitem__(self, name): # return self._data[name] # # def __delitem__(self, name): # del self._data[name] # # def __iter__(self): # for sid, data in self._data.iteritems(): # # Allow contains override to filter out sids. # if sid in self: # if len(data): # yield sid # # def iterkeys(self): # # Allow contains override to filter out sids. # return (sid for sid in self._data.iterkeys() if sid in self) # # def keys(self): # # Allow contains override to filter out sids. # return list(self.iterkeys()) # # def itervalues(self): # return (value for sid, value in self.iteritems()) # # def values(self): # return list(self.itervalues()) # # def iteritems(self): # return ((sid, value) for sid, value # in self._data.iteritems() # if sid in self) # # def items(self): # return list(self.iteritems()) # # def __len__(self): # return len(self.keys()) # # class SIDData(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return self.__dict__[name] # # def __setitem__(self, name, value): # self.__dict__[name] = value # # def __len__(self): # return len(self.__dict__) # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "SIDData({0})".format(self.__dict__) # # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() . Output only the next line.
self.current_data[event.sid] = {event.contract: SIDData()}
Predict the next line for this snippet: <|code_start|> for txn, order in process_trade(event): if txn.amount != 0: self.algo.perf_tracker.process_event(txn) self.algo.perf_tracker.process_event(order) self.algo.perf_tracker.process_event(event) def transform(self, stream_in): """ Main generator work loop. """ # Initialize the mkt_close mkt_close = self.algo.perf_tracker.market_close # inject the current algo # snapshot time to any log record generated. with self.processor.threadbound(): updated = False bm_updated = False for date, snapshot in stream_in: self.algo.set_datetime(date) self.simulation_dt = date self.algo.perf_tracker.set_date(date) self.algo.blotter.set_date(date) # If we're still in the warmup period. Use the event to # update our universe, but don't yield any perf messages, # and don't send a snapshot to handle_data. if date < self.algo_start: for event in snapshot: <|code_end|> with the help of current file imports: from logbook import Logger, Processor from alephnull.protocol import ( BarData, SIDData, DATASOURCE_TYPE ) from alephnull.gens.utils import hash_args import alephnull.finance.trading as trading and context from other files: # Path: alephnull/protocol.py # class BarData(object): # """ # Holds the event data for all sids for a given dt. # # This is what is passed as `data` to the `handle_data` function. # # Note: Many methods are analogues of dictionary because of historical # usage of what this replaced as a dictionary subclass. # """ # # def __init__(self): # self._data = {} # self._contains_override = None # # def __contains__(self, name): # if self._contains_override: # if self._contains_override(name): # return name in self._data # else: # return False # else: # return name in self._data # # def has_key(self, name): # """ # DEPRECATED: __contains__ is preferred, but this method is for # compatibility with existing algorithms. # """ # return name in self # # def __setitem__(self, name, value): # self._data[name] = value # # def __getitem__(self, name): # return self._data[name] # # def __delitem__(self, name): # del self._data[name] # # def __iter__(self): # for sid, data in self._data.iteritems(): # # Allow contains override to filter out sids. # if sid in self: # if len(data): # yield sid # # def iterkeys(self): # # Allow contains override to filter out sids. # return (sid for sid in self._data.iterkeys() if sid in self) # # def keys(self): # # Allow contains override to filter out sids. # return list(self.iterkeys()) # # def itervalues(self): # return (value for sid, value in self.iteritems()) # # def values(self): # return list(self.itervalues()) # # def iteritems(self): # return ((sid, value) for sid, value # in self._data.iteritems() # if sid in self) # # def items(self): # return list(self.iteritems()) # # def __len__(self): # return len(self.keys()) # # class SIDData(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return self.__dict__[name] # # def __setitem__(self, name, value): # self.__dict__[name] = value # # def __len__(self): # return len(self.__dict__) # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "SIDData({0})".format(self.__dict__) # # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() , which may contain function names, class names, or code. Output only the next line.
if event.type == DATASOURCE_TYPE.SPLIT:
Here is a snippet: <|code_start|># Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log = Logger('Trade Simulation') class AlgorithmSimulator(object): EMISSION_TO_PERF_KEY_MAP = { 'minute': 'minute_perf', 'daily': 'daily_perf' } def get_hash(self): """ There should only ever be one TSC in the system, so we don't bother passing args into the hash. """ <|code_end|> . Write the next line using the current file imports: from logbook import Logger, Processor from alephnull.protocol import ( BarData, SIDData, DATASOURCE_TYPE ) from alephnull.gens.utils import hash_args import alephnull.finance.trading as trading and context from other files: # Path: alephnull/protocol.py # class BarData(object): # """ # Holds the event data for all sids for a given dt. # # This is what is passed as `data` to the `handle_data` function. # # Note: Many methods are analogues of dictionary because of historical # usage of what this replaced as a dictionary subclass. # """ # # def __init__(self): # self._data = {} # self._contains_override = None # # def __contains__(self, name): # if self._contains_override: # if self._contains_override(name): # return name in self._data # else: # return False # else: # return name in self._data # # def has_key(self, name): # """ # DEPRECATED: __contains__ is preferred, but this method is for # compatibility with existing algorithms. # """ # return name in self # # def __setitem__(self, name, value): # self._data[name] = value # # def __getitem__(self, name): # return self._data[name] # # def __delitem__(self, name): # del self._data[name] # # def __iter__(self): # for sid, data in self._data.iteritems(): # # Allow contains override to filter out sids. # if sid in self: # if len(data): # yield sid # # def iterkeys(self): # # Allow contains override to filter out sids. # return (sid for sid in self._data.iterkeys() if sid in self) # # def keys(self): # # Allow contains override to filter out sids. # return list(self.iterkeys()) # # def itervalues(self): # return (value for sid, value in self.iteritems()) # # def values(self): # return list(self.itervalues()) # # def iteritems(self): # return ((sid, value) for sid, value # in self._data.iteritems() # if sid in self) # # def items(self): # return list(self.iteritems()) # # def __len__(self): # return len(self.keys()) # # class SIDData(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return self.__dict__[name] # # def __setitem__(self, name, value): # self.__dict__[name] = value # # def __len__(self): # return len(self.__dict__) # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "SIDData({0})".format(self.__dict__) # # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() , which may include functions, classes, or code. Output only the next line.
return self.__class__.__name__ + hash_args()
Given the following code snippet before the placeholder: <|code_start|> if 'expected_transactions' in test.zipline_test_config: test.assertEqual( test.zipline_test_config['expected_transactions'], transaction_count ) else: test.assertEqual( test.zipline_test_config['order_count'], transaction_count ) # the final message is the risk report, the second to # last is the final day's results. Positions is a list of # dicts. closing_positions = output[-2]['daily_perf']['positions'] # confirm that all orders were filled. # iterate over the output updates, overwriting # orders when they are updated. Then check the status on all. orders_by_id = {} for update in output: if 'daily_perf' in update: if 'orders' in update['daily_perf']: for order in update['daily_perf']['orders']: orders_by_id[order['id']] = order for order in orders_by_id.itervalues(): test.assertEqual( order['status'], <|code_end|> , predict the next line using imports from the current file: from logbook import FileHandler from alephnull.finance.blotter import ORDER_STATUS and context including class names, function names, and sometimes code from other files: # Path: alephnull/finance/blotter.py # ORDER_STATUS = Enum( # 'OPEN', # 'FILLED', # 'CANCELLED' # ) . Output only the next line.
ORDER_STATUS.FILLED,
Predict the next line after this snippet: <|code_start|># limitations under the License. # log = Logger('Blotter') ORDER_STATUS = Enum( 'OPEN', 'FILLED', 'CANCELLED' ) # On an order to buy, between .05 below to .95 above a penny, use that penny. # On an order to sell, between .05 above to .95 below a penny, use that penny. # buy: [.0095, .0195) -> round to .01, sell: (.0005, .0105] -> round to .01 def round_for_minimum_price_variation(x, is_buy, diff=(0.0095 - .005)): # relies on rounding half away from zero, unlike numpy's bankers' rounding rounded = round(x - (diff if is_buy else -diff), 2) if zp_math.tolerant_equals(rounded, 0.0): return 0.0 return rounded class Blotter(object): def __init__(self): <|code_end|> using the current file's imports: import math import uuid import numpy as np import alephnull.errors import alephnull.protocol as zp import alephnull.utils.math_utils as zp_math from copy import copy from collections import defaultdict from logbook import Logger from alephnull.finance.slippage import ( VolumeShareSlippage, transact_partial, check_order_triggers ) from alephnull.finance.commission import PerShare from alephnull.utils.protocol_utils import Enum and any relevant context from other files: # Path: alephnull/finance/slippage.py # class VolumeShareSlippage(SlippageModel): # def __init__(self, # volume_limit=.25, # price_impact=0.1): # # self.volume_limit = volume_limit # self.price_impact = price_impact # # def __repr__(self): # return """ # {class_name}( # volume_limit={volume_limit}, # price_impact={price_impact}) # """.strip().format(class_name=self.__class__.__name__, # volume_limit=self.volume_limit, # price_impact=self.price_impact) # # def process_order(self, event, order): # # max_volume = self.volume_limit * event.volume # # # price impact accounts for the total volume of transactions # # created against the current minute bar # remaining_volume = max_volume - self.volume_for_bar # if remaining_volume < 1: # # we can't fill any more transactions # return # # # the current order amount will be the min of the # # volume available in the bar or the open amount. # cur_volume = int(min(remaining_volume, abs(order.open_amount))) # # if cur_volume < 1: # return # # # tally the current amount into our total amount ordered. # # total amount will be used to calculate price impact # total_volume = self.volume_for_bar + cur_volume # # volume_share = min(total_volume / event.volume, # self.volume_limit) # # simulated_impact = (volume_share) ** 2 \ # * math.copysign(self.price_impact, order.direction) \ # * event.price # # return create_transaction( # event, # order, # # In the future, we may want to change the next line # # for limit pricing # event.price + simulated_impact, # math.copysign(cur_volume, order.direction) # ) # # def transact_partial(slippage, commission): # return partial(transact_stub, slippage, commission) # # def check_order_triggers(order, event): # """ # Given an order and a trade event, return a tuple of # (stop_reached, limit_reached). # For market orders, will return (False, False). # For stop orders, limit_reached will always be False. # For limit orders, stop_reached will always be False. # # Orders that have been triggered already (price targets reached), # the order's current values are returned. # """ # if order.triggered: # return (order.stop_reached, order.limit_reached) # # stop_reached = False # limit_reached = False # # if the stop price is reached, simply set stop_reached # if order.stop is not None: # if (order.direction * (event.price - order.stop) <= 0): # # convert stop -> limit or market # stop_reached = True # # # if the limit price is reached, we execute this order at # # (event.price + simulated_impact) # # we skip this order with a continue when the limit is not reached # if order.limit is not None: # # if limit conditions not met, then continue # if (order.direction * (event.price - order.limit) <= 0): # limit_reached = True # # return (stop_reached, limit_reached) . Output only the next line.
self.transact = transact_partial(VolumeShareSlippage(), PerShare())
Given snippet: <|code_start|># limitations under the License. # log = Logger('Blotter') ORDER_STATUS = Enum( 'OPEN', 'FILLED', 'CANCELLED' ) # On an order to buy, between .05 below to .95 above a penny, use that penny. # On an order to sell, between .05 above to .95 below a penny, use that penny. # buy: [.0095, .0195) -> round to .01, sell: (.0005, .0105] -> round to .01 def round_for_minimum_price_variation(x, is_buy, diff=(0.0095 - .005)): # relies on rounding half away from zero, unlike numpy's bankers' rounding rounded = round(x - (diff if is_buy else -diff), 2) if zp_math.tolerant_equals(rounded, 0.0): return 0.0 return rounded class Blotter(object): def __init__(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import math import uuid import numpy as np import alephnull.errors import alephnull.protocol as zp import alephnull.utils.math_utils as zp_math from copy import copy from collections import defaultdict from logbook import Logger from alephnull.finance.slippage import ( VolumeShareSlippage, transact_partial, check_order_triggers ) from alephnull.finance.commission import PerShare from alephnull.utils.protocol_utils import Enum and context: # Path: alephnull/finance/slippage.py # class VolumeShareSlippage(SlippageModel): # def __init__(self, # volume_limit=.25, # price_impact=0.1): # # self.volume_limit = volume_limit # self.price_impact = price_impact # # def __repr__(self): # return """ # {class_name}( # volume_limit={volume_limit}, # price_impact={price_impact}) # """.strip().format(class_name=self.__class__.__name__, # volume_limit=self.volume_limit, # price_impact=self.price_impact) # # def process_order(self, event, order): # # max_volume = self.volume_limit * event.volume # # # price impact accounts for the total volume of transactions # # created against the current minute bar # remaining_volume = max_volume - self.volume_for_bar # if remaining_volume < 1: # # we can't fill any more transactions # return # # # the current order amount will be the min of the # # volume available in the bar or the open amount. # cur_volume = int(min(remaining_volume, abs(order.open_amount))) # # if cur_volume < 1: # return # # # tally the current amount into our total amount ordered. # # total amount will be used to calculate price impact # total_volume = self.volume_for_bar + cur_volume # # volume_share = min(total_volume / event.volume, # self.volume_limit) # # simulated_impact = (volume_share) ** 2 \ # * math.copysign(self.price_impact, order.direction) \ # * event.price # # return create_transaction( # event, # order, # # In the future, we may want to change the next line # # for limit pricing # event.price + simulated_impact, # math.copysign(cur_volume, order.direction) # ) # # def transact_partial(slippage, commission): # return partial(transact_stub, slippage, commission) # # def check_order_triggers(order, event): # """ # Given an order and a trade event, return a tuple of # (stop_reached, limit_reached). # For market orders, will return (False, False). # For stop orders, limit_reached will always be False. # For limit orders, stop_reached will always be False. # # Orders that have been triggered already (price targets reached), # the order's current values are returned. # """ # if order.triggered: # return (order.stop_reached, order.limit_reached) # # stop_reached = False # limit_reached = False # # if the stop price is reached, simply set stop_reached # if order.stop is not None: # if (order.direction * (event.price - order.stop) <= 0): # # convert stop -> limit or market # stop_reached = True # # # if the limit price is reached, we execute this order at # # (event.price + simulated_impact) # # we skip this order with a continue when the limit is not reached # if order.limit is not None: # # if limit conditions not met, then continue # if (order.direction * (event.price - order.limit) <= 0): # limit_reached = True # # return (stop_reached, limit_reached) which might include code, classes, or functions. Output only the next line.
self.transact = transact_partial(VolumeShareSlippage(), PerShare())
Given the code snippet: <|code_start|> self.filled = filled self.status = ORDER_STATUS.OPEN self.stop = stop self.limit = limit self.stop_reached = False self.limit_reached = False self.direction = math.copysign(1, self.amount) self.type = zp.DATASOURCE_TYPE.ORDER def make_id(self): return uuid.uuid4().hex def to_dict(self): py = copy(self.__dict__) for field in ['type', 'direction']: del py[field] return py def to_api_obj(self): pydict = self.to_dict() obj = zp.Order(initial_values=pydict) return obj def check_triggers(self, event): """ Update internal state based on price triggers and the trade event's price. """ stop_reached, limit_reached = \ <|code_end|> , generate the next line using the imports in this file: import math import uuid import numpy as np import alephnull.errors import alephnull.protocol as zp import alephnull.utils.math_utils as zp_math from copy import copy from collections import defaultdict from logbook import Logger from alephnull.finance.slippage import ( VolumeShareSlippage, transact_partial, check_order_triggers ) from alephnull.finance.commission import PerShare from alephnull.utils.protocol_utils import Enum and context (functions, classes, or occasionally code) from other files: # Path: alephnull/finance/slippage.py # class VolumeShareSlippage(SlippageModel): # def __init__(self, # volume_limit=.25, # price_impact=0.1): # # self.volume_limit = volume_limit # self.price_impact = price_impact # # def __repr__(self): # return """ # {class_name}( # volume_limit={volume_limit}, # price_impact={price_impact}) # """.strip().format(class_name=self.__class__.__name__, # volume_limit=self.volume_limit, # price_impact=self.price_impact) # # def process_order(self, event, order): # # max_volume = self.volume_limit * event.volume # # # price impact accounts for the total volume of transactions # # created against the current minute bar # remaining_volume = max_volume - self.volume_for_bar # if remaining_volume < 1: # # we can't fill any more transactions # return # # # the current order amount will be the min of the # # volume available in the bar or the open amount. # cur_volume = int(min(remaining_volume, abs(order.open_amount))) # # if cur_volume < 1: # return # # # tally the current amount into our total amount ordered. # # total amount will be used to calculate price impact # total_volume = self.volume_for_bar + cur_volume # # volume_share = min(total_volume / event.volume, # self.volume_limit) # # simulated_impact = (volume_share) ** 2 \ # * math.copysign(self.price_impact, order.direction) \ # * event.price # # return create_transaction( # event, # order, # # In the future, we may want to change the next line # # for limit pricing # event.price + simulated_impact, # math.copysign(cur_volume, order.direction) # ) # # def transact_partial(slippage, commission): # return partial(transact_stub, slippage, commission) # # def check_order_triggers(order, event): # """ # Given an order and a trade event, return a tuple of # (stop_reached, limit_reached). # For market orders, will return (False, False). # For stop orders, limit_reached will always be False. # For limit orders, stop_reached will always be False. # # Orders that have been triggered already (price targets reached), # the order's current values are returned. # """ # if order.triggered: # return (order.stop_reached, order.limit_reached) # # stop_reached = False # limit_reached = False # # if the stop price is reached, simply set stop_reached # if order.stop is not None: # if (order.direction * (event.price - order.stop) <= 0): # # convert stop -> limit or market # stop_reached = True # # # if the limit price is reached, we execute this order at # # (event.price + simulated_impact) # # we skip this order with a continue when the limit is not reached # if order.limit is not None: # # if limit conditions not met, then continue # if (order.direction * (event.price - order.limit) <= 0): # limit_reached = True # # return (stop_reached, limit_reached) . Output only the next line.
check_order_triggers(self, event)
Given snippet: <|code_start|>Tools to generate data sources. """ class DataFrameSource(DataSource): """ Yields all events in event_list that match the given sid_filter. If no event_list is specified, generates an internal stream of events to filter. Returns all events if filter is None. Configuration options: sids : list of values representing simulated internal sids start : start date delta : timedelta between internal events filter : filter to remove the sids """ def __init__(self, data, **kwargs): assert isinstance(data.index, pd.tseries.index.DatetimeIndex) self.data = data # Unpack config dictionary with default values. self.sids = kwargs.get('sids', data.columns) self.start = kwargs.get('start', data.index[0]) self.end = kwargs.get('end', data.index[-1]) # Hash_value for downstream sorting. <|code_end|> , continue by predicting the next line. Consider current file imports: import pandas as pd from alephnull.gens.utils import hash_args from alephnull.sources.data_source import DataSource and context: # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() # # Path: alephnull/sources/data_source.py # class DataSource(object): # # __metaclass__ = ABCMeta # # @property # def event_type(self): # return DATASOURCE_TYPE.TRADE # # @property # def mapping(self): # """ # Mappings of the form: # target_key: (mapping_function, source_key) # """ # return {} # # @abstractproperty # def raw_data(self): # """ # An iterator that yields the raw datasource, # in chronological order of data, one event at a time. # """ # NotImplemented # # @abstractproperty # def instance_hash(self): # """ # A hash that represents the unique args to the source. # """ # pass # # def get_hash(self): # return self.__class__.__name__ + "-" + self.instance_hash # # def apply_mapping(self, raw_row): # """ # Override this to hand craft conversion of row. # """ # row = {target: mapping_func(raw_row[source_key]) # for target, (mapping_func, source_key) # in self.mapping.items()} # row.update({'source_id': self.get_hash()}) # row.update({'type': self.event_type}) # return row # # @property # def mapped_data(self): # for row in self.raw_data: # yield Event(self.apply_mapping(row)) # # def __iter__(self): # return self # # def next(self): # return self.mapped_data.next() which might include code, classes, or functions. Output only the next line.
self.arg_string = hash_args(data, **kwargs)
Predict the next line for this snippet: <|code_start|> all_ = pd.concat(frames, axis=1).T try: all_ = all_.groupby(axis=0, level=0).apply(logic).reset_index( level=(0, 2), drop=True) except: all_ = all_.groupby(axis=0, level=0).apply(logic) #Todo: handle multiple contract returns all_ = all_.groupby(axis=0, level=0).agg(lambda x: x.max()) #Todo: Data should be reconstructed into BarData object data = all_.T.to_dict() front_months = [(sym, all_.ix[sym]['contract']) for sym in all_.index] back_months = [sym for sym in self.perf_tracker.get_portfolio().positions if sym not in front_months] offsets = {} for sym in back_months: offsets[sym] = 0 for order_id in self.get_orders(sym): order = self.blotter.orders[order_id] if order.status != 3: offsets[sym] += (order.amount - order.filled) stack = self.perf_tracker.get_portfolio().positions[sym].amount + offsets[sym] if stack != 0: self.order(sym, -stack) [self.order(exp, stack) for exp in front_months if exp[0] == sym[0]] <|code_end|> with the help of current file imports: import pandas as pd from pandas import Series, DataFrame from alephnull.protocol import BarData, SIDData and context from other files: # Path: alephnull/protocol.py # class BarData(object): # """ # Holds the event data for all sids for a given dt. # # This is what is passed as `data` to the `handle_data` function. # # Note: Many methods are analogues of dictionary because of historical # usage of what this replaced as a dictionary subclass. # """ # # def __init__(self): # self._data = {} # self._contains_override = None # # def __contains__(self, name): # if self._contains_override: # if self._contains_override(name): # return name in self._data # else: # return False # else: # return name in self._data # # def has_key(self, name): # """ # DEPRECATED: __contains__ is preferred, but this method is for # compatibility with existing algorithms. # """ # return name in self # # def __setitem__(self, name, value): # self._data[name] = value # # def __getitem__(self, name): # return self._data[name] # # def __delitem__(self, name): # del self._data[name] # # def __iter__(self): # for sid, data in self._data.iteritems(): # # Allow contains override to filter out sids. # if sid in self: # if len(data): # yield sid # # def iterkeys(self): # # Allow contains override to filter out sids. # return (sid for sid in self._data.iterkeys() if sid in self) # # def keys(self): # # Allow contains override to filter out sids. # return list(self.iterkeys()) # # def itervalues(self): # return (value for sid, value in self.iteritems()) # # def values(self): # return list(self.itervalues()) # # def iteritems(self): # return ((sid, value) for sid, value # in self._data.iteritems() # if sid in self) # # def items(self): # return list(self.iteritems()) # # def __len__(self): # return len(self.keys()) # # class SIDData(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return self.__dict__[name] # # def __setitem__(self, name, value): # self.__dict__[name] = value # # def __len__(self): # return len(self.__dict__) # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "SIDData({0})".format(self.__dict__) , which may contain function names, class names, or code. Output only the next line.
bar_data = BarData()
Based on the snippet: <|code_start|> try: all_ = all_.groupby(axis=0, level=0).apply(logic).reset_index( level=(0, 2), drop=True) except: all_ = all_.groupby(axis=0, level=0).apply(logic) #Todo: handle multiple contract returns all_ = all_.groupby(axis=0, level=0).agg(lambda x: x.max()) #Todo: Data should be reconstructed into BarData object data = all_.T.to_dict() front_months = [(sym, all_.ix[sym]['contract']) for sym in all_.index] back_months = [sym for sym in self.perf_tracker.get_portfolio().positions if sym not in front_months] offsets = {} for sym in back_months: offsets[sym] = 0 for order_id in self.get_orders(sym): order = self.blotter.orders[order_id] if order.status != 3: offsets[sym] += (order.amount - order.filled) stack = self.perf_tracker.get_portfolio().positions[sym].amount + offsets[sym] if stack != 0: self.order(sym, -stack) [self.order(exp, stack) for exp in front_months if exp[0] == sym[0]] bar_data = BarData() <|code_end|> , predict the immediate next line with the help of imports: import pandas as pd from pandas import Series, DataFrame from alephnull.protocol import BarData, SIDData and context (classes, functions, sometimes code) from other files: # Path: alephnull/protocol.py # class BarData(object): # """ # Holds the event data for all sids for a given dt. # # This is what is passed as `data` to the `handle_data` function. # # Note: Many methods are analogues of dictionary because of historical # usage of what this replaced as a dictionary subclass. # """ # # def __init__(self): # self._data = {} # self._contains_override = None # # def __contains__(self, name): # if self._contains_override: # if self._contains_override(name): # return name in self._data # else: # return False # else: # return name in self._data # # def has_key(self, name): # """ # DEPRECATED: __contains__ is preferred, but this method is for # compatibility with existing algorithms. # """ # return name in self # # def __setitem__(self, name, value): # self._data[name] = value # # def __getitem__(self, name): # return self._data[name] # # def __delitem__(self, name): # del self._data[name] # # def __iter__(self): # for sid, data in self._data.iteritems(): # # Allow contains override to filter out sids. # if sid in self: # if len(data): # yield sid # # def iterkeys(self): # # Allow contains override to filter out sids. # return (sid for sid in self._data.iterkeys() if sid in self) # # def keys(self): # # Allow contains override to filter out sids. # return list(self.iterkeys()) # # def itervalues(self): # return (value for sid, value in self.iteritems()) # # def values(self): # return list(self.itervalues()) # # def iteritems(self): # return ((sid, value) for sid, value # in self._data.iteritems() # if sid in self) # # def items(self): # return list(self.iteritems()) # # def __len__(self): # return len(self.keys()) # # class SIDData(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return self.__dict__[name] # # def __setitem__(self, name, value): # self.__dict__[name] = value # # def __len__(self): # return len(self.__dict__) # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "SIDData({0})".format(self.__dict__) . Output only the next line.
bar_data.__dict__['_data'].update({k: SIDData(v) for k, v in data.iteritems()})
Predict the next line after this snippet: <|code_start|> for date, group in grouped_events: for event in group: perf_tracker.process_event(event) msg = perf_tracker.handle_market_close() perf_messages.append(msg) self.assertEqual(perf_tracker.txn_count, len(txns)) self.assertEqual(perf_tracker.txn_count, len(orders)) cumulative_pos = perf_tracker.cumulative_performance.positions[sid] expected_size = len(txns) / 2 * -25 self.assertEqual(cumulative_pos.amount, expected_size) self.assertEqual(len(perf_messages), sim_params.days_in_period) def trades_with_txns(self, events, no_txn_dt): for event in events: # create a transaction for all but # first trade in each sid, to simulate None transaction if event.dt != no_txn_dt: order = Order( sid=event.sid, amount=-25, dt=event.dt ) yield order yield event <|code_end|> using the current file's imports: import collections import heapq import logging import operator import unittest import datetime import pytz import itertools import zipline.utils.factory as factory import zipline.finance.performance as perf import zipline.utils.math_utils as zp_math import zipline.protocol from nose_parameterized import parameterized from zipline.finance.slippage import Transaction, create_transaction from zipline.gens.composites import date_sorted_sources from zipline.finance.trading import SimulationParameters from zipline.finance.blotter import Order from zipline.finance import trading from zipline.protocol import DATASOURCE_TYPE from zipline.utils.factory import create_random_simulation_parameters from zipline.protocol import Event and any relevant context from other files: # Path: zipline/finance/slippage.py # class Transaction(object): # # def __init__(self, sid, amount, dt, price, order_id, commission=None): # self.sid = sid # self.amount = amount # self.dt = dt # self.price = price # self.order_id = order_id # self.commission = commission # self.type = DATASOURCE_TYPE.TRANSACTION # # def __getitem__(self, name): # return self.__dict__[name] # # def to_dict(self): # py = copy(self.__dict__) # del py['type'] # return py # # def create_transaction(event, order, price, amount): # # # floor the amount to protect against non-whole number orders # # TODO: Investigate whether we can add a robust check in blotter # # and/or tradesimulation, as well. # amount_magnitude = int(abs(amount)) # # if amount_magnitude < 1: # raise Exception("Transaction magnitude must be at least 1.") # # transaction = Transaction( # sid=event.sid, # amount=int(amount), # dt=event.dt, # price=price, # order_id=order.id # ) # # return transaction . Output only the next line.
txn = Transaction(
Using the snippet: <|code_start|># # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.getLogger('Test Perf Tracking') onesec = datetime.timedelta(seconds=1) oneday = datetime.timedelta(days=1) tradingday = datetime.timedelta(hours=6, minutes=30) def create_txn(event, price, amount): mock_order = Order(None, None, event.sid, id=None) <|code_end|> , determine the next line of code. You have imports: import collections import heapq import logging import operator import unittest import datetime import pytz import itertools import zipline.utils.factory as factory import zipline.finance.performance as perf import zipline.utils.math_utils as zp_math import zipline.protocol from nose_parameterized import parameterized from zipline.finance.slippage import Transaction, create_transaction from zipline.gens.composites import date_sorted_sources from zipline.finance.trading import SimulationParameters from zipline.finance.blotter import Order from zipline.finance import trading from zipline.protocol import DATASOURCE_TYPE from zipline.utils.factory import create_random_simulation_parameters from zipline.protocol import Event and context (class names, function names, or code) available: # Path: zipline/finance/slippage.py # class Transaction(object): # # def __init__(self, sid, amount, dt, price, order_id, commission=None): # self.sid = sid # self.amount = amount # self.dt = dt # self.price = price # self.order_id = order_id # self.commission = commission # self.type = DATASOURCE_TYPE.TRANSACTION # # def __getitem__(self, name): # return self.__dict__[name] # # def to_dict(self): # py = copy(self.__dict__) # del py['type'] # return py # # def create_transaction(event, order, price, amount): # # # floor the amount to protect against non-whole number orders # # TODO: Investigate whether we can add a robust check in blotter # # and/or tradesimulation, as well. # amount_magnitude = int(abs(amount)) # # if amount_magnitude < 1: # raise Exception("Transaction magnitude must be at least 1.") # # transaction = Transaction( # sid=event.sid, # amount=int(amount), # dt=event.dt, # price=price, # order_id=order.id # ) # # return transaction . Output only the next line.
return create_transaction(event, mock_order, price, amount)
Given snippet: <|code_start|> beta value for the same period as all other values Returns: float. The alpha of the algorithm. """ return algorithm_period_return - \ (treasury_period_return + beta * (benchmark_period_returns - treasury_period_return)) ########################### # End Risk Metric Section # ########################### def get_treasury_rate(treasury_curves, treasury_duration, day): rate = None curve = treasury_curves.ix[day] # 1month note data begins in 8/2001, # so we can use 3month instead. idx = TREASURY_DURATIONS.index(treasury_duration) for duration in TREASURY_DURATIONS[idx:]: rate = curve[duration] if rate is not None: break return rate def search_day_distance(end_date, dt): <|code_end|> , continue by predicting the next line. Consider current file imports: import logbook import numpy as np import alephnull.utils.math_utils as zp_math from alephnull.finance import trading and context: # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): which might include code, classes, or functions. Output only the next line.
tdd = trading.environment.trading_day_distance(dt, end_date)
Based on the snippet: <|code_start|>""" Unit tests for finance.slippage """ class SlippageTestCase(TestCase): def test_volume_share_slippage(self): event = Event( {'volume': 200, 'type': 4, 'price': 3.0, 'datetime': datetime.datetime( 2006, 1, 5, 14, 31, tzinfo=pytz.utc), 'high': 3.15, 'low': 2.85, 'sid': 133, 'source_id': 'test_source', 'close': 3.0, 'dt': datetime.datetime(2006, 1, 5, 14, 31, tzinfo=pytz.utc), 'open': 3.0} ) <|code_end|> , predict the immediate next line with the help of imports: import datetime import pytz import pandas as pd from unittest import TestCase from nose_parameterized import parameterized from zipline.finance.slippage import VolumeShareSlippage from zipline.protocol import Event, DATASOURCE_TYPE from zipline.finance.blotter import Order and context (classes, functions, sometimes code) from other files: # Path: zipline/finance/slippage.py # class VolumeShareSlippage(SlippageModel): # # def __init__(self, # volume_limit=.25, # price_impact=0.1): # # self.volume_limit = volume_limit # self.price_impact = price_impact # # def __repr__(self): # return """ # {class_name}( # volume_limit={volume_limit}, # price_impact={price_impact}) # """.strip().format(class_name=self.__class__.__name__, # volume_limit=self.volume_limit, # price_impact=self.price_impact) # # def process_order(self, event, order): # # max_volume = self.volume_limit * event.volume # # # price impact accounts for the total volume of transactions # # created against the current minute bar # remaining_volume = max_volume - self.volume_for_bar # if remaining_volume < 1: # # we can't fill any more transactions # return # # # the current order amount will be the min of the # # volume available in the bar or the open amount. # cur_volume = int(min(remaining_volume, abs(order.open_amount))) # # if cur_volume < 1: # return # # # tally the current amount into our total amount ordered. # # total amount will be used to calculate price impact # total_volume = self.volume_for_bar + cur_volume # # volume_share = min(total_volume / event.volume, # self.volume_limit) # # simulated_impact = (volume_share) ** 2 \ # * math.copysign(self.price_impact, order.direction) \ # * event.price # # return create_transaction( # event, # order, # # In the future, we may want to change the next line # # for limit pricing # event.price + simulated_impact, # math.copysign(cur_volume, order.direction) # ) . Output only the next line.
slippage_model = VolumeShareSlippage()
Next line prediction: <|code_start|># # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Returns(object): """ Class that maintains a dictionary from sids to the sid's closing price N trading days ago. """ <|code_end|> . Use current file imports: (from alephnull.errors import WrongDataForTransform from alephnull.transforms.utils import TransformMeta from collections import defaultdict, deque) and context including class names, function names, or small code snippets from other files: # Path: alephnull/transforms/utils.py # class TransformMeta(type): # """ # Metaclass that automatically packages a class inside of # StatefulTransform on initialization. Specifically, if Foo is a # class with its __metaclass__ attribute set to TransformMeta, then # calling Foo(*args, **kwargs) will return StatefulTransform(Foo, # *args, **kwargs) instead of an instance of Foo. (Note that you can # still recover an instance of a "raw" Foo by introspecting the # resulting StatefulTransform's 'state' field.) # """ # # def __call__(cls, *args, **kwargs): # return StatefulTransform(cls, *args, **kwargs) . Output only the next line.
__metaclass__ = TransformMeta
Using the snippet: <|code_start|># You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def hash_args(*args, **kwargs): """Define a unique string for any set of representable args.""" arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in kwargs.iteritems()]) combined = ':'.join([arg_string, kwarg_string]) hasher = md5() hasher.update(combined) return hasher.hexdigest() def assert_datasource_protocol(event): """Assert that an event meets the protocol for datasource outputs.""" assert isinstance(event.source_id, basestring) <|code_end|> , determine the next line of code. You have imports: import pytz import numbers from hashlib import md5 from datetime import datetime from alephnull.protocol import DATASOURCE_TYPE and context (class names, function names, or code) available: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) . Output only the next line.
assert event.type in DATASOURCE_TYPE
Given snippet: <|code_start|># # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. DEFAULT_TIMEOUT = 15 # seconds EXTENDED_TIMEOUT = 90 class ExceptionTestCase(TestCase): def setUp(self): self.zipline_test_config = { 'sid': 133, <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import TestCase from zipline.test_algorithms import ( ExceptionAlgorithm, DivByZeroAlgorithm, SetPortfolioAlgorithm, ) from zipline.finance.slippage import FixedSlippage from zipline.transforms.utils import StatefulTransform from zipline.utils.test_utils import ( drain_zipline, setup_logger, teardown_logger, ExceptionSource, ExceptionTransform ) import zipline.utils.simfactory as simfactory import zipline.utils.factory as factory and context: # Path: zipline/finance/slippage.py # class FixedSlippage(SlippageModel): # # def __init__(self, spread=0.0): # """ # Use the fixed slippage model, which will just add/subtract # a specified spread spread/2 will be added on buys and subtracted # on sells per share # """ # self.spread = spread # # def process_order(self, event, order): # return create_transaction( # event, # order, # event.price + (self.spread / 2.0 * order.direction), # order.amount, # ) which might include code, classes, or functions. Output only the next line.
'slippage': FixedSlippage()
Using the snippet: <|code_start|> | _metrics | calculated based on the positions aggregated | | | through all the events delivered to this tracker. | | | For details look at the comments for | | | :py:meth:`zipline.finance.risk.RiskMetrics.to_dict`| +-----------------+----------------------------------------------------+ """ from __future__ import division log = logbook.Logger('Performance') class BasePerformanceTracker(object): """ Tracks the performance of the algorithm. """ def __init__(self, sim_params, perf_tracker_class): self.sim_params = sim_params self.perf_tracker_class = perf_tracker_class self.period_start = self.sim_params.period_start self.period_end = self.sim_params.period_end self.last_close = self.sim_params.last_close first_day = self.sim_params.first_open self.market_open, self.market_close = \ <|code_end|> , determine the next line of code. You have imports: import logbook import pandas as pd import alephnull.protocol as zp import alephnull.finance.risk as risk from pandas.tseries.tools import normalize_date from alephnull.finance import trading from . period import PerformancePeriod from . futures_period import FuturesPerformancePeriod and context (class names, function names, or code) available: # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): . Output only the next line.
trading.environment.get_open_and_close(first_day)
Given snippet: <|code_start|> # responsibility of creating an instance to # TransformMeta's parent class, which is 'type'. This is # what is implicitly done behind the scenes by the python # interpreter for most classes anyway, but here we have to # be explicit because we've overridden the method that # usually resolves to our super call. self.state = super(TransformMeta, tnfm_class).__call__( *args, **kwargs) # Normal object instantiation. else: self.state = tnfm_class(*args, **kwargs) # save the window_length of the state for external access. self.window_length = self.state.window_length # Create the string associated with this generator's output. self.namestring = tnfm_class.__name__ + hash_args(*args, **kwargs) def get_hash(self): return self.namestring def transform(self, stream_in): return self._gen(stream_in) def _gen(self, stream_in): # IMPORTANT: Messages may contain pointers that are shared with # other streams. Transforms that modify their input # messages should only manipulate copies. for message in stream_in: # we only handle TRADE events. if (hasattr(message, 'type') and message.type not in ( <|code_end|> , continue by predicting the next line. Consider current file imports: import types import logbook from numbers import Integral from datetime import datetime from collections import deque from abc import ABCMeta, abstractmethod from alephnull.protocol import DATASOURCE_TYPE from alephnull.gens.utils import assert_sort_unframe_protocol, hash_args from alephnull.finance import trading and context: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def assert_sort_unframe_protocol(event): # """Same as above.""" # assert isinstance(event.source_id, basestring) # assert event.type in DATASOURCE_TYPE # # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() # # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): which might include code, classes, or functions. Output only the next line.
DATASOURCE_TYPE.TRADE,
Here is a snippet: <|code_start|> else: self.state = tnfm_class(*args, **kwargs) # save the window_length of the state for external access. self.window_length = self.state.window_length # Create the string associated with this generator's output. self.namestring = tnfm_class.__name__ + hash_args(*args, **kwargs) def get_hash(self): return self.namestring def transform(self, stream_in): return self._gen(stream_in) def _gen(self, stream_in): # IMPORTANT: Messages may contain pointers that are shared with # other streams. Transforms that modify their input # messages should only manipulate copies. for message in stream_in: # we only handle TRADE events. if (hasattr(message, 'type') and message.type not in ( DATASOURCE_TYPE.TRADE, DATASOURCE_TYPE.CUSTOM)): yield message continue # allow upstream generators to yield None to avoid # blocking. if message is None: continue <|code_end|> . Write the next line using the current file imports: import types import logbook from numbers import Integral from datetime import datetime from collections import deque from abc import ABCMeta, abstractmethod from alephnull.protocol import DATASOURCE_TYPE from alephnull.gens.utils import assert_sort_unframe_protocol, hash_args from alephnull.finance import trading and context from other files: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def assert_sort_unframe_protocol(event): # """Same as above.""" # assert isinstance(event.source_id, basestring) # assert event.type in DATASOURCE_TYPE # # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() # # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): , which may include functions, classes, or code. Output only the next line.
assert_sort_unframe_protocol(message)
Given snippet: <|code_start|> update, the state class must produce a message to be fed downstream. Any transform class with the FORWARDER class variable set to true will forward all fields in the original message. Otherwise only dt, tnfm_id, and tnfm_value are forwarded. """ def __init__(self, tnfm_class, *args, **kwargs): assert isinstance(tnfm_class, (types.ObjectType, types.ClassType)), \ "Stateful transform requires a class." assert hasattr(tnfm_class, 'update'), \ "Stateful transform requires the class to have an update method" # Create an instance of our transform class. if isinstance(tnfm_class, TransformMeta): # Classes derived TransformMeta have their __call__ # attribute overridden. Since this is what is usually # used to create an instance, we have to delegate the # responsibility of creating an instance to # TransformMeta's parent class, which is 'type'. This is # what is implicitly done behind the scenes by the python # interpreter for most classes anyway, but here we have to # be explicit because we've overridden the method that # usually resolves to our super call. self.state = super(TransformMeta, tnfm_class).__call__( *args, **kwargs) # Normal object instantiation. else: self.state = tnfm_class(*args, **kwargs) # save the window_length of the state for external access. self.window_length = self.state.window_length # Create the string associated with this generator's output. <|code_end|> , continue by predicting the next line. Consider current file imports: import types import logbook from numbers import Integral from datetime import datetime from collections import deque from abc import ABCMeta, abstractmethod from alephnull.protocol import DATASOURCE_TYPE from alephnull.gens.utils import assert_sort_unframe_protocol, hash_args from alephnull.finance import trading and context: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def assert_sort_unframe_protocol(event): # """Same as above.""" # assert isinstance(event.source_id, basestring) # assert event.type in DATASOURCE_TYPE # # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() # # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): which might include code, classes, or functions. Output only the next line.
self.namestring = tnfm_class.__name__ + hash_args(*args, **kwargs)
Here is a snippet: <|code_start|> if (hasattr(event, 'type') and event.type not in ( DATASOURCE_TYPE.TRADE, DATASOURCE_TYPE.CUSTOM)): return self.assert_well_formed(event) # Add new event and increment totals. self.ticks.append(event) # Subclasses should override handle_add to define behavior for # adding new ticks. self.handle_add(event) # Clear out any expired events. # # oldest newest # | | # V V while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt): # popleft removes and returns the oldest tick in self.ticks popped = self.ticks.popleft() # Subclasses should override handle_remove to define # behavior for removing ticks. self.handle_remove(popped) def out_of_market_window(self, oldest, newest): oldest_index = \ <|code_end|> . Write the next line using the current file imports: import types import logbook from numbers import Integral from datetime import datetime from collections import deque from abc import ABCMeta, abstractmethod from alephnull.protocol import DATASOURCE_TYPE from alephnull.gens.utils import assert_sort_unframe_protocol, hash_args from alephnull.finance import trading and context from other files: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def assert_sort_unframe_protocol(event): # """Same as above.""" # assert isinstance(event.source_id, basestring) # assert event.type in DATASOURCE_TYPE # # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() # # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): , which may include functions, classes, or code. Output only the next line.
trading.environment.trading_days.searchsorted(oldest)
Given the code snippet: <|code_start|> / algo_volatility) class RiskMetricsCumulative(object): """ :Usage: Instantiate RiskMetricsCumulative once. Call update() method on each dt to update the metrics. """ METRIC_NAMES = ( 'alpha', 'beta', 'sharpe', 'algorithm_volatility', 'benchmark_volatility', 'downside_risk', 'sortino', 'information', ) def __init__(self, sim_params, returns_frequency=None, create_first_day_stats=False): """ - @returns_frequency allows for configuration of the whether the benchmark and algorithm returns are in units of minutes or days, if `None` defaults to the `emission_rate` in `sim_params`. """ <|code_end|> , generate the next line using the imports in this file: import functools import logbook import math import numpy as np import alephnull.utils.math_utils as zp_math import pandas as pd from alephnull.finance import trading from pandas.tseries.tools import normalize_date from . risk import ( alpha, check_entry, choose_treasury, ) and context (functions, classes, or occasionally code) from other files: # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): . Output only the next line.
self.treasury_curves = trading.environment.treasury_curves
Based on the snippet: <|code_start|> self.full = False # Set to -inf essentially to cause update on first attempt. self.last_dt = pd.Timestamp('1900-1-1', tz='UTC') self.updated = False self.cached = None self.last_args = None self.last_kwargs = None # Data panel that provides bar information to fill in the window, # when no bar ticks are available from the data source generator # Used in universes that 'rollover', e.g. one that has a different # set of stocks per quarter self.supplemental_data = None self.rolling_panel = None self.daily_rolling_panel = None def handle_data(self, data, *args, **kwargs): """ Point of entry. Process an event frame. """ # extract dates dts = [event.datetime for event in data._data.itervalues()] # we have to provide the event with a dt. This is only for # checking if the event is outside the window or not so a # couple of seconds shouldn't matter. We don't add it to # the data parameter, because it would mix dt with the # sid keys. <|code_end|> , predict the immediate next line with the help of imports: import functools import logbook import numpy import pandas as pd from numbers import Integral from alephnull.utils.data import RollingPanel from alephnull.protocol import Event from alephnull.finance import trading from . utils import check_window_length and context (classes, functions, sometimes code) from other files: # Path: alephnull/protocol.py # class Event(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return getattr(self, name) # # def __setitem__(self, name, value): # setattr(self, name, value) # # def __delitem__(self, name): # delattr(self, name) # # def keys(self): # return self.__dict__.keys() # # def __eq__(self, other): # return self.__dict__ == other.__dict__ # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "Event({0})".format(self.__dict__) # # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): . Output only the next line.
event = Event()
Given the code snippet: <|code_start|>log = logbook.Logger('BatchTransform') func_map = {'open_price': 'first', 'close_price': 'last', 'low': 'min', 'high': 'max', 'volume': 'sum' } def get_sample_func(item): if item in func_map: return func_map[item] else: return 'last' def downsample_panel(minute_rp, daily_rp, mkt_close): """ @minute_rp is a rolling panel, which should have minutely rows @daily_rp is a rolling panel, which should have daily rows @dt is the timestamp to use when adding a frame to daily_rp Using the history in minute_rp, a new daily bar is created by downsampling. The data from the daily bar is then added to the daily rolling panel using add_frame. """ cur_panel = minute_rp.get_current() sids = minute_rp.minor_axis day_frame = pd.DataFrame(columns=sids, index=cur_panel.items) <|code_end|> , generate the next line using the imports in this file: import functools import logbook import numpy import pandas as pd from numbers import Integral from alephnull.utils.data import RollingPanel from alephnull.protocol import Event from alephnull.finance import trading from . utils import check_window_length and context (functions, classes, or occasionally code) from other files: # Path: alephnull/protocol.py # class Event(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return getattr(self, name) # # def __setitem__(self, name, value): # setattr(self, name, value) # # def __delitem__(self, name): # delattr(self, name) # # def keys(self): # return self.__dict__.keys() # # def __eq__(self, other): # return self.__dict__ == other.__dict__ # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "Event({0})".format(self.__dict__) # # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): . Output only the next line.
dt1 = trading.environment.normalize_date(mkt_close)
Here is a snippet: <|code_start|> sid_list = config.get('sid_list') if not sid_list: sid = config.get('sid') sid_list = [sid] concurrent_trades = config.get('concurrent_trades', False) if 'order_count' in config: order_count = config['order_count'] else: order_count = 100 if 'order_amount' in config: order_amount = config['order_amount'] else: order_amount = 100 if 'trade_count' in config: trade_count = config['trade_count'] else: # to ensure all orders are filled, we provide one more # trade than order trade_count = 101 #------------------- # Create the Algo #------------------- if 'algorithm' in config: test_algo = config['algorithm'] else: <|code_end|> . Write the next line using the current file imports: import alephnull.utils.factory as factory from alephnull.test_algorithms import TestAlgorithm and context from other files: # Path: alephnull/test_algorithms.py # class TestAlgorithm(TradingAlgorithm): # """ # This algorithm will send a specified number of orders, to allow unit tests # to verify the orders sent/received, transactions created, and positions # at the close of a simulation. # """ # # def initialize(self, sid, amount, order_count, sid_filter=None): # self.count = order_count # self.sid = sid # self.amount = amount # self.incr = 0 # # if sid_filter: # self.sid_filter = sid_filter # else: # self.sid_filter = [self.sid] # # def handle_data(self, data): # # place an order for 100 shares of sid # if self.incr < self.count: # self.order(self.sid, self.amount) # self.incr += 1 , which may include functions, classes, or code. Output only the next line.
test_algo = TestAlgorithm(
Predict the next line for this snippet: <|code_start|> # Create your views here. def post_list(request): posts = Post.objects.filter().order_by('-published_date') categories = Category.objects.filter().order_by('name') template_name = 'bamboo/post_list.html' context_data = {'posts': posts, 'categories': categories} return render(request, template_name, context_data) def post_list_by_tag(request, pk): posts = Post.objects.filter(category=pk).order_by('-published_date') categories = Category.objects.filter().order_by('name') template_name = 'bamboo/post_list_by_tag.html' context_data = {'posts': posts, 'categories': categories} return render(request, template_name, context_data) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) template_name = 'bamboo/post_detail.html' context_data = {'post': post, } return render(request, template_name, context_data) def post_new(request): if request.method == "POST": <|code_end|> with the help of current file imports: from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from .models import Post, Category from .forms import PostForm, CommentForm, PasswordCheckForm and context from other files: # Path: bamboo/models.py # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Category(models.Model): # # class Meta: # # ordering = ['name'] # name = models.CharField(verbose_name=u'이름', max_length=50) # slug = models.SlugField(unique=True, null=True, blank=True) # description = models.TextField(verbose_name=u'말머리 설명', blank=True) # # def __str__(self): # return self.name # # Path: bamboo/forms.py # class PostForm(forms.ModelForm): # post_password = forms.CharField(widget=forms.PasswordInput) # # class Meta: # model = Post # fields = ('category', 'writer', 'post_password', 'title', 'text', ) # # class CommentForm(forms.ModelForm): # # class Meta: # model = Comment # fields = ('author', 'text', ) # # class PasswordCheckForm(forms.Form): # password = forms.CharField(widget=forms.PasswordInput) , which may contain function names, class names, or code. Output only the next line.
form = PostForm(request.POST)
Continue the code snippet: <|code_start|> return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'bamboo/post_edit.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) # post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'bamboo/post_edit.html', {'form': form}) def post_remove(request, pk): post = get_object_or_404(Post, pk=pk) post.delete() return redirect('post_list') def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": <|code_end|> . Use current file imports: from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from .models import Post, Category from .forms import PostForm, CommentForm, PasswordCheckForm and context (classes, functions, or code) from other files: # Path: bamboo/models.py # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Category(models.Model): # # class Meta: # # ordering = ['name'] # name = models.CharField(verbose_name=u'이름', max_length=50) # slug = models.SlugField(unique=True, null=True, blank=True) # description = models.TextField(verbose_name=u'말머리 설명', blank=True) # # def __str__(self): # return self.name # # Path: bamboo/forms.py # class PostForm(forms.ModelForm): # post_password = forms.CharField(widget=forms.PasswordInput) # # class Meta: # model = Post # fields = ('category', 'writer', 'post_password', 'title', 'text', ) # # class CommentForm(forms.ModelForm): # # class Meta: # model = Comment # fields = ('author', 'text', ) # # class PasswordCheckForm(forms.Form): # password = forms.CharField(widget=forms.PasswordInput) . Output only the next line.
form = CommentForm(request.POST)
Here is a snippet: <|code_start|> post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'bamboo/post_edit.html', {'form': form}) def post_remove(request, pk): post = get_object_or_404(Post, pk=pk) post.delete() return redirect('post_list') def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'bamboo/add_comment_to_post.html', {'form': form}) def post_edit_check_password(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": <|code_end|> . Write the next line using the current file imports: from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from .models import Post, Category from .forms import PostForm, CommentForm, PasswordCheckForm and context from other files: # Path: bamboo/models.py # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Category(models.Model): # # class Meta: # # ordering = ['name'] # name = models.CharField(verbose_name=u'이름', max_length=50) # slug = models.SlugField(unique=True, null=True, blank=True) # description = models.TextField(verbose_name=u'말머리 설명', blank=True) # # def __str__(self): # return self.name # # Path: bamboo/forms.py # class PostForm(forms.ModelForm): # post_password = forms.CharField(widget=forms.PasswordInput) # # class Meta: # model = Post # fields = ('category', 'writer', 'post_password', 'title', 'text', ) # # class CommentForm(forms.ModelForm): # # class Meta: # model = Comment # fields = ('author', 'text', ) # # class PasswordCheckForm(forms.Form): # password = forms.CharField(widget=forms.PasswordInput) , which may include functions, classes, or code. Output only the next line.
form = PasswordCheckForm(request.POST)
Here is a snippet: <|code_start|> # Register your models here. class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ['name']} list_display = ['id', 'name', 'slug'] list_editable = ['name', 'slug', 'description'] search_fields = ['name'] ordering = ['name'] class PostAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['published_date']}), ('Post 내용', {'fields': ['writer', 'title', 'text', 'post_password']}), ] list_display = ('title', 'published_date', 'category', 'post_password') list_display_links = ['title'] list_filter = ['published_date', 'category'] list_editable = ['category', ] search_fields = ['title', 'text', ] ordering = ['-published_date'] class CommentAdmin(admin.ModelAdmin): fields = ['created_date', 'author', 'text', ] <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from .models import Category, Post, Comment and context from other files: # Path: bamboo/models.py # class Category(models.Model): # # class Meta: # # ordering = ['name'] # name = models.CharField(verbose_name=u'이름', max_length=50) # slug = models.SlugField(unique=True, null=True, blank=True) # description = models.TextField(verbose_name=u'말머리 설명', blank=True) # # def __str__(self): # return self.name # # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Comment(models.Model): # post = models.ForeignKey( # 'bamboo.Post', # on_delete=models.CASCADE, # related_name='comments' # ) # author = models.CharField(max_length=200) # text = models.TextField() # created_date = models.DateTimeField(default=timezone.now) # approved_comment = models.BooleanField(default=False) # # def approve(self): # self.approved_comment = True # self.save() # # def __str__(self): # return self.text , which may include functions, classes, or code. Output only the next line.
admin.site.register(Category, CategoryAdmin)
Next line prediction: <|code_start|> # Register your models here. class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ['name']} list_display = ['id', 'name', 'slug'] list_editable = ['name', 'slug', 'description'] search_fields = ['name'] ordering = ['name'] class PostAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['published_date']}), ('Post 내용', {'fields': ['writer', 'title', 'text', 'post_password']}), ] list_display = ('title', 'published_date', 'category', 'post_password') list_display_links = ['title'] list_filter = ['published_date', 'category'] list_editable = ['category', ] search_fields = ['title', 'text', ] ordering = ['-published_date'] class CommentAdmin(admin.ModelAdmin): fields = ['created_date', 'author', 'text', ] admin.site.register(Category, CategoryAdmin) <|code_end|> . Use current file imports: (from django.contrib import admin from .models import Category, Post, Comment ) and context including class names, function names, or small code snippets from other files: # Path: bamboo/models.py # class Category(models.Model): # # class Meta: # # ordering = ['name'] # name = models.CharField(verbose_name=u'이름', max_length=50) # slug = models.SlugField(unique=True, null=True, blank=True) # description = models.TextField(verbose_name=u'말머리 설명', blank=True) # # def __str__(self): # return self.name # # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Comment(models.Model): # post = models.ForeignKey( # 'bamboo.Post', # on_delete=models.CASCADE, # related_name='comments' # ) # author = models.CharField(max_length=200) # text = models.TextField() # created_date = models.DateTimeField(default=timezone.now) # approved_comment = models.BooleanField(default=False) # # def approve(self): # self.approved_comment = True # self.save() # # def __str__(self): # return self.text . Output only the next line.
admin.site.register(Post, PostAdmin)
Predict the next line after this snippet: <|code_start|> # Register your models here. class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ['name']} list_display = ['id', 'name', 'slug'] list_editable = ['name', 'slug', 'description'] search_fields = ['name'] ordering = ['name'] class PostAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['published_date']}), ('Post 내용', {'fields': ['writer', 'title', 'text', 'post_password']}), ] list_display = ('title', 'published_date', 'category', 'post_password') list_display_links = ['title'] list_filter = ['published_date', 'category'] list_editable = ['category', ] search_fields = ['title', 'text', ] ordering = ['-published_date'] class CommentAdmin(admin.ModelAdmin): fields = ['created_date', 'author', 'text', ] admin.site.register(Category, CategoryAdmin) admin.site.register(Post, PostAdmin) <|code_end|> using the current file's imports: from django.contrib import admin from .models import Category, Post, Comment and any relevant context from other files: # Path: bamboo/models.py # class Category(models.Model): # # class Meta: # # ordering = ['name'] # name = models.CharField(verbose_name=u'이름', max_length=50) # slug = models.SlugField(unique=True, null=True, blank=True) # description = models.TextField(verbose_name=u'말머리 설명', blank=True) # # def __str__(self): # return self.name # # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Comment(models.Model): # post = models.ForeignKey( # 'bamboo.Post', # on_delete=models.CASCADE, # related_name='comments' # ) # author = models.CharField(max_length=200) # text = models.TextField() # created_date = models.DateTimeField(default=timezone.now) # approved_comment = models.BooleanField(default=False) # # def approve(self): # self.approved_comment = True # self.save() # # def __str__(self): # return self.text . Output only the next line.
admin.site.register(Comment, CommentAdmin)
Given snippet: <|code_start|> class PostForm(forms.ModelForm): post_password = forms.CharField(widget=forms.PasswordInput) class Meta: <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from .models import Post, Comment and context: # Path: bamboo/models.py # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Comment(models.Model): # post = models.ForeignKey( # 'bamboo.Post', # on_delete=models.CASCADE, # related_name='comments' # ) # author = models.CharField(max_length=200) # text = models.TextField() # created_date = models.DateTimeField(default=timezone.now) # approved_comment = models.BooleanField(default=False) # # def approve(self): # self.approved_comment = True # self.save() # # def __str__(self): # return self.text which might include code, classes, or functions. Output only the next line.
model = Post
Here is a snippet: <|code_start|> class PostForm(forms.ModelForm): post_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Post fields = ('category', 'writer', 'post_password', 'title', 'text', ) class CommentForm(forms.ModelForm): class Meta: <|code_end|> . Write the next line using the current file imports: from django import forms from .models import Post, Comment and context from other files: # Path: bamboo/models.py # class Post(models.Model): # # author = models.ForeignKey('auth.User', null=True) # writer = models.CharField(max_length=100) # title = models.CharField(max_length=200) # text = models.TextField() # # created_date = models.DateTimeField(default=timezone.now) # published_date = models.DateTimeField(blank=True, null=True) # category = models.ForeignKey(Category, default=1, blank=True) # post_password = models.CharField(verbose_name=u'password', max_length=100, default='', help_text="글을 수정하거나 지울 때 사용할 비밀번호를 적어주세요") # # def publish(self): # self.published_date = timezone.now() # self.save() # # def __str__(self): # return self.title # # class Comment(models.Model): # post = models.ForeignKey( # 'bamboo.Post', # on_delete=models.CASCADE, # related_name='comments' # ) # author = models.CharField(max_length=200) # text = models.TextField() # created_date = models.DateTimeField(default=timezone.now) # approved_comment = models.BooleanField(default=False) # # def approve(self): # self.approved_comment = True # self.save() # # def __str__(self): # return self.text , which may include functions, classes, or code. Output only the next line.
model = Comment
Continue the code snippet: <|code_start|> INSTALL_REQ = False def test_deepsea(): model = kipoi.get_model("DeepSEA/variantEffects") <|code_end|> . Use current file imports: import kipoi import kipoi_veff import kipoi_veff.snv_predict as sp import pytest import os from kipoi_veff.utils.generic import ModelInfoExtractor from kipoiseq.dataloaders.sequence import SeqIntervalDl from kipoi.pipeline import install_model_requirements and context (classes, functions, or code) from other files: # Path: kipoiseq/dataloaders/sequence.py # class SeqIntervalDl(Dataset): # """ # info: # doc: > # Dataloader for a combination of fasta and tab-delimited input files such as bed files. The dataloader extracts # regions from the fasta file as defined in the tab-delimited `intervals_file` and converts them into one-hot encoded # format. Returned sequences are of the type np.array with the shape inferred from the arguments: `alphabet_axis` # and `dummy_axis`. # args: # intervals_file: # doc: bed3+<columns> file path containing intervals + (optionally) labels # example: # url: https://raw.githubusercontent.com/kipoi/kipoiseq/master/tests/data/intervals_51bp.tsv # md5: a76e47b3df87fd514860cf27fdc10eb4 # fasta_file: # doc: Reference genome FASTA file path. # example: # url: https://raw.githubusercontent.com/kipoi/kipoiseq/master/tests/data/hg38_chr22_32000000_32300000.fa # md5: 01320157a250a3d2eea63e89ecf79eba # num_chr_fasta: # doc: True, the the dataloader will make sure that the chromosomes don't start with chr. # label_dtype: # doc: 'None, datatype of the task labels taken from the intervals_file. Example: str, int, float, np.float32' # auto_resize_len: # doc: None, required sequence length. # use_strand: # doc: reverse-complement fasta sequence if bed file defines negative strand. Requires a bed6 file # alphabet_axis: # doc: axis along which the alphabet runs (e.g. A,C,G,T for DNA) # dummy_axis: # doc: defines in which dimension a dummy axis should be added. None if no dummy axis is required. # alphabet: # doc: > # alphabet to use for the one-hot encoding. This defines the order of the one-hot encoding. # Can either be a list or a string: 'ACGT' or ['A, 'C', 'G', 'T']. Default: 'ACGT' # dtype: # doc: 'defines the numpy dtype of the returned array. Example: int, np.int32, np.float32, float' # ignore_targets: # doc: if True, don't return any target variables # # output_schema: # inputs: # name: seq # shape: (None, 4) # doc: One-hot encoded DNA sequence # special_type: DNASeq # associated_metadata: ranges # targets: # shape: (None,) # doc: (optional) values following the bed-entry - chr start end target1 target2 .... # metadata: # ranges: # type: GenomicRanges # doc: Ranges describing inputs.seq # postprocessing: # variant_effects: # bed_input: # - intervals_file # """ # # def __init__(self, # intervals_file, # fasta_file, # num_chr_fasta=False, # label_dtype=None, # auto_resize_len=None, # # max_seq_len=None, # use_strand=False, # alphabet_axis=1, # dummy_axis=None, # alphabet="ACGT", # ignore_targets=False, # dtype=None): # # core dataset, not using the one-hot encoding params # self.seq_dl = StringSeqIntervalDl(intervals_file, fasta_file, num_chr_fasta=num_chr_fasta, # label_dtype=label_dtype, auto_resize_len=auto_resize_len, # use_strand=use_strand, # ignore_targets=ignore_targets) # # self.input_transform = ReorderedOneHot(alphabet=alphabet, # dtype=dtype, # alphabet_axis=alphabet_axis, # dummy_axis=dummy_axis) # # def __len__(self): # return len(self.seq_dl) # # def __getitem__(self, idx): # ret = self.seq_dl[idx] # ret['inputs'] = self.input_transform(str(ret["inputs"])) # return ret # # @classmethod # def get_output_schema(cls): # """Get the output schema. Overrides the default `cls.output_schema` # """ # output_schema = deepcopy(cls.output_schema) # # # get the default kwargs # kwargs = default_kwargs(cls) # # # figure out the input shape # mock_input_transform = ReorderedOneHot(alphabet=kwargs['alphabet'], # dtype=kwargs['dtype'], # alphabet_axis=kwargs['alphabet_axis'], # dummy_axis=kwargs['dummy_axis']) # input_shape = mock_input_transform.get_output_shape( # kwargs['auto_resize_len']) # # # modify it # output_schema.inputs.shape = input_shape # # # (optionally) get rid of the target shape # if kwargs['ignore_targets']: # output_schema.targets = None # # return output_schema . Output only the next line.
mie = ModelInfoExtractor(model, SeqIntervalDl)
Predict the next line after this snippet: <|code_start|> class SwapAxes(object): """np.swapaxes wrapper If any if the axis is None, do nothing. """ def __init__(self, axis1=None, axis2=None): self.axis1 = axis1 self.axis2 = axis2 def __call__(self, x): if self.axis1 is None or self.axis2 is None: return x else: return np.swapaxes(x, self.axis1, self.axis2) # Intervals class ResizeInterval(object): """Resize the interval """ def __init__(self, width, anchor='center'): self.width = width self.anchor = anchor def __call__(self, interval): <|code_end|> using the current file's imports: import numpy as np import warnings from kipoiseq.transforms import functional as F from kipoiseq.utils import DNA, parse_alphabet, parse_dtype and any relevant context from other files: # Path: kipoiseq/transforms/functional.py # def _get_alphabet_dict(alphabet): # def _get_index_dict(alphabet): # def one_hot2token(arr): # def one_hot2string(arr, alphabet=DNA): # def rc_dna(seq): # def rc_rna(seq): # def tokenize(seq, alphabet=DNA, neutral_alphabet=["N"]): # def token2one_hot(tokens, alphabet_size=4, neutral_value=.25, dtype=None): # def one_hot(seq, alphabet=DNA, neutral_alphabet=['N'], neutral_value=.25, dtype=None): # def one_hot_dna(seq: str, # alphabet: list = DNA, # neutral_alphabet: str = 'N', # neutral_value: Any = 0.25, # dtype=np.float32) -> np.ndarray: # def to_uint8(string): # def pad(seq, length, value="N", anchor="center"): # def trim(seq, length, anchor="center"): # def fixed_len(seq, length, anchor="center", value="N"): # def resize_interval(interval, width, anchor='center'): # def translate(seq: str, hg38=False): # TRANSLATION_TABLE = { # 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M', # 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T', # 'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K', # 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R', # 'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L', # 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P', # 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q', # 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R', # 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V', # 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A', # 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E', # 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G', # 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S', # 'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L', # 'TAC': 'Y', 'TAT': 'Y', 'TAA': '_', 'TAG': '_', # 'TGC': 'C', 'TGT': 'C', 'TGA': '_', 'TGG': 'W', # } # TRANSLATION_TABLE_FOR_HG38 = { # 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M', # 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T', # 'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K', # 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R', # 'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L', # 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P', # 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q', # 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R', # 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V', # 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A', # 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E', # 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G', # 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S', # 'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L', # 'TAC': 'Y', 'TAT': 'Y', 'TAA': '_', 'TAG': '_', # 'TGC': 'C', 'TGT': 'C', 'TGA': 'U', 'TGG': 'W', # TGA to U instead of STOP codon # 'XXX': 'X', # ambiguous start # 'NNN': '' # empty string for ambiguous protein # } # # Path: kipoiseq/utils.py # DNA = ("A", "C", "G", "T") # # def parse_alphabet(alphabet): # if isinstance(alphabet, str): # return list(alphabet) # else: # return alphabet # # def parse_dtype(dtype): # if isinstance(dtype, string_types): # try: # return eval(dtype) # except Exception as e: # raise ValueError( # "Unable to parse dtype: {}. \nException: {}".format(dtype, e)) # else: # return dtype . Output only the next line.
return F.resize_interval(interval, self.width, self.anchor)
Continue the code snippet: <|code_start|># Intervals class ResizeInterval(object): """Resize the interval """ def __init__(self, width, anchor='center'): self.width = width self.anchor = anchor def __call__(self, interval): return F.resize_interval(interval, self.width, self.anchor) # Sequences class OneHot(object): """One-hot encode the sequence # Arguments alphabet: alphabet to use for the one-hot encoding. This defines the order of the one-hot encoding. Can either be a list or a string: 'ACGT' or ['A, 'C', 'G', 'T'] neutral_alphabet: which element to use neutral_value: value of the neutral element dtype: defines the numpy dtype of the returned array. alphabet_axis: axis along which the alphabet runs (e.g. A,C,G,T for DNA) dummy_axis: defines in which dimension a dummy axis should be added. None if no dummy axis is required. """ <|code_end|> . Use current file imports: import numpy as np import warnings from kipoiseq.transforms import functional as F from kipoiseq.utils import DNA, parse_alphabet, parse_dtype and context (classes, functions, or code) from other files: # Path: kipoiseq/transforms/functional.py # def _get_alphabet_dict(alphabet): # def _get_index_dict(alphabet): # def one_hot2token(arr): # def one_hot2string(arr, alphabet=DNA): # def rc_dna(seq): # def rc_rna(seq): # def tokenize(seq, alphabet=DNA, neutral_alphabet=["N"]): # def token2one_hot(tokens, alphabet_size=4, neutral_value=.25, dtype=None): # def one_hot(seq, alphabet=DNA, neutral_alphabet=['N'], neutral_value=.25, dtype=None): # def one_hot_dna(seq: str, # alphabet: list = DNA, # neutral_alphabet: str = 'N', # neutral_value: Any = 0.25, # dtype=np.float32) -> np.ndarray: # def to_uint8(string): # def pad(seq, length, value="N", anchor="center"): # def trim(seq, length, anchor="center"): # def fixed_len(seq, length, anchor="center", value="N"): # def resize_interval(interval, width, anchor='center'): # def translate(seq: str, hg38=False): # TRANSLATION_TABLE = { # 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M', # 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T', # 'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K', # 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R', # 'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L', # 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P', # 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q', # 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R', # 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V', # 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A', # 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E', # 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G', # 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S', # 'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L', # 'TAC': 'Y', 'TAT': 'Y', 'TAA': '_', 'TAG': '_', # 'TGC': 'C', 'TGT': 'C', 'TGA': '_', 'TGG': 'W', # } # TRANSLATION_TABLE_FOR_HG38 = { # 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M', # 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T', # 'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K', # 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R', # 'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L', # 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P', # 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q', # 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R', # 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V', # 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A', # 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E', # 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G', # 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S', # 'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L', # 'TAC': 'Y', 'TAT': 'Y', 'TAA': '_', 'TAG': '_', # 'TGC': 'C', 'TGT': 'C', 'TGA': 'U', 'TGG': 'W', # TGA to U instead of STOP codon # 'XXX': 'X', # ambiguous start # 'NNN': '' # empty string for ambiguous protein # } # # Path: kipoiseq/utils.py # DNA = ("A", "C", "G", "T") # # def parse_alphabet(alphabet): # if isinstance(alphabet, str): # return list(alphabet) # else: # return alphabet # # def parse_dtype(dtype): # if isinstance(dtype, string_types): # try: # return eval(dtype) # except Exception as e: # raise ValueError( # "Unable to parse dtype: {}. \nException: {}".format(dtype, e)) # else: # return dtype . Output only the next line.
def __init__(self, alphabet=DNA, neutral_alphabet='N', neutral_value=0.25, dtype=None):
Given snippet: <|code_start|>from __future__ import division from __future__ import absolute_import from __future__ import print_function # sequence -> array def _get_alphabet_dict(alphabet): return {l: i for i, l in enumerate(alphabet)} def _get_index_dict(alphabet): return {i: l for i, l in enumerate(alphabet)} def one_hot2token(arr): return arr.argmax(axis=2) <|code_end|> , continue by predicting the next line. Consider current file imports: from typing import Any from kipoiseq.utils import DNA from copy import deepcopy from six import string_types import numpy as np and context: # Path: kipoiseq/utils.py # DNA = ("A", "C", "G", "T") which might include code, classes, or functions. Output only the next line.
def one_hot2string(arr, alphabet=DNA):
Here is a snippet: <|code_start|>"""Test BedDataset """ def write_tmp(string, tmpdir): p = tmpdir.mkdir("bed-files").join("file2.txt") p.write(string) return str(p) def test_bed3(tmpdir): bed_file = write_tmp('chr1\t1\t2\nchr1\t1\t3', tmpdir) <|code_end|> . Write the next line using the current file imports: from kipoiseq.dataloaders.sequence import BedDataset from pybedtools import Interval import numpy as np import pytest and context from other files: # Path: kipoiseq/dataloaders/sequence.py # class BedDataset(object): # """Reads a tsv file in the following format: # ``` # chr start stop task1 task2 ... # ``` # # # Arguments # tsv_file: tsv file type # bed_columns: number of columns corresponding to the bed file. All the columns # after that will be parsed as targets # num_chr: if specified, 'chr' in the chromosome name will be dropped # label_dtype: specific data type for labels, Example: `float` or `np.float32` # ambiguous_mask: if specified, rows containing only ambiguous_mask values will be skipped # incl_chromosomes: exclusive list of chromosome names to include in the final dataset. # if not None, only these will be present in the dataset # excl_chromosomes: list of chromosome names to omit from the dataset. # ignore_targets: if True, target variables are ignored # """ # # # bed types accorging to # # https://www.ensembl.org/info/website/upload/bed.html # bed_types = [str, # chrom # int, # chromStart # int, # chromEnd # str, # name # str, # score, as str to prevent issues, also its useless # str, # strand # int, # thickStart # int, # thickEnd # str, # itemRbg # int, # blockCount # int, # blockSizes # int] # blockStarts # # def __init__(self, tsv_file, # label_dtype=None, # bed_columns=3, # num_chr=False, # ambiguous_mask=None, # incl_chromosomes=None, # excl_chromosomes=None, # ignore_targets=False): # # TODO - `chrom` column: use pd.Categorical for memory efficiency # self.tsv_file = tsv_file # self.bed_columns = bed_columns # self.num_chr = num_chr # self.label_dtype = label_dtype # self.ambiguous_mask = ambiguous_mask # self.incl_chromosomes = incl_chromosomes # self.excl_chromosomes = excl_chromosomes # self.ignore_targets = ignore_targets # # df_peek = pd.read_table(self.tsv_file, # header=None, # nrows=1, # sep='\t') # found_columns = df_peek.shape[1] # self.n_tasks = found_columns - self.bed_columns # if self.n_tasks < 0: # raise ValueError("BedDataset requires at least {} valid bed columns. Found only {} columns". # format(self.bed_columns, found_columns)) # # self.df = pd.read_table(self.tsv_file, # header=None, # dtype={i: d # for i, d in enumerate(self.bed_types[:self.bed_columns] + # [self.label_dtype] * self.n_tasks)}, # sep='\t') # if self.num_chr and self.df.iloc[0][0].startswith("chr"): # self.df[0] = self.df[0].str.replace("^chr", "") # if not self.num_chr and not self.df.iloc[0][0].startswith("chr"): # self.df[0] = "chr" + self.df[0] # # if ambiguous_mask is not None: # # exclude regions where only ambigous labels are present # self.df = self.df[~np.all( # self.df.iloc[:, self.bed_columns:] == ambiguous_mask, axis=1)] # # # omit data outside chromosomes # if incl_chromosomes is not None: # self.df = self.df[self.df[0].isin(incl_chromosomes)] # if excl_chromosomes is not None: # self.df = self.df[~self.df[0].isin(excl_chromosomes)] # # def __getitem__(self, idx): # """Returns (pybedtools.Interval, labels) # """ # row = self.df.iloc[idx] # # # TODO: use kipoiseq.dataclasses.interval instead of pybedtools # import pybedtools # interval = pybedtools.create_interval_from_list( # [to_scalar(x) for x in row.iloc[:self.bed_columns]]) # # if self.ignore_targets or self.n_tasks == 0: # labels = {} # else: # labels = row.iloc[self.bed_columns:].values.astype( # self.label_dtype) # return interval, labels # # def __len__(self): # return len(self.df) # # def get_targets(self): # return self.df.iloc[:, self.bed_columns:].values.astype(self.label_dtype) , which may include functions, classes, or code. Output only the next line.
bt = BedDataset(bed_file)
Predict the next line for this snippet: <|code_start|> pytestmark_gtf = pytest.mark.skipif(not os.path.isfile(gtf_file_GRCh38), reason="File does not exist") pytestmark_fasta = pytest.mark.skipif(not os.path.isfile(fasta_file_GRCh38), reason="File does not exist") pytestmark_vcf = pytest.mark.skipif(not os.path.isfile(vcf_file_for_testing_synonymous_mutations), reason="File does not exist") pytestmark_protein = pytest.mark.skipif(not os.path.isfile(protein_file_GRCh38), reason="File does not exist") @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def tse(): <|code_end|> with the help of current file imports: from tqdm import tqdm_notebook as tqdm from kipoiseq.extractors.protein import SingleVariantProteinVCFSeqExtractor, TranscriptSeqExtractor, SingleSeqProteinVCFSeqExtractor from kipoiseq.transforms.functional import translate from pyfaidx import Fasta from conftest import gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations, protein_file_GRCh38 import pytest import os import pandas as pd and context from other files: # Path: kipoiseq/extractors/protein.py # class SingleVariantProteinVCFSeqExtractor(SingleVariantExtractorMixin, ProteinVCFSeqExtractor): # pass # # class TranscriptSeqExtractor(GenericMultiIntervalSeqExtractor): # # def __init__(self, gtf_file, fasta_file): # self.fasta_file = str(fasta_file) # self.gtf_file = str(gtf_file) # # cds_fetcher = CDSFetcher(self.gtf_file) # # extractor = FastaStringExtractor(self.fasta_file, use_strand=False) # # super().__init__( # extractor=extractor, # interval_fetcher=cds_fetcher # ) # # @property # def df(self): # return self.extractor.df # # @property # def cds(self): # return self.extractor.df # # @classmethod # def _prepare_seq( # cls, # seqs: List[str], # intervals: List[Interval], # reverse_complement: Union[str, bool], # # **kwargs # ) -> str: # """ # Prepare the dna sequence in the final variant, which should be # translated in amino acid sequence # :param seqs: current dna sequence # :param intervals: the list of intervals corresponding to the sequence snippets # :param reverse_complement: should the dna be reverse-complemented? # :return: prepared dna sequence ready for translation into amino acid sequence # """ # seq = super()._prepare_seq( # seqs=seqs, # intervals=intervals, # reverse_complement=reverse_complement, # ) # tag = intervals[0].attrs["tag"] # seq = cut_transcript_seq(seq, tag) # return seq # # def get_protein_seq(self, transcript_id: str): # """ # Extract amino acid sequence for given transcript_id # :param transcript_id: # :return: amino acid sequence # """ # return translate(self.get_seq(transcript_id), hg38=True) # # class SingleSeqProteinVCFSeqExtractor(SingleSeqExtractorMixin, ProteinVCFSeqExtractor): # pass # # Path: kipoiseq/transforms/functional.py # def translate(seq: str, hg38=False): # """Translate the DNA/RNA sequence into AA. # # Note: it stops after it encounters a stop codon # # # Arguments # seq: DNA/RNA sequence # stop_none: return None if a stop codon is encountered # """ # if len(seq) % 3 != 0: # raise ValueError("len(seq) % 3 != 0") # # outl = [''] * (len(seq) // 3) # if hg38: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE_FOR_HG38[codon] # else: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE[codon] # # return "".join(outl) , which may contain function names, class names, or code. Output only the next line.
return TranscriptSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38)
Predict the next line after this snippet: <|code_start|>@pytestmark_vcf @pytestmark_protein @pytest.mark.xfail def test_hg38(tse): with open('err_transcripts', 'w+') as f: dfp = read_pep_fa(protein_file) dfp['transcript_id'] = dfp.transcript.str.split(".", n=1, expand=True)[0] #assert not dfp['transcript_id'].duplicated().any() dfp = dfp.set_index("transcript_id") #dfp = dfp[~dfp.chromosome.isnull()] assert len(tse) > 100 assert tse.transcripts.isin(dfp.index).all() div3_error = 0 seq_mismatch_err = 0 err_transcripts = [] for transcript_id in tqdm(tse.transcripts): # make sure all ids can be found in the proteome dna_seq = tse.get_seq(transcript_id) if dna_seq == "NNN": f.write(transcript_id+' has an ambiguous start and end.Skip!') continue # dna_seq = dna_seq[:(len(dna_seq) // 3) * 3] # if len(dna_seq) % 3 != 0: # div3_error += 1 # print("len(dna_seq) % 3 != 0: {}".format(transcript_id)) # err_transcripts.append({"transcript_id": transcript_id, "div3_err": True}) # continue if len(dna_seq) % 3 != 0: f.write(transcript_id) continue <|code_end|> using the current file's imports: from tqdm import tqdm_notebook as tqdm from kipoiseq.extractors.protein import SingleVariantProteinVCFSeqExtractor, TranscriptSeqExtractor, SingleSeqProteinVCFSeqExtractor from kipoiseq.transforms.functional import translate from pyfaidx import Fasta from conftest import gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations, protein_file_GRCh38 import pytest import os import pandas as pd and any relevant context from other files: # Path: kipoiseq/extractors/protein.py # class SingleVariantProteinVCFSeqExtractor(SingleVariantExtractorMixin, ProteinVCFSeqExtractor): # pass # # class TranscriptSeqExtractor(GenericMultiIntervalSeqExtractor): # # def __init__(self, gtf_file, fasta_file): # self.fasta_file = str(fasta_file) # self.gtf_file = str(gtf_file) # # cds_fetcher = CDSFetcher(self.gtf_file) # # extractor = FastaStringExtractor(self.fasta_file, use_strand=False) # # super().__init__( # extractor=extractor, # interval_fetcher=cds_fetcher # ) # # @property # def df(self): # return self.extractor.df # # @property # def cds(self): # return self.extractor.df # # @classmethod # def _prepare_seq( # cls, # seqs: List[str], # intervals: List[Interval], # reverse_complement: Union[str, bool], # # **kwargs # ) -> str: # """ # Prepare the dna sequence in the final variant, which should be # translated in amino acid sequence # :param seqs: current dna sequence # :param intervals: the list of intervals corresponding to the sequence snippets # :param reverse_complement: should the dna be reverse-complemented? # :return: prepared dna sequence ready for translation into amino acid sequence # """ # seq = super()._prepare_seq( # seqs=seqs, # intervals=intervals, # reverse_complement=reverse_complement, # ) # tag = intervals[0].attrs["tag"] # seq = cut_transcript_seq(seq, tag) # return seq # # def get_protein_seq(self, transcript_id: str): # """ # Extract amino acid sequence for given transcript_id # :param transcript_id: # :return: amino acid sequence # """ # return translate(self.get_seq(transcript_id), hg38=True) # # class SingleSeqProteinVCFSeqExtractor(SingleSeqExtractorMixin, ProteinVCFSeqExtractor): # pass # # Path: kipoiseq/transforms/functional.py # def translate(seq: str, hg38=False): # """Translate the DNA/RNA sequence into AA. # # Note: it stops after it encounters a stop codon # # # Arguments # seq: DNA/RNA sequence # stop_none: return None if a stop codon is encountered # """ # if len(seq) % 3 != 0: # raise ValueError("len(seq) % 3 != 0") # # outl = [''] * (len(seq) // 3) # if hg38: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE_FOR_HG38[codon] # else: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE[codon] # # return "".join(outl) . Output only the next line.
prot_seq = translate(dna_seq, hg38=True)
Based on the snippet: <|code_start|> def test_parse_alphabet(): assert parse_alphabet(['A', 'C']) == ['A', 'C'] assert parse_alphabet('AC') == ['A', 'C'] def test_parse_type(): with pytest.raises(Exception): <|code_end|> , predict the immediate next line with the help of imports: import pytest import numpy as np from kipoiseq.utils import parse_alphabet, parse_dtype and context (classes, functions, sometimes code) from other files: # Path: kipoiseq/utils.py # def parse_alphabet(alphabet): # if isinstance(alphabet, str): # return list(alphabet) # else: # return alphabet # # def parse_dtype(dtype): # if isinstance(dtype, string_types): # try: # return eval(dtype) # except Exception as e: # raise ValueError( # "Unable to parse dtype: {}. \nException: {}".format(dtype, e)) # else: # return dtype . Output only the next line.
parse_dtype('string')
Predict the next line for this snippet: <|code_start|> pytestmark_gtf = pytest.mark.skipif(not os.path.isfile(gtf_file_GRCh38), reason="File does not exist") pytestmark_fasta = pytest.mark.skipif(not os.path.isfile(fasta_file_GRCh38), reason="File does not exist") pytestmark_vcf = pytest.mark.skipif(not os.path.isfile(vcf_file_for_testing_synonymous_mutations), reason="File does not exist") pytestmark_protein = pytest.mark.skipif(not os.path.isfile(protein_file_GRCh38), reason="File does not exist") @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def ssp(): return SingleSeqProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations) @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def svp(): <|code_end|> with the help of current file imports: from tqdm import tqdm_notebook as tqdm from kipoiseq.extractors.protein import SingleVariantProteinVCFSeqExtractor, TranscriptSeqExtractor, SingleSeqProteinVCFSeqExtractor from kipoiseq.transforms.functional import translate from pyfaidx import Fasta from conftest import gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations, protein_file_GRCh38, uniprot_seq_ref import pytest import os and context from other files: # Path: kipoiseq/extractors/protein.py # class SingleVariantProteinVCFSeqExtractor(SingleVariantExtractorMixin, ProteinVCFSeqExtractor): # pass # # class TranscriptSeqExtractor(GenericMultiIntervalSeqExtractor): # # def __init__(self, gtf_file, fasta_file): # self.fasta_file = str(fasta_file) # self.gtf_file = str(gtf_file) # # cds_fetcher = CDSFetcher(self.gtf_file) # # extractor = FastaStringExtractor(self.fasta_file, use_strand=False) # # super().__init__( # extractor=extractor, # interval_fetcher=cds_fetcher # ) # # @property # def df(self): # return self.extractor.df # # @property # def cds(self): # return self.extractor.df # # @classmethod # def _prepare_seq( # cls, # seqs: List[str], # intervals: List[Interval], # reverse_complement: Union[str, bool], # # **kwargs # ) -> str: # """ # Prepare the dna sequence in the final variant, which should be # translated in amino acid sequence # :param seqs: current dna sequence # :param intervals: the list of intervals corresponding to the sequence snippets # :param reverse_complement: should the dna be reverse-complemented? # :return: prepared dna sequence ready for translation into amino acid sequence # """ # seq = super()._prepare_seq( # seqs=seqs, # intervals=intervals, # reverse_complement=reverse_complement, # ) # tag = intervals[0].attrs["tag"] # seq = cut_transcript_seq(seq, tag) # return seq # # def get_protein_seq(self, transcript_id: str): # """ # Extract amino acid sequence for given transcript_id # :param transcript_id: # :return: amino acid sequence # """ # return translate(self.get_seq(transcript_id), hg38=True) # # class SingleSeqProteinVCFSeqExtractor(SingleSeqExtractorMixin, ProteinVCFSeqExtractor): # pass # # Path: kipoiseq/transforms/functional.py # def translate(seq: str, hg38=False): # """Translate the DNA/RNA sequence into AA. # # Note: it stops after it encounters a stop codon # # # Arguments # seq: DNA/RNA sequence # stop_none: return None if a stop codon is encountered # """ # if len(seq) % 3 != 0: # raise ValueError("len(seq) % 3 != 0") # # outl = [''] * (len(seq) // 3) # if hg38: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE_FOR_HG38[codon] # else: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE[codon] # # return "".join(outl) , which may contain function names, class names, or code. Output only the next line.
return SingleVariantProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations)
Predict the next line after this snippet: <|code_start|>pytestmark_vcf = pytest.mark.skipif(not os.path.isfile(vcf_file_for_testing_synonymous_mutations), reason="File does not exist") pytestmark_protein = pytest.mark.skipif(not os.path.isfile(protein_file_GRCh38), reason="File does not exist") @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def ssp(): return SingleSeqProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations) @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def svp(): return SingleVariantProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations) @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def tse(): <|code_end|> using the current file's imports: from tqdm import tqdm_notebook as tqdm from kipoiseq.extractors.protein import SingleVariantProteinVCFSeqExtractor, TranscriptSeqExtractor, SingleSeqProteinVCFSeqExtractor from kipoiseq.transforms.functional import translate from pyfaidx import Fasta from conftest import gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations, protein_file_GRCh38, uniprot_seq_ref import pytest import os and any relevant context from other files: # Path: kipoiseq/extractors/protein.py # class SingleVariantProteinVCFSeqExtractor(SingleVariantExtractorMixin, ProteinVCFSeqExtractor): # pass # # class TranscriptSeqExtractor(GenericMultiIntervalSeqExtractor): # # def __init__(self, gtf_file, fasta_file): # self.fasta_file = str(fasta_file) # self.gtf_file = str(gtf_file) # # cds_fetcher = CDSFetcher(self.gtf_file) # # extractor = FastaStringExtractor(self.fasta_file, use_strand=False) # # super().__init__( # extractor=extractor, # interval_fetcher=cds_fetcher # ) # # @property # def df(self): # return self.extractor.df # # @property # def cds(self): # return self.extractor.df # # @classmethod # def _prepare_seq( # cls, # seqs: List[str], # intervals: List[Interval], # reverse_complement: Union[str, bool], # # **kwargs # ) -> str: # """ # Prepare the dna sequence in the final variant, which should be # translated in amino acid sequence # :param seqs: current dna sequence # :param intervals: the list of intervals corresponding to the sequence snippets # :param reverse_complement: should the dna be reverse-complemented? # :return: prepared dna sequence ready for translation into amino acid sequence # """ # seq = super()._prepare_seq( # seqs=seqs, # intervals=intervals, # reverse_complement=reverse_complement, # ) # tag = intervals[0].attrs["tag"] # seq = cut_transcript_seq(seq, tag) # return seq # # def get_protein_seq(self, transcript_id: str): # """ # Extract amino acid sequence for given transcript_id # :param transcript_id: # :return: amino acid sequence # """ # return translate(self.get_seq(transcript_id), hg38=True) # # class SingleSeqProteinVCFSeqExtractor(SingleSeqExtractorMixin, ProteinVCFSeqExtractor): # pass # # Path: kipoiseq/transforms/functional.py # def translate(seq: str, hg38=False): # """Translate the DNA/RNA sequence into AA. # # Note: it stops after it encounters a stop codon # # # Arguments # seq: DNA/RNA sequence # stop_none: return None if a stop codon is encountered # """ # if len(seq) % 3 != 0: # raise ValueError("len(seq) % 3 != 0") # # outl = [''] * (len(seq) // 3) # if hg38: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE_FOR_HG38[codon] # else: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE[codon] # # return "".join(outl) . Output only the next line.
return TranscriptSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38)
Using the snippet: <|code_start|> pytestmark_gtf = pytest.mark.skipif(not os.path.isfile(gtf_file_GRCh38), reason="File does not exist") pytestmark_fasta = pytest.mark.skipif(not os.path.isfile(fasta_file_GRCh38), reason="File does not exist") pytestmark_vcf = pytest.mark.skipif(not os.path.isfile(vcf_file_for_testing_synonymous_mutations), reason="File does not exist") pytestmark_protein = pytest.mark.skipif(not os.path.isfile(protein_file_GRCh38), reason="File does not exist") @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def ssp(): <|code_end|> , determine the next line of code. You have imports: from tqdm import tqdm_notebook as tqdm from kipoiseq.extractors.protein import SingleVariantProteinVCFSeqExtractor, TranscriptSeqExtractor, SingleSeqProteinVCFSeqExtractor from kipoiseq.transforms.functional import translate from pyfaidx import Fasta from conftest import gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations, protein_file_GRCh38, uniprot_seq_ref import pytest import os and context (class names, function names, or code) available: # Path: kipoiseq/extractors/protein.py # class SingleVariantProteinVCFSeqExtractor(SingleVariantExtractorMixin, ProteinVCFSeqExtractor): # pass # # class TranscriptSeqExtractor(GenericMultiIntervalSeqExtractor): # # def __init__(self, gtf_file, fasta_file): # self.fasta_file = str(fasta_file) # self.gtf_file = str(gtf_file) # # cds_fetcher = CDSFetcher(self.gtf_file) # # extractor = FastaStringExtractor(self.fasta_file, use_strand=False) # # super().__init__( # extractor=extractor, # interval_fetcher=cds_fetcher # ) # # @property # def df(self): # return self.extractor.df # # @property # def cds(self): # return self.extractor.df # # @classmethod # def _prepare_seq( # cls, # seqs: List[str], # intervals: List[Interval], # reverse_complement: Union[str, bool], # # **kwargs # ) -> str: # """ # Prepare the dna sequence in the final variant, which should be # translated in amino acid sequence # :param seqs: current dna sequence # :param intervals: the list of intervals corresponding to the sequence snippets # :param reverse_complement: should the dna be reverse-complemented? # :return: prepared dna sequence ready for translation into amino acid sequence # """ # seq = super()._prepare_seq( # seqs=seqs, # intervals=intervals, # reverse_complement=reverse_complement, # ) # tag = intervals[0].attrs["tag"] # seq = cut_transcript_seq(seq, tag) # return seq # # def get_protein_seq(self, transcript_id: str): # """ # Extract amino acid sequence for given transcript_id # :param transcript_id: # :return: amino acid sequence # """ # return translate(self.get_seq(transcript_id), hg38=True) # # class SingleSeqProteinVCFSeqExtractor(SingleSeqExtractorMixin, ProteinVCFSeqExtractor): # pass # # Path: kipoiseq/transforms/functional.py # def translate(seq: str, hg38=False): # """Translate the DNA/RNA sequence into AA. # # Note: it stops after it encounters a stop codon # # # Arguments # seq: DNA/RNA sequence # stop_none: return None if a stop codon is encountered # """ # if len(seq) % 3 != 0: # raise ValueError("len(seq) % 3 != 0") # # outl = [''] * (len(seq) // 3) # if hg38: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE_FOR_HG38[codon] # else: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE[codon] # # return "".join(outl) . Output only the next line.
return SingleSeqProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations)
Based on the snippet: <|code_start|>@pytestmark_protein @pytest.fixture def ssp(): return SingleSeqProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations) @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def svp(): return SingleVariantProteinVCFSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations) @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein @pytest.fixture def tse(): return TranscriptSeqExtractor(gtf_file_GRCh38, fasta_file_GRCh38) @pytestmark_gtf @pytestmark_fasta @pytestmark_vcf @pytestmark_protein def test_vcf_single_variant_synonymous_mutations(tse, svp): transcript_id = 'ENST00000356175' <|code_end|> , predict the immediate next line with the help of imports: from tqdm import tqdm_notebook as tqdm from kipoiseq.extractors.protein import SingleVariantProteinVCFSeqExtractor, TranscriptSeqExtractor, SingleSeqProteinVCFSeqExtractor from kipoiseq.transforms.functional import translate from pyfaidx import Fasta from conftest import gtf_file_GRCh38, fasta_file_GRCh38, vcf_file_for_testing_synonymous_mutations, protein_file_GRCh38, uniprot_seq_ref import pytest import os and context (classes, functions, sometimes code) from other files: # Path: kipoiseq/extractors/protein.py # class SingleVariantProteinVCFSeqExtractor(SingleVariantExtractorMixin, ProteinVCFSeqExtractor): # pass # # class TranscriptSeqExtractor(GenericMultiIntervalSeqExtractor): # # def __init__(self, gtf_file, fasta_file): # self.fasta_file = str(fasta_file) # self.gtf_file = str(gtf_file) # # cds_fetcher = CDSFetcher(self.gtf_file) # # extractor = FastaStringExtractor(self.fasta_file, use_strand=False) # # super().__init__( # extractor=extractor, # interval_fetcher=cds_fetcher # ) # # @property # def df(self): # return self.extractor.df # # @property # def cds(self): # return self.extractor.df # # @classmethod # def _prepare_seq( # cls, # seqs: List[str], # intervals: List[Interval], # reverse_complement: Union[str, bool], # # **kwargs # ) -> str: # """ # Prepare the dna sequence in the final variant, which should be # translated in amino acid sequence # :param seqs: current dna sequence # :param intervals: the list of intervals corresponding to the sequence snippets # :param reverse_complement: should the dna be reverse-complemented? # :return: prepared dna sequence ready for translation into amino acid sequence # """ # seq = super()._prepare_seq( # seqs=seqs, # intervals=intervals, # reverse_complement=reverse_complement, # ) # tag = intervals[0].attrs["tag"] # seq = cut_transcript_seq(seq, tag) # return seq # # def get_protein_seq(self, transcript_id: str): # """ # Extract amino acid sequence for given transcript_id # :param transcript_id: # :return: amino acid sequence # """ # return translate(self.get_seq(transcript_id), hg38=True) # # class SingleSeqProteinVCFSeqExtractor(SingleSeqExtractorMixin, ProteinVCFSeqExtractor): # pass # # Path: kipoiseq/transforms/functional.py # def translate(seq: str, hg38=False): # """Translate the DNA/RNA sequence into AA. # # Note: it stops after it encounters a stop codon # # # Arguments # seq: DNA/RNA sequence # stop_none: return None if a stop codon is encountered # """ # if len(seq) % 3 != 0: # raise ValueError("len(seq) % 3 != 0") # # outl = [''] * (len(seq) // 3) # if hg38: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE_FOR_HG38[codon] # else: # for i in range(0, len(seq), 3): # codon = seq[i:i + 3] # outl[i // 3] = TRANSLATION_TABLE[codon] # # return "".join(outl) . Output only the next line.
ref_seq = translate(tse.get_seq(transcript_id), True)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) def PortFilter(ports): """ PortFilter(ports, ...) Filter events by port name or number. The *ports* argument can be a single port or a list of multiple ports. """ <|code_end|> . Write the next line using the current file imports: import _mididings import mididings.util as _util import mididings.overload as _overload import mididings.arguments as _arguments import mididings.unitrepr as _unitrepr import functools as _functools from mididings.units.base import _Filter and context from other files: # Path: mididings/units/base.py # class _Filter(_Unit, _Selector): # """ # Wrapper class for all filters. # """ # def __init__(self, unit): # _Unit.__init__(self, unit) # # def __invert__(self): # """ # Invert the filter (still act on the same event types, unary # operator ~). # """ # return self.invert() # # def __neg__(self): # """ # Negate the filter (ignoring event types, unary operator -) # """ # return self.negate() # # def invert(self): # return _InvertedFilter(self, False) # # def negate(self): # return _InvertedFilter(self, True) # # def build(self): # return self # # def build_negated(self): # return self.negate() , which may include functions, classes, or code. Output only the next line.
return _Filter(_mididings.PortFilter(map(_util.actual, ports)))
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # try: except: class OverloadTestCase(unittest.TestCase): def setUp(self): # yuck! <|code_end|> using the current file's imports: import unittest2 as unittest import unittest from mididings import overload and any relevant context from other files: # Path: mididings/overload.py # def call(args, kwargs, funcs, name=None): # def __init__(self, name, docstring): # def add(self, f): # def __call__(self, *args, **kwargs): # def _register_overload(f, docstring): # def mark(f, docstring=None): # def call_overload(*args, **kwargs): # def __init__(self, *partial_args): # def __call__(self, f): # def call_overload(*args, **kwargs): # class _Overload(object): # class partial(object): . Output only the next line.
self.registry_bak = overload._registry.copy()
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # @_unitrepr.accept(_util.port_number) def Port(port): """ Port(port) Change the event's port number. """ <|code_end|> with the help of current file imports: import _mididings import mididings.util as _util import mididings.misc as _misc import mididings.overload as _overload import mididings.constants as _constants import mididings.arguments as _arguments import mididings.unitrepr as _unitrepr from mididings.units.base import _Unit, Filter, Split, Pass from mididings.units.splits import VelocitySplit from mididings.units.generators import NoteOn, NoteOff, PolyAftertouch and context from other files: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_unitrepr.accept(_arguments.reduce_bitmask([_constants._EventType]), # add_varargs=True) # def Filter(types): # """ # Filter(types, ...) # # Filter by event type. Multiple types can be given as bitmasks, lists, or # separate parameters. # """ # return _Filter(_mididings.TypeFilter(types)) # # @_arguments.accept({ # _arguments.nullable(_arguments.reduce_bitmask([_constants._EventType])): # _UNIT_TYPES # }) # def Split(mapping): # """ # Split(mapping) # # Split by event type. # """ # return _Split(mapping) # # @_unitrepr.store # def Pass(): # """ # Do nothing. This is sometimes useful/necessary as a placeholder, much like # the ``pass`` statement in Python. # """ # return _Unit(_mididings.Pass(True)) # # Path: mididings/units/splits.py # @_overload.mark( # """ # VelocitySplit(threshold, patch_lower, patch_upper) # VelocitySplit(mapping) # # Split events by note-on velocity. Non-note events are sent to all patches. # # The first version splits at a single threshold. The second version allows # an arbitrary number of (possibly overlapping) value ranges, with # *mapping* being a dictionary of the form ``{(lower, upper): patch, ...}``. # """ # ) # @_arguments.accept(_util.velocity_limit, _UNIT_TYPES, _UNIT_TYPES) # def VelocitySplit(threshold, patch_lower, patch_upper): # return _make_threshold(VelocityFilter(0, threshold), # patch_lower, patch_upper) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.note_number_ref, _util.velocity_value_ref) # def NoteOn(port, channel, note, velocity): # """ # NoteOn(note, velocity) # NoteOn(port, channel, note, velocity) # # Create a note-on event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.NOTEON, # _util.actual_ref(port), # _util.actual_ref(channel), # note, # velocity # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.note_number_ref, _util.velocity_value_ref) # def NoteOff(port, channel, note, velocity=0): # """ # NoteOff(note, velocity=0) # NoteOff(port, channel, note, velocity=0) # # Create a note-off event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.NOTEOFF, # _util.actual_ref(port), # _util.actual_ref(channel), # note, # velocity # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.note_number_ref, int) # def PolyAftertouch(port, channel, note, value): # """ # PolyAftertouch(note, value) # PolyAftertouch(port, channel, note, value) # # Create a polyphonic aftertouch event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.POLY_AFTERTOUCH, # _util.actual_ref(port), # _util.actual_ref(channel), # note, # value # )) , which may contain function names, class names, or code. Output only the next line.
return _Unit(_mididings.Port(_util.actual(port)))
Given snippet: <|code_start|> Process the incoming MIDI event using a Python function, then continue executing the mididings patch with the events returned from that function. :param function: a function, or any other callable object, that will be called with a :class:`~.MidiEvent` object as its first argument. The function's return value can be: - a single :class:`~.MidiEvent` object. - a list of :class:`~.MidiEvent` objects. - ``None`` (or an empty list). Instead of ``return``\ ing :class:`~.MidiEvent` objects, *function* may also be a generator that ``yield``\ s :class:`~.MidiEvent` objects. :param \*args: optional positional arguments that will be passed to *function*. :param \*\*kwargs: optional keyword arguments that will be passed to *function*. Any other MIDI processing will be stalled until *function* returns, so this should only be used with functions that don't block. Use :func:`Call()` for tasks that may take longer and/or don't require returning any MIDI events. """ <|code_end|> , continue by predicting the next line. Consider current file imports: import _mididings import mididings.event as _event import mididings.overload as _overload import mididings.unitrepr as _unitrepr import mididings.misc as _misc import sys as _sys import _thread import thread as _thread import subprocess as _subprocess import types as _types import copy as _copy import collections as _collections import inspect as _inspect from mididings.units.base import _Unit from mididings.setup import get_config as _get_config and context: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # Path: mididings/setup.py # def get_config(var): # return _config[var] which might include code, classes, or functions. Output only the next line.
if _get_config('backend') == 'jack-rt' and not _get_config('silent'):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # class EngineTestCase(MididingsTestCase): def test_in_ports(self): ports = ['foo', 'bar', 'baz'] config(in_ports = ports) <|code_end|> , determine the next line of code. You have imports: from tests.helpers import * from mididings import * from mididings import engine and context (class names, function names, or code) available: # Path: mididings/engine.py # def _start_backend(): # def __init__(self): # def setup(self, scenes, control, pre, post): # def run(self): # def _start_delay(self): # def _parse_scene_number(self, number): # def scene_switch_callback(self, scene, subscene): # def _call_hooks(self, name, *args): # def switch_scene(self, scene, subscene=None): # def switch_subscene(self, subscene): # def current_scene(self): # def current_subscene(self): # def scenes(self): # def process_event(self, ev): # def output_event(self, ev): # def process(self, ev): # def restart(self): # def _restart(): # def quit(self): # def run(patch): # def run(scenes, control=None, pre=None, post=None): # def switch_scene(scene, subscene=None): # def switch_subscene(subscene): # def current_scene(): # def current_subscene(): # def scenes(): # def output_event(ev): # def in_ports(): # def out_ports(): # def time(): # def active(): # def restart(): # def quit(): # def process_file(infile, outfile, patch): # class Engine(_mididings.Engine): . Output only the next line.
self.assertEqual(engine.in_ports(), ports)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # @_unitrepr.accept(_util.event_type, _util.port_number_ref, _util.channel_number_ref, int, int) def Generator(type, port=_constants.EVENT_PORT, channel=_constants.EVENT_CHANNEL, data1=0, data2=0): """ Generator(type, port, channel, data1=0, data2=0) Generic generator to change the incoming event's type and data. System common and system realtime events can only be created this way. """ <|code_end|> , determine the next line of code. You have imports: import _mididings import mididings.constants as _constants import mididings.util as _util import mididings.overload as _overload import mididings.unitrepr as _unitrepr from mididings.units.base import _Unit and context (class names, function names, or code) available: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) . Output only the next line.
return _Unit(_mididings.Generator(
Next line prediction: <|code_start|> yield _event.NoteOnEvent( ev.port, ev.channel, n, self.notes[n][0]) self.current_note = n self.diverted = d def VoiceFilter(voice='highest', time=0.1, retrigger=False): """ Filter individual voices from a chord. :param voice: The voice to be filtered. This can be ``'highest'``, ``'lowest'``, or an integer index (positive or negative, the same way Python lists are indexed, with 0 being the lowest voice and -1 the highest). :param time: The period in seconds for which a newly played note may still be unassigned from the selected voice, when additional notes are played. :param retrigger: If true, a new note-on event will be sent when a note is reassigned to the selected voice as a result of another note being released. """ if voice == 'highest': voice = -1 elif voice == 'lowest': voice = 0 <|code_end|> . Use current file imports: (import mididings as _m import mididings.event as _event import mididings.engine as _engine from mididings.extra.per_channel import PerChannel as _PerChannel) and context including class names, function names, or small code snippets from other files: # Path: mididings/extra/per_channel.py # class PerChannel(object): # """ # Utility class, usable with Process() and Call(), that delegates events # to different instances of the same class, using one instance per # channel/port combination. # New instances are created as needed, using the given factory function, # when the first event with a new channel/port arrives. # """ # def __init__(self, factory): # self.channel_proc = {} # self.factory = factory # # def __call__(self, ev): # k = (ev.port, ev.channel) # if k not in self.channel_proc: # self.channel_proc[k] = self.factory() # return self.channel_proc[k](ev) . Output only the next line.
return _m.Filter(_m.NOTE) % _m.Process(_PerChannel(
Here is a snippet: <|code_start|># # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # class _SuppressPC(object): def __init__(self): self.current = None def __call__(self, ev): if ev.program == self.current: return None else: self.current = ev.program return ev def SuppressPC(): """ Filter out program changes if the same program has already been selected on the same port/channel. """ return (_m.Filter(_m.PROGRAM) % <|code_end|> . Write the next line using the current file imports: import mididings as _m from mididings.extra.per_channel import PerChannel as _PerChannel and context from other files: # Path: mididings/extra/per_channel.py # class PerChannel(object): # """ # Utility class, usable with Process() and Call(), that delegates events # to different instances of the same class, using one instance per # channel/port combination. # New instances are created as needed, using the given factory function, # when the first event with a new channel/port arrives. # """ # def __init__(self, factory): # self.channel_proc = {} # self.factory = factory # # def __call__(self, ev): # k = (ev.port, ev.channel) # if k not in self.channel_proc: # self.channel_proc[k] = self.factory() # return self.channel_proc[k](ev) , which may include functions, classes, or code. Output only the next line.
_m.Process(_PerChannel(_SuppressPC)))
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # @decorator.decorator def store(f, *args, **kwargs): """ Decorator that modifies the function f to store its own arguments in the unit it returns. """ unit = f(*args, **kwargs) # store the unit's name, the function object, and the value of # each argument <|code_end|> , predict the next line using imports from the current file: from mididings import overload from mididings import arguments from mididings import misc import inspect import sys import decorator and context including class names, function names, and sometimes code from other files: # Path: mididings/overload.py # def call(args, kwargs, funcs, name=None): # def __init__(self, name, docstring): # def add(self, f): # def __call__(self, *args, **kwargs): # def _register_overload(f, docstring): # def mark(f, docstring=None): # def call_overload(*args, **kwargs): # def __init__(self, *partial_args): # def __call__(self, f): # def call_overload(*args, **kwargs): # class _Overload(object): # class partial(object): # # Path: mididings/arguments.py # class accept(object): # class _constraint(object): # class _any(_constraint): # class _type_constraint(_constraint): # class _value_constraint(_constraint): # class nullable(_constraint): # class sequenceof(_constraint): # class tupleof(_constraint): # class mappingof(_constraint): # class flatten(_constraint): # class each(_constraint): # class either(_constraint): # class transform(_constraint): # class condition(_constraint): # class reduce_bitmask(_constraint): # def __init__(self, *constraints, **kwargs): # def __call__(self, f): # def wrapper(self, f, *args, **kwargs): # def _apply_constraint(constraint, arg, func_name, arg_name): # def _make_constraint(c): # def __call__(self, arg): # def __init__(self, types, multiple=False): # def __call__(self, arg): # def __repr__(self): # def __init__(self, values): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, fromwhat, towhat): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what, return_type=None): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *requirements): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *alternatives): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def _function_repr(f): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): . Output only the next line.
unit._name = f.name if isinstance(f, overload._Overload) else f.__name__
Next line prediction: <|code_start|># (at your option) any later version. # @decorator.decorator def store(f, *args, **kwargs): """ Decorator that modifies the function f to store its own arguments in the unit it returns. """ unit = f(*args, **kwargs) # store the unit's name, the function object, and the value of # each argument unit._name = f.name if isinstance(f, overload._Overload) else f.__name__ unit._function = f unit._args = args return unit def accept(*constraints, **kwargs): """ @arguments.accept() and @unitrepr.store composed into a single decorator for convenience. """ def composed(f): <|code_end|> . Use current file imports: (from mididings import overload from mididings import arguments from mididings import misc import inspect import sys import decorator) and context including class names, function names, or small code snippets from other files: # Path: mididings/overload.py # def call(args, kwargs, funcs, name=None): # def __init__(self, name, docstring): # def add(self, f): # def __call__(self, *args, **kwargs): # def _register_overload(f, docstring): # def mark(f, docstring=None): # def call_overload(*args, **kwargs): # def __init__(self, *partial_args): # def __call__(self, f): # def call_overload(*args, **kwargs): # class _Overload(object): # class partial(object): # # Path: mididings/arguments.py # class accept(object): # class _constraint(object): # class _any(_constraint): # class _type_constraint(_constraint): # class _value_constraint(_constraint): # class nullable(_constraint): # class sequenceof(_constraint): # class tupleof(_constraint): # class mappingof(_constraint): # class flatten(_constraint): # class each(_constraint): # class either(_constraint): # class transform(_constraint): # class condition(_constraint): # class reduce_bitmask(_constraint): # def __init__(self, *constraints, **kwargs): # def __call__(self, f): # def wrapper(self, f, *args, **kwargs): # def _apply_constraint(constraint, arg, func_name, arg_name): # def _make_constraint(c): # def __call__(self, arg): # def __init__(self, types, multiple=False): # def __call__(self, arg): # def __repr__(self): # def __init__(self, values): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, fromwhat, towhat): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what, return_type=None): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *requirements): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *alternatives): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def _function_repr(f): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): . Output only the next line.
return arguments.accept(*constraints, **kwargs) (store(f))
Here is a snippet: <|code_start|> """ Decorator that modifies the function f to store its own arguments in the unit it returns. """ unit = f(*args, **kwargs) # store the unit's name, the function object, and the value of # each argument unit._name = f.name if isinstance(f, overload._Overload) else f.__name__ unit._function = f unit._args = args return unit def accept(*constraints, **kwargs): """ @arguments.accept() and @unitrepr.store composed into a single decorator for convenience. """ def composed(f): return arguments.accept(*constraints, **kwargs) (store(f)) return composed def unit_to_string(unit): # can't do anything for units that didn't go through @store (or @accept) assert hasattr(unit, '_name') <|code_end|> . Write the next line using the current file imports: from mididings import overload from mididings import arguments from mididings import misc import inspect import sys import decorator and context from other files: # Path: mididings/overload.py # def call(args, kwargs, funcs, name=None): # def __init__(self, name, docstring): # def add(self, f): # def __call__(self, *args, **kwargs): # def _register_overload(f, docstring): # def mark(f, docstring=None): # def call_overload(*args, **kwargs): # def __init__(self, *partial_args): # def __call__(self, f): # def call_overload(*args, **kwargs): # class _Overload(object): # class partial(object): # # Path: mididings/arguments.py # class accept(object): # class _constraint(object): # class _any(_constraint): # class _type_constraint(_constraint): # class _value_constraint(_constraint): # class nullable(_constraint): # class sequenceof(_constraint): # class tupleof(_constraint): # class mappingof(_constraint): # class flatten(_constraint): # class each(_constraint): # class either(_constraint): # class transform(_constraint): # class condition(_constraint): # class reduce_bitmask(_constraint): # def __init__(self, *constraints, **kwargs): # def __call__(self, f): # def wrapper(self, f, *args, **kwargs): # def _apply_constraint(constraint, arg, func_name, arg_name): # def _make_constraint(c): # def __call__(self, arg): # def __init__(self, types, multiple=False): # def __call__(self, arg): # def __repr__(self): # def __init__(self, values): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, fromwhat, towhat): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what, return_type=None): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *requirements): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *alternatives): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def _function_repr(f): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): , which may include functions, classes, or code. Output only the next line.
argnames = misc.getargspec(unit._function)[0]
Given snippet: <|code_start|># # router.py - A simple OSC-controlled MIDI router that sends all incoming # events to the output port/channel determined by the current scene/subscene. # # To route the output to a different MIDI port/channel, send an OSC message # /mididings/switch_scene <port> <channel> # to UDP port 56418. # # For example, using the send_osc command from pyliblo: # $ send_osc 56418 /mididings/switch_scene 13 1 # NPORTS = 16 config( out_ports=NPORTS, ) hook( <|code_end|> , continue by predicting the next line. Consider current file imports: from mididings import * from mididings.extra.osc import OSCInterface and context: # Path: mididings/extra/osc.py # class OSCInterface(object): # """ # Allows controlling mididings via OSC. # # :param port: # the OSC port to listen on. # # :param notify_ports: # a list of OSC ports to notify when the current scene changes. # # These messages are currently understood: # # - **/mididings/switch_scene ,i**: switch to the given scene number. # - **/mididings/switch_subscene ,i**: switch to the given subscene number. # - **/mididings/prev_scene**: switch to the previous scene. # - **/mididings/next_scene**: switch to the next scene. # - **/mididings/prev_subscene**: switch to the previous subscene. # - **/mididings/next_subscene**: switch to the next subscene. # - **/mididings/panic**: send all-notes-off on all channels and on all # output ports. # - **/mididings/quit**: terminate mididings. # """ # def __init__(self, port=56418, notify_ports=[56419]): # self.port = port # if _misc.issequence(notify_ports): # self.notify_ports = notify_ports # else: # self.notify_ports = [notify_ports] # # def on_start(self): # if self.port is not None: # self.server = _liblo.ServerThread(self.port) # self.server.register_methods(self) # self.server.start() # # self.send_config() # # def on_exit(self): # if self.port is not None: # self.server.stop() # del self.server # # def on_switch_scene(self, scene, subscene): # for p in self.notify_ports: # _liblo.send(p, '/mididings/current_scene', scene, subscene) # # def send_config(self): # for p in self.notify_ports: # # send data offset # _liblo.send(p, '/mididings/data_offset', # _setup.get_config('data_offset')) # # # send list of scenes # _liblo.send(p, '/mididings/begin_scenes') # s = _engine.scenes() # for n in sorted(s.keys()): # _liblo.send(p, '/mididings/add_scene', n, s[n][0], *s[n][1]) # _liblo.send(p, '/mididings/end_scenes') # # @_liblo.make_method('/mididings/query', '') # def query_cb(self, path, args): # self.send_config() # for p in self.notify_ports: # _liblo.send(p, '/mididings/current_scene', # _engine.current_scene(), _engine.current_subscene()) # # @_liblo.make_method('/mididings/switch_scene', 'i') # @_liblo.make_method('/mididings/switch_scene', 'ii') # def switch_scene_cb(self, path, args): # _engine.switch_scene(*args) # # @_liblo.make_method('/mididings/switch_subscene', 'i') # def switch_subscene_cb(self, path, args): # _engine.switch_subscene(*args) # # @_liblo.make_method('/mididings/prev_scene', '') # def prev_scene_cb(self, path, args): # s = sorted(_engine.scenes().keys()) # n = s.index(_engine.current_scene()) - 1 # if n >= 0: # _engine.switch_scene(s[n]) # # @_liblo.make_method('/mididings/next_scene', '') # def next_scene_cb(self, path, args): # s = sorted(_engine.scenes().keys()) # n = s.index(_engine.current_scene()) + 1 # if n < len(s): # _engine.switch_scene(s[n]) # # @_liblo.make_method('/mididings/prev_subscene', '') # @_liblo.make_method('/mididings/prev_subscene', 'i') # def prev_subscene_cb(self, path, args): # s = _engine.scenes()[_engine.current_scene()] # n = _util.actual(_engine.current_subscene()) - 1 # if len(s[1]) and len(args) and args[0]: # n %= len(s[1]) # if n >= 0: # _engine.switch_subscene(_util.offset(n)) # # @_liblo.make_method('/mididings/next_subscene', '') # @_liblo.make_method('/mididings/next_subscene', 'i') # def next_subscene_cb(self, path, args): # s = _engine.scenes()[_engine.current_scene()] # n = _util.actual(_engine.current_subscene()) + 1 # if len(s[1]) and len(args) and args[0]: # n %= len(s[1]) # if n < len(s[1]): # _engine.switch_subscene(_util.offset(n)) # # @_liblo.make_method('/mididings/panic', '') # def panic_cb(self, path, args): # _panic._panic_bypass() # # @_liblo.make_method('/mididings/restart', '') # def restart_cb(self, path, args): # _engine.restart() # # @_liblo.make_method('/mididings/quit', '') # def quit_cb(self, path, args): # _engine.quit() which might include code, classes, or functions. Output only the next line.
OSCInterface(56418, 56419),
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # class Scene(object): """ Scene(name, patch, init_patch=None, exit_patch=None) Construct a Scene object to be used with the :func:`run()` function. :param name: a string describing the scene. :param patch: the patch defining the MIDI processing to take place for incoming events. :param init_patch: an optional patch that will be triggered when switching to this scene. :param exit_patch: an optional patch that will be triggered when switching away from this scene. """ <|code_end|> , predict the immediate next line with the help of imports: from mididings.units.base import _UNIT_TYPES import mididings.patch as _patch import mididings.arguments as _arguments and context (classes, functions, sometimes code) from other files: # Path: mididings/units/base.py # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) . Output only the next line.
@_arguments.accept(None, _arguments.nullable(str), _UNIT_TYPES,
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2011 Sébastien Devaux # Copyright (C) 2012-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # class _CtrlToSysEx(object): def __init__(self, sysex, index, checksum_start): self.sysex = util.sysex_data(sysex) self.index = index self.checksum_start = checksum_start def __call__(self, ev): sysex = self.sysex sysex[self.index] = ev.value if self.checksum_start is not None: checksum = sum(self.sysex[self.checksum_start:-2]) sysex[-2] = (128 - checksum) % 128 <|code_end|> using the current file's imports: from mididings import * from mididings import event from mididings import util and any relevant context from other files: # Path: mididings/event.py # def _make_property(type, data, name=None, offset=False): # def getter(self): # def setter(self, value): # def getter(self): # def setter(self, value): # def __init__( # self, type, # port=_util.NoDataOffset(0), channel=_util.NoDataOffset(0), # data1=0, data2=0, sysex=None # ): # def __getinitargs__(self): # def _check_type_attribute(self, type, name): # def _type_to_string(self): # def _sysex_to_hex(self, max_length): # def to_string(self, portnames=[], portname_length=0, max_length=0): # def __repr__(self): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def _finalize(self): # def _type_getter(self): # def _type_setter(self, type): # def _get_sysex(self): # def _sysex_getter(self): # def _sysex_setter(self, sysex): # def NoteOnEvent(port, channel, note, velocity): # def NoteOffEvent(port, channel, note, velocity=0): # def CtrlEvent(port, channel, ctrl, value): # def PitchbendEvent(port, channel, value): # def AftertouchEvent(port, channel, value): # def PolyAftertouchEvent(port, channel, note, value): # def ProgramEvent(port, channel, program): # def SysExEvent(port, sysex): # class MidiEvent(_mididings.MidiEvent): # # Path: mididings/util.py # _NOTE_NUMBERS = { # 'c': 0, # 'c#': 1, 'db': 1, # 'd': 2, # 'd#': 3, 'eb': 3, # 'e': 4, # 'f': 5, # 'f#': 6, 'gb': 6, # 'g': 7, # 'g#': 8, 'ab': 8, # 'a': 9, # 'a#': 10, 'bb': 10, # 'b': 11, # } # _NOTE_NAMES = { # 0: 'c', # 1: 'c#', # 2: 'd', # 3: 'd#', # 4: 'e', # 5: 'f', # 6: 'f#', # 7: 'g', # 8: 'g#', # 9: 'a', # 10: 'a#', # 11: 'b', # } # _CONTROLLER_NAMES = { # 0: 'Bank select (MSB)', # 1: 'Modulation', # 6: 'Data entry (MSB)', # 7: 'Volume', # 10: 'Pan', # 11: 'Expression', # 32: 'Bank select (LSB)', # 38: 'Data entry (LSB)', # 64: 'Sustain', # 65: 'Portamento', # 66: 'Sostenuto', # 67: 'Soft pedal', # 68: 'Legato pedal', # 98: 'NRPN (LSB)', # 99: 'NRPN (MSB)', # 100: 'RPN (LSB)', # 101: 'RPN (MSB)', # 121: 'Reset all controllers', # 123: 'All notes off', # } # def note_number(note, allow_end=False): # def note_limit(note): # def note_range(notes): # def note_name(note): # def tonic_note_number(key): # def controller_name(ctrl): # def event_type(type): # def port_number(port): # def channel_number(channel): # def program_number(program): # def ctrl_number(ctrl): # def ctrl_value(value, allow_end=False): # def ctrl_limit(value): # def ctrl_range(value): # def velocity_value(velocity, allow_end=False): # def velocity_limit(velocity): # def velocity_range(velocity): # def scene_number(scene): # def subscene_number(subscene): # def sysex_to_bytearray(sysex): # def sysex_data(sysex, allow_partial=False): # def sysex_manufacturer(manufacturer): # def __new__(cls, value): # def __repr__(self): # def __str__(self): # def offset(n): # def actual(n): # def _allow_event_attribute(f): # def func(first, *args, **kwargs): # class NoDataOffset(int): . Output only the next line.
return event.SysExEvent(ev.port, sysex)
Given the following code snippet before the placeholder: <|code_start|># # 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 2 of the License, or # (at your option) any later version. # try: except: def data_offsets(f): """ Run the test f twice, with data offsets 0 and 1 """ def data_offset_wrapper(self): for offset in (0, 1): def off(n): return n + offset config(data_offset = offset) f(self, off) data_offset_wrapper.__name__ = f.__name__ return data_offset_wrapper class MididingsTestCase(unittest.TestCase): def setUp(self): <|code_end|> , predict the next line using imports from the current file: import unittest2 as unittest import unittest import random import itertools import sys import copy import mididings import mididings.event from mididings import * from mididings import setup, engine, misc, constants from mididings.event import * and context including class names, function names, and sometimes code from other files: # Path: mididings/setup.py # _VALID_BACKENDS = _mididings.available_backends() # _DEFAULT_CONFIG = { # 'backend': 'alsa' if 'alsa' in _VALID_BACKENDS else 'jack', # 'client_name': 'mididings', # 'in_ports': 1, # 'out_ports': 1, # 'data_offset': 1, # 'octave_offset': 2, # 'initial_scene': None, # 'start_delay': None, # 'silent': False, # } # def _default_portname(n, out): # def _parse_portnames(ports, out): # def _parse_port_connections(ports, out): # def reset(): # def config(**kwargs): # def _config_impl(override=False, **kwargs): # def _config_updated(): # def get_config(var): # def hook(*args): # def get_hooks(): # # Path: mididings/engine.py # def _start_backend(): # def __init__(self): # def setup(self, scenes, control, pre, post): # def run(self): # def _start_delay(self): # def _parse_scene_number(self, number): # def scene_switch_callback(self, scene, subscene): # def _call_hooks(self, name, *args): # def switch_scene(self, scene, subscene=None): # def switch_subscene(self, subscene): # def current_scene(self): # def current_subscene(self): # def scenes(self): # def process_event(self, ev): # def output_event(self, ev): # def process(self, ev): # def restart(self): # def _restart(): # def quit(self): # def run(patch): # def run(scenes, control=None, pre=None, post=None): # def switch_scene(scene, subscene=None): # def switch_subscene(subscene): # def current_scene(): # def current_subscene(): # def scenes(): # def output_event(ev): # def in_ports(): # def out_ports(): # def time(): # def active(): # def restart(): # def quit(): # def process_file(infile, outfile, patch): # class Engine(_mididings.Engine): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): # # Path: mididings/constants.py # class _EventType(_NamedBitMask): # class _EventAttribute(_NamedFlag): # _EVENT_TYPES = {} . Output only the next line.
setup.reset()
Given the following code snippet before the placeholder: <|code_start|> resulting events. """ r = self.run_scenes({ setup.get_config('data_offset'): patch }, events) return list(itertools.chain(*r)) def run_scenes(self, scenes, events): """ Run the given events through the given scenes, return the list of resulting events. """ # run scenes r1 = self._run_scenes_impl(scenes, events) # check if events can be rebuilt from their repr() for r in r1: for ev in r: rebuilt = eval(repr(ev), self.mididings_dict) self.assertEqual(rebuilt, ev) rebuilt = self._rebuild_repr(scenes) if rebuilt is not None: # run scenes rebuilt from their repr(), result should be identical r2 = self._run_scenes_impl(rebuilt, events) self.assertEqual(r2, r1) return r1 def _run_scenes_impl(self, scenes, events): # set up a dummy engine setup._config_impl(backend='dummy') <|code_end|> , predict the next line using imports from the current file: import unittest2 as unittest import unittest import random import itertools import sys import copy import mididings import mididings.event from mididings import * from mididings import setup, engine, misc, constants from mididings.event import * and context including class names, function names, and sometimes code from other files: # Path: mididings/setup.py # _VALID_BACKENDS = _mididings.available_backends() # _DEFAULT_CONFIG = { # 'backend': 'alsa' if 'alsa' in _VALID_BACKENDS else 'jack', # 'client_name': 'mididings', # 'in_ports': 1, # 'out_ports': 1, # 'data_offset': 1, # 'octave_offset': 2, # 'initial_scene': None, # 'start_delay': None, # 'silent': False, # } # def _default_portname(n, out): # def _parse_portnames(ports, out): # def _parse_port_connections(ports, out): # def reset(): # def config(**kwargs): # def _config_impl(override=False, **kwargs): # def _config_updated(): # def get_config(var): # def hook(*args): # def get_hooks(): # # Path: mididings/engine.py # def _start_backend(): # def __init__(self): # def setup(self, scenes, control, pre, post): # def run(self): # def _start_delay(self): # def _parse_scene_number(self, number): # def scene_switch_callback(self, scene, subscene): # def _call_hooks(self, name, *args): # def switch_scene(self, scene, subscene=None): # def switch_subscene(self, subscene): # def current_scene(self): # def current_subscene(self): # def scenes(self): # def process_event(self, ev): # def output_event(self, ev): # def process(self, ev): # def restart(self): # def _restart(): # def quit(self): # def run(patch): # def run(scenes, control=None, pre=None, post=None): # def switch_scene(scene, subscene=None): # def switch_subscene(subscene): # def current_scene(): # def current_subscene(): # def scenes(): # def output_event(ev): # def in_ports(): # def out_ports(): # def time(): # def active(): # def restart(): # def quit(): # def process_file(infile, outfile, patch): # class Engine(_mididings.Engine): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): # # Path: mididings/constants.py # class _EventType(_NamedBitMask): # class _EventAttribute(_NamedFlag): # _EVENT_TYPES = {} . Output only the next line.
e = engine.Engine()
Here is a snippet: <|code_start|> def run_scenes(self, scenes, events): """ Run the given events through the given scenes, return the list of resulting events. """ # run scenes r1 = self._run_scenes_impl(scenes, events) # check if events can be rebuilt from their repr() for r in r1: for ev in r: rebuilt = eval(repr(ev), self.mididings_dict) self.assertEqual(rebuilt, ev) rebuilt = self._rebuild_repr(scenes) if rebuilt is not None: # run scenes rebuilt from their repr(), result should be identical r2 = self._run_scenes_impl(rebuilt, events) self.assertEqual(r2, r1) return r1 def _run_scenes_impl(self, scenes, events): # set up a dummy engine setup._config_impl(backend='dummy') e = engine.Engine() e.setup(scenes, None, None, None) r = [] # allow input to be a single event, as well as a sequence of events <|code_end|> . Write the next line using the current file imports: import unittest2 as unittest import unittest import random import itertools import sys import copy import mididings import mididings.event from mididings import * from mididings import setup, engine, misc, constants from mididings.event import * and context from other files: # Path: mididings/setup.py # _VALID_BACKENDS = _mididings.available_backends() # _DEFAULT_CONFIG = { # 'backend': 'alsa' if 'alsa' in _VALID_BACKENDS else 'jack', # 'client_name': 'mididings', # 'in_ports': 1, # 'out_ports': 1, # 'data_offset': 1, # 'octave_offset': 2, # 'initial_scene': None, # 'start_delay': None, # 'silent': False, # } # def _default_portname(n, out): # def _parse_portnames(ports, out): # def _parse_port_connections(ports, out): # def reset(): # def config(**kwargs): # def _config_impl(override=False, **kwargs): # def _config_updated(): # def get_config(var): # def hook(*args): # def get_hooks(): # # Path: mididings/engine.py # def _start_backend(): # def __init__(self): # def setup(self, scenes, control, pre, post): # def run(self): # def _start_delay(self): # def _parse_scene_number(self, number): # def scene_switch_callback(self, scene, subscene): # def _call_hooks(self, name, *args): # def switch_scene(self, scene, subscene=None): # def switch_subscene(self, subscene): # def current_scene(self): # def current_subscene(self): # def scenes(self): # def process_event(self, ev): # def output_event(self, ev): # def process(self, ev): # def restart(self): # def _restart(): # def quit(self): # def run(patch): # def run(scenes, control=None, pre=None, post=None): # def switch_scene(scene, subscene=None): # def switch_subscene(subscene): # def current_scene(): # def current_subscene(): # def scenes(): # def output_event(ev): # def in_ports(): # def out_ports(): # def time(): # def active(): # def restart(): # def quit(): # def process_file(infile, outfile, patch): # class Engine(_mididings.Engine): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): # # Path: mididings/constants.py # class _EventType(_NamedBitMask): # class _EventAttribute(_NamedFlag): # _EVENT_TYPES = {} , which may include functions, classes, or code. Output only the next line.
if not misc.issequence(events):
Given the following code snippet before the placeholder: <|code_start|> rep = repr(v) if 'Process' in rep or 'Call' in rep: # patches with Process() units etc. are too tricky for now return None w = eval(rep, self.mididings_dict) # the repr() of the rebuilt patch should be identical to the repr() # string it was built from self.assertEqual(repr(w), rep) r[k] = w return r def make_event(self, *args, **kwargs): """ Create a new MIDI event. Attributes can be specified in args or kwargs, unspecified attributes are filled with random values. """ type, port, channel, data1, data2, sysex = \ itertools.islice(itertools.chain(args, itertools.repeat(None)), 6) for k, v in kwargs.items(): if k == 'type': type = v if k == 'port': port = v elif k == 'channel': channel = v elif k in ('data1', 'note', 'ctrl'): data1 = v elif k in ('data2', 'velocity', 'value'): data2 = v elif k == 'program': data2 = v - setup.get_config('data_offset') elif k == 'sysex': sysex = v if type is None: if channel is None: <|code_end|> , predict the next line using imports from the current file: import unittest2 as unittest import unittest import random import itertools import sys import copy import mididings import mididings.event from mididings import * from mididings import setup, engine, misc, constants from mididings.event import * and context including class names, function names, and sometimes code from other files: # Path: mididings/setup.py # _VALID_BACKENDS = _mididings.available_backends() # _DEFAULT_CONFIG = { # 'backend': 'alsa' if 'alsa' in _VALID_BACKENDS else 'jack', # 'client_name': 'mididings', # 'in_ports': 1, # 'out_ports': 1, # 'data_offset': 1, # 'octave_offset': 2, # 'initial_scene': None, # 'start_delay': None, # 'silent': False, # } # def _default_portname(n, out): # def _parse_portnames(ports, out): # def _parse_port_connections(ports, out): # def reset(): # def config(**kwargs): # def _config_impl(override=False, **kwargs): # def _config_updated(): # def get_config(var): # def hook(*args): # def get_hooks(): # # Path: mididings/engine.py # def _start_backend(): # def __init__(self): # def setup(self, scenes, control, pre, post): # def run(self): # def _start_delay(self): # def _parse_scene_number(self, number): # def scene_switch_callback(self, scene, subscene): # def _call_hooks(self, name, *args): # def switch_scene(self, scene, subscene=None): # def switch_subscene(self, subscene): # def current_scene(self): # def current_subscene(self): # def scenes(self): # def process_event(self, ev): # def output_event(self, ev): # def process(self, ev): # def restart(self): # def _restart(): # def quit(self): # def run(patch): # def run(scenes, control=None, pre=None, post=None): # def switch_scene(scene, subscene=None): # def switch_subscene(subscene): # def current_scene(): # def current_subscene(): # def scenes(): # def output_event(ev): # def in_ports(): # def out_ports(): # def time(): # def active(): # def restart(): # def quit(): # def process_file(infile, outfile, patch): # class Engine(_mididings.Engine): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): # # Path: mididings/constants.py # class _EventType(_NamedBitMask): # class _EventAttribute(_NamedFlag): # _EVENT_TYPES = {} . Output only the next line.
type = random.choice(list(set(constants._EVENT_TYPES.values())
Given the following code snippet before the placeholder: <|code_start|># # klick.py - uses SendOSC() to start/stop klick, or change its tempo # # klick: http://das.nasophon.de/klick/ # # CC 13 runs/terminates the klick process (alternatively, # run "klick -P -o 1234"), # CC 14 starts/stops the metronome, and CC 15 changes tempo. # port = 1234 run( Filter(CTRL) >> CtrlSplit({ # CC 13: run/terminate klick process 13: CtrlValueSplit( 64, <|code_end|> , predict the next line using imports from the current file: from mididings import * from mididings.extra.osc import SendOSC and context including class names, function names, and sometimes code from other files: # Path: mididings/extra/osc.py # def SendOSC(target, path, *args): # """ # Send an OSC message. # Parameters are the same as for :func:`liblo.send()`. # Additionally, instead of a specific value, each data argument may also # be a Python function that takes a single :class:`~.MidiEvent` parameter, # and returns the value to be sent. # """ # return _Call(_SendOSC(target, path, args)) . Output only the next line.
SendOSC(port, '/klick/quit'),
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # try: except: class ArgumentsTestCase(unittest.TestCase): def test_simple(self): <|code_end|> with the help of current file imports: import unittest2 as unittest import unittest from mididings import arguments from mididings import misc and context from other files: # Path: mididings/arguments.py # class accept(object): # class _constraint(object): # class _any(_constraint): # class _type_constraint(_constraint): # class _value_constraint(_constraint): # class nullable(_constraint): # class sequenceof(_constraint): # class tupleof(_constraint): # class mappingof(_constraint): # class flatten(_constraint): # class each(_constraint): # class either(_constraint): # class transform(_constraint): # class condition(_constraint): # class reduce_bitmask(_constraint): # def __init__(self, *constraints, **kwargs): # def __call__(self, f): # def wrapper(self, f, *args, **kwargs): # def _apply_constraint(constraint, arg, func_name, arg_name): # def _make_constraint(c): # def __call__(self, arg): # def __init__(self, types, multiple=False): # def __call__(self, arg): # def __repr__(self): # def __init__(self, values): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, fromwhat, towhat): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what, return_type=None): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *requirements): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *alternatives): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def _function_repr(f): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): , which may contain function names, class names, or code. Output only the next line.
@arguments.accept(int)
Predict the next line after this snippet: <|code_start|> def test_kwargs_any(self): @arguments.accept(None, kwargs={None: int}) def foo(*args, **kwargs): self.assertEqual(len(args), 2) self.assertEqual(args[0], 23) self.assertEqual(args[1], 42) self.assertEqual(len(kwargs), 2) self.assertEqual(kwargs['bar'], 13) self.assertEqual(kwargs['baz'], 666) foo(23, 42, bar=13, baz=666) with self.assertRaises(TypeError): foo(23, 42, bar=13, baz=66.6) def test_nullable(self): @arguments.accept(arguments.nullable(int)) def foo(a): pass foo(None) foo(42) with self.assertRaises(TypeError): foo() with self.assertRaises(TypeError): foo(123.456) def test_sequenceof(self): @arguments.accept(arguments.sequenceof(int)) def foo(a): <|code_end|> using the current file's imports: import unittest2 as unittest import unittest from mididings import arguments from mididings import misc and any relevant context from other files: # Path: mididings/arguments.py # class accept(object): # class _constraint(object): # class _any(_constraint): # class _type_constraint(_constraint): # class _value_constraint(_constraint): # class nullable(_constraint): # class sequenceof(_constraint): # class tupleof(_constraint): # class mappingof(_constraint): # class flatten(_constraint): # class each(_constraint): # class either(_constraint): # class transform(_constraint): # class condition(_constraint): # class reduce_bitmask(_constraint): # def __init__(self, *constraints, **kwargs): # def __call__(self, f): # def wrapper(self, f, *args, **kwargs): # def _apply_constraint(constraint, arg, func_name, arg_name): # def _make_constraint(c): # def __call__(self, arg): # def __init__(self, types, multiple=False): # def __call__(self, arg): # def __repr__(self): # def __init__(self, values): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *what): # def __call__(self, arg): # def __repr__(self): # def __init__(self, fromwhat, towhat): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what, return_type=None): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *requirements): # def __call__(self, arg): # def __repr__(self): # def __init__(self, *alternatives): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, function): # def __call__(self, arg): # def __repr__(self): # def __init__(self, what): # def __call__(self, arg): # def _function_repr(f): # # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): . Output only the next line.
self.assertTrue(misc.issequenceof(a, int))
Predict the next line after this snippet: <|code_start|> self.notes[-2][0], self.notes[-2][1]) r = [ev, noteon] else: # note isn't sounding, discard note off r = None # remove released note from list self.notes = [x for x in self.notes if x[0] != ev.note] return r def LimitPolyphony(max_polyphony, remove_oldest=True): """ Limit the "MIDI polyphony". :param max_polyphony: The maximum number of simultaneous notes. :param remove_oldest: If true, the oldest notes will be stopped when the maximum polyphony is exceeded. If false, no new notes are accepted while *max_polyphony* notes are already held. Note that the actual polyphony of a connected synthesizer can still be higher than the limit set here, e.g. due to a long release phase. """ return (_m.Filter(_m.NOTE) % <|code_end|> using the current file's imports: import mididings as _m import mididings.event as _event from mididings.extra.per_channel import PerChannel as _PerChannel and any relevant context from other files: # Path: mididings/extra/per_channel.py # class PerChannel(object): # """ # Utility class, usable with Process() and Call(), that delegates events # to different instances of the same class, using one instance per # channel/port combination. # New instances are created as needed, using the given factory function, # when the first event with a new channel/port arrives. # """ # def __init__(self, factory): # self.channel_proc = {} # self.factory = factory # # def __call__(self, ev): # k = (ev.port, ev.channel) # if k not in self.channel_proc: # self.channel_proc[k] = self.factory() # return self.channel_proc[k](ev) . Output only the next line.
_m.Process(_PerChannel(
Given snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # @_unitrepr.store def Sanitize(): """ Sanitize() Make sure the event is a valid MIDI message. Events with invalid port (output), channel, controller, program or note number are discarded. Note velocity and controller values are confined to the range 0-127. """ <|code_end|> , continue by predicting the next line. Consider current file imports: import _mididings import mididings.constants as _constants import mididings.util as _util import mididings.overload as _overload import mididings.unitrepr as _unitrepr from mididings.units.base import _Unit and context: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) which might include code, classes, or functions. Output only the next line.
return _Unit(_mididings.Sanitize())
Based on the snippet: <|code_start|> """ if port is None: port = _util.offset(0) if channel is None: channel = _util.offset(0) if isinstance(program, tuple): bank, program = program else: bank = None init = [] if bank is not None: init.append(Ctrl(port, channel, 0, bank // 128)) init.append(Ctrl(port, channel, 32, bank % 128)) if program is not None: init.append(Program(port, channel, program)) if volume is not None: init.append(Ctrl(port, channel, 7, volume)) if pan is not None: init.append(Ctrl(port, channel, 10, pan)) if expression is not None: init.append(Ctrl(port, channel, 11, expression)) for k, v in ctrls.items(): init.append(Ctrl(port, channel, k, v)) <|code_end|> , predict the immediate next line with the help of imports: from mididings.units.base import _Unit, Fork, Chain, _UNIT_TYPES from mididings.units.generators import Program, Ctrl from mididings.units.modifiers import Port, Channel import mididings.unitrepr as _unitrepr import mididings.util as _util import functools as _functools import copy as _copy and context (classes, functions, sometimes code) from other files: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.program_number_ref) # def Program(port, channel, program): # """ # Program(program) # Program(port, channel, program) # # Create a program change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.PROGRAM, # _util.actual_ref(port), # _util.actual_ref(channel), # 0, # _util.actual_ref(program) # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.ctrl_number_ref, _util.ctrl_value_ref) # def Ctrl(port, channel, ctrl, value): # """ # Ctrl(ctrl, value) # Ctrl(port, channel, ctrl, value) # # Create a control change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.CTRL, # _util.actual_ref(port), # _util.actual_ref(channel), # ctrl, # value # )) # # Path: mididings/units/modifiers.py # @_unitrepr.accept(_util.port_number) # def Port(port): # """ # Port(port) # # Change the event's port number. # """ # return _Unit(_mididings.Port(_util.actual(port))) # # @_unitrepr.accept(_util.channel_number) # def Channel(channel): # """ # Channel(channel) # # Change the event's channel number. # """ # return _Unit(_mididings.Channel(_util.actual(channel))) . Output only the next line.
return Fork([
Given snippet: <|code_start|> init.append(Ctrl(port, channel, 11, expression)) for k, v in ctrls.items(): init.append(Ctrl(port, channel, k, v)) return Fork([ Init(init), Port(port) >> Channel(channel) ]) class OutputTemplate(object): """ OutputTemplate(*args, **kwargs) Create an object that when called will behave like :func:`~.Output()`, with *args* and *kwargs* replacing some of its arguments. That is, :class:`~.OutputTemplate()` is not a unit by itself, but returns one when called. This works just like ``functools.partial(Output, *args, **kwargs)``, but with the added benefit that an :class:`~.OutputTemplate()` object also supports operator ``>>`` like any unit. """ def __init__(self, *args, **kwargs): self.partial = _functools.partial(Output, *args, **kwargs) self.before = [] self.after = [] def __call__(self, *args, **kwargs): <|code_end|> , continue by predicting the next line. Consider current file imports: from mididings.units.base import _Unit, Fork, Chain, _UNIT_TYPES from mididings.units.generators import Program, Ctrl from mididings.units.modifiers import Port, Channel import mididings.unitrepr as _unitrepr import mididings.util as _util import functools as _functools import copy as _copy and context: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.program_number_ref) # def Program(port, channel, program): # """ # Program(program) # Program(port, channel, program) # # Create a program change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.PROGRAM, # _util.actual_ref(port), # _util.actual_ref(channel), # 0, # _util.actual_ref(program) # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.ctrl_number_ref, _util.ctrl_value_ref) # def Ctrl(port, channel, ctrl, value): # """ # Ctrl(ctrl, value) # Ctrl(port, channel, ctrl, value) # # Create a control change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.CTRL, # _util.actual_ref(port), # _util.actual_ref(channel), # ctrl, # value # )) # # Path: mididings/units/modifiers.py # @_unitrepr.accept(_util.port_number) # def Port(port): # """ # Port(port) # # Change the event's port number. # """ # return _Unit(_mididings.Port(_util.actual(port))) # # @_unitrepr.accept(_util.channel_number) # def Channel(channel): # """ # Channel(channel) # # Change the event's channel number. # """ # return _Unit(_mididings.Channel(_util.actual(channel))) which might include code, classes, or functions. Output only the next line.
return (Chain(self.before)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # class _InitExit(_Unit): def __init__(self, init_patch=[], exit_patch=[]): self.init_patch = init_patch self.exit_patch = exit_patch <|code_end|> , predict the immediate next line with the help of imports: from mididings.units.base import _Unit, Fork, Chain, _UNIT_TYPES from mididings.units.generators import Program, Ctrl from mididings.units.modifiers import Port, Channel import mididings.unitrepr as _unitrepr import mididings.util as _util import functools as _functools import copy as _copy and context (classes, functions, sometimes code) from other files: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.program_number_ref) # def Program(port, channel, program): # """ # Program(program) # Program(port, channel, program) # # Create a program change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.PROGRAM, # _util.actual_ref(port), # _util.actual_ref(channel), # 0, # _util.actual_ref(program) # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.ctrl_number_ref, _util.ctrl_value_ref) # def Ctrl(port, channel, ctrl, value): # """ # Ctrl(ctrl, value) # Ctrl(port, channel, ctrl, value) # # Create a control change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.CTRL, # _util.actual_ref(port), # _util.actual_ref(channel), # ctrl, # value # )) # # Path: mididings/units/modifiers.py # @_unitrepr.accept(_util.port_number) # def Port(port): # """ # Port(port) # # Change the event's port number. # """ # return _Unit(_mididings.Port(_util.actual(port))) # # @_unitrepr.accept(_util.channel_number) # def Channel(channel): # """ # Channel(channel) # # Change the event's channel number. # """ # return _Unit(_mididings.Channel(_util.actual(channel))) . Output only the next line.
@_unitrepr.accept(_UNIT_TYPES)
Next line prediction: <|code_start|> To send a bank select (CC #0 and CC #32) before the program change, *program* can be a tuple with two elements, where the first element is the bank number, and the second is the program number. Values for the commonly used controllers *volume* (#7), *pan* (#10) and *expression* (#11) can be specified directly. For all other controllers, the *ctrls* argument can contain a mapping from controller numbers to their respective values. If *port* or *channel* are ``None``, events will be routed to the first port/channel. """ if port is None: port = _util.offset(0) if channel is None: channel = _util.offset(0) if isinstance(program, tuple): bank, program = program else: bank = None init = [] if bank is not None: init.append(Ctrl(port, channel, 0, bank // 128)) init.append(Ctrl(port, channel, 32, bank % 128)) if program is not None: <|code_end|> . Use current file imports: (from mididings.units.base import _Unit, Fork, Chain, _UNIT_TYPES from mididings.units.generators import Program, Ctrl from mididings.units.modifiers import Port, Channel import mididings.unitrepr as _unitrepr import mididings.util as _util import functools as _functools import copy as _copy) and context including class names, function names, or small code snippets from other files: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.program_number_ref) # def Program(port, channel, program): # """ # Program(program) # Program(port, channel, program) # # Create a program change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.PROGRAM, # _util.actual_ref(port), # _util.actual_ref(channel), # 0, # _util.actual_ref(program) # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.ctrl_number_ref, _util.ctrl_value_ref) # def Ctrl(port, channel, ctrl, value): # """ # Ctrl(ctrl, value) # Ctrl(port, channel, ctrl, value) # # Create a control change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.CTRL, # _util.actual_ref(port), # _util.actual_ref(channel), # ctrl, # value # )) # # Path: mididings/units/modifiers.py # @_unitrepr.accept(_util.port_number) # def Port(port): # """ # Port(port) # # Change the event's port number. # """ # return _Unit(_mididings.Port(_util.actual(port))) # # @_unitrepr.accept(_util.channel_number) # def Channel(channel): # """ # Channel(channel) # # Change the event's channel number. # """ # return _Unit(_mididings.Channel(_util.actual(channel))) . Output only the next line.
init.append(Program(port, channel, program))
Given the following code snippet before the placeholder: <|code_start|> Route incoming events to the specified *port* and *channel*. When switching to the scene containing this unit, a program change and/or arbitrary control changes can be sent. To send a bank select (CC #0 and CC #32) before the program change, *program* can be a tuple with two elements, where the first element is the bank number, and the second is the program number. Values for the commonly used controllers *volume* (#7), *pan* (#10) and *expression* (#11) can be specified directly. For all other controllers, the *ctrls* argument can contain a mapping from controller numbers to their respective values. If *port* or *channel* are ``None``, events will be routed to the first port/channel. """ if port is None: port = _util.offset(0) if channel is None: channel = _util.offset(0) if isinstance(program, tuple): bank, program = program else: bank = None init = [] if bank is not None: <|code_end|> , predict the next line using imports from the current file: from mididings.units.base import _Unit, Fork, Chain, _UNIT_TYPES from mididings.units.generators import Program, Ctrl from mididings.units.modifiers import Port, Channel import mididings.unitrepr as _unitrepr import mididings.util as _util import functools as _functools import copy as _copy and context including class names, function names, and sometimes code from other files: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.program_number_ref) # def Program(port, channel, program): # """ # Program(program) # Program(port, channel, program) # # Create a program change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.PROGRAM, # _util.actual_ref(port), # _util.actual_ref(channel), # 0, # _util.actual_ref(program) # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.ctrl_number_ref, _util.ctrl_value_ref) # def Ctrl(port, channel, ctrl, value): # """ # Ctrl(ctrl, value) # Ctrl(port, channel, ctrl, value) # # Create a control change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.CTRL, # _util.actual_ref(port), # _util.actual_ref(channel), # ctrl, # value # )) # # Path: mididings/units/modifiers.py # @_unitrepr.accept(_util.port_number) # def Port(port): # """ # Port(port) # # Change the event's port number. # """ # return _Unit(_mididings.Port(_util.actual(port))) # # @_unitrepr.accept(_util.channel_number) # def Channel(channel): # """ # Channel(channel) # # Change the event's channel number. # """ # return _Unit(_mididings.Channel(_util.actual(channel))) . Output only the next line.
init.append(Ctrl(port, channel, 0, bank // 128))
Continue the code snippet: <|code_start|> port = _util.offset(0) if channel is None: channel = _util.offset(0) if isinstance(program, tuple): bank, program = program else: bank = None init = [] if bank is not None: init.append(Ctrl(port, channel, 0, bank // 128)) init.append(Ctrl(port, channel, 32, bank % 128)) if program is not None: init.append(Program(port, channel, program)) if volume is not None: init.append(Ctrl(port, channel, 7, volume)) if pan is not None: init.append(Ctrl(port, channel, 10, pan)) if expression is not None: init.append(Ctrl(port, channel, 11, expression)) for k, v in ctrls.items(): init.append(Ctrl(port, channel, k, v)) return Fork([ Init(init), <|code_end|> . Use current file imports: from mididings.units.base import _Unit, Fork, Chain, _UNIT_TYPES from mididings.units.generators import Program, Ctrl from mididings.units.modifiers import Port, Channel import mididings.unitrepr as _unitrepr import mididings.util as _util import functools as _functools import copy as _copy and context (classes, functions, or code) from other files: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.program_number_ref) # def Program(port, channel, program): # """ # Program(program) # Program(port, channel, program) # # Create a program change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.PROGRAM, # _util.actual_ref(port), # _util.actual_ref(channel), # 0, # _util.actual_ref(program) # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.ctrl_number_ref, _util.ctrl_value_ref) # def Ctrl(port, channel, ctrl, value): # """ # Ctrl(ctrl, value) # Ctrl(port, channel, ctrl, value) # # Create a control change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.CTRL, # _util.actual_ref(port), # _util.actual_ref(channel), # ctrl, # value # )) # # Path: mididings/units/modifiers.py # @_unitrepr.accept(_util.port_number) # def Port(port): # """ # Port(port) # # Change the event's port number. # """ # return _Unit(_mididings.Port(_util.actual(port))) # # @_unitrepr.accept(_util.channel_number) # def Channel(channel): # """ # Channel(channel) # # Change the event's channel number. # """ # return _Unit(_mididings.Channel(_util.actual(channel))) . Output only the next line.
Port(port) >> Channel(channel)
Next line prediction: <|code_start|> port = _util.offset(0) if channel is None: channel = _util.offset(0) if isinstance(program, tuple): bank, program = program else: bank = None init = [] if bank is not None: init.append(Ctrl(port, channel, 0, bank // 128)) init.append(Ctrl(port, channel, 32, bank % 128)) if program is not None: init.append(Program(port, channel, program)) if volume is not None: init.append(Ctrl(port, channel, 7, volume)) if pan is not None: init.append(Ctrl(port, channel, 10, pan)) if expression is not None: init.append(Ctrl(port, channel, 11, expression)) for k, v in ctrls.items(): init.append(Ctrl(port, channel, k, v)) return Fork([ Init(init), <|code_end|> . Use current file imports: (from mididings.units.base import _Unit, Fork, Chain, _UNIT_TYPES from mididings.units.generators import Program, Ctrl from mididings.units.modifiers import Port, Channel import mididings.unitrepr as _unitrepr import mididings.util as _util import functools as _functools import copy as _copy) and context including class names, function names, or small code snippets from other files: # Path: mididings/units/base.py # class _Unit(object): # """ # Wrapper class for all units. # """ # def __init__(self, unit): # self.unit = unit # # def __rshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, self, other) # # def __rrshift__(self, other): # """ # Connect units in series (operator >>). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Chain, other, self) # # def __floordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, self, other) # # def __rfloordiv__(self, other): # """ # Connect units in parallel (operator //). # """ # if not isinstance(other, _UNIT_TYPES): # return NotImplemented # return _join_units(_Fork, other, self) # # def __pos__(self): # """ # Apply to duplicate (unary operator +) # """ # return self.add() # # def add(self): # return Fork([ Pass(), self ]) # # def __repr__(self): # return _unitrepr.unit_to_string(self) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/generators.py # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.program_number_ref) # def Program(port, channel, program): # """ # Program(program) # Program(port, channel, program) # # Create a program change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.PROGRAM, # _util.actual_ref(port), # _util.actual_ref(channel), # 0, # _util.actual_ref(program) # )) # # @_overload.partial((_constants.EVENT_PORT, _constants.EVENT_CHANNEL)) # @_unitrepr.accept(_util.port_number_ref, _util.channel_number_ref, # _util.ctrl_number_ref, _util.ctrl_value_ref) # def Ctrl(port, channel, ctrl, value): # """ # Ctrl(ctrl, value) # Ctrl(port, channel, ctrl, value) # # Create a control change event, replacing the incoming event. # """ # return _Unit(_mididings.Generator( # _constants.CTRL, # _util.actual_ref(port), # _util.actual_ref(channel), # ctrl, # value # )) # # Path: mididings/units/modifiers.py # @_unitrepr.accept(_util.port_number) # def Port(port): # """ # Port(port) # # Change the event's port number. # """ # return _Unit(_mididings.Port(_util.actual(port))) # # @_unitrepr.accept(_util.channel_number) # def Channel(channel): # """ # Channel(channel) # # Change the event's channel number. # """ # return _Unit(_mididings.Channel(_util.actual(channel))) . Output only the next line.
Port(port) >> Channel(channel)
Given snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # if sys.version_info >= (3,): unichr = chr class LiveDings(object): def __init__(self, options): self.options = options # start OSC server self.osc = LiveOSC(self, self.options.control_port, self.options.listen_port) self.osc.start() if self.options.themed: <|code_end|> , continue by predicting the next line. Consider current file imports: from mididings.live.widgets import LiveThemedFactory, UnthemedFactory from mididings.live.osc_control import LiveOSC import sys and context: # Path: mididings/live/widgets.py # class LiveThemedFactory(object): # def __init__(self, color, color_highlight, color_background): # self.color = color # self.color_highlight = color_highlight # self.color_background = color_background # # def Tk(self, **options): # w = Tkinter.Tk() # w.config(background=self.color_background) # w.config(**options) # return w # # def Frame(self, master, **options): # w = Tkinter.Frame(master) # w.config(background=self.color) # w.config(**options) # return w # # def AutoScrollbar(self, master, **options): # w = AutoScrollbar(master) # w.config( # background=self.color, # activebackground=self.color_highlight, # troughcolor=self.color_background, # borderwidth=1, # relief='flat', # width=16, # ) # w.config(**options) # return w # # def Listbox(self, master, **options): # w = Tkinter.Listbox(master) # w.config( # background=self.color_background, # foreground=self.color, # selectbackground=self.color_background, # selectforeground=self.color_highlight, # selectborderwidth=0, # borderwidth=0, # ) # w.config(**options) # return w # # def Button(self, master, **options): # w = Tkinter.Button(master) # w.config( # background=self.color_background, # foreground=self.color, # activebackground=self.color_background, # activeforeground=self.color_highlight, # borderwidth=0, # highlightthickness=0, # relief='flat', # ) # w.config(**options) # return w # # def Canvas(self, master, **options): # w = Tkinter.Canvas(master) # w.config(background=self.color_background) # w.config(**options) # return w # # class UnthemedFactory(object): # def Tk(self, **options): # w = Tkinter.Tk() # w.config(**options) # return w # # def Frame(self, master, **options): # return Tkinter.Frame(master, **options) # # def AutoScrollbar(self, master, **options): # return AutoScrollbar(master, **options) # # def Listbox(self, master, **options): # return Tkinter.Listbox(master, **options) # # def Button(self, master, **options): # return Tkinter.Button(master, **options) # # def Canvas(self, master, **options): # return Tkinter.Canvas(master, **options) # # Path: mididings/live/osc_control.py # class LiveOSC(liblo.ServerThread): # def __init__(self, dings, control_port, listen_port): # liblo.ServerThread.__init__(self, listen_port) # # self.dings = dings # self.control_port = control_port # # self._scenes = {} # # def query(self): # self.send(self.control_port, '/mididings/query') # # def switch_scene(self, n): # self.send(self.control_port, '/mididings/switch_scene', n) # # def switch_subscene(self, n): # self.send(self.control_port, '/mididings/switch_subscene', n) # # def prev_scene(self): # self.send(self.control_port, '/mididings/prev_scene') # # def next_scene(self): # self.send(self.control_port, '/mididings/next_scene') # # def prev_subscene(self): # self.send(self.control_port, '/mididings/prev_subscene') # # def next_subscene(self): # self.send(self.control_port, '/mididings/next_subscene') # # def panic(self): # self.send(self.control_port, '/mididings/panic') # # @liblo.make_method('/mididings/data_offset', 'i') # def data_offset_cb(self, path, args): # self.dings.set_data_offset(args[0]) # # @liblo.make_method('/mididings/begin_scenes', '') # def begin_scenes_cb(self, path, args): # self._scenes = {} # # @liblo.make_method('/mididings/add_scene', None) # def add_scene_cb(self, path, args): # number, name = args[:2] # subscenes = args[2:] # self._scenes[number] = (name, subscenes) # # @liblo.make_method('/mididings/end_scenes', '') # def end_scenes_cb(self, path, args): # self.dings.set_scenes(self._scenes) # # @liblo.make_method('/mididings/current_scene', 'ii') # def current_scene_cb(self, path, args): # self.dings.set_current_scene(args[0], args[1]) which might include code, classes, or functions. Output only the next line.
widget_factory = LiveThemedFactory(self.options.color,
Given the following code snippet before the placeholder: <|code_start|># # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # if sys.version_info >= (3,): unichr = chr class LiveDings(object): def __init__(self, options): self.options = options # start OSC server self.osc = LiveOSC(self, self.options.control_port, self.options.listen_port) self.osc.start() if self.options.themed: widget_factory = LiveThemedFactory(self.options.color, self.options.color_highlight, self.options.color_background) else: <|code_end|> , predict the next line using imports from the current file: from mididings.live.widgets import LiveThemedFactory, UnthemedFactory from mididings.live.osc_control import LiveOSC import sys and context including class names, function names, and sometimes code from other files: # Path: mididings/live/widgets.py # class LiveThemedFactory(object): # def __init__(self, color, color_highlight, color_background): # self.color = color # self.color_highlight = color_highlight # self.color_background = color_background # # def Tk(self, **options): # w = Tkinter.Tk() # w.config(background=self.color_background) # w.config(**options) # return w # # def Frame(self, master, **options): # w = Tkinter.Frame(master) # w.config(background=self.color) # w.config(**options) # return w # # def AutoScrollbar(self, master, **options): # w = AutoScrollbar(master) # w.config( # background=self.color, # activebackground=self.color_highlight, # troughcolor=self.color_background, # borderwidth=1, # relief='flat', # width=16, # ) # w.config(**options) # return w # # def Listbox(self, master, **options): # w = Tkinter.Listbox(master) # w.config( # background=self.color_background, # foreground=self.color, # selectbackground=self.color_background, # selectforeground=self.color_highlight, # selectborderwidth=0, # borderwidth=0, # ) # w.config(**options) # return w # # def Button(self, master, **options): # w = Tkinter.Button(master) # w.config( # background=self.color_background, # foreground=self.color, # activebackground=self.color_background, # activeforeground=self.color_highlight, # borderwidth=0, # highlightthickness=0, # relief='flat', # ) # w.config(**options) # return w # # def Canvas(self, master, **options): # w = Tkinter.Canvas(master) # w.config(background=self.color_background) # w.config(**options) # return w # # class UnthemedFactory(object): # def Tk(self, **options): # w = Tkinter.Tk() # w.config(**options) # return w # # def Frame(self, master, **options): # return Tkinter.Frame(master, **options) # # def AutoScrollbar(self, master, **options): # return AutoScrollbar(master, **options) # # def Listbox(self, master, **options): # return Tkinter.Listbox(master, **options) # # def Button(self, master, **options): # return Tkinter.Button(master, **options) # # def Canvas(self, master, **options): # return Tkinter.Canvas(master, **options) # # Path: mididings/live/osc_control.py # class LiveOSC(liblo.ServerThread): # def __init__(self, dings, control_port, listen_port): # liblo.ServerThread.__init__(self, listen_port) # # self.dings = dings # self.control_port = control_port # # self._scenes = {} # # def query(self): # self.send(self.control_port, '/mididings/query') # # def switch_scene(self, n): # self.send(self.control_port, '/mididings/switch_scene', n) # # def switch_subscene(self, n): # self.send(self.control_port, '/mididings/switch_subscene', n) # # def prev_scene(self): # self.send(self.control_port, '/mididings/prev_scene') # # def next_scene(self): # self.send(self.control_port, '/mididings/next_scene') # # def prev_subscene(self): # self.send(self.control_port, '/mididings/prev_subscene') # # def next_subscene(self): # self.send(self.control_port, '/mididings/next_subscene') # # def panic(self): # self.send(self.control_port, '/mididings/panic') # # @liblo.make_method('/mididings/data_offset', 'i') # def data_offset_cb(self, path, args): # self.dings.set_data_offset(args[0]) # # @liblo.make_method('/mididings/begin_scenes', '') # def begin_scenes_cb(self, path, args): # self._scenes = {} # # @liblo.make_method('/mididings/add_scene', None) # def add_scene_cb(self, path, args): # number, name = args[:2] # subscenes = args[2:] # self._scenes[number] = (name, subscenes) # # @liblo.make_method('/mididings/end_scenes', '') # def end_scenes_cb(self, path, args): # self.dings.set_scenes(self._scenes) # # @liblo.make_method('/mididings/current_scene', 'ii') # def current_scene_cb(self, path, args): # self.dings.set_current_scene(args[0], args[1]) . Output only the next line.
widget_factory = UnthemedFactory()
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # if sys.version_info >= (3,): unichr = chr class LiveDings(object): def __init__(self, options): self.options = options # start OSC server <|code_end|> . Write the next line using the current file imports: from mididings.live.widgets import LiveThemedFactory, UnthemedFactory from mididings.live.osc_control import LiveOSC import sys and context from other files: # Path: mididings/live/widgets.py # class LiveThemedFactory(object): # def __init__(self, color, color_highlight, color_background): # self.color = color # self.color_highlight = color_highlight # self.color_background = color_background # # def Tk(self, **options): # w = Tkinter.Tk() # w.config(background=self.color_background) # w.config(**options) # return w # # def Frame(self, master, **options): # w = Tkinter.Frame(master) # w.config(background=self.color) # w.config(**options) # return w # # def AutoScrollbar(self, master, **options): # w = AutoScrollbar(master) # w.config( # background=self.color, # activebackground=self.color_highlight, # troughcolor=self.color_background, # borderwidth=1, # relief='flat', # width=16, # ) # w.config(**options) # return w # # def Listbox(self, master, **options): # w = Tkinter.Listbox(master) # w.config( # background=self.color_background, # foreground=self.color, # selectbackground=self.color_background, # selectforeground=self.color_highlight, # selectborderwidth=0, # borderwidth=0, # ) # w.config(**options) # return w # # def Button(self, master, **options): # w = Tkinter.Button(master) # w.config( # background=self.color_background, # foreground=self.color, # activebackground=self.color_background, # activeforeground=self.color_highlight, # borderwidth=0, # highlightthickness=0, # relief='flat', # ) # w.config(**options) # return w # # def Canvas(self, master, **options): # w = Tkinter.Canvas(master) # w.config(background=self.color_background) # w.config(**options) # return w # # class UnthemedFactory(object): # def Tk(self, **options): # w = Tkinter.Tk() # w.config(**options) # return w # # def Frame(self, master, **options): # return Tkinter.Frame(master, **options) # # def AutoScrollbar(self, master, **options): # return AutoScrollbar(master, **options) # # def Listbox(self, master, **options): # return Tkinter.Listbox(master, **options) # # def Button(self, master, **options): # return Tkinter.Button(master, **options) # # def Canvas(self, master, **options): # return Tkinter.Canvas(master, **options) # # Path: mididings/live/osc_control.py # class LiveOSC(liblo.ServerThread): # def __init__(self, dings, control_port, listen_port): # liblo.ServerThread.__init__(self, listen_port) # # self.dings = dings # self.control_port = control_port # # self._scenes = {} # # def query(self): # self.send(self.control_port, '/mididings/query') # # def switch_scene(self, n): # self.send(self.control_port, '/mididings/switch_scene', n) # # def switch_subscene(self, n): # self.send(self.control_port, '/mididings/switch_subscene', n) # # def prev_scene(self): # self.send(self.control_port, '/mididings/prev_scene') # # def next_scene(self): # self.send(self.control_port, '/mididings/next_scene') # # def prev_subscene(self): # self.send(self.control_port, '/mididings/prev_subscene') # # def next_subscene(self): # self.send(self.control_port, '/mididings/next_subscene') # # def panic(self): # self.send(self.control_port, '/mididings/panic') # # @liblo.make_method('/mididings/data_offset', 'i') # def data_offset_cb(self, path, args): # self.dings.set_data_offset(args[0]) # # @liblo.make_method('/mididings/begin_scenes', '') # def begin_scenes_cb(self, path, args): # self._scenes = {} # # @liblo.make_method('/mididings/add_scene', None) # def add_scene_cb(self, path, args): # number, name = args[:2] # subscenes = args[2:] # self._scenes[number] = (name, subscenes) # # @liblo.make_method('/mididings/end_scenes', '') # def end_scenes_cb(self, path, args): # self.dings.set_scenes(self._scenes) # # @liblo.make_method('/mididings/current_scene', 'ii') # def current_scene_cb(self, path, args): # self.dings.set_current_scene(args[0], args[1]) , which may include functions, classes, or code. Output only the next line.
self.osc = LiveOSC(self, self.options.control_port,
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # def call(args, kwargs, funcs, name=None): """ Search funcs for a function with parameters such that args and kwargs can be applied, and call the first suitable function that is found. """ for f in funcs: n = len(args) # get argument names and the number of default arguments of f <|code_end|> , predict the next line using imports from the current file: from mididings import misc import inspect import functools and context including class names, function names, and sometimes code from other files: # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): . Output only the next line.
argspec = misc.getargspec(f)
Next line prediction: <|code_start|> return r elif ev.type == _m.NOTEON: self.held_notes.add(ev.note) return ev elif ev.type == _m.NOTEOFF: self.held_notes.discard(ev.note) # send note off only if the note is not currently being sustained if ev.note not in self.sustained_notes: return ev else: return None else: # everything else: return as is return ev def PedalToNoteoff(ctrl=64, sostenuto=False): """ Convert sustain pedal control changes to note-off events, by delaying note-offs until the pedal is released. :param ctrl: The pedal's controller number. :param sostenuto: If true act like a sostenuto pedal, instead of a regular sustain pedal. """ if sostenuto: <|code_end|> . Use current file imports: (import mididings as _m import mididings.event as _event from mididings.extra.per_channel import PerChannel as _PerChannel) and context including class names, function names, or small code snippets from other files: # Path: mididings/extra/per_channel.py # class PerChannel(object): # """ # Utility class, usable with Process() and Call(), that delegates events # to different instances of the same class, using one instance per # channel/port combination. # New instances are created as needed, using the given factory function, # when the first event with a new channel/port arrives. # """ # def __init__(self, factory): # self.channel_proc = {} # self.factory = factory # # def __call__(self, ev): # k = (ev.port, ev.channel) # if k not in self.channel_proc: # self.channel_proc[k] = self.factory() # return self.channel_proc[k](ev) . Output only the next line.
proc = _m.Process(_PerChannel(lambda: _SostenutoToNoteoff(ctrl)))
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # def _make_split(t, d, unpack=False): if unpack: # if dictionary key is a tuple, unpack and pass as individual # parameters to ctor t = lambda p, t=t: t(*(p if isinstance(p, tuple) else (p,))) # build dict with all items from d, except d[None] dd = dict((k, v) for k, v in d.items() if k is not None) # build fork from all normal items r = Fork((t(k) >> w) for k, w in dd.items()) # add else-rule, if any if None in d: <|code_end|> with the help of current file imports: from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util and context from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) , which may contain function names, class names, or code. Output only the next line.
f = Chain(~t(k) for k in dd.keys())
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # # mididings # # Copyright (C) 2008-2014 Dominic Sacré <dominic.sacre@gmx.de> # # 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 2 of the License, or # (at your option) any later version. # def _make_split(t, d, unpack=False): if unpack: # if dictionary key is a tuple, unpack and pass as individual # parameters to ctor t = lambda p, t=t: t(*(p if isinstance(p, tuple) else (p,))) # build dict with all items from d, except d[None] dd = dict((k, v) for k, v in d.items() if k is not None) # build fork from all normal items <|code_end|> . Use current file imports: (from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util) and context including class names, function names, or small code snippets from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) . Output only the next line.
r = Fork((t(k) >> w) for k, w in dd.items())
Given the code snippet: <|code_start|>def _make_split(t, d, unpack=False): if unpack: # if dictionary key is a tuple, unpack and pass as individual # parameters to ctor t = lambda p, t=t: t(*(p if isinstance(p, tuple) else (p,))) # build dict with all items from d, except d[None] dd = dict((k, v) for k, v in d.items() if k is not None) # build fork from all normal items r = Fork((t(k) >> w) for k, w in dd.items()) # add else-rule, if any if None in d: f = Chain(~t(k) for k in dd.keys()) r.append(f >> d[None]) return r def _make_threshold(f, patch_lower, patch_upper): return Fork([ f >> patch_lower, ~f >> patch_upper, ]) @_arguments.accept({ _arguments.nullable(_arguments.flatten(_util.port_number, tuple)): <|code_end|> , generate the next line using the imports in this file: from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util and context (functions, classes, or occasionally code) from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) . Output only the next line.
_UNIT_TYPES
Predict the next line for this snippet: <|code_start|> # build fork from all normal items r = Fork((t(k) >> w) for k, w in dd.items()) # add else-rule, if any if None in d: f = Chain(~t(k) for k in dd.keys()) r.append(f >> d[None]) return r def _make_threshold(f, patch_lower, patch_upper): return Fork([ f >> patch_lower, ~f >> patch_upper, ]) @_arguments.accept({ _arguments.nullable(_arguments.flatten(_util.port_number, tuple)): _UNIT_TYPES }) def PortSplit(mapping): """ PortSplit(mapping) Split events by input port, with *mapping* being a dictionary of the form ``{ports: patch, ...}``. """ <|code_end|> with the help of current file imports: from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util and context from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) , which may contain function names, class names, or code. Output only the next line.
return _make_split(PortFilter, mapping)
Next line prediction: <|code_start|> ~f >> patch_upper, ]) @_arguments.accept({ _arguments.nullable(_arguments.flatten(_util.port_number, tuple)): _UNIT_TYPES }) def PortSplit(mapping): """ PortSplit(mapping) Split events by input port, with *mapping* being a dictionary of the form ``{ports: patch, ...}``. """ return _make_split(PortFilter, mapping) @_arguments.accept({ _arguments.nullable(_arguments.flatten(_util.channel_number, tuple)): _UNIT_TYPES }) def ChannelSplit(mapping): """ ChannelSplit(mapping) Split events by input channel, with *mapping* being a dictionary of the form ``{channels: patch, ...}``. """ <|code_end|> . Use current file imports: (from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util) and context including class names, function names, or small code snippets from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) . Output only the next line.
return _make_split(ChannelFilter, mapping)
Based on the snippet: <|code_start|> @_arguments.accept({ _arguments.nullable(_arguments.flatten(_util.channel_number, tuple)): _UNIT_TYPES }) def ChannelSplit(mapping): """ ChannelSplit(mapping) Split events by input channel, with *mapping* being a dictionary of the form ``{channels: patch, ...}``. """ return _make_split(ChannelFilter, mapping) @_overload.mark( """ KeySplit(threshold, patch_lower, patch_upper) KeySplit(mapping) Split events by key. Non-note events are sent to all patches. The first version splits at a single threshold. The second version allows an arbitrary number of (possibly overlapping) note ranges, with *mapping* being a dictionary of the form ``{note_range: patch, ...}``. """ ) @_arguments.accept(_util.note_limit, _UNIT_TYPES, _UNIT_TYPES) def KeySplit(threshold, patch_lower, patch_upper): <|code_end|> , predict the immediate next line with the help of imports: from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util and context (classes, functions, sometimes code) from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) . Output only the next line.
return _make_threshold(KeyFilter(0, threshold),
Here is a snippet: <|code_start|>}) def CtrlSplit(mapping): """ CtrlSplit(mapping) Split events by controller number, with *mapping* being a dictionary of the form ``{ctrls: patch, ...}``. Non-control-change events are discarded. """ return _make_split(CtrlFilter, mapping) @_overload.mark( """ CtrlValueSplit(threshold, patch_lower, patch_upper) CtrlValueSplit(mapping) Split events by controller value. The first version splits at a single threshold. The second version allows an arbitrary number of (possibly overlapping) value ranges, with *mapping* being a dictionary of the form ``{value: patch, ...}`` or ``{(lower, upper): patch, ...}``. Non-control-change events are discarded. """ ) @_arguments.accept(_util.ctrl_limit, _UNIT_TYPES, _UNIT_TYPES) def CtrlValueSplit(threshold, patch_lower, patch_upper): <|code_end|> . Write the next line using the current file imports: from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util and context from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) , which may include functions, classes, or code. Output only the next line.
return _make_threshold(CtrlValueFilter(0, threshold),
Based on the snippet: <|code_start|>@_arguments.accept({ _arguments.nullable(_arguments.flatten(_util.program_number, tuple)): _UNIT_TYPES }) def ProgramSplit(mapping): """ ProgramSplit(mapping) Split events by program number, with *mapping* being a dictionary of the form ``{programs: patch, ...}``. Non-program-change events are discarded. """ return _make_split(ProgramFilter, mapping) @_overload.mark( """ SysExSplit(mapping) SysExSplit(manufacturers=...) Split events by sysex data or manufacturer id, with *mapping* being a dictionary of the form ``{sysex: patch, ...}``, and *manufacturers* being a dictionary of the form ``{manufacturer: patch, ...}`` (cf. :func:`SysExFilter()`). Non-sysex events are discarded. """ ) @_arguments.accept(dict) def SysExSplit(mapping): <|code_end|> , predict the immediate next line with the help of imports: from mididings.units.base import Chain, Fork, _UNIT_TYPES from mididings.units.filters import ( PortFilter, ChannelFilter, KeyFilter, VelocityFilter, CtrlFilter, CtrlValueFilter, ProgramFilter, SysExFilter) import mididings.overload as _overload import mididings.arguments as _arguments import mididings.util as _util and context (classes, functions, sometimes code) from other files: # Path: mididings/units/base.py # @_arguments.accept([_UNIT_TYPES], add_varargs=True) # def Chain(units): # """ # Units connected in series. # """ # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Chain(units) # # @_arguments.accept([_UNIT_TYPES], add_varargs=True, # kwargs={'remove_duplicates': (True, False, None)}) # def Fork(units, **kwargs): # """ # Units connected in parallel. # """ # remove_duplicates = (kwargs['remove_duplicates'] # if 'remove_duplicates' in kwargs else None) # # # handle a single list argument differently for backward compatibility # if len(units) == 1 and type(units[0]) == list: # units = units[0] # # return _Fork(units, remove_duplicates) # # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/units/filters.py # @_unitrepr.accept(_arguments.flatten(_util.port_number), add_varargs=True) # def PortFilter(ports): # """ # PortFilter(ports, ...) # # Filter events by port name or number. The *ports* argument can be a single # port or a list of multiple ports. # """ # return _Filter(_mididings.PortFilter(map(_util.actual, ports))) # # @_unitrepr.accept(_arguments.flatten(_util.channel_number), add_varargs=True) # def ChannelFilter(channels): # """ # ChannelFilter(channels, ...) # # Filter events by channel number. The *channels* argument can be a single # channel number or a list of multiple channel numbers. # System events (which don't carry channel information) are discarded. # """ # return _Filter(_mididings.ChannelFilter(map(_util.actual, channels))) # # @_overload.mark( # """ # KeyFilter(note_range) # KeyFilter(lower, upper) # KeyFilter(lower=...) # KeyFilter(upper=...) # KeyFilter(notes=...) # # Filter note events by key (note number or note range). All other events # are let through. # The last form expects its argument to be a list of individual note names # or numbers. # """ # ) # @_unitrepr.accept(_util.note_range) # def KeyFilter(note_range): # return _Filter(_mididings.KeyFilter(note_range[0], note_range[1], [])) # # @_overload.mark( # """ # VelocityFilter(value) # VelocityFilter(lower=...) # VelocityFilter(upper=...) # VelocityFilter(lower, upper) # # Filter note-on events by velocity. All other events are let through. # """ # ) # @_unitrepr.accept(_util.velocity_value) # def VelocityFilter(value): # return _Filter(_mididings.VelocityFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.ctrl_number), add_varargs=True) # def CtrlFilter(ctrls): # """ # CtrlFilter(ctrls, ...) # # Filter control change events by controller number. The *ctrls* argument # can be a single controller or a list of multiple controller numbers. # All other events are discarded. # """ # return _Filter(_mididings.CtrlFilter(ctrls)) # # @_overload.mark( # """ # CtrlValueFilter(value) # CtrlValueFilter(lower=...) # CtrlValueFilter(upper=...) # CtrlValueFilter(lower, upper) # # Filter control change events by controller value. All other events are # discarded. # """ # ) # @_unitrepr.accept(_util.ctrl_value) # def CtrlValueFilter(value): # return _Filter(_mididings.CtrlValueFilter(value, value + 1)) # # @_unitrepr.accept(_arguments.flatten(_util.program_number), add_varargs=True) # def ProgramFilter(programs): # """ # ProgramFilter(programs, ...) # # Filter program change events by program number. The *programs* argument # can be a single program number or a list of program numbers. # All other events are discarded. # """ # return _Filter(_mididings.ProgramFilter(map(_util.actual, programs))) # # @_overload.mark( # r""" # SysExFilter(sysex) # SysExFilter(manufacturer=...) # # Filter system exclusive events by the data they contain, specified as a # string or as a sequence of integers. # If *sysex* does not end with ``F7``, partial matches that start with the # given data bytes are accepted. # # Alternatively, a sysex manufacturer id can be specified, which may be # either a string or a sequence of integers, with a length of one or three # bytes. # # All non-sysex events are discarded. # """ # ) # @_unitrepr.accept(_functools.partial(_util.sysex_data, allow_partial=True)) # def SysExFilter(sysex): # partial = (sysex[-1] != '\xf7') # return _Filter(_mididings.SysExFilter(sysex, partial)) . Output only the next line.
return _make_split(SysExFilter, mapping)
Here is a snippet: <|code_start|> """ A decorator that applies type checks and other constraints to the arguments of the decorated function. Constraints must be given in the order of the function's positional arguments, one constraint per argument. If the function accepts variable arguments, one additional constraint must be specified, and will be applied to each of those arguments. If the optional keyword argument add_varargs is True, the decorated function will accept variable arguments, which are combined with the last regular positional argument into a single tuple. This tuple is then passed to the original function as a single argument. The kwargs dictionary, itself passed as an optional keyword argument, maps keyword arguments to the corresponding constraints. None can be used as a key in this dictionary to specify constraints for keyword arguments with any name. """ def __init__(self, *constraints, **kwargs): self.add_varargs = (kwargs['add_varargs'] if 'add_varargs' in kwargs else False) kwargs_constraints = kwargs['kwargs'] if 'kwargs' in kwargs else {} # build all constraints self.constraints = [_make_constraint(c) for c in constraints] self.kwargs_constraints = dict((k, _make_constraint(v)) for k, v in kwargs_constraints.items()) def __call__(self, f): <|code_end|> . Write the next line using the current file imports: from mididings import misc import inspect import collections import types import functools import decorator and context from other files: # Path: mididings/misc.py # def flatten(arg): # def issequence(seq, accept_string=False): # def issequenceof(seq, t): # def islambda(f): # def getargspec(f): # def __init__(self, replacement=None): # def wrapper(self, f, *args, **kwargs): # def __call__(self, f): # def __new__(cls, value, name): # def __init__(self, value, name): # def __getnewargs__(self): # def __repr__(self): # def __str__(self): # def __or__(self, other): # def __invert__(self): # def prune_globals(g): # def sequence_to_hex(data): # def __init__(self, data): # def __repr__(self): # def get_terminal_size(): # class deprecated(object): # class NamedFlag(int): # class NamedBitMask(NamedFlag): # class bytestring(object): , which may include functions, classes, or code. Output only the next line.
argspec = misc.getargspec(f)
Given snippet: <|code_start|> # monophonic: turn off previous note, play new note if len(self.notes): r = [_event.NoteOffEvent( ev.port, ev.channel, self.notes[0], 0)] else: r = [] self.notes = [ev.note] return r + [ev] elif ev.type == _m.NOTEOFF: # ignore all note-off events return None def LatchNotes(polyphonic=False, reset=None): """ Makes notes latching, so they will keep playing when the key is released. :param polyphonic: If true, each note can be stopped individually by pressing the corresponding key again. Otherwise pressing a key will automatically turn off any previous notes. :param reset: a note (name/number) that acts as a reset key, stopping all currently playing notes. """ return (_m.Filter(_m.NOTE) % <|code_end|> , continue by predicting the next line. Consider current file imports: import mididings as _m import mididings.event as _event import mididings.util as _util from mididings.extra.per_channel import PerChannel as _PerChannel and context: # Path: mididings/extra/per_channel.py # class PerChannel(object): # """ # Utility class, usable with Process() and Call(), that delegates events # to different instances of the same class, using one instance per # channel/port combination. # New instances are created as needed, using the given factory function, # when the first event with a new channel/port arrives. # """ # def __init__(self, factory): # self.channel_proc = {} # self.factory = factory # # def __call__(self, ev): # k = (ev.port, ev.channel) # if k not in self.channel_proc: # self.channel_proc[k] = self.factory() # return self.channel_proc[k](ev) which might include code, classes, or functions. Output only the next line.
_m.Process(_PerChannel(
Using the snippet: <|code_start|> # run the same interpreter with the same arguments again _os.execl(_sys.executable, _sys.executable, *_sys.argv) def quit(self): self._quit.set() @_overload.mark( """ run(patch) run(scenes=..., control=None, pre=None, post=None) Start the MIDI processing. This is usually the last function called by a mididings script. The first version just runs a single patch, while the second version allows switching between multiple scenes. :param patch: a single patch. :param scenes: a dictionary with program numbers as keys, and :class:`Scene` objects, :class:`SceneGroup` objects or plain patches as values. :param control: an optional "control" patch, which is always active, and runs in parallel to the current scene. :param pre: an optional patch that allows common processing to take place before every scene. Does not affect the control patch. :param post: an optional patch that allows common processing to take place after every scene. Does not affect the control patch. """ ) <|code_end|> , determine the next line of code. You have imports: import _mididings import mididings.patch as _patch import mididings.scene as _scene import mididings.util as _util import mididings.misc as _misc import mididings.setup as _setup import mididings.constants as _constants import mididings.overload as _overload import mididings.arguments as _arguments import time as _time import weakref as _weakref import threading as _threading import gc as _gc import atexit as _atexit import os as _os import sys as _sys import smf from mididings.units.base import _UNIT_TYPES from mididings.scene import _SCENE_TYPES and context (class names, function names, or code) available: # Path: mididings/units/base.py # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/scene.py # _SCENE_TYPES = (Scene, SceneGroup) + _UNIT_TYPES . Output only the next line.
@_arguments.accept(_UNIT_TYPES)
Based on the snippet: <|code_start|> The first version just runs a single patch, while the second version allows switching between multiple scenes. :param patch: a single patch. :param scenes: a dictionary with program numbers as keys, and :class:`Scene` objects, :class:`SceneGroup` objects or plain patches as values. :param control: an optional "control" patch, which is always active, and runs in parallel to the current scene. :param pre: an optional patch that allows common processing to take place before every scene. Does not affect the control patch. :param post: an optional patch that allows common processing to take place after every scene. Does not affect the control patch. """ ) @_arguments.accept(_UNIT_TYPES) def run(patch): if (isinstance(patch, dict) and all(not isinstance(k, _constants._EventType) for k in patch.keys())): # bypass the overload mechanism (just this once...) if there's no way # the given dict could be accepted as a split run(scenes=patch) else: e = Engine() e.setup({_util.offset(0): patch}, None, None, None) e.run() @_overload.mark @_arguments.accept( <|code_end|> , predict the immediate next line with the help of imports: import _mididings import mididings.patch as _patch import mididings.scene as _scene import mididings.util as _util import mididings.misc as _misc import mididings.setup as _setup import mididings.constants as _constants import mididings.overload as _overload import mididings.arguments as _arguments import time as _time import weakref as _weakref import threading as _threading import gc as _gc import atexit as _atexit import os as _os import sys as _sys import smf from mididings.units.base import _UNIT_TYPES from mididings.scene import _SCENE_TYPES and context (classes, functions, sometimes code) from other files: # Path: mididings/units/base.py # _UNIT_TYPES = (_Unit, list, dict, _constants._EventType) # # Path: mididings/scene.py # _SCENE_TYPES = (Scene, SceneGroup) + _UNIT_TYPES . Output only the next line.
{_util.scene_number: _SCENE_TYPES},
Here is a snippet: <|code_start|> dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(dir + '/../..') class TestCapacities(unittest.TestCase): def test_tabular_eps_greedy(self): nb_states = 3 nb_actions = 2 with tf.Graph().as_default(): tf.set_random_seed(1) inputs_t = tf.random_uniform(shape=[2], minval=0, maxval=3, dtype=tf.int32) # inputs_t = tf.Print(inputs_t, data=[inputs_t], message='inputs_t') Qs = tf.random_uniform(shape=[nb_states, nb_actions]) # Qs = tf.Print(Qs, data=[Qs], message='Qs', summarize=12) q_preds = tf.gather(Qs, inputs_t) # q_preds = tf.Print(q_preds, data=[q_preds], message='q_preds', summarize=6) N0 = 100 <|code_end|> . Write the next line using the current file imports: import os, sys, unittest, timeit import numpy as np import tensorflow as tf from agents import capacities and context from other files: # Path: agents/capacities.py # def swish(x): # def eps_greedy(inputs_t, q_preds_t, nb_actions, N0, min_eps, nb_state=None): # def tabular_eps_greedy(inputs_t, q_preds_t, nb_states, nb_actions, N0, min_eps): # def tabular_UCB(Qs_t, inputs_t): # def eligibility_traces(Qs_t, states_t, actions_t, discount, lambda_value): # def eligibility_dutch_traces(Qs_t, states_t, actions_t, lr, discount, lambda_value): # def get_expected_rewards(episode_rewards, discount=.99): # def tf_get_n_step_expected_rewards(episode_rewards_t, estimates_t, discount, n_step): # def get_n_step_expected_rewards(episode_rewards, estimates, discount=.99, n_step=1): # def get_n_step_expected_rewards_mat(episode_rewards, estimates, discount=.99, n_step=1): # def get_lambda_expected_rewards(episode_rewards, estimates, discount=.99, lambda_value=.9): # def get_mc_target(rewards_t, discount): # def get_td_target(Qs_t, rewards_t, next_states_t, next_actions_t, discount): # def get_td_n_target(Qs_t, rewards_t, next_state_t, next_action_t, discount, n_step): # def get_q_learning_target(Qs_t, rewards_t, next_states_t, discount): # def get_expected_sarsa_target(Qs_t, rewards_t, next_states_t, next_probs_t, discount): # def get_sigma_target(Qs_t, sigma, rewards_t, next_states_t, next_actions_t, next_probs_t, discount): # def tabular_learning(Qs_t, states_t, actions_t, targets): # def tabular_learning_with_lr(init_lr, decay_steps, Qs_t, states_t, actions_t, targets): # def counter(name): # def fix_scope(from_scope): # def build_batches(dtKeys, sequence_history, batch_size): # def policy(network_params, inputs, summary_collections=None): # def value_f(network_params, inputs, summary_collections=None): # def predictive_model(network_params, m_inputs, dynamic_batch_size, m_initial_state=None, summary_collections=None): # def projection(proj_params, inputs, summary_collections=None): # N = tf.Variable(1., trainable=False, dtype=tf.float32, name='N') # N = tf.Variable(tf.ones(shape=[nb_state]), name='N', trainable=False) # W1 = tf.get_variable('W1' # , shape=[ network_params['nb_inputs'], network_params['nb_units'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W2 = tf.get_variable('W2' # , shape=[ network_params['nb_units'], network_params['nb_units'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W3 = tf.get_variable('W3' # , shape=[ network_params['nb_units'], network_params['nb_outputs'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W1 = tf.get_variable('W1' # , shape=[ network_params['nb_inputs'], network_params['nb_units'] ] # , initializer=w_init # ) # W2 = tf.get_variable('W2' # , shape=[ network_params['nb_units'], network_params['nb_units'] ] # , initializer=w_init # ) # W3 = tf.get_variable('W3' # , shape=[ network_params['nb_units'], network_params['nb_outputs'] ] # , initializer=w_init # ) # W1 = tf.get_variable('W1' # , shape=[ proj_params['nb_units'], proj_params['nb_units'] ] # , initializer=w_init # ) # W2 = tf.get_variable('W2' # , shape=[ proj_params['nb_units'], proj_params['nb_actions'] ] # , initializer=w_init # ) , which may include functions, classes, or code. Output only the next line.
actions, probs = capacities.tabular_eps_greedy(inputs_t, q_preds, nb_states, nb_actions, N0, 0.)
Here is a snippet: <|code_start|> def play(self, env, render=True): obs = env.reset() score = 0 done = False while True: if render: env.render() act, state = self.act(obs) next_obs, reward, done, info = env.step(act) score += reward obs = next_obs if done: break self.play_counter += 1 pscore_sum = self.sess.run(self.pscore_sum_t, feed_dict={ self.pscore_plh: score, }) self.sw.add_summary(pscore_sum, self.play_counter) return score class TabularBasicAgent(BasicAgent): """ Agent implementing tabular Q-learning. """ def __init__(self, config, env): if 'debug' in config: <|code_end|> . Write the next line using the current file imports: import json, os import tensorflow as tf from gym.spaces import Discrete, Box from utils import phis and context from other files: # Path: utils/phis.py # def CartPole0phi1(obs, done=False): # def CartPole0phi2(obs, done=False): # def MountainCar0phi(obs, done=False): # def Acrobot1phi(obs, done=False): # def getPhiConfig(env_name, debug=False): , which may include functions, classes, or code. Output only the next line.
config.update(phis.getPhiConfig(config['env_name'], config['debug']))
Next line prediction: <|code_start|> dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(dir + '/../..') class TestReplayBuffer(unittest.TestCase): def test_replay_buffer_init(self): templates = [('test1', tf.int32, ()), ('test2', tf.int32, (1,)), ('test3', tf.int32, (2, 2))] capacity = 2 <|code_end|> . Use current file imports: (import os, sys, unittest import numpy as np import tensorflow as tf from utils import replay_buffer) and context including class names, function names, or small code snippets from other files: # Path: utils/replay_buffer.py # class ReplayBuffer: # class PrioritizedReplayBuffer: # def __init__(self, templates, capacity): # def _create_buffers(self, templates): # def reset(self): # def size(self): # def append(self, tensors): # def sample(self, nb_samples): # def get_all_buffers(self): # def __init__(self, templates, capactiy): # def size(self): # def append(self, priority, tensors): # def sample(self, amount, temperature=1): . Output only the next line.
rep_buf = replay_buffer.ReplayBuffer(templates, capacity)
Given the code snippet: <|code_start|> random_config.update(fixed_params) return random_config def act(self, obs, done=False): state_id = self.phi(obs, done) act, estimate = self.sess.run([self.action_t, self.q_value_t], feed_dict={ self.inputs_plh: [ state_id ] }) return act, state_id, estimate def build_graph(self, graph): with graph.as_default(): tf.set_random_seed(self.random_seed) self.inputs_plh = tf.placeholder(tf.int32, shape=[None], name="inputs_plh") q_scope = tf.VariableScope(reuse=False, name='QValues') with tf.variable_scope(q_scope): self.Qs = tf.get_variable('Qs' , shape=[self.nb_state, self.action_space.n] , initializer=tf.constant_initializer(self.initial_q_value) , dtype=tf.float32 ) tf.summary.histogram('Qarray', self.Qs) self.q_preds_t = tf.gather(self.Qs, self.inputs_plh) policy_scope = tf.VariableScope(reuse=False, name='Policy') with tf.variable_scope(policy_scope): <|code_end|> , generate the next line using the imports in this file: import numpy as np import tensorflow as tf from agents import TabularBasicAgent, capacities and context (functions, classes, or occasionally code) from other files: # Path: agents/capacities.py # def swish(x): # def eps_greedy(inputs_t, q_preds_t, nb_actions, N0, min_eps, nb_state=None): # def tabular_eps_greedy(inputs_t, q_preds_t, nb_states, nb_actions, N0, min_eps): # def tabular_UCB(Qs_t, inputs_t): # def eligibility_traces(Qs_t, states_t, actions_t, discount, lambda_value): # def eligibility_dutch_traces(Qs_t, states_t, actions_t, lr, discount, lambda_value): # def get_expected_rewards(episode_rewards, discount=.99): # def tf_get_n_step_expected_rewards(episode_rewards_t, estimates_t, discount, n_step): # def get_n_step_expected_rewards(episode_rewards, estimates, discount=.99, n_step=1): # def get_n_step_expected_rewards_mat(episode_rewards, estimates, discount=.99, n_step=1): # def get_lambda_expected_rewards(episode_rewards, estimates, discount=.99, lambda_value=.9): # def get_mc_target(rewards_t, discount): # def get_td_target(Qs_t, rewards_t, next_states_t, next_actions_t, discount): # def get_td_n_target(Qs_t, rewards_t, next_state_t, next_action_t, discount, n_step): # def get_q_learning_target(Qs_t, rewards_t, next_states_t, discount): # def get_expected_sarsa_target(Qs_t, rewards_t, next_states_t, next_probs_t, discount): # def get_sigma_target(Qs_t, sigma, rewards_t, next_states_t, next_actions_t, next_probs_t, discount): # def tabular_learning(Qs_t, states_t, actions_t, targets): # def tabular_learning_with_lr(init_lr, decay_steps, Qs_t, states_t, actions_t, targets): # def counter(name): # def fix_scope(from_scope): # def build_batches(dtKeys, sequence_history, batch_size): # def policy(network_params, inputs, summary_collections=None): # def value_f(network_params, inputs, summary_collections=None): # def predictive_model(network_params, m_inputs, dynamic_batch_size, m_initial_state=None, summary_collections=None): # def projection(proj_params, inputs, summary_collections=None): # N = tf.Variable(1., trainable=False, dtype=tf.float32, name='N') # N = tf.Variable(tf.ones(shape=[nb_state]), name='N', trainable=False) # W1 = tf.get_variable('W1' # , shape=[ network_params['nb_inputs'], network_params['nb_units'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W2 = tf.get_variable('W2' # , shape=[ network_params['nb_units'], network_params['nb_units'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W3 = tf.get_variable('W3' # , shape=[ network_params['nb_units'], network_params['nb_outputs'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W1 = tf.get_variable('W1' # , shape=[ network_params['nb_inputs'], network_params['nb_units'] ] # , initializer=w_init # ) # W2 = tf.get_variable('W2' # , shape=[ network_params['nb_units'], network_params['nb_units'] ] # , initializer=w_init # ) # W3 = tf.get_variable('W3' # , shape=[ network_params['nb_units'], network_params['nb_outputs'] ] # , initializer=w_init # ) # W1 = tf.get_variable('W1' # , shape=[ proj_params['nb_units'], proj_params['nb_units'] ] # , initializer=w_init # ) # W2 = tf.get_variable('W2' # , shape=[ proj_params['nb_units'], proj_params['nb_actions'] ] # , initializer=w_init # ) # # Path: agents/basic_agent.py # class TabularBasicAgent(BasicAgent): # """ # Agent implementing tabular Q-learning. # """ # def __init__(self, config, env): # if 'debug' in config: # config.update(phis.getPhiConfig(config['env_name'], config['debug'])) # else: # config.update(phis.getPhiConfig(config['env_name'])) # super(TabularBasicAgent, self).__init__(config, env) . Output only the next line.
self.actions_t, self.probs_t = capacities.tabular_eps_greedy(
Predict the next line for this snippet: <|code_start|> 'lr': get_lr() , 'lr_decay_steps': get_lr_decay_steps() , 'discount': get_discount() , 'N0': get_N0() , 'min_eps': get_min_eps() , 'initial_q_value': get_initial_q_value() } random_config.update(fixed_params) return random_config def build_graph(self, graph): with graph.as_default(): tf.set_random_seed(self.random_seed) self.inputs_plh = tf.placeholder(tf.int32, shape=[None], name="inputs_plh") q_scope = tf.VariableScope(reuse=False, name='QValues') with tf.variable_scope(q_scope): self.Qs = tf.get_variable('Qs' , shape=[self.nb_state, self.action_space.n] , initializer=tf.constant_initializer(self.initial_q_value) , dtype=tf.float32 ) tf.summary.histogram('Qarray', self.Qs) self.q_preds_t = tf.gather(self.Qs, self.inputs_plh) policy_scope = tf.VariableScope(reuse=False, name='Policy') with tf.variable_scope(policy_scope): if 'UCB' in self.config and self.config['UCB']: <|code_end|> with the help of current file imports: import numpy as np import tensorflow as tf from agents import TabularBasicAgent, capacities and context from other files: # Path: agents/capacities.py # def swish(x): # def eps_greedy(inputs_t, q_preds_t, nb_actions, N0, min_eps, nb_state=None): # def tabular_eps_greedy(inputs_t, q_preds_t, nb_states, nb_actions, N0, min_eps): # def tabular_UCB(Qs_t, inputs_t): # def eligibility_traces(Qs_t, states_t, actions_t, discount, lambda_value): # def eligibility_dutch_traces(Qs_t, states_t, actions_t, lr, discount, lambda_value): # def get_expected_rewards(episode_rewards, discount=.99): # def tf_get_n_step_expected_rewards(episode_rewards_t, estimates_t, discount, n_step): # def get_n_step_expected_rewards(episode_rewards, estimates, discount=.99, n_step=1): # def get_n_step_expected_rewards_mat(episode_rewards, estimates, discount=.99, n_step=1): # def get_lambda_expected_rewards(episode_rewards, estimates, discount=.99, lambda_value=.9): # def get_mc_target(rewards_t, discount): # def get_td_target(Qs_t, rewards_t, next_states_t, next_actions_t, discount): # def get_td_n_target(Qs_t, rewards_t, next_state_t, next_action_t, discount, n_step): # def get_q_learning_target(Qs_t, rewards_t, next_states_t, discount): # def get_expected_sarsa_target(Qs_t, rewards_t, next_states_t, next_probs_t, discount): # def get_sigma_target(Qs_t, sigma, rewards_t, next_states_t, next_actions_t, next_probs_t, discount): # def tabular_learning(Qs_t, states_t, actions_t, targets): # def tabular_learning_with_lr(init_lr, decay_steps, Qs_t, states_t, actions_t, targets): # def counter(name): # def fix_scope(from_scope): # def build_batches(dtKeys, sequence_history, batch_size): # def policy(network_params, inputs, summary_collections=None): # def value_f(network_params, inputs, summary_collections=None): # def predictive_model(network_params, m_inputs, dynamic_batch_size, m_initial_state=None, summary_collections=None): # def projection(proj_params, inputs, summary_collections=None): # N = tf.Variable(1., trainable=False, dtype=tf.float32, name='N') # N = tf.Variable(tf.ones(shape=[nb_state]), name='N', trainable=False) # W1 = tf.get_variable('W1' # , shape=[ network_params['nb_inputs'], network_params['nb_units'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W2 = tf.get_variable('W2' # , shape=[ network_params['nb_units'], network_params['nb_units'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W3 = tf.get_variable('W3' # , shape=[ network_params['nb_units'], network_params['nb_outputs'] ] # , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev']) # ) # W1 = tf.get_variable('W1' # , shape=[ network_params['nb_inputs'], network_params['nb_units'] ] # , initializer=w_init # ) # W2 = tf.get_variable('W2' # , shape=[ network_params['nb_units'], network_params['nb_units'] ] # , initializer=w_init # ) # W3 = tf.get_variable('W3' # , shape=[ network_params['nb_units'], network_params['nb_outputs'] ] # , initializer=w_init # ) # W1 = tf.get_variable('W1' # , shape=[ proj_params['nb_units'], proj_params['nb_units'] ] # , initializer=w_init # ) # W2 = tf.get_variable('W2' # , shape=[ proj_params['nb_units'], proj_params['nb_actions'] ] # , initializer=w_init # ) # # Path: agents/basic_agent.py # class TabularBasicAgent(BasicAgent): # """ # Agent implementing tabular Q-learning. # """ # def __init__(self, config, env): # if 'debug' in config: # config.update(phis.getPhiConfig(config['env_name'], config['debug'])) # else: # config.update(phis.getPhiConfig(config['env_name'])) # super(TabularBasicAgent, self).__init__(config, env) , which may contain function names, class names, or code. Output only the next line.
self.actions_t, self.probs_t = capacities.tabular_UCB(