text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def search(self, fields=[], **kwargs): '''taobao.products.search 搜索产品信息 两种方式搜索所有产品信息(二种至少传一种): 传入关键字q搜索 传入cid和props搜索 返回值支持:product_id,name,pic_path,cid,props,price,tsc 当用户指定了cid并且cid为垂直市场(3C电器城、鞋城)的类目id时,默认只返回小二确认的产品。如果用户没有指定cid,或cid为普通的类目,默认返回商家确认或小二确认的产品。如果用户自定了status字段,以指定的status类型为准''' ...
[ "def", "search", "(", "self", ",", "fields", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.products.search'", ")", "if", "not", "fields", ":", "product", "=", "Product", "(", ")", "fields", "=", "product"...
53.142857
27.285714
def jstemplate(parser, token): """Templatetag to handle any of the Mustache-based templates. Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``, ``[[`` and ``]]`` with ``{{`` and ``}}`` and ``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts with Django's template engine when using any ...
[ "def", "jstemplate", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endjstemplate'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "JSTemplateNode", "(", "nodelist", ")" ]
40
13.833333
def get(self, limit=None, offset=None): """ :param offset: int of the offset to use :param limit: int of max number of puzzles to return :return: list of Transfer dict """ return self.connection.get('account/transfer/admin/array', limit=limi...
[ "def", "get", "(", "self", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "return", "self", ".", "connection", ".", "get", "(", "'account/transfer/admin/array'", ",", "limit", "=", "limit", ",", "offset", "=", "offset", ")" ]
47.285714
15.857143
def merge(cls, first, second): """ Return an AttributeList that is the result of merging first with second. """ merged = AttributeList([], None) assert (isinstance(first, AttributeList)) assert (isinstance(second, AttributeList)) merged._contents = first._content...
[ "def", "merge", "(", "cls", ",", "first", ",", "second", ")", ":", "merged", "=", "AttributeList", "(", "[", "]", ",", "None", ")", "assert", "(", "isinstance", "(", "first", ",", "AttributeList", ")", ")", "assert", "(", "isinstance", "(", "second", ...
32
15
def objects_get(self, bucket, key, projection='noAcl'): """Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. projection: the projection of the object to retrieve. Returns: A parsed object inf...
[ "def", "objects_get", "(", "self", ",", "bucket", ",", "key", ",", "projection", "=", "'noAcl'", ")", ":", "args", "=", "{", "}", "if", "projection", "is", "not", "None", ":", "args", "[", "'projection'", "]", "=", "projection", "url", "=", "Api", "....
36.277778
20.222222
def main(req_port=None, res_port=None, use_security=False): '''main of queue :param req_port: port for clients :param res_port: port for servers ''' if req_port is None: req_port = env.get_req_port() if res_port is None: res_port = env.get_res_port() auth = None try: ...
[ "def", "main", "(", "req_port", "=", "None", ",", "res_port", "=", "None", ",", "use_security", "=", "False", ")", ":", "if", "req_port", "is", "None", ":", "req_port", "=", "env", ".", "get_req_port", "(", ")", "if", "res_port", "is", "None", ":", "...
39.382353
19.735294
def gen_fields(field: Field) -> Generator[Field, None, None]: """ Starting with a Deform :class:`Field`, yield the field itself and any children. """ yield field for c in field.children: for f in gen_fields(c): yield f
[ "def", "gen_fields", "(", "field", ":", "Field", ")", "->", "Generator", "[", "Field", ",", "None", ",", "None", "]", ":", "yield", "field", "for", "c", "in", "field", ".", "children", ":", "for", "f", "in", "gen_fields", "(", "c", ")", ":", "yield...
28.222222
16.444444
def phone_numbers(self): """ :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList """ if self._phone_numbers is None: self._phone_numbers = PhoneNumberList(self) return self._phone_numbers
[ "def", "phone_numbers", "(", "self", ")", ":", "if", "self", ".", "_phone_numbers", "is", "None", ":", "self", ".", "_phone_numbers", "=", "PhoneNumberList", "(", "self", ")", "return", "self", ".", "_phone_numbers" ]
34.428571
9.285714
def check_cache(self, e_tag, match): """Checks the ETag and sends a cache match response if it matches.""" if e_tag != match: return False self.send_response(304) self.send_header("ETag", e_tag) self.send_header("Cache-Control", "max-age={0}"....
[ "def", "check_cache", "(", "self", ",", "e_tag", ",", "match", ")", ":", "if", "e_tag", "!=", "match", ":", "return", "False", "self", ".", "send_response", "(", "304", ")", "self", ".", "send_header", "(", "\"ETag\"", ",", "e_tag", ")", "self", ".", ...
37.727273
10.727273
def insert(self, key, value): """Inserts the item at the specified position. Similar to list.insert().""" self._values.insert(key, self._type_checker.CheckValue(value)) if not self._message_listener.dirty: self._message_listener.Modified()
[ "def", "insert", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "_values", ".", "insert", "(", "key", ",", "self", ".", "_type_checker", ".", "CheckValue", "(", "value", ")", ")", "if", "not", "self", ".", "_message_listener", ".", "di...
50.6
7.6
async def request(self, request): """ Execute a STUN transaction and return the response. """ assert request.transaction_id not in self.transactions if self.integrity_key: self.__add_authentication(request) transaction = stun.Transaction(request, self.server...
[ "async", "def", "request", "(", "self", ",", "request", ")", ":", "assert", "request", ".", "transaction_id", "not", "in", "self", ".", "transactions", "if", "self", ".", "integrity_key", ":", "self", ".", "__add_authentication", "(", "request", ")", "transa...
33.866667
17.6
def list_user_page_views(self, user_id, end_time=None, start_time=None): """ List user page views. Return the user's page view history in json format, similar to the available CSV download. Pagination is used as described in API basics section. Page views are returned in d...
[ "def", "list_user_page_views", "(", "self", ",", "user_id", ",", "end_time", "=", "None", ",", "start_time", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "p...
41.857143
24.25
def generate_overlapping_psds(opt, gwstrain, flen, delta_f, flow, dyn_range_factor=1., precision=None): """Generate a set of overlapping PSDs to cover a stretch of data. This allows one to analyse a long stretch of data with PSD measurements that change with time. Paramete...
[ "def", "generate_overlapping_psds", "(", "opt", ",", "gwstrain", ",", "flen", ",", "delta_f", ",", "flow", ",", "dyn_range_factor", "=", "1.", ",", "precision", "=", "None", ")", ":", "if", "not", "opt", ".", "psd_estimation", ":", "psd", "=", "from_cli", ...
45.977011
22.425287
def v_depth(d, depth): """Iterate values on specific depth. depth has to be greater equal than 0. Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>` """ if depth == 0: yield d else: for node in DictTree.v(d): for nod...
[ "def", "v_depth", "(", "d", ",", "depth", ")", ":", "if", "depth", "==", "0", ":", "yield", "d", "else", ":", "for", "node", "in", "DictTree", ".", "v", "(", "d", ")", ":", "for", "node1", "in", "DictTree", ".", "v_depth", "(", "node", ",", "de...
34.545455
14.090909
def create_report(self, report_type, account_id, term_id=None, params={}): """ Generates a report instance for the canvas account id. https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.create """ if term_id is not None: params["enrollm...
[ "def", "create_report", "(", "self", ",", "report_type", ",", "account_id", ",", "term_id", "=", "None", ",", "params", "=", "{", "}", ")", ":", "if", "term_id", "is", "not", "None", ":", "params", "[", "\"enrollment_term_id\"", "]", "=", "term_id", "url...
36.375
19.625
def calculate_concordance_probability(graph: BELGraph, key: str, cutoff: Optional[float] = None, permutations: Optional[int] = None, percentage: Optional[float] = None,...
[ "def", "calculate_concordance_probability", "(", "graph", ":", "BELGraph", ",", "key", ":", "str", ",", "cutoff", ":", "Optional", "[", "float", "]", "=", "None", ",", "permutations", ":", "Optional", "[", "int", "]", "=", "None", ",", "percentage", ":", ...
47.488372
26.27907
def create(self, attributes): """ Create a new space :param attributes: Refer to API. Pass in argument as dictionary :type attributes: dict :return: Details of newly created space :rtype: dict """ if not isinstance(attributes, dict): r...
[ "def", "create", "(", "self", ",", "attributes", ")", ":", "if", "not", "isinstance", "(", "attributes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Dictionary of values expected'", ")", "attributes", "=", "json", ".", "dumps", "(", "attributes", ")"...
37.769231
15.615385
def defaults(f, self, *args, **kwargs): """ For ``PARAMETERS`` keys, replace None ``kwargs`` with ``self`` attr values. Should be applied on the top of any decorator stack so other decorators see the "right" kwargs. Will also apply transformations found in ``TRANSFORMS``. """ for name, dat...
[ "def", "defaults", "(", "f", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "data", "in", "PARAMETERS", ".", "iteritems", "(", ")", ":", "kwargs", "[", "name", "]", "=", "kwargs", ".", "get", "(", "name", ...
37.5
18.214286
async def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): """Build a building.""" if isinstance(near, Unit): near = near.position.to2 elif near is not None: ...
[ "async", "def", "build", "(", "self", ",", "building", ":", "UnitTypeId", ",", "near", ":", "Union", "[", "Point2", ",", "Point3", "]", ",", "max_distance", ":", "int", "=", "20", ",", "unit", ":", "Optional", "[", "Unit", "]", "=", "None", ",", "r...
41.722222
27.111111
def get_random(self): """ Returns a random statement from the database """ Statement = self.get_model('statement') statement = Statement.objects.order_by('?').first() if statement is None: raise self.EmptyDatabaseException() return statement
[ "def", "get_random", "(", "self", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "statement", "=", "Statement", ".", "objects", ".", "order_by", "(", "'?'", ")", ".", "first", "(", ")", "if", "statement", "is", "None", "...
25.083333
17.583333
def update_parent_directory_number(self, parent_dir_num): # type: (int) -> None ''' A method to update the parent directory number for this Path Table Record from the directory record. Parameters: parent_dir_num - The new parent directory number to assign to this PTR. ...
[ "def", "update_parent_directory_number", "(", "self", ",", "parent_dir_num", ")", ":", "# type: (int) -> None", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'Path Table Record not yet initialized'", ")", "s...
38.142857
24.428571
def __neighbor_indexes_points(self, optic_object): """! @brief Return neighbors of the specified object in case of sequence of points. @param[in] optic_object (optics_descriptor): Object for which neighbors should be returned in line with connectivity radius. @return (list) List ...
[ "def", "__neighbor_indexes_points", "(", "self", ",", "optic_object", ")", ":", "kdnodes", "=", "self", ".", "__kdtree", ".", "find_nearest_dist_nodes", "(", "self", ".", "__sample_pointer", "[", "optic_object", ".", "index_object", "]", ",", "self", ".", "__eps...
55.333333
39.416667
def inherit_flags(toolset, base, prohibited_properties = []): """Brings all flag definitions from the 'base' toolset into the 'toolset' toolset. Flag definitions whose conditions make use of properties in 'prohibited-properties' are ignored. Don't confuse property and feature, for example <debug-symbols...
[ "def", "inherit_flags", "(", "toolset", ",", "base", ",", "prohibited_properties", "=", "[", "]", ")", ":", "assert", "isinstance", "(", "toolset", ",", "basestring", ")", "assert", "isinstance", "(", "base", ",", "basestring", ")", "assert", "is_iterable_type...
44.566667
23.633333
def option(name, help=""): """Decorator that add an option to the wrapped command or function.""" def decorator(func): options = getattr(func, "options", []) _option = Param(name, help) # Insert at the beginning so the apparent order is preserved options.insert(0, _option) ...
[ "def", "option", "(", "name", ",", "help", "=", "\"\"", ")", ":", "def", "decorator", "(", "func", ")", ":", "options", "=", "getattr", "(", "func", ",", "\"options\"", ",", "[", "]", ")", "_option", "=", "Param", "(", "name", ",", "help", ")", "...
34.181818
15.090909
def _init_notes(self): """Set up the UserNotes page with the initial JSON schema.""" self.cached_json = { 'ver': self.schema, 'users': {}, 'constants': { 'users': [x.name for x in self.subreddit.moderator()], 'warnings': Note.warnings ...
[ "def", "_init_notes", "(", "self", ")", ":", "self", ".", "cached_json", "=", "{", "'ver'", ":", "self", ".", "schema", ",", "'users'", ":", "{", "}", ",", "'constants'", ":", "{", "'users'", ":", "[", "x", ".", "name", "for", "x", "in", "self", ...
32.5
17.916667
def _parse_from_table(html_chunk, what): """ Go thru table data in `html_chunk` and try to locate content of the neighbor cell of the cell containing `what`. Returns: str: Table data or None. """ ean_tag = html_chunk.find("tr", fn=must_contain("th", what, "td")) if not ean_tag: ...
[ "def", "_parse_from_table", "(", "html_chunk", ",", "what", ")", ":", "ean_tag", "=", "html_chunk", ".", "find", "(", "\"tr\"", ",", "fn", "=", "must_contain", "(", "\"th\"", ",", "what", ",", "\"td\"", ")", ")", "if", "not", "ean_tag", ":", "return", ...
26.857143
19.857143
def download_kitchen(split=False): """Download structured grid of kitchen with velocity field. Use the ``split`` argument to extract all of the furniture in the kitchen. """ mesh = _download_and_read('kitchen.vtk') if not split: return mesh extents = { 'door' : (27, 27, 14, 18, ...
[ "def", "download_kitchen", "(", "split", "=", "False", ")", ":", "mesh", "=", "_download_and_read", "(", "'kitchen.vtk'", ")", "if", "not", "split", ":", "return", "mesh", "extents", "=", "{", "'door'", ":", "(", "27", ",", "27", ",", "14", ",", "18", ...
37.171429
7.971429
def __enforce_only_strings_dict(dictionary): ''' Returns a dictionary that has string keys and values. ''' ret = {} for key, value in iteritems(dictionary): ret[six.text_type(key)] = six.text_type(value) return ret
[ "def", "__enforce_only_strings_dict", "(", "dictionary", ")", ":", "ret", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "dictionary", ")", ":", "ret", "[", "six", ".", "text_type", "(", "key", ")", "]", "=", "six", ".", "text_type"...
23.9
23.9
def get_assessment_section_mdata(): """Return default mdata map for AssessmentSection""" return { 'assessment_taken': { 'element_label': { 'text': 'assessment taken', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCR...
[ "def", "get_assessment_section_mdata", "(", ")", ":", "return", "{", "'assessment_taken'", ":", "{", "'element_label'", ":", "{", "'text'", ":", "'assessment taken'", ",", "'languageTypeId'", ":", "str", "(", "DEFAULT_LANGUAGE_TYPE", ")", ",", "'scriptTypeId'", ":",...
35.52
15.36
def setattrs(obj, **kwargs): """ >>> data = SimpleNamespace() >>> setattrs(data, a=1, b=2) # doctest:+ELLIPSIS namespace(a=1, b=2) """ for key, value in kwargs.items(): setattr(obj, key, value) return obj
[ "def", "setattrs", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "obj", ",", "key", ",", "value", ")", "return", "obj" ]
25.888889
9.666667
def B3(formula): """ Rewrite formula eval result into Boolean3 :param formula: :return: Boolean3 """ if isinstance(formula, true) or formula is True or formula == Boolean3.Top.name or formula == Boolean3.Top.value: return Boolean3.Top if isinstance(formula, false) or formula is False...
[ "def", "B3", "(", "formula", ")", ":", "if", "isinstance", "(", "formula", ",", "true", ")", "or", "formula", "is", "True", "or", "formula", "==", "Boolean3", ".", "Top", ".", "name", "or", "formula", "==", "Boolean3", ".", "Top", ".", "value", ":", ...
37.833333
24.5
def add_callback(self, method): """ Attaches a mehtod that will be called when the future finishes. :param method: A callable from an actor that will be called when the future completes. The only argument for that method must be the future itself from wich you can get th...
[ "def", "add_callback", "(", "self", ",", "method", ")", ":", "from_actor", "=", "get_current", "(", ")", "if", "from_actor", "is", "not", "None", ":", "callback", "=", "(", "method", ",", "from_actor", ".", "channel", ",", "from_actor", ".", "url", ")", ...
44.793103
18.241379
def query_entity_with_permission(self, permission, user=None, Model=Entity): """Filter a query on an :class:`Entity` or on of its subclasses. Usage:: read_q = security.query_entity_with_permission(READ, Model=MyModel) MyModel.query.filter(read_q) It should always be pl...
[ "def", "query_entity_with_permission", "(", "self", ",", "permission", ",", "user", "=", "None", ",", "Model", "=", "Entity", ")", ":", "assert", "isinstance", "(", "permission", ",", "Permission", ")", "assert", "issubclass", "(", "Model", ",", "Entity", ")...
36.392857
22.285714
def generate(env): """Add Builders and construction variables for the mwcc to an Environment.""" import SCons.Defaults import SCons.Tool set_vars(env) static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CActi...
[ "def", "generate", "(", "env", ")", ":", "import", "SCons", ".", "Defaults", "import", "SCons", ".", "Tool", "set_vars", "(", "env", ")", "static_obj", ",", "shared_obj", "=", "SCons", ".", "Tool", ".", "createObjBuilders", "(", "env", ")", "for", "suffi...
31.375
21.45
def _ask_openapi(): """Return whether we should create a (new) skeleton.""" if Path('openapi.yml').exists(): question = 'Override local openapi.yml with a new skeleton? (y/N) ' default = False else: question = 'Do you have REST endpoints and wish to create an ...
[ "def", "_ask_openapi", "(", ")", ":", "if", "Path", "(", "'openapi.yml'", ")", ".", "exists", "(", ")", ":", "question", "=", "'Override local openapi.yml with a new skeleton? (y/N) '", "default", "=", "False", "else", ":", "question", "=", "'Do you have REST endpoi...
36.388889
15.888889
def optimized(fn): """Decorator that will call the optimized c++ version of a pycast function if available rather than theo original pycast function :param function fn: original pycast function :return: return the wrapped function :rtype: function """ def _optimized(self, *args, **kwa...
[ "def", "optimized", "(", "fn", ")", ":", "def", "_optimized", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\" This method calls the pycastC function if\n optimization is enabled and the pycastC function\n is available.\n\n :param: ...
40.681818
21.954545
def fill_datetime(self): """Returns when the slot was filled. Returns: A datetime.datetime. Raises: SlotNotFilledError if the value hasn't been filled yet. """ if not self.filled: raise SlotNotFilledError('Slot with name "%s", key "%s" not yet filled.' ...
[ "def", "fill_datetime", "(", "self", ")", ":", "if", "not", "self", ".", "filled", ":", "raise", "SlotNotFilledError", "(", "'Slot with name \"%s\", key \"%s\" not yet filled.'", "%", "(", "self", ".", "name", ",", "self", ".", "key", ")", ")", "return", "self...
28.230769
20.615385
def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(...
[ "def", "image_meta_delete", "(", "self", ",", "image_id", "=", "None", ",", "# pylint: disable=C0103", "name", "=", "None", ",", "keys", "=", "None", ")", ":", "nt_ks", "=", "self", ".", "compute_conn", "if", "name", ":", "for", "image", "in", "nt_ks", "...
38.117647
15.411765
def require_qt(func): """Specify that a function requires a Qt application. Use this decorator to specify that a function needs a running Qt application before it can run. An error is raised if that is not the case. """ @wraps(func) def wrapped(*args, **kwargs): if not QApplication...
[ "def", "require_qt", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "QApplication", ".", "instance", "(", ")", ":", "# pragma: no cover", "raise", "RuntimeError...
33.071429
20.357143
def __update(self, task_source): """ Recheck next start of tasks from the given one only :param task_source: source to check :return: None """ next_start = task_source.next_start() if next_start is not None: if next_start.tzinfo is None or next_start.tzinfo != timezone.utc: raise ValueError('Inval...
[ "def", "__update", "(", "self", ",", "task_source", ")", ":", "next_start", "=", "task_source", ".", "next_start", "(", ")", "if", "next_start", "is", "not", "None", ":", "if", "next_start", ".", "tzinfo", "is", "None", "or", "next_start", ".", "tzinfo", ...
30.888889
15.888889
def _sanitize_config(custom_config): """Checks whether ``custom_config`` is sane and returns a sanitized dict <str -> (str|object)> It checks if keys are all strings and sanitizes values of a given dictionary as follows: - If string, number or boolean is given as a value, it is converted to string. ...
[ "def", "_sanitize_config", "(", "custom_config", ")", ":", "if", "not", "isinstance", "(", "custom_config", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Component-specific configuration must be given as a dict type, given: %s\"", "%", "str", "(", "type", "(", ...
47.096774
26.806452
def getCollectionClass(cls, name) : """Return the class object of a collection given its 'name'""" try : return cls.collectionClasses[name] except KeyError : raise KeyError( "There is no Collection Class of type: '%s'; currently supported values: [%s]" % (name, ', '.join(...
[ "def", "getCollectionClass", "(", "cls", ",", "name", ")", ":", "try", ":", "return", "cls", ".", "collectionClasses", "[", "name", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "\"There is no Collection Class of type: '%s'; currently supported values: [%s]\...
58
28.666667
def index_order(self, sources=True, destinations=True): """ Return the order of indices as they appear in array references. Use *source* and *destination* to filter output """ if sources: arefs = chain(*self.sources.values()) else: arefs = [] ...
[ "def", "index_order", "(", "self", ",", "sources", "=", "True", ",", "destinations", "=", "True", ")", ":", "if", "sources", ":", "arefs", "=", "chain", "(", "*", "self", ".", "sources", ".", "values", "(", ")", ")", "else", ":", "arefs", "=", "[",...
28.809524
19.666667
def get_item_content(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, **kwargs): """GetItemContent. Get Item Metadata and/or Content...
[ "def", "get_item_content", "(", "self", ",", "repository_id", ",", "path", ",", "project", "=", "None", ",", "scope_path", "=", "None", ",", "recursion_level", "=", "None", ",", "include_content_metadata", "=", "None", ",", "latest_processed_change", "=", "None"...
74.607143
40.303571
def open_database(self): """ Opens the sqlite database. """ if not self.con: try: self.con = psycopg2.connect(host=self.host, database=self.dbname, user=self.user, password=self.password, port=self.port) exc...
[ "def", "open_database", "(", "self", ")", ":", "if", "not", "self", ".", "con", ":", "try", ":", "self", ".", "con", "=", "psycopg2", ".", "connect", "(", "host", "=", "self", ".", "host", ",", "database", "=", "self", ".", "dbname", ",", "user", ...
32.307692
13.846154
def get_context(self): """Return an SSL.Context from self attributes.""" # See https://code.activestate.com/recipes/442473/ c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_c...
[ "def", "get_context", "(", "self", ")", ":", "# See https://code.activestate.com/recipes/442473/", "c", "=", "SSL", ".", "Context", "(", "SSL", ".", "SSLv23_METHOD", ")", "c", ".", "use_privatekey_file", "(", "self", ".", "private_key", ")", "if", "self", ".", ...
42.555556
11.333333
def quat_to_rotation_matrix(q): """Convert unit quaternion to rotation matrix Parameters ------------- q : (4,) ndarray Unit quaternion, scalar as first element Returns ---------------- R : (3,3) ndarray Rotation matrix """ q = q.flatten() asser...
[ "def", "quat_to_rotation_matrix", "(", "q", ")", ":", "q", "=", "q", ".", "flatten", "(", ")", "assert", "q", ".", "size", "==", "4", "assert_almost_equal", "(", "np", ".", "linalg", ".", "norm", "(", "q", ")", ",", "1.0", ",", "err_msg", "=", "\"N...
29.28
20.4
def latex(self): """ Returns a string representation for use in LaTeX """ if not self: return "" s = str(self) s = s.replace("==", " = ") s = s.replace("<=", " \leq ") s = s.replace(">=", " \geq ") s = s.replace("&&", r" \text{ and } ")...
[ "def", "latex", "(", "self", ")", ":", "if", "not", "self", ":", "return", "\"\"", "s", "=", "str", "(", "self", ")", "s", "=", "s", ".", "replace", "(", "\"==\"", ",", "\" = \"", ")", "s", "=", "s", ".", "replace", "(", "\"<=\"", ",", "\" \\le...
28.538462
11.153846
def volatility(self, n, freq=None, which='close', ann=True, model='ln', min_periods=1, rolling='simple'): """Return the annualized volatility series. N is the number of lookback periods. :param n: int, number of lookback periods :param freq: resample frequency or None :param which: pric...
[ "def", "volatility", "(", "self", ",", "n", ",", "freq", "=", "None", ",", "which", "=", "'close'", ",", "ann", "=", "True", ",", "model", "=", "'ln'", ",", "min_periods", "=", "1", ",", "rolling", "=", "'simple'", ")", ":", "if", "model", "not", ...
50.487179
20.769231
def get_external_ip(): """Returns the current external IP, based on http://icanhazip.com/. It will probably fail if the network setup is too complicated or the service is down. """ response = requests.get('http://icanhazip.com/') if not response.ok: raise RuntimeError('Failed to get exte...
[ "def", "get_external_ip", "(", ")", ":", "response", "=", "requests", ".", "get", "(", "'http://icanhazip.com/'", ")", "if", "not", "response", ".", "ok", ":", "raise", "RuntimeError", "(", "'Failed to get external ip: %s'", "%", "response", ".", "content", ")",...
42.222222
17.333333
def import_items(import_directives, style, quiet_load=False): """ Import the items in import_directives and return a list of the imported items Each item in import_directives should be one of the following forms * a tuple like ('module.submodule', ('classname1', 'classname2')), which indicates a 'f...
[ "def", "import_items", "(", "import_directives", ",", "style", ",", "quiet_load", "=", "False", ")", ":", "imported_objects", "=", "{", "}", "for", "directive", "in", "import_directives", ":", "try", ":", "# First try a straight import", "if", "isinstance", "(", ...
58.571429
29.914286
def neg(self): """Negative value of all components.""" self.x = -self.x self.y = -self.y self.z = -self.z
[ "def", "neg", "(", "self", ")", ":", "self", ".", "x", "=", "-", "self", ".", "x", "self", ".", "y", "=", "-", "self", ".", "y", "self", ".", "z", "=", "-", "self", ".", "z" ]
26.6
14.8
def update_edit_menu(self): """Update edit menu""" widget, textedit_properties = self.get_focus_widget_properties() if textedit_properties is None: # widget is not an editor/console return # !!! Below this line, widget is expected to be a QPlainTextEdit # in...
[ "def", "update_edit_menu", "(", "self", ")", ":", "widget", ",", "textedit_properties", "=", "self", ".", "get_focus_widget_properties", "(", ")", "if", "textedit_properties", "is", "None", ":", "# widget is not an editor/console\r", "return", "# !!! Below this line, widg...
42.388889
21.194444
def _check_err(resp, url_suffix, data, allow_pagination): """ Raise DataServiceError if the response wasn't successful. :param resp: requests.Response back from the request :param url_suffix: str url to include in an error message :param data: data payload we sent :param ...
[ "def", "_check_err", "(", "resp", ",", "url_suffix", ",", "data", ",", "allow_pagination", ")", ":", "total_pages", "=", "resp", ".", "headers", ".", "get", "(", "'x-total-pages'", ")", "if", "not", "allow_pagination", "and", "total_pages", ":", "raise", "Un...
51.666667
17.333333
def _throat_props(self): r''' Helper Function to calculate the throat normal vectors ''' network = self.network net_Ts = network.throats(self.name) conns = network['throat.conns'][net_Ts] p1 = conns[:, 0] p2 = conns[:, 1] coords = network['pore.coo...
[ "def", "_throat_props", "(", "self", ")", ":", "network", "=", "self", ".", "network", "net_Ts", "=", "network", ".", "throats", "(", "self", ".", "name", ")", "conns", "=", "network", "[", "'throat.conns'", "]", "[", "net_Ts", "]", "p1", "=", "conns",...
37.714286
14.428571
def cdf(self, y, f, var): r""" Cumulative density function of the likelihood. Parameters ---------- y: ndarray query quantiles, i.e.\ :math:`P(Y \leq y)`. f: ndarray latent function from the GLM prior (:math:`\mathbf{f} = \boldsymbol\...
[ "def", "cdf", "(", "self", ",", "y", ",", "f", ",", "var", ")", ":", "var", "=", "self", ".", "_check_param", "(", "var", ")", "return", "norm", ".", "cdf", "(", "y", ",", "loc", "=", "f", ",", "scale", "=", "np", ".", "sqrt", "(", "var", "...
30.772727
17.727273
def part(self, channel, reason=''): """ Part a channel. Required arguments: * channel - Channel to part. Optional arguments: * reason='' - Reason for parting. """ with self.lock: self.is_in_channel(channel) self.send('PART %s :%s' ...
[ "def", "part", "(", "self", ",", "channel", ",", "reason", "=", "''", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "is_in_channel", "(", "channel", ")", "self", ".", "send", "(", "'PART %s :%s'", "%", "(", "channel", ",", "reason", ")", ...
31.764706
9.647059
def remove_user(config, group, username): """Remove specified user from specified group.""" client = Client() client.prepare_connection() group_api = API(client) try: group_api.remove_user(group, username) except ldap_tools.exceptions.NoGroupsFound: # pragma:...
[ "def", "remove_user", "(", "config", ",", "group", ",", "username", ")", ":", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "group_api", "=", "API", "(", "client", ")", "try", ":", "group_api", ".", "remove_user", "(",...
48.142857
17.5
def _generate_metrics(bam_fname, config_file, ref_file, bait_file, target_file): """Run Picard commands to generate metrics files when missing. """ with open(config_file) as in_handle: config = yaml.safe_load(in_handle) broad_runner = broad.runner_from_config(config) ba...
[ "def", "_generate_metrics", "(", "bam_fname", ",", "config_file", ",", "ref_file", ",", "bait_file", ",", "target_file", ")", ":", "with", "open", "(", "config_file", ")", "as", "in_handle", ":", "config", "=", "yaml", ".", "safe_load", "(", "in_handle", ")"...
43.047619
7.952381
def array_to_encoded(array, dtype=None, encoding='base64'): """ Export a numpy array to a compact serializable dictionary. Parameters ------------ array : array Any numpy array dtype : str or None Optional dtype to encode array encoding : str 'base64' or 'binary' Retu...
[ "def", "array_to_encoded", "(", "array", ",", "dtype", "=", "None", ",", "encoding", "=", "'base64'", ")", ":", "array", "=", "np", ".", "asanyarray", "(", "array", ")", "shape", "=", "array", ".", "shape", "# ravel also forces contiguous", "flat", "=", "n...
27.575
16.825
def prune_by_ngram_count(self, minimum=None, maximum=None, label=None): """Removes results rows whose total n-gram count (across all works bearing this n-gram) is outside the range specified by `minimum` and `maximum`. For each text, the count used as part of the sum across all ...
[ "def", "prune_by_ngram_count", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by n-gram count'", ")", "def", "calculate_total", "(", "gro...
43.076923
21.057692
def extract(data, defs, byteoffset=0): """ Extract fields from data into a structure based on field definitions in defs. byteoffset is added to each local byte offset to get the byte offset returned for each field. defs is a list of lists comprising start, width in bits, format,...
[ "def", "extract", "(", "data", ",", "defs", ",", "byteoffset", "=", "0", ")", ":", "retval", "=", "ListDict", "(", ")", "for", "fielddef", "in", "defs", ":", "start", ",", "width", ",", "form", ",", "name", ",", "desc", "=", "fielddef", "if", "form...
43.023256
18.232558
def give_us_somethin_to_talk_about(self, message): """new topic: set the room topic to a random conversation starter.""" r = requests.get("http://www.chatoms.com/chatom.json?Normal=1&Fun=2&Philosophy=3&Out+There=4") data = r.json() self.set_topic(data["text"], message=message)
[ "def", "give_us_somethin_to_talk_about", "(", "self", ",", "message", ")", ":", "r", "=", "requests", ".", "get", "(", "\"http://www.chatoms.com/chatom.json?Normal=1&Fun=2&Philosophy=3&Out+There=4\"", ")", "data", "=", "r", ".", "json", "(", ")", "self", ".", "set_t...
61
20.4
def remove(self): """ Remove a cursor. Remove all `Selection`\\s, disconnect all callbacks, and allow the cursor to be garbage collected. """ for disconnectors in self._disconnectors: disconnectors() for sel in self.selections: self.remove...
[ "def", "remove", "(", "self", ")", ":", "for", "disconnectors", "in", "self", ".", "_disconnectors", ":", "disconnectors", "(", ")", "for", "sel", "in", "self", ".", "selections", ":", "self", ".", "remove_selection", "(", "sel", ")", "for", "s", "in", ...
31.428571
11.857143
def identify(file_elements): """ Outputs an ordered sequence of instances of TopLevel types. Elements start with an optional TableElement, followed by zero or more pairs of (TableHeaderElement, TableElement). """ if not file_elements: return _validate_file_elements(file_elements) ...
[ "def", "identify", "(", "file_elements", ")", ":", "if", "not", "file_elements", ":", "return", "_validate_file_elements", "(", "file_elements", ")", "# An iterator over enumerate(the non-metadata) elements", "iterator", "=", "PeekableIterator", "(", "(", "element_i", ","...
34.025
25.425
def norm_package_version(version): """Normalize a version by removing extra spaces and parentheses.""" if version: version = ','.join(v.strip() for v in version.split(',')).strip() if version.startswith('(') and version.endswith(')'): version = version[1:-1] version = ''.jo...
[ "def", "norm_package_version", "(", "version", ")", ":", "if", "version", ":", "version", "=", "','", ".", "join", "(", "v", ".", "strip", "(", ")", "for", "v", "in", "version", ".", "split", "(", "','", ")", ")", ".", "strip", "(", ")", "if", "v...
30.307692
23.153846
def cmd_ssh(self, argv, help): """Log into the instance with ssh using the automatically generated known hosts""" parser = argparse.ArgumentParser( prog="%s ssh" % self.progname, description=help, ) instances = self.get_instances(command='init_ssh_key') pa...
[ "def", "cmd_ssh", "(", "self", ",", "argv", ",", "help", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"%s ssh\"", "%", "self", ".", "progname", ",", "description", "=", "help", ",", ")", "instances", "=", "self", ".",...
39.137255
13.058824
def elements(self): """Return the BIC's Party Prefix, Country Code, Party Suffix and Branch Code as a tuple.""" return (self.party_prefix, self.country_code, self.party_suffix, self.branch_code)
[ "def", "elements", "(", "self", ")", ":", "return", "(", "self", ".", "party_prefix", ",", "self", ".", "country_code", ",", "self", ".", "party_suffix", ",", "self", ".", "branch_code", ")" ]
46
12
def load(self, path): """ Load yaml-formatted config file. Parameters ---------- path : str path to config file """ with open(path) as f: self.config = full_load(f) if self.config is None: sys.stderr.write("War...
[ "def", "load", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "self", ".", "config", "=", "full_load", "(", "f", ")", "if", "self", ".", "config", "is", "None", ":", "sys", ".", "stderr", ".", "write", "("...
26.5
13.428571
def get(self): '''Called by the protocol consumer''' if self._current: return self._resume(self._current, False) else: return self._get(None)
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "_current", ":", "return", "self", ".", "_resume", "(", "self", ".", "_current", ",", "False", ")", "else", ":", "return", "self", ".", "_get", "(", "None", ")" ]
30.666667
15.333333
def start(self): """ Start the client. If it is already :attr:`running`, :class:`RuntimeError` is raised. While the client is running, it will try to keep an XMPP connection open to the server associated with :attr:`local_jid`. """ if self.running: ra...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "running", ":", "raise", "RuntimeError", "(", "\"client already running\"", ")", "self", ".", "_main_task", "=", "asyncio", ".", "ensure_future", "(", "self", ".", "_main", "(", ")", ",", "loop", ...
32.6875
18.6875
def _copy_template_to_config(self, template_path, config_path, overwrite=False): """Write the default config from a template. :type template_path: str :param template_path: The template config file path. :type config_path: str :param config_path...
[ "def", "_copy_template_to_config", "(", "self", ",", "template_path", ",", "config_path", ",", "overwrite", "=", "False", ")", ":", "config_path", "=", "os", ".", "path", ".", "expanduser", "(", "config_path", ")", "if", "not", "overwrite", "and", "os", ".",...
36.814815
18.925926
def strel_line(length, angle): """Create a line structuring element for morphological operations length - distance between first and last pixels of the line, rounded down angle - angle from the horizontal, counter-clockwise in degrees. Note: uses draw_line's Bresenham algorithm to select ...
[ "def", "strel_line", "(", "length", ",", "angle", ")", ":", "angle", "=", "float", "(", "angle", ")", "*", "np", ".", "pi", "/", "180.", "x_off", "=", "int", "(", "np", ".", "finfo", "(", "float", ")", ".", "eps", "+", "np", ".", "cos", "(", ...
36.96
17.28
def stop(vm_): ''' Hard power down the virtual machine, this is equivalent to pulling the power CLI Example: .. code-block:: bash salt '*' virt.stop <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: ...
[ "def", "stop", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi", "...
22.6
22
def sqlinsert(table, row): """Generates SQL insert into table ... Returns (sql, parameters) >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'}) ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto']) >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'}) ('insert into t2 (id, name) ...
[ "def", "sqlinsert", "(", "table", ",", "row", ")", ":", "validate_name", "(", "table", ")", "fields", "=", "sorted", "(", "row", ".", "keys", "(", ")", ")", "validate_names", "(", "fields", ")", "values", "=", "[", "row", "[", "field", "]", "for", ...
38.4375
15.625
def is_equal(self, other): """ Computes whether two Partial Orderings contain the same information """ if not (hasattr(other, 'get_domain') or hasattr(other, 'upper') or hasattr(other, 'lower')): other = self.coerce(other) if self.is_domain_equal(other) \ ...
[ "def", "is_equal", "(", "self", ",", "other", ")", ":", "if", "not", "(", "hasattr", "(", "other", ",", "'get_domain'", ")", "or", "hasattr", "(", "other", ",", "'upper'", ")", "or", "hasattr", "(", "other", ",", "'lower'", ")", ")", ":", "other", ...
44.363636
19.272727
def section(self, ctx, optional=False): """ Return section of the config for a specific context (sub-command). Parameters: ctx (Context): The Click context object. optional (bool): If ``True``, return an empty config object when section is missing. ...
[ "def", "section", "(", "self", ",", "ctx", ",", "optional", "=", "False", ")", ":", "values", "=", "self", ".", "load", "(", ")", "try", ":", "return", "values", "[", "ctx", ".", "info_name", "]", "except", "KeyError", ":", "if", "optional", ":", "...
38.55
24.45
def consume(self, word_ids: mx.nd.NDArray) -> None: """ Consumes a word for each trie, updating respective states. :param word_ids: The set of word IDs. """ word_ids = word_ids.asnumpy().tolist() for i, word_id in enumerate(word_ids): if self.global_avoid_sta...
[ "def", "consume", "(", "self", ",", "word_ids", ":", "mx", ".", "nd", ".", "NDArray", ")", "->", "None", ":", "word_ids", "=", "word_ids", ".", "asnumpy", "(", ")", ".", "tolist", "(", ")", "for", "i", ",", "word_id", "in", "enumerate", "(", "word_...
44.416667
16.083333
def pattern(head, *args, mode=1, wc_name=None, conditions=None, **kwargs) \ -> Pattern: """'Flat' constructor for the Pattern class Positional and keyword arguments are mapped into `args` and `kwargs`, respectively. Useful for defining rules that match an instantiated Expression with specific a...
[ "def", "pattern", "(", "head", ",", "*", "args", ",", "mode", "=", "1", ",", "wc_name", "=", "None", ",", "conditions", "=", "None", ",", "*", "*", "kwargs", ")", "->", "Pattern", ":", "if", "len", "(", "args", ")", "==", "0", ":", "args", "=",...
37.285714
18.714286
def find_embedding(elt, embedding=None): """Try to get elt embedding elements. :param embedding: embedding element. Must have a module. :return: a list of [module [,class]*] embedding elements which define elt. :rtype: list """ result = [] # result is empty in the worst case # start to ...
[ "def", "find_embedding", "(", "elt", ",", "embedding", "=", "None", ")", ":", "result", "=", "[", "]", "# result is empty in the worst case", "# start to get module", "module", "=", "getmodule", "(", "elt", ")", "if", "module", "is", "not", "None", ":", "# if ...
32.03125
21.0625
def group_dict_by_value(d: dict) -> dict: """ Group a dictionary by values. Parameters ---------- d : dict Input dictionary Returns ------- dict Output dictionary. The keys are the values of the initial dictionary and the values ae given by a list of keys corre...
[ "def", "group_dict_by_value", "(", "d", ":", "dict", ")", "->", "dict", ":", "d_out", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "v", "in", "d_out", ":", "d_out", "[", "v", "]", ".", "append", "(", "k",...
23.321429
21.535714
def pov(self, color: chess.Color) -> "Score": """Get the score from the point of view of the given *color*.""" return self.relative if self.turn == color else -self.relative
[ "def", "pov", "(", "self", ",", "color", ":", "chess", ".", "Color", ")", "->", "\"Score\"", ":", "return", "self", ".", "relative", "if", "self", ".", "turn", "==", "color", "else", "-", "self", ".", "relative" ]
62.333333
11.666667
def separate(text): '''Takes text and separates it into a list of words''' alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: if char in alphabet or char in alphabet.upper(): news...
[ "def", "separate", "(", "text", ")", ":", "alphabet", "=", "'abcdefghijklmnopqrstuvwxyz'", "words", "=", "text", ".", "split", "(", ")", "standardwords", "=", "[", "]", "for", "word", "in", "words", ":", "newstr", "=", "''", "for", "char", "in", "word", ...
33.384615
14.307692
def custom_sort(param): """Custom Click(Command|Group).params sorter. Case insensitive sort with capitals after lowercase. --version at the end since I can't sort --help. :param click.core.Option param: Parameter to evaluate. :return: Sort weight. :rtype: int """ ...
[ "def", "custom_sort", "(", "param", ")", ":", "option", "=", "param", ".", "opts", "[", "0", "]", ".", "lstrip", "(", "'-'", ")", "if", "param", ".", "param_type_name", "!=", "'option'", ":", "return", "False", ",", "return", "True", ",", "option", "...
35.142857
22.571429
def send_voice(self, voice, **options): """ Send an OPUS-encoded .ogg audio file. :param voice: Object containing the audio data :param options: Additional sendVoice options (see https://core.telegram.org/bots/api#sendvoice) :Example: >>> with open("voice.o...
[ "def", "send_voice", "(", "self", ",", "voice", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendVoice\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "voice", "=", "voice", ",", "*", ...
30.5
16.875
def register_post_execute(self, func): """Register a function for calling after code execution. """ if not callable(func): raise ValueError('argument %s must be callable' % func) self._post_execute[func] = True
[ "def", "register_post_execute", "(", "self", ",", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "ValueError", "(", "'argument %s must be callable'", "%", "func", ")", "self", ".", "_post_execute", "[", "func", "]", "=", "True" ]
41.5
6.666667
def __AddAdditionalProperties(self, message, schema, properties): """Add an additionalProperties field to message.""" additional_properties_info = schema['additionalProperties'] entries_type_name = self.__AddAdditionalPropertyType( message.name, additional_properties_info) de...
[ "def", "__AddAdditionalProperties", "(", "self", ",", "message", ",", "schema", ",", "properties", ")", ":", "additional_properties_info", "=", "schema", "[", "'additionalProperties'", "]", "entries_type_name", "=", "self", ".", "__AddAdditionalPropertyType", "(", "me...
46.409091
17
def process_path_part(part, parameters): """ Given a part of a path either: - If it is a parameter: parse it to a regex group - Otherwise: escape any special regex characters """ if PARAMETER_REGEX.match(part): parameter_name = part.strip('{}') try...
[ "def", "process_path_part", "(", "part", ",", "parameters", ")", ":", "if", "PARAMETER_REGEX", ".", "match", "(", "part", ")", ":", "parameter_name", "=", "part", ".", "strip", "(", "'{}'", ")", "try", ":", "parameter", "=", "find_parameter", "(", "paramet...
28.809524
10.714286
def super_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hparams.moe_hidden_sizes = "512" hparams.batch_size = 16384 hparams.max_length = 0 # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. h...
[ "def", "super_lm_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "moe_hidden_sizes", "=", "\"512\"", "hparams", ".", "batch_size", "=", "16384", "hparams", ".", ...
38.604167
12.083333
def simple_ensure_index(request, database_name, collection_name): """Ensure a MongoDB index on a particular field name""" name = "Ensure a MongoDB index on a particular field name" if request.method == 'POST': form = EnsureIndexForm(request.POST) if form.is_valid(): result = fo...
[ "def", "simple_ensure_index", "(", "request", ",", "database_name", ",", "collection_name", ")", ":", "name", "=", "\"Ensure a MongoDB index on a particular field name\"", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "EnsureIndexForm", "(", "reque...
41.344828
20.206897
def __release_particle(self): """Pull a particle from the queue and add it to the active list.""" # Calculate a potential angle for the particle. angle = random.randint(int(self.direction_range[0]), int(self.direction_range[1])) velocity = Vector2.from_polar(angle, self.particle_speed) ...
[ "def", "__release_particle", "(", "self", ")", ":", "# Calculate a potential angle for the particle.", "angle", "=", "random", ".", "randint", "(", "int", "(", "self", ".", "direction_range", "[", "0", "]", ")", ",", "int", "(", "self", ".", "direction_range", ...
49.454545
16.636364
def from_time(cls, source): """ datetime.time -> SubRipTime corresponding to time object """ return cls(hours=source.hour, minutes=source.minute, seconds=source.second, milliseconds=source.microsecond // 1000)
[ "def", "from_time", "(", "cls", ",", "source", ")", ":", "return", "cls", "(", "hours", "=", "source", ".", "hour", ",", "minutes", "=", "source", ".", "minute", ",", "seconds", "=", "source", ".", "second", ",", "milliseconds", "=", "source", ".", "...
41.333333
15.333333
def is_pangram(string): """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise. """ return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset...
[ "def", "is_pangram", "(", "string", ")", ":", "return", "is_full_string", "(", "string", ")", "and", "set", "(", "SPACES_RE", ".", "sub", "(", "''", ",", "string", ")", ")", ".", "issuperset", "(", "letters_set", ")" ]
36.111111
21.444444
def get_all(self, **kwargs): """ Get all keys currently stored in etcd. :param keys_only: if True, retrieve only the keys, not the values :returns: sequence of (value, metadata) tuples """ range_response = self.get_all_response(**kwargs) for kv in range_response....
[ "def", "get_all", "(", "self", ",", "*", "*", "kwargs", ")", ":", "range_response", "=", "self", ".", "get_all_response", "(", "*", "*", "kwargs", ")", "for", "kv", "in", "range_response", ".", "kvs", ":", "yield", "(", "kv", ".", "value", ",", "KVMe...
38.3
15.1
def _set_fabric_trunk(self, v, load=False): """ Setter method for fabric_trunk, mapped from YANG variable /interface/fortygigabitethernet/fabric/fabric_trunk (container) If this variable is read-only (config: false) in the source YANG file, then _set_fabric_trunk is considered as a private method. B...
[ "def", "_set_fabric_trunk", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
74.583333
36.583333
def validate(self, scorer=None, k=1, test_size=0.1, stratify=False, shuffle=True, seed=100, indices=None): """Evaluate score by cross-validation. Parameters ---------- scorer : function(y_true,y_pred), default None Scikit-learn like metric that returns a score. k : i...
[ "def", "validate", "(", "self", ",", "scorer", "=", "None", ",", "k", "=", "1", ",", "test_size", "=", "0.1", ",", "stratify", "=", "False", ",", "shuffle", "=", "True", ",", "seed", "=", "100", ",", "indices", "=", "None", ")", ":", "if", "self"...
39.08046
21.827586
def ekucec(handle, segno, recno, column, nvals, cvals, isnull): """ Update a character column entry in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekucec_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record....
[ "def", "ekucec", "(", "handle", ",", "segno", ",", "recno", ",", "column", ",", "nvals", ",", "cvals", ",", "isnull", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "segno", "=", "ctypes", ".", "c_int", "(", "segno", ")", "rec...
37.1
16.833333
def _check_cygwin_installed(cyg_arch='x86_64'): ''' Return True or False if cygwin is installed. Use the cygcheck executable to check install. It is installed as part of the base package, and we use it to check packages ''' path_to_cygcheck = os.sep.join(['C:', ...
[ "def", "_check_cygwin_installed", "(", "cyg_arch", "=", "'x86_64'", ")", ":", "path_to_cygcheck", "=", "os", ".", "sep", ".", "join", "(", "[", "'C:'", ",", "_get_cyg_dir", "(", "cyg_arch", ")", ",", "'bin'", ",", "'cygcheck.exe'", "]", ")", "LOG", ".", ...
38.866667
19
def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, ...
[ "def", "available", "(", "name", ")", ":", "(", "enabled_services", ",", "disabled_services", ")", "=", "_get_service_list", "(", "include_enabled", "=", "True", ",", "include_disabled", "=", "True", ")", "return", "name", "in", "enabled_services", "or", "name",...
31.071429
30.071429
def property_list(self, property_list): """Setter method; for a description see the getter method.""" if property_list is not None: msg = "The 'property_list' init parameter and attribute of " \ "CIMInstance is deprecated; Set only the desired properties " \ "...
[ "def", "property_list", "(", "self", ",", "property_list", ")", ":", "if", "property_list", "is", "not", "None", ":", "msg", "=", "\"The 'property_list' init parameter and attribute of \"", "\"CIMInstance is deprecated; Set only the desired properties \"", "\"instead.\"", "if",...
50.866667
17.2