code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if namespace is None: namespace = {'xs': 'http://www.w3.org/2001/XMLSchema'} schema_root = etree.parse(StringIO(self.schema)) document = schema_root.xpath(self.get_element_from_clark(element), namespaces=namespace) return document...
def get_documentation(self, element, namespace=None, schema_str=None)
**Helper method:** should return an schema specific documentation given an element parsing or getting the `Clark's Notation`_ `{url:schema}Element` from the message error on validate method. :param str element: Element string following the Clark's Notation :param dict namespace: Element...
3.565776
3.382041
1.054326
'''taobao.simba.insight.wordsbase.get =================================== 词基础数据查询''' request = TOPRequest('taobao.simba.insight.wordsbase.get') request['words'] = words request['time'] = time request['filter'] = aFilter if nick!=None: request['nick'] = nic...
def get(self, session, words, time='DAY|WEEK|MONTH|3MONTH', aFilter='PV|CLICK|AVGCPC|COMPETITION', nick=None)
taobao.simba.insight.wordsbase.get =================================== 词基础数据查询
5.532494
3.346978
1.652982
'''taobao.simba.insight.wordscats.get =================================== 词和类目查询''' request = TOPRequest('taobao.simba.insight.wordscats.get') request['wordCategories'] = wordCategories request['filter'] = aFilter if nick!=None: request['nick'] = nick self...
def get(self, wordCategories, aFilter='PV|CLICK|AVGCPC|COMPETITION', nick=None)
taobao.simba.insight.wordscats.get =================================== 词和类目查询
6.034992
3.325222
1.814914
'''taobao.simba.creativeids.changed.get =================================== 获取修改的创意ID''' request = TOPRequest('taobao.simba.creativeids.changed.get') request['start_time'] = start_time request['page_size'] = page_size request['page_no'] = page_no if nick!=...
def changed_get(self, start_time, nick=None, page_size=200, page_no=1)
taobao.simba.creativeids.changed.get =================================== 获取修改的创意ID
6.311664
4.055169
1.556449
if m == 0 or n == 0: return spmatrix([], [], [], (m,n)) nnz = min(max(0, int(round(a*m*n))), m*n) nz = matrix(random.sample(range(m*n), nnz), tc='i') return spmatrix(normal(nnz,1), nz%m, matrix([int(ii) for ii in nz/m]), (m,n))
def sp_rand(m,n,a)
Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.
4.626223
4.106004
1.126697
obj = None if uid is not None: obj = get_object_by_uid(uid) else: obj = get_object_by_request() if obj is None: fail(404, "No object found") complete = req.get_complete(default=_marker) if complete is _marker: complete = True items = make_items_for([obj],...
def get_record(uid=None)
Get a single record
5.199881
5.152215
1.009251
# fetch the catalog results results = get_search_results(portal_type=portal_type, uid=uid, **kw) # fetch the batch params from the request size = req.get_batch_size() start = req.get_batch_start() # check for existing complete flag complete = req.get_complete(default=_marker) if ...
def get_batched(portal_type=None, uid=None, endpoint=None, **kw)
Get batched results
5.887381
5.726306
1.028129
# disable CSRF req.disable_csrf_protection() # destination where to create the content container = uid and get_object_by_uid(uid) or None # extract the data from the request records = req.get_request_data() results = [] for record in records: # get the portal_type ...
def create_items(portal_type=None, uid=None, endpoint=None, **kw)
create items 1. If the uid is given, get the object and create the content in there (assumed that it is folderish) 2. If the uid is 0, the target folder is assumed the portal. 3. If there is no uid given, the payload is checked for either a key - `parent_uid` specifies the *uid* of the targ...
4.150684
4.179141
0.993191
# disable CSRF req.disable_csrf_protection() # the data to update records = req.get_request_data() # we have an uid -> try to get an object for it obj = get_object_by_uid(uid) if obj: record = records[0] # ignore other records if we got an uid obj = update_object_wit...
def update_items(portal_type=None, uid=None, endpoint=None, **kw)
update items 1. If the uid is given, the user wants to update the object with the data given in request body 2. If no uid is given, the user wants to update a bunch of objects. -> each record contains either an UID, path or parent_path + id
4.404286
4.154771
1.060055
# disable CSRF req.disable_csrf_protection() # try to find the requested objects objects = find_objects(uid=uid) # We don't want to delete the portal object if filter(lambda o: is_root(o), objects): fail(400, "Can not delete the portal object") results = [] for obj in ob...
def delete_items(portal_type=None, uid=None, endpoint=None, **kw)
delete items 1. If the uid is given, we can ignore the request body and delete the object with the given uid (if the uid was valid). 2. If no uid is given, the user wants to delete more than one item. => go through each item and extract the uid. Delete it afterwards. // we should do this k...
7.239403
6.733138
1.07519
# check if the user wants to include children include_children = req.get_children(False) def extract_data(brain_or_object): info = get_info(brain_or_object, endpoint=endpoint, complete=complete) if include_children and is_folderish(brain_or_object): info.update(get_childre...
def make_items_for(brains_or_objects, endpoint=None, complete=False)
Generate API compatible data items for the given list of brains/objects :param brains_or_objects: List of objects or brains :type brains_or_objects: list/Products.ZCatalog.Lazy.LazyMap :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :param complete: Fla...
3.558256
3.865918
0.920417
# also extract the brain data for objects if not is_brain(brain_or_object): brain_or_object = get_brain(brain_or_object) if brain_or_object is None: logger.warn("Couldn't find/fetch brain of {}".format(brain_or_object)) return {} complete = True # When ...
def get_info(brain_or_object, endpoint=None, complete=False)
Extract the data from the catalog brain or object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :param complete: Fl...
5.279697
4.987875
1.058506
# If no endpoint was given, guess the endpoint by portal type if endpoint is None: endpoint = get_endpoint(brain_or_object) uid = get_uid(brain_or_object) portal_type = get_portal_type(brain_or_object) resource = portal_type_to_resource(portal_type) return { "uid": uid, ...
def get_url_info(brain_or_object, endpoint=None)
Generate url information for the content object/catalog brain :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :return...
3.077643
3.23255
0.952079
# special case for the portal object if is_root(brain_or_object): return {} # get the parent object parent = get_parent(brain_or_object) portal_type = get_portal_type(parent) resource = portal_type_to_resource(portal_type) # fall back if no endpoint specified if endpoint ...
def get_parent_info(brain_or_object, endpoint=None)
Generate url information for the parent object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :returns: URL informat...
3.304357
3.206462
1.030531
# fetch the contents (if folderish) children = get_contents(brain_or_object) def extract_data(brain_or_object): return get_info(brain_or_object, complete=complete) items = map(extract_data, children) return { "children_count": len(items), "children": items }
def get_children_info(brain_or_object, complete=False)
Generate data items of the contained contents :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param complete: Flag to wake up the object and fetch all data :type complete: bool :returns: info mapping of contain...
4.496592
4.897178
0.918201
# extract the file field from the object if omitted field = get_field(obj, fieldname) # get the value with the fieldmanager fm = IFieldManager(field) # return None if we have no file data if fm.get_size(obj) == 0: return None out = { "content_type": fm.get_content_ty...
def get_file_info(obj, fieldname, default=None)
Extract file data from a file field :param obj: Content object :type obj: ATContentType/DexterityContentType :param fieldname: Schema name of the field :type fieldname: str/unicode :returns: File data mapping :rtype: dict
4.875075
5.073939
0.960807
# ensure we have a full content object obj = get_object(brain_or_object) # get the portal workflow tool wf_tool = get_tool("portal_workflow") # the assigned workflows of this object workflows = wf_tool.getWorkflowsFor(obj) # no worfkflows assigned -> return if not workflows: ...
def get_workflow_info(brain_or_object, endpoint=None)
Generate workflow information of the assigned workflows :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :returns: Wor...
3.949219
3.952102
0.999271
portal = get_portal() catalog = ICatalog(portal) catalog_query = ICatalogQuery(catalog) query = catalog_query.make_query(**kw) return catalog(query)
def search(**kw)
Search the catalog adapter :returns: Catalog search results :rtype: iterable
5.807077
6.465842
0.898116
# If we have an UID, return the object immediately if uid is not None: logger.info("UID '%s' found, returning the object immediately" % uid) return u.to_list(get_object_by_uid(uid)) # allow to search search for the Plone Site with portal_type include_portal = False if u.to_str...
def get_search_results(portal_type=None, uid=None, **kw)
Search the catalog and return the results :returns: Catalog search results :rtype: iterable
4.690417
4.683235
1.001533
if is_brain(brain_or_object): return brain_or_object if is_root(brain_or_object): return brain_or_object # fetch the brain by UID uid = get_uid(brain_or_object) uc = get_tool("uid_catalog") results = uc({"UID": uid}) or search(query={'UID': uid}) if len(results) == 0: ...
def get_brain(brain_or_object)
Return a ZCatalog brain for the object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: True if the object is a catalog brain :rtype: bool
4.461418
4.327257
1.031004
obj = get_object(brain_or_object) # The portal object has no schema if is_root(obj): return {} schema = get_schema(obj) if is_dexterity_content(obj): names = schema.names() fields = map(lambda name: schema.get(name), names) schema_fields = dict(zip(names, fields)...
def get_fields(brain_or_object)
Get the list of fields from the object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: List of fields :rtype: list
5.106266
5.076021
1.005958
fields = get_fields(brain_or_object) return fields.get(name, default)
def get_field(brain_or_object, name, default=None)
Return the named field
2.982827
2.84837
1.047205
obj = get_object(brain_or_object) if not is_dexterity_content(obj): fail(400, "Only Dexterity contents can have assigned behaviors") assignable = IBehaviorAssignable(obj, None) if not assignable: return {} out = {} for behavior in assignable.enumerateBehaviors(): for...
def get_behaviors(brain_or_object)
Iterate over all behaviors that are assigned to the object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Behaviors :rtype: list
6.800802
6.187087
1.099193
if not isinstance(uid, basestring): return False if uid != "0" and len(uid) != 32: return False return True
def is_uid(uid)
Checks if the passed in uid is a valid UID :param uid: The uid to check :type uid: string :return: True if the uid is a valid 32 alphanumeric uid or '0' :rtype: bool
3.424859
3.033169
1.129136
if not isinstance(path, basestring): return False portal_path = get_path(get_portal()) if not path.startswith(portal_path): return False obj = get_object_by_path(path) if obj is None: return False return True
def is_path(path)
Checks if the passed in path is a valid Path within the portal :param path: The path to check :type uid: string :return: True if the path is a valid path within the portal :rtype: bool
3.120107
2.934699
1.063178
mapping = { "today": 0, "yesterday": 1, "this-week": 7, "this-month": 30, "this-year": 365, } today = DateTime(DateTime().Date()) # current date without the time return today - mapping.get(literal, 0)
def calculate_delta_date(literal)
Calculate the date in the past from the given literal :param literal: A date literal, e.g. "today" :type literal: str :returns: Date between the literal and today :rtype: DateTime
4.025845
3.596834
1.119275
# This function bridges the value of the field to a probably more complex # JSON structure to return to the client. # extract the value from the object if omitted if value is _marker: value = IDataManager(obj).json_data(fieldname) # convert objects if isinstance(value, ImplicitAc...
def to_json_value(obj, fieldname, value=_marker, default=None)
JSON save value encoding :param obj: Content object :type obj: ATContentType/DexterityContentType :param fieldname: Schema name of the field :type fieldname: str/unicode :param value: The field value :type value: depends on the field type :returns: JSON encoded field value :rtype: field...
6.117693
6.168253
0.991803
# known date types date_types = (datetime.datetime, datetime.date, DateTime) return isinstance(thing, date_types)
def is_date(thing)
Checks if the given thing represents a date :param thing: The object to check if it is a date :type thing: arbitrary object :returns: True if we have a date object :rtype: bool
5.219313
6.488424
0.804404
# not a date if not is_date(date): return default # handle Zope DateTime objects if isinstance(date, (DateTime)): return date.ISO8601() # handle python datetime objects return date.isoformat()
def to_iso_date(date, default=None)
ISO representation for the date object :param date: A date object :type field: datetime/DateTime :returns: The ISO format of the date :rtype: str
5.953958
5.778081
1.030439
# Nothing to do if the object is contentish if not is_folderish(brain_or_object): return [] # Returning objects (not brains) to make sure we do not miss any child. # It may happen when children belong to different catalogs and not # found on 'portal_catalog'. ret = filter(lambda o...
def get_contents(brain_or_object)
Lookup folder contents for this object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: List of contained contents :rtype: list/Products.ZCatalog.Lazy.LazyMap
11.276804
10.181424
1.107586
if is_root(brain_or_object): return get_portal() if is_brain(brain_or_object): parent_path = get_parent_path(brain_or_object) return get_object_by_path(parent_path) return brain_or_object.aq_parent
def get_parent(brain_or_object)
Locate the parent object of the content/catalog brain :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: parent object :rtype: Parent content
3.352488
3.534318
0.948553
portal_types = get_portal_types() resources = map(portal_type_to_resource, portal_types) return dict(zip(resources, portal_types))
def get_resource_mapping()
Map resources used in the routes to portal types :returns: Mapping of resource->portal_type :rtype: dict
4.864989
4.124541
1.179523
if resource is None: return None resource_mapping = get_resource_mapping() portal_type = resource_mapping.get(resource.lower()) if portal_type is None: logger.warn("Could not map the resource '{}' " "to any known portal type".format(resource)) return porta...
def resource_to_portal_type(resource)
Converts a resource to a portal type :param resource: Resource name as it is used in the content route :type name: string :returns: Portal type name :rtype: string
2.982614
3.128926
0.953239
container_paths = config.CONTAINER_PATHS_FOR_PORTAL_TYPES container_path = container_paths.get(portal_type) if container_path is None: return None portal_path = get_path(get_portal()) return get_object_by_path("/".join([portal_path, container_path]))
def get_container_for(portal_type)
Returns the single holding container object of this content type :param portal_type: The portal type requested :type portal_type: string :returns: Folderish container where the portal type can be created :rtype: AT content object
3.99993
4.377504
0.913747
try: return router.url_for(endpoint, force_external=True, values=values) except Exception: logger.warn("Could not build API URL for endpoint '%s'. " "No route provider registered?" % endpoint) # build generic API URL return router.url_for(default, force_...
def url_for(endpoint, default=DEFAULT_ENDPOINT, **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
5.073076
5.211599
0.97342
portal_type = get_portal_type(brain_or_object) resource = portal_type_to_resource(portal_type) # Try to get the right namespaced endpoint endpoints = router.DefaultRouter.view_functions.keys() if resource in endpoints: return resource # exact match endpoint_candidates = filter(lam...
def get_endpoint(brain_or_object, default=DEFAULT_ENDPOINT)
Calculate the endpoint for this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Endpoint for this object :rtype: string
4.856205
5.410907
0.897484
# nothing to do here if not record: return None if record.get("uid"): return get_object_by_uid(record["uid"]) if record.get("path"): return get_object_by_path(record["path"]) if record.get("parent_path") and record.get("id"): path = "/".join([record["parent_pat...
def get_object_by_record(record)
Find an object by a given record Inspects request the record to locate an object :param record: A dictionary representation of an object :type record: dict :returns: Found Object or None :rtype: object
2.829362
2.826185
1.001124
# nothing to do here if not isinstance(path, basestring): return None # path must be a string path = str(path) portal = get_portal() portal_path = get_path(portal) if path == portal_path: return portal if path.startswith(portal_path): segments = path.spl...
def get_object_by_path(path)
Find an object by a given physical path :param path: The physical path of the object to find :type path: string :returns: Found Object or None :rtype: object
3.751224
3.717319
1.009121
pm = get_tool("portal_membership") member_ids = pm.listMemberIds() # How can it be possible to get member ids with None? return filter(lambda x: x, member_ids)
def get_member_ids()
Return all member ids of the portal.
7.775787
6.884381
1.129482
if user_or_username is None: return None if hasattr(user_or_username, "getUserId"): return ploneapi.user.get(user_or_username.getUserId()) return ploneapi.user.get(userid=u.to_string(user_or_username))
def get_user(user_or_username=None)
Return Plone User :param user_or_username: Plone user or user id :type groupname: PloneUser/MemberData/str :returns: Plone MemberData :rtype: object
4.297552
4.01959
1.069152
# The objects to cut objects = [] # get the object by the given uid or try to find it by the request # parameters obj = get_object_by_uid(uid) or get_object_by_request() if obj: objects.append(obj) else: # no uid -> go through the record items records = req.get...
def find_objects(uid=None)
Find the object by its UID 1. get the object from the given uid 2. fetch objects specified in the request parameters 3. fetch objects located in the request body :param uid: The UID of the object to find :type uid: string :returns: List of found objects :rtype: list
4.665502
4.417926
1.056039
portal_type = portal_type or record.get("portal_type") container = get_container_for(portal_type) if container: return container parent_uid = record.pop("parent_uid", None) parent_path = record.pop("parent_path", None) target = None # Try to find the target object if pare...
def find_target_container(portal_type, record)
Locates a target container for the given portal_type and record :param record: The dictionary representation of a content object :type record: dict :returns: folder which contains the object :rtype: object
2.804332
3.007226
0.932531
if "id" in data: # always omit the id as senaite LIMS generates a proper one id = data.pop("id") logger.warn("Passed in ID '{}' omitted! Senaite LIMS " "generates a proper ID for you" .format(id)) try: # Special case for ARs # => return immediat...
def create_object(container, portal_type, **data)
Creates an object slug :returns: The new created content object :rtype: object
9.045178
8.966369
1.008789
container = get_object(container) request = req.get_request() # we need to resolve the SampleType to a full object sample_type = data.get("SampleType", None) if sample_type is None: fail(400, "Please provide a SampleType") # TODO We should handle the same values as in the DataManag...
def create_analysisrequest(container, **data)
Create a minimun viable AnalysisRequest :param container: A single folderish catalog brain or content object :type container: ATContentType/DexterityContentType/CatalogBrain
7.817017
8.073964
0.968176
# ensure we have a full content object content = get_object(content) # get the proper data manager dm = IDataManager(content) if dm is None: fail(400, "Update for this object is not allowed") # Iterate through record items for k, v in record.items(): try: ...
def update_object_with_data(content, record)
Update the content with the record data :param content: A single folderish catalog brain or content object :type content: ATContentType/DexterityContentType/CatalogBrain :param record: The data to update :type record: dict :returns: The updated content object :rtype: object :raises: ...
4.577384
4.479417
1.021871
obj = get_object(brain_or_object) # Call the validator of AT Content Types if is_at_content(obj): return obj.validate(data=data) return {}
def validate_object(brain_or_object, data)
Validate the entire object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param data: The sharing dictionary as returned from the API :type data: dict :returns: invalidity status :rtype: dict
9.67543
10.771411
0.898251
obj = get_object(brain_or_object) # we do not want to delete the site root! if is_root(obj): fail(401, "Deactivating the Portal is not allowed") try: do_transition_for(brain_or_object, "deactivate") except Unauthorized: fail(401, "Not allowed to deactivate object '%s'" %...
def deactivate_object(brain_or_object)
Deactivate the given object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Nothing :rtype: None
6.162667
7.229776
0.852401
portal_reg = ploneapi.portal.get_tool(name="portal_registry") found_registers = {} for record in portal_reg.records: if keyword is None: found_registers[record] = api.get_registry_record(record) elif keyword.lower() in record.lower(): found_registers[record] = ap...
def get_registry_records_by_keyword(keyword=None)
Get all the registry records (names and values) whose name contains the specified keyword or, if keyword is None, return all registry items :param keyword: The keyword that has to be contained in the record name :type keyword: str or None :returns: Dictionary mapping the names of the found record...
3.485554
3.796012
0.918215
settings = [] if keyword is None: # iterate over all the schemas to return all settings for key, ischemas in CONTROLPANEL_INTERFACE_MAPPING.items(): settings_from_ifaces = map(get_settings_from_interface, ischemas) settings_from_key = {k: v for d in settings_from_ifa...
def get_settings_by_keyword(keyword=None)
Get the settings associated to the specified keyword or, if keyword is None, get all the settings. :param keyword: settings to be retrieved :return: dictionary with the settings plus a key to identify from which keyword where retrieved.
3.410191
3.463205
0.984692
settings = {} schema_id = iface.getName() settings[schema_id] = {} schema = getAdapter(api.get_portal(), iface) for setting in getFieldNames(iface): value = getattr(schema, setting, None) if is_json_serializable(value): settings[schema_id][setting] = value return...
def get_settings_from_interface(iface)
Get the configuration settings associated to a list of schema interfaces :param iface: The schema interface from which we want to get its fields :return: Dictionary with iface name as key and as value a dictionary with the setting names (keys) linked to that schema and its values.
5.916253
5.712584
1.035653
batch = make_batch(sequence, size, start) return { "pagesize": batch.get_pagesize(), "next": batch.make_next_url(), "previous": batch.make_prev_url(), "page": batch.get_pagenumber(), "pages": batch.get_numpages(), "count": batch.get_sequence_length(), ...
def get_batch(sequence, size, start=0, endpoint=None, complete=False)
create a batched result record out of a sequence (catalog brains)
3.96465
3.981252
0.99583
text = os.path.expanduser(text) head, tail = os.path.split(text) search_dir = os.path.join('.', head) candidates = [s for s in os.listdir(search_dir) if s.startswith(tail)] if state >= len(candidates): return None if len(candidates) == 1: fn = os.path.join(head, candidat...
def fcomplete(text, state)
Readline completion function: Filenames
2.588679
2.536712
1.020486
request.responseHeaders.addRawHeader(b'content-type', b'application/json') request.responseHeaders.addRawHeader(b'Access-Control-Allow-Origin', b'*') request.responseHeaders.addRawHeader(b'Access-Control-Allow-Methods', b'GET, POST, PUT, DELETE') request.responseHeaders.addRawHe...
def _setHeaders(self, request)
Those headers will allow you to call API methods from web browsers, they require CORS: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
1.825246
1.810839
1.007956
self.cols = int(math.ceil(len(self.elements) / float(self.rows)))
def calculate_columns(self)
Assuming the number of rows is constant, work out the best number of columns to use.
7.65867
4.219218
1.815187
# Update the number of rows and colums self.rows = max(self.rows, row+rows) self.cols = max(self.cols, col+cols) # Add the raw element record self.elements.append((col, row, cols, rows, element))
def add_element(self, element, col, row, cols=1, rows=1)
Adds the given element to the given position in the grid, with the given size. There is no limit to the number of elements that can be assigned to the same cell(s).
3.410919
3.984544
0.856037
self.rules.append( (start_col, start_row, end_col, end_row, width, color) )
def add_rule(self, start_col, start_row, end_col, end_row, width=0.5, color=(0,0,0))
Adds a rule to the grid. The row and column numbers are those on the top left of the corresponding cell in the grid. So if the grid is 10x10, then the right hand edge of the grid will be column 10, and the bottom will be column 10. In other words there is one more rule-row and column tha...
2.305154
2.480198
0.929423
sort_index = base_index + 2 sized_elements.sort(key=lambda x: x[sort_index]) for element_data in sized_elements: start, end = element_data[base_index], element_data[sort_index] end += start element, size = element_data[4:6] # Find the tot...
def _compile_dimension_size(self, base_index, array, property, sized_elements)
Build one set of col widths or row heights.
4.09068
3.942448
1.037599
# Gat a list of elements with their sizes, so we don't have to # recalculate that each time. sized_elements = [ (col, row, cols, rows, element, element.get_minimum_size(data)) for col, row, cols, rows, element in self.elements ] # Create the...
def get_minimum_size(self, data)
Finds the minimum size of the grid.
3.819156
3.76128
1.015388
size = self.get_minimum_size(data) # Find how much extra space we have. extra_width = rect.w - size.x extra_height = rect.h - size.y # Distribute the extra space into the correct rows and columns. if self.scaling_col is None or not 0 <= self.scaling_col < self....
def render(self, rect, data)
Draws the cells in grid.
2.263879
2.265749
0.999175
'''taobao.taobaoke.report.get 淘宝客报表查询 淘宝客报表查询''' request = TOPRequest('taobao.taobaoke.items.get') request['date'] = date request['page_no'] = page_no request['page_size'] = page_size if not fields: fields = self.fields request['fields...
def get(self, date, page_no=1, page_size=40, fields=[])
taobao.taobaoke.report.get 淘宝客报表查询 淘宝客报表查询
4.657044
2.882936
1.615382
'''taobao.taobaoke.shops.convert 淘客店铺转换 淘宝客店铺转换''' request = TOPRequest('taobao.taobaoke.shops.convert') request['sids'] = sids if not fields: taobaokeShop = TaobaokeShop() fields = taobaokeShop.fields request['fields'] = fields fo...
def convert(self, sids, fields=[], **kwargs)
taobao.taobaoke.shops.convert 淘客店铺转换 淘宝客店铺转换
5.119836
3.395289
1.507923
'''taobao.taobaoke.items.convert 淘客商品转换 淘宝客商品转换''' request = TOPRequest('taobao.taobaoke.items.convert') if not fields: taobaokeItem = TaobaokeItem() fields = taobaokeItem.fields request['fields'] = fields for k, v in kwargs.iteritems(): ...
def items_convert(self, fields=[], **kwargs)
taobao.taobaoke.items.convert 淘客商品转换 淘宝客商品转换
5.550554
4.023899
1.379397
'''taobao.taobaoke.items.detail.get 查询淘宝客推广商品详细信息 查询淘宝客推广商品详细信息''' request = TOPRequest('taobao.taobaoke.items.detail.get') request['num_iids'] = num_iids if not fields: taobaokeItem = TaobaokeItem() fields = taobaokeItem.fields request['f...
def items_detail_get(self, num_iids, fields=[], **kwargs)
taobao.taobaoke.items.detail.get 查询淘宝客推广商品详细信息 查询淘宝客推广商品详细信息
4.099318
3.194892
1.283085
'''taobao.taobaoke.listurl.get 淘宝客关键词搜索URL 淘宝客关键词搜索URL''' request = TOPRequest('taobao.taobaoke.listurl.get') request['q'] = q for k, v in kwargs.iteritems(): if k not in ('nick', 'outer_code', 'pid') and v==None: continue request[k] = v s...
def listurl_get(self, q, **kwargs)
taobao.taobaoke.listurl.get 淘宝客关键词搜索URL 淘宝客关键词搜索URL
5.651765
3.701278
1.526977
'''taobao.taobaoke.tool.relation 工具联盟注册校验 判断用户pid是否是appkey关联的注册用户''' request = TOPRequest('taobao.taobaoke.tool.relation') request['pubid'] = pubid self.create(self.execute(request), fields=['tools_user']) return self.tools_user
def tool_relation(self, pubid)
taobao.taobaoke.tool.relation 工具联盟注册校验 判断用户pid是否是appkey关联的注册用户
11.60117
3.742869
3.099539
lines = itertools.dropwhile(not_eq(BLOCK_START % name), data) gen = itertools.takewhile(not_eq(BLOCK_END % name), tail(lines)) return gen if newline is None else newline.join(gen)
def get_block(name, data, newline="\n")
First block in a list of one line strings containing reStructuredText data. The result is as a joined string with the given newline, or a line generator if it's None. The BLOCK_START and BLOCK_END delimiters are selected with the given name and aren't included in the result.
5.778071
4.943371
1.168853
@allow_implicit_stop def remove_blocks(name, iterable): start, end = BLOCK_START % name, BLOCK_END % name it = iter(iterable) while True: line = next(it) while line != start: yield line line = next(it) it = tail(ite...
def all_but_blocks(names, data, newline="\n", remove_empty_next=True, remove_comments=True)
Multiline string from a list of strings data, removing every block with any of the given names, as well as their delimiters. Removes the empty lines after BLOCK_END when ``remove_empty_next`` is True. Returns a joined string with the given newline, or a line generator if it's None. If desired, this func...
3.624331
3.469742
1.044554
it = iter(data) while True: line = next(it) while ":" in line or not line.lstrip().startswith(".."): yield line line = next(it) indent = indent_size(line) it = itertools.dropwhile(lambda el: indent_size(el) > indent ...
def commentless(data)
Generator that removes from a list of strings the double dot reStructuredText comments and its contents based on indentation, removing trailing empty lines after each comment as well.
4.65181
4.478662
1.038661
def replacer(regex, url): replacement = r"\1 {0}/\2".format(url.rstrip("/")) return lambda line: regex.sub(replacement, line, count=1) replacers = [replacer(REGEX_ABS_URLS_TARGET, target_url), replacer(REGEX_ABS_URLS_IMAGE, image_url)] return [functools.reduce(lambda el...
def abs_urls(data, target_url, image_url)
Filter for a list of reStructuredText lines that replaces relative link targets and image sources by absolute URLs given the base URLs that should be used (``target_url`` for link targets, ``image_url``for image sources). Returns a list of strings.
3.476055
3.200516
1.086092
top = 0 stack[0] = j while (top >= 0): p = stack[top] i = head[p] if i == -1: top -= 1 post[k] = p k += 1 else: head[p] = next[i] top += 1 stack[top] = i return k
def __tdfs(j, k, head, next, post, stack)
Depth-first search and postorder of a tree rooted at node j.
2.914619
2.751367
1.059335
n = len(parent) k = 0 p = matrix(0,(n,1)) head = matrix(-1,(n,1)) next = matrix(0,(n,1)) stack = matrix(0,(n,1)) for j in range(n-1,-1,-1): if (parent[j] == j): continue next[j] = head[parent[j]] head[parent[j]] = j for j in range(n): if (parent[j]...
def post_order(parent)
Post order a forest.
3.464396
3.307754
1.047356
assert isinstance(A,spmatrix), "A must be a sparse matrix" assert A.size[0] == A.size[1], "A must be a square matrix" n = A.size[0] cp,ri,_ = A.CCS parent = matrix(0,(n,1)) w = matrix(0,(n,1)) for k in range(n): parent[k] = k w[k] = -1 for p in range(cp[k],cp[k...
def etree(A)
Compute elimination tree from upper triangle of A.
3.966714
3.79114
1.046312
jleaf = 0 if i<=j or first[j] <= maxfirst[i]: return -1, jleaf maxfirst[i] = first[j] jprev = prevleaf[i] prevleaf[i] = j if jprev == -1: jleaf = 1 else: jleaf = 2 if jleaf == 1: return i, jleaf q = jprev while q != ancestor[q]: q = ancestor[q] s = jprev while s != q...
def __leaf(i, j, first, maxfirst, prevleaf, ancestor)
Determine if j is leaf of i'th row subtree.
3.332011
3.303032
1.008774
n = A.size[0] colcount = matrix(0,(n,1)) ancestor = matrix(range(n),(n,1)) maxfirst = matrix(-1,(n,1)) prevleaf = matrix(-1,(n,1)) first = matrix(-1,(n,1)) for k in range(n): j = post[k] if first[j] == -1: colcount[j] = 1 else: colcou...
def counts(A, parent, post)
Compute column counts.
3.635055
3.540407
1.026734
n = len(par) flag = matrix(-1, (n, 1)) snpar = matrix(-1, (n, 1)) snodes = n ch = {} for j in post: if par[j] in ch: ch[par[j]].append(j) else: ch[par[j]] = [j] mdeg = colcount[j] - 1 if par[j] != j: if mdeg == colcount[par[j]] and fl...
def pothen_sun(par, post, colcount)
Find supernodes and supernodal etree. ARGUMENTS par parent array post array with post ordering colcount array with column counts RETURNS snpar supernodal parent structure flag integer vector of length n; if flag[i] < 0, then -flag[i] is the degree of ...
3.413683
3.082487
1.107444
snpar, flag = pothen_sun(par, post, colcount) n = len(par) N = len(snpar) snode = matrix(0, (n,1)) snptr = matrix(0, (N+1,1)) slist = [[] for i in range(n)] for i in range(n): f = flag[i] if f < 0: slist[i].append(i) else: slist[f].appen...
def supernodes(par, post, colcount)
Find supernodes. ARGUMENTS par parent array post array with post ordering colcount array with column counts RETURNS snode array with supernodes; snode[snptr[k]:snptr[k+1]] contains the indices of supernode k snptr pointer array; snptr[k] is the index of...
3.49601
3.473168
1.006577
N = len(snpost) ch = {} for j in snpost: if snpar[j] in ch: ch[snpar[j]].append(j) else: ch[snpar[j]] = [j] snlist = [snode[snptr[k]:snptr[k+1]] for k in range(N)] snpar_ = +snpar colcount_ = +colcount Ns = N for k in snpost: if snpar_[k] != k: ...
def amalgamate(colcount, snode, snptr, snpar, snpost, merge_function)
Supernodal amalgamation. colcount, snode, snptr, snpar, snpost = ... amalgamate(colcount, snode, snptr, snpar, snpost, merge_function) PURPOSE Iterates over the clique tree in topological order and greedily merges a supernode with its parent if merge_function(|J_{par(k)}|, |J_k...
2.82742
2.731376
1.035163
Alo = tril(A) cp,ri,_ = Alo.CCS N = len(snpar) # colptr for compressed cholesky factor colptr = matrix(0,(N+1,1)) for k in range(N): colptr[k+1] = colptr[k] + colcount[snode[snptr[k]]] rowidx = matrix(-1,(colptr[-1],1)) cnnz = matrix(0,(N,1)) # compute compressed spar...
def embed(A, colcount, snode, snptr, snpar, snpost)
Compute filled pattern. colptr, rowidx = embed(A, colcount, snode, snptr, snpar, snpost) PURPOSE Computes rowindices and column pointer for representative vertices in supernodes. ARGUMENTS A sparse matrix colcount vector with column counts snode vector with supernodes ...
3.685275
3.662183
1.006306
relptr = matrix(0, (len(snptr),1)) relidx = matrix(-1, (colptr[-1],1)) def lfind(a,b): i = 0 ret = +a for k in range(len(a)): while a[k] != b[i]: i += 1 ret[k] = i i += 1 return ret for k in range(len(snpar)): p ...
def relative_idx(colptr, rowidx, snptr, snpar)
Compute relative indices of update matrices in frontal matrix of parent.
3.28218
3.169333
1.035606
n = A.size[0] assert type(A) == spmatrix, "A must be a sparse matrix" assert A.size[1] == n, "A must be a square matrix" assert len(p) == n, "length of p must be equal to the order of A" if isinstance(p, list): p = matrix(p) As = symmetrize(A) cp,ri,_ = As.CCS # compute inve...
def peo(A, p)
Checks whether an ordering is a perfect elmimination order. Returns `True` if the permutation :math:`p` is a perfect elimination order for a Cholesky factorization :math:`PAP^T = LL^T`. Only the lower triangular part of :math:`A` is accessed. :param A: :py:class:`spmatrix` :param p: :...
6.027358
5.387419
1.118784
assert tsize >= 0, "tsize must be nonnegative" assert tfill >= 0, "tfill must be nonnegative" def fmerge(ccp,cck,np,nk): fill = (ccp - (cck - nk))*nk if fill <= tfill or (nk <= tsize and np <= tsize): return True else: return False # ins...
def merge_size_fill(tsize = 8, tfill = 8)
Simple heuristic for supernodal amalgamation (clique merging). Returns a function that returns `True` if either (i) supernode k and supernode par(k) are both of size at most `tsize`, or (ii), merging supernodes par[k] and k induces at most `tfill` nonzeros in the lower triangular part of the spars...
6.283818
5.557347
1.130723
return cspmatrix(self, 1.0).spmatrix(reordered = reordered, symmetric = symmetric)
def sparsity_pattern(self, reordered = True, symmetric = True)
Returns a sparse matrix with the filled pattern. By default, the routine uses the reordered pattern, and the inverse permutation is applied if `reordered` is `False`. :param reordered: boolean (default: `True`) :param symmetric: boolean (default: `True`)
12.042289
16.319839
0.737893
nnz = 0 for k in range(len(self.snpost)): nn = self.snptr[k+1]-self.snptr[k] na = self.relptr[k+1]-self.relptr[k] nnz += nn*(nn+1)/2 + nn*na return nnz
def nnz(self)
Returns the number of lower-triangular nonzeros.
5.205772
4.767141
1.092011
if reordered: return [list(self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)] else: return [list(self.__p[self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]]) for k in range(self.Nsn)]
def cliques(self, reordered = True)
Returns a list of cliques
3.271759
3.299011
0.991739
if reordered: return [list(self.snrowidx[self.sncolptr[k]+self.snptr[k+1]-self.snptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)] else: return [list(self.__p[self.snrowidx[self.sncolptr[k]+self.snptr[k+1]-self.snptr[k]:self.sncolptr[k+1]]]) for k in range(self.Nsn)...
def separators(self, reordered = True)
Returns a list of separator sets
3.067922
3.046054
1.007179
if reordered: return [list(self.snode[self.snptr[k]:self.snptr[k+1]]) for k in range(self.Nsn)] else: return [list(self.__p[self.snode[self.snptr[k]:self.snptr[k+1]]]) for k in range(self.Nsn)]
def supernodes(self, reordered = True)
Returns a list of supernode sets
2.941108
2.877982
1.021934
n = self.symb.n snptr = self.symb.snptr snode = self.symb.snode relptr = self.symb.relptr snrowidx = self.symb.snrowidx sncolptr = self.symb.sncolptr blkptr = self.symb.blkptr blkval = self.blkval if self.is_factor: if...
def spmatrix(self, reordered = True, symmetric = False)
Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered matrix is returned if the optional argument `reordered` is `True` (default), and otherwise the inverse permutation is applied. Only the default options are allowed if the :py:class:`cspmatrix` :math:`A` represents ...
3.53182
3.456506
1.021789
sncolptr = self.symb.sncolptr snptr = self.symb.snptr snode = self.symb.snode blkptr = self.symb.blkptr D = matrix(0.0,(self.symb.n,1)) for k in range(self.symb.Nsn): nn = snptr[k+1]-snptr[k] w = sncolptr[k+1]-sncolptr[k] ...
def diag(self, reordered = True)
Returns a vector with the diagonal elements of the matrix.
3.96128
3.836605
1.032496
return cspmatrix(self.symb, blkval = +self.blkval, factor = self.is_factor)
def copy(self)
Returns a new :py:class:`cspmatrix` object with a reference to the same symbolic factorization, but with a copy of the array that stores the numerical values.
49.657394
18.385578
2.700888
assert self.is_factor is False, "cannot add spmatrix to a cspmatrix factor" n = self.symb.n snptr = self.symb.snptr snode = self.symb.snode relptr = self.symb.relptr snrowidx = self.symb.snrowidx sncolptr = self.symb.sncolptr blkptr = self.symb.b...
def _iadd_spmatrix(self, X, alpha = 1.0)
Add a sparse matrix :math:`X` to :py:class:`cspmatrix`.
5.308725
5.101275
1.040666
assert self.is_factor is False, "cannot project matrix onto a cspmatrix factor" assert isinstance(A, matrix), "argument A must be a dense matrix" symb = self.symb blkval = self.blkval n = symb.n snptr = symb.snptr snode = symb.snode relp...
def add_projection(self, A, alpha = 1.0, beta = 1.0, reordered=False)
Add projection of a dense matrix :math:`A` to :py:class:`cspmatrix`. X := alpha*proj(A) + beta*X
4.462945
4.236342
1.05349
assert params is None or isinstance(params, dict) if value is None: if not optional: assert value is not None else: if type is not None: assert isinstance(value, type) if max_length is not None: assert ...
def _check_param(cls, name=None, value=None, params=None, optional=True, max_length=None, type=None, gte=None, lte=None, sub_max_length=None, sub_type=None)
This checks the value for different type, max length, etc. If all of the checks pass, then the value is placed in the params bucket :param name: The name of the parameter :param value: The value of param :param params: The dictionary where the param should go if all of the checks pass ...
1.548965
1.618927
0.956785
url = "/v1/url" method = "POST" params = {} # Check Params self._check_param("data", data, params, type=dict) self._check_param("alias", alias, params, type=(binary_type, text_type)) self._check_param("type", type, params, type=int, lte=2, gte=0) ...
def create_deep_link_url(self, data=None, alias=None, type=0, duration=None, identity=None, tags=None, campaign=None, feature=None, channel=None, stage=None, skip_api_call=False)
Creates a deep linking url See the URL https://dev.branch.io/references/http_api/#creating-a-deep-linking-url You can also use this method to bulk create deep link by setting "skip_api_call=True" and using the parameters returned by the method as an array and call "create_deep_linking_urls" ...
1.919429
1.933614
0.992664
url = "/v1/url/bulk/%s" % self.branch_key method = "POST" # Checks params self._check_param(value=url_params, type=list, sub_type=dict, optional=False) return self.make_api_call(method, url, json_params=url_params)
def create_deep_linking_urls(self, url_params)
Bulk Creates Deep Linking URLs See the URL https://dev.branch.io/references/http_api/#bulk-creating-deep-linking-urls :param url_params: Array of values returned from "create_deep_link_url(..., skip_api_call=True)" :return: The response
6.533953
5.957919
1.096684
url = self.BRANCH_BASE_URI+url if self.verbose is True: print("Making web request: {}".format(url)) if json_params is not None: encoded_params = json.dumps(json_params) headers = {'Content-Type': 'application/json'} else: encode...
def make_api_call(self, method, url, json_params=None)
Accesses the branch API :param method: The HTTP method :param url: The URL :param json_params: JSON parameters :return: The parsed response
2.413167
2.340203
1.031179
def wrapper(cls): for attr in dir(lib): if attr.startswith(lib_prefix): name = attr.replace(lib_prefix, enum_prefix) cls.add(name, getattr(lib, attr)) return cls return wrapper
def make_enum(lib_prefix, enum_prefix='')
Class decorator for automatically adding enum values. The values are read directly from the :attr:`spotify.lib` CFFI wrapper around libspotify. All values starting with ``lib_prefix`` are added. The ``lib_prefix`` is stripped from the name. Optionally, ``enum_prefix`` can be specified to add a prefix t...
2.903303
2.486048
1.167839
if isinstance(value, text_type): return value.encode('utf-8') elif isinstance(value, ffi.CData): return ffi.string(value) elif isinstance(value, binary_type): return value else: raise ValueError('Value must be text, bytes, or char[]')
def to_bytes(value)
Converts bytes, unicode, and C char arrays to bytes. Unicode strings are encoded to UTF-8.
2.912375
2.812014
1.03569
if value == ffi.NULL: return None elif isinstance(value, ffi.CData): return ffi.string(value) else: raise ValueError('Value must be char[] or NULL')
def to_bytes_or_none(value)
Converts C char arrays to bytes and C NULL values to None.
4.669926
3.179096
1.468947
if isinstance(value, ffi.CData): return ffi.string(value).decode('utf-8') elif isinstance(value, binary_type): return value.decode('utf-8') elif isinstance(value, text_type): return value else: raise ValueError('Value must be text, bytes, or char[]')
def to_unicode(value)
Converts bytes, unicode, and C char arrays to unicode strings. Bytes and C char arrays are decoded from UTF-8.
2.607624
2.56845
1.015252
if value == ffi.NULL: return None elif isinstance(value, ffi.CData): return ffi.string(value).decode('utf-8') else: raise ValueError('Value must be char[] or NULL')
def to_unicode_or_none(value)
Converts C char arrays to unicode and C NULL values to None. C char arrays are decoded from UTF-8.
3.537056
3.177351
1.113209