Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def run_azure(target, jobs, n=1, nproc=None, path='.', delete=True, config=None, **kwargs): import ecell4.extra.azure_batch as azure_batch return azure_batch.run_azure(target, jobs, n, path, delete, config)
[ "\n Evaluate the given function with each set of arguments, and return a list of results.\n This function does in parallel with Microsoft Azure Batch.\n\n This function is the work in progress.\n The argument `nproc` doesn't work yet.\n See `ecell4.extra.azure_batch.run_azure` for details.\n\n See...
Please provide a description of the function:def getseed(myseed, i): rndseed = int(myseed[(i - 1) * 8: i * 8], 16) rndseed = rndseed % (2 ** 31) #XXX: trancate the first bit return rndseed
[ "\n Return a single seed from a long seed given by `genseeds`.\n\n Parameters\n ----------\n myseed : bytes\n A long seed given by `genseeds(n)`.\n i : int\n An index less than n.\n\n Returns\n -------\n rndseed : int\n A seed (less than (2 ** 31))\n\n " ]
Please provide a description of the function:def list_species(model, seeds=None): seeds = None or [] from ecell4_base.core import Species if not isinstance(seeds, list): seeds = list(seeds) expanded = model.expand([Species(serial) for serial in seeds]) species_list = [sp.serial() for...
[ "This function is deprecated." ]
Please provide a description of the function:def ensemble_simulations( t, y0=None, volume=1.0, model=None, solver='ode', is_netfree=False, species_list=None, without_reset=False, return_type='matplotlib', opt_args=(), opt_kwargs=None, structures=None, rndseed=None, n=1, nproc=None, method=None, erro...
[ "\n Run simulations multiple times and return its ensemble.\n Arguments are almost same with ``ecell4.util.simulation.run_simulation``.\n `observers` and `progressbar` is not available here.\n\n Parameters\n ----------\n n : int, optional\n A number of runs. Default is 1.\n nproc : int, ...
Please provide a description of the function:def save_bd5( space, filename, group_index=0, object_name="molecule", spatial_unit="meter", time_unit="second", trunc=False, with_radius=False): if isinstance(space, (list, tuple, set)): for i, space_ in enumerate(space): ...
[ "Save a space in the BDML-BD5 format (https://github.com/openssbd/BDML-BD5).\n\n Open file for read/write, if it already exists, and create a new file, otherwise.\n If trunc is True, always create a new file.\n A new group named `group_name` is created. If the group already exists, returns\n an exceptio...
Please provide a description of the function:def _escapeCharacters(tag): for i,c in enumerate(tag.contents): if type(c) != bs4.element.NavigableString: continue c.replace_with(_escapeCharSub(r'\\\1', c))
[ "non-recursively escape underlines and asterisks\n\tin the tag" ]
Please provide a description of the function:def _breakRemNewlines(tag): for i,c in enumerate(tag.contents): if type(c) != bs4.element.NavigableString: continue c.replace_with(re.sub(r' {2,}', ' ', c).replace('\n',''))
[ "non-recursively break spaces and remove newlines in the tag" ]
Please provide a description of the function:def _markdownify(tag, _listType=None, _blockQuote=False, _listIndex=1): children = tag.find_all(recursive=False) if tag.name == '[document]': for child in children: _markdownify(child) return if tag.name not in _supportedTags or not _supportedAttrs(tag): if t...
[ "recursively converts a tag into markdown" ]
Please provide a description of the function:def convert(html): bs = BeautifulSoup(html, 'html.parser') _markdownify(bs) ret = unicode(bs).replace(u'\xa0', '&nbsp;') ret = re.sub(r'\n{3,}', r'\n\n', ret) # ! FIXME: hack ret = re.sub(r'&lt;&lt;&lt;FLOATING LINK: (.+)&gt;&gt;&gt;', r'<\1>', ret) # ! FIXME: hack ...
[ "converts an html string to markdown while preserving unsupported markup." ]
Please provide a description of the function:def create(cls, type): if type == 0: return FilterDropShadow(id) elif type == 1: return FilterBlur(id) elif type == 2: return FilterGlow(id) elif type == 3: return FilterBevel(id) elif type == 4: return FilterGradientGlow(id) ...
[ " Return the specified Filter " ]
Please provide a description of the function:def dimensions(self): return (self.xmax - self.xmin, self.ymax - self.ymin)
[ "\n Returns dimensions as (x, y) tuple.\n " ]
Please provide a description of the function:def export(self, exporter=None, force_stroke=False): exporter = SVGExporter() if exporter is None else exporter if self._data is None: raise Exception("This SWF was not loaded! (no data)") if len(self.tags) == 0: raise...
[ "\n Export this SWF using the specified exporter. \n When no exporter is passed in the default exporter used \n is swf.export.SVGExporter.\n \n Exporters should extend the swf.export.BaseExporter class.\n \n @param exporter : the exporter to use\n @param force...
Please provide a description of the function:def parse(self, data): self._data = data = data if isinstance(data, SWFStream) else SWFStream(data) self._header = SWFHeader(self._data) if self._header.compressed: temp = BytesIO() if self._header.compressed_zlib: ...
[ " \n Parses the SWF.\n \n The @data parameter can be a file object or a SWFStream\n " ]
Please provide a description of the function:def int32(x): if x>0xFFFFFFFF: raise OverflowError if x>0x7FFFFFFF: x=int(0x100000000-x) if x<2147483648: return -x else: return -2147483648 return x
[ " Return a signed or unsigned int " ]
Please provide a description of the function:def bin(self, s): return str(s) if s<=1 else bin(s>>1) + str(s&1)
[ " Return a value as a binary string " ]
Please provide a description of the function:def calc_max_bits(self, signed, values): b = 0 vmax = -10000000 for val in values: if signed: b = b | val if val >= 0 else b | ~val << 1 vmax = val if vmax < val else vmax else:...
[ " Calculates the maximim needed bits to represent a value " ]
Please provide a description of the function:def readbits(self, bits): if bits == 0: return 0 # fast byte-aligned path if bits % 8 == 0 and self._bits_pending == 0: return self._read_bytes_aligned(bits // 8) out = 0 mask...
[ "\n Read the specified number of bits from the stream.\n Returns 0 for bits == 0.\n ", "\n transfers t bits from the top of y_n to the bottom of x.\n then returns x and the remaining bits in y\n " ]
Please provide a description of the function:def readSB(self, bits): shift = 32 - bits return int32(self.readbits(bits) << shift) >> shift
[ " Read a signed int using the specified number of bits " ]
Please provide a description of the function:def readEncodedU32(self): self.reset_bits_pending(); result = self.readUI8(); if result & 0x80 != 0: result = (result & 0x7f) | (self.readUI8() << 7) if result & 0x4000 != 0: result = (result & 0x3fff) ...
[ " Read a encoded unsigned int " ]
Please provide a description of the function:def readFLOAT16(self): self.reset_bits_pending() word = self.readUI16() sign = -1 if ((word & 0x8000) != 0) else 1 exponent = (word >> 10) & 0x1f significand = word & 0x3ff if exponent == 0: if significand ...
[ " Read a 2 byte float " ]
Please provide a description of the function:def readSTYLECHANGERECORD(self, states, fill_bits, line_bits, level = 1): return SWFShapeRecordStyleChange(self, states, fill_bits, line_bits, level)
[ " Read a SWFShapeRecordStyleChange " ]
Please provide a description of the function:def readTEXTRECORD(self, glyphBits, advanceBits, previousRecord=None, level=1): if self.readUI8() == 0: return None else: self.seek(self.tell() - 1) return SWFTextRecord(self, glyphBits, advanceBits, previousRecord...
[ " Read a SWFTextRecord " ]
Please provide a description of the function:def readACTIONRECORD(self): action = None actionCode = self.readUI8() if actionCode != 0: actionLength = self.readUI16() if actionCode >= 0x80 else 0 #print "0x%x"%actionCode, actionLength action = SWFActio...
[ " Read a SWFActionRecord " ]
Please provide a description of the function:def readACTIONRECORDs(self): out = [] while 1: action = self.readACTIONRECORD() if action: out.append(action) else: break return out
[ " Read zero or more button records (zero-terminated) " ]
Please provide a description of the function:def readCLIPACTIONRECORD(self, version): pos = self.tell() flags = self.readUI32() if version >= 6 else self.readUI16() if flags == 0: return None else: self.seek(pos) return SWFClipActionRecord(sel...
[ " Read a SWFClipActionRecord " ]
Please provide a description of the function:def readRGB(self): self.reset_bits_pending(); r = self.readUI8() g = self.readUI8() b = self.readUI8() return (0xff << 24) | (r << 16) | (g << 8) | b
[ " Read a RGB color " ]
Please provide a description of the function:def readRGBA(self): self.reset_bits_pending(); r = self.readUI8() g = self.readUI8() b = self.readUI8() a = self.readUI8() return (a << 24) | (r << 16) | (g << 8) | b
[ " Read a RGBA color " ]
Please provide a description of the function:def readString(self): s = self.f.read(1) string = b"" while ord(s) > 0: string += s s = self.f.read(1) return string.decode()
[ " Read a string " ]
Please provide a description of the function:def readFILTER(self): filterId = self.readUI8() filter = SWFFilterFactory.create(filterId) filter.parse(self) return filter
[ " Read a SWFFilter " ]
Please provide a description of the function:def readFILTERLIST(self): number = self.readUI8() return [self.readFILTER() for _ in range(number)]
[ " Read a length-prefixed list of FILTERs " ]
Please provide a description of the function:def readBUTTONRECORDs(self, version): out = [] while 1: button = self.readBUTTONRECORD(version) if button: out.append(button) else: break return out
[ " Read zero or more button records (zero-terminated) " ]
Please provide a description of the function:def readBUTTONCONDACTIONSs(self): out = [] while 1: action = self.readBUTTONCONDACTION() if action: out.append(action) else: break return out
[ " Read zero or more button-condition actions " ]
Please provide a description of the function:def readtag_header(self): pos = self.tell() tag_type_and_length = self.readUI16() tag_length = tag_type_and_length & 0x003f if tag_length == 0x3f: # The SWF10 spec sez that this is a signed int. # Shouldn't it ...
[ " Read a tag header " ]
Please provide a description of the function:def read(self, count=0): return self.f.read(count) if count > 0 else self.f.read()
[ " Read " ]
Please provide a description of the function:def create(cls, type): if type == 0: return TagEnd() elif type == 1: return TagShowFrame() elif type == 2: return TagDefineShape() elif type == 4: return TagPlaceObject() elif type == 5: return TagRemoveObject() elif t...
[ " Return the created tag by specifying an integer " ]
Please provide a description of the function:def get_dependencies(self): s = super(SWFTimelineContainer, self).get_dependencies() for dt in self.all_tags_of_type(DefinitionTag): s.update(dt.get_dependencies()) return s
[ " Returns the character ids this tag refers to " ]
Please provide a description of the function:def all_tags_of_type(self, type_or_types, recurse_into_sprites = True): for t in self.tags: if isinstance(t, type_or_types): yield t if recurse_into_sprites: for t in self.tags: # recurse into n...
[ "\n Generator for all tags of the given type_or_types.\n\n Generates in breadth-first order, optionally including all sub-containers.\n " ]
Please provide a description of the function:def build_dictionary(self): d = {} for t in self.all_tags_of_type(DefinitionTag, recurse_into_sprites = False): if t.characterId in d: #print 'redefinition of characterId %d:' % (t.characterId) #print ' wa...
[ "\n Return a dictionary of characterIds to their defining tags.\n " ]
Please provide a description of the function:def collect_sound_streams(self): rc = [] current_stream = None # looking in all containers for frames for tag in self.all_tags_of_type((TagSoundStreamHead, TagSoundStreamBlock)): if isinstance(tag, TagSoundStreamHead): ...
[ "\n Return a list of sound streams in this timeline and its children.\n The streams are returned in order with respect to the timeline.\n\n A stream is returned as a list: the first element is the tag\n which introduced that stream; other elements are the tags\n which made up the ...
Please provide a description of the function:def collect_video_streams(self): rc = [] streams_by_id = {} # scan first for all streams for t in self.all_tags_of_type(TagDefineVideoStream): stream = [ t ] streams_by_id[t.characterId] = stream r...
[ "\n Return a list of video streams in this timeline and its children.\n The streams are returned in order with respect to the timeline.\n\n A stream is returned as a list: the first element is the tag\n which introduced that stream; other elements are the tags\n which made up the ...
Please provide a description of the function:def parse(self, data, length, version=1): pos = data.tell() self.characterId = data.readUI16() self.depth = data.readUI16(); self.matrix = data.readMATRIX(); self.hasCharacter = True; self.hasMatrix = True; if ...
[ " Parses this tag " ]
Please provide a description of the function:def parse(self, data, length, version=1): self.characterId = data.readUI16() self.depth = data.readUI16()
[ " Parses this tag " ]
Please provide a description of the function:def export(self, swf, force_stroke=False): self.svg = self._e.svg(version=SVG_VERSION) self.force_stroke = force_stroke self.defs = self._e.defs() self.root = self._e.g() self.svg.append(self.defs) self.svg.append(self...
[ " Exports the specified SWF to SVG.\n\n @param swf The SWF.\n @param force_stroke Whether to force strokes on non-stroked fills.\n " ]
Please provide a description of the function:def export(self, swf, shape, **export_opts): # If `shape` is given as int, find corresponding shape tag. if isinstance(shape, Tag): shape_tag = shape else: shapes = [x for x in swf.all_tags_of_type((TagDefineShape, Ta...
[ " Exports the specified shape of the SWF to SVG.\n\n @param swf The SWF.\n @param shape Which shape to export, either by characterId(int) or as a Tag object.\n " ]
Please provide a description of the function:def export(self, swf, frame, **export_opts): self.wanted_frame = frame return super(FrameSVGExporterMixin, self).export(swf, *export_opts)
[ " Exports a frame of the specified SWF to SVG.\n\n @param swf The SWF.\n @param frame Which frame to export, by 0-based index (int)\n " ]
Please provide a description of the function:def parse_arg(f, kwd, offset=0): vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]])
[ "\n convert dictionary of keyword argument and value to positional argument\n equivalent to::\n\n vnames = describe(f)\n return tuple([kwd[k] for k in vnames[offset:]])\n\n " ]
Please provide a description of the function:def _get_args_and_errors(self, minuit=None, args=None, errors=None): ret_arg = None ret_error = None if minuit is not None: # case 1 ret_arg = minuit.args ret_error = minuit.errors return ret_arg, ret_error # no minuit specified...
[ "\n consistent algorithm to get argument and errors\n 1) get it from minuit if minuit is available\n 2) if not get it from args and errors\n 2.1) if args is dict parse it.\n 3) if all else fail get it from self.last_arg\n " ]
Please provide a description of the function:def draw_residual(x, y, yerr, xerr, show_errbars=True, ax=None, zero_line=True, grid=True, **kwargs): from matplotlib import pyplot as plt ax = plt.gca() if ax is None else ax if show_errbars: p...
[ "Draw a residual plot on the axis.\n\n By default, if show_errbars if True, residuals are drawn as blue points\n with errorbars with no endcaps. If show_errbars is False, residuals are\n drawn as a bar graph with black bars.\n\n **Arguments**\n\n - **x** array of numbers, x-coordinates\n\n ...
Please provide a description of the function:def draw_compare(f, arg, edges, data, errors=None, ax=None, grid=True, normed=False, parts=False): from matplotlib import pyplot as plt # arg is either map or tuple ax = plt.gca() if ax is None else ax arg = parse_arg(f, arg, 1) if isinstance(arg, dict)...
[ "\n TODO: this needs to be rewritten\n " ]
Please provide a description of the function:def draw_pdf(f, arg, bound, bins=100, scale=1.0, density=True, normed_pdf=False, ax=None, **kwds): edges = np.linspace(bound[0], bound[1], bins) return draw_pdf_with_edges(f, arg, edges, ax=ax, scale=scale, density=density, ...
[ "\n draw pdf with given argument and bounds.\n\n **Arguments**\n\n * **f** your pdf. The first argument is assumed to be independent\n variable\n\n * **arg** argument can be tuple or list\n\n * **bound** tuple(xmin,xmax)\n\n * **bins** number of bins to plot pdf. Default 1...
Please provide a description of the function:def draw_compare_hist(f, arg, data, bins=100, bound=None, ax=None, weights=None, normed=False, use_w2=False, parts=False, grid=True): from matplotlib import pyplot as plt ax = plt.gca() if ax is None else ax bound = minmax(data) if bou...
[ "\n draw histogram of data with poisson error bar and f(x,*arg).\n\n ::\n\n data = np.random.rand(10000)\n f = gaussian\n draw_compare_hist(f, {'mean':0,'sigma':1}, data, normed=True)\n\n **Arguments**\n\n - **f**\n - **arg** argument pass to f. Can be dictionary or list....
Please provide a description of the function:def gen_toyn(f, nsample, ntoy, bound, accuracy=10000, quiet=True, **kwd): return gen_toy(f, nsample * ntoy, bound, accuracy, quiet, **kwd).reshape((ntoy, nsample))
[ "\n just alias of gentoy for nample and then reshape to ntoy,nsample)\n :param f:\n :param nsample:\n :param bound:\n :param accuracy:\n :param quiet:\n :param kwd:\n :return:\n " ]
Please provide a description of the function:def gen_toy(f, nsample, bound, accuracy=10000, quiet=True, **kwd): # based on inverting cdf this is fast but you will need to give it a reasonable range # unlike roofit which is based on accept reject vnames = describe(f) if not quiet: print(vna...
[ "\n generate ntoy\n :param f:\n :param nsample:\n :param ntoy:\n :param bound:\n :param accuracy:\n :param quiet:\n :param kwd: the rest of keyword argument will be passed to f\n :return: numpy.ndarray\n " ]
Please provide a description of the function:def fit_uml(f, data, quiet=False, print_level=0, *arg, **kwd): uml = UnbinnedLH(f, data) minuit = Minuit(uml, print_level=print_level, **kwd) minuit.set_strategy(2) minuit.migrad() if not minuit.migrad_ok() or not minuit.matrix_accurate(): if...
[ "\n perform unbinned likelihood fit\n :param f: pdf\n :param data: data\n :param quiet: if not quite draw latest fit on fail fit\n :param printlevel: minuit printlevel\n :return:\n " ]
Please provide a description of the function:def fit_binx2(f, data, bins=30, bound=None, print_level=0, quiet=False, *arg, **kwd): uml = BinnedChi2(f, data, bins=bins, bound=bound) minuit = Minuit(uml, print_level=print_level, **kwd) minuit.set_strategy(2) minuit.migrad() if not minuit.migrad_o...
[ "\n perform chi^2 fit\n :param f:\n :param data:\n :param bins:\n :param range:\n :param printlevel:\n :param quiet:\n :param arg:\n :param kwd:\n :return:\n " ]
Please provide a description of the function:def fit_binlh(f, data, bins=30, bound=None, quiet=False, weights=None, use_w2=False, print_level=0, pedantic=True, extended=False, *arg, **kwd): uml = BinnedLH(f, data, bins=bins, bound=bound, weights=weig...
[ "\n perform bin likelihood fit\n :param f:\n :param data:\n :param bins:\n :param range:\n :param quiet:\n :param weights:\n :param use_w2:\n :param printlevel:\n :param pedantic:\n :param extended:\n :param arg:\n :param kwd:\n :return:\n " ]
Please provide a description of the function:def pprint_arg(vnames, value): ret = '' for name, v in zip(vnames, value): ret += '%s=%s;' % (name, str(v)) return ret;
[ "\n pretty print argument\n :param vnames:\n :param value:\n :return:\n " ]
Please provide a description of the function:def gauss_pdf(x, mu, sigma): return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)
[ "Normalized Gaussian" ]
Please provide a description of the function:def get_chunks(sequence, chunk_size): return [ sequence[idx:idx + chunk_size] for idx in range(0, len(sequence), chunk_size) ]
[ "Split sequence into chunks.\n\n :param list sequence:\n :param int chunk_size:\n " ]
Please provide a description of the function:def get_kwargs(kwargs): return { key: value for key, value in six.iteritems(kwargs) if key != 'self' }
[ "Get all keys and values from dictionary where key is not `self`.\n\n :param dict kwargs: Input parameters\n " ]
Please provide a description of the function:def check_status_code(response, codes=None): codes = codes or [httplib.OK] checker = ( codes if callable(codes) else lambda resp: resp.status_code in codes ) if not checker(response): raise exceptions.ApiError(response, re...
[ "Check HTTP status code and raise exception if incorrect.\n\n :param Response response: HTTP response\n :param codes: List of accepted codes or callable\n :raises: ApiError if code invalid\n " ]
Please provide a description of the function:def result_or_error(response): data = response.json() result = data.get('result') if result is not None: return result raise exceptions.ApiError(response, data)
[ "Get `result` field from Betfair response or raise exception if not\n found.\n\n :param Response response:\n :raises: ApiError if no results passed\n " ]
Please provide a description of the function:def process_result(result, model=None): if model is None: return result if isinstance(result, collections.Sequence): return [model(**item) for item in result] return model(**result)
[ "Cast response JSON to Betfair model(s).\n\n :param result: Betfair response JSON\n :param BetfairModel model: Deserialization format; if `None`, return raw\n JSON\n " ]
Please provide a description of the function:def make_payload(base, method, params): payload = { 'jsonrpc': '2.0', 'method': '{base}APING/v1.0/{method}'.format(**locals()), 'params': utils.serialize_dict(params), 'id': 1, } return payload
[ "Build Betfair JSON-RPC payload.\n\n :param str base: Betfair base (\"Sports\" or \"Account\")\n :param str method: Betfair endpoint\n :param dict params: Request parameters\n " ]
Please provide a description of the function:def requires_login(func, *args, **kwargs): self = args[0] if self.session_token: return func(*args, **kwargs) raise exceptions.NotLoggedIn()
[ "Decorator to check that the user is logged in. Raises `BetfairError`\n if instance variable `session_token` is absent.\n " ]
Please provide a description of the function:def nearest_price(price, cutoffs=CUTOFFS): if price <= MIN_PRICE: return MIN_PRICE if price > MAX_PRICE: return MAX_PRICE price = as_dec(price) for cutoff, step in cutoffs: if price < cutoff: break step = as_dec(s...
[ "Returns the nearest Betfair odds value to price.\n\n Adapted from Anton Zemlyanov's AlgoTrader project (MIT licensed).\n https://github.com/AlgoTrader/betfair-sports-api/blob/master/lib/betfair_price.js\n\n :param float price: Approximate Betfair price (i.e. decimal odds value)\n :param tuple cutoffs: ...
Please provide a description of the function:def ticks_difference(price_1, price_2): price_1_index = PRICES.index(as_dec(price_1)) price_2_index = PRICES.index(as_dec(price_2)) return abs(price_1_index - price_2_index)
[ "Returns the absolute difference in terms of \"ticks\" (i.e. individual\n price increments) between two Betfair prices.\n\n :param float price_1: An exact, valid Betfair price\n :param float price_2: An exact, valid Betfair price\n :returns: The absolute value of the difference between the prices in \"t...
Please provide a description of the function:def price_ticks_away(price, n_ticks): price_index = PRICES.index(as_dec(price)) return float(PRICES[price_index + n_ticks])
[ "Returns an exact, valid Betfair price that is n_ticks \"ticks\" away from\n the given price. n_ticks may positive, negative or zero (in which case the\n same price is returned) but if there is no price n_ticks away from the\n given price then an exception will be thrown.\n\n :param float price: An exac...
Please provide a description of the function:def login(self, username, password): response = self.session.post( os.path.join(self.identity_url, 'certlogin'), cert=self.cert_file, data=urllib.urlencode({ 'username': username, 'password'...
[ "Log in to Betfair. Sets `session_token` if successful.\n\n :param str username: Username\n :param str password: Password\n :raises: BetfairLoginError\n " ]
Please provide a description of the function:def list_market_profit_and_loss( self, market_ids, include_settled_bets=False, include_bsp_bets=None, net_of_commission=None): return self.make_api_request( 'Sports', 'listMarketProfitAndLoss', util...
[ "Retrieve profit and loss for a given list of markets.\n\n :param list market_ids: List of markets to calculate profit and loss\n :param bool include_settled_bets: Option to include settled bets\n :param bool include_bsp_bets: Option to include BSP bets\n :param bool net_of_commission: O...
Please provide a description of the function:def iter_list_market_book(self, market_ids, chunk_size, **kwargs): return itertools.chain(*( self.list_market_book(market_chunk, **kwargs) for market_chunk in utils.get_chunks(market_ids, chunk_size) ))
[ "Split call to `list_market_book` into separate requests.\n\n :param list market_ids: List of market IDs\n :param int chunk_size: Number of records per chunk\n :param dict kwargs: Arguments passed to `list_market_book`\n " ]
Please provide a description of the function:def iter_list_market_profit_and_loss( self, market_ids, chunk_size, **kwargs): return itertools.chain(*( self.list_market_profit_and_loss(market_chunk, **kwargs) for market_chunk in utils.get_chunks(market_ids, chunk_size)...
[ "Split call to `list_market_profit_and_loss` into separate requests.\n\n :param list market_ids: List of market IDs\n :param int chunk_size: Number of records per chunk\n :param dict kwargs: Arguments passed to `list_market_profit_and_loss`\n " ]
Please provide a description of the function:def place_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'placeOrders', utils.get_kwargs(locals()), model=models.PlaceExecutionReport, )
[ "Place new orders into market. This operation is atomic in that all\n orders will be placed or none will be placed.\n\n :param str market_id: The market id these orders are to be placed on\n :param list instructions: List of `PlaceInstruction` objects\n :param str customer_ref: Optional ...
Please provide a description of the function:def cancel_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'cancelOrders', utils.get_kwargs(locals()), model=models.CancelExecutionReport, )
[ "Cancel all bets OR cancel all bets on a market OR fully or\n partially cancel particular orders on a market.\n\n :param str market_id: If not supplied all bets are cancelled\n :param list instructions: List of `CancelInstruction` objects\n :param str customer_ref: Optional order identif...
Please provide a description of the function:def replace_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'replaceOrders', utils.get_kwargs(locals()), model=models.ReplaceExecutionReport, )
[ "This operation is logically a bulk cancel followed by a bulk place.\n The cancel is completed first then the new orders are placed.\n\n :param str market_id: The market id these orders are to be placed on\n :param list instructions: List of `ReplaceInstruction` objects\n :param str cust...
Please provide a description of the function:def update_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'updateOrders', utils.get_kwargs(locals()), model=models.UpdateExecutionReport, )
[ "Update non-exposure changing fields.\n\n :param str market_id: The market id these orders are to be placed on\n :param list instructions: List of `UpdateInstruction` objects\n :param str customer_ref: Optional order identifier string\n " ]
Please provide a description of the function:def get_account_funds(self, wallet=None): return self.make_api_request( 'Account', 'getAccountFunds', utils.get_kwargs(locals()), model=models.AccountFundsResponse, )
[ "Get available to bet amount.\n\n :param Wallet wallet: Name of the wallet in question\n " ]
Please provide a description of the function:def get_account_statement( self, locale=None, from_record=None, record_count=None, item_date_range=None, include_item=None, wallet=None): return self.make_api_request( 'Account', 'getAccountStatement', ...
[ "Get account statement.\n\n :param str locale: The language to be used where applicable\n :param int from_record: Specifies the first record that will be returned\n :param int record_count: Specifies the maximum number of records to be returned\n :param TimeRange item_date_range: Return ...
Please provide a description of the function:def get_account_details(self): return self.make_api_request( 'Account', 'getAccountDetails', utils.get_kwargs(locals()), model=models.AccountDetailsResponse, )
[ "Returns the details relating your account, including your discount\n rate and Betfair point balance.\n " ]
Please provide a description of the function:def list_currency_rates(self, from_currency=None): return self.make_api_request( 'Account', 'listCurrencyRates', utils.get_kwargs(locals()), model=models.CurrencyRate, )
[ "Returns a list of currency rates based on given currency\n\n :param str from_currency: The currency from which the rates are computed\n " ]
Please provide a description of the function:def transfer_funds(self, from_, to, amount): return self.make_api_request( 'Account', 'transferFunds', utils.get_kwargs(locals()), model=models.TransferResponse, )
[ "Transfer funds between the UK Exchange and Australian Exchange wallets.\n\n :param Wallet from_: Source wallet\n :param Wallet to: Destination wallet\n :param float amount: Amount to transfer\n " ]
Please provide a description of the function:def comment_count(object): return Comment.objects.filter( object_id=object.pk, content_type=ContentType.objects.get_for_model(object) ).count()
[ "\n Usage:\n {% comment_count obj %}\n or\n {% comment_count obj as var %}\n " ]
Please provide a description of the function:def comments(object): return Comment.objects.filter( object_id=object.pk, content_type=ContentType.objects.get_for_model(object) )
[ "\n Usage:\n {% comments obj as var %}\n " ]
Please provide a description of the function:def comment_form(context, object): user = context.get("user") form_class = context.get("form", CommentForm) form = form_class(obj=object, user=user) return form
[ "\n Usage:\n {% comment_form obj as comment_form %}\n Will read the `user` var out of the contex to know if the form should be\n form an auth'd user or not.\n " ]
Please provide a description of the function:def comment_target(object): return reverse("pinax_comments:post_comment", kwargs={ "content_type_id": ContentType.objects.get_for_model(object).pk, "object_id": object.pk })
[ "\n Usage:\n {% comment_target obj [as varname] %}\n " ]
Please provide a description of the function:def parse(self, text, html=True): '''Parse the text and return a ParseResult instance.''' self._urls = [] self._users = [] self._lists = [] self._tags = [] reply = REPLY_REGEX.match(text) reply = reply.groups(0)[0] if ...
[]
Please provide a description of the function:def _text(self, text): '''Parse a Tweet without generating HTML.''' URL_REGEX.sub(self._parse_urls, text) USERNAME_REGEX.sub(self._parse_users, text) LIST_REGEX.sub(self._parse_lists, text) HASHTAG_REGEX.sub(self._parse_tags, text) ...
[]
Please provide a description of the function:def _html(self, text): '''Parse a Tweet and generate HTML.''' html = URL_REGEX.sub(self._parse_urls, text) html = USERNAME_REGEX.sub(self._parse_users, html) html = LIST_REGEX.sub(self._parse_lists, html) return HASHTAG_REGEX.sub(self....
[]
Please provide a description of the function:def _parse_urls(self, match): '''Parse URLs.''' mat = match.group(0) # Fix a bug in the regex concerning www...com and www.-foo.com domains # TODO fix this in the regex instead of working around it here domain = match.group(5) ...
[]
Please provide a description of the function:def _parse_users(self, match): '''Parse usernames.''' # Don't parse lists here if match.group(2) is not None: return match.group(0) mat = match.group(0) if self._include_spans: self._users.append((mat[1:], mat...
[]
Please provide a description of the function:def _parse_lists(self, match): '''Parse lists.''' # Don't parse usernames here if match.group(4) is None: return match.group(0) pre, at_char, user, list_name = match.groups() list_name = list_name[1:] if self._inc...
[]
Please provide a description of the function:def _parse_tags(self, match): '''Parse hashtags.''' mat = match.group(0) # Fix problems with the regex capturing stuff infront of the # tag = None for i in '#\uff03': pos = mat.rfind(i) if pos != -1: ...
[]
Please provide a description of the function:def _shorten_url(self, text): '''Shorten a URL and make sure to not cut of html entities.''' if len(text) > self._max_url_length and self._max_url_length != -1: text = text[0:self._max_url_length - 3] amp = text.rfind('&') ...
[]
Please provide a description of the function:def format_list(self, at_char, user, list_name): '''Return formatted HTML for a list.''' return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' \ % (user, list_name, at_char, user, list_name)
[]
Please provide a description of the function:def follow_shortlinks(shortlinks): links_followed = {} for shortlink in shortlinks: url = shortlink request_result = requests.get(url) redirect_history = request_result.history # history might look like: # (<Response [301]...
[ "Follow redirects in list of shortlinks, return dict of resulting URLs" ]
Please provide a description of the function:def _GetFieldAttributes(field): if not isinstance(field, messages.Field): raise TypeError('Field %r to be copied not a ProtoRPC field.' % (field,)) positional_args = [] kwargs = { 'required': field.required, 'repeated': field.repeated, 'varian...
[ "Decomposes field into the needed arguments to pass to the constructor.\n\n This can be used to create copies of the field or to compare if two fields\n are \"equal\" (since __eq__ is not implemented on messages.Field).\n\n Args:\n field: A ProtoRPC message field (potentially to be copied).\n\n Raises:\n ...
Please provide a description of the function:def _CompareFields(field, other_field): field_attrs = _GetFieldAttributes(field) other_field_attrs = _GetFieldAttributes(other_field) if field_attrs != other_field_attrs: return False return field.__class__ == other_field.__class__
[ "Checks if two ProtoRPC fields are \"equal\".\n\n Compares the arguments, rather than the id of the elements (which is\n the default __eq__ behavior) as well as the class of the fields.\n\n Args:\n field: A ProtoRPC message field to be compared.\n other_field: A ProtoRPC message field to be compared.\n\n ...
Please provide a description of the function:def _CopyField(field, number=None): positional_args, kwargs = _GetFieldAttributes(field) number = number or field.number positional_args.append(number) return field.__class__(*positional_args, **kwargs)
[ "Copies a (potentially) owned ProtoRPC field instance into a new copy.\n\n Args:\n field: A ProtoRPC message field to be copied.\n number: An integer for the field to override the number of the field.\n Defaults to None.\n\n Raises:\n TypeError: If the field is not an instance of messages.Field.\n...
Please provide a description of the function:def combined_message_class(self): if self.__combined_message_class is not None: return self.__combined_message_class fields = {} # We don't need to preserve field.number since this combined class is only # used for the protorpc remote.method and i...
[ "A ProtoRPC message class with both request and parameters fields.\n\n Caches the result in a local private variable. Uses _CopyField to create\n copies of the fields from the existing request and parameters classes since\n those fields are \"owned\" by the message classes.\n\n Raises:\n TypeError:...
Please provide a description of the function:def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name if not isinstance(container, cls): raise TypeError('%r not an instance of %r, could not be added to cache.' % (container, cls)) if remote_info in cls.__remot...
[ "Adds a ResourceContainer to a cache tying it to a protorpc method.\n\n Args:\n remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding\n to a method.\n container: An instance of ResourceContainer.\n\n Raises:\n TypeError: if the container is not an instance of cls.\n ...