text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def hasLock(self): ''' hasLock - Property, returns True if we have the lock, or False if we do not. @return <bool> - True/False if we have the lock or not. ''' # If we don't hold it currently, return False if self.held is False: return False ...
[ "def", "hasLock", "(", "self", ")", ":", "# If we don't hold it currently, return False", "if", "self", ".", "held", "is", "False", ":", "return", "False", "# Otherwise if we think we hold it, but it is not held, we have lost it.", "if", "not", "self", ".", "isHeld", ":",...
28.75
0.008415
def run(self): ''' Runs the de-trending step. ''' try: # Load raw data log.info("Loading target data...") self.load_tpf() self.mask_planets() self.plot_aperture([self.dvs.top_right() for i in range(4)]) self.init_...
[ "def", "run", "(", "self", ")", ":", "try", ":", "# Load raw data", "log", ".", "info", "(", "\"Loading target data...\"", ")", "self", ".", "load_tpf", "(", ")", "self", ".", "mask_planets", "(", ")", "self", ".", "plot_aperture", "(", "[", "self", ".",...
34.62
0.001685
def _resolve_placeholder(placeholder, original): """Resolve a placeholder to the given original object. :param placeholder: The placeholder to resolve, in place. :type placeholder: dict :param original: The object that the placeholder represents. :type original: dict """ new = copy.deepcopy...
[ "def", "_resolve_placeholder", "(", "placeholder", ",", "original", ")", ":", "new", "=", "copy", ".", "deepcopy", "(", "original", ")", "# The name remains the same.", "new", "[", "\"name\"", "]", "=", "placeholder", "[", "\"name\"", "]", "new", "[", "\"full_...
40.25
0.001348
def run(self): """ Run the pipeline queue. The pipeline queue will run forever. """ while True: self._event.clear() self._queue.get().run(self._event)
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "self", ".", "_event", ".", "clear", "(", ")", "self", ".", "_queue", ".", "get", "(", ")", ".", "run", "(", "self", ".", "_event", ")" ]
25
0.009662
def smart_open(filename: str, mode: str = 'Ur', buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None, closefd: bool = True) -> IO: """ Context manager (for use with ``with``) that opens a filename and provides a :class:`IO` object. If the filename ...
[ "def", "smart_open", "(", "filename", ":", "str", ",", "mode", ":", "str", "=", "'Ur'", ",", "buffering", ":", "int", "=", "-", "1", ",", "encoding", ":", "str", "=", "None", ",", "errors", ":", "str", "=", "None", ",", "newline", ":", "str", "="...
43.041667
0.000947
def stack_fits(fitslist, outname, axis=0, ctype=None, keep_old=False, fits=False): """ Stack a list of fits files along a given axiis. fitslist: list of fits file to combine outname: output file name axis: axis along which to combine the files fits: If True will axis FITS orderin...
[ "def", "stack_fits", "(", "fitslist", ",", "outname", ",", "axis", "=", "0", ",", "ctype", "=", "None", ",", "keep_old", "=", "False", ",", "fits", "=", "False", ")", ":", "import", "numpy", "try", ":", "import", "pyfits", "except", "ImportError", ":",...
32.327869
0.012303
def Pc(counts, atom_count): r'''Estimates the critcal pressure of an organic compound using the Joback method as a function of chemical structure only. This correlation was developed using the actual number of atoms forming the molecule as well. .. math:: ...
[ "def", "Pc", "(", "counts", ",", "atom_count", ")", ":", "tot", "=", "0.0", "for", "group", ",", "count", "in", "counts", ".", "items", "(", ")", ":", "tot", "+=", "joback_groups_id_dict", "[", "group", "]", ".", "Pc", "*", "count", "Pc", "=", "(",...
34.461538
0.008683
def _simple_convex_hull(points): r"""Compute the convex hull for a set of points. .. _wikibooks: https://en.wikibooks.org/wiki/Algorithm_Implementation/\ Geometry/Convex_hull/Monotone_chain This uses Andrew's monotone chain convex hull algorithm and this code used a `wikibooks`_ imp...
[ "def", "_simple_convex_hull", "(", "points", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-branches", "if", "points", ".", "size", "==", "0", ":", "return", "points", "# First,...
34.978022
0.000306
def chunk(keywords, lines): """ Divide a file into chunks between key words in the list """ chunks = dict() chunk = [] # Create an empty dictionary using all the keywords for keyword in keywords: chunks[keyword] = [] # Populate dictionary with lists of chunks asso...
[ "def", "chunk", "(", "keywords", ",", "lines", ")", ":", "chunks", "=", "dict", "(", ")", "chunk", "=", "[", "]", "# Create an empty dictionary using all the keywords", "for", "keyword", "in", "keywords", ":", "chunks", "[", "keyword", "]", "=", "[", "]", ...
25.541667
0.009434
def transmit(self, frame): """ Convert a frame object to a frame string and transmit to the server. :param Frame frame: the Frame object to transmit """ with self.__listeners_change_condition: listeners = sorted(self.listeners.items()) for (_, listener) in l...
[ "def", "transmit", "(", "self", ",", "frame", ")", ":", "with", "self", ".", "__listeners_change_condition", ":", "listeners", "=", "sorted", "(", "self", ".", "listeners", ".", "items", "(", ")", ")", "for", "(", "_", ",", "listener", ")", "in", "list...
32.214286
0.002153
def add_offset_radec(ra_deg, dec_deg, delta_deg_ra, delta_deg_dec): """ Algorithm to compute RA/Dec from RA/Dec base position plus tangent plane offsets. """ # To radians x = math.radians(delta_deg_ra) y = math.radians(delta_deg_dec) raz = math.radians(ra_deg) decz = math.radians(dec...
[ "def", "add_offset_radec", "(", "ra_deg", ",", "dec_deg", ",", "delta_deg_ra", ",", "delta_deg_dec", ")", ":", "# To radians", "x", "=", "math", ".", "radians", "(", "delta_deg_ra", ")", "y", "=", "math", ".", "radians", "(", "delta_deg_dec", ")", "raz", "...
25.517241
0.001302
def _resolve_time(value): ''' Resolve the time in seconds of a configuration value. ''' if value is None or isinstance(value,(int,long)): return value if NUMBER_TIME.match(value): return long(value) simple = SIMPLE_TIME.match(value) if SIMPLE_TIME.match(value): multiplier = long( simple.grou...
[ "def", "_resolve_time", "(", "value", ")", ":", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "(", "int", ",", "long", ")", ")", ":", "return", "value", "if", "NUMBER_TIME", ".", "match", "(", "value", ")", ":", "return", "long"...
24.9
0.029014
def dip_and_closest_unimodal_from_cdf(xF, yF, plotting=False, verbose=False, eps=1e-12): ''' Dip computed as distance between empirical distribution function (EDF) and cumulative distribution function for the unimodal distribution with smallest such distance. The optimal unimodal distributio...
[ "def", "dip_and_closest_unimodal_from_cdf", "(", "xF", ",", "yF", ",", "plotting", "=", "False", ",", "verbose", "=", "False", ",", "eps", "=", "1e-12", ")", ":", "## TODO! Preprocess xF and yF so that yF increasing and xF does", "## not have more than two copies of each x-...
38.133929
0.002282
def mme_match(case_obj, match_type, mme_base_url, mme_token, nodes=None, mme_accepts=None): """Initiate a MatchMaker match against either other Scout patients or external nodes Args: case_obj(dict): a scout case object already submitted to MME match_type(str): 'internal' or 'external' m...
[ "def", "mme_match", "(", "case_obj", ",", "match_type", ",", "mme_base_url", ",", "mme_token", ",", "nodes", "=", "None", ",", "mme_accepts", "=", "None", ")", ":", "query_patients", "=", "[", "]", "server_responses", "=", "[", "]", "url", "=", "None", "...
46.490566
0.012719
def restart_service(service, log=False): """ restarts a service """ with settings(): if log: bookshelf2.logging_helpers.log_yellow( 'stoping service %s' % service) sudo('service %s stop' % service) if log: bookshelf2.logging_helpers.log_yellow( ...
[ "def", "restart_service", "(", "service", ",", "log", "=", "False", ")", ":", "with", "settings", "(", ")", ":", "if", "log", ":", "bookshelf2", ".", "logging_helpers", ".", "log_yellow", "(", "'stoping service %s'", "%", "service", ")", "sudo", "(", "'ser...
34.5
0.002353
def match_preferences(self, pcr=None, issuer=None): """ Match the clients preferences against what the provider can do. This is to prepare for later client registration and or what functionality the client actually will use. In the client configuration the client preferences are ...
[ "def", "match_preferences", "(", "self", ",", "pcr", "=", "None", ",", "issuer", "=", "None", ")", ":", "if", "not", "pcr", ":", "pcr", "=", "self", ".", "service_context", ".", "provider_info", "regreq", "=", "oidc", ".", "RegistrationRequest", "for", "...
39.209302
0.000579
def new_timestamped_uid(bits=32): """ A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of randomness. The advantage of this is it sorts nicely by time, while still being unique. Example: 20150912T084555Z-378465-43vtwbx """ return "%s-%s" % (re.sub('[^\w.]', '', datetim...
[ "def", "new_timestamped_uid", "(", "bits", "=", "32", ")", ":", "return", "\"%s-%s\"", "%", "(", "re", ".", "sub", "(", "'[^\\w.]'", ",", "''", ",", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", ")", ".", "replace", "(", "\".\"", ",...
52.714286
0.018667
def host_names(urls): ''' Takes a StringCounter of normalized URL and parses their hostnames N.B. this assumes that absolute URLs will begin with http:// in order to accurately resolve the host name. Relative URLs will not have host names. ''' host_names = StringCounter() for url ...
[ "def", "host_names", "(", "urls", ")", ":", "host_names", "=", "StringCounter", "(", ")", "for", "url", "in", "urls", ":", "host_names", "[", "urlparse", "(", "url", ")", ".", "netloc", "]", "+=", "urls", "[", "url", "]", "return", "host_names" ]
26
0.002475
def write_generator_data(self, file): """ Write generator data as CSV. """ writer = self._get_writer(file) writer.writerow(["bus"] + GENERATOR_ATTRS) for g in self.case.generators: i = g.bus._i writer.writerow([i] + [getattr(g,a) for a in GENERATOR_ATTRS]...
[ "def", "write_generator_data", "(", "self", ",", "file", ")", ":", "writer", "=", "self", ".", "_get_writer", "(", "file", ")", "writer", ".", "writerow", "(", "[", "\"bus\"", "]", "+", "GENERATOR_ATTRS", ")", "for", "g", "in", "self", ".", "case", "."...
34.777778
0.009346
def __x_google_quota_definitions_descriptor(self, limit_definitions): """Describes the quota limit definitions for an API. Args: limit_definitions: List of endpoints.LimitDefinition tuples Returns: A dict descriptor of the API's quota limit definitions. """ if not limit_definitions: ...
[ "def", "__x_google_quota_definitions_descriptor", "(", "self", ",", "limit_definitions", ")", ":", "if", "not", "limit_definitions", ":", "return", "None", "definitions_list", "=", "[", "{", "'name'", ":", "ld", ".", "metric_name", ",", "'metric'", ":", "ld", "....
26.666667
0.002413
def handler(*names, **kwargs): """Creates an Event Handler This decorator can be applied to methods of classes derived from :class:`circuits.core.components.BaseComponent`. It marks the method as a handler for the events passed as arguments to the ``@handler`` decorator. The events are specified by...
[ "def", "handler", "(", "*", "names", ",", "*", "*", "kwargs", ")", ":", "def", "wrapper", "(", "f", ")", ":", "if", "names", "and", "isinstance", "(", "names", "[", "0", "]", ",", "bool", ")", "and", "not", "names", "[", "0", "]", ":", "f", "...
41.719512
0.000286
def add_features(self, features, merge='outer', duplicates='ignore', min_studies=0, threshold=0.0001): """ Add new features to FeatureTable. Args: features (str, DataFrame): A filename to load data from, or a pandas DataFrame. In either case, studies are ...
[ "def", "add_features", "(", "self", ",", "features", ",", "merge", "=", "'outer'", ",", "duplicates", "=", "'ignore'", ",", "min_studies", "=", "0", ",", "threshold", "=", "0.0001", ")", ":", "if", "isinstance", "(", "features", ",", "string_types", ")", ...
54.530303
0.000819
def retry_using_http_NTLM_auth(self, auth_header_field, auth_header, response, auth_type, args): # Get the certificate of the server if using HTTPS for CBT server_certificate_hash = _get_server_cert(response) """Attempt to authenticate using HTTP NTLM challeng...
[ "def", "retry_using_http_NTLM_auth", "(", "self", ",", "auth_header_field", ",", "auth_header", ",", "response", ",", "auth_type", ",", "args", ")", ":", "# Get the certificate of the server if using HTTPS for CBT", "server_certificate_hash", "=", "_get_server_cert", "(", "...
40.170455
0.001657
def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) ...
[ "def", "plot_predict", "(", "self", ",", "h", "=", "5", ",", "past_values", "=", "20", ",", "intervals", "=", "True", ",", "oos_data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "seab...
45.255814
0.010309
def create(backbone: ModelFactory, input_block: typing.Optional[ModelFactory]=None, initial_std_dev=0.4, factorized_noise=True): """ Vel factory function """ if input_block is None: input_block = IdentityFactory() return NoisyQModelFactory( input_block=input_block, backbone=backb...
[ "def", "create", "(", "backbone", ":", "ModelFactory", ",", "input_block", ":", "typing", ".", "Optional", "[", "ModelFactory", "]", "=", "None", ",", "initial_std_dev", "=", "0.4", ",", "factorized_noise", "=", "True", ")", ":", "if", "input_block", "is", ...
43.222222
0.012594
def get_next_version(self, increment=None): """ Return the next version based on prior tagged releases. """ increment = increment or self.increment return self.infer_next_version(self.get_latest_version(), increment)
[ "def", "get_next_version", "(", "self", ",", "increment", "=", "None", ")", ":", "increment", "=", "increment", "or", "self", ".", "increment", "return", "self", ".", "infer_next_version", "(", "self", ".", "get_latest_version", "(", ")", ",", "increment", "...
36.833333
0.030973
def dispatch_request(self, body): """Given a parsed JSON request object, call the correct Intent, Launch, or SessionEnded function. This function is called after request parsing and validaion and will raise a `ValueError` if an unknown request type comes in. :param body: JSON o...
[ "def", "dispatch_request", "(", "self", ",", "body", ")", ":", "req_type", "=", "body", ".", "get", "(", "'request'", ",", "{", "}", ")", ".", "get", "(", "'type'", ")", "session_obj", "=", "body", ".", "get", "(", "'session'", ")", "session", "=", ...
32.55
0.001491
def _get_fiber_image(self, cpores): r""" Produce image by filling in voxels along throat edges using Bresenham line then performing distance transform on fiber voxels to erode the pore space """ fiber_rad = self.network.fiber_rad vox_len = self.network.resolution ...
[ "def", "_get_fiber_image", "(", "self", ",", "cpores", ")", ":", "fiber_rad", "=", "self", ".", "network", ".", "fiber_rad", "vox_len", "=", "self", ".", "network", ".", "resolution", "# Voxel length of fiber radius", "fiber_rad", "=", "np", ".", "around", "("...
43.287129
0.000671
def command_output( self, command, shell=False, capture_stderr=False, localized=False ): """ Run a command and return its output as unicode. The command can either be supplied as a sequence or string. :param command: command to run can be a str or list :param shell: ...
[ "def", "command_output", "(", "self", ",", "command", ",", "shell", "=", "False", ",", "capture_stderr", "=", "False", ",", "localized", "=", "False", ")", ":", "# make a pretty command for error loggings and...", "if", "isinstance", "(", "command", ",", "basestri...
41.269841
0.001878
def validate(cls, obj, raiseException=False, complainUnrecognized=False): """Check if the object satisfies this behavior's requirements. @param obj: The L{ContentLine<base.ContentLine>} or L{Component<base.Component>} to be validated. @param raiseException: I...
[ "def", "validate", "(", "cls", ",", "obj", ",", "raiseException", "=", "False", ",", "complainUnrecognized", "=", "False", ")", ":", "if", "not", "cls", ".", "allowGroup", "and", "obj", ".", "group", "is", "not", "None", ":", "err", "=", "\"{0} has a gro...
48.02439
0.002489
def obfuscate(p, action): """Obfuscate the auth details to avoid easy snatching. It's best to use a throw away account for these alerts to avoid having your authentication put at risk by storing it locally. """ key = "ru7sll3uQrGtDPcIW3okutpFLo6YYtd5bWSpbZJIopYQ0Du0a1WlhvJOaZEH" s = list() ...
[ "def", "obfuscate", "(", "p", ",", "action", ")", ":", "key", "=", "\"ru7sll3uQrGtDPcIW3okutpFLo6YYtd5bWSpbZJIopYQ0Du0a1WlhvJOaZEH\"", "s", "=", "list", "(", ")", "if", "action", "==", "'store'", ":", "if", "PY2", ":", "for", "i", "in", "range", "(", "len", ...
34.821429
0.000998
def use_comparative_hierarchy_view(self): """Pass through to provider HierarchyLookupSession.use_comparative_hierarchy_view""" self._hierarchy_view = COMPARATIVE # self._get_provider_session('hierarchy_lookup_session') # To make sure the session is tracked for session in self._get_provid...
[ "def", "use_comparative_hierarchy_view", "(", "self", ")", ":", "self", ".", "_hierarchy_view", "=", "COMPARATIVE", "# self._get_provider_session('hierarchy_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", "_get_provider_sessions", "("...
50.666667
0.008621
def _jsmin(self): """Copy the input to the output, deleting the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. """...
[ "def", "_jsmin", "(", "self", ")", ":", "self", ".", "theA", "=", "'\\n'", "self", ".", "_action", "(", "3", ")", "while", "self", ".", "theA", "!=", "'\\000'", ":", "if", "self", ".", "theA", "==", "' '", ":", "if", "isAlphanum", "(", "self", "....
37.243902
0.001914
def display_files(self, pcs_files): '''重新格式化一下文件列表, 去除不需要的信息 这一操作主要是为了便于接下来的查找工作. 文件的path都被提取出来, 然后放到了一个list中. ''' tree_iters = [] for pcs_file in pcs_files: path = pcs_file['path'] pixbuf, type_ = self.app.mime.get(path, pcs_file['isdir'], ...
[ "def", "display_files", "(", "self", ",", "pcs_files", ")", ":", "tree_iters", "=", "[", "]", "for", "pcs_file", "in", "pcs_files", ":", "path", "=", "pcs_file", "[", "'path'", "]", "pixbuf", ",", "type_", "=", "self", ".", "app", ".", "mime", ".", "...
42.133333
0.001547
def matlabstr2py(string): """Return Python object from Matlab string representation. Return str, bool, int, float, list (Matlab arrays or cells), or dict (Matlab structures) types. Use to access ScanImage metadata. >>> matlabstr2py('1') 1 >>> matlabstr2py("['x y z' true false; 1 2.0 -3e4;...
[ "def", "matlabstr2py", "(", "string", ")", ":", "# TODO: handle invalid input", "# TODO: review unboxing of multidimensional arrays", "def", "lex", "(", "s", ")", ":", "# return sequence of tokens from matlab string representation", "tokens", "=", "[", "'['", "]", "while", ...
28.935065
0.000217
def delete_ec2_role(self, role, mount_point='aws-ec2'): """DELETE /auth/<mount_point>/role/<role> :param role: :type role: :param mount_point: :type mount_point: :return: :rtype: """ return self._adapter.delete('/v1/auth/{0}/role/{1}'.format(mount...
[ "def", "delete_ec2_role", "(", "self", ",", "role", ",", "mount_point", "=", "'aws-ec2'", ")", ":", "return", "self", ".", "_adapter", ".", "delete", "(", "'/v1/auth/{0}/role/{1}'", ".", "format", "(", "mount_point", ",", "role", ")", ")" ]
29.454545
0.008982
def check_columns_fit(unoccupied_columns, row, offset, row_length): """ Checks if all the occupied columns in the row fit in the indices given by free columns. >>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4) True >>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4) Tr...
[ "def", "check_columns_fit", "(", "unoccupied_columns", ",", "row", ",", "offset", ",", "row_length", ")", ":", "for", "index", ",", "item", "in", "row", ":", "adjusted_index", "=", "(", "index", "+", "offset", ")", "%", "row_length", "# Check if the index is i...
29.32
0.001321
def Debugger_setBlackboxedRanges(self, scriptId, positions): """ Function path: Debugger.setBlackboxedRanges Domain: Debugger Method name: setBlackboxedRanges WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the ...
[ "def", "Debugger_setBlackboxedRanges", "(", "self", ",", "scriptId", ",", "positions", ")", ":", "assert", "isinstance", "(", "positions", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'positions' must be of type '['list', 'tuple']'. Received type: '%s'\"", ...
46.045455
0.031915
def hook_output (module:nn.Module, detach:bool=True, grad:bool=False)->Hook: "Return a `Hook` that stores activations of `module` in `self.stored`" return Hook(module, _hook_inner, detach=detach, is_forward=not grad)
[ "def", "hook_output", "(", "module", ":", "nn", ".", "Module", ",", "detach", ":", "bool", "=", "True", ",", "grad", ":", "bool", "=", "False", ")", "->", "Hook", ":", "return", "Hook", "(", "module", ",", "_hook_inner", ",", "detach", "=", "detach",...
74
0.044643
def _set_future_result(self): """Set the result or exception from the job if it is complete.""" # This must be done in a lock to prevent the polling thread # and main thread from both executing the completion logic # at the same time. with self._completion_lock: # If ...
[ "def", "_set_future_result", "(", "self", ")", ":", "# This must be done in a lock to prevent the polling thread", "# and main thread from both executing the completion logic", "# at the same time.", "with", "self", ".", "_completion_lock", ":", "# If the operation isn't complete or if t...
48.833333
0.002232
def create_qc(self, product_id=None, expected_result='', actual_result='', weight=100, status='success', **kwargs): ''' create_qc(self, product_id=None, expected_result='', actual_result='', weight=100, status='success', **kwargs) Create Quality Criteria :Parameters: * *product...
[ "def", "create_qc", "(", "self", ",", "product_id", "=", "None", ",", "expected_result", "=", "''", ",", "actual_result", "=", "''", ",", "weight", "=", "100", ",", "status", "=", "'success'", ",", "*", "*", "kwargs", ")", ":", "request_data", "=", "{"...
58.235294
0.00994
def choose_submit(self, submit): """Selects the input (or button) element to use for form submission. :param submit: The bs4.element.Tag (or just its *name*-attribute) that identifies the submit element to use. If ``None``, will choose the first valid submit element in the form,...
[ "def", "choose_submit", "(", "self", ",", "submit", ")", ":", "# Since choose_submit is destructive, it doesn't make sense to call", "# this method twice unless no submit is specified.", "if", "self", ".", "_submit_chosen", ":", "if", "submit", "is", "None", ":", "return", ...
39.0625
0.00078
def do_mailfy(self, query): """ Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return an equivalent array. Args: ----- query: The element to be searched....
[ "def", "do_mailfy", "(", "self", ",", "query", ")", ":", "from", "bs4", "import", "BeautifulSoup", "#LINKEDIN-------------------------------------------------", "r", "=", "br", ".", "open", "(", "'https://www.linkedin.com/'", ")", "br", ".", "select_form", "(", "nr"...
34.576471
0.009593
def insert(self): """Insert the object into the database""" if not self.curs: raise LIGOLwDBError, "Database connection not initalized" if len(self.table) == 0: raise LIGOLwDBError, 'attempt to insert empty table' for tab in self.table.keys(): # find and add any missing unique ids ...
[ "def", "insert", "(", "self", ")", ":", "if", "not", "self", ".", "curs", ":", "raise", "LIGOLwDBError", ",", "\"Database connection not initalized\"", "if", "len", "(", "self", ".", "table", ")", "==", "0", ":", "raise", "LIGOLwDBError", ",", "'attempt to i...
37.023256
0.02448
def wait_for_stateful_block_init(context, mri, timeout=DEFAULT_TIMEOUT): """Wait until a Block backed by a StatefulController has initialized Args: context (Context): The context to use to make the child block mri (str): The mri of the child block timeout (float): The maximum time to wa...
[ "def", "wait_for_stateful_block_init", "(", "context", ",", "mri", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "context", ".", "when_matches", "(", "[", "mri", ",", "\"state\"", ",", "\"value\"", "]", ",", "StatefulStates", ".", "READY", ",", "bad_values...
41.083333
0.001984
def wave_range(self, cenwave, npix, waveunits=None, round='round'): """Get the wavelength range covered by the given number of pixels centered on the given wavelength. .. note:: This calls :func:`wave_range` with ``self.binset`` as the first argument. Parameters ...
[ "def", "wave_range", "(", "self", ",", "cenwave", ",", "npix", ",", "waveunits", "=", "None", ",", "round", "=", "'round'", ")", ":", "# make sure we have a binset to work with", "if", "self", ".", "binset", "is", "None", ":", "raise", "exceptions", ".", "Un...
33.857143
0.001538
def pan_zoom_high_equalarea(self,event): """ Uses the toolbar for the canvas to change the function from zoom to pan or pan to zoom @param: event -> the wx.MouseEvent that triggered this funciton """ if event.LeftIsDown() or event.ButtonDClick(): return elif s...
[ "def", "pan_zoom_high_equalarea", "(", "self", ",", "event", ")", ":", "if", "event", ".", "LeftIsDown", "(", ")", "or", "event", ".", "ButtonDClick", "(", ")", ":", "return", "elif", "self", ".", "high_EA_setting", "==", "\"Zoom\"", ":", "self", ".", "h...
38.684211
0.01328
def get_user_title_url( self, user_fill, title=None, phone=None, tax_no=None, addr=None, bank_type=None, bank_no=None, out_title_id=None): """ 获取添加发票链接 获取链接,发送给用户。用户同意以后,发票抬头信息将会录入到用户微信中 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0 :p...
[ "def", "get_user_title_url", "(", "self", ",", "user_fill", ",", "title", "=", "None", ",", "phone", "=", "None", ",", "tax_no", "=", "None", ",", "addr", "=", "None", ",", "bank_type", "=", "None", ",", "bank_no", "=", "None", ",", "out_title_id", "="...
32.5
0.00249
def _unpack_union(type_: int, union: Any) -> Any: """ unpack items from parser new_property (value_converter) """ if type_ == lib.TCOD_TYPE_BOOL: return bool(union.b) elif type_ == lib.TCOD_TYPE_CHAR: return union.c.decode("latin-1") elif type_ == lib.TCOD_TYPE_INT: r...
[ "def", "_unpack_union", "(", "type_", ":", "int", ",", "union", ":", "Any", ")", "->", "Any", ":", "if", "type_", "==", "lib", ".", "TCOD_TYPE_BOOL", ":", "return", "bool", "(", "union", ".", "b", ")", "elif", "type_", "==", "lib", ".", "TCOD_TYPE_CH...
34.68
0.001122
def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)): """Connect two lines to generate the surface inbetween. .. hint:: |ribbon| |ribbon.py|_ """ if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() ppoints1 = vtk.v...
[ "def", "Ribbon", "(", "line1", ",", "line2", ",", "c", "=", "\"m\"", ",", "alpha", "=", "1", ",", "res", "=", "(", "200", ",", "5", ")", ")", ":", "if", "isinstance", "(", "line1", ",", "Actor", ")", ":", "line1", "=", "line1", ".", "coordinate...
30.634921
0.000502
def _create_environment(config, outdir): """Constructor for an instance of the environment. Args: config: Object providing configurations via attributes. outdir: Directory to store videos in. Raises: NotImplementedError: For action spaces other than Box and Discrete. Returns: Wrapped OpenAI G...
[ "def", "_create_environment", "(", "config", ",", "outdir", ")", ":", "if", "isinstance", "(", "config", ".", "env", ",", "str", ")", ":", "env", "=", "gym", ".", "make", "(", "config", ".", "env", ")", "else", ":", "env", "=", "config", ".", "env"...
34.444444
0.011765
def _getClassInstance(path, args=None): """ Returns a class instance from a .py file. Args: path (str): Absolute path to .py file args (dict): Arguments passed via class constructor Returns: object: Class instance or None """ if not path.endswith(".py"): return None if args is None: args...
[ "def", "_getClassInstance", "(", "path", ",", "args", "=", "None", ")", ":", "if", "not", "path", ".", "endswith", "(", "\".py\"", ")", ":", "return", "None", "if", "args", "is", "None", ":", "args", "=", "{", "}", "classname", "=", "AtomShieldsScanner...
24.666667
0.035111
def get_json_argument(self, name, default=None): """Find and return the argument with key 'name' from JSON request data. Similar to Tornado's get_argument() method. :param str name: The name of the json key you want to get the value for :param bool default: The default value if nothing ...
[ "def", "get_json_argument", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "default", "is", "None", ":", "default", "=", "self", ".", "_ARG_DEFAULT", "if", "not", "self", ".", "request", ".", "arguments", ":", "self", ".", "load...
43.5
0.001874
def system_error(self, msg_id=None, message=None, description=None, validation_timeout=False, exc_info=None, **kw): """Add an error message for an unexpected exception in validator code, and move it to the front of the error message list. If `exc_info` is supplied, the error...
[ "def", "system_error", "(", "self", ",", "msg_id", "=", "None", ",", "message", "=", "None", ",", "description", "=", "None", ",", "validation_timeout", "=", "False", ",", "exc_info", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "exc_info", ":", ...
43.666667
0.001867
def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match, _join=u('').join, _PY3=PY3, _maxunicode=sys.maxunicode): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid ...
[ "def", "py_scanstring", "(", "s", ",", "end", ",", "encoding", "=", "None", ",", "strict", "=", "True", ",", "_b", "=", "BACKSLASH", ",", "_m", "=", "STRINGCHUNK", ".", "match", ",", "_join", "=", "u", "(", "''", ")", ".", "join", ",", "_PY3", "=...
39.964706
0.001149
def get_peaks(blk, neighbors=2): """ Get all peak indices in blk (sorted by index value) but the ones at the vector limits (first and last ``neighbors - 1`` values). A peak is the max value in a neighborhood of ``neighbors`` values for each side. """ size = 1 + 2 * neighbors pairs = enumerate(Stream(blk)....
[ "def", "get_peaks", "(", "blk", ",", "neighbors", "=", "2", ")", ":", "size", "=", "1", "+", "2", "*", "neighbors", "pairs", "=", "enumerate", "(", "Stream", "(", "blk", ")", ".", "blocks", "(", "size", "=", "size", ",", "hop", "=", "1", ")", "...
39.571429
0.015873
def _data_build(self, data, modname, path): """Build tree node from data and add some informations""" try: node = _parse(data + "\n") except (TypeError, ValueError, SyntaxError) as exc: raise exceptions.AstroidSyntaxError( "Parsing Python code failed:\n{er...
[ "def", "_data_build", "(", "self", ",", "data", ",", "modname", ",", "path", ")", ":", "try", ":", "node", "=", "_parse", "(", "data", "+", "\"\\n\"", ")", "except", "(", "TypeError", ",", "ValueError", ",", "SyntaxError", ")", "as", "exc", ":", "rai...
37.827586
0.001778
def properties_for(self, index): """ Returns a list of properties, such that each entry in the list corresponds to the element of the index given. Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_for([2,3,5]) [['one'], ['one', 'two'], ['two...
[ "def", "properties_for", "(", "self", ",", "index", ")", ":", "return", "vectorize", "(", "lambda", "i", ":", "[", "prop", "for", "prop", "in", "self", ".", "properties", "(", ")", "if", "i", "in", "self", "[", "prop", "]", "]", ",", "otypes", "=",...
36.5
0.008909
def _prettify_dict(key): """Return a human readable format of a key (dict). Example: Description: My Wonderful Key Uid: a54d6de1-922a-4998-ad34-cb838646daaa Created_At: 2016-09-15T12:42:32 Metadata: owner=me; Modified_At: 2016-09-15T12:42:32 Value: secret_...
[ "def", "_prettify_dict", "(", "key", ")", ":", "assert", "isinstance", "(", "key", ",", "dict", ")", "pretty_key", "=", "''", "for", "key", ",", "value", "in", "key", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ...
31
0.001304
def run(run_or_experiment, name=None, stop=None, config=None, resources_per_trial=None, num_samples=1, local_dir=None, upload_dir=None, trial_name_creator=None, loggers=None, sync_function=None, checkpoint_freq=0, checkpoint...
[ "def", "run", "(", "run_or_experiment", ",", "name", "=", "None", ",", "stop", "=", "None", ",", "config", "=", "None", ",", "resources_per_trial", "=", "None", ",", "num_samples", "=", "1", ",", "local_dir", "=", "None", ",", "upload_dir", "=", "None", ...
41.552632
0.000124
def configure(self, options, conf): """Configure plugin. Plugin is enabled by default. """ self.conf = conf self.when = options.browser_closer_when
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "self", ".", "conf", "=", "conf", "self", ".", "when", "=", "options", ".", "browser_closer_when" ]
35
0.011173
def print_hex(self, value, justify_right=True): """Print a numeric value in hexadecimal. Value should be from 0 to FFFF. """ if value < 0 or value > 0xFFFF: # Ignore out of range values. return self.print_number_str('{0:X}'.format(value), justify_right)
[ "def", "print_hex", "(", "self", ",", "value", ",", "justify_right", "=", "True", ")", ":", "if", "value", "<", "0", "or", "value", ">", "0xFFFF", ":", "# Ignore out of range values.", "return", "self", ".", "print_number_str", "(", "'{0:X}'", ".", "format",...
43.428571
0.009677
def nodeDumpOutput(self, doc, cur, level, format, encoding): """Dump an XML node, recursive behaviour, children are printed too. Note that @format = 1 provide node indenting only if xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was called """ if doc is None: doc__o = ...
[ "def", "nodeDumpOutput", "(", "self", ",", "doc", ",", "cur", ",", "level", ",", "format", ",", "encoding", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "cur", "is", "None", ...
50
0.013752
def read_node_status(self, name, **kwargs): # noqa: E501 """read_node_status # noqa: E501 read status of the specified Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api....
[ "def", "read_node_status", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "read_node...
43.727273
0.002035
def wrapup(self): """ Finishes up after execution finishes, does not remove any graphical output. """ for actor in self.actors: if actor.skip: continue actor.wrapup() super(ActorHandler, self).wrapup()
[ "def", "wrapup", "(", "self", ")", ":", "for", "actor", "in", "self", ".", "actors", ":", "if", "actor", ".", "skip", ":", "continue", "actor", ".", "wrapup", "(", ")", "super", "(", "ActorHandler", ",", "self", ")", ".", "wrapup", "(", ")" ]
30.333333
0.010676
def handle(self, *args, **options): """Command handle.""" models.Observer.objects.all().delete() models.Subscriber.objects.all().delete() for cache_key in cache.keys(search='{}*'.format(THROTTLE_CACHE_PREFIX)): cache.delete(cache_key)
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "models", ".", "Observer", ".", "objects", ".", "all", "(", ")", ".", "delete", "(", ")", "models", ".", "Subscriber", ".", "objects", ".", "all", "(", ")", ".", ...
39
0.010753
def getUserAgent(): ''' Generate a randomized user agent by permuting a large set of possible values. The returned user agent should look like a valid, in-use brower, with a specified preferred language of english. Return value is a list of tuples, where each tuple is one of the user-agent headers. Currently can...
[ "def", "getUserAgent", "(", ")", ":", "coding", "=", "random", ".", "choice", "(", "ENCODINGS", ")", "random", ".", "shuffle", "(", "coding", ")", "coding", "=", "random", ".", "choice", "(", "(", "\", \"", ",", "\",\"", ")", ")", ".", "join", "(", ...
32.964286
0.030526
def getNextRecord(self): """ Get the next record to encode. Includes getting a record from the `dataSource` and applying filters. If the filters request more data from the `dataSource` continue to get data from the `dataSource` until all filters are satisfied. This method is separate from :meth:`...
[ "def", "getNextRecord", "(", "self", ")", ":", "allFiltersHaveEnoughData", "=", "False", "while", "not", "allFiltersHaveEnoughData", ":", "# Get the data from the dataSource", "data", "=", "self", ".", "dataSource", ".", "getNextRecordDict", "(", ")", "if", "not", "...
32.633333
0.014881
def register_applications(self, applications, models=None, backends=None): '''A higher level registration functions for group of models located on application modules. It uses the :func:`model_iterator` function to iterate through all :class:`Model` models available in ``applications`` and register them using t...
[ "def", "register_applications", "(", "self", ",", "applications", ",", "models", "=", "None", ",", "backends", "=", "None", ")", ":", "return", "list", "(", "self", ".", "_register_applications", "(", "applications", ",", "models", ",", "backends", ")", ")" ...
44.884615
0.001678
def parse(self, data, path=None): """ Args: data (str): Raw specification text. path (Optional[str]): Path to specification on filesystem. Only used to tag tokens with the file they originated from. """ assert not self.exhausted, 'Must call get_par...
[ "def", "parse", "(", "self", ",", "data", ",", "path", "=", "None", ")", ":", "assert", "not", "self", ".", "exhausted", ",", "'Must call get_parser() to reset state.'", "self", ".", "path", "=", "path", "parsed_data", "=", "self", ".", "yacc", ".", "parse...
48.333333
0.002255
def estimate_ride(api_client): """Use an UberRidesClient to fetch a ride estimate and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. """ try: estimate = api_client.estimate_ride( product_id=SURGE_PRO...
[ "def", "estimate_ride", "(", "api_client", ")", ":", "try", ":", "estimate", "=", "api_client", ".", "estimate_ride", "(", "product_id", "=", "SURGE_PRODUCT_ID", ",", "start_latitude", "=", "START_LAT", ",", "start_longitude", "=", "START_LNG", ",", "end_latitude"...
27.772727
0.001582
def activated(self, item): """Double-click event""" editor_item = self.editor_items.get( self.editor_ids.get(self.current_editor)) line = 0 if item == editor_item: line = 1 elif isinstance(item, TreeItem): line = item.line se...
[ "def", "activated", "(", "self", ",", "item", ")", ":", "editor_item", "=", "self", ".", "editor_items", ".", "get", "(", "self", ".", "editor_ids", ".", "get", "(", "self", ".", "current_editor", ")", ")", "line", "=", "0", "if", "item", "==", "edit...
36.538462
0.002051
def upsert(db, table, key_cols, update_dict): """Fabled upsert for SQLiteDB. Perform an upsert based on primary key. :param SQLiteDB db: database :param str table: table to upsert into :param str key_cols: name of key columns :param dict update_dict: key-value pairs to upsert """ with...
[ "def", "upsert", "(", "db", ",", "table", ",", "key_cols", ",", "update_dict", ")", ":", "with", "db", ":", "cur", "=", "db", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'UPDATE {} SET {} WHERE {}'", ".", "format", "(", "table", ",", "','", ...
31.413793
0.001065
def eout(s): """ Input: s - unicode string to print Output: Nothing """ if allow_print: if con_encoding=='': x=sys.stdin.encoding if x==None: b=s.encode() else: b=s.encode(x, 'ignore') else: b=s.encode(con_encoding,...
[ "def", "eout", "(", "s", ")", ":", "if", "allow_print", ":", "if", "con_encoding", "==", "''", ":", "x", "=", "sys", ".", "stdin", ".", "encoding", "if", "x", "==", "None", ":", "b", "=", "s", ".", "encode", "(", ")", "else", ":", "b", "=", "...
22.580645
0.043836
def validate_sceneInfo(self): """Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong. """ if self.sceneInfo.prefix not in self.__satellitesMap: raise WrongSceneNameError('USGS Downloader: Prefix of %s (%s) is invalid' ...
[ "def", "validate_sceneInfo", "(", "self", ")", ":", "if", "self", ".", "sceneInfo", ".", "prefix", "not", "in", "self", ".", "__satellitesMap", ":", "raise", "WrongSceneNameError", "(", "'USGS Downloader: Prefix of %s (%s) is invalid'", "%", "(", "self", ".", "sce...
56
0.01005
def non_fluents(self) -> Dict[str, PVariable]: '''Returns non-fluent pvariables.''' return { str(pvar): pvar for pvar in self.pvariables if pvar.is_non_fluent() }
[ "def", "non_fluents", "(", "self", ")", "->", "Dict", "[", "str", ",", "PVariable", "]", ":", "return", "{", "str", "(", "pvar", ")", ":", "pvar", "for", "pvar", "in", "self", ".", "pvariables", "if", "pvar", ".", "is_non_fluent", "(", ")", "}" ]
58.666667
0.02809
def epsilon_net(points, close_distance): '''Selects a subset of `points` to preserve graph structure while minimizing the number of points used, by removing points within `close_distance`. Returns the downsampled indices.''' num_points = points.shape[0] indices = set(range(num_points)) selected = [] while...
[ "def", "epsilon_net", "(", "points", ",", "close_distance", ")", ":", "num_points", "=", "points", ".", "shape", "[", "0", "]", "indices", "=", "set", "(", "range", "(", "num_points", ")", ")", "selected", "=", "[", "]", "while", "indices", ":", "idx",...
38.538462
0.013645
def _check_module_is_text_embedding(module_spec): """Raises ValueError if `module_spec` is not a text-embedding module. Args: module_spec: A `ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with Tensor(string, shape=(?,)) -> Tensor(float32, shape=(?,K))....
[ "def", "_check_module_is_text_embedding", "(", "module_spec", ")", ":", "issues", "=", "[", "]", "# Find issues with signature inputs.", "input_info_dict", "=", "module_spec", ".", "get_input_info_dict", "(", ")", "if", "len", "(", "input_info_dict", ")", "!=", "1", ...
36.714286
0.008844
def backup(app): """Dump the database.""" dump_path = dump_database(app) config = PsiturkConfig() config.load_config() conn = boto.connect_s3( config.get('AWS Access', 'aws_access_key_id'), config.get('AWS Access', 'aws_secret_access_key'), ) bucket = conn.create_bucket( ...
[ "def", "backup", "(", "app", ")", ":", "dump_path", "=", "dump_database", "(", "app", ")", "config", "=", "PsiturkConfig", "(", ")", "config", ".", "load_config", "(", ")", "conn", "=", "boto", ".", "connect_s3", "(", "config", ".", "get", "(", "'AWS A...
24.416667
0.001642
def rand_imancon(X, rho): """Iman-Conover Method to generate random ordinal variables (Implementation adopted from Ekstrom, 2005) x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Correlation Matrix Links ...
[ "def", "rand_imancon", "(", "X", ",", "rho", ")", ":", "import", "numpy", "as", "np", "import", "scipy", ".", "stats", "as", "sstat", "import", "scipy", ".", "special", "as", "sspec", "# data prep", "n", ",", "d", "=", "X", ".", "shape", "# Ordering", ...
29.448276
0.000567
def channels_open(self, room_id, **kwargs): """Adds the channel back to the user’s list of channels.""" return self.__call_api_post('channels.open', roomId=room_id, kwargs=kwargs)
[ "def", "channels_open", "(", "self", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'channels.open'", ",", "roomId", "=", "room_id", ",", "kwargs", "=", "kwargs", ")" ]
64.333333
0.015385
def pop(self): """Pop the top revision off the stack back onto the collection at the given id. This method applies the action. Note: This assumes you don't have two revisions scheduled closer than a single scheduling cycle. """ revisions = yield self.list() if len(revisions) >...
[ "def", "pop", "(", "self", ")", ":", "revisions", "=", "yield", "self", ".", "list", "(", ")", "if", "len", "(", "revisions", ")", ">", "0", ":", "revision", "=", "revisions", "[", "0", "]", "# Update type action", "if", "revision", ".", "get", "(", ...
37.551724
0.008949
def prepare_site_model(exposure_xml, sites_csv, vs30_csv, z1pt0, z2pt5, vs30measured, grid_spacing=0, assoc_distance=5, output='site_model.csv'): """ Prepare a site_model.csv file from exposure xml files/site csv files, vs30 csv files and a grid spacing which ca...
[ "def", "prepare_site_model", "(", "exposure_xml", ",", "sites_csv", ",", "vs30_csv", ",", "z1pt0", ",", "z2pt5", ",", "vs30measured", ",", "grid_spacing", "=", "0", ",", "assoc_distance", "=", "5", ",", "output", "=", "'site_model.csv'", ")", ":", "hdf5", "=...
47.373494
0.000249
def isCollapsed( self ): """ Returns whether or not this group box is collapsed. :return <bool> """ if not self.isCollapsible(): return False if self._inverted: return self.isChecked() return not self.isChec...
[ "def", "isCollapsed", "(", "self", ")", ":", "if", "not", "self", ".", "isCollapsible", "(", ")", ":", "return", "False", "if", "self", ".", "_inverted", ":", "return", "self", ".", "isChecked", "(", ")", "return", "not", "self", ".", "isChecked", "(",...
26.166667
0.018462
def PCA_components(x): """ Principal Component Analysis helper to check out eigenvalues of components. **Args:** * `x` : input matrix (2d array), every row represents new sample **Returns:** * `components`: sorted array of principal components eigenvalues """ # validat...
[ "def", "PCA_components", "(", "x", ")", ":", "# validate inputs", "try", ":", "x", "=", "np", ".", "array", "(", "x", ")", "except", ":", "raise", "ValueError", "(", "'Impossible to convert x to a numpy array.'", ")", "# eigen values and eigen vectors of data covarian...
31.541667
0.008974
def go_up(self): """ Go up one, wrap to end if necessary """ if self.current_option > 0: self.current_option += -1 else: self.current_option = len(self.items) - 1 self.draw()
[ "def", "go_up", "(", "self", ")", ":", "if", "self", ".", "current_option", ">", "0", ":", "self", ".", "current_option", "+=", "-", "1", "else", ":", "self", ".", "current_option", "=", "len", "(", "self", ".", "items", ")", "-", "1", "self", ".",...
26.444444
0.00813
def or_(self, first_qe, *qes): ''' Works the same as the query expression method ``or_`` ''' self.__query_obj.or_(first_qe, *qes) return self
[ "def", "or_", "(", "self", ",", "first_qe", ",", "*", "qes", ")", ":", "self", ".", "__query_obj", ".", "or_", "(", "first_qe", ",", "*", "qes", ")", "return", "self" ]
33.8
0.011561
def clear(self): """Return the mean estimate and reset the streaming statistics.""" value = self._sum / tf.cast(self._count, self._dtype) with tf.control_dependencies([value]): reset_value = self._sum.assign(tf.zeros_like(self._sum)) reset_count = self._count.assign(0) with tf.control_depend...
[ "def", "clear", "(", "self", ")", ":", "value", "=", "self", ".", "_sum", "/", "tf", ".", "cast", "(", "self", ".", "_count", ",", "self", ".", "_dtype", ")", "with", "tf", ".", "control_dependencies", "(", "[", "value", "]", ")", ":", "reset_value...
47.5
0.010336
def constant_compare(a, b): """ Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal """ if not isinstance(a, byte_cls): ra...
[ "def", "constant_compare", "(", "a", ",", "b", ")", ":", "if", "not", "isinstance", "(", "a", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n a must be a byte string, not %s\n '''", ",", "type_name", "(", "...
20.926829
0.001114
def taper_rate(p0, p1): '''Compute the taper rate between points p0 and p1 Args: p0, p1: iterables with first 4 components containing (x, y, z, r) Returns: The taper rate, defined as the absolute value of the difference in the diameters of p0 and p1 divided by the euclidian distanc...
[ "def", "taper_rate", "(", "p0", ",", "p1", ")", ":", "return", "2", "*", "abs", "(", "p0", "[", "COLS", ".", "R", "]", "-", "p1", "[", "COLS", ".", "R", "]", ")", "/", "point_dist", "(", "p0", ",", "p1", ")" ]
33.75
0.002404
def get_windzone(conn, geometry): 'Find windzone from map.' # TODO@Günni if geometry.geom_type in ['Polygon', 'MultiPolygon']: coords = geometry.centroid else: coords = geometry sql = """ SELECT zone FROM oemof_test.windzones WHERE st_contains(geom, ST_PointFromText('...
[ "def", "get_windzone", "(", "conn", ",", "geometry", ")", ":", "# TODO@Günni", "if", "geometry", ".", "geom_type", "in", "[", "'Polygon'", ",", "'MultiPolygon'", "]", ":", "coords", "=", "geometry", ".", "centroid", "else", ":", "coords", "=", "geometry", ...
28.529412
0.001996
async def _load_authentication(self): """Read authentication from kube-config user section if exists. This function goes through various authentication methods in user section of kube-config and stops if it finds a valid authentication method. The order of authentication methods is: ...
[ "async", "def", "_load_authentication", "(", "self", ")", ":", "if", "not", "self", ".", "_user", ":", "logging", ".", "debug", "(", "'No user section in current context.'", ")", "return", "if", "self", ".", "provider", "==", "'gcp'", ":", "await", "self", "...
31.684211
0.001612
def get_action_groups(self): """Get all Action Groups. :return: List of Action Groups """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get(BASE_URL + "getActionGroups", headers=header, ...
[ "def", "get_action_groups", "(", "self", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "request", "=", "requests", ".", "get", "(", "BASE_URL", "+", "\"getActionGroups\"", ",",...
25.941176
0.002186
def parse_grid_facets(facets): """ Return two lists of facetting variables, for the rows & columns """ valid_seqs = ["('var1', '.')", "('var1', 'var2')", "('.', 'var1')", "((var1, var2), (var3, var4))"] error_msg_s = ("Valid sequences for specifying 'facets' look like" ...
[ "def", "parse_grid_facets", "(", "facets", ")", ":", "valid_seqs", "=", "[", "\"('var1', '.')\"", ",", "\"('var1', 'var2')\"", ",", "\"('.', 'var1')\"", ",", "\"((var1, var2), (var3, var4))\"", "]", "error_msg_s", "=", "(", "\"Valid sequences for specifying 'facets' look like...
28.387097
0.000549
def get_email_context(self,**kwargs): ''' Overrides EmailRecipientMixin ''' context = super(Customer,self).get_email_context(**kwargs) context.update({ 'first_name': self.first_name, 'last_name': self.last_name, 'email': self.email, 'fullName': sel...
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "Customer", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'first_name'", ":", "se...
35.272727
0.01005
def accuracy_score(df, col_true=None, col_pred=None, normalize=True): """ Compute accuracy of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true label :type col_true...
[ "def", "accuracy_score", "(", "df", ",", "col_true", "=", "None", ",", "col_pred", "=", "None", ",", "normalize", "=", "True", ")", ":", "if", "not", "col_pred", ":", "col_pred", "=", "get_field_name_by_role", "(", "df", ",", "FieldRole", ".", "PREDICTED_C...
32.947368
0.001552
def train_fn(data_dir=None, output_dir=None, model_class=gin.REQUIRED, dataset=gin.REQUIRED, input_names=None, target_names=None, train_steps=1000, eval_steps=1, eval_frequency=100): """Train the given model on the given dataset. Args: data_dir: Directory where the data i...
[ "def", "train_fn", "(", "data_dir", "=", "None", ",", "output_dir", "=", "None", ",", "model_class", "=", "gin", ".", "REQUIRED", ",", "dataset", "=", "gin", ".", "REQUIRED", ",", "input_names", "=", "None", ",", "target_names", "=", "None", ",", "train_...
45.742424
0.008755
def insert_mode(page_html, mode): ''' Insert mode ''' page_html = page_html.decode("utf-8") match_found = False matches = re.finditer('workerId={{ workerid }}', page_html) match = None for match in matches: match_found = True if match_found: new_html = page_html[:match.end()]...
[ "def", "insert_mode", "(", "page_html", ",", "mode", ")", ":", "page_html", "=", "page_html", ".", "decode", "(", "\"utf-8\"", ")", "match_found", "=", "False", "matches", "=", "re", ".", "finditer", "(", "'workerId={{ workerid }}'", ",", "page_html", ")", "...
32.142857
0.00216
def copy_file( source_path, target_path, allow_undo=True, no_confirm=False, rename_on_collision=True, silent=False, extra_flags=0, hWnd=None ): """Perform a shell-based file copy. Copying in this way allows the possibility of undo, auto-renaming, and showing the "flying file"...
[ "def", "copy_file", "(", "source_path", ",", "target_path", ",", "allow_undo", "=", "True", ",", "no_confirm", "=", "False", ",", "rename_on_collision", "=", "True", ",", "silent", "=", "False", ",", "extra_flags", "=", "0", ",", "hWnd", "=", "None", ")", ...
24.241379
0.001368
def convert_wide_to_long(wide_data, ind_vars, alt_specific_vars, availability_vars, obs_id_col, choice_col, new_alt_id_name=None): """ Will convert a cross-sectio...
[ "def", "convert_wide_to_long", "(", "wide_data", ",", "ind_vars", ",", "alt_specific_vars", ",", "availability_vars", ",", "obs_id_col", ",", "choice_col", ",", "new_alt_id_name", "=", "None", ")", ":", "##########", "# Check that all columns of wide_data are being", "# u...
43.566787
0.000081