text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def populate(self, struct): """Generates the list tree. struct: if a list/set/tuple is given, a flat list is generated <*l><li>v1</li><li>v2</li>...</*l> If the list type is 'Dl' a flat list without definitions is generated <*l><dt>v1</dt><dt>v2</dt>...</*l> If the given...
[ "def", "populate", "(", "self", ",", "struct", ")", ":", "if", "struct", "is", "None", ":", "# Maybe raise? Empty the list?", "return", "self", "if", "isinstance", "(", "struct", ",", "(", "list", ",", "set", ",", "tuple", ")", ")", ":", "struct", "=", ...
34.96
21.16
def authenticate(self, provider): """ Starts OAuth authorization flow, will redirect to 3rd party site. """ callback_url = url_for(".callback", provider=provider, _external=True) provider = self.get_provider(provider) session['next'] = request.args.get('next') or '' ...
[ "def", "authenticate", "(", "self", ",", "provider", ")", ":", "callback_url", "=", "url_for", "(", "\".callback\"", ",", "provider", "=", "provider", ",", "_external", "=", "True", ")", "provider", "=", "self", ".", "get_provider", "(", "provider", ")", "...
44.375
13.375
def is_contained_in(pe_pe, root): ''' Determine if a PE_PE is contained within a EP_PKG or a C_C. ''' if not pe_pe: return False if type(pe_pe).__name__ != 'PE_PE': pe_pe = one(pe_pe).PE_PE[8001]() ep_pkg = one(pe_pe).EP_PKG[8000]() c_c = one(pe_pe).C_C[8003]() ...
[ "def", "is_contained_in", "(", "pe_pe", ",", "root", ")", ":", "if", "not", "pe_pe", ":", "return", "False", "if", "type", "(", "pe_pe", ")", ".", "__name__", "!=", "'PE_PE'", ":", "pe_pe", "=", "one", "(", "pe_pe", ")", ".", "PE_PE", "[", "8001", ...
21.25
20.666667
def build_columns(self, X, verbose=False): """construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse arr...
[ "def", "build_columns", "(", "self", ",", "X", ",", "verbose", "=", "False", ")", ":", "return", "sp", ".", "sparse", ".", "csc_matrix", "(", "X", "[", ":", ",", "self", ".", "feature", "]", "[", ":", ",", "np", ".", "newaxis", "]", ")" ]
25.125
18.1875
def newtons_method_scalar(f: fl.Fluxion, x: float, tol: float =1e-8) -> float: """Solve the equation f(x) = 0 for a function from R->R using Newton's method""" max_iters: int = 100 for i in range(max_iters): # Evaluate f(x) and f'(x) y, dy_dx = f(x) # Is y within the tolerance? ...
[ "def", "newtons_method_scalar", "(", "f", ":", "fl", ".", "Fluxion", ",", "x", ":", "float", ",", "tol", ":", "float", "=", "1e-8", ")", "->", "float", ":", "max_iters", ":", "int", "=", "100", "for", "i", "in", "range", "(", "max_iters", ")", ":",...
34.133333
15.466667
def canForward(self, request: Request): """ Determine whether to forward client REQUESTs to replicas, based on the following logic: - If exactly f+1 PROPAGATE requests are received, then forward. - If less than f+1 of requests then probably there's no consensus on the ...
[ "def", "canForward", "(", "self", ",", "request", ":", "Request", ")", ":", "if", "self", ".", "requests", ".", "forwarded", "(", "request", ")", ":", "return", "'already forwarded'", "# If not enough Propagates, don't bother comparing", "if", "not", "self", ".", ...
37.741935
22.83871
def add(self, quantity): """ Adds an angle to the value """ newvalue = self._value + quantity self.set(newvalue.deg)
[ "def", "add", "(", "self", ",", "quantity", ")", ":", "newvalue", "=", "self", ".", "_value", "+", "quantity", "self", ".", "set", "(", "newvalue", ".", "deg", ")" ]
25.166667
5.5
def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. :rtype: Datetime :raises: DeserializationError if string format invalid. """ if isinstance(attr, ET.Element): attr =...
[ "def", "deserialize_iso", "(", "attr", ")", ":", "if", "isinstance", "(", "attr", ",", "ET", ".", "Element", ")", ":", "attr", "=", "attr", ".", "text", "try", ":", "attr", "=", "attr", ".", "upper", "(", ")", "match", "=", "Deserializer", ".", "va...
38.885714
15.485714
def create_jwt_token(secret, client_id): """ Create JWT token for GOV.UK Notify Tokens have standard header: { "typ": "JWT", "alg": "HS256" } Claims consist of: iss: identifier for the client iat: issued at in epoch seconds (UTC) :param secret: Application signing ...
[ "def", "create_jwt_token", "(", "secret", ",", "client_id", ")", ":", "assert", "secret", ",", "\"Missing secret key\"", "assert", "client_id", ",", "\"Missing client id\"", "headers", "=", "{", "\"typ\"", ":", "__type__", ",", "\"alg\"", ":", "__algorithm__", "}"...
22.0625
18.9375
def order(self, pair, side, price, quantity, private_key, use_native_token=True, order_type="limit"): """ This function is a wrapper function around the create and execute order functions to help make this processes simpler for the end user by combining these requests in 1 step. Executio...
[ "def", "order", "(", "self", ",", "pair", ",", "side", ",", "price", ",", "quantity", ",", "private_key", ",", "use_native_token", "=", "True", ",", "order_type", "=", "\"limit\"", ")", ":", "create_order", "=", "self", ".", "create_order", "(", "private_k...
53.15493
25.352113
def abfGroups(abfFolder): """ Given a folder path or list of files, return groups (dict) by cell. Rules which define parents (cells): * assume each cell has one or several ABFs * that cell can be labeled by its "ID" or "parent" ABF (first abf) * the ID is just the filename of the fi...
[ "def", "abfGroups", "(", "abfFolder", ")", ":", "# prepare the list of files, filenames, and IDs", "files", "=", "False", "if", "type", "(", "abfFolder", ")", "is", "str", "and", "os", ".", "path", ".", "isdir", "(", "abfFolder", ")", ":", "files", "=", "abf...
36.678571
18.428571
def save_trailer(self, tocpos): """Save the trailer to disk. CArchives can be opened from the end - the trailer points back to the start. """ totallen = tocpos + self.toclen + self.TRLLEN pyvers = sys.version_info[0]*10 + sys.version_info[1] trl = struct.pack(self....
[ "def", "save_trailer", "(", "self", ",", "tocpos", ")", ":", "totallen", "=", "tocpos", "+", "self", ".", "toclen", "+", "self", ".", "TRLLEN", "pyvers", "=", "sys", ".", "version_info", "[", "0", "]", "*", "10", "+", "sys", ".", "version_info", "[",...
42.6
16.1
def doeigs_s(tau, Vdirs): """ get elements of s from eigenvaulues - note that this is very unstable Input: tau,V: tau is an list of eigenvalues in decreasing order: [t1,t2,t3] V is an list of the eigenvector directions [[V1_dec,V1_inc],[V2_dec,V2_...
[ "def", "doeigs_s", "(", "tau", ",", "Vdirs", ")", ":", "t", "=", "np", ".", "zeros", "(", "(", "3", ",", "3", ",", ")", ",", "'f'", ")", "# initialize the tau diagonal matrix", "V", "=", "[", "]", "for", "j", "in", "range", "(", "3", ")", ":", ...
31.5
17.666667
def find_first_available_template(self, template_name_list): """ Given a list of template names, find the first one that actually exists and is available. """ if isinstance(template_name_list, six.string_types): return template_name_list else: # Ta...
[ "def", "find_first_available_template", "(", "self", ",", "template_name_list", ")", ":", "if", "isinstance", "(", "template_name_list", ",", "six", ".", "string_types", ")", ":", "return", "template_name_list", "else", ":", "# Take advantage of fluent_pages' internal imp...
42.5
17.3
def is_set(self, key): """Check to see if the key has been set in any of the data locations. """ path = key.split(self._key_delimiter) lower_case_key = key.lower() val = self._find(lower_case_key) if val is None: source = self._find(path[0].lower()) ...
[ "def", "is_set", "(", "self", ",", "key", ")", ":", "path", "=", "key", ".", "split", "(", "self", ".", "_key_delimiter", ")", "lower_case_key", "=", "key", ".", "lower", "(", ")", "val", "=", "self", ".", "_find", "(", "lower_case_key", ")", "if", ...
32.357143
15.928571
def image_create(comptparms, clrspc): """Creates a new image structure. Wraps the openjp2 library function opj_image_create. Parameters ---------- cmptparms : comptparms_t The component parameters. clrspc : int Specifies the color space. Returns ------- image : Ima...
[ "def", "image_create", "(", "comptparms", ",", "clrspc", ")", ":", "OPENJP2", ".", "opj_image_create", ".", "argtypes", "=", "[", "ctypes", ".", "c_uint32", ",", "ctypes", ".", "POINTER", "(", "ImageComptParmType", ")", ",", "COLOR_SPACE_TYPE", "]", "OPENJP2",...
29.807692
19.269231
def find(self, obj): """Returns the index of the given object in the queue, it might be string which will be searched inside each task. :arg obj: object we are looking :return: -1 if the object is not found or else the location of the task """ if not self.connected: ...
[ "def", "find", "(", "self", ",", "obj", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "ConnectionError", "(", "'Queue is not connected'", ")", "data", "=", "self", ".", "rdb", ".", "lrange", "(", "self", ".", "_name", ",", "0", ",", ...
33.6875
16.6875
def multiplicative_self_attention(units, n_hidden=None, n_output_features=None, activation=None): """ Computes multiplicative self attention for time series of vectors (with batch dimension) the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices with dimensionality [...
[ "def", "multiplicative_self_attention", "(", "units", ",", "n_hidden", "=", "None", ",", "n_output_features", "=", "None", ",", "activation", "=", "None", ")", ":", "n_input_features", "=", "units", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", ...
55.296296
30.074074
def module_remove(name): ''' Removes SELinux module name The name of the module to remove .. versionadded:: 2016.11.6 ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} modules = __salt__['selinux.list_semod']() if name not i...
[ "def", "module_remove", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "modules", "=", "__salt__", "[", "'selinux.list_semod'", "]", "(", ...
27.625
19.791667
def push(self, cart, env=None, callback=None): """ `cart` - Release cart to push items from `callback` - Optional callback to call if juicer.utils.upload_rpm succeeds Pushes the items in a release cart to the pre-release environment. """ juicer.utils.Log.log_debug("Initi...
[ "def", "push", "(", "self", ",", "cart", ",", "env", "=", "None", ",", "callback", "=", "None", ")", ":", "juicer", ".", "utils", ".", "Log", ".", "log_debug", "(", "\"Initializing push of cart '%s'\"", "%", "cart", ".", "cart_name", ")", "if", "not", ...
34.75
19.875
def make_long_description(): """ Generate the reST long_description for setup() from source files. Returns the generated long_description as a unicode string. """ readme_path = README_PATH # Remove our HTML comments because PyPI does not allow it. # See the setup.py docstring for more inf...
[ "def", "make_long_description", "(", ")", ":", "readme_path", "=", "README_PATH", "# Remove our HTML comments because PyPI does not allow it.", "# See the setup.py docstring for more info on this.", "readme_md", "=", "strip_html_comments", "(", "read", "(", "readme_path", ")", ")...
33.3125
22.03125
def rellink (source, dest): """Create a symbolic link to path *source* from path *dest*. If either *source* or *dest* is an absolute path, the link from *dest* will point to the absolute path of *source*. Otherwise, the link to *source* from *dest* will be a relative link. """ from os.path impo...
[ "def", "rellink", "(", "source", ",", "dest", ")", ":", "from", "os", ".", "path", "import", "isabs", ",", "dirname", ",", "relpath", ",", "abspath", "if", "isabs", "(", "source", ")", ":", "os", ".", "symlink", "(", "source", ",", "dest", ")", "el...
35.733333
19.533333
def sadd(self, key, *members): """Add the specified members to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. An error is returned when the value stored at key i...
[ "def", "sadd", "(", "self", ",", "key", ",", "*", "members", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'SADD'", ",", "key", "]", "+", "list", "(", "members", ")", ",", "len", "(", "members", ")", ")" ]
39.88
24.32
def startResponse(self, status, headers, excInfo=None): """ extends startResponse to call speakerBox in a thread """ self.status = status self.headers = headers self.reactor.callInThread( responseInColor, self.request, status, headers ) return ...
[ "def", "startResponse", "(", "self", ",", "status", ",", "headers", ",", "excInfo", "=", "None", ")", ":", "self", ".", "status", "=", "status", "self", ".", "headers", "=", "headers", "self", ".", "reactor", ".", "callInThread", "(", "responseInColor", ...
32.1
12.7
def build_source_reading(expnum, ccd=None, ftype='p'): """ Build an astrom.Observation object for a SourceReading :param expnum: (str) Name or CFHT Exposure number of the observation. :param ccd: (str) CCD is this observation associated with. (can be None) :param ftype: (str) ex...
[ "def", "build_source_reading", "(", "expnum", ",", "ccd", "=", "None", ",", "ftype", "=", "'p'", ")", ":", "logger", ".", "debug", "(", "\"Building source reading for expnum:{} ccd:{} ftype:{}\"", ".", "format", "(", "expnum", ",", "ccd", ",", "ftype", ")", ")...
41.823529
24.764706
def mouse_click(self, widget, event=None): """Triggered when mouse click is pressed in the history tree. The method shows all scoped data for an execution step as tooltip or fold and unfold the tree by double-click and select respective state for double clicked element. """ if ev...
[ "def", "mouse_click", "(", "self", ",", "widget", ",", "event", "=", "None", ")", ":", "if", "event", ".", "type", "==", "Gdk", ".", "EventType", ".", "_2BUTTON_PRESS", "and", "event", ".", "get_button", "(", ")", "[", "1", "]", "==", "1", ":", "("...
56.132653
30.459184
def is_dark_terminal_background(cls): """ :return: Whether we have a dark Terminal background color, or None if unknown. We currently just check the env var COLORFGBG, which some terminals define like "<foreground-color>:<background-color>", and if <background-color> ...
[ "def", "is_dark_terminal_background", "(", "cls", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"COLORFGBG\"", ",", "None", ")", ":", "parts", "=", "os", ".", "environ", "[", "\"COLORFGBG\"", "]", ".", "split", "(", "\";\"", ")", "try", ":",...
51.26087
24.130435
def join(self, channel): """Add this user to the channel's user list and add the channel to this user's list of joined channels. """ if channel not in self.channels: channel.users.add(self.nick) self.channels.append(channel)
[ "def", "join", "(", "self", ",", "channel", ")", ":", "if", "channel", "not", "in", "self", ".", "channels", ":", "channel", ".", "users", ".", "add", "(", "self", ".", "nick", ")", "self", ".", "channels", ".", "append", "(", "channel", ")" ]
35.25
6.25
def plot_data(self, proj, ax): """ Creates and plots the contourplot of the original data. This is done by evaluating the density of projected datapoints on a grid. """ x, y = proj x_data = self.ig.independent_data[x] y_data = self.ig.dependent_data[y] pro...
[ "def", "plot_data", "(", "self", ",", "proj", ",", "ax", ")", ":", "x", ",", "y", "=", "proj", "x_data", "=", "self", ".", "ig", ".", "independent_data", "[", "x", "]", "y_data", "=", "self", ".", "ig", ".", "dependent_data", "[", "y", "]", "proj...
37.76
17.76
def transform_audio(self, y): '''Compute the tempogram Parameters ---------- y : np.ndarray Audio buffer Returns ------- data : dict data['tempogram'] : np.ndarray, shape=(n_frames, win_length) The tempogram ''' ...
[ "def", "transform_audio", "(", "self", ",", "y", ")", ":", "n_frames", "=", "self", ".", "n_frames", "(", "get_duration", "(", "y", "=", "y", ",", "sr", "=", "self", ".", "sr", ")", ")", "tgram", "=", "tempogram", "(", "y", "=", "y", ",", "sr", ...
28.363636
21.818182
def get_definition(self, name: YangIdentifier, kw: YangIdentifier) -> Optional["Statement"]: """Search ancestor statements for a definition. Args: name: Name of a grouping or datatype (with no prefix). kw: ``grouping`` or ``typedef``. Raises: ...
[ "def", "get_definition", "(", "self", ",", "name", ":", "YangIdentifier", ",", "kw", ":", "YangIdentifier", ")", "->", "Optional", "[", "\"Statement\"", "]", ":", "stmt", "=", "self", ".", "superstmt", "while", "stmt", ":", "res", "=", "stmt", ".", "find...
31.333333
17.555556
def at(self, row, col): """Return the value at the given cell position. Args: row (int): zero-based row number col (int): zero-based column number Returns: cell value Raises: TypeError: if ``row`` or ``col`` is not an ``int`` Ind...
[ "def", "at", "(", "self", ",", "row", ",", "col", ")", ":", "if", "not", "(", "isinstance", "(", "row", ",", "int", ")", "and", "isinstance", "(", "col", ",", "int", ")", ")", ":", "raise", "TypeError", "(", "row", ",", "col", ")", "return", "s...
33.2
15.066667
def base_url(self): """Base URL for resolving resource URLs""" if self.doc.package_url: return self.doc.package_url return self.doc._ref
[ "def", "base_url", "(", "self", ")", ":", "if", "self", ".", "doc", ".", "package_url", ":", "return", "self", ".", "doc", ".", "package_url", "return", "self", ".", "doc", ".", "_ref" ]
24
17.428571
def pop_result(self, key): """Returns the result for ``key`` and unregisters it.""" self.pending_callbacks.remove(key) return self.results.pop(key)
[ "def", "pop_result", "(", "self", ",", "key", ")", ":", "self", ".", "pending_callbacks", ".", "remove", "(", "key", ")", "return", "self", ".", "results", ".", "pop", "(", "key", ")" ]
42
5
def save(self, *args, **kwargs): """ call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save """ after_save = kwargs.pop('after_save', True) super(LayerExternal, self).save(*args, **kwargs) # call after_e...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "after_save", "=", "kwargs", ".", "pop", "(", "'after_save'", ",", "True", ")", "super", "(", "LayerExternal", ",", "self", ")", ".", "save", "(", "*", "args", ",", ...
37.444444
15
def stSpectralRollOff(X, c, fs): """Computes spectral roll-off""" totalEnergy = numpy.sum(X ** 2) fftLength = len(X) Thres = c*totalEnergy # Ffind the spectral rolloff as the frequency position # where the respective spectral energy is equal to c*totalEnergy CumSum = numpy.cumsum(X ** 2) + ...
[ "def", "stSpectralRollOff", "(", "X", ",", "c", ",", "fs", ")", ":", "totalEnergy", "=", "numpy", ".", "sum", "(", "X", "**", "2", ")", "fftLength", "=", "len", "(", "X", ")", "Thres", "=", "c", "*", "totalEnergy", "# Ffind the spectral rolloff as the fr...
33.428571
15
def on_conflict(self, fields: List[Union[str, Tuple[str]]], action, index_predicate: str=None): """Sets the action to take when conflicts arise when attempting to insert/create a new row. Arguments: fields: The fields the conflicts can occur in. action: ...
[ "def", "on_conflict", "(", "self", ",", "fields", ":", "List", "[", "Union", "[", "str", ",", "Tuple", "[", "str", "]", "]", "]", ",", "action", ",", "index_predicate", ":", "str", "=", "None", ")", ":", "return", "self", ".", "get_queryset", "(", ...
37.4
24.066667
def paste_clipboard(self, event): """ Send the clipboard content as user input to the CPU. """ log.critical("paste clipboard") clipboard = self.root.clipboard_get() for line in clipboard.splitlines(): log.critical("paste line: %s", repr(line)) self...
[ "def", "paste_clipboard", "(", "self", ",", "event", ")", ":", "log", ".", "critical", "(", "\"paste clipboard\"", ")", "clipboard", "=", "self", ".", "root", ".", "clipboard_get", "(", ")", "for", "line", "in", "clipboard", ".", "splitlines", "(", ")", ...
37.777778
6
def Reset(self): """Preserves FSM but resets starting state and current record.""" # Current state is Start state. self._cur_state = self.states['Start'] self._cur_state_name = 'Start' # Clear table of results and current record. self._result = [] self._ClearAllRecord()
[ "def", "Reset", "(", "self", ")", ":", "# Current state is Start state.", "self", ".", "_cur_state", "=", "self", ".", "states", "[", "'Start'", "]", "self", ".", "_cur_state_name", "=", "'Start'", "# Clear table of results and current record.", "self", ".", "_resul...
29.1
15.8
def windows_install(path_to_python=""): """ Sets the .py extension to be associated with the ftype Python which is then set to the python.exe you provide in the path_to_python variable or after the -p flag if run as a script. Once the python environment is set up the function proceeds to set PATH an...
[ "def", "windows_install", "(", "path_to_python", "=", "\"\"", ")", ":", "if", "not", "path_to_python", ":", "print", "(", "\"Please enter the path to your python.exe you wish Windows to use to run python files. If you do not, this script will not be able to set up a full python environme...
49.253731
28.865672
def modify(self, management_address=None, username=None, password=None, connection_type=None): """ Modifies a remote system for remote replication. :param management_address: same as the one in `create` method. :param username: username for accessing the remote system. ...
[ "def", "modify", "(", "self", ",", "management_address", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "connection_type", "=", "None", ")", ":", "req_body", "=", "self", ".", "_cli", ".", "make_body", "(", "managementAddress...
42.235294
19.529412
def open(self, url, mode='rb', reload=False, filename=None): """Open a file, downloading it first if it does not yet exist. Unlike when you call a loader directly like ``my_loader()``, this ``my_loader.open()`` method does not attempt to parse or interpret the file; it simply returns an...
[ "def", "open", "(", "self", ",", "url", ",", "mode", "=", "'rb'", ",", "reload", "=", "False", ",", "filename", "=", "None", ")", ":", "if", "'://'", "not", "in", "url", ":", "path_that_might_be_relative", "=", "url", "path", "=", "os", ".", "path", ...
43.741935
21.064516
def get_resource(self, resource_wrapper=None): """ Returns a ``Resource`` instance. :param resource_wrapper: A Resource subclass. :return: A ``Resource`` instance. :raises PoolEmptyError: If attempt to get resource fails or times out. """ rtracker = ...
[ "def", "get_resource", "(", "self", ",", "resource_wrapper", "=", "None", ")", ":", "rtracker", "=", "None", "if", "resource_wrapper", "is", "None", ":", "resource_wrapper", "=", "self", ".", "_resource_wrapper", "if", "self", ".", "empty", "(", ")", ":", ...
33.283333
19.916667
def findall(pattern, string, flags=0): """Return a list of all non-overlapping matches in the string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.""" re...
[ "def", "findall", "(", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")", ".", "findall", "(", "string", ")", "# if sys.hexversion >= 0x02020000:", "# __all__.append(\"finditer\")", "def", "fi...
40
15.833333
def eigenvalues_auto(mat, n_eivals='auto'): """ Automatically computes the spectrum of a given Laplacian matrix. Parameters ---------- mat : numpy.ndarray or scipy.sparse Laplacian matrix n_eivals : string or int or tuple Number of eigenvalues to compute / use for approximat...
[ "def", "eigenvalues_auto", "(", "mat", ",", "n_eivals", "=", "'auto'", ")", ":", "do_full", "=", "True", "n_lower", "=", "150", "n_upper", "=", "150", "nv", "=", "mat", ".", "shape", "[", "0", "]", "if", "n_eivals", "==", "'auto'", ":", "if", "mat", ...
37.666667
25.105263
def rpc_receiver_count(self, service, routing_id): '''Get the number of peers that would handle a particular RPC :param service: the service name :type service: anything hash-able :param routing_id: the id used for narrowing within the service handlers :type routing_...
[ "def", "rpc_receiver_count", "(", "self", ",", "service", ",", "routing_id", ")", ":", "peers", "=", "len", "(", "list", "(", "self", ".", "_dispatcher", ".", "find_peer_routes", "(", "const", ".", "MSG_TYPE_RPC_REQUEST", ",", "service", ",", "routing_id", "...
38.944444
20.277778
def generate_search_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate search results for a set of n-grams.""" parser = subparsers.add_parser( 'search', description=constants.SEARCH_DESCRIPTION, epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter, ...
[ "def", "generate_search_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'search'", ",", "description", "=", "constants", ".", "SEARCH_DESCRIPTION", ",", "epilog", "=", "constants", ".", "SEARCH_EPILOG", ",", "formatte...
47
8.642857
def instruction_list(self): """Return a list of instructions for this CompositeGate. If the CompositeGate itself contains composites, call this method recursively. """ instruction_list = [] for instruction in self.data: if isinstance(instruction, CompositeGat...
[ "def", "instruction_list", "(", "self", ")", ":", "instruction_list", "=", "[", "]", "for", "instruction", "in", "self", ".", "data", ":", "if", "isinstance", "(", "instruction", ",", "CompositeGate", ")", ":", "instruction_list", ".", "extend", "(", "instru...
37.384615
14.230769
def fetch_credential(self, credential=None, profile=None): """Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str, None: Fetched credential or ``None...
[ "def", "fetch_credential", "(", "self", ",", "credential", "=", "None", ",", "profile", "=", "None", ")", ":", "q", "=", "self", ".", "db", ".", "get", "(", "self", ".", "query", ".", "profile", "==", "profile", ")", "if", "q", "is", "not", "None",...
31.5
20
def pass_creds_to_nylas(): """ This view loads the credentials from Google and passes them to Nylas, to set up native authentication. """ # If you haven't already connected with Google, this won't work. if not google.authorized: return "Error: not yet connected with Google!", 400 if...
[ "def", "pass_creds_to_nylas", "(", ")", ":", "# If you haven't already connected with Google, this won't work.", "if", "not", "google", ".", "authorized", ":", "return", "\"Error: not yet connected with Google!\"", ",", "400", "if", "\"refresh_token\"", "not", "in", "google",...
43.439394
24.106061
def push_call_history_item(self, state, call_type, state_for_scoped_data, input_data=None): """Adds a new call-history-item to the history item list A call history items stores information about the point in time where a method (entry, execute, exit) of certain state was called. :param...
[ "def", "push_call_history_item", "(", "self", ",", "state", ",", "call_type", ",", "state_for_scoped_data", ",", "input_data", "=", "None", ")", ":", "last_history_item", "=", "self", ".", "get_last_history_item", "(", ")", "from", "rafcon", ".", "core", ".", ...
60
29.105263
def get_recipients_data(self, reports): """Recipients data to be used in the template """ if not reports: return [] recipients = [] recipient_names = [] for num, report in enumerate(reports): # get the linked AR of this ARReport ar = ...
[ "def", "get_recipients_data", "(", "self", ",", "reports", ")", ":", "if", "not", "reports", ":", "return", "[", "]", "recipients", "=", "[", "]", "recipient_names", "=", "[", "]", "for", "num", ",", "report", "in", "enumerate", "(", "reports", ")", ":...
37.885714
13.314286
def dotprint( expr, styles=None, maxdepth=None, repeat=True, labelfunc=expr_labelfunc(str, str), idfunc=None, get_children=_op_children, **kwargs): """Return the `DOT`_ (graph) description of an Expression tree as a string Args: expr (object): The expression to render into a gra...
[ "def", "dotprint", "(", "expr", ",", "styles", "=", "None", ",", "maxdepth", "=", "None", ",", "repeat", "=", "True", ",", "labelfunc", "=", "expr_labelfunc", "(", "str", ",", "str", ")", ",", "idfunc", "=", "None", ",", "get_children", "=", "_op_child...
46.398148
23.166667
def ipi_base_number(name=None): """ IPI Base Number field. An IPI Base Number code written on a field follows the Pattern C-NNNNNNNNN-M. This being: - C: header, a character. - N: numeric value. - M: control digit. So, for example, an IPI Base Number code field can contain I-000000229-...
[ "def", "ipi_base_number", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'IPI Base Number Field'", "field", "=", "pp", ".", "Regex", "(", "'I-[0-9]{9}-[0-9]'", ")", "# Name", "field", ".", "setName", "(", "name", ")", ...
22.151515
20.636364
def configure_count(self, ns, definition): """ Register a count endpoint. The definition's func should be a count function, which must: - accept kwargs for the query string - return a count is the total number of items available The definition's request_schema will be u...
[ "def", "configure_count", "(", "self", ",", "ns", ",", "definition", ")", ":", "@", "self", ".", "add_route", "(", "ns", ".", "collection_path", ",", "Operation", ".", "Count", ",", "ns", ")", "@", "qs", "(", "definition", ".", "request_schema", ")", "...
39.46875
20.96875
def read_hdf(path_or_buf, key=None, mode='r', **kwargs): """ Read from the store, close it if we opened it. Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : string, buffer or path object Path to the file to open, or an op...
[ "def", "read_hdf", "(", "path_or_buf", ",", "key", "=", "None", ",", "mode", "=", "'r'", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "not", "in", "[", "'r'", ",", "'r+'", ",", "'a'", "]", ":", "raise", "ValueError", "(", "'mode {0} is not allowe...
35.697479
20.789916
def invoke_with_usage (self, args, **kwargs): """Invoke the command with standardized usage-help processing. Same calling convention as `Command.invoke()`, except here *args* is an un-parsed list of strings. """ ap = self.get_arg_parser (**kwargs) args = ap.parse_args (a...
[ "def", "invoke_with_usage", "(", "self", ",", "args", ",", "*", "*", "kwargs", ")", ":", "ap", "=", "self", ".", "get_arg_parser", "(", "*", "*", "kwargs", ")", "args", "=", "ap", ".", "parse_args", "(", "args", ")", "return", "self", ".", "invoke", ...
40
10.666667
def get_frequency_list(lang, wordlist='best', match_cutoff=30): """ Read the raw data from a wordlist file, returning it as a list of lists. (See `read_cBpack` for what this represents.) Because we use the `langcodes` module, we can handle slight variations in language codes. For example, looking f...
[ "def", "get_frequency_list", "(", "lang", ",", "wordlist", "=", "'best'", ",", "match_cutoff", "=", "30", ")", ":", "available", "=", "available_languages", "(", "wordlist", ")", "best", ",", "score", "=", "langcodes", ".", "best_match", "(", "lang", ",", ...
41.72
21.24
def input_validate_yubikey_secret(data, name='data'): """ Input validation for YHSM_YubiKeySecret or string. """ if isinstance(data, pyhsm.aead_cmd.YHSM_YubiKeySecret): data = data.pack() return input_validate_str(data, name)
[ "def", "input_validate_yubikey_secret", "(", "data", ",", "name", "=", "'data'", ")", ":", "if", "isinstance", "(", "data", ",", "pyhsm", ".", "aead_cmd", ".", "YHSM_YubiKeySecret", ")", ":", "data", "=", "data", ".", "pack", "(", ")", "return", "input_val...
48.2
9.4
def set_perplexities(self, new_perplexities): """Change the perplexities of the affinity matrix. Note that we only allow lowering the perplexities or restoring them to their original maximum value. This restriction exists because setting a higher perplexity value requires recomputing al...
[ "def", "set_perplexities", "(", "self", ",", "new_perplexities", ")", ":", "if", "np", ".", "array_equal", "(", "self", ".", "perplexities", ",", "new_perplexities", ")", ":", "return", "new_perplexities", "=", "self", ".", "check_perplexities", "(", "new_perple...
40.829268
22.317073
def process_targets_element(cls, scanner_target): """ Receive an XML object with the target, ports and credentials to run a scan against. @param: XML element with target subelements. Each target has <hosts> and <ports> subelements. Hosts can be a single host, a host range, a com...
[ "def", "process_targets_element", "(", "cls", ",", "scanner_target", ")", ":", "target_list", "=", "[", "]", "for", "target", "in", "scanner_target", ":", "ports", "=", "''", "credentials", "=", "{", "}", "for", "child", "in", "target", ":", "if", "child",...
40.305085
15.864407
def add_pending(self, family: str, email: str=None) -> models.Analysis: """Add pending entry for an analysis.""" started_at = dt.datetime.now() new_log = self.Analysis(family=family, status='pending', started_at=started_at) new_log.user = self.user(email) if email else None self....
[ "def", "add_pending", "(", "self", ",", "family", ":", "str", ",", "email", ":", "str", "=", "None", ")", "->", "models", ".", "Analysis", ":", "started_at", "=", "dt", ".", "datetime", ".", "now", "(", ")", "new_log", "=", "self", ".", "Analysis", ...
50.857143
17.714286
def build_from_job_list(scheme_files, templates, base_output_dir): """Use $scheme_files as a job lists and build base16 templates using $templates (a list of TemplateGroup objects).""" queue = Queue() for scheme in scheme_files: queue.put(scheme) if len(scheme_files) < 40: thread_nu...
[ "def", "build_from_job_list", "(", "scheme_files", ",", "templates", ",", "base_output_dir", ")", ":", "queue", "=", "Queue", "(", ")", "for", "scheme", "in", "scheme_files", ":", "queue", ".", "put", "(", "scheme", ")", "if", "len", "(", "scheme_files", "...
26.807692
19.653846
def request(self, source="candidate"): """Validate the contents of the specified configuration. *source* is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated :seealso: :ref:`srctarget_params`""" node = new_e...
[ "def", "request", "(", "self", ",", "source", "=", "\"candidate\"", ")", ":", "node", "=", "new_ele", "(", "\"validate\"", ")", "if", "type", "(", "source", ")", "is", "str", ":", "src", "=", "util", ".", "datastore_or_url", "(", "\"source\"", ",", "so...
42.266667
21.866667
def parse_params(self, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search='grid_search', num_iterations=64, gamma=0.01, const...
[ "def", "parse_params", "(", "self", ",", "y_target", "=", "None", ",", "image_target", "=", "None", ",", "initial_num_evals", "=", "100", ",", "max_num_evals", "=", "10000", ",", "stepsize_search", "=", "'grid_search'", ",", "num_iterations", "=", "64", ",", ...
46.301887
15.735849
def output_path(self, path_name): """ Modify a path so it fits expectations. Avoid returning relative paths that start with '../' and possibly return relative paths when output and cache directories match. """ # make sure it is a valid posix format ...
[ "def", "output_path", "(", "self", ",", "path_name", ")", ":", "# make sure it is a valid posix format", "path", "=", "to_posix", "(", "path_name", ")", "assert", "(", "path", "==", "path_name", ")", ",", "\"path_name passed to output_path must be in posix format\"", "i...
36.333333
19.958333
def with_revision(self, label, number): """ Returns a Tag with a given revision """ t = self.clone() t.revision = Revision(label, number) return t
[ "def", "with_revision", "(", "self", ",", "label", ",", "number", ")", ":", "t", "=", "self", ".", "clone", "(", ")", "t", ".", "revision", "=", "Revision", "(", "label", ",", "number", ")", "return", "t" ]
26.857143
6.857143
def update_machine_state(state_path): """Update the machine state using the provided state declaration.""" charmhelpers.contrib.templating.contexts.juju_state_to_yaml( salt_grains_path) subprocess.check_call([ 'salt-call', '--local', 'state.template', state_path, ...
[ "def", "update_machine_state", "(", "state_path", ")", ":", "charmhelpers", ".", "contrib", ".", "templating", ".", "contexts", ".", "juju_state_to_yaml", "(", "salt_grains_path", ")", "subprocess", ".", "check_call", "(", "[", "'salt-call'", ",", "'--local'", ","...
31.3
16.7
def get_meta(self, key, conforming=True): """ RETURN METADATA ON FILE IN BUCKET :param key: KEY, OR PREFIX OF KEY :param conforming: TEST IF THE KEY CONFORMS TO REQUIRED PATTERN :return: METADATA, IF UNIQUE, ELSE ERROR """ try: metas = list(self.bucke...
[ "def", "get_meta", "(", "self", ",", "key", ",", "conforming", "=", "True", ")", ":", "try", ":", "metas", "=", "list", "(", "self", ".", "bucket", ".", "list", "(", "prefix", "=", "key", ")", ")", "metas", "=", "wrap", "(", "[", "m", "for", "m...
39.333333
15.238095
def prepare_environment(default_settings=_default_settings, **kwargs): # pylint: disable=unused-argument ''' Prepare ENV for web-application :param default_settings: minimal needed settings for run app :type default_settings: dict :param kwargs: other overrided settings :rtype: None ''' ...
[ "def", "prepare_environment", "(", "default_settings", "=", "_default_settings", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "for", "key", ",", "value", "in", "default_settings", ".", "items", "(", ")", ":", "os", ".", "environ", ".",...
34.823529
17.529412
def model_schema( model: Type['main.BaseModel'], by_alias: bool = True, ref_prefix: Optional[str] = None ) -> Dict[str, Any]: """ Generate a JSON Schema for one model. With all the sub-models defined in the ``definitions`` top-level JSON key. :param model: a Pydantic model (a class that inherits fr...
[ "def", "model_schema", "(", "model", ":", "Type", "[", "'main.BaseModel'", "]", ",", "by_alias", ":", "bool", "=", "True", ",", "ref_prefix", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "ref_pre...
52.56
32.16
def press_and_tap(self, press_key, tap_key, n=1, interval=0, pre_dl=None, post_dl=None): """Press combination of two keys, like Ctrl + C, Alt + F4. The second key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "c") bot.press_and_tap("shift", "1"...
[ "def", "press_and_tap", "(", "self", ",", "press_key", ",", "tap_key", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "press_key", "=", "self", ".", "_parse_key", "(", "press_key", ")...
29.333333
17.809524
def replace_template(self, template_content, team_context, template_id): """ReplaceTemplate. [Preview API] Replace template contents :param :class:`<WorkItemTemplate> <azure.devops.v5_1.work_item_tracking.models.WorkItemTemplate>` template_content: Template contents to replace with :para...
[ "def", "replace_template", "(", "self", ",", "template_content", ",", "team_context", ",", "template_id", ")", ":", "project", "=", "None", "team", "=", "None", "if", "team_context", "is", "not", "None", ":", "if", "team_context", ".", "project_id", ":", "pr...
52.147059
23.676471
def get_attributes(**kwargs): """ Get all attributes """ attrs = db.DBSession.query(Attr).order_by(Attr.name).all() return attrs
[ "def", "get_attributes", "(", "*", "*", "kwargs", ")", ":", "attrs", "=", "db", ".", "DBSession", ".", "query", "(", "Attr", ")", ".", "order_by", "(", "Attr", ".", "name", ")", ".", "all", "(", ")", "return", "attrs" ]
18.375
18.875
def create_packages_archive(packages, filename): """ Create a tar archive which will contain the files for the packages listed in packages. """ import tarfile tar = tarfile.open(filename, "w") def add(src, dst): logger.debug('adding to tar: %s -> %s', src, dst) tar.add(src, dst)...
[ "def", "create_packages_archive", "(", "packages", ",", "filename", ")", ":", "import", "tarfile", "tar", "=", "tarfile", ".", "open", "(", "filename", ",", "\"w\"", ")", "def", "add", "(", "src", ",", "dst", ")", ":", "logger", ".", "debug", "(", "'ad...
40.070423
21.56338
def saveDirectory(alias): """save a directory to a certain alias/nickname""" if not settings.platformCompatible(): return False dataFile = open(settings.getDataFile(), "wb") currentDirectory = os.path.abspath(".") directory = {alias : currentDirectory} pickle.dump(directory, dataFile) speech.success(alias + " ...
[ "def", "saveDirectory", "(", "alias", ")", ":", "if", "not", "settings", ".", "platformCompatible", "(", ")", ":", "return", "False", "dataFile", "=", "open", "(", "settings", ".", "getDataFile", "(", ")", ",", "\"wb\"", ")", "currentDirectory", "=", "os",...
44.1
13.2
def assert_less(first, second, msg_fmt="{msg}"): """Fail if first is not less than second. >>> assert_less('bar', 'foo') >>> assert_less(5, 5) Traceback (most recent call last): ... AssertionError: 5 is not less than 5 The following msg_fmt arguments are supported: * msg - the defa...
[ "def", "assert_less", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "first", "<", "second", ":", "msg", "=", "\"{!r} is not less than {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", "(", "msg_fmt", ...
30.833333
15.055556
def keplerian_sheared_field_locations(ax, kbos, date, ras, decs, names, elongation=False, plot=False): """ Shift fields from the discovery set to the requested date by the average motion of L7 kbos in the discovery field. :param ras: :param decs: :param plot: :param ax: :param kbos: precompu...
[ "def", "keplerian_sheared_field_locations", "(", "ax", ",", "kbos", ",", "date", ",", "ras", ",", "decs", ",", "names", ",", "elongation", "=", "False", ",", "plot", "=", "False", ")", ":", "seps", "=", "{", "'dra'", ":", "0.", ",", "'ddec'", ":", "0...
39.136364
25.227273
def get(self, key, default=None, type_=None): """ Return the last data value for the passed key. If key doesn't exist or value is an empty list, return `default`. """ try: rv = self[key] except KeyError: return default if type_ is not None:...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "type_", "=", "None", ")", ":", "try", ":", "rv", "=", "self", "[", "key", "]", "except", "KeyError", ":", "return", "default", "if", "type_", "is", "not", "None", ":", "try...
28.8
14.266667
def get_json_response(self, content, **kwargs): """Returns a json response object.""" # Don't care to return a django form or view in the response here. # Remove those from the context. if isinstance(content, dict): response_content = {k: deepcopy(v) for k, v in content.item...
[ "def", "get_json_response", "(", "self", ",", "content", ",", "*", "*", "kwargs", ")", ":", "# Don't care to return a django form or view in the response here.", "# Remove those from the context.", "if", "isinstance", "(", "content", ",", "dict", ")", ":", "response_conte...
46.533333
21.533333
def verify_gmt_integrity(gmt): """ Make sure that set ids are unique. Args: gmt (GMT object): list of dicts Returns: None """ # Verify that set ids are unique set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt] assert len(set(set_ids)) == len(set_ids), ( "Set identif...
[ "def", "verify_gmt_integrity", "(", "gmt", ")", ":", "# Verify that set ids are unique", "set_ids", "=", "[", "d", "[", "SET_IDENTIFIER_FIELD", "]", "for", "d", "in", "gmt", "]", "assert", "len", "(", "set", "(", "set_ids", ")", ")", "==", "len", "(", "set...
23.866667
20.866667
def get_owner(self, default=True): """Return (User ID, Group ID) tuple :param bool default: Whether to return default if not set. :rtype: tuple[int, int] """ uid, gid = self.owner if not uid and default: uid = os.getuid() if not gid and default: ...
[ "def", "get_owner", "(", "self", ",", "default", "=", "True", ")", ":", "uid", ",", "gid", "=", "self", ".", "owner", "if", "not", "uid", "and", "default", ":", "uid", "=", "os", ".", "getuid", "(", ")", "if", "not", "gid", "and", "default", ":",...
23.8
17.933333
def run(self, **kwargs): """ Run the model Parameters ---------- ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method """ from calculate import compute self.app_main(**kwargs) ...
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "calculate", "import", "compute", "self", ".", "app_main", "(", "*", "*", "kwargs", ")", "# get the default output name", "output", "=", "osp", ".", "join", "(", "self", ".", "exp_conf...
32.129032
19.096774
def validate_steps(self, request, workflow, start, end): """Validates the workflow steps from ``start`` to ``end``, inclusive. Returns a dict describing the validation state of the workflow. """ errors = {} for step in workflow.steps[start:end + 1]: if not step.actio...
[ "def", "validate_steps", "(", "self", ",", "request", ",", "workflow", ",", "start", ",", "end", ")", ":", "errors", "=", "{", "}", "for", "step", "in", "workflow", ".", "steps", "[", "start", ":", "end", "+", "1", "]", ":", "if", "not", "step", ...
40.25
15.75
def _modname(path): """Return a plausible module name for the path""" base = os.path.basename(path) filename, ext = os.path.splitext(base) return filename
[ "def", "_modname", "(", "path", ")", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "base", ")", "return", "filename" ]
33.2
10.2
def convert_raw_data_to_universes(raw_data) -> tuple: """ converts the raw data to a readable universes tuple. The raw_data is scanned from index 0 and has to have 16-bit numbers with high byte first. The data is converted from the start to the beginning! :param raw_data: the raw data to convert :re...
[ "def", "convert_raw_data_to_universes", "(", "raw_data", ")", "->", "tuple", ":", "if", "len", "(", "raw_data", ")", "%", "2", "!=", "0", ":", "raise", "TypeError", "(", "'The given data has not a length that is a multiple of 2!'", ")", "rtrnList", "=", "[", "]", ...
47.769231
20.384615
def getMeta(self, uri): """Return meta information about an action. Cache the result as specified by the server""" action = urlparse(uri).path mediaKey = self.cacheKey + '_meta_' + action mediaKey = mediaKey.replace(' ', '__') meta = cache.get(mediaKey, None) # Nothin...
[ "def", "getMeta", "(", "self", ",", "uri", ")", ":", "action", "=", "urlparse", "(", "uri", ")", ".", "path", "mediaKey", "=", "self", ".", "cacheKey", "+", "'_meta_'", "+", "action", "mediaKey", "=", "mediaKey", ".", "replace", "(", "' '", ",", "'__...
37.185185
28.740741
def get_yaml_items(self, dir_path, param=None): ''' Loops through the dir_path and parses all YAML files inside the directory. If no param is defined, then all YAML items will be returned in a list. If a param is defined, then all items will be scanned for this param and...
[ "def", "get_yaml_items", "(", "self", ",", "dir_path", ",", "param", "=", "None", ")", ":", "result", "=", "[", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "return", "[", "]", "for", "filename", "in", "os", ".", ...
30.40625
20.34375
def get_item(self, address, state = 'fresh'): """Get an item from the cache. :Parameters: - `address`: its address. - `state`: the worst state that is acceptable. :Types: - `address`: any hashable - `state`: `str` :return: the item or `No...
[ "def", "get_item", "(", "self", ",", "address", ",", "state", "=", "'fresh'", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "item", "=", "self", ".", "_items", ".", "get", "(", "address", ")", "if", "not", "item", ":", "re...
30.043478
14.695652
def get_history_item_for_tree_iter(self, child_tree_iter): """Hands history item for tree iter and compensate if tree item is a dummy item :param Gtk.TreeIter child_tree_iter: Tree iter of row :rtype rafcon.core.execution.execution_history.HistoryItem: :return history tree item: ...
[ "def", "get_history_item_for_tree_iter", "(", "self", ",", "child_tree_iter", ")", ":", "history_item", "=", "self", ".", "history_tree_store", "[", "child_tree_iter", "]", "[", "self", ".", "HISTORY_ITEM_STORAGE_ID", "]", "if", "history_item", "is", "None", ":", ...
56.866667
26.6
def dict_to_object(self, d): """ Decode datetime value from string to datetime """ for k, v in list(d.items()): if isinstance(v, six.string_types) and len(v) == 19: # Decode a datetime string to a datetime object try: d[k] =...
[ "def", "dict_to_object", "(", "self", ",", "d", ")", ":", "for", "k", ",", "v", "in", "list", "(", "d", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "six", ".", "string_types", ")", "and", "len", "(", "v", ")", "==", "...
39.789474
15.263158
def create_attachment(cls, session, attachment): """Create an attachment. An attachment must be sent to the API before it can be used in a thread. Use this method to create the attachment, then use the resulting hash when creating a thread. Note that HelpScout only supports att...
[ "def", "create_attachment", "(", "cls", ",", "session", ",", "attachment", ")", ":", "return", "super", "(", "Conversations", ",", "cls", ")", ".", "create", "(", "session", ",", "attachment", ",", "endpoint_override", "=", "'/attachments.json'", ",", "out_typ...
36.28
23.36
def read_abinit_hdr(self): """ Read the variables associated to the Abinit header. Return :class:`AbinitHeader` """ d = {} for hvar in _HDR_VARIABLES.values(): ncname = hvar.etsf_name if hvar.etsf_name is not None else hvar.name if ncname in self....
[ "def", "read_abinit_hdr", "(", "self", ")", ":", "d", "=", "{", "}", "for", "hvar", "in", "_HDR_VARIABLES", ".", "values", "(", ")", ":", "ncname", "=", "hvar", ".", "etsf_name", "if", "hvar", ".", "etsf_name", "is", "not", "None", "else", "hvar", "....
45.148148
20.333333
def previousSibling(self): ''' previousSibling - Returns the previous sibling. This would be the previous node (text or tag) in the parent's list This could be text or an element. use previousSiblingElement to ensure element @return <None/str/AdvancedTa...
[ "def", "previousSibling", "(", "self", ")", ":", "parentNode", "=", "self", ".", "parentNode", "# If no parent, no previous sibling", "if", "not", "parentNode", ":", "return", "None", "# Determine block index on parent of this node", "myBlockIdx", "=", "parentNode", ".", ...
37.24
29
def scroll(self, rect, dx, dy, attr=None, fill=' '): u'''Scroll a rectangle.''' if attr is None: attr = self.attr x0, y0, x1, y1 = rect source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1) dest = self.fixcoord(x0 + dx, y0 + dy) style = CHAR_INFO() style...
[ "def", "scroll", "(", "self", ",", "rect", ",", "dx", ",", "dy", ",", "attr", "=", "None", ",", "fill", "=", "' '", ")", ":", "if", "attr", "is", "None", ":", "attr", "=", "self", ".", "attr", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "re...
41
16.384615
def add_source(source, key=None, fail_invalid=False): """Add a package source to this system. @param source: a URL or sources.list entry, as supported by add-apt-repository(1). Examples:: ppa:charmers/example deb https://stub:key@private.example.com/ubuntu trusty main In addition: ...
[ "def", "add_source", "(", "source", ",", "key", "=", "None", ",", "fail_invalid", "=", "False", ")", ":", "_mapping", "=", "OrderedDict", "(", "[", "(", "r\"^distro$\"", ",", "lambda", ":", "None", ")", ",", "# This is a NOP", "(", "r\"^(?:proposed|distro-pr...
43.908046
21.609195
def insert(self, item, priority): """Adds item to DEPQ with given priority by performing a binary search on the concurrently rotating deque. Amount rotated R of DEPQ of length n would be n <= R <= 3n/2. Performance: O(n)""" with self.lock: self_data = self.data ...
[ "def", "insert", "(", "self", ",", "item", ",", "priority", ")", ":", "with", "self", ".", "lock", ":", "self_data", "=", "self", ".", "data", "rotate", "=", "self_data", ".", "rotate", "self_items", "=", "self", ".", "items", "maxlen", "=", "self", ...
34.602941
16.558824
def Analyze(self, hashes): """Looks up hashes in nsrlsvr. Args: hashes (list[str]): hash values to look up. Returns: list[HashAnalysis]: analysis results, or an empty list on error. """ logger.debug( 'Opening connection to {0:s}:{1:d}'.format(self._host, self._port)) nsrl_...
[ "def", "Analyze", "(", "self", ",", "hashes", ")", ":", "logger", ".", "debug", "(", "'Opening connection to {0:s}:{1:d}'", ".", "format", "(", "self", ".", "_host", ",", "self", ".", "_port", ")", ")", "nsrl_socket", "=", "self", ".", "_GetSocket", "(", ...
24.34375
23.4375
def create_board(self, name, project_ids, preset="scrum", location_type='user', location_id=None): """Create a new board for the ``project_ids``. :param name: name of the board :type name: str :param project_ids: the projects to create the board in :type pro...
[ "def", "create_board", "(", "self", ",", "name", ",", "project_ids", ",", "preset", "=", "\"scrum\"", ",", "location_type", "=", "'user'", ",", "location_id", "=", "None", ")", ":", "if", "self", ".", "_options", "[", "'agile_rest_path'", "]", "!=", "Green...
43.377778
16.733333
def update(self, fieldname, localValue, remoteValue): ''' Returns the appropriate current value, based on the changes recorded by this ChangeTracker, the value stored by the server (`localValue`), and the value stored by the synchronizing client (`remoteValue`). If `remoteValue` conflicts with chang...
[ "def", "update", "(", "self", ",", "fieldname", ",", "localValue", ",", "remoteValue", ")", ":", "if", "localValue", "==", "remoteValue", ":", "return", "localValue", "ct", "=", "constants", ".", "ITEM_DELETED", "if", "remoteValue", "is", "None", "else", "co...
38.408163
25.714286