code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if self.debuglevel > 1: print(datetime.datetime.now().time(), *args, file=sys.stderr) else: print(*args, file=sys.stderr)
def _print_debug(self, *args)
Method output debug message into stderr :param args: Message(s) to output :rtype args: string
3.015681
3.282613
0.918683
if not port and (host.find(':') == host.rfind(':')): i = host.rfind(':') if i >= 0: host, port = host[:i], host[i + 1:] try: port = int(port) except ValueError: raise OSError('nonnumeric port...
def _parse_host(cls, host='localhost', port=0)
Parse provided hostname and extract port number :param host: Server hostname :type host: string :param port: Server port :return: Tuple of (host, port) :rtype: tuple
2.974134
3.06102
0.971616
if proxy_type not in socks.DEFAULT_PORTS.keys(): raise NotSupportedProxyType (proxy_host, proxy_port) = self._parse_host(host=proxy_host, port=proxy_port) if not proxy_port: proxy_port = socks.DEFAULT_PORTS[proxy_type] (host, port) = self._parse_host(host...
def connect_proxy(self, proxy_host='localhost', proxy_port=0, proxy_type=socks.HTTP, host='localhost', port=0)
Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__...
2.902182
2.960702
0.980234
if self._status == self.SR_UNSUPPORTED: return False status = c_int() try: prctl(PR_GET_CHILD_SUBREAPER, addressof(status), 0, 0, 0) except OSError: self._status = self.SR_UNSUPPORTED else: self._status = self.SR_ENABLED if...
def enabled(self)
read or write the child sub-reaper flag of the current process This property behaves in the following manner: * If a read is attempted and a prior read or write has determined that this feature is unavailable (status is equal to ``SR_UNSUPPORTED``) then no further attempts are made...
4.117805
2.501801
1.645937
''' Generate API sign code ''' for k, v in params.iteritems(): if type(v) == int: v = str(v) elif type(v) == float: v = '%.2f'%v elif type(v) in (list, set): v = ','.join([str(i) for i in v]) elif type(v) == bool: v = 'true...
def _sign(self,params)
Generate API sign code
2.432326
2.207355
1.101919
''' pyTOP.API -- TOPRequest instance ''' params = { 'app_key' : self.API_KEY, 'v' : self.API_VERSION, 'format' : self.FORMAT, #'sign_method' : self.SIGN_METHOD, 'partner_id' : self.SDK_VERSON } api_para...
def execute(self, request, session=None, method='post')
pyTOP.API -- TOPRequest instance
3.241415
2.881765
1.124802
''' Create model attributes ''' if not fields: fields = self.fields if not models and hasattr(self, 'models'): models = self.models for field in fields: setattr(self,field,None) if not data: return None for k, v in data.iteritems(): ...
def create(self, data, fields=[], models={})
Create model attributes
2.468588
2.348849
1.050978
size = self.element.get_minimum_size(data) if self.angle in (RotateLM.NORMAL, RotateLM.UPSIDE_DOWN): return size else: return datatypes.Point(size.y, size.x)
def get_minimum_size(self, data)
Returns the rotated minimum size.
6.591451
5.404496
1.219624
hw = size.x * 0.5 hh = size.y * 0.5 a = datatypes.Point(hw, hh).get_rotated(self.angle) b = datatypes.Point(-hw, hh).get_rotated(self.angle) c = datatypes.Point(hw, -hh).get_rotated(self.angle) d = datatypes.Point(-hw, -hh).get_rotated(self.angle) minp ...
def _calculate_ms_from_base(self, size)
Calculates the rotated minimum size from the given base minimum size.
2.048517
1.975808
1.0368
# read the attribute attr = getattr(self.context, name, None) if callable(attr): return attr() return attr
def get(self, name)
Get a JSON compatible structure for the named attribute
5.57197
5.838398
0.954366
value = self.get(name) if value is Missing.Value: return default return value
def json_data(self, name, default=None)
Get a JSON compatible value of the field
8.818462
7.816208
1.128228
# check read permission sm = getSecurityManager() permission = permissions.View if not sm.checkPermission(permission, self.context): raise Unauthorized("Not allowed to view the Plone portal") # read the attribute attr = getattr(self.context, name, N...
def get(self, name)
Get the value by name
6.636106
6.550649
1.013046
# check write permission sm = getSecurityManager() permission = permissions.ManagePortal if not sm.checkPermission(permission, self.context): raise Unauthorized("Not allowed to modify the Plone portal") # set the attribute if not hasattr(self.contex...
def set(self, name, value, **kw)
Set the attribute to the given value. The keyword arguments represent the other attribute values to integrate constraints to other values.
5.169102
5.538042
0.933381
# fetch the field by name field = api.get_field(self.context, name) # bail out if we have no field if not field: return False # call the field adapter and set the value fieldmanager = IFieldManager(field) return fieldmanager.set(self.contex...
def set(self, name, value, **kw)
Set the field to the given value. The keyword arguments represent the other field values to integrate constraints to other values.
5.434254
5.386216
1.008919
# Check the write permission of the context # XXX: This should be done on field level by the field manager adapter if not self.can_write(): raise Unauthorized("You are not allowed to modify this content") # fetch the field by name field = api.get_field(self...
def json_data(self, name)
Get a JSON compatible structure for the named attribute
6.715064
6.543678
1.026191
sm = getSecurityManager() permission = permissions.ModifyPortalContent if not sm.checkPermission(permission, self.context): return False return True
def can_write(self)
Check if the field is writeable
7.335457
6.860956
1.06916
sm = getSecurityManager() if not sm.checkPermission(permissions.View, self.context): return False return True
def can_read(self)
Check if the field is readable
6.792542
6.335775
1.072093
return url_xsd response = urllib2.urlopen(url_xsd) content = response.read() cached = NamedTemporaryFile(delete=False) named = cached.name # Find all urls in the main xslt file. urls = re.findall(r'href=[\'"]?([^\'" >]+)', content) # mapping in the...
def send_s3_xsd(self, url_xsd): # pragma: no cover if self.check_s3(self.domain, urlparse(url_xsd).path[1:])
This method will not be re-run always, only locally and when xsd are regenerated, read the test_008_force_s3_creation on test folder
3.579764
3.536448
1.012249
s3.meta.client.head_bucket(Bucket=bucket) except ClientError: # If the bucket does not exists then simply use the original # I silently fail returning everything as it is in the url return False try: # If the key does not exists do not return F...
def check_s3(self, bucket, element): # pragma: no cover session = boto3.Session(profile_name=self.profile_name) s3 = session.resource('s3') try
This method is a helper con `cache_s3`. Read method `cache_s3` for more information. :param bucket: :param element: :return:
9.186372
9.859312
0.931746
# https://docs.python.org/3/glossary.html#term-eafp. # # The Coverage was excluded in order to avoid decrease it because an # unused tool. url_parsed = urlparse(url) if self.domain == urlparse(url).netloc: # If I am asking for the same domain it is probably be...
def cache_s3(self, url, named): # pragma: no cover # **Technical Notes:** # # Even if the tries are looking nested, this is perfect valid for # this case
Basically this is not to deploy automatically this is to be run once all is properly defined to catch the xsd in your own S3 instance and avoid third party (like government servers) failure, trying to manage the cache transparently to the user. This method was created due to SAT is too ...
6.261867
6.223701
1.006132
# TODO: Use directly the file object instead of the name of the file # with seek(0) cached = self._cache_it(url) if not isfile(cached.name): # If /tmp files are deleted self._cache_it.cache_clear() cached = self._cache_it(url) re...
def cache_it(self, url)
Take an url which deliver a plain document and convert it to a temporary file, this document is an xslt file expecting contains all xslt definitions, then the cache process is recursive. :param url: document origin url :type url: str :return file_path: local new absolute path ...
7.164944
7.930907
0.90342
dom = etree.parse(document) # TODO: cuando este probando - # fuente: # http://stackoverflow.com/questions/16698935/how-to-transform-an-xml-file-using-xslt-in-python xslt = etree.parse(xslt) transform = etree.XSLT(xslt) newdom = transform(dom) return newd...
def get_original(document, xslt)
Get the original chain given document path and xslt local path :param str document: local absolute path to document :param str xslt: local absolute path to xst file :return: new chain generated. :rtype: str
4.248685
4.482195
0.947903
with self._close_lock: sfd = self._sfd if sfd >= 0: self._sfd = -1 self._signals = frozenset() close(sfd)
def close(self)
Close the internal signalfd file descriptor if it isn't closed :raises OSError: If the underlying ``close(2)`` fails. The error message matches those found in the manual page.
5.443119
5.017713
1.084781
if fd < 0: _err_closed() self = cls.__new__() object.__init__(self) self._sfd = fd self._signals = signals return self
def fromfd(cls, fd, signals)
Create a new signalfd object from a given file descriptor :param fd: A pre-made file descriptor obtained from ``signalfd_create(2)` :param signals: A pre-made frozenset that describes the monitored signals :raises ValueError: If fd is not a valid file descrip...
5.616792
9.360916
0.600026
if self._sfd < 0: _err_closed() mask = sigset_t() sigemptyset(mask) if signals is not None: for signal in signals: sigaddset(mask, signal) # flags are ignored when sfd is not -1 _signalfd(self._sfd, mask, 0) self._s...
def update(self, signals)
Update the mask of signals this signalfd reacts to :param signals: A replacement set of signal numbers to monitor :raises ValueError: If :meth:`closed()` is True
7.680634
6.348043
1.209921
if maxsignals is None: maxsignals = len(self._signals) if maxsignals <= 0: raise ValueError("maxsignals must be greater than 0") info_list = (signalfd_siginfo * maxsignals)() num_read = read(self._sfd, byref(info_list), sizeof(info_list)) return i...
def read(self, maxsignals=None)
Read information about currently pending signals. :param maxsignals: Maximum number of signals to read. By default this is the same as the number of signals registered with this signalfd. :returns: A list of signalfd_siginfo object with information about most ...
3.981694
3.074253
1.295174
self.draft.set_curie(self, name, href) return self
def add_curie(self, name, href)
Adds a CURIE definition. A CURIE link with the given ``name`` and ``href`` is added to the document. This method returns self, allowing it to be chained with additional method calls.
9.990437
15.022451
0.665034
if isinstance(target, bytes): target = target.decode('utf-8') if isinstance(target, str) or isinstance(target, unicode): new_link = dict(href=target, **kwargs) else: new_link = dict(href=target.url(), **kwargs) self._add_rel('_links', rel, ne...
def add_link(self, rel, target, wrap=False, **kwargs)
Adds a link to the document. This method adds a link to the given ``target`` to the document with the given ``rel``. If one or more links are already present for that link relationship type, the new link will be added to the existing links for that link relationship type. Unlik...
2.786876
3.254708
0.85626
new_embed = target.as_object() self._add_rel('_embedded', rel, new_embed, wrap) if self.draft.automatic_link: self.add_link(rel, target, wrap) return self
def embed(self, rel, target, wrap=False)
Embeds a document inside this document. This method embeds the given document in this document with the given ``rel``. If one or more documents have already been embedded for that ``rel``, the new document will be embedded in addition to those documents. This method returns sel...
9.406843
10.878998
0.864679
self.o.setdefault(key, {}) if wrap: self.o[key].setdefault(rel, []) if rel not in self.o[key]: self.o[key][rel] = thing return existing = self.o[key].get(rel) if isinstance(existing, list): existing.append(thing) ...
def _add_rel(self, key, rel, thing, wrap)
Adds ``thing`` to links or embedded resources. Calling code should not use this method directly and should use ``embed`` or ``add_link`` instead.
2.250814
2.372043
0.948893
about_info = wx.adv.AboutDialogInfo() for k, v in metadata.items(): setattr(about_info, snake2ucamel(k), v) wx.adv.AboutBox(about_info)
def about_box()
A simple about dialog box using the distribution data files.
5.383661
5.073297
1.061176
try: self.client = Client(self.url) except ValueError as e: self.message = e.message except URLError: self.message = 'The url you provided: ' + \ '%s could not be reached' % self.url
def sign(self, xml_doc)
Sign the document with a third party signatory. :param str xml_doc: Document self signed in plain xml :returns answer: Answer is given from the signatory itself if connected.
5.356897
5.83482
0.918091
hooks = hooks or dict() if key in hooks: try: return hooks.get(key).__call__(hook_data) or hook_data except Exception, why: warnings.warn(str(why)) return hook_data
def dispatch_hook(key, hooks, hook_data)
Dispatches a hook dictionary on a given piece of data.
4.522657
4.141545
1.092022
if not HAS_PLONE_PROTECT: logger.warn( "Can not disable CSRF protection – please install plone.protect" ) return False request = get_request() interface.alsoProvides(request, IDisableCSRFProtection) return True
def disable_csrf_protection()
disables the CSRF protection https://pypi.python.org/pypi/plone.protect
8.878215
6.671134
1.33084
data = get_form() or get_query_string() return data.get(key, default)
def get(key, default=None)
return the key from the request
7.463659
7.269756
1.026673
value = get(key, default) if isinstance(value, list): value = value[0] if isinstance(value, bool): return value if value is default: return default return value.lower() in TRUE_VALUES
def is_true(key, default=False)
Check if the value is in TRUE_VALUES
2.928447
2.491086
1.17557
limit = _.convert(get("sort_limit"), _.to_int) if (limit < 1): limit = None # catalog raises IndexError if limit < 1 return limit
def get_sort_limit()
returns the 'sort_limit' from the request
12.733753
13.484283
0.94434
sort_on = get("sort_on") if allowed_indexes and sort_on not in allowed_indexes: logger.warn("Index '{}' is not in allowed_indexes".format(sort_on)) return None return sort_on
def get_sort_on(allowed_indexes=None)
returns the 'sort_on' from the request
3.186167
2.990893
1.06529
q = get("q", "") qs = q.lstrip("*.!$%&/()=#-+:'`´^") if qs and not qs.endswith("*"): qs += "*" return qs
def get_query()
returns the 'query' from the request
12.739061
14.04614
0.906944
request = get_request() data = request.get("BODY", "{}") if not is_json_deserializable(data): from plone.jsonapi.routes.exceptions import APIError raise APIError(400, "Request Data is not JSON deserializable – Check JSON Syntax!") return _.convert(json.loads(data), _.to_list)
def get_request_data()
extract and convert the json data from the request returns a list of dictionaries
9.067343
10.5462
0.859773
data = get_json() data[key] = value request = get_request() request["BODY"] = json.dumps(data)
def set_json_item(key, value)
manipulate json data on the fly
5.533198
5.009186
1.10461
return self.request_encode_url('GET', url, fields=fields, **urlopen_kw)
def get_url(self, url, fields=None, **urlopen_kw)
.. deprecated:: 1.0 Use :meth:`request` instead.
6.547603
5.083311
1.288059
return self.request_encode_body('POST', url, fields=fields, headers=headers, **urlopen_kw)
def post_url(self, url, fields=None, headers=None, **urlopen_kw)
.. deprecated:: 1.0 Use :meth:`request` instead.
4.861234
4.26473
1.139869
if self._is_active: return if self._setmask: self._old_mask = sigset_t() sigemptyset(self._old_mask) self._do_mask(SIG_SETMASK, self._mask, self._old_mask) else: self._do_mask(SIG_BLOCK, self._mask, None) self._is_activ...
def block(self)
Use the masking function (``sigprocmask(2)`` or ``pthread_sigmask(3)``) to block signals. This method uses either ``SIG_SETMASK`` or ``SIG_BLOCK``, depending on how the object was constructed. After this method is called, the subsequent call to :meth:`unblock()` will undo its effects. ...
4.47491
3.3403
1.339673
if not self._is_active: return if self._setmask: if self._old_mask is None: raise ValueError("block() wasn't called yet!") self._do_mask(SIG_SETMASK, self._old_mask, None) self._old_mask = None else: self._do_ma...
def unblock(self)
Use the masking function (``sigprocmask(2)`` or ``pthread_sigmask(3)``) to unblock signals. :raises ValueError: If the old mask is not obtained yet. This only happens in when ``setmask=True`` was passed to the initializer and ``unblock()`` is called before ``block()`...
4.010685
2.889338
1.388098
mask = sigset_t() sigemptyset(mask) cls._do_mask(0, None, mask) signals = [] for sig_num in range(1, NSIG): if sigismember(mask, sig_num): signals.append(sig_num) self = cls(signals) self._is_active = True self._old_mas...
def get(cls)
Use the masking function (``sigprocmask(2)`` or ``pthread_sigmask(3)``) to obtain the mask of blocked signals :returns: A fresh :class:`sigprocmask` object. The returned object behaves as it was constructed with the list of currently blocked signals, ``setmask=False`` and a...
6.715613
6.032296
1.113276
bmp = wx.Bitmap.FromRGBA(width, height) # Mask color is #000000 dc = wx.MemoryDC(bmp) dc.Brush = wx.Brush((255,) * 3) # Any non-black would do dc.DrawRoundedRectangle(0, 0, width, height, radius) dc.SelectObject(wx.NullBitmap) bmp.SetMaskColour((0,) * 3) return wx.Region(bmp)
def rounded_rectangle_region(width, height, radius)
Returns a rounded rectangle wx.Region
3.97294
3.68503
1.07813
def decorator(func): @wraps(func) def wrapper(*args, **kwargs): wrapper.timer.cancel() # Debounce wrapper.timer = threading.Timer(lag, func, args=args, kwargs=kwargs) wrapper.timer.start() wrapper.timer = threading.Timer(0, lambda: None) # timer.cancel now exists return wrapper ...
def call_after(lag)
Parametrized decorator for calling a function after a time ``lag`` given in milliseconds. This cancels simultaneous calls.
3.424447
3.096042
1.106073
ctrl_is_down = wx.GetKeyState(wx.WXK_CONTROL) shift_is_down = wx.GetKeyState(wx.WXK_SHIFT) ms = wx.GetMouseState() new_pos = None # New initialization when keys pressed change if self._key_state != (ctrl_is_down, shift_is_down): self._key_state = (ctrl_is_down, shift_is_down) ...
def on_timer(self, evt)
Keep watching the mouse displacement via timer Needed since EVT_MOVE doesn't happen once the mouse gets outside the frame
3.210169
3.168028
1.013302
assert not self.watching def selector(evt): if evt.is_directory: return False path = evt.path if path in self._last_fnames: # Detected a "killing cycle" return False for pattern in self.skip_pattern.split(";"): if fnmatch(path, pattern.strip()): re...
def start(self)
Starts watching the path and running the test jobs.
6.275497
5.978528
1.049673
self.stop() # DoseWatcher if evt.EventObject is not self: # Avoid deadlocks self.Close() # wx.Frame evt.Skip()
def on_close(self, evt)
Pop-up menu and wx.EVT_CLOSE closing event
22.175173
18.180908
1.219696
def deco(fn): @wraps(fn) def _fn(self, *args, **kwargs): try: return fn(self, *args, **kwargs) finally: for cache_name in cache_names: setattr(self, cache_name, None) return _fn return deco
def mutator(*cache_names)
Decorator for ``Document`` methods that change the document. This decorator ensures that the object's caches are kept in sync when changes are made.
2.202711
2.456285
0.896765
if key.startswith('/'): return urlparse.urljoin(self.base_uri, key) else: return self.curies.expand(key)
def canonical_key(self, key)
Returns the canonical key for the given ``key``.
4.992363
4.770467
1.046515
if not 'self' in self.links: return None self_link = self.links['self'] if isinstance(self_link, list): for link in self_link: return link.url() return self_link.url()
def url(self)
Returns the URL for the resource based on the ``self`` link. This method returns the ``href`` of the document's ``self`` link if it has one, or ``None`` if the document lacks a ``self`` link, or the ``href`` of the document's first ``self`` link if it has more than one.
3.90127
3.013257
1.294702
if key in self.RESERVED_ATTRIBUTE_NAMES: return self.o[key] = value
def set_property(self, key, value)
Set a property on the document. Calling code should use this method to add and modify properties on the document instead of modifying ``properties`` directly. If ``key`` is ``"_links"`` or ``"_embedded"`` this method will silently fail. If there is no property with the name in...
9.481469
19.364538
0.489631
if key in self.RESERVED_ATTRIBUTE_NAMES: raise KeyError(key) del self.o[key]
def delete_property(self, key)
Remove a property from the document. Calling code should use this method to remove properties on the document instead of modifying ``properties`` directly. If there is a property with the name in ``key``, it will be removed. Otherwise, a ``KeyError`` will be thrown.
7.684146
11.044655
0.695734
return link.Link(dict(href=href, **kwargs), self.base_uri)
def link(self, href, **kwargs)
Retuns a new link relative to this resource.
9.675393
6.927184
1.396728
if hasattr(target, 'as_link'): link = target.as_link() else: link = self.link(target, **kwargs) links = self.o.setdefault(LINKS_KEY, {}) new_link = link.as_object() collected_links = CanonicalRels(links, self.curies, self.base_uri) if re...
def add_link(self, rel, target, wrap=False, **kwargs)
Adds a link to the document. Calling code should use this method to add links instead of modifying ``links`` directly. This method adds a link to the given ``target`` to the document with the given ``rel``. If one or more links are already present for that link relationship typ...
3.037492
3.178368
0.955677
if not LINKS_KEY in self.o: return links = self.o[LINKS_KEY] if rel is None: for rel in list(links.keys()): self.delete_link(rel, href) return if callable(href): href_filter = href else: href_f...
def delete_link(self, rel=None, href=lambda _: True)
Deletes links from the document. Calling code should use this method to remove links instead of modyfying ``links`` directly. The optional arguments, ``rel`` and ``href`` are used to select the links that will be deleted. If neither of the optional arguments are given, this met...
1.911991
1.99344
0.959142
if isinstance(o, list): return [cls.from_object(x, base_uri, parent_curies, draft) for x in o] return cls(o, base_uri, parent_curies, draft)
def from_object(cls, o, base_uri=None, parent_curies=None, draft=AUTO)
Returns a new ``Document`` based on a JSON object or array. Arguments: - ``o``: a dictionary holding the deserializated JSON for the new ``Document``, or a ``list`` of such documents. - ``base_uri``: optional URL used as the basis when expanding ...
2.109042
2.191388
0.962423
return cls.from_object({}, base_uri=base_uri, draft=draft)
def empty(cls, base_uri=None, draft=AUTO)
Returns an empty ``Document``. Arguments: - ``base_uri``: optional URL used as the basis when expanding relative URLs in the document. - ``draft``: a ``Draft`` instance that selects the version of the spec to which the document should conform...
4.868861
7.913281
0.615277
if other == self: return embedded = self.o.setdefault(EMBEDDED_KEY, {}) collected_embedded = CanonicalRels(embedded, self.curies, self.base_uri) if rel not in collected_embedded:...
def embed(self, rel, other, wrap=False)
Embeds a document inside this document. Arguments: - ``rel``: a string specifying the link relationship type of the embedded resource. ``rel`` should be a well-known link relation name from the IANA registry (http://www.iana.org/assignments/link-relations/link-relations.x...
3.756053
3.435554
1.093289
if EMBEDDED_KEY not in self.o: return if rel is None: for rel in list(self.o[EMBEDDED_KEY].keys()): self.delete_embedded(rel, href) return if rel not in self.o[EMBEDDED_KEY]: return if callable(href): ...
def delete_embedded(self, rel=None, href=lambda _: True)
Removes an embedded resource from this document. Calling code should use this method to remove embedded resources instead of modifying ``embedded`` directly. The optional arguments, ``rel`` and ``href`` are used to select the embedded resources that will be removed. If neither of the o...
1.758477
1.848832
0.951129
curies = self.o[LINKS_KEY][self.draft.curies_rel] if isinstance(curies, dict) and curies['name'] == name: del self.o[LINKS_KEY][self.draft.curies_rel] return for i, curie in enumerate(curies): if curie['name'] == name: del curies[i] ...
def drop_curie(self, name)
Removes a CURIE. The CURIE link with the given name is removed from the document.
3.835858
3.731411
1.027991
'''taobao.increment.customer.permit 开通增量消息服务 提供app为自己的用户开通增量消息服务功能''' request = TOPRequest('taobao.increment.customer.permit') self.create(self.execute(request, session), fields=['app_customer',], models={'app_customer':AppCustomer}) return self.app_customer
def customer_permit(self, session)
taobao.increment.customer.permit 开通增量消息服务 提供app为自己的用户开通增量消息服务功能
14.132775
5.022372
2.813964
'''taobao.increment.customer.stop 关闭用户的增量消息服务 供应用关闭其用户的增量消息服务功能,这样可以节省ISV的流量。''' request = TOPRequest('taobao.increment.customer.stop') request['nick'] = nick self.create(self.execute(request, session), fields=['is_success',]) return self.is_success
def customer_stop(self, nick, session)
taobao.increment.customer.stop 关闭用户的增量消息服务 供应用关闭其用户的增量消息服务功能,这样可以节省ISV的流量。
13.004842
3.202508
4.060831
'''taobao.increment.customers.get 查询应用为用户开通的增量消息服务 提供查询应用为自身用户所开通的增量消息服务信息。''' request = TOPRequest('taobao.increment.customers.get') request['page_no'] = page_no request['page_size'] = page_size if nicks!=None: request['nicks'] = nicks self.create(self.e...
def customers_get(self, session, page_no=1, page_size=10, nicks=None)
taobao.increment.customers.get 查询应用为用户开通的增量消息服务 提供查询应用为自身用户所开通的增量消息服务信息。
6.862436
3.179345
2.158443
'''taobao.increment.items.get 获取商品变更通知信息 开通主动通知业务的APP可以通过该接口获取商品变更通知信息 建议获取增量消息的时间间隔是:半个小时''' request = TOPRequest('taobao.increment.items.get') for k, v in kwargs.iteritems(): if k not in ('status', 'nick', 'start_modified', 'end_modified', 'page_no', 'page_size') a...
def items_get(self, **kwargs)
taobao.increment.items.get 获取商品变更通知信息 开通主动通知业务的APP可以通过该接口获取商品变更通知信息 建议获取增量消息的时间间隔是:半个小时
9.034426
3.937309
2.294569
'''taobao.increment.refunds.get 获取退款变更通知信息 开通主动通知业务的APP可以通过该接口获取用户的退款变更通知信息 建议在获取增量消息的时间间隔是:半个小时''' request = TOPRequest('taobao.increment.refunds.get') for k, v in kwargs.iteritems(): if k not in ('status', 'nick', 'start_modified', 'end_modified', 'page_no', 'page_...
def refunds_get(self, **kwargs)
taobao.increment.refunds.get 获取退款变更通知信息 开通主动通知业务的APP可以通过该接口获取用户的退款变更通知信息 建议在获取增量消息的时间间隔是:半个小时
8.95861
3.676267
2.436877
'''taobao.increment.trades.get 获取交易和评价变更通知信息 开通主动通知业务的APP可以通过该接口获取用户的交易和评价变更通知信息 建议在获取增量消息的时间间隔是:半个小时''' request = TOPRequest('taobao.increment.trades.get') for k, v in kwargs.iteritems(): if k not in ('status', 'nick', 'type', 'start_modified', 'end_modified', 'page...
def trades_get(self, **kwargs)
taobao.increment.trades.get 获取交易和评价变更通知信息 开通主动通知业务的APP可以通过该接口获取用户的交易和评价变更通知信息 建议在获取增量消息的时间间隔是:半个小时
8.763293
3.553632
2.46601
cigs = list(self.items()) new_cigs = [] c, cum_len = self.cigar, 0 for i, (l, op) in enumerate(cigs): if op in Cigar.read_consuming_ops: cum_len += l if op == "H": cum_len += l new_cigs.append(cigs[i]) ...
def mask_left(self, n_seq_bases, mask="S")
Return a new cigar with cigar string where the first `n_seq_bases` are soft-masked unless they are already hard-masked.
3.944573
3.758615
1.049475
return Cigar(Cigar(self._reverse_cigar()).mask_left(n_seq_bases, mask)._reverse_cigar())
def mask_right(self, n_seq_bases, mask="S")
Return a new cigar with cigar string where the last `n_seq_bases` are soft-masked unless they are already hard-masked.
7.856041
5.283983
1.486765
cigs = [] for op, grps in groupby(self.items(), itemgetter(1)): cigs.append((sum(g[0] for g in grps), op)) return Cigar(self.string_from_elements(cigs))
def merge_like_ops(self)
>>> Cigar("1S20M").merge_like_ops() Cigar('1S20M') >>> Cigar("1S1S20M").merge_like_ops() Cigar('2S20M') >>> Cigar("1S1S1S20M").merge_like_ops() Cigar('3S20M') >>> Cigar("1S1S1S20M1S1S").merge_like_ops() Cigar('3S20M2S')
6.649597
5.02061
1.32446
out = FlushStreamThread(process=process, stream_name="stdout", formatter=out_formatter, size=size) err = FlushStreamThread(process=process, stream_name="stderr", formatter=err_formatter, size=size) out.start() err.start() yield out, err ...
def flush_stream_threads(process, out_formatter=None, err_formatter=terminal.fg.red, size=1)
Context manager that creates 2 threads, one for each standard stream (stdout/stderr), updating in realtime the piped data. The formatters are callables that receives manipulates the data, e.g. coloring it before writing to a ``sys`` stream. See ``FlushStreamThread`` for more information.
2.011908
2.030084
0.991047
process = subprocess.Popen(test_command, bufsize=0, shell=True, cwd=work_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE) with flush_stream_threads(process): try: yield process finally: if process.poll...
def runner(test_command, work_dir=None)
Internal test job runner context manager. Run the test_command in a subprocess and instantiates 2 FlushStreamThread, one for each standard stream (output/stdout and error/stderr). It yields the subprocess.Popen instance that was spawned to run the given test command in the given working directory....
3.059815
3.084569
0.991975
while self.is_alive(): self.killed = True time.sleep(POLLING_DELAY) # "Was a process spawned?" polling if not self.spawned: continue # Either self.run returns or runner yields if self.process.poll() is None: # It's running ...
def kill(self, sig=signal.SIGTERM)
Terminate the test job. Kill the subprocess if it was spawned, abort the spawning process otherwise. This information can be collected afterwards by reading the self.killed and self.spawned flags. Also join the 3 related threads to the caller thread. This can be safely called f...
7.626537
7.857617
0.970592
if not issubclass(validator, CerberusValidator): raise TypeError( "Validator must be a subclass of more.cerberus.CerberusValidator" ) return partial(load, schema, validator, update)
def loader(schema, validator=CerberusValidator, update=None)
Create a load function based on schema dict and Validator class. :param schema: a Cerberus schema dict. :param validator: the validator class which must be a subclass of more.cerberus.CerberusValidator which is the default. :param update: will pass the update flag to the validator, when ``True`` ...
3.769654
3.209893
1.174386
n = len(symb.snode) # order of block Ncliques = len(symb.snpar) # number of cliques # compute clique orders dims = [symb.sncolptr[j+1]-symb.sncolptr[j] for j in range(Ncliques)] # compute offsets in block-diagonal structure offsets = [0] for i in range(Ncliques): off...
def symb_to_block(symb, coupling = 'full')
Maps a symbolic factorization to a block-diagonal structure with coupling constraints. :param symb: :py:class:`symbolic` :param coupling: optional :return dims: list of block dimensions :return sparse_to_block: dictionary :return constraints: list o...
2.789563
2.620895
1.064355
'''taobao.vas.order.search 订单记录导出 用于ISV查询自己名下的应用及收费项目的订单记录。目前所有应用调用此接口的频率限制为200次/分钟,即每分钟内,所有应用调用此接口的次数加起来最多为200次。''' request = TOPRequest('taobao.vas.order.search') request['article_code'] = article_code for k, v in kwargs.iteritems(): if k not in ('item_code...
def order_search(self, article_code, **kwargs)
taobao.vas.order.search 订单记录导出 用于ISV查询自己名下的应用及收费项目的订单记录。目前所有应用调用此接口的频率限制为200次/分钟,即每分钟内,所有应用调用此接口的次数加起来最多为200次。
6.971817
3.267188
2.133889
'''taobao.vas.subsc.search 订购记录导出 用于ISV查询自己名下的应用及收费项目的订购记录''' request = TOPRequest('taobao.vas.subsc.search') request['article_code'] = article_code for k, v in kwargs.iteritems(): if k not in ('item_code', 'nick', 'start_deadline', 'end_deadline', 'status', ...
def subsc_search(self, article_code, **kwargs)
taobao.vas.subsc.search 订购记录导出 用于ISV查询自己名下的应用及收费项目的订购记录
7.632161
4.385509
1.740313
'''taobao.vas.subscribe.get 订购关系查询 用于ISV根据登录进来的淘宝会员名查询该为该会员开通哪些收费项目,ISV只能查询自己名下的应用及收费项目的订购情况''' request = TOPRequest('taobao.vas.subscribe.get') request['nick'] = nick request['article_code'] = article_code self.create(self.execute(request), fields=['article_user...
def subscribe_get(self, nick, article_code)
taobao.vas.subscribe.get 订购关系查询 用于ISV根据登录进来的淘宝会员名查询该为该会员开通哪些收费项目,ISV只能查询自己名下的应用及收费项目的订购情况
8.727419
2.609257
3.34479
assert isinstance(A, cspmatrix) and A.is_factor is False, "A must be a cspmatrix" tol = kwargs.get('tol',1e-15) X = matrix(A.spmatrix(reordered = True, symmetric = True)) symb = A.symb n = symb.n snptr = symb.snptr sncolptr = symb.sncolptr snrowidx = symb.snrowidx # visit...
def psdcompletion(A, reordered = True, **kwargs)
Maximum determinant positive semidefinite matrix completion. The routine takes a cspmatrix :math:`A` and returns the maximum determinant positive semidefinite matrix completion :math:`X` as a dense matrix, i.e., .. math:: P( X ) = A :param A: :py:class:`cspmatrix` :param r...
4.501678
4.530216
0.993701
size = (1.0 - 2.0*self.margin) * rectangle.h offset = self.margin * rectangle.h per_mark = 1.0 / float(self.total) bottom = offset + size * float(self.index) * per_mark top = bottom + per_mark * size c = data['output'] with c: c.translate(re...
def render(self, rectangle, data)
Draws the signature mark. Note that this draws OUTSIDE the rectangle we're given. If cropping is involved, then this obviously won't work.
4.859818
4.414572
1.100858
def wrapper(f): try: router.DefaultRouter.add_url_rule(route, endpoint=endpoint, view_func=f, options=kw) except AssertionError, e: l...
def add_route(route, endpoint=None, **kw)
Add a new JSON API route
4.114934
4.122436
0.99818
try: return router.url_for(endpoint, force_external=True, values=values) except Exception: # XXX plone.jsonapi.core should catch the BuildError of Werkzeug and # throw another error which can be handled here. logger.debug("Could not build API URL for endpoint '%s'. " ...
def url_for(endpoint, default="senaite.jsonapi.get", **values)
Looks up the API URL for the given endpoint :param endpoint: The name of the registered route (aka endpoint) :type endpoint: string :returns: External URL for this endpoint :rtype: string/None
8.196395
8.614079
0.951511
assert isinstance(L, cspmatrix) and L.is_factor is True, "L must be a cspmatrix factor" n = L.symb.n snpost = L.symb.snpost snptr = L.symb.snptr chptr = L.symb.chptr chidx = L.symb.chidx relptr = L.symb.relptr relidx = L.symb.relidx blkptr = L.symb.blkptr blkval = L.blkva...
def projected_inverse(L)
Supernodal multifrontal projected inverse. The routine computes the projected inverse .. math:: Y = P(L^{-T}L^{-1}) where :math:`L` is a Cholesky factor. On exit, the argument :math:`L` contains the projected inverse :math:`Y`. :param L: :py:class:`cspmatrix` (factor)
4.948425
4.76251
1.039037
system_parser = subparsers.add_parser("system", help='Available commands: \'info\'') system_subparsers = system_parser.add_subparsers(help='System commands') # system info arguments info_parser = system_subparsers.add_parser('info', help='Get system status information') info_parser.add_argumen...
def define_system_args(subparsers)
Append the parser arguments for the 'system' commands
3.708841
3.620585
1.024376
parser = argparse.ArgumentParser(description='StreamSets Data Collector tools.') subparsers = parser.add_subparsers(help='sdc-tool') define_pipeline_args(subparsers) define_system_args(subparsers) args = parser.parse_args(args=args) result = args.func(args) return result
def run_with_args(args)
Main script entry point.
4.614605
4.377127
1.054254
user = api.get_user(user) current = api.get_current_user() if api.is_anonymous(): return { "username": current.getUserName(), "authenticated": False, "roles": current.getRoles(), "api_url": api.url_for("plone.jsonapi.routes.users", username="curr...
def get_user_info(user)
Get the user information
3.747781
3.741565
1.001661
user_ids = [] # Don't allow anonymous users to query a user other than themselves if api.is_anonymous(): username = "current" # query all users if no username was given if username is None: user_ids = api.get_member_ids() elif username == "current": current_user = ...
def get(context, request, username=None)
Plone users route
3.634105
3.665633
0.991399
if ploneapi.user.is_anonymous(): request.response.setStatus(401) request.response.setHeader('WWW-Authenticate', 'basic realm="JSONAPI AUTH"', 1) logger.info("*** BASIC AUTHENTICATE ***") return {}
def auth(context, request)
Basic Authentication
8.984074
8.646133
1.039086
# extract the data __ac_name = request.get("__ac_name", None) __ac_password = request.get("__ac_password", None) logger.info("*** LOGIN %s ***" % __ac_name) if __ac_name is None: api.fail(400, "__ac_name is missing") if __ac_password is None: api.fail(400, "__ac_password i...
def login(context, request)
Login Route Login route to authenticate a user against Plone.
5.761413
5.528439
1.042141
logger.info("*** LOGOUT ***") acl_users = api.get_tool("acl_users") acl_users.logout(request) return { "url": api.url_for("senaite.jsonapi.v1.users"), "success": True }
def logout(context, request)
Logout Route
10.578744
10.592481
0.998703
if isinstance(A,spmatrix): idx = [i for i,ij in enumerate(zip(A.I,A.J)) if ij[0]>=ij[1]] return spmatrix(A.V[idx],A.I[idx],A.J[idx],A.size) elif isinstance(A,matrix): B = matrix(0.0, A.size) lapack.lacpy(A, B, uplo = 'L') return B else: raise TypeError
def tril(A)
Returns the lower triangular part of :math:`A`.
3.684793
3.595765
1.024759
assert type(A) is spmatrix, "argument must be a sparse matrix" assert A.size[0] == A.size[1], "argument must me a square matrix" idx = [i for i,ij in enumerate(zip(A.I,A.J)) if ij[0] > ij[1]] return tril(A) + spmatrix(A.V[idx], A.J[idx], A.I[idx], A.size)
def symmetrize(A)
Returns a symmetric matrix from a sparse square matrix :math:`A`. Only the lower triangular entries of :math:`A` are accessed.
3.886677
3.889704
0.999222
assert isinstance(A,spmatrix), "argument must be a sparse matrix" assert A.size[0] == A.size[1], "A must be a square matrix" assert A.size[0] == len(p), "length of p must be equal to the order of A" return A[p,p]
def perm(A, p)
Symmetric permutation of a symmetric sparse matrix. :param A: :py:class:`spmatrix` :param p: :py:class:`matrix` or :class:`list` of length `A.size[0]`
2.987887
3.088186
0.967522
'''taobao.fenxiao.discount.add 新增等级折扣 新增等级折扣''' request = TOPRequest('taobao.fenxiao.discount.add') request['discount_name'] = discount_name request['target_types'] = target_types request['target_ids'] = target_ids request['discount_types'] = discount_typ...
def add(self, discount_name, target_types, target_ids, discount_types, discount_values, session)
taobao.fenxiao.discount.add 新增等级折扣 新增等级折扣
2.755428
2.08603
1.320896
'''taobao.fenxiao.discount.update 修改等级折扣 修改等级折扣''' request = TOPRequest('taobao.fenxiao.discount.update') for k, v in kwargs.iteritems(): if k not in ('discount_id', 'discount_name', 'discount_status', 'detail_ids', 'target_types', 'target_ids', 'discount_types', 'di...
def update(self, session, **kwargs)
taobao.fenxiao.discount.update 修改等级折扣 修改等级折扣
5.559246
4.349818
1.278041
'''taobao.fenxiao.discounts.get 获取折扣信息 查询折扣信息''' request = TOPRequest('taobao.fenxiao.discounts.get') if discount_id!=None: request['discount_id'] = discount_id if ext_fields!=None: request['ext_fields'] = ext_fields self.create(self.execute(request, session)) ...
def get(self, session, discount_id=None, ext_fields=None)
taobao.fenxiao.discounts.get 获取折扣信息 查询折扣信息
3.449399
2.777715
1.241812
'''taobao.fenxiao.cooperation.get 获取供应商的合作关系信息 获取供应商的合作关系信息''' request = TOPRequest('taobao.fenxiao.cooperation.get') for k, v in kwargs.iteritems(): if k not in ('status', 'start_date', 'end_date', 'trade_type', 'page_no', 'page_size') and v==None: continue ...
def get(self, session, **kwargs)
taobao.fenxiao.cooperation.get 获取供应商的合作关系信息 获取供应商的合作关系信息
5.448181
3.98565
1.366949