signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@cli.command()<EOL>@click.pass_obj<EOL>def distance(globs):
globs.locations.distance()<EOL>
Calculate distance between locations.
f12207:m4
@cli.command()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@click.pass_obj<EOL>def final_bearing(globs, string):
globs.locations.bearing('<STR_LIT>', string)<EOL>
Calculate final bearing between locations.
f12207:m5
@cli.command()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', default=<NUM_LIT:0>, type=float,<EOL>help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', type=click.Choice(['<STR_LIT:h>', '<STR_LIT:m>', '<STR_LIT:s>']),<EOL>help='<STR_LIT>')<EOL>@click.pass_obj<EOL>def flight_plan(globs, speed, time):
globs.locations.flight_plan(speed, time)<EOL>
Calculate flight plan for locations.
f12207:m6
@cli.command()<EOL>@click.argument('<STR_LIT>', type=float)<EOL>@click.pass_obj<EOL>def range(globs, distance):
globs.locations.range(distance)<EOL>
Check locations are within a given range.
f12207:m7
@cli.command()<EOL>@click.pass_obj<EOL>def sunrise(globs):
globs.locations.sun_events('<STR_LIT>')<EOL>
Calculate the sunrise time for locations.
f12207:m8
@cli.command()<EOL>@click.pass_obj<EOL>def sunset(globs):
globs.locations.sun_events('<STR_LIT>')<EOL>
Calculate the sunset time for locations.
f12207:m9
def read_locations(filename):
data = ConfigParser()<EOL>if filename == '<STR_LIT:->':<EOL><INDENT>data.read_file(sys.stdin)<EOL><DEDENT>else:<EOL><INDENT>data.read(filename)<EOL><DEDENT>if not data.sections():<EOL><INDENT>logging.debug('<STR_LIT>')<EOL><DEDENT>locations = {}<EOL>for name in data.sections():<EOL><INDENT>if data.has_option(name, '<ST...
Pull locations from a user's config file. Args: filename (str): Config file to parse Returns: dict: List of locations from config file
f12207:m10
def read_csv(filename):
field_names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT:name>')<EOL>data = utils.prepare_csv_read(filename, field_names, skipinitialspace=True)<EOL>locations = {}<EOL>args = []<EOL>for index, row in enumerate(data, <NUM_LIT:1>):<EOL><INDENT>name = '<STR_LIT>' % (index, row['<STR_LIT:name>'])<EOL>locations[name] = (row['<STR...
Pull locations from a user's CSV file. Read gpsbabel_'s CSV output format .. _gpsbabel: http://www.gpsbabel.org/ Args: filename (str): CSV file to parse Returns: tuple of dict and list: List of locations as ``str`` objects
f12207:m11
def main():
logging.basicConfig(format='<STR_LIT>')<EOL>try:<EOL><INDENT>cli()<EOL>return <NUM_LIT:0><EOL><DEDENT>except LocationsError as error:<EOL><INDENT>print(error)<EOL>return <NUM_LIT:2><EOL><DEDENT>except RuntimeError as error:<EOL><INDENT>print(error)<EOL>return <NUM_LIT:255><EOL><DEDENT>except OSError as error:<EOL><INDE...
Main script handler. Returns: int: 0 for success, >1 error code
f12207:m12
def __init__(self, function=None, data=None):
super(LocationsError, self).__init__()<EOL>self.function = function<EOL>self.data = data<EOL>
Initialise a new ``LocationsError`` object. Args: function (str): Function where error is raised data (tuple): Location number and data
f12207:c0:m0
def __str__(self):
if self.function:<EOL><INDENT>return '<STR_LIT>' % self.function<EOL><DEDENT>elif self.data:<EOL><INDENT>return '<STR_LIT>' % self.data<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Pretty printed error string. Returns: str: Human readable error string
f12207:c0:m1
def __init__(self, latitude, longitude, name, units='<STR_LIT>'):
super(NumberedPoint, self).__init__(latitude, longitude, units)<EOL>self.name = name<EOL>
Initialise a new ``NumberedPoint`` object. Args: latitude (float): Location's latitude longitude (float): Location's longitude name (str): Location's name or command line position units (str): Unit type to be used for distances
f12207:c1:m0
def __format__(self, format_spec='<STR_LIT>'):
return super(NumberedPoint, self).__format__('<STR_LIT>')<EOL>
Extended pretty printing for location strings. Args: format_spec (str): Coordinate formatting system to use Returns: str: Human readable string representation of ``NumberedPoint`` object Raises: ValueError: Unknown value for ``format_spec``
f12207:c1:m1
def __init__(self, locations=None, format='<STR_LIT>', verbose=True,<EOL>config_locations=None, units='<STR_LIT>'):
super(NumberedPoints, self).__init__()<EOL>self.format = format<EOL>self.verbose = verbose<EOL>self._config_locations = config_locations<EOL>self.units = units<EOL>if locations:<EOL><INDENT>self.import_locations(locations, config_locations)<EOL><DEDENT>
Initialise a new ``NumberedPoints`` object. Args: locations (list of str): Location identifiers format (str): Coordinate formatting system to use verbose (bool): Whether to generate verbose output config_locations (dict): Locations imported from user's config ...
f12207:c2:m0
def __repr__(self):
return utils.repr_assist(self, {'<STR_LIT>': self[:]})<EOL>
Self-documenting string representation. Returns: str: String to recreate ``NumberedPoints`` object
f12207:c2:m1
def import_locations(self, locations, config_locations):
for number, location in enumerate(locations):<EOL><INDENT>if config_locations and location in config_locations:<EOL><INDENT>latitude, longitude = config_locations[location]<EOL>self.append(NumberedPoint(latitude, longitude, location,<EOL>self.units))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>data = utils.parse_loc...
Import locations from arguments. Args: locations (list of str): Location identifiers config_locations (dict): Locations imported from user's config file
f12207:c2:m2
def display(self, locator):
for location in self:<EOL><INDENT>if locator:<EOL><INDENT>output = location.to_grid_locator(locator)<EOL><DEDENT>else:<EOL><INDENT>output = format(location, self.format)<EOL><DEDENT>if self.verbose:<EOL><INDENT>click.echo('<STR_LIT>' % (location.name, output))<EOL><DEDENT>else:<EOL><INDENT>click.echo(output)<EOL><DEDEN...
Pretty print locations. Args: locator (str): Accuracy of Maidenhead locator output
f12207:c2:m3
def distance(self):
distances = list(super(NumberedPoints, self).distance())<EOL>leg_msg = ['<STR_LIT>', ]<EOL>total_msg = ['<STR_LIT>', ]<EOL>if self.units == '<STR_LIT>':<EOL><INDENT>leg_msg.append('<STR_LIT>')<EOL>total_msg.append('<STR_LIT>')<EOL><DEDENT>elif self.units == '<STR_LIT>':<EOL><INDENT>leg_msg.append('<STR_LIT>')<EOL>total...
Calculate distances between locations.
f12207:c2:m4
def bearing(self, mode, string):
bearings = getattr(super(NumberedPoints, self), mode)()<EOL>if string:<EOL><INDENT>bearings = map(utils.angle_to_name, bearings)<EOL><DEDENT>else:<EOL><INDENT>bearings = ['<STR_LIT>' % bearing for bearing in bearings]<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>verbose_fmt = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDEN...
Calculate bearing/final bearing between locations. Args: mode (str): Type of bearing to calculate string (bool): Use named directions
f12207:c2:m5
def range(self, distance):
test_location = self[<NUM_LIT:0>]<EOL>for location in self[<NUM_LIT:1>:]:<EOL><INDENT>in_range = test_location.__eq__(location, distance)<EOL>if self.verbose:<EOL><INDENT>text = ['<STR_LIT>', ]<EOL>if not in_range:<EOL><INDENT>text.append('<STR_LIT>')<EOL><DEDENT>text.append('<STR_LIT>')<EOL>if self.units == '<STR_LIT>...
Test whether locations are within a given range of the first. Args: distance (float): Distance to test location is within
f12207:c2:m6
def destination(self, distance, bearing, locator):
destinations = super(NumberedPoints, self).destination(bearing,<EOL>distance)<EOL>for location, destination in zip(self, destinations):<EOL><INDENT>if locator:<EOL><INDENT>output = destination.to_grid_locator(locator)<EOL><DEDENT>else:<EOL><INDENT>output = format(location, self.format)<EOL><DEDENT>if self.verbose:<EOL>...
Calculate destination locations for given distance and bearings. Args: distance (float): Distance to travel bearing (float): Direction of travel locator (str): Accuracy of Maidenhead locator output
f12207:c2:m7
def sun_events(self, mode):
mode_str = mode.capitalize()<EOL>times = getattr(super(NumberedPoints, self), mode)()<EOL>for location, time in zip(self, times):<EOL><INDENT>if self.verbose:<EOL><INDENT>if time:<EOL><INDENT>click.echo('<STR_LIT>'<EOL>% (mode_str, time, location.name))<EOL><DEDENT>else:<EOL><INDENT>click.echo("<STR_LIT>"<EOL>% (mode_s...
Calculate sunrise/sunset times for locations. Args: mode (str): Sun event to display
f12207:c2:m8
def flight_plan(self, speed, time):
if len(self) == <NUM_LIT:1>:<EOL><INDENT>raise LocationsError('<STR_LIT>')<EOL><DEDENT>if self.verbose:<EOL><INDENT>click.echo('<STR_LIT>'<EOL>'<STR_LIT>' % (self.units, time))<EOL><DEDENT>legs = [(<NUM_LIT:0>, <NUM_LIT:0>), ] + list(self.inverse())<EOL>for leg, loc in zip(legs, self):<EOL><INDENT>if leg == (<NUM_LIT:0...
Output the flight plan corresponding to the given locations. .. todo:: Description Args: speed (float): Speed to use for elapsed time calculation time (str): Time unit to use for output
f12207:c2:m9
def _gen_header(self, sequence, payloadtype):
protocol = bytearray.fromhex("<STR_LIT>")<EOL>source = bytearray.fromhex("<STR_LIT>")<EOL>target = bytearray.fromhex("<STR_LIT>")<EOL>reserved1 = bytearray.fromhex("<STR_LIT>")<EOL>sequence = pack("<STR_LIT>", sequence)<EOL>ack = pack("<STR_LIT>", <NUM_LIT:3>)<EOL>reserved2 = bytearray.fromhex("<STR_LIT>")<EOL>packet_t...
Create packet header.
f12209:c2:m1
def _gen_packet(self, sequence, payloadtype, payload=None):
contents = self._gen_header(sequence, payloadtype)<EOL>if payload:<EOL><INDENT>contents.extend(payload)<EOL><DEDENT>size = pack("<STR_LIT>", len(contents) + <NUM_LIT:2>)<EOL>packet = bytearray(size)<EOL>packet.extend(contents)<EOL>return packet<EOL>
Generate packet header.
f12209:c2:m2
def _gen_packet_setcolor(self, sequence, hue, sat, bri, kel, fade):
hue = min(max(hue, HUE_MIN), HUE_MAX)<EOL>sat = min(max(sat, SATURATION_MIN), SATURATION_MAX)<EOL>bri = min(max(bri, BRIGHTNESS_MIN), BRIGHTNESS_MAX)<EOL>kel = min(max(kel, TEMP_MIN), TEMP_MAX)<EOL>reserved1 = pack("<STR_LIT>", <NUM_LIT:0>)<EOL>hue = pack("<STR_LIT>", hue)<EOL>saturation = pack("<STR_LIT>", sat)<EOL>br...
Generate "setcolor" packet payload.
f12209:c2:m3
def _gen_packet_get(self, sequence):
<EOL>return self._gen_packet(sequence, PayloadType.GET)<EOL>
Generate "get" packet payload.
f12209:c2:m4
def _gen_packet_setpower(self, sequence, power, fade):
level = pack("<STR_LIT>", Power.BULB_OFF if power == <NUM_LIT:0> else Power.BULB_ON)<EOL>duration = pack("<STR_LIT>", fade)<EOL>payload = bytearray(level)<EOL>payload.extend(duration)<EOL>return self._gen_packet(sequence, PayloadType.SETPOWER2, payload)<EOL>
Generate "setpower" packet payload.
f12209:c2:m5
def _packet_ack(self, packet, sequence):
if packet["<STR_LIT>"] == sequence:<EOL><INDENT>if packet["<STR_LIT>"] == PayloadType.SETCOLOR:<EOL><INDENT>self._color_callback(packet["<STR_LIT:target>"],<EOL>packet["<STR_LIT>"],<EOL>packet["<STR_LIT>"],<EOL>packet["<STR_LIT>"],<EOL>packet["<STR_LIT>"])<EOL><DEDENT>elif packet["<STR_LIT>"] == PayloadType.SETPOWER2:<...
Check packet for ack.
f12209:c2:m6
def _process_packet(self, sequence):
if self._packets:<EOL><INDENT>with self._packet_lock:<EOL><INDENT>self._packets[:] = [packet for packet in self._packets<EOL>if self._packet_ack(packet, sequence)]<EOL><DEDENT><DEDENT>
Check packet list for acks.
f12209:c2:m7
def _packet_timeout(self, packet, now):
if now >= packet["<STR_LIT>"]:<EOL><INDENT>return False<EOL><DEDENT>if now >= packet["<STR_LIT>"]:<EOL><INDENT>self._send_command(packet)<EOL>return False<EOL><DEDENT>return True<EOL>
Check packet for timeout.
f12209:c2:m8
def _packet_manager(self):
while True:<EOL><INDENT>if self._packets:<EOL><INDENT>with self._packet_lock:<EOL><INDENT>now = time.time()<EOL>self._packets[:] =[packet for packet in self._packets<EOL>if self._packet_timeout(packet, now)]<EOL><DEDENT><DEDENT>time.sleep(ACK_RESEND / <NUM_LIT:2>)<EOL><DEDENT>
Watch packet list for timeouts.
f12209:c2:m9
def _packet_listener(self):
while True:<EOL><INDENT>datastream, source = self._sock.recvfrom(BUFFERSIZE)<EOL>ipaddr, port = source<EOL>try:<EOL><INDENT>sio = io.BytesIO(datastream)<EOL>dummy1, sec_part = struct.unpack("<STR_LIT>",<EOL>sio.read(<NUM_LIT:4>))<EOL>protocol = sec_part % <NUM_LIT><EOL>if protocol == <NUM_LIT>:<EOL><INDENT>source, dumm...
Packet listener.
f12209:c2:m10
def _send_command(self, cmd):
self._queue.put(cmd)<EOL>
Add to command queue.
f12209:c2:m11
def _command_sender(self):
sequence = -<NUM_LIT:1><EOL>while True:<EOL><INDENT>cmd = self._queue.get()<EOL>ipaddr = cmd["<STR_LIT:target>"]<EOL>payloadtype = cmd["<STR_LIT>"]<EOL>if "<STR_LIT>" not in cmd:<EOL><INDENT>sequence = (sequence + <NUM_LIT:1>) % SEQUENCE_COUNT<EOL>cmd["<STR_LIT>"] = sequence + SEQUENCE_BASE<EOL><DEDENT>packet = None<EO...
Command sender.
f12209:c2:m12
def probe(self, ipaddr=None):
if ipaddr is None:<EOL><INDENT>ipaddr = self._broadcast_addr<EOL><DEDENT>cmd = {"<STR_LIT>": PayloadType.GET,<EOL>"<STR_LIT:target>": ipaddr}<EOL>self._send_command(cmd)<EOL>
Probe given address for bulb.
f12209:c2:m13
def set_power(self, ipaddr, power, fade):
cmd = {"<STR_LIT>": PayloadType.SETPOWER2,<EOL>"<STR_LIT:target>": ipaddr,<EOL>"<STR_LIT>": power,<EOL>"<STR_LIT>": fade}<EOL>self._send_command(cmd)<EOL>
Send SETPOWER message.
f12209:c2:m14
def set_color(self, ipaddr, hue, sat, bri, kel, fade):
cmd = {"<STR_LIT>": PayloadType.SETCOLOR,<EOL>"<STR_LIT:target>": ipaddr,<EOL>"<STR_LIT>": hue,<EOL>"<STR_LIT>": sat,<EOL>"<STR_LIT>": bri,<EOL>"<STR_LIT>": kel,<EOL>"<STR_LIT>": fade}<EOL>self._send_command(cmd)<EOL>
Send SETCOLOR message.
f12209:c2:m15
def __int__(self):
return self.value<EOL>
Enum
f12213:c1:m0
def __init__(self):
'''<STR_LIT>'''<EOL>self.ErrorID = <NUM_LIT:0><EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.ErrorMsg = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>
Constructor
f12215:c0:m0
def __init__(self):
'''<STR_LIT>'''<EOL>self.OrderID = "<STR_LIT>"<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.InstrumentID = "<STR_LIT>"<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.Direction = DirectType.Buy<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.Offset = OffsetType.Open<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>sel...
initionalize
f12215:c1:m0
def __init__(self):
'''<STR_LIT>'''<EOL>self.TradeID = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>self.InstrumentID = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>self.ExchangeID = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>self.Direction = DirectType.Buy<EOL>'''<STR_LIT>'''<EOL>self.Offset = OffsetType.Open<EOL>'''<STR_LIT>'''<EOL>self.Price = <NUM_LIT:0.0><EO...
Constructor
f12215:c2:m0
def __init__(self):
'''<STR_LIT>'''<EOL>self.InstrumentID = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.ProductID = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.ExchangeID = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.VolumeMultiple = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL...
Constructor
f12215:c3:m0
def __init__(self):
'''<STR_LIT>'''<EOL>self.PreBalance = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>self.PositionProfit = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>self.CloseProfit = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>self.Commission = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>self.CurrMargin = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>self.FrozenCash...
Constructor
f12215:c4:m0
def __init__(self):
'''<STR_LIT>'''<EOL>self.InstrumentID = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>self.Direction = DirectType.Buy<EOL>'''<STR_LIT>'''<EOL>self.Price = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>self.Position = <NUM_LIT:1><EOL>'''<STR_LIT>'''<EOL>self.YdPosition = <NUM_LIT:0><EOL>'''<STR_LIT>'''<EOL>self.TdPosition = <NUM_LIT:0><E...
Constructor
f12215:c5:m0
def __init__(self):
'''<STR_LIT>'''<EOL>self.Instrument = '<STR_LIT>'<EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.LastPrice = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.AskPrice = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>self.BidPrice = <NUM_LIT:0.0><EOL>'''<STR_LIT>'''<EOL>'''<STR_LIT>'''<EOL>sel...
初始化
f12215:c7:m0
def ReqConnect(self, pAddress: str):
self.q.CreateApi()<EOL>spi = self.q.CreateSpi()<EOL>self.q.RegisterSpi(spi)<EOL>self.q.OnFrontConnected = self._OnFrontConnected<EOL>self.q.OnFrontDisconnected = self._OnFrontDisConnected<EOL>self.q.OnRspUserLogin = self._OnRspUserLogin<EOL>self.q.OnRtnDepthMarketData = self._OnRtnDepthMarketData<EOL>self.q.OnRspSubMar...
连接行情前置 :param pAddress:
f12216:c0:m1
def ReqUserLogin(self, user: str, pwd: str, broker: str):
self.q.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd)<EOL>
登录 :param user: :param pwd: :param broker:
f12216:c0:m2
def ReqSubscribeMarketData(self, pInstrument: str):
self.q.SubscribeMarketData(pInstrument)<EOL>
订阅合约行情 :param pInstrument:
f12216:c0:m3
def ReqUserLogout(self):
self.q.Release()<EOL>self.inst_tick.clear()<EOL>self.logined = False<EOL>threading.Thread(target=self.OnDisConnected, args=(self, <NUM_LIT:0>)).start()<EOL>
退出接口(正常退出,不会触发OnFrontDisconnected)
f12216:c0:m4
def _qry(self):
<EOL>ord_cnt = <NUM_LIT:0><EOL>trd_cnt = <NUM_LIT:0><EOL>while True:<EOL><INDENT>time.sleep(<NUM_LIT:0.5>)<EOL>if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt:<EOL><INDENT>break<EOL><DEDENT>ord_cnt = len(self.orders)<EOL>trd_cnt = len(self.trades)<EOL><DEDENT>self.t.ReqQryInstrument()<EOL>time.sleep(<NUM...
查询帐号相关信息
f12217:c0:m7
def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool):
if pInvestorPositionDetail.getInstrumentID() == '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>detail = PositionDetail()<EOL>detail.Instrument = pInvestorPositionDetail.getInstrumentID()<EOL>detail.CloseProfit = pInvestorPositionDetail.getCloseProfitByTrade()<EOL>detail.Direction = DirectType.Buy if pInvestorPositionDetai...
持仓明细
f12217:c0:m11
def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField):
msg = pTradingNoticeInfo.getFieldContent()<EOL>if len(msg) > <NUM_LIT:0>:<EOL><INDENT>threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start()<EOL><DEDENT>
交易提醒
f12217:c0:m19
def ReqConnect(self, front: str):
self.t.CreateApi()<EOL>spi = self.t.CreateSpi()<EOL>self.t.RegisterSpi(spi)<EOL>self.t.OnFrontConnected = self._OnFrontConnected<EOL>self.t.OnRspUserLogin = self._OnRspUserLogin<EOL>self.t.OnFrontDisconnected = self._OnFrontDisconnected<EOL>self.t.OnRspSettlementInfoConfirm = self._OnRspSettlementInfoConfirm<EOL>self.t...
连接交易前置 :param front:
f12217:c0:m23
def ReqUserLogin(self, user: str, pwd: str, broker: str):
self.broker = broker<EOL>self.investor = user<EOL>self.password = pwd<EOL>self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd)<EOL>
登录 :param user: :param pwd: :param broker:
f12217:c0:m24
def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = <NUM_LIT:0.0>, pVolume: int = <NUM_LIT:1>, pType: OrderType = OrderType.Limit, pCustom: int = <NUM_LIT:0>):
OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice<EOL>TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC<EOL>LimitPrice = <NUM_LIT:0.0><EOL>VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV<EOL>if pType == OrderType.Market: <EOL><INDENT>OrderPriceType = TThostFtdcOrderPric...
委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return:
f12217:c0:m25
def ReqOrderAction(self, OrderID: str):
of = self.orders[OrderID]<EOL>if not of:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>pOrderId = of.OrderID<EOL>return self.t.ReqOrderAction(<EOL>self.broker,<EOL>self.investor,<EOL>OrderRef=pOrderId.split('<STR_LIT:|>')[<NUM_LIT:2>],<EOL>FrontID=int(pOrderId.split('<STR_LIT:|>')[<NUM_LIT:1>]),<EOL>Ses...
撤单 :param OrderID:
f12217:c0:m26
def ReqUserLogout(self):
self.logined = False<EOL>time.sleep(<NUM_LIT:3>)<EOL>self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor)<EOL>self.t.RegisterSpi(None)<EOL>self.t.Release()<EOL>threading.Thread(target=self.OnDisConnected, args=(self, <NUM_LIT:0>)).start()<EOL>
退出接口
f12217:c0:m27
def OnConnected(self, obj):
print('<STR_LIT>'.format('<STR_LIT>'))<EOL>
接口连接 :param obj:
f12217:c0:m28
def OnDisConnected(self, obj, reason: int):
print('<STR_LIT>'.format(reason))<EOL>
接口断开 :param obj: :param reason:
f12217:c0:m29
def OnUserLogin(self, obj, info: InfoField):
print('<STR_LIT>'.format(info))<EOL>
登录响应 :param obj: :param info:
f12217:c0:m30
def OnOrder(self, obj, f: OrderField):
print('<STR_LIT>'.format(f.__dict__))<EOL>
委托响应 :param obj: :param f:
f12217:c0:m31
def OnTrade(self, obj, f: TradeField):
print('<STR_LIT>'.format(f.__dict__))<EOL>
成交响应 :param obj: :param f:
f12217:c0:m32
def OnCancel(self, obj, f: OrderField):
print('<STR_LIT>'.format(f.__dict__))<EOL>
撤单响应 :param self: :param obj: :param f:OrderField:
f12217:c0:m33
def OnErrCancel(self, obj, f: OrderField, info: InfoField):
print('<STR_LIT>'.format(f.__dict__))<EOL>print(info)<EOL>
撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField:
f12217:c0:m34
def OnErrOrder(self, obj, f: OrderField, info: InfoField):
print('<STR_LIT>'.format(f.__dict__))<EOL>print(info)<EOL>
委托错误 :param self: :param obj: :param f:OrderField: :param info:InfoField:
f12217:c0:m35
def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus):
print('<STR_LIT>'.format(inst, str(status).strip().split('<STR_LIT:.>')[-<NUM_LIT:1>]))<EOL>
交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus:
f12217:c0:m36
def OnRtnNotice(self, obj, time: str, msg: str):
print(f'<STR_LIT>')<EOL>
交易提醒 :param obj: :param time: :param msg: :return:
f12217:c0:m37
def OnRtnQuote(self, obj, quote: CThostFtdcQuoteField):
print('<STR_LIT>'.format(quote.__dict__))<EOL>
报价通知 :param obj: :param quote: :return:
f12217:c0:m38
def OnErrRtnQuote(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField):
print('<STR_LIT>'.format(quote.__dict__))<EOL>print(info)<EOL>
:param obj: :param quote: :return:
f12217:c0:m39
def OnErrRtnForQuoteInsert(self, obj, quote: CThostFtdcInputQuoteField, info: InfoField):
print('<STR_LIT>'.format(quote.__dict__))<EOL>print(info)<EOL>
询价录入错误回报 :param obj: :param quote: :return:
f12217:c0:m40
def process_line(self, idx, line):
if '<STR_LIT>' in line: <EOL><INDENT>py_line = '<STR_LIT:#>' + line[<NUM_LIT:3>:]<EOL>if py_line.find('<STR_LIT>') > <NUM_LIT:0>:<EOL><INDENT>self.enum_comment[py_line[py_line.find('<STR_LIT>'):py_line.find('<STR_LIT>')]] = '<STR_LIT>' % py_line[py_line.find('<STR_LIT>') + <NUM_LIT:3>:-<NUM_LIT:1>]<EOL><DEDENT>else:<E...
处理每行
f12219:c0:m1
def process_typedef(self, line):
content = line.split('<STR_LIT:U+0020>')<EOL>type_ = self.type_dict[content[<NUM_LIT:1>]]<EOL>if type_ == '<STR_LIT>' and '<STR_LIT:[>' in line:<EOL><INDENT>type_ = '<STR_LIT>' % (type_, line[line.index('<STR_LIT:[>') + <NUM_LIT:1>:line.index('<STR_LIT:]>')])<EOL><DEDENT>keyword = content[<NUM_LIT:2>]<EOL>if '<STR_LIT:...
处理类型申明
f12219:c0:m2
def run(self):
<EOL>self.fenum.write('<STR_LIT:\n>')<EOL>self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), '<STR_LIT>'), '<STR_LIT:r>')<EOL>for idx, line in enumerate(self.fcpp):<EOL><INDENT>l = self.process_line(idx, line)<EOL>self.f_data_type.write(l)<EOL><DEDENT>self.fcpp.close()<EOL>self.f_data_type.close()<EOL>self.fe...
主函数
f12219:c0:m3
def run(self):
fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), '<STR_LIT>'), '<STR_LIT:r>')<EOL>fpy = open(os.path.join(self.out_path, '<STR_LIT>'), '<STR_LIT:w>', encoding='<STR_LIT:utf-8>')<EOL>fpy.write('<STR_LIT:\n>')<EOL>fpy.write('<STR_LIT>')<EOL>fpy.write('<STR_LIT:\n>')<EOL>py_str = '<STR_LIT>'<EOL>py_str_idx = <NUM_L...
主函数
f12220:c0:m1
def read(*paths):
basedir = os.path.dirname(__file__)<EOL>fullpath = os.path.join(basedir, *paths)<EOL>contents = io.open(fullpath, encoding='<STR_LIT:utf-8>').read().strip()<EOL>return contents<EOL>
Read a text file.
f12231:m0
@cli.command()<EOL>@click.argument('<STR_LIT>', default='<STR_LIT>')<EOL>def init(arg):
answers = {'<STR_LIT:a>': <NUM_LIT:1>}<EOL>if arg == '<STR_LIT>':<EOL><INDENT>input("""<STR_LIT>""")<EOL><DEDENT>elif arg == '<STR_LIT>':<EOL><INDENT>raise NotImplementedError()<EOL><DEDENT>else:<EOL><INDENT>url = arg<EOL>answers = dict(<EOL>input='<STR_LIT>',<EOL>title=os.path.basename(url),<EOL>input_url=url,<EOL>pro...
Bootstrap a processing pipeline script. ARG is either a path or a URL for some data to read from, 'hello-world' for a full working code example, or leave empty for an interactive walkthrough.
f12240:m10
@classmethod<EOL><INDENT>def from_block(cls, block):<DEDENT>
rseqs = cma.realign_seqs(block)<EOL>records = (SeqRecord(Seq(rseq, extended_protein),<EOL>id=bseq['<STR_LIT:id>'],<EOL>description=bseq['<STR_LIT:description>'],<EOL>dbxrefs=bseq['<STR_LIT>'].values(), <EOL>annotations=dict(<EOL>index=bseq['<STR_LIT:index>'],<EOL>length=bseq['<STR_LIT>'],<EOL>dbxrefs=bseq['<STR_LIT>'...
Instantiate this class given a raw block (see parse_raw).
f12279:c0:m1
def find_seq_rec(block, name, case_sensitive=True):
if case_sensitive:<EOL><INDENT>def test(name, rec):<EOL><INDENT>return name in rec['<STR_LIT:id>']<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def test(name, rec):<EOL><INDENT>return name.upper() in rec['<STR_LIT:id>'].upper()<EOL><DEDENT><DEDENT>for rec in block['<STR_LIT>']:<EOL><INDENT>if test(name, rec):<EOL><INDENT>retu...
Given part of a sequence ID, find the first matching record.
f12280:m0
def find_seq_id(block, name, case_sensitive=True):
<EOL>rec = find_seq_rec(block, name, case_sensitive)<EOL>return rec['<STR_LIT:id>']<EOL>
Given part of a sequence ID, find the first actual ID that contains it. Example:: >>> find_seq_id(block, '2QG5') 'gi|158430190|pdb|2QG5|A' Raise a ValueError if no matching key is found.
f12280:m1
def get_consensus(block):
from collections import Counter<EOL>columns = zip(*[[c for c in row['<STR_LIT>'] if not c.islower()]<EOL>for row in block['<STR_LIT>']])<EOL>cons_chars = [Counter(col).most_common()[<NUM_LIT:0>][<NUM_LIT:0>] for col in columns]<EOL>cons_chars = [c if c != '<STR_LIT:->' else '<STR_LIT:X>' for c in cons_chars]<EOL>assert...
Calculate a simple consensus sequence for the block.
f12280:m2
def get_conservation(block):
consensus = block['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']<EOL>assert all(c.isupper() for c in consensus),"<STR_LIT>"<EOL>cleaned = [[c for c in s['<STR_LIT>'] if not c.islower()]<EOL>for s in block['<STR_LIT>'][<NUM_LIT:1>:]]<EOL>height = float(len(cleaned))<EOL>for row in cleaned:<EOL><INDENT>if len(row) != len(consens...
Calculate conservation levels at each consensus position. Return a dict of {position: float conservation}
f12280:m3
def get_equivalent_positions(block):
consensus = block['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']<EOL>rest = block['<STR_LIT>'][<NUM_LIT:1>:]<EOL>if '<STR_LIT:->' in consensus or '<STR_LIT:.>' in consensus:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>seen = set()<EOL>dupes = set()<EOL>for rec in rest:<EOL><INDENT>if rec['<STR_LIT:id>'] in seen:<EOL>...
Create a mapping of equivalent residue positions to consensus. Build a dict-of-dicts:: {consensus-posn: {id: equiv-posn, id: equiv-posn, ...}, ...} The first sequence in the alignment is assumed to be the (gapless) consensus sequence.
f12280:m4
def get_inserts(block):
def find_inserts(seq, head_len):<EOL><INDENT>"""<STR_LIT>"""<EOL>in_insert = False<EOL>curr_start = None<EOL>deletions = <NUM_LIT:0><EOL>for idx, is_lower in enumerate(map(str.islower, seq)):<EOL><INDENT>if is_lower:<EOL><INDENT>if not in_insert:<EOL><INDENT>curr_start = head_len + idx + <NUM_LIT:1> - deletions<EOL>in_...
Identify the inserts in sequence in a block. Inserts are relative to the consensus (theoretically), and identified by lowercase letters in the sequence. The returned integer pairs represent the insert start and end positions in the full-length sequence, using one-based numbering. The first sequenc...
f12280:m5
def number_letters(block_or_record, key=None):
if key:<EOL><INDENT>logging.warn("<STR_LIT>")<EOL>assert '<STR_LIT>' in block_or_record, "<STR_LIT>"<EOL>record = find_seq_rec(block_or_record, key)<EOL><DEDENT>else:<EOL><INDENT>assert '<STR_LIT:id>' in block_or_record, "<STR_LIT>"<EOL>record = block_or_record<EOL><DEDENT>seq = record['<STR_LIT>'].replace('<STR_LIT:->...
Return a dict of {posn: restype} for each letter in the sequence.
f12280:m6
def _parse_blocks(instream):
ilines = sugar.unblank(instream)<EOL>for line in ilines:<EOL><INDENT>if line.startswith('<STR_LIT:[>'):<EOL><INDENT>level, one, name, seqcount, params = _parse_block_header(line)<EOL>qlen, qchars = _parse_block_postheader(next(ilines))<EOL>sequences = list(_parse_sequences(ilines, qlen))<EOL>if not len(sequences) == se...
Parse an alignment block from the given file handle. Block looks like: [0_(1)=fa2cma(8){go=10000,gx=2000,pn=1000.0,lf=0,rf=0}: (209)***********************************************... ... sequences, numbered 1-8 ... _0].
f12281:m1
def _parse_sequences(ilines, expect_qlen):
while True:<EOL><INDENT>first = next(ilines)<EOL>if first.startswith('<STR_LIT:_>') and first.endswith('<STR_LIT>'):<EOL><INDENT>break<EOL><DEDENT>try:<EOL><INDENT>index, this_len, query_len = _parse_seq_preheader(first)<EOL><DEDENT>except ValueError:<EOL><INDENT>logging.warn('<STR_LIT>', first)<EOL>continue<EOL><DEDEN...
Parse the sequences in the current block. Sequence looks like: $3=227(209): >gi|15606894|ref|NP_214275.1| {|2(244)|<Aquificae(B)>}DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|2984127|gb|AAC07663.1| DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|75 {()YVPFARKYRPKFFREVIGQEAP...
f12281:m2
def _parse_block_header(line):
level = line[<NUM_LIT:1>]<EOL>one, _rest = line[<NUM_LIT:4>:].split('<STR_LIT>', <NUM_LIT:1>)<EOL>name, _rest = _rest.split('<STR_LIT:(>', <NUM_LIT:1>)<EOL>seqcount, _rest = _rest.split('<STR_LIT:)>', <NUM_LIT:1>)<EOL>params = _rest.strip('<STR_LIT>')<EOL>return int(level), int(one), name, int(seqcount), params<EOL>
[0_(1)=fa2cma(8){go=10000,gx=2000,pn=1000.0,lf=0,rf=0}:
f12281:m3
def _parse_block_postheader(line):
parts = line[<NUM_LIT:1>:].split('<STR_LIT:)>', <NUM_LIT:1>)<EOL>qlen = int(parts[<NUM_LIT:0>])<EOL>if not len(parts[<NUM_LIT:1>]) == qlen:<EOL><INDENT>logging.warn("<STR_LIT>",<EOL>qlen, len(parts[<NUM_LIT:1>]))<EOL><DEDENT>return qlen, parts[<NUM_LIT:1>]<EOL>
(209)**************!*****************!!*************...
f12281:m4
def _parse_seq_preheader(line):
match = re.match(r"<STR_LIT>", line, re.VERBOSE)<EOL>if not match:<EOL><INDENT>raise ValueError("<STR_LIT>" + line)<EOL><DEDENT>index, this_len, query_len = match.groups()<EOL>return list(map(int, (index, this_len, query_len)))<EOL>
$3=227(209):
f12281:m5
def _parse_seq_header(line):
<EOL>_parts = line[<NUM_LIT:1>:].split(None, <NUM_LIT:1>)<EOL>rec_id = _parts[<NUM_LIT:0>]<EOL>descr = _parts[<NUM_LIT:1>] if _parts[<NUM_LIT:1>:] else '<STR_LIT>'<EOL>dbxrefs = {}<EOL>if '<STR_LIT:|>' in rec_id:<EOL><INDENT>id_gen = iter(rec_id.rstrip('<STR_LIT:|>').split('<STR_LIT:|>'))<EOL>for key in id_gen:<EOL><IN...
Unique ID, head/tail lengths and taxonomy info from a sequence header. The description is the part of the FASTA/CMA sequence header starting after the first space (i.e. excluding ID), to the end of the line. This function looks inside the first '{...}' pair to extract info. Ex: >consensus seq ...
f12281:m6
def _parse_seq_body(line):
line = line.rstrip('<STR_LIT:*>')<EOL>if '<STR_LIT>' in line:<EOL><INDENT>head, _rest = line.split('<STR_LIT>', <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>_rest = line.split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>]<EOL>head, _rest = _rest.split('<STR_LIT:)>', <NUM_LIT:1>)<EOL><DEDENT>if '<STR_LIT>' in _rest:<EOL><INDENT>...
Ex: {()YVPFARKYRPKFFREVIGQEAPVRILKALNcknpskgepcgereiDRGVFPDVRA-LKLLDQASVYGE()}* MENINNI{()----------FKLILVGDGKFFSSSGEIIFNIWDTKFGGLRDGYYRLTYKNEDDM()}* Or: {(HY)ELPWVEKYR... The sequence fragments in parentheses represent N- or C-terminal flanking regions that are not part of the alignment block (I think). Most tools...
f12281:m7
def realign_seqs(block, gap_char='<STR_LIT:.>', align_indels=False):
<EOL>all_chars = [list(sq['<STR_LIT>']) for sq in block['<STR_LIT>']]<EOL>nrows = len(all_chars)<EOL>i = <NUM_LIT:0><EOL>while i < len(all_chars[<NUM_LIT:0>]):<EOL><INDENT>rows_need_gaps = [r for r in all_chars if not r[i].islower()]<EOL>if len(rows_need_gaps) != nrows:<EOL><INDENT>for row in rows_need_gaps:<EOL><INDEN...
Add gaps to a block so all residues in a column are equivalent. Given a block, containing a list of "sequences" (dicts) each containing a "seq" (actual string sequence, where upper=match, lower=insert, dash=gap), insert gaps (- or .) into the sequences s.t. 1. columns line up properly, and 2. all ...
f12281:m11
def consensus2block(record, level=<NUM_LIT:0>, name=None):
cons_ungap = str(record.seq).replace('<STR_LIT:->', '<STR_LIT>').replace('<STR_LIT:.>', '<STR_LIT>').upper()<EOL>record.seq = cons_ungap<EOL>return dict(<EOL>level=level, <EOL>one=<NUM_LIT:1>,<EOL>name=name or record.id,<EOL>params='<STR_LIT>',<EOL>query_length=len(cons_ungap),<EOL>query_chars='<STR_LIT:*>'*len(cons_un...
Convert a Biopython SeqRecord to a esbglib.cma block. Ungapping is handled here.
f12281:m12
def seqrecord2sequence(record, qlen, index):
<EOL>description = (record.description.split('<STR_LIT:U+0020>', <NUM_LIT:1>)[<NUM_LIT:1>]<EOL>if '<STR_LIT:U+0020>' in record.description<EOL>else '<STR_LIT:U+0020>')<EOL>return dict(index=index,<EOL>id=record.id,<EOL>description=description,<EOL>dbxrefs={},<EOL>phylum='<STR_LIT>',<EOL>taxchar='<STR_LIT>',<EOL>head_le...
Convert a Biopython SeqRecord to a esbglib.cma block. Indels (gaps, casing) must have already been handled in the record.
f12281:m13
def collapse_to_consensus(seqrecords, strict=False, do_iron=True):
level = <NUM_LIT:0><EOL>name = seqrecords[<NUM_LIT:0>].id<EOL>if hasattr(seqrecords, '<STR_LIT>'):<EOL><INDENT>if hasattr(seqrecords, '<STR_LIT>'):<EOL><INDENT>level = seqrecords.level<EOL><DEDENT>if hasattr(seqrecords, '<STR_LIT:name>'):<EOL><INDENT>name = seqrecords.name<EOL><DEDENT>seqrecords = seqrecords._records<E...
Opposite of realign_seqs. Input sequences should all be the same length. The first record must be the consensus.
f12281:m15
def iron(sequence):
r_indel = re.compile(r'<STR_LIT>')<EOL>orig_sequence = sequence<EOL>while r_indel.search(sequence):<EOL><INDENT>in_insert = False<EOL>in_gap = False<EOL>seen_gaps = <NUM_LIT:0><EOL>inserts = []<EOL>outchars = []<EOL>for char in sequence:<EOL><INDENT>if in_insert:<EOL><INDENT>if char.islower():<EOL><INDENT>inserts.appen...
Iron out' indel regions in the aligned sequence. Any inserts next to deletions are converted to matches (uppercase). Given a CMA string like: AAAAbc--de-f--gAAA Result: AAAABCDEFgAAA
f12281:m16
@contextlib.contextmanager<EOL>def maybe_open(infile, mode='<STR_LIT:r>'):
<EOL>if isinstance(infile, basestring):<EOL><INDENT>handle = open(infile, mode)<EOL>do_close = True<EOL><DEDENT>else:<EOL><INDENT>handle = infile<EOL>do_close = False<EOL><DEDENT>yield handle<EOL>if do_close:<EOL><INDENT>handle.close()<EOL><DEDENT>
Take a file name or a handle, and return a handle. Simplifies creating functions that automagically accept either a file name or an already opened file handle.
f12282:m1
def unblank(stream):
return itertools.ifilter(None, (line.strip() for line in stream))<EOL>
Remove blank lines from a file being read iteratively.
f12282:m2
@task(name='<STR_LIT>')<EOL>def purge_old_logs(delete_before_days=<NUM_LIT:7>):
delete_before_date = timezone.now() - timedelta(days=delete_before_days)<EOL>logs_deleted = Log.objects.filter(<EOL>created_on__lte=delete_before_date).delete()<EOL>return logs_deleted<EOL>
Purges old logs from the database table
f12291:m0