code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Get the token from headers token = headers.get( current_app.config['OAUTH2SERVER_JWT_AUTH_HEADER'] ) if token is None: raise JWTInvalidHeaderError # Get authentication type authentication_type = \ current_app.config['OAUTH2SERVER_JWT_AUTH_HEADER_TYPE'] # Check ...
def jwt_verify_token(headers)
Verify the JWT token. :param dict headers: The request headers. :returns: The token data. :rtype: dict
3.586654
3.585214
1.000402
@wraps(f) def decorated(*args, **kwargs): try: return f(*args, **kwargs) except OAuth2Error as e: # Only FatalClientError are handled by Flask-OAuthlib (as these # errors should not be redirect back to the client - see # http://tools.ietf.org/...
def error_handler(f)
Handle uncaught OAuth errors.
3.334861
3.29591
1.011818
if request.method == 'GET': client = Client.query.filter_by( client_id=kwargs.get('client_id') ).first() if not client: abort(404) scopes = current_oauth2server.scopes ctx = dict( client=client, oauth_request=kwargs.get('...
def authorize(*args, **kwargs)
View for rendering authorization request.
3.227767
2.952043
1.093401
client = Client.query.filter_by( client_id=request.form.get('client_id') ).first() if not client: abort(404) if not client.is_confidential and \ 'client_credentials' == request.form.get('grant_type'): error = InvalidClientError() response = jsonify(dict...
def access_token()
Token view handles exchange/refresh access tokens.
4.759147
4.651922
1.023049
from oauthlib.oauth2.rfc6749.errors import raise_from_error try: error = None raise_from_error(request.values.get('error'), params=dict()) except OAuth2Error as raised: error = raised return render_template('invenio_oauth2server/errors.html', error=error)
def errors()
Error view in case of invalid oauth requests.
5.177835
4.851165
1.067339
if current_app.testing or current_app.debug: return jsonify(dict( user=request.oauth.user.id, client=request.oauth.client.client_id, scopes=list(request.oauth.scopes) )) else: abort(404)
def info()
Test to verify that you have been authenticated.
3.582469
3.778151
0.948207
if max_key_period <= 0 or (key_period is not None and key_period <= 0): raise ValueError("Period values must be positive integers") original_text = ciphertext # Make the assumption that non alphabet characters have not been encrypted # TODO: This is fairly poor code. Once languages are a t...
def crack(ciphertext, *fitness_functions, key_period=None, max_key_period=30)
Break ``ciphertext`` by finding (or using the given) key_period then breaking ``key_period`` many Caesar ciphers. Example: >>> decryptions = crack("OMSTV", fitness.ChiSquared(analysis.frequency.english.unigrams)) >>> print(decryptions[0]) HELLO Args: ciphertext (str): The text ...
5.531583
5.325016
1.038792
if max_key_period <= 0: raise ValueError("max_key_period must be a positive integer") key_scores = [] for period in range(1, min(max_key_period, len(ciphertext)) + 1): score = abs(ENGLISH_IC - index_of_coincidence(*split_columns(ciphertext, period))) key_scores.append((period, ...
def key_periods(ciphertext, max_key_period)
Rank all key periods for ``ciphertext`` up to and including ``max_key_period`` Example: >>> key_periods(ciphertext, 30) [2, 4, 8, 3, ...] Args: ciphertext (str): The text to analyze max_key_period (int): The maximum period the key could be Returns: Sorted list of k...
3.308677
3.386987
0.976879
index = 0 decrypted = "" for char in ciphertext: if char in string.punctuation + string.whitespace + string.digits: decrypted += char continue # Not part of the decryption # Rotate character by the alphabet position of the letter in the key alphabet = s...
def decrypt(key, ciphertext)
Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: >>> decrypt("KEY", "RIJVS") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted ciphertext
4.517299
4.924773
0.91726
# Where do we start? Build options in starts which has entries # that are a pair comprised of the uri and a list of acceptable # capabilities starts = [] if (self.sitemap_name is not None): print("Starting from explicit --sitemap %s" % (self.sitemap_name)) ...
def explore(self)
INTERACTIVE exploration source capabilities. Will use sitemap URI taken either from explicit self.sitemap_name or derived from the mappings supplied.
5.640933
5.381121
1.048282
uri = explorer_resource.uri caps = explorer_resource.acceptable_capabilities checks = explorer_resource.checks print("Reading %s" % (uri)) options = {} capability = None try: if (caps == 'resource'): # Not expecting a capabilit...
def explore_uri(self, explorer_resource, show_back=True)
INTERACTIVE exploration of capabilities document(s) starting at a given URI. Will flag warnings if the document is not of type listed in caps.
5.026712
5.004785
1.004381
num_entries = len(list.resources) capability = '(unknown capability)' if ('capability' in list.md): capability = list.md['capability'] if (index): capability += 'index' print( "Parsed %s document with %d entries:" % (capabi...
def explore_show_summary(self, list, index=False, expected=None, context=None)
Show summary of one capability document. Given a capability document or index (in list, index True if it is an index), write out a simply textual summary of the document with all related documents shown as numbered options (of the form [#] ...description...) which will then form a menu ...
2.989237
2.907015
1.028284
print("HEAD %s" % (uri)) if (re.match(r'^\w+:', uri)): # Looks like a URI response = requests.head(uri) else: # Mock up response if we have a local file response = self.head_on_file(uri) print(" status: %s" % (response.status_code...
def explore_show_head(self, uri, check_headers=None)
Do HEAD on uri and show infomation. Will also check headers against any values specified in check_headers.
3.20177
3.119894
1.026243
response = HeadResponse() if (not os.path.isfile(file)): response.status_code = '404' else: response.status_code = '200' response.headers[ 'last-modified'] = datetime_to_str(os.path.getmtime(file)) response.headers['content...
def head_on_file(self, file)
Mock up requests.head(..) response on local file.
2.650711
2.401746
1.10366
index = re.match(r'(.+)index$', capability) archive = re.match(r'(.+)\-archive$', capability) if (capability == 'capabilitylistindex'): return([]) # not allowed so no valid references elif (index): return([index.group(1)]) # name without index ending ...
def allowed_entries(self, capability)
Return list of allowed entries for given capability document. Includes handling of capability = *index where the only acceptable entries are *.
4.661934
4.416872
1.055483
full_uri = urljoin(context, uri) if (full_uri != uri): print(" WARNING - expanded relative URI to %s" % (full_uri)) uri = full_uri return(uri)
def expand_relative_uri(self, context, uri)
If uri is relative then expand in context. Prints warning if expansion happens.
4.649115
4.511644
1.03047
outputs = [] best_score = -float('inf') for step in range(nsteps): next_node, score, output = get_next_node(copy.deepcopy(start_node)) # Keep track of best score and the start node becomes finish node if score > best_score: start_node = copy.deepcopy(next_node) ...
def hill_climb(nsteps, start_node, get_next_node)
Modular hill climbing algorithm. Example: >>> def get_next_node(node): ... a, b = random.sample(range(len(node)), 2) ... node[a], node[b] = node[b], node[a] ... plaintext = decrypt(node, ciphertext) ... score = lantern.score(plaintext, *fitness_functions) ...
3.377187
3.17972
1.062102
'''scan_models High-level api: Download models from the device by <get-schema> operation defined in RFC6022, and analyze dependencies among models using pyang package. Parameters ---------- folder : `str` A path to a folder that stores YANG files do...
def scan_models(self, folder='./yang', download='check')
scan_models High-level api: Download models from the device by <get-schema> operation defined in RFC6022, and analyze dependencies among models using pyang package. Parameters ---------- folder : `str` A path to a folder that stores YANG files downloaded. ...
6.828726
1.307261
5.223691
'''load_model High-level api: Load schema information by compiling the model using pyang package. Parameters ---------- model : `str` Model name. Returns ------- Model An instance of Model. YAML Example:: ...
def load_model(self, model)
load_model High-level api: Load schema information by compiling the model using pyang package. Parameters ---------- model : `str` Model name. Returns ------- Model An instance of Model. YAML Example:: de...
4.651848
1.875367
2.4805
'''take_notification High-level api: Receive notification messages. Parameters ---------- block : `bool` True if this is a blocking call. timeout : `int` Timeout value in seconds. Returns ------- Notification ...
def take_notification(self, block=True, timeout=None)
take_notification High-level api: Receive notification messages. Parameters ---------- block : `bool` True if this is a blocking call. timeout : `int` Timeout value in seconds. Returns ------- Notification An insta...
5.467219
2.317799
2.358798
'''extract_config High-level api: Extract config from a rpc-reply of get-config or get message. Parameters ---------- reply : `RPCReply` An instance of RPCReply in ncclient package. It has to be a successful reply in order to extract config, sin...
def extract_config(self, reply, type='netconf')
extract_config High-level api: Extract config from a rpc-reply of get-config or get message. Parameters ---------- reply : `RPCReply` An instance of RPCReply in ncclient package. It has to be a successful reply in order to extract config, since there is...
4.186968
1.553703
2.694831
'''get_xpath High-level api: Given a config or schema node, get_xpath returns an xpath of the node, which starts from the model root. Each identifier uses the `prefix:tagname` notation if argument 'type' is not specified. Parameters ---------- node : `Element` ...
def get_xpath(self, node, type=Tag.XPATH, instance=True)
get_xpath High-level api: Given a config or schema node, get_xpath returns an xpath of the node, which starts from the model root. Each identifier uses the `prefix:tagname` notation if argument 'type' is not specified. Parameters ---------- node : `Element` ...
4.883867
1.244952
3.922936
'''_get_ns Low-level api: Return a dict of nsmap. Parameters ---------- reply : `Element` rpc-reply as an instance of Element. Returns ------- dict A dict of nsmap. ''' def get_prefix(url): if url i...
def _get_ns(self, reply)
_get_ns Low-level api: Return a dict of nsmap. Parameters ---------- reply : `Element` rpc-reply as an instance of Element. Returns ------- dict A dict of nsmap.
4.132007
2.879601
1.434923
kwargs.setdefault('type', 'checkbox') field_id = kwargs.pop('id', field.id) html = [u'<div class="row">'] for value, label, checked in field.iter_choices(): choice_id = u'%s-%s' % (field_id, value) options = dict( kwargs, name=field.name, value...
def scopes_multi_checkbox(field, **kwargs)
Render multi checkbox widget.
2.33689
2.24368
1.041543
if valuelist: self.data = '\n'.join([ x.strip() for x in filter(lambda x: x, '\n'.join(valuelist).splitlines()) ])
def process_formdata(self, valuelist)
Process form data.
3.695034
3.62467
1.019412
if isinstance(value, six.text_type): value = value.split("\n") value = [v.strip() for v in value] for v in value: validate_redirect_uri(v) self._redirect_uris = "\n".join(value) or ""
def redirect_uris(self, value)
Validate and store redirect URIs for client.
2.951242
2.724939
1.083049
validate_scopes(scopes) self._default_scopes = " ".join(set(scopes)) if scopes else ""
def default_scopes(self, scopes)
Set default scopes for client.
6.68985
5.773371
1.158743
no_users = Token.query.filter_by( client_id=self.client_id, is_personal=False, is_internal=False ).count() return no_users
def get_users(self)
Get number of users.
5.157036
4.412611
1.168704
validate_scopes(scopes) self._scopes = " ".join(set(scopes)) if scopes else ""
def scopes(self, scopes)
Set scopes. :param scopes: The list of scopes.
6.810543
8.290714
0.821466
return [k for k, s in current_oauth2server.scope_choices() if k in self.scopes]
def get_visible_scopes(self)
Get list of non-internal scopes for token. :returns: A list of scopes.
18.026581
20.893339
0.862791
with db.session.begin_nested(): scopes = " ".join(scopes) if scopes else "" c = Client( name=name, user_id=user_id, is_internal=True, is_confidential=False, _default_scopes=scopes ) ...
def create_personal(cls, name, user_id, scopes=None, is_internal=False)
Create a personal access token. A token that is bound to a specific user and which doesn't expire, i.e. similar to the concept of an API key. :param name: Client name. :param user_id: User ID. :param scopes: The list of permitted scopes. (Default: ``None``) :param is_in...
2.976742
2.960312
1.00555
sch, netloc, path, par, query, fra = urlparse(value) if not (sch and netloc): raise InvalidRedirectURIError() if sch != 'https': if ':' in netloc: netloc, port = netloc.split(':', 1) if not (netloc in ('localhost', '127.0.0.1') and sch == 'http'): raise I...
def validate_redirect_uri(value)
Validate a redirect URI. Redirect URIs must be a valid URL and use https unless the host is localhost for which http is accepted. :param value: The redirect URI.
4.234406
4.604397
0.919644
for value in value_list: if value not in current_oauth2server.scopes: raise ScopeDoesNotExists(value) return True
def validate_scopes(value_list)
Validate if each element in a list is a registered scope. :param value_list: The list of scopes. :raises invenio_oauth2server.errors.ScopeDoesNotExists: The exception is raised if a scope is not registered. :returns: ``True`` if it's successfully validated.
7.181033
3.984628
1.802184
'''Open a subprocess in another working directory Raises ValueError if system binary does not exist Raises CalledProcessError if the return code is non-zero :returns: list of standard output and standard error from subprocess :param args: a list of command line arguments for subprocess :param...
def check_output_cwd(args, cwd, timeout=None)
Open a subprocess in another working directory Raises ValueError if system binary does not exist Raises CalledProcessError if the return code is non-zero :returns: list of standard output and standard error from subprocess :param args: a list of command line arguments for subprocess :param cwd: t...
3.328337
2.078353
1.60143
try: interpretations = translate(u(otp)) except Exception: return otp if len(interpretations) == 0: return otp elif len(interpretations) > 1: # If there are multiple interpretations first try to use the same # translat...
def get_otp_modehex_interpretation(self, otp)
Return modhex interpretation of the provided OTP. If there are multiple interpretations available, first one is used, because if the OTP uses all 16 characters in its alphabet there is only one possible interpretation of that OTP. :return: Modhex interpretation of the OTP. :rty...
5.076257
5.030579
1.00908
def shift_case_sensitive(shift, symbol): case = [case for case in alphabet if symbol in case] if not case: return symbol case = case[0] index = case.index(symbol) return case[(index - shift) % len(case)] return shift_case_sensitive
def make_shift_function(alphabet)
Construct a shift function from an alphabet. Examples: Shift cases independently >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase]) <function make_shift_function.<locals>.shift_case_sensitive> Additionally shift punctuation characters >>> make_shift...
4.074748
3.030574
1.344547
if min_key >= max_key: raise ValueError("min_key cannot exceed max_key") decryptions = [] for key in range(min_key, max_key): plaintext = decrypt(key, ciphertext, shift_function=shift_function) decryptions.append(Decryption(plaintext, key, score(plaintext, *fitness_functions)))...
def crack(ciphertext, *fitness_functions, min_key=0, max_key=26, shift_function=shift_case_english)
Break ``ciphertext`` by enumerating keys between ``min_key`` and ``max_key``. Example: >>> decryptions = crack("KHOOR", fitness.english.quadgrams) >>> print(''.join(decryptions[0].plaintext)) HELLO Args: ciphertext (iterable): The symbols to decrypt *fitness_functions (...
2.547051
2.512198
1.013873
return [shift_function(key, symbol) for symbol in ciphertext]
def decrypt(key, ciphertext, shift_function=shift_case_english)
Decrypt Shift enciphered ``ciphertext`` using ``key``. Examples: >>> ''.join(decrypt(3, "KHOOR")) HELLO >> decrypt(15, [0xcf, 0x9e, 0xaf, 0xe0], shift_bytes) [0xde, 0xad, 0xbe, 0xef] Args: key (int): The shift to use ciphertext (iterable): The symbols to decryp...
7.685854
8.557566
0.898136
'''taobao.trade.ordersku.update 更新交易订单的销售属性 需要商家或以上权限才可调用此接口,可重复调用本接口更新交易备注,本接口同时具有添加备注的功能''' request = TOPRequest('taobao.trade.ordersku.update') request['oid'] = oid if sku_id!=None: request['sku_id'] = sku_id if sku_props!=None: request['sku_props'] = sku_prop...
def ordersku_update(self, oid, sku_id=None, sku_props=None)
taobao.trade.ordersku.update 更新交易订单的销售属性 需要商家或以上权限才可调用此接口,可重复调用本接口更新交易备注,本接口同时具有添加备注的功能
6.416385
2.154496
2.978138
'''taobao.topats.result.get 获取异步任务结果 使用指南:http://open.taobao.com/doc/detail.htm?id=30 - 1.此接口用于获取异步任务处理的结果,传入的task_id必需属于当前的appKey才可以 - 2.此接口只返回执行完成的任务结果,未执行完的返回结果里面不包含任务结果,只有任务id,执行状态 - 3.执行完成的每个task的子任务结果内容与单个任务的结果结构一致。如:taobao.topats.trades.fullinfo.get返回的...
def get(self, task_id)
taobao.topats.result.get 获取异步任务结果 使用指南:http://open.taobao.com/doc/detail.htm?id=30 - 1.此接口用于获取异步任务处理的结果,传入的task_id必需属于当前的appKey才可以 - 2.此接口只返回执行完成的任务结果,未执行完的返回结果里面不包含任务结果,只有任务id,执行状态 - 3.执行完成的每个task的子任务结果内容与单个任务的结果结构一致。如:taobao.topats.trades.fullinfo.get返回的子任务结果就会是Tra...
11.417255
1.638358
6.968719
'''taobao.topats.trade.accountreport.get 异步获取淘宝卖家绑定的支付宝账户的财务明细 - 1.提供异步下载用户支付宝对账信息接口 - 2.一次调用最多支持下载3个月的对账信息 - 3.仅能获取2010年6月10日以后的信息 - 4.提交任务会进行初步任务校验,如果成功会返回任务号和创建时间,如果失败就报错 - 5.可以接收淘宝发出的任务完成消息,也可以过一段时间来取结果。获取结果接口为taobao.topats.result.get - 6.支付宝证书签名...
def accountreport_get(self, start_created, end_created, session, fields=[])
taobao.topats.trade.accountreport.get 异步获取淘宝卖家绑定的支付宝账户的财务明细 - 1.提供异步下载用户支付宝对账信息接口 - 2.一次调用最多支持下载3个月的对账信息 - 3.仅能获取2010年6月10日以后的信息 - 4.提交任务会进行初步任务校验,如果成功会返回任务号和创建时间,如果失败就报错 - 5.可以接收淘宝发出的任务完成消息,也可以过一段时间来取结果。获取结果接口为taobao.topats.result.get - 6.支付宝证书签名方法见文档:“http...
8.274885
1.356097
6.101987
'''taobao.topats.trades.fullinfo.get 异步批量获取交易订单详情api 使用指南:http://open.taobao.com/dev/index.php/ATS%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97 - 1.提供异步批量获取订单详情功能 - 2.一次调用最多支持40个订单 - 3.提交任务会进行初步任务校验,如果成功会返回任务号和创建时间,如果失败就报错 - 4.可以接收淘宝发出的任务完成消息,也可以过一段时间来取结果。获取结果接口为taoba...
def fullinfo_get(self, tids, session, fields=[])
taobao.topats.trades.fullinfo.get 异步批量获取交易订单详情api 使用指南:http://open.taobao.com/dev/index.php/ATS%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97 - 1.提供异步批量获取订单详情功能 - 2.一次调用最多支持40个订单 - 3.提交任务会进行初步任务校验,如果成功会返回任务号和创建时间,如果失败就报错 - 4.可以接收淘宝发出的任务完成消息,也可以过一段时间来取结果。获取结果接口为taobao.topats.re...
9.793569
1.610991
6.079219
'''taobao.trade.close 卖家关闭一笔交易 关闭一笔订单,可以是主订单或子订单。''' request = TOPRequest('taobao.trade.close') request['tid'] = tid request['close_reason'] = close_reason self.create(self.execute(request, session)['trade']) return self
def close(self, tid, close_reason, session)
taobao.trade.close 卖家关闭一笔交易 关闭一笔订单,可以是主订单或子订单。
6.478471
3.035936
2.133929
'''taobao.trade.fullinfo.get 获取单笔交易的详细信息 获取单笔交易的详细信息 - 1.只有在交易成功的状态下才能取到交易佣金,其它状态下取到的都是零或空值 - 2.只有单笔订单的情况下Trade数据结构中才包含商品相关的信息 - 3.获取到的Order中的payment字段在单笔子订单时包含物流费用,多笔子订单时不包含物流费用 注:包含以下字段的返回会增加TOP的后台压力,请仅在确实需要的情况下才去获取:commission_fee, buyer_alipay_no, seller_a...
def fullinfo_get(self, tid, session, fields=[])
taobao.trade.fullinfo.get 获取单笔交易的详细信息 获取单笔交易的详细信息 - 1.只有在交易成功的状态下才能取到交易佣金,其它状态下取到的都是零或空值 - 2.只有单笔订单的情况下Trade数据结构中才包含商品相关的信息 - 3.获取到的Order中的payment字段在单笔子订单时包含物流费用,多笔子订单时不包含物流费用 注:包含以下字段的返回会增加TOP的后台压力,请仅在确实需要的情况下才去获取:commission_fee, buyer_alipay_no, seller_alipay_no, b...
10.41239
1.526187
6.822484
'''taobao.trade.memo.add 对一笔交易添加备注 根据登录用户的身份(买家或卖家),自动添加相应的交易备注,不能重复调用些接口添加备注,需要更新备注请用taobao.trade.memo.update''' request = TOPRequest('taobao.trade.memo.add') request['tid'] = tid request['memo'] = memo if flag!=None: request['flag'] = flag self.create(s...
def memo_add(self, tid, memo, session, flag=None)
taobao.trade.memo.add 对一笔交易添加备注 根据登录用户的身份(买家或卖家),自动添加相应的交易备注,不能重复调用些接口添加备注,需要更新备注请用taobao.trade.memo.update
7.764633
2.350355
3.3036
'''taobao.trade.memo.update 修改一笔交易备注 需要商家或以上权限才可调用此接口,可重复调用本接口更新交易备注,本接口同时具有添加备注的功能''' request = TOPRequest('taobao.trade.memo.update') request['tid'] = tid if memo!=None: request['memo'] = memo if flag!=None: request['flag'] = flag if reset!=None: reques...
def memo_update(self, tid, session, memo=None, flag=None, reset=None)
taobao.trade.memo.update 修改一笔交易备注 需要商家或以上权限才可调用此接口,可重复调用本接口更新交易备注,本接口同时具有添加备注的功能
5.553218
2.285017
2.430274
'''taobao.trade.postage.update 修改订单邮费价格 修改订单邮费接口,通过传入订单编号和邮费价格,修改订单的邮费,返回修改时间modified,邮费post_fee,总费用total_fee。''' request = TOPRequest('taobao.trade.postage.update') request['tid'] = tid request['post_fee'] = post_fee self.create(self.execute(request, session)['t...
def postage_update(self, tid, post_fee, session)
taobao.trade.postage.update 修改订单邮费价格 修改订单邮费接口,通过传入订单编号和邮费价格,修改订单的邮费,返回修改时间modified,邮费post_fee,总费用total_fee。
6.94481
2.365814
2.935484
'''taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间''' request = TOPRequest('taobao.trade.receivetime.delay') request['tid'] = tid request['days'] = days self.create(self.execute(request, session)['trade']) return self
def receivetime_delay(self, tid, days, session)
taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间
5.293673
3.248456
1.629597
'''taobao.trade.shippingaddress.update 更改交易的收货地址''' request = TOPRequest('taobao.trade.shippingaddress.update') request['tid'] = tid for k, v in kwargs.iteritems(): if k not in ('receiver_name','receiver_phone','receiver_mobile','receiver_state','receiver_city','receiver_dist...
def shippingaddress_update(self, tid, session, **kwargs)
taobao.trade.shippingaddress.update 更改交易的收货地址
3.767579
3.086282
1.22075
'''taobao.trades.bought.get 搜索当前会话用户作为买家达成的交易记录 搜索当前会话用户作为买家达成的交易记录(目前只能查询三个月以内的订单)''' request = TOPRequest('taobao.trades.bought.get') if not fields: trade = Trade() fields = trade.fields request['fields'] = fields for k, v in kwargs.iter...
def bought_get(self, session, fields=[], **kwargs)
taobao.trades.bought.get 搜索当前会话用户作为买家达成的交易记录 搜索当前会话用户作为买家达成的交易记录(目前只能查询三个月以内的订单)
5.313999
3.045733
1.744736
'''taobao.trade.confirmfee.get 获取交易确认收货费用 获取交易确认收货费用 可以获取主订单或子订单的确认收货费用''' request = TOPRequest('taobao.trade.confirmfee.get') request['tid'] = tid request['is_detail'] = is_detail self.create(self.execute(request, session)['trade_confirm_fee']) return se...
def get(self, tid, is_detail, session)
taobao.trade.confirmfee.get 获取交易确认收货费用 获取交易确认收货费用 可以获取主订单或子订单的确认收货费用
5.544245
2.531546
2.190063
collector = [] if isinstance(headers, dict): headers = headers.items() elif isinstance(headers, basestring): return headers for i, (value, params) in enumerate(headers): _params = [] for (p_k, p_v) in params.items(): _params.append('%s=%s' % (p_k, ...
def header_expand(headers)
Returns an HTTP Header value string from a dictionary. Example expansion:: {'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}} # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c (('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {})) ...
3.13232
2.821407
1.110198
# Use /dev/urandom if it is available. Fall back to random module # if not. It might be worthwhile to extend this function to use # other platform-specific mechanisms for getting random bytes. if os.path.exists("/dev/urandom"): f = open("/dev/urandom") s = f.read(n) f.clos...
def randombytes(n)
Return n random bytes.
3.207695
3.189513
1.0057
cookie_dict = {} for _, cookies in cj._cookies.items(): for _, cookies in cookies.items(): for cookie in cookies.values(): # print cookie cookie_dict[cookie.name] = cookie.value return cookie_dict
def dict_from_cookiejar(cj)
Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from.
3.054619
3.299971
0.92565
# return cookiejar if one was passed in if isinstance(cookie_dict, cookielib.CookieJar): return cookie_dict # create cookiejar cj = cookielib.CookieJar() cj = add_dict_to_cookiejar(cj, cookie_dict) return cj
def cookiejar_from_dict(cookie_dict)
Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar.
3.142382
3.407554
0.922181
for k, v in cookie_dict.items(): cookie = cookielib.Cookie( version=0, name=k, value=v, port=None, port_specified=False, domain='', domain_specified=False, domain_initial_dot=False, path='/', ...
def add_dict_to_cookiejar(cj, cookie_dict)
Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar.
1.467061
1.513837
0.969101
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) return charset_re.findall(content)
def get_encodings_from_content(content)
Returns encodings from given content string. :param content: bytestring to extract encodings from.
4.922645
4.862911
1.012284
content_type = headers.get('content-type') if not content_type: return None content_type, params = cgi.parse_header(content_type) if 'charset' in params: return params['charset'].strip("'\"")
def get_encoding_from_headers(headers)
Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from.
1.995364
2.104453
0.948163
encodings = get_encodings_from_content(content) for encoding in encodings: try: return unicode(content, encoding) except (UnicodeError, TypeError): pass return content
def unicode_from_html(content)
Attempts to decode an HTML string into unicode. If unsuccessful, the original content is returned.
4.141567
3.476078
1.191448
encoding = get_encoding_from_headers(r.headers) if encoding is None: for item in iterator: yield item return decoder = codecs.getincrementaldecoder(encoding)(errors='replace') for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv ...
def stream_decode_response_unicode(iterator, r)
Stream decodes a iterator.
2.438233
2.44206
0.998433
try: dec = zlib.decompressobj(16 + zlib.MAX_WBITS) for chunk in iterator: rv = dec.decompress(chunk) if rv: yield rv buf = dec.decompress('') rv = buf + dec.flush() if rv: yield rv except zlib.error: pass
def stream_decode_gzip(iterator)
Stream decodes a gzip-encoded iterator
2.726488
2.908273
0.937494
with open(filename, 'rb') as fh: self.app_key = fh.read()
def load_application_key_file(self, filename=b'spotify_appkey.key')
Load your libspotify application key file. If called without arguments, it tries to read ``spotify_appkey.key`` from the current working directory. This is an alternative to setting :attr:`application_key` yourself. The file must be a binary key file, not the C code key file that can b...
3.085135
4.818808
0.640228
c = data['output'] word_space = c.text_width( ' ', font_name=self.font_name, font_size=self.font_size) # Arrange the text as words on lines self._layout = [[]] x = self.font_size if self.paragraph_indent else 0 for word in sel...
def _do_layout(self, data)
Lays the text out into separate lines and calculates their total height.
3.156225
3.100807
1.017872
def build(resp): response = Response() # Pass settings over. response.config = self.config if resp: # Fallback to None if there's no staus_code, for whatever reason. response.status_code = getattr(resp, 'status', None...
def _build_response(self, resp, is_error=False)
Build internal :class:`Response <Response>` object from given response.
3.354563
3.328239
1.007909
if hasattr(data, '__iter__'): data = dict(data) if hasattr(data, 'items'): result = [] for k, vs in data.items(): for v in isinstance(vs, list) and vs or [vs]: result.append((k.encode('utf-8') if isinstance(k, unicode) el...
def _encode_params(data)
Encode parameters in a piece of data. If the data supplied is a dictionary, encodes each parameter in it, and returns a list of tuples containing the encoded parameters, and a urlencoded version of that. Otherwise, assumes the data is already encoded appropriately, and returns ...
2.475463
2.194111
1.128231
if not self.url: raise URLRequired() # Support for unicode domain names and paths. scheme, netloc, path, params, query, fragment = urlparse(self.url) if not scheme: raise ValueError() netloc = netloc.encode('idna') if isinstance(path,...
def full_url(self)
Build the actual URL to use.
2.802119
2.640514
1.061202
url = [] p = urlsplit(self.full_url) # Proxies use full URLs. if p.scheme in self.proxies: return self.full_url path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.a...
def path_url(self)
Build the path URL to use.
3.84858
3.542792
1.086313
# Logging if self.config.get('verbose'): self.config.get('verbose').write('%s %s %s\n' % ( datetime.now().isoformat(), self.method, self.url )) # Build the URL url = self.full_url # Nottin' on you. body = None ...
def send(self, anyway=False, prefetch=False)
Sends the request. Returns True of successful, false if not. If there was an HTTPError during transmission, self.response.status_code will contain the HTTPError code. Once a request is successfully sent, `sent` will equal True. :param anyway: If True, request will be sent, even if it h...
3.405957
3.342112
1.019103
if self._content_consumed: raise RuntimeError( 'The content for this response was already consumed' ) def generate(): while 1: chunk = self.raw.read(chunk_size) if not chunk: break ...
def iter_content(self, chunk_size=10 * 1024, decode_unicode=None)
Iterates over the response data. This avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
2.505619
2.477579
1.011317
if self._content is not None: return self._content if self._content_consumed: raise RuntimeError('The content for this response was ' 'already consumed') # Read the contents. try: self._content = self.raw.read...
def content(self)
Content of the response, in bytes or unicode (if available).
3.555805
3.065202
1.160056
if self.error: raise self.error if (self.status_code >= 300) and (self.status_code < 400): raise HTTPError('%s Redirection' % self.status_code) elif (self.status_code >= 400) and (self.status_code < 500): raise HTTPError('%s Client Error' % self.st...
def raise_for_status(self)
Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred.
1.738725
1.617947
1.074649
if isinstance(fileobj, int): fd = fileobj else: try: fd = fileobj.fileno() except AttributeError: fd = None if fd is None or fd < 0: raise ValueError("invalid fileobj: {!r}".format(fileobj)) return fd
def _get_fd(fileobj)
Get a descriptor out of a file object. :param fileobj: An integer (existing descriptor) or any object having the `fileno()` method. :raises ValueError: if the descriptor cannot be obtained or if the descriptor is invalid :returns: file descriptor number
2.175118
2.4662
0.881971
self = cls() if epoll_events & select.EPOLLIN: self |= EVENT_READ if epoll_events & select.EPOLLOUT: self |= EVENT_WRITE # Treat EPOLLHUP specially, as both 'read and write ready' so that on # the outside this can be interpreted as EOF if ...
def from_epoll_events(cls, epoll_events)
Create a :class:`_EpollSelectorEvents` instance out of a bit mask using ``EPOLL*`` family of constants.
4.301046
4.380165
0.981937
epoll_events = 0 if self & EVENT_READ: epoll_events |= select.EPOLLIN if self & EVENT_WRITE: epoll_events |= select.EPOLLOUT return epoll_events
def get_epoll_events(self)
Create a bit mask using ``EPOLL*`` family of constants.
3.032279
2.586087
1.172536
fd = _get_fd(fileobj) key = self._fd_map[fd] try: self._epoll.unregister(fd) except OSError: pass del self._fd_map[fd] return key
def unregister(self, fileobj)
Remove interest in IO events from the specified fileobj :param fileobj: Any existing file-like object that has a fileno() method and was previously registered with :meth:`register()` :raises ValueError: if `fileobj` is invalid or not supported :raises KeyErro...
3.551091
3.316174
1.07084
fd = _get_fd(fileobj) epoll_events = _EpollSelectorEvents(events).get_epoll_events() if fd not in self._fd_map: raise KeyError("{!r} is not registered".format(fileobj)) key = SelectorKey(fileobj, fd, events, data) self._fd_map[fd] = key self._epoll.mo...
def modify(self, fileobj, events, data=None)
Modify interest in specified IO events on the specified file object :param fileobj: Any existing file-like object that has a fileno() method :param events: A bitmask composed of EVENT_READ and EVENT_WRITE :param data: (optional) Arbitrary data :raises...
3.787964
3.271226
1.157964
if timeout is None: epoll_timeout = -1 elif timeout <= 0: epoll_timeout = 0 else: epoll_timeout = timeout max_events = len(self._fd_map) or -1 result = [] for fd, epoll_events in self._epoll.poll(epoll_timeout, max_events): ...
def select(self, timeout=None)
Wait until one or more of the registered file objects becomes ready or until the timeout expires. :param timeout: maximum wait time, in seconds (see below for special meaning) :returns: A list of pairs (key, events) for each ready file object. Note that the ...
3.298856
3.208418
1.028188
'''xxxxx.xxxxx.campaign.budget.update =================================== 更新一个推广计划的日限额''' request = TOPRequest('xxxxx.xxxxx.campaign.budget.update') request['campaign_id'] = campaign_id request['budget'] = budget if nick!=None: request['nick'] = nick self....
def update(self, campaign_id, budget, nick=None)
xxxxx.xxxxx.campaign.budget.update =================================== 更新一个推广计划的日限额
7.018483
4.291572
1.635411
'''xxxxx.xxxxx.campaign.area.get =================================== 取得一个推广计划的投放地域设置''' request = TOPRequest('xxxxx.xxxxx.campaign.area.get') request['campaign_id'] = campaign_id if nick!=None: request['nick'] = nick self.create(self.execute(request), fields=['suc...
def get(self, campaign_id, nick=None)
xxxxx.xxxxx.campaign.area.get =================================== 取得一个推广计划的投放地域设置
9.312572
4.508883
2.065383
'''xxxxx.xxxxx.campaign.area.update =================================== 更新一个推广计划的投放地域''' request = TOPRequest('xxxxx.xxxxx.campaign.area.update') request['campaign_id'] = campaign_id request['area'] = area if nick!=None: request['nick'] = nick self.create(...
def update(self, campaign_id, area, nick=None)
xxxxx.xxxxx.campaign.area.update =================================== 更新一个推广计划的投放地域
7.232886
4.278975
1.690332
'''xxxxx.xxxxx.campaign.schedule.update =================================== 更新一个推广计划的分时折扣设置''' request = TOPRequest('xxxxx.xxxxx.campaign.schedule.update') request['campaign_id'] = campaign_id request['schedule'] = schedule if nick!=None: request['nick'] = nick ...
def update(self, campaign_id, schedule, nick=None)
xxxxx.xxxxx.campaign.schedule.update =================================== 更新一个推广计划的分时折扣设置
7.09986
4.266777
1.663987
'''xxxxx.xxxxx.adgroup.catmatch.get =================================== 取得一个推广组的类目出价''' request = TOPRequest('xxxxx.xxxxx.adgroup.catmatch.get') request['adgroup_id'] = adgroup_id if nick!=None: request['nick'] = nick self.create(self.execute(request), fields=['su...
def get(self, adgroup_id, nick=None)
xxxxx.xxxxx.adgroup.catmatch.get =================================== 取得一个推广组的类目出价
9.648772
4.558857
2.116489
'''xxxxx.xxxxx.adgroup.catmatch.update =================================== 更新一个推广组的类目出价,可以设置类目出价、是否使用默认出价、是否打开类目出价''' request = TOPRequest('xxxxx.xxxxx.adgroup.catmatch.update') request['adgroup_id'] = adgroup_id request['catmatch_id'] = catmatch_id request['max_p...
def update(self, adgroup_id, catmatch_id, max_price, is_default_price, online_status, nick=None)
xxxxx.xxxxx.adgroup.catmatch.update =================================== 更新一个推广组的类目出价,可以设置类目出价、是否使用默认出价、是否打开类目出价
4.554386
2.59249
1.756761
'''xxxxx.xxxxx.creative.add =================================== 创建一个创意''' request = TOPRequest('xxxxx.xxxxx.creative.add') request['adgroup_id'] = adgroup_id request['title'] = title request['img_url'] = img_url if nick!=None: request['nick'] = nick ...
def add(self, adgroup_id, title, img_url, nick=None)
xxxxx.xxxxx.creative.add =================================== 创建一个创意
6.431486
4.470941
1.438508
'''xxxxx.xxxxx.creative.delete =================================== 删除一个创意''' request = TOPRequest('xxxxx.xxxxx.creative.delete') request['creative_id'] = creative_id if nick!=None: request['nick'] = nick self.create(self.execute(request), fields=['success','result...
def delete(self, creative_id, nick=None)
xxxxx.xxxxx.creative.delete =================================== 删除一个创意
8.587074
5.896492
1.456302
'''xxxxx.xxxxx.creative.update =================================== 更新一个创意的信息,可以设置创意标题、创意图片''' request = TOPRequest('xxxxx.xxxxx.creative.update') request['adgroup_id'] = adgroup_id request['creative_id'] = creative_id request['title'] = title request['img_...
def update(self, adgroup_id, creative_id, title, img_url, nick=None)
xxxxx.xxxxx.creative.update =================================== 更新一个创意的信息,可以设置创意标题、创意图片
5.604256
3.88801
1.44142
'''xxxxx.xxxxx.campaign.areaoptions.get =================================== 取得推广计划的可设置投放地域列表''' request = TOPRequest('xxxxx.xxxxx.campaign.areaoptions.get') self.create(self.execute(request), fields=['success','result'], models={'result':AreaOption}) return self.result
def get(self)
xxxxx.xxxxx.campaign.areaoptions.get =================================== 取得推广计划的可设置投放地域列表
18.435572
5.405674
3.410412
'''xxxxx.xxxxx.adgroup.add =================================== 创建一个推广组''' request = TOPRequest('xxxxx.xxxxx.adgroup.add') request['campaign_id'] = campaign_id request['item_id'] = item_id request['default_price'] = default_price request['title'] = title ...
def add(self, campaign_id, item_id, default_price, title, img_url, nick=None)
xxxxx.xxxxx.adgroup.add =================================== 创建一个推广组
4.851042
3.369798
1.439565
'''xxxxx.xxxxx.adgroup.delete =================================== 删除一个推广组''' request = TOPRequest('xxxxx.xxxxx.adgroup.delete') request['group_id'] = group_id if nick!=None: request['nick'] = nick self.create(self.execute(request), fields=['success','result','succ...
def delete(self, group_id, nick=None)
xxxxx.xxxxx.adgroup.delete =================================== 删除一个推广组
9.341125
5.560804
1.679816
'''xxxxx.xxxxx.adgroup.update =================================== 更新一个推广组的信息,可以设置默认出价、是否上线、非搜索出价、非搜索是否使用默认出价''' request = TOPRequest('xxxxx.xxxxx.adgroup.update') request['adgroup_id'] = adgroup_id request['default_price'] = default_price request['nonsearch_max_pr...
def update(self, adgroup_id, default_price, nonsearch_max_price, is_nonsearch_default_price, online_status, campaign_id, nick=None)
xxxxx.xxxxx.adgroup.update =================================== 更新一个推广组的信息,可以设置默认出价、是否上线、非搜索出价、非搜索是否使用默认出价
3.892216
2.318902
1.678474
'''xxxxx.xxxxx.campaign.add =================================== 创建一个推广计划''' request = TOPRequest('xxxxx.xxxxx.campaign.add') request['title'] = title if nick!=None: request['nick'] = nick self.create(self.execute(request), fields=['success','result','success','res...
def add(self, title, nick=None)
xxxxx.xxxxx.campaign.add =================================== 创建一个推广计划
9.76318
5.549593
1.759261
'''xxxxx.xxxxx.campaign.update =================================== 更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。''' request = TOPRequest('xxxxx.xxxxx.campaign.update') request['campaign_id'] = campaign_id request['title'] = title request['is_smooth'] = is_smoot...
def update(self, campaign_id, title, is_smooth, online_status, nick=None)
xxxxx.xxxxx.campaign.update =================================== 更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。
6.437406
2.91272
2.210101
'''xxxxx.xxxxx.campaign.platform.update =================================== 取得一个推广计划的投放平台设置''' request = TOPRequest('xxxxx.xxxxx.campaign.platform.update') request['campaign_id'] = campaign_id request['search_channels'] = search_channels request['nonsearch_channel...
def update(self, campaign_id, search_channels, nonsearch_channels, outside_discount, nick=None)
xxxxx.xxxxx.campaign.platform.update =================================== 取得一个推广计划的投放平台设置
5.329232
3.165592
1.683487
username = utils.to_char(username) if password is not None: password = utils.to_char(password) spotifyconnect.Error.maybe_raise( lib.SpConnectionLoginPassword( username, password)) elif blob is not None: blob = ut...
def login(self, username, password=None, blob=None, zeroconf=None)
Authenticate to Spotify's servers. You can login with one of three combinations: - ``username`` and ``password`` - ``username`` and ``blob`` - ``username`` and ``zeroconf`` To get the ``blob`` string, you must once log in with ``username`` and ``password``. You'll then...
3.013553
3.072951
0.980671
assert spotifyconnect._session_instance.player.num_listeners( spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0 spotifyconnect._session_instance.player.on( spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
def on(self)
Turn on the alsa_sink sink. This is done automatically when the sink is instantiated, so you'll only need to call this method if you ever call :meth:`off` and want to turn the sink back on.
5.778327
5.571159
1.037186
spotifyconnect._session_instance.player.off( spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery) assert spotifyconnect._session_instance.player.num_listeners( spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0 self._close()
def off(self)
Turn off the alsa_sink sink. This disconnects the sink from the relevant session events.
5.553879
4.864926
1.141616
def wrapped(*args, **kwargs): kwargs['return_response'] = False kwargs['prefetch'] = True return f(*args, **kwargs) return wrapped
def patched(f)
Patches a given API function to not send.
5.348074
5.058585
1.057227
if pools: r._pools = pools r.send() return r.response
def send(r, pools=None)
Sends a given Request object.
8.856324
7.6807
1.153062
if size: pool = Pool(size) pool.map(send, requests) pool.join() else: jobs = [gevent.spawn(send, r) for r in requests] gevent.joinall(jobs) if prefetch: [r.response.content for r in requests] return [r.response for r in requests]
def map(requests, prefetch=True, size=None)
Concurrently converts a list of Requests to Responses. :param requests: a collection of Request objects. :param prefetch: If False, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. If None, no throttling occurs.
2.867425
2.957675
0.969486
'''taobao.time.get 获取前台展示的店铺类目 获取淘宝系统当前时间''' request = TOPRequest('taobao.time.get') self.create(self.execute(request)) return self.time
def get(self)
taobao.time.get 获取前台展示的店铺类目 获取淘宝系统当前时间
19.688562
4.818975
4.085632