Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def update_portfolio(self): if not self._dirty_portfolio: return portfolio = self._portfolio pt = self.position_tracker portfolio.positions = pt.get_positions() position_stats = pt.stats portfolio.positi...
[ "Force a computation of the current portfolio state.\n " ]
Please provide a description of the function:def override_account_fields(self, settled_cash=not_overridden, accrued_interest=not_overridden, buying_power=not_overridden, equity_with_loan=not_o...
[ "Override fields on ``self.account``.\n " ]
Please provide a description of the function:def datashape_type_to_numpy(type_): if isinstance(type_, Option): type_ = type_.ty if isinstance(type_, DateTime): return np.dtype('datetime64[ns]') if isinstance(type_, String): return np.dtype(object) if type_ in integral: ...
[ "\n Given a datashape type, return the associated numpy type. Maps\n datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the\n numpy datetime returned by datashape isn't supported by pipeline.\n\n Parameters\n ----------\n type_: datashape.coretypes.Type\n The datashape type....
Please provide a description of the function:def new_dataset(expr, missing_values, domain): missing_values = dict(missing_values) class_dict = {'ndim': 2 if SID_FIELD_NAME in expr.fields else 1} for name, type_ in expr.dshape.measure.fields: # Don't generate a column for sid or timestamp, since...
[ "\n Creates or returns a dataset from a blaze expression.\n\n Parameters\n ----------\n expr : Expr\n The blaze expression representing the values.\n missing_values : frozenset((name, value) pairs\n Association pairs column name and missing_value for that column.\n\n This needs t...
Please provide a description of the function:def _check_resources(name, expr, resources): if expr is None: return bound = expr._resources() if not bound and resources is None: raise ValueError('no resources provided to compute %s' % name) if bound and resources: raise ValueE...
[ "Validate that the expression and resources passed match up.\n\n Parameters\n ----------\n name : str\n The name of the argument we are checking.\n expr : Expr\n The potentially bound expr.\n resources\n The explicitly passed resources to compute expr.\n\n Raises\n ------\n...
Please provide a description of the function:def _check_datetime_field(name, measure): if not isinstance(measure[name], (Date, DateTime)): raise TypeError( "'{name}' field must be a '{dt}', not: '{dshape}'".format( name=name, dt=DateTime(), ds...
[ "Check that a field is a datetime inside some measure.\n\n Parameters\n ----------\n name : str\n The name of the field to check.\n measure : Record\n The record to check the field of.\n\n Raises\n ------\n TypeError\n If the field is not a datetime inside ``measure``.\n ...
Please provide a description of the function:def _get_metadata(field, expr, metadata_expr, no_metadata_rule): if isinstance(metadata_expr, bz.Expr) or metadata_expr is None: return metadata_expr try: return expr._child['_'.join(((expr._name or ''), field))] except (ValueError, Attribut...
[ "Find the correct metadata expression for the expression.\n\n Parameters\n ----------\n field : {'deltas', 'checkpoints'}\n The kind of metadata expr to lookup.\n expr : Expr\n The baseline expression.\n metadata_expr : Expr, 'auto', or None\n The metadata argument. If this is 'a...
Please provide a description of the function:def _ensure_timestamp_field(dataset_expr, deltas, checkpoints): measure = dataset_expr.dshape.measure if TS_FIELD_NAME not in measure.names: dataset_expr = bz.transform( dataset_expr, **{TS_FIELD_NAME: dataset_expr[AD_FIELD_NAME]}...
[ "Verify that the baseline and deltas expressions have a timestamp field.\n\n If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will\n be copied from the ``AD_FIELD_NAME``. If one is provided, then we will\n verify that it is the correct dshape.\n\n Parameters\n ----------\n data...
Please provide a description of the function:def from_blaze(expr, deltas='auto', checkpoints='auto', loader=None, resources=None, odo_kwargs=None, missing_values=None, domain=GENERIC, no_deltas_rule='...
[ "Create a Pipeline API object from a blaze expression.\n\n Parameters\n ----------\n expr : Expr\n The blaze expression to use.\n deltas : Expr, 'auto' or None, optional\n The expression to use for the point in time adjustments.\n If the string 'auto' is passed, a deltas expr will b...
Please provide a description of the function:def bind_expression_to_resources(expr, resources): # bind the resources into the expression if resources is None: resources = {} # _subs stands for substitute. It's not actually private, blaze just # prefixes symbol-manipulation methods with un...
[ "\n Bind a Blaze expression to resources.\n\n Parameters\n ----------\n expr : bz.Expr\n The expression to which we want to bind resources.\n resources : dict[bz.Symbol -> any]\n Mapping from the loadable terms of ``expr`` to actual data resources.\n\n Returns\n -------\n bound...
Please provide a description of the function:def get_materialized_checkpoints(checkpoints, colnames, lower_dt, odo_kwargs): if checkpoints is not None: ts = checkpoints[TS_FIELD_NAME] checkpoints_ts = odo( ts[ts < lower_dt].max(), pd.Timestamp, **odo_kwargs ...
[ "\n Computes a lower bound and a DataFrame checkpoints.\n\n Parameters\n ----------\n checkpoints : Expr\n Bound blaze expression for a checkpoints table from which to get a\n computed lower bound.\n colnames : iterable of str\n The names of the columns for which checkpoints shou...
Please provide a description of the function:def ffill_query_in_range(expr, lower, upper, checkpoints=None, odo_kwargs=None, ts_field=TS_FIELD_NAME): odo_kwargs = odo_kwargs or {} co...
[ "Query a blaze expression in a given time range properly forward filling\n from values that fall before the lower date.\n\n Parameters\n ----------\n expr : Expr\n Bound blaze expression.\n lower : datetime\n The lower date to query for.\n upper : datetime\n The upper date to ...
Please provide a description of the function:def register_dataset(self, dataset, expr, deltas=None, checkpoints=None, odo_kwargs=None): expr_data = ExprData( expr, ...
[ "Explicitly map a datset to a collection of blaze expressions.\n\n Parameters\n ----------\n dataset : DataSet\n The pipeline dataset to map to the given expressions.\n expr : Expr\n The baseline values.\n deltas : Expr, optional\n The deltas for t...
Please provide a description of the function:def register_column(self, column, expr, deltas=None, checkpoints=None, odo_kwargs=None): self._table_expressions[column] = ExprData( ...
[ "Explicitly map a single bound column to a collection of blaze\n expressions. The expressions need to have ``timestamp`` and ``as_of``\n columns.\n\n Parameters\n ----------\n column : BoundColumn\n The pipeline dataset to map to the given expressions.\n expr : E...
Please provide a description of the function:def merge_ownership_periods(mappings): return valmap( lambda v: tuple( OwnershipPeriod( a.start, b.start, a.sid, a.value, ) for a, b in sliding_window( 2,...
[ "\n Given a dict of mappings where the values are lists of\n OwnershipPeriod objects, returns a dict with the same structure with\n new OwnershipPeriod objects adjusted so that the periods have no\n gaps.\n\n Orders the periods chronologically, and pushes forward the end date\n of each period to m...
Please provide a description of the function:def build_ownership_map(table, key_from_row, value_from_row): return _build_ownership_map_from_rows( sa.select(table.c).execute().fetchall(), key_from_row, value_from_row, )
[ "\n Builds a dict mapping to lists of OwnershipPeriods, from a db table.\n " ]
Please provide a description of the function:def build_grouped_ownership_map(table, key_from_row, value_from_row, group_key): grouped_rows = groupby( group_key, sa.select(table.c).execute().fetchall(...
[ "\n Builds a dict mapping group keys to maps of keys to to lists of\n OwnershipPeriods, from a db table.\n " ]
Please provide a description of the function:def _filter_kwargs(names, dict_): return {k: v for k, v in dict_.items() if k in names and v is not None}
[ "Filter out kwargs from a dictionary.\n\n Parameters\n ----------\n names : set[str]\n The names to select from ``dict_``.\n dict_ : dict[str, any]\n The dictionary to select from.\n\n Returns\n -------\n kwargs : dict[str, any]\n ``dict_`` where the keys intersect with ``n...
Please provide a description of the function:def _convert_asset_timestamp_fields(dict_): for key in _asset_timestamp_fields & viewkeys(dict_): value = pd.Timestamp(dict_[key], tz='UTC') dict_[key] = None if isnull(value) else value return dict_
[ "\n Takes in a dict of Asset init args and converts dates to pd.Timestamps\n " ]
Please provide a description of the function:def was_active(reference_date_value, asset): return ( asset.start_date.value <= reference_date_value <= asset.end_date.value )
[ "\n Whether or not `asset` was active at the time corresponding to\n `reference_date_value`.\n\n Parameters\n ----------\n reference_date_value : int\n Date, represented as nanoseconds since EPOCH, for which we want to know\n if `asset` was alive. This is generally the result of access...
Please provide a description of the function:def lookup_asset_types(self, sids): found = {} missing = set() for sid in sids: try: found[sid] = self._asset_type_cache[sid] except KeyError: missing.add(sid) if not missing: ...
[ "\n Retrieve asset types for a list of sids.\n\n Parameters\n ----------\n sids : list[int]\n\n Returns\n -------\n types : dict[sid -> str or None]\n Asset types for the provided sids.\n " ]
Please provide a description of the function:def retrieve_all(self, sids, default_none=False): sids = list(sids) hits, missing, failures = {}, set(), [] for sid in sids: try: asset = self._asset_cache[sid] if not default_none and asset is None...
[ "\n Retrieve all assets in `sids`.\n\n Parameters\n ----------\n sids : iterable of int\n Assets to retrieve.\n default_none : bool\n If True, return None for failed lookups.\n If False, raise `SidsNotFound`.\n\n Returns\n -------\n ...
Please provide a description of the function:def _select_most_recent_symbols_chunk(self, sid_group): cols = self.equity_symbol_mappings.c # These are the columns we actually want. data_cols = (cols.sid,) + tuple(cols[name] for name in symbol_columns) # Also select the max of e...
[ "Retrieve the most recent symbol for a set of sids.\n\n Parameters\n ----------\n sid_group : iterable[int]\n The sids to lookup. The length of this sequence must be less than\n or equal to SQLITE_MAX_VARIABLE_NUMBER because the sids will be\n passed in as sql b...
Please provide a description of the function:def _retrieve_assets(self, sids, asset_tbl, asset_type): # Fastpath for empty request. if not sids: return {} cache = self._asset_cache hits = {} querying_equities = issubclass(asset_type, Equity) filter_...
[ "\n Internal function for loading assets from a table.\n\n This should be the only method of `AssetFinder` that writes Assets into\n self._asset_cache.\n\n Parameters\n ---------\n sids : iterable of int\n Asset ids to look up.\n asset_tbl : sqlalchemy.Tab...
Please provide a description of the function:def _lookup_symbol_strict(self, ownership_map, multi_country, symbol, as_of_date): # split the symbol into the components, if there are no...
[ "\n Resolve a symbol to an asset object without fuzzy matching.\n\n Parameters\n ----------\n ownership_map : dict[(str, str), list[OwnershipPeriod]]\n The mapping from split symbols to ownership periods.\n multi_country : bool\n Does this mapping span multip...
Please provide a description of the function:def lookup_symbol(self, symbol, as_of_date, fuzzy=False, country_code=None): if symbol is None: raise TypeError("Cannot lookup asset for symbol of None for " ...
[ "Lookup an equity by symbol.\n\n Parameters\n ----------\n symbol : str\n The ticker symbol to resolve.\n as_of_date : datetime or None\n Look up the last owner of this symbol as of this datetime.\n If ``as_of_date`` is None, then this can only resolve th...
Please provide a description of the function:def lookup_symbols(self, symbols, as_of_date, fuzzy=False, country_code=None): if not symbols: return [] multi_country = country_code is None ...
[ "\n Lookup a list of equities by symbol.\n\n Equivalent to::\n\n [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols]\n\n but potentially faster because repeated lookups are memoized.\n\n Parameters\n ----------\n symbols : sequence[str]\n Sequence...
Please provide a description of the function:def lookup_future_symbol(self, symbol): data = self._select_asset_by_symbol(self.futures_contracts, symbol)\ .execute().fetchone() # If no data found, raise an exception if not data: raise SymbolNotFound(symbo...
[ "Lookup a future contract by symbol.\n\n Parameters\n ----------\n symbol : str\n The symbol of the desired contract.\n\n Returns\n -------\n future : Future\n The future contract referenced by ``symbol``.\n\n Raises\n ------\n Sym...
Please provide a description of the function:def get_supplementary_field(self, sid, field_name, as_of_date): try: periods = self.equity_supplementary_map_by_sid[ field_name, sid, ] assert periods, 'empty periods list for %r' % (field_n...
[ "Get the value of a supplementary field for an asset.\n\n Parameters\n ----------\n sid : int\n The sid of the asset to query.\n field_name : str\n Name of the supplementary field.\n as_of_date : pd.Timestamp, None\n The last known value on this da...
Please provide a description of the function:def _lookup_generic_scalar(self, obj, as_of_date, country_code, matches, missing): result = self._looku...
[ "\n Convert asset_convertible to an asset.\n\n On success, append to matches.\n On failure, append to missing.\n " ]
Please provide a description of the function:def lookup_generic(self, obj, as_of_date, country_code): matches = [] missing = [] # Interpret input as scalar. if isinstance(obj, (AssetConvertible, ContinuousFuture)): self._lookup_generic_scalar( obj=ob...
[ "\n Convert an object into an Asset or sequence of Assets.\n\n This method exists primarily as a convenience for implementing\n user-facing APIs that can handle multiple kinds of input. It should\n not be used for internal code where we already know the expected types\n of our in...
Please provide a description of the function:def _compute_asset_lifetimes(self, country_codes): equities_cols = self.equities.c if country_codes: buf = np.array( tuple( sa.select(( equities_cols.sid, ...
[ "\n Compute and cache a recarray of asset lifetimes.\n " ]
Please provide a description of the function:def lifetimes(self, dates, include_start_date, country_codes): if isinstance(country_codes, string_types): raise TypeError( "Got string {!r} instead of an iterable of strings in " "AssetFinder.lifetimes.".format(co...
[ "\n Compute a DataFrame representing asset lifetimes for the specified date\n range.\n\n Parameters\n ----------\n dates : pd.DatetimeIndex\n The dates for which to compute lifetimes.\n include_start_date : bool\n Whether or not to count the asset as a...
Please provide a description of the function:def equities_sids_for_country_code(self, country_code): sids = self._compute_asset_lifetimes([country_code]).sid return tuple(sids.tolist())
[ "Return all of the sids for a given country.\n\n Parameters\n ----------\n country_code : str\n An ISO 3166 alpha-2 country code.\n\n Returns\n -------\n tuple[int]\n The sids whose exchanges are in this country.\n " ]
Please provide a description of the function:def load_raw_arrays(self, columns, start_date, end_date, assets): rolls_by_asset = {} for asset in assets: rf = self._roll_finders[asset.roll_style] rolls_by_asset[asset] = rf.get_rolls( asset.root_symbol, ...
[ "\n Parameters\n ----------\n fields : list of str\n 'sid'\n start_dt: Timestamp\n Beginning of the window range.\n end_dt: Timestamp\n End of the window range.\n sids : list of int\n The asset identifiers in the window.\n\n R...
Please provide a description of the function:def get_value(self, continuous_future, dt, field): rf = self._roll_finders[continuous_future.roll_style] sid = (rf.get_contract_center(continuous_future.root_symbol, dt, cont...
[ "\n Retrieve the value at the given coordinates.\n\n Parameters\n ----------\n sid : int\n The asset identifier.\n dt : pd.Timestamp\n The timestamp for the desired data point.\n field : string\n The OHLVC name for the desired data point.\n\...
Please provide a description of the function:def get_last_traded_dt(self, asset, dt): rf = self._roll_finders[asset.roll_style] sid = (rf.get_contract_center(asset.root_symbol, dt, asset.offset)) if sid is None:...
[ "\n Get the latest minute on or before ``dt`` in which ``asset`` traded.\n\n If there are no trades on or before ``dt``, returns ``pd.NaT``.\n\n Parameters\n ----------\n asset : zipline.asset.Asset\n The asset for which to get the last traded minute.\n dt : pd.T...
Please provide a description of the function:def load_raw_arrays(self, columns, start_date, end_date, assets): rolls_by_asset = {} tc = self.trading_calendar start_session = tc.minute_to_session_label(start_date) end_session = tc.minute_to_session_label(end_date) for a...
[ "\n Parameters\n ----------\n fields : list of str\n 'open', 'high', 'low', 'close', or 'volume'\n start_dt: Timestamp\n Beginning of the window range.\n end_dt: Timestamp\n End of the window range.\n sids : list of int\n The asset id...
Please provide a description of the function:def current_portfolio_weights(self): position_values = pd.Series({ asset: ( position.last_sale_price * position.amount * asset.price_multiplier ) for asset, posit...
[ "\n Compute each asset's weight in the portfolio by calculating its held\n value divided by the total value of all positions.\n\n Each equity's value is its price times the number of shares held. Each\n futures contract's value is its unit price times number of shares held\n times...
Please provide a description of the function:def __hosting_wechat_img(self, content_info, hosting_callback): assert callable(hosting_callback) content_img_list = content_info.pop("content_img_list") content_html = content_info.pop("content_html") for idx, img_url in enumerate(c...
[ "将微信明细中图片托管到云端,同时将html页面中的对应图片替换\n\n Parameters\n ----------\n content_info : dict 微信文章明细字典\n {\n 'content_img_list': [], # 从微信文章解析出的原始图片列表\n 'content_html': '', # 从微信文章解析出文章的内容\n }\n hosting_callback : callable\n 托管回调函数,传入单个...
Please provide a description of the function:def get_gzh_info(self, wecgat_id_or_name, unlock_callback=None, identify_image_callback=None, decode_url=True): info = self.search_gzh(wecgat_id_or_name, 1, unlock_callback, identify_image_callback, decode_url) try: return next(info) ...
[ "获取公众号微信号 wechatid 的信息\n\n 因为wechatid唯一确定,所以第一个就是要搜索的公众号\n\n Parameters\n ----------\n wecgat_id_or_name : str or unicode\n wechat_id or wechat_name\n unlock_callback : callable\n 处理出现验证码页面的函数,参见 unlock_callback_example\n identify_image_callback : call...
Please provide a description of the function:def search_gzh(self, keyword, page=1, unlock_callback=None, identify_image_callback=None, decode_url=True): url = WechatSogouRequest.gen_search_gzh_url(keyword, page) session = requests.session() resp = self.__get_by_unlock(url, ...
[ "搜索 公众号\n\n 对于出现验证码的情况,可以由使用者自己提供:\n 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程\n 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决\n 注意:\n 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用\n...
Please provide a description of the function:def search_article(self, keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None, unlock_callback=None, identify_image_c...
[ "搜索 文章\n\n 对于出现验证码的情况,可以由使用者自己提供:\n 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程\n 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决\n 注意:\n 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用\n\...
Please provide a description of the function:def get_gzh_article_by_history(self, keyword=None, url=None, unlock_callback_sogou=None, identify_image_callback_sogou=None, unlock_callback_weixin=None, ...
[ "从 公众号的最近10条群发页面 提取公众号信息 和 文章列表信息\n\n 对于出现验证码的情况,可以由使用者自己提供:\n 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程\n 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决\n 注意:\n 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 iden...
Please provide a description of the function:def get_gzh_article_by_hot(self, hot_index, page=1, unlock_callback=None, identify_image_callback=None): assert hasattr(WechatSogouConst.hot_index, hot_index) assert isinstance(page, int) and page > 0 url = WechatSogouRequest.gen_hot_url(ho...
[ "获取 首页热门文章\n\n Parameters\n ----------\n hot_index : WechatSogouConst.hot_index\n 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx\n page : int\n 页数\n\n Returns\n -------\n list[dict]\n {\n 'gzh': {\n 'he...
Please provide a description of the function:def get_article_content(self, url, del_qqmusic=True, del_mpvoice=True, unlock_callback=None, identify_image_callback=None, hosting_callback=None, raw=False): resp = self.__get_by_unlock(url, un...
[ "获取文章原文,避免临时链接失效\n\n Parameters\n ----------\n url : str or unicode\n 原文链接,临时链接\n raw : bool\n True: 返回原始html\n False: 返回处理后的html\n del_qqmusic: bool\n True:微信原文中有插入的qq音乐,则删除\n False:微信源文中有插入的qq音乐,则保留\n del_mpvoice: boo...
Please provide a description of the function:def get_sugg(self, keyword): url = 'http://w.sugg.sogou.com/sugg/ajaj_json.jsp?key={}&type=wxpub&pr=web'.format( quote(keyword.encode('utf-8'))) r = requests.get(url) if not r.ok: raise WechatSogouRequestsException('ge...
[ "获取微信搜狗搜索关键词联想\n\n Parameters\n ----------\n keyword : str or unicode\n 关键词\n\n Returns\n -------\n list[str]\n 联想关键词列表\n\n Raises\n ------\n WechatSogouRequestsException\n " ]
Please provide a description of the function:def unlock_sogou_callback_example(url, req, resp, img, identify_image_callback): # no use resp url_quote = url.split('weixin.sogou.com/')[-1] unlock_url = 'http://weixin.sogou.com/antispider/thank.php' data = { 'c': identify_image_callback(img), ...
[ "手动打码解锁\n\n Parameters\n ----------\n url : str or unicode\n 验证码页面 之前的 url\n req : requests.sessions.Session\n requests.Session() 供调用解锁\n resp : requests.models.Response\n requests 访问页面返回的,已经跳转了\n img : bytes\n 验证码图片二进制数据\n identify_image_callback : callable\n ...
Please provide a description of the function:def unlock_weixin_callback_example(url, req, resp, img, identify_image_callback): # no use resp unlock_url = 'https://mp.weixin.qq.com/mp/verifycode' data = { 'cert': time.time() * 1000, 'input': identify_image_callback(img) } header...
[ "手动打码解锁\n\n Parameters\n ----------\n url : str or unicode\n 验证码页面 之前的 url\n req : requests.sessions.Session\n requests.Session() 供调用解锁\n resp : requests.models.Response\n requests 访问页面返回的,已经跳转了\n img : bytes\n 验证码图片二进制数据\n identify_image_callback : callable\n ...
Please provide a description of the function:def gen_search_article_url(keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None): assert isinstance(page, int) and page > 0 assert...
[ "拼接搜索 文章 URL\n\n Parameters\n ----------\n keyword : str or unicode\n 搜索文字\n page : int, optional\n 页数 the default is 1\n timesn : WechatSogouConst.search_article_time\n 时间 anytime 没有限制 / day 一天 / week 一周 / month 一月 / year 一年 / specific 自定\n ...
Please provide a description of the function:def gen_search_gzh_url(keyword, page=1): assert isinstance(page, int) and page > 0 qs_dict = OrderedDict() qs_dict['type'] = _search_type_gzh qs_dict['page'] = page qs_dict['ie'] = 'utf8' qs_dict['query'] = keyword ...
[ "拼接搜索 公众号 URL\n\n Parameters\n ----------\n keyword : str or unicode\n 搜索文字\n page : int, optional\n 页数 the default is 1\n\n Returns\n -------\n str\n search_gzh_url\n " ]
Please provide a description of the function:def gen_hot_url(hot_index, page=1): assert hasattr(WechatSogouConst.hot_index, hot_index) assert isinstance(page, int) and page > 0 index_urls = { WechatSogouConst.hot_index.hot: 0, # 热门 WechatSogouConst.hot_index.g...
[ "拼接 首页热门文章 URL\n\n Parameters\n ----------\n hot_index : WechatSogouConst.hot_index\n 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx\n page : int\n 页数\n\n Returns\n -------\n str\n 热门文章分类的url\n " ]
Please provide a description of the function:def get_first_of_element(element, sub, contype=None): content = element.xpath(sub) return list_or_empty(content, contype)
[ "抽取lxml.etree库中elem对象中文字\n\n Args:\n element: lxml.etree.Element\n sub: str\n\n Returns:\n elem中文字\n " ]
Please provide a description of the function:def get_encoding_from_reponse(r): encoding = requests.utils.get_encodings_from_content(r.text) return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers)
[ "获取requests库get或post返回的对象编码\n\n Args:\n r: requests库get或post返回的对象\n\n Returns:\n 对象编码\n " ]
Please provide a description of the function:def _replace_str_html(s): html_str_list = [ ('&#39;', '\''), ('&quot;', '"'), ('&amp;', '&'), ('&yen;', '¥'), ('amp;', ''), ('&lt;', '<'), ('&gt;', '>'), ('&nbsp;', ' '), ('\\', '') ] fo...
[ "替换html‘&quot;’等转义内容为正常内容\n\n Args:\n s: 文字内容\n\n Returns:\n s: 处理反转义后的文字\n " ]
Please provide a description of the function:def get_gzh_by_search(text): post_view_perms = WechatSogouStructuring.__get_post_view_perm(text) page = etree.HTML(text) lis = page.xpath('//ul[@class="news-list2"]/li') relist = [] for li in lis: url = get_first_...
[ "从搜索公众号获得的文本 提取公众号信息\n\n Parameters\n ----------\n text : str or unicode\n 搜索公众号获得的文本\n\n Returns\n -------\n list[dict]\n {\n 'open_id': '', # 微信号唯一ID\n 'profile_url': '', # 最近10条群发页链接\n 'headimage': '', ...
Please provide a description of the function:def get_article_by_search(text): page = etree.HTML(text) lis = page.xpath('//ul[@class="news-list"]/li') articles = [] for li in lis: url = get_first_of_element(li, 'div[1]/a/@href') if url: ti...
[ "从搜索文章获得的文本 提取章列表信息\n\n Parameters\n ----------\n text : str or unicode\n 搜索文章获得的文本\n\n Returns\n -------\n list[dict]\n {\n 'article': {\n 'title': '', # 文章标题\n 'url': '', # 文章链接\n ...
Please provide a description of the function:def get_gzh_info_by_history(text): page = etree.HTML(text) profile_area = get_first_of_element(page, '//div[@class="profile_info_area"]') profile_img = get_first_of_element(profile_area, 'div[1]/span/img/@src') profile_name = get_fi...
[ "从 历史消息页的文本 提取公众号信息\n\n Parameters\n ----------\n text : str or unicode\n 历史消息页的文本\n\n Returns\n -------\n dict\n {\n 'wechat_name': '', # 名称\n 'wechat_id': '', # 微信id\n 'introduction': '', # 描述\n ...
Please provide a description of the function:def get_article_by_history_json(text, article_json=None): if article_json is None: article_json = find_article_json_re.findall(text) if not article_json: return [] article_json = article_json[0] + '}}]}' ...
[ "从 历史消息页的文本 提取文章列表信息\n\n Parameters\n ----------\n text : str or unicode\n 历史消息页的文本\n article_json : dict\n 历史消息页的文本 提取出来的文章json dict\n\n Returns\n -------\n list[dict]\n {\n 'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发...
Please provide a description of the function:def get_gzh_article_by_hot(text): page = etree.HTML(text) lis = page.xpath('/html/body/li') gzh_article_list = [] for li in lis: url = get_first_of_element(li, 'div[1]/h4/a/@href') title = get_first_of_element(...
[ "从 首页热门搜索 提取公众号信息 和 文章列表信息\n\n Parameters\n ----------\n text : str or unicode\n 首页热门搜索 页 中 某一页 的文本\n\n Returns\n -------\n list[dict]\n {\n 'gzh': {\n 'headimage': str, # 公众号头像\n 'wechat_name': str...
Please provide a description of the function:def get_article_detail(text, del_qqmusic=True, del_voice=True): # 1. 获取微信文本content html_obj = BeautifulSoup(text, "lxml") content_text = html_obj.find('div', {'class': 'rich_media_content', 'id': 'js_content'}) # 2. 删除部分标签 if...
[ "根据微信文章的临时链接获取明细\n\n 1. 获取文本中所有的图片链接列表\n 2. 获取微信文章的html内容页面(去除标题等信息)\n\n Parameters\n ----------\n text : str or unicode\n 一篇微信文章的文本\n del_qqmusic: bool\n 删除文章中的qq音乐\n del_voice: bool\n 删除文章中的语音内容\n\n Returns\n -------\n...
Please provide a description of the function:def _decode_image(fobj, session, filename): buf = fobj.read() image = tfds.core.lazy_imports.cv2.imdecode( np.fromstring(buf, dtype=np.uint8), flags=3) # Note: Converts to RGB. if image is None: logging.warning( "Image %s could not be decoded by ...
[ "Reads and decodes an image from a file object as a Numpy array.\n\n The SUN dataset contains images in several formats (despite the fact that\n all of them have .jpg extension). Some of them are:\n - BMP (RGB)\n - PNG (grayscale, RGBA, RGB interlaced)\n - JPEG (RGB)\n - GIF (1-frame RGB)\n Since TFD...
Please provide a description of the function:def _process_image_file(fobj, session, filename): # We need to read the image files and convert them to JPEG, since some files # actually contain GIF, PNG or BMP data (despite having a .jpg extension) and # some encoding options that will make TF crash in general. ...
[ "Process image files from the dataset." ]
Please provide a description of the function:def _generate_examples(self, archive): prefix_len = len("SUN397") with tf.Graph().as_default(): with utils.nogpu_session() as sess: for filepath, fobj in archive: if (filepath.endswith(".jpg") and filepath not in _SUN397_IGN...
[ "Yields examples." ]
Please provide a description of the function:def _parse_parallel_sentences(f1, f2): def _parse_text(path): split_path = path.split(".") if split_path[-1] == "gz": lang = split_path[-2] with tf.io.gfile.GFile(path) as f, gzip.GzipFile(fileobj=f) as g: return g.read().split("\n"), l...
[ "Returns examples from parallel SGML or text files, which may be gzipped.", "Returns the sentences from a single text file, which may be gzipped.", "Returns sentences from a single SGML file." ]
Please provide a description of the function:def _parse_tmx(path): def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language not found in `tuv` attributes.") def _get_tuv_seg(tuv): segs = tuv.findall("seg") assert len(segs) == ...
[ "Generates examples from TMX file." ]
Please provide a description of the function:def _parse_tsv(path, language_pair=None): if language_pair is None: lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])\.tsv", path) assert lang_match is not None, "Invalid TSV filename: %s" % path l1, l2 = lang_match.groups() else: l1, l2 = language...
[ "Generates examples from TSV file." ]
Please provide a description of the function:def _parse_wikiheadlines(path): lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])$", path) assert lang_match is not None, "Invalid Wikiheadlines filename: %s" % path l1, l2 = lang_match.groups() with tf.io.gfile.GFile(path) as f: for line in f: s1, s...
[ "Generates examples from Wikiheadlines dataset file." ]
Please provide a description of the function:def _parse_czeng(*paths, **kwargs): filter_path = kwargs.get("filter_path", None) if filter_path: re_block = re.compile(r"^[^-]+-b(\d+)-\d\d[tde]") with tf.io.gfile.GFile(filter_path) as f: bad_blocks = { blk for blk in re.search( ...
[ "Generates examples from CzEng v1.6, with optional filtering for v1.7." ]
Please provide a description of the function:def _inject_language(self, src, strings): if src not in self.sources: raise ValueError("Invalid source for '{0}': {1}".format(self.name, src)) def _format_string(s): if "{0}" in s and "{1}" and "{src}" in s: return s.format(*sorted([src, self...
[ "Injects languages into (potentially) template strings." ]
Please provide a description of the function:def subsets(self): source, target = self.builder_config.language_pair filtered_subsets = {} for split, ss_names in self._subsets.items(): filtered_subsets[split] = [] for ss_name in ss_names: ds = DATASET_MAP[ss_name] if ds.target...
[ "Subsets that make up each split of the dataset for the language pair." ]
Please provide a description of the function:def _generate_examples(self, split_subsets, extraction_map): source, _ = self.builder_config.language_pair def _get_local_paths(ds, extract_dirs): rel_paths = ds.get_path(source) if len(extract_dirs) == 1: extract_dirs = extract_dirs * len(r...
[ "Returns the examples in the raw (text) form." ]
Please provide a description of the function:def builder(name, **builder_init_kwargs): name, builder_kwargs = _dataset_name_and_kwargs_from_name_str(name) builder_kwargs.update(builder_init_kwargs) if name in _ABSTRACT_DATASET_REGISTRY: raise DatasetNotFoundError(name, is_abstract=True) if name in _IN_DE...
[ "Fetches a `tfds.core.DatasetBuilder` by string name.\n\n Args:\n name: `str`, the registered name of the `DatasetBuilder` (the snake case\n version of the class name). This can be either `\"dataset_name\"` or\n `\"dataset_name/config_name\"` for datasets with `BuilderConfig`s.\n As a convenience...
Please provide a description of the function:def load(name, split=None, data_dir=None, batch_size=1, download=True, as_supervised=False, with_info=False, builder_kwargs=None, download_and_prepare_kwargs=None, as_dataset_kwargs=None, ...
[ "Loads the named dataset into a `tf.data.Dataset`.\n\n If `split=None` (the default), returns all splits for the dataset. Otherwise,\n returns the specified split.\n\n `load` is a convenience method that fetches the `tfds.core.DatasetBuilder` by\n string name, optionally calls `DatasetBuilder.download_and_prepa...
Please provide a description of the function:def _dataset_name_and_kwargs_from_name_str(name_str): res = _NAME_REG.match(name_str) if not res: raise ValueError(_NAME_STR_ERR.format(name_str)) name = res.group("dataset_name") kwargs = _kwargs_str_to_kwargs(res.group("kwargs")) try: for attr in ["con...
[ "Extract kwargs from name str." ]
Please provide a description of the function:def _cast_to_pod(val): bools = {"True": True, "False": False} if val in bools: return bools[val] try: return int(val) except ValueError: try: return float(val) except ValueError: return tf.compat.as_text(val)
[ "Try cast to int, float, bool, str, in that order." ]
Please provide a description of the function:def _try_import(module_name): try: mod = importlib.import_module(module_name) return mod except ImportError: err_msg = ("Tried importing %s but failed. See setup.py extras_require. " "The dataset you are trying to use may have additional " ...
[ "Try importing a module, with an informative error message on failure." ]
Please provide a description of the function:def np_to_list(elem): if isinstance(elem, list): return elem elif isinstance(elem, tuple): return list(elem) elif isinstance(elem, np.ndarray): return list(elem) else: raise ValueError( 'Input elements of a sequence should be either a numpy...
[ "Returns list from list, tuple or ndarray." ]
Please provide a description of the function:def _transpose_dict_list(dict_list): # 1. Unstack numpy arrays into list dict_list = utils.map_nested(np_to_list, dict_list, dict_only=True) # 2. Extract the sequence length (and ensure the length is constant for all # elements) length = {'value': None} # dict...
[ "Transpose a nested dict[list] into a list[nested dict]." ]
Please provide a description of the function:def get_tensor_info(self): # Add the additional length dimension to every shape def add_length_dim(tensor_info): return feature_lib.TensorInfo( shape=(self._length,) + tensor_info.shape, dtype=tensor_info.dtype, ) tensor_inf...
[ "See base class for details." ]
Please provide a description of the function:def get_serialized_info(self): # Add the additional length dimension to every serialized features def add_length_dim(serialized_info): if isinstance(serialized_info, tf.io.FixedLenFeature): if self._length is not None: return tf.i...
[ "See base class for details.", "Add the length dimension to the serialized_info.\n\n Args:\n serialized_info: One of tf.io.FixedLenFeature, tf.io.VarLenFeature,...\n\n Returns:\n new_serialized_info: serialized_info with extended first dimension\n " ]
Please provide a description of the function:def _split_generators(self, dl_manager): # Download the full MNIST Database filenames = { "train_data": _MNIST_TRAIN_DATA_FILENAME, "train_labels": _MNIST_TRAIN_LABELS_FILENAME, "test_data": _MNIST_TEST_DATA_FILENAME, "test_labels...
[ "Returns SplitGenerators." ]
Please provide a description of the function:def _generate_examples(self, num_examples, data_path, label_path): images = _extract_mnist_images(data_path, num_examples) labels = _extract_mnist_labels(label_path, num_examples) data = list(zip(images, labels)) # Data is shuffled automatically to dist...
[ "Generate MNIST examples as dicts.\n\n Args:\n num_examples (int): The number of example.\n data_path (str): Path to the data files\n label_path (str): Path to the labels\n\n Yields:\n Generator yielding the next examples\n " ]
Please provide a description of the function:def _split_generators(self, dl_manager): # Download images and annotations that come in separate archives. # Note, that the extension of archives is .tar.gz even though the actual # archives format is uncompressed tar. dl_paths = dl_manager.download_and_...
[ "Returns SplitGenerators." ]
Please provide a description of the function:def _generate_examples(self, images_dir_path, labels_path, setid_path, split_name): with tf.io.gfile.GFile(labels_path, "rb") as f: labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0] with tf.io.gfile.GFile(setid_path,...
[ "Yields examples." ]
Please provide a description of the function:def get_dataset_feature_statistics(builder, split): statistics = statistics_pb2.DatasetFeatureStatistics() # Make this to the best of our abilities. schema = schema_pb2.Schema() dataset = builder.as_dataset(split=split) # Just computing the number of examples...
[ "Calculate statistics for the specified split." ]
Please provide a description of the function:def read_from_json(json_filename): with tf.io.gfile.GFile(json_filename) as f: dataset_info_json_str = f.read() # Parse it back into a proto. parsed_proto = json_format.Parse(dataset_info_json_str, dataset_info_pb2.DatasetInfo(...
[ "Read JSON-formatted proto into DatasetInfo proto." ]
Please provide a description of the function:def full_name(self): names = [self._builder.name] if self._builder.builder_config: names.append(self._builder.builder_config.name) names.append(str(self.version)) return posixpath.join(*names)
[ "Full canonical name: (<dataset_name>/<config_name>/<version>)." ]
Please provide a description of the function:def update_splits_if_different(self, split_dict): assert isinstance(split_dict, splits_lib.SplitDict) # If splits are already defined and identical, then we do not update if self._splits and splits_lib.check_splits_equals( self._splits, split_dict):...
[ "Overwrite the splits if they are different from the current ones.\n\n * If splits aren't already defined or different (ex: different number of\n shards), then the new split dict is used. This will trigger stats\n computation during download_and_prepare.\n * If splits are already defined in DatasetI...
Please provide a description of the function:def _set_splits(self, split_dict): # Update the dictionary representation. # Use from/to proto for a clean copy self._splits = split_dict.copy() # Update the proto del self.as_proto.splits[:] # Clear previous for split_info in split_dict.to_pro...
[ "Split setter (private method)." ]
Please provide a description of the function:def _compute_dynamic_properties(self, builder): # Fill other things by going over the dataset. splits = self.splits for split_info in utils.tqdm( splits.values(), desc="Computing statistics...", unit=" split"): try: split_name = split_i...
[ "Update from the DatasetBuilder." ]
Please provide a description of the function:def write_to_directory(self, dataset_info_dir): # Save the metadata from the features (vocabulary, labels,...) if self.features: self.features.save_metadata(dataset_info_dir) if self.redistribution_info.license: with tf.io.gfile.GFile(self._lice...
[ "Write `DatasetInfo` as JSON to `dataset_info_dir`." ]
Please provide a description of the function:def read_from_directory(self, dataset_info_dir): if not dataset_info_dir: raise ValueError( "Calling read_from_directory with undefined dataset_info_dir.") json_filename = self._dataset_info_filename(dataset_info_dir) # Load the metadata fr...
[ "Update DatasetInfo from the JSON file in `dataset_info_dir`.\n\n This function updates all the dynamically generated fields (num_examples,\n hash, time of creation,...) of the DatasetInfo.\n\n This will overwrite all previous metadata.\n\n Args:\n dataset_info_dir: `str` The directory containing t...
Please provide a description of the function:def initialize_from_bucket(self): # In order to support Colab, we use the HTTP GCS API to access the metadata # files. They are copied locally and then loaded. tmp_dir = tempfile.mkdtemp("tfds") data_files = gcs_utils.gcs_dataset_info_files(self.full_nam...
[ "Initialize DatasetInfo from GCS bucket info files." ]
Please provide a description of the function:def _split_generators(self, dl_manager): url = _DL_URLS[self.builder_config.name] data_dirs = dl_manager.download_and_extract(url) path_to_dataset = os.path.join(data_dirs, tf.io.gfile.listdir(data_dirs)[0]) train_a_path = os.path.join(path_to_dataset,...
[ "Returns SplitGenerators." ]
Please provide a description of the function:def _map_promise(map_fn, all_inputs): all_promises = utils.map_nested(map_fn, all_inputs) # Apply the function res = utils.map_nested(_wait_on_promise, all_promises) return res
[ "Map the function into each element and resolve the promise." ]
Please provide a description of the function:def _handle_download_result(self, resource, tmp_dir_path, sha256, dl_size): fnames = tf.io.gfile.listdir(tmp_dir_path) if len(fnames) > 1: raise AssertionError('More than one file in %s.' % tmp_dir_path) original_fname = fnames[0] tmp_path = os.pat...
[ "Store dled file to definitive place, write INFO file, return path." ]
Please provide a description of the function:def _download(self, resource): if isinstance(resource, six.string_types): resource = resource_lib.Resource(url=resource) url = resource.url if url in self._sizes_checksums: expected_sha256 = self._sizes_checksums[url][1] download_path = sel...
[ "Download resource, returns Promise->path to downloaded file." ]
Please provide a description of the function:def _extract(self, resource): if isinstance(resource, six.string_types): resource = resource_lib.Resource(path=resource) path = resource.path extract_method = resource.extract_method if extract_method == resource_lib.ExtractMethod.NO_EXTRACT: ...
[ "Extract a single archive, returns Promise->path to extraction result." ]
Please provide a description of the function:def _download_extract(self, resource): if isinstance(resource, six.string_types): resource = resource_lib.Resource(url=resource) def callback(path): resource.path = path return self._extract(resource) return self._download(resource).then(ca...
[ "Download-extract `Resource` or url, returns Promise->path." ]