text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'function') and self.function is not None: _dict['function'] = self.function if hasattr(self, 'input_bucket_location' ) and self.input_bucket_location is ...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'function'", ")", "and", "self", ".", "function", "is", "not", "None", ":", "_dict", "[", "'function'", "]", "=", "self", ".", "function", "if", "...
53
0.002471
def create_sampler(self, inputs, targets, input_reader=None, target_reader=None, input_transform=None, target_transform=None, co_transform=None, input_return_processor=None, target_return_processor=None, co_return_processor=None): """ Create a BIDSSampler that can be used to generate in...
[ "def", "create_sampler", "(", "self", ",", "inputs", ",", "targets", ",", "input_reader", "=", "None", ",", "target_reader", "=", "None", ",", "input_transform", "=", "None", ",", "target_transform", "=", "None", ",", "co_transform", "=", "None", ",", "input...
51.857143
0.02168
def batch_fn(dataset, training, shapes, target_names, batch_size=32, eval_batch_size=32, bucket_batch_length=32, bucket_max_length=256, bucket_min_length=8, bucket_length_step=1.1, buckets=None): """Batching function.""" del target_names # If bucketing is not specified, chec...
[ "def", "batch_fn", "(", "dataset", ",", "training", ",", "shapes", ",", "target_names", ",", "batch_size", "=", "32", ",", "eval_batch_size", "=", "32", ",", "bucket_batch_length", "=", "32", ",", "bucket_max_length", "=", "256", ",", "bucket_min_length", "=",...
45.142857
0.009294
def write_acceptance_fraction(self, acceptance_fraction): """Write acceptance_fraction data to file. Results are written to ``[sampler_group]/acceptance_fraction``; the resulting dataset has shape (ntemps, nwalkers). Parameters ----------- acceptance_fraction : numpy.nd...
[ "def", "write_acceptance_fraction", "(", "self", ",", "acceptance_fraction", ")", ":", "# check", "assert", "acceptance_fraction", ".", "shape", "==", "(", "self", ".", "ntemps", ",", "self", ".", "nwalkers", ")", ",", "(", "\"acceptance fraction must have shape nte...
39.047619
0.002381
def filter_pages(pages, pagenum, pagename): """ Choices pages by pagenum and pagename """ if pagenum: try: pages = [list(pages)[pagenum - 1]] except IndexError: raise IndexError('Invalid page number: %d' % pagenum) if pagename: pages = [page for page in pages...
[ "def", "filter_pages", "(", "pages", ",", "pagenum", ",", "pagename", ")", ":", "if", "pagenum", ":", "try", ":", "pages", "=", "[", "list", "(", "pages", ")", "[", "pagenum", "-", "1", "]", "]", "except", "IndexError", ":", "raise", "IndexError", "(...
31.857143
0.002179
def rowsum_stdev(x, beta): r"""Compute row sum standard deviation. Compute for approximation x, the std dev of the row sums s(x) = ( 1/n \sum_k (x_k beta_k - betabar)^2 )^(1/2) with betabar = 1/n dot(beta,x) Parameters ---------- x : array beta : array Returns ------- s(x...
[ "def", "rowsum_stdev", "(", "x", ",", "beta", ")", ":", "n", "=", "x", ".", "size", "betabar", "=", "(", "1.0", "/", "n", ")", "*", "np", ".", "dot", "(", "x", ",", "beta", ")", "stdev", "=", "np", ".", "sqrt", "(", "(", "1.0", "/", "n", ...
21.423077
0.001718
def add_layer(self, layer=None, **kwargs): '''Add a :ref:`layer <layers>` to our network graph. Parameters ---------- layer : int, tuple, dict, or :class:`Layer <theanets.layers.base.Layer>` A value specifying the layer to add. For more information, please see :r...
[ "def", "add_layer", "(", "self", ",", "layer", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# if the given layer is a Layer instance, just add it and move on.", "if", "isinstance", "(", "layer", ",", "layers", ".", "Layer", ")", ":", "self", ".", "layers", ...
41.897959
0.001903
def encode_location(location: BioCLocation): """Encode a single location.""" return etree.Element('location', {'offset': str(location.offset), 'length': str(location.length)})
[ "def", "encode_location", "(", "location", ":", "BioCLocation", ")", ":", "return", "etree", ".", "Element", "(", "'location'", ",", "{", "'offset'", ":", "str", "(", "location", ".", "offset", ")", ",", "'length'", ":", "str", "(", "location", ".", "len...
52
0.009479
def _observe(self, api_command): """Observe an endpoint.""" path = api_command.path duration = api_command.observe_duration if duration <= 0: raise ValueError("Observation duration has to be greater than 0.") url = api_command.url(self._host) err_callback = ap...
[ "def", "_observe", "(", "self", ",", "api_command", ")", ":", "path", "=", "api_command", ".", "path", "duration", "=", "api_command", ".", "observe_duration", "if", "duration", "<=", "0", ":", "raise", "ValueError", "(", "\"Observation duration has to be greater ...
32.204545
0.00137
def hqwe(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH, zetaV, xdirect, qweargs, use_ne_eval, msrc, mrec): r"""Hankel Transform using Quadrature-With-Extrapolation. *Quadrature-With-Extrapolation* was introduced to geophysics by [Key12]_. It is one of many so-called *ISE* meth...
[ "def", "hqwe", "(", "zsrc", ",", "zrec", ",", "lsrc", ",", "lrec", ",", "off", ",", "factAng", ",", "depth", ",", "ab", ",", "etaH", ",", "etaV", ",", "zetaH", ",", "zetaV", ",", "xdirect", ",", "qweargs", ",", "use_ne_eval", ",", "msrc", ",", "m...
36.358885
0.000093
def list_snapshots(self): """ Returns a list of all snapshots of this volume. """ return [snap for snap in self.manager.list_snapshots() if snap.volume_id == self.id]
[ "def", "list_snapshots", "(", "self", ")", ":", "return", "[", "snap", "for", "snap", "in", "self", ".", "manager", ".", "list_snapshots", "(", ")", "if", "snap", ".", "volume_id", "==", "self", ".", "id", "]" ]
34.833333
0.009346
def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore """ if len(labels) == 0: # only void pixels, the gra...
[ "def", "lovasz_hinge_flat", "(", "logits", ",", "labels", ")", ":", "if", "len", "(", "labels", ")", "==", "0", ":", "# only void pixels, the gradients should be 0", "return", "logits", ".", "sum", "(", ")", "*", "0.", "signs", "=", "2.", "*", "labels", "....
36.5
0.008011
def get_reverse(self): """By default, Cable entries are sorted by rating and Broadcast ratings are sorted by time. By default, float attributes are sorted from highest to lowest and non-float attributes are sorted alphabetically (show, net) or chronologically (time). """ ...
[ "def", "get_reverse", "(", "self", ")", ":", "if", "self", ".", "sort", "in", "FLOAT_ATTRIBUTES", ":", "return", "True", "elif", "self", ".", "sort", "in", "NONFLOAT_ATTRIBUTES", ":", "return", "False", "else", ":", "raise", "InvalidSortError", "(", "self", ...
41.5
0.009823
def _read_mode_tr(self, size, kind): """Read Traceroute option. Positional arguments: size - int, length of option kind - int, 82 (TR) Returns: * dict -- extracted Traceroute (TR) option Structure of Traceroute (TR) option [RFC 1393][RFC 6814]: ...
[ "def", "_read_mode_tr", "(", "self", ",", "size", ",", "kind", ")", ":", "if", "size", "!=", "12", ":", "raise", "ProtocolError", "(", "f'{self.alias}: [Optno {kind}] invalid format'", ")", "_idnm", "=", "self", ".", "_read_unpack", "(", "2", ")", "_ohcn", "...
41.078431
0.000932
def ensure_cache_folder(self): """ Creates a gradle cache folder if it does not exist. """ if os.path.exists(self.cache_folder) is False: os.makedirs(self.cache_folder)
[ "def", "ensure_cache_folder", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "cache_folder", ")", "is", "False", ":", "os", ".", "makedirs", "(", "self", ".", "cache_folder", ")" ]
30.833333
0.010526
def __stream_format_allowed(self, stream): """ Check whether a stream allows formatting such as coloring. Inspired from Python cookbook, #475186 """ # curses isn't available on all platforms try: import curses as CURSES except: return False...
[ "def", "__stream_format_allowed", "(", "self", ",", "stream", ")", ":", "# curses isn't available on all platforms", "try", ":", "import", "curses", "as", "CURSES", "except", ":", "return", "False", "try", ":", "CURSES", ".", "setupterm", "(", ")", "return", "CU...
29.4
0.008791
def absent(version, name): ''' Ensure that the named cluster is absent version Version of the postgresql server of the cluster to remove name The name of the cluster to remove .. versionadded:: 2015.XX ''' ret = {'name': name, 'changes': {}, ...
[ "def", "absent", "(", "version", ",", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "#check if cluster exists and remove it", "if", "__salt__", "...
29.685714
0.001864
def repo( state, host, source, target, branch='master', pull=True, rebase=False, user=None, group=None, use_ssh_user=False, ssh_keyscan=False, ): ''' Clone/pull git repositories. + source: the git source URL + target: target directory to clone to + branch: branch to pull/checkout + ...
[ "def", "repo", "(", "state", ",", "host", ",", "source", ",", "target", ",", "branch", "=", "'master'", ",", "pull", "=", "True", ",", "rebase", "=", "False", ",", "user", "=", "None", ",", "group", "=", "None", ",", "use_ssh_user", "=", "False", "...
31.575472
0.001738
def verb_chain_texts(self): """The list of texts of ``verb_chains`` layer elements.""" if not self.is_tagged(VERB_CHAINS): self.tag_verb_chains() return self.texts(VERB_CHAINS)
[ "def", "verb_chain_texts", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "VERB_CHAINS", ")", ":", "self", ".", "tag_verb_chains", "(", ")", "return", "self", ".", "texts", "(", "VERB_CHAINS", ")" ]
41.6
0.009434
def compress_G2(pt: G2Uncompressed) -> G2Compressed: """ The compressed point (z1, z2) has the bit order: z1: (c_flag1, b_flag1, a_flag1, x1) z2: (c_flag2, b_flag2, a_flag2, x2) where - c_flag1 is always set to 1 - b_flag1 indicates infinity when set to 1 - a_flag1 helps determine the y-...
[ "def", "compress_G2", "(", "pt", ":", "G2Uncompressed", ")", "->", "G2Compressed", ":", "if", "not", "is_on_curve", "(", "pt", ",", "b2", ")", ":", "raise", "ValueError", "(", "\"The given point is not on the twisted curve over FQ**2\"", ")", "if", "is_inf", "(", ...
35.8
0.000907
def login_as_bot(): """ Login as the bot account "octogrid", if user isn't authenticated on Plotly """ plotly_credentials_file = join( join(expanduser('~'), PLOTLY_DIRECTORY), PLOTLY_CREDENTIALS_FILENAME) if isfile(plotly_credentials_file): with open(plotly_credentials_file, 'r') as f: credentials = lo...
[ "def", "login_as_bot", "(", ")", ":", "plotly_credentials_file", "=", "join", "(", "join", "(", "expanduser", "(", "'~'", ")", ",", "PLOTLY_DIRECTORY", ")", ",", "PLOTLY_CREDENTIALS_FILENAME", ")", "if", "isfile", "(", "plotly_credentials_file", ")", ":", "with"...
30.3125
0.032
def transform_coords(self, width, height): """Return the current absolute coordinates of the touch event, transformed to screen coordinates. For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`, :attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method raises :exc:`AttributeError`. ...
[ "def", "transform_coords", "(", "self", ",", "width", ",", "height", ")", ":", "if", "self", ".", "type", "not", "in", "{", "EventType", ".", "TOUCH_DOWN", ",", "EventType", ".", "TOUCH_MOTION", "}", ":", "raise", "AttributeError", "(", "_wrong_meth", ".",...
36
0.024706
def checkablePopup( self ): """ Returns the popup if this widget is checkable. :return <QListView> || None """ if not self._checkablePopup and self.isCheckable(): popup = QListView(self) popup.setSelectionMode(QListView.NoSelection) ...
[ "def", "checkablePopup", "(", "self", ")", ":", "if", "not", "self", ".", "_checkablePopup", "and", "self", ".", "isCheckable", "(", ")", ":", "popup", "=", "QListView", "(", "self", ")", "popup", ".", "setSelectionMode", "(", "QListView", ".", "NoSelectio...
37.375
0.009788
def where(self, *args, **kwargs): " :where " [(self._where.append(x)) for x in args] return self
[ "def", "where", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "[", "(", "self", ".", "_where", ".", "append", "(", "x", ")", ")", "for", "x", "in", "args", "]", "return", "self" ]
26.25
0.009259
def _get_language_modeling_inputs(filename, delimiter="\n", repeat=1, append_space_to_final_punctionation=True): """Read a file of partial texts to continue. The purpose of append_space_to_final_punctionation is t...
[ "def", "_get_language_modeling_inputs", "(", "filename", ",", "delimiter", "=", "\"\\n\"", ",", "repeat", "=", "1", ",", "append_space_to_final_punctionation", "=", "True", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "filename", ")", "as", "f", "...
32.344828
0.008282
def check_header_comment(filename): """Checks if the header-comment of the given file needs fixing.""" # Check input file. name = os.path.basename( filename ) # Read content of input file. sourcefile = open( filename, "rU" ) content = sourcefile.read() sourcefile.close() # Search content...
[ "def", "check_header_comment", "(", "filename", ")", ":", "# Check input file.", "name", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "# Read content of input file.", "sourcefile", "=", "open", "(", "filename", ",", "\"rU\"", ")", "content", "=...
37.055556
0.010234
def get_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: ...
[ "def", "get_operation", "(", "self", ",", "name", ",", "retry", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ")", ":", "request", "=", "operations_pb2", ".", "GetOperationRequest", "(", "na...
45.589744
0.002203
def step_size(self, t0=None, t1=None): ''' Return the time in seconds of a step. If a begin and end timestamp, return the time in seconds between them after adjusting for what buckets they alias to. If t1 and t0 resolve to the same bucket, ''' if t0!=None and t1!=None: tb0 = self.to_bucket...
[ "def", "step_size", "(", "self", ",", "t0", "=", "None", ",", "t1", "=", "None", ")", ":", "if", "t0", "!=", "None", "and", "t1", "!=", "None", ":", "tb0", "=", "self", ".", "to_bucket", "(", "t0", ")", "tb1", "=", "self", ".", "to_bucket", "("...
39.769231
0.035917
def logarithmic_r(min_n, max_n, factor): """ Creates a list of values by successively multiplying a minimum value min_n by a factor > 1 until a maximum value max_n is reached. Args: min_n (float): minimum value (must be < max_n) max_n (float): maximum value (must be > min_n) factor (flo...
[ "def", "logarithmic_r", "(", "min_n", ",", "max_n", ",", "factor", ")", ":", "assert", "max_n", ">", "min_n", "assert", "factor", ">", "1", "max_i", "=", "int", "(", "np", ".", "floor", "(", "np", ".", "log", "(", "1.0", "*", "max_n", "/", "min_n",...
30.47619
0.009091
def encode(self, word): """Return the Standardized Phonetic Frequency Code (SPFC) of a word. Parameters ---------- word : str The word to transform Returns ------- str The SPFC value Raises ------ AttributeError ...
[ "def", "encode", "(", "self", ",", "word", ")", ":", "def", "_raise_word_ex", "(", ")", ":", "\"\"\"Raise an AttributeError.\n\n Raises\n ------\n AttributeError\n Word attribute must be a string with a space or period dividing\n ...
30.337143
0.000365
def __downloadPage(factory, *args, **kwargs): """Start a HTTP download, returning a HTTPDownloader object""" # The Twisted API is weird: # 1) web.client.downloadPage() doesn't give us the HTTP headers # 2) there is no method that simply accepts a URL and gives you back # a HTTPDownloader object ...
[ "def", "__downloadPage", "(", "factory", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# The Twisted API is weird:", "# 1) web.client.downloadPage() doesn't give us the HTTP headers", "# 2) there is no method that simply accepts a URL and gives you back", "# a HTTPDownload...
39.15
0.002494
def create_product(cls, product, **kwargs): """Create Product Create a new Product This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_product(product, async=True) >>> result = thre...
[ "def", "create_product", "(", "cls", ",", "product", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_create_product_with_http_info",...
38.809524
0.002395
def get_dict(self, timeout=-1): """Get the results as a dict, keyed by engine_id. timeout behavior is described in `get()`. """ results = self.get(timeout) engine_ids = [ md['engine_id'] for md in self._metadata ] bycount = sorted(engine_ids, key=lambda k: engine_ids.co...
[ "def", "get_dict", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "results", "=", "self", ".", "get", "(", "timeout", ")", "engine_ids", "=", "[", "md", "[", "'engine_id'", "]", "for", "md", "in", "self", ".", "_metadata", "]", "bycount", "=...
36.8
0.010601
def fetch_images(self, images, depth_level): """\ download the images to temp disk and set their dimensions - we're going to score the images in the order in which they appear so images higher up will have more importance, - we'll count the area of the 1st image as a score ...
[ "def", "fetch_images", "(", "self", ",", "images", ",", "depth_level", ")", ":", "image_results", "=", "{", "}", "initial_area", "=", "float", "(", "0.0", ")", "total_score", "=", "float", "(", "0.0", ")", "cnt", "=", "float", "(", "1.0", ")", "MIN_WID...
46.23913
0.001842
def extract_cluster_amount(self, radius): """! @brief Obtains amount of clustering that can be allocated by using specified radius for ordering diagram and borders between them. @details When growth of reachability-distances is detected than it is considered as a start point of cluster, ...
[ "def", "extract_cluster_amount", "(", "self", ",", "radius", ")", ":", "amount_clusters", "=", "1", "cluster_start", "=", "False", "cluster_pick", "=", "False", "total_similarity", "=", "True", "previous_cluster_distance", "=", "None", "previous_distance", "=", "Non...
42.9
0.010254
def cli(ctx, feature_id, attribute_key, attribute_value, organism="", sequence=""): """Delete an attribute from a feature Output: A standard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.delete_attribute(feature_id, attribute_key, attribute_value, organism=organism, s...
[ "def", "cli", "(", "ctx", ",", "feature_id", ",", "attribute_key", ",", "attribute_value", ",", "organism", "=", "\"\"", ",", "sequence", "=", "\"\"", ")", ":", "return", "ctx", ".", "gi", ".", "annotations", ".", "delete_attribute", "(", "feature_id", ","...
41.25
0.008902
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE): ''' Sign certificate with acme_tiny for let's encrypt ''' private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name) certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name) certificate_request_path = '{}/...
[ "def", "acme_sign_certificate", "(", "common_name", ",", "size", "=", "DEFAULT_KEY_SIZE", ")", ":", "private_key_path", "=", "'{}/{}.key'", ".", "format", "(", "CERTIFICATES_PATH", ",", "common_name", ")", "certificate_path", "=", "'{}/{}.crt'", ".", "format", "(", ...
39.75
0.001364
def error(title="", text="", width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, timeout=None): """ Display a simple error :param text: text inside the window :type text: str :param title: title of the window :type title: str :param width: window width :type width: int :param heig...
[ "def", "error", "(", "title", "=", "\"\"", ",", "text", "=", "\"\"", ",", "width", "=", "DEFAULT_WIDTH", ",", "height", "=", "DEFAULT_HEIGHT", ",", "timeout", "=", "None", ")", ":", "return", "_simple_dialog", "(", "Gtk", ".", "MessageType", ".", "ERROR"...
29.888889
0.001802
def createRandomObjects(self, numObjects, numPoints, numLocations=None, numFeatures=None): """ Creates a set of random objects and adds them to the machine. If numLocations and numFeatures and not specifi...
[ "def", "createRandomObjects", "(", "self", ",", "numObjects", ",", "numPoints", ",", "numLocations", "=", "None", ",", "numFeatures", "=", "None", ")", ":", "if", "numObjects", ">", "0", ":", "if", "numLocations", "is", "None", ":", "numLocations", "=", "n...
37.107143
0.012195
def get_manager_cmd(self): """Get our daemon script path.""" cmd = os.path.abspath(os.path.join(os.path.dirname(__file__), "server", "notebook_daemon.py")) assert os.path.exists(cmd) return cmd
[ "def", "get_manager_cmd", "(", "self", ")", ":", "cmd", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"server\"", ",", "\"notebook_daemon.py\"", ")", ...
44.2
0.013333
def addCutterTool(actor): """Create handles to cut away parts of a mesh. .. hint:: |cutter| |cutter.py|_ """ if isinstance(actor, vtk.vtkVolume): return _addVolumeCutterTool(actor) elif isinstance(actor, vtk.vtkImageData): from vtkplotter import Volume return _addVolumeCutte...
[ "def", "addCutterTool", "(", "actor", ")", ":", "if", "isinstance", "(", "actor", ",", "vtk", ".", "vtkVolume", ")", ":", "return", "_addVolumeCutterTool", "(", "actor", ")", "elif", "isinstance", "(", "actor", ",", "vtk", ".", "vtkImageData", ")", ":", ...
30.433735
0.000383
def _get_package_data(): """ Import a set of important packages and return relevant data about them in a dict. Imports are done in here to avoid potential for circular imports and other problems, and to make iteration simpler. """ moddata = [] modlist = ( "click", "config...
[ "def", "_get_package_data", "(", ")", ":", "moddata", "=", "[", "]", "modlist", "=", "(", "\"click\"", ",", "\"configobj\"", ",", "\"cryptography\"", ",", "\"globus_cli\"", ",", "\"globus_sdk\"", ",", "\"jmespath\"", ",", "\"requests\"", ",", "\"six\"", ",", "...
26.261905
0.000874
def compress(args): """ %prog compress a.agp b.agp Convert coordinates based on multiple AGP files. Useful to simplify multiple liftOvers to compress multiple chain files into a single chain file, in upgrading locations of genomic features. Example: `a.agp` could contain split scaffolds: ...
[ "def", "compress", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "compress", ".", "__doc__", ")", "p", ".", "set_outfile", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", ...
33.333333
0.002159
def probe_wdl(self, board: chess.Board) -> int: """ Probes for win/draw/loss-information. Returns ``1`` if the side to move is winning, ``0`` if it is a draw, and ``-1`` if the side to move is losing. >>> import chess >>> import chess.gaviota >>> >>> wit...
[ "def", "probe_wdl", "(", "self", ",", "board", ":", "chess", ".", "Board", ")", "->", "int", ":", "dtm", "=", "self", ".", "probe_dtm", "(", "board", ")", "if", "dtm", "==", "0", ":", "if", "board", ".", "is_checkmate", "(", ")", ":", "return", "...
31.647059
0.001803
def _to_narrow(self, terms, data, mask, dates, symbols): """ Convert raw computed pipeline results into a DataFrame for public APIs. Parameters ---------- terms : dict[str -> Term] Dict mapping column names to terms. data : dict[str -> ndarray[ndim=2]] ...
[ "def", "_to_narrow", "(", "self", ",", "terms", ",", "data", ",", "mask", ",", "dates", ",", "symbols", ")", ":", "assert", "len", "(", "dates", ")", "==", "1", "if", "not", "mask", ".", "any", "(", ")", ":", "# Manually handle the empty DataFrame case. ...
39.565217
0.000715
def sheet_asdict(fn, sheet=0, header=True, startcell=None, stopcell=None, usecols=None, chnames_out=None): """Read data from a spread sheet. Return the data in a dict with column numbers as keys. fn: str The file to read from. sheet: int or str If int, it is the index ...
[ "def", "sheet_asdict", "(", "fn", ",", "sheet", "=", "0", ",", "header", "=", "True", ",", "startcell", "=", "None", ",", "stopcell", "=", "None", ",", "usecols", "=", "None", ",", "chnames_out", "=", "None", ")", ":", "book", "=", "xlrd", ".", "op...
34.42623
0.000463
def getPosition(self): """See comments in base class.""" position = super(PermuteInt, self).getPosition() position = int(round(position)) return position
[ "def", "getPosition", "(", "self", ")", ":", "position", "=", "super", "(", "PermuteInt", ",", "self", ")", ".", "getPosition", "(", ")", "position", "=", "int", "(", "round", "(", "position", ")", ")", "return", "position" ]
33.2
0.011765
def database( state, host, name, present=True, owner=None, template=None, encoding=None, lc_collate=None, lc_ctype=None, tablespace=None, connection_limit=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postg...
[ "def", "database", "(", "state", ",", "host", ",", "name", ",", "present", "=", "True", ",", "owner", "=", "None", ",", "template", "=", "None", ",", "encoding", "=", "None", ",", "lc_collate", "=", "None", ",", "lc_ctype", "=", "None", ",", "tablesp...
32.774648
0.000417
def min(self): """Return the minimum of ``self``. See Also -------- numpy.amin max """ results = [x.ufuncs.min() for x in self.elem] return np.min(results)
[ "def", "min", "(", "self", ")", ":", "results", "=", "[", "x", ".", "ufuncs", ".", "min", "(", ")", "for", "x", "in", "self", ".", "elem", "]", "return", "np", ".", "min", "(", "results", ")" ]
21.1
0.009091
def remove(path, load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.remove \\ /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians path The path to remove .. versionadded:: 2016.3.0 load_path A colon-s...
[ "def", "remove", "(", "path", ",", "load_path", "=", "None", ")", ":", "load_path", "=", "_check_load_paths", "(", "load_path", ")", "aug", "=", "_Augeas", "(", "loadpath", "=", "load_path", ")", "ret", "=", "{", "'retval'", ":", "False", "}", "try", "...
22.894737
0.001103
def plotNLL_v_Flux(nll, fluxType, nstep=25, xlims=None): """ Plot the (negative) log-likelihood as a function of normalization nll : a LnLFN object nstep : Number of steps to plot xlims : x-axis limits, if None, take tem from the nll object returns fig,ax, which are matplotlib figure and axes o...
[ "def", "plotNLL_v_Flux", "(", "nll", ",", "fluxType", ",", "nstep", "=", "25", ",", "xlims", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "xlims", "is", "None", ":", "xmin", "=", "nll", ".", "interp", ".", "xmin", ...
24.594595
0.002114
def guggenheim_katayama(target, K2, n, temperature='pore.temperature', critical_temperature='pore.critical_temperature', critical_pressure='pore.critical_pressure'): r""" Missing description Parameters ---------- target : OpenPNM Object The ob...
[ "def", "guggenheim_katayama", "(", "target", ",", "K2", ",", "n", ",", "temperature", "=", "'pore.temperature'", ",", "critical_temperature", "=", "'pore.critical_temperature'", ",", "critical_pressure", "=", "'pore.critical_pressure'", ")", ":", "T", "=", "target", ...
30.457143
0.000909
def GetDeviceStringProperty(dev_ref, key): """Reads string property from the HID device.""" cf_key = CFStr(key) type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFStringGetTypeID(): raise errors.OsHidError('...
[ "def", "GetDeviceStringProperty", "(", "dev_ref", ",", "key", ")", ":", "cf_key", "=", "CFStr", "(", "key", ")", "type_ref", "=", "iokit", ".", "IOHIDDeviceGetProperty", "(", "dev_ref", ",", "cf_key", ")", "cf", ".", "CFRelease", "(", "cf_key", ")", "if", ...
34.95
0.018106
def run(url, output, config): """ Extracts database dump from given database URL and outputs sanitized copy of it into given stream. :param url: URL to the database which is to be sanitized. :type url: str :param output: Stream where sanitized copy of the database dump will be ...
[ "def", "run", "(", "url", ",", "output", ",", "config", ")", ":", "parsed_url", "=", "urlparse", ".", "urlparse", "(", "url", ")", "db_module_path", "=", "SUPPORTED_DATABASE_MODULES", ".", "get", "(", "parsed_url", ".", "scheme", ")", "if", "not", "db_modu...
39.291667
0.00207
def read(self, mode='r', *, buffering=-1, encoding=None, newline=None): ''' read data from the file. ''' with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp: return fp.read()
[ "def", "read", "(", "self", ",", "mode", "=", "'r'", ",", "*", ",", "buffering", "=", "-", "1", ",", "encoding", "=", "None", ",", "newline", "=", "None", ")", ":", "with", "self", ".", "open", "(", "mode", "=", "mode", ",", "buffering", "=", "...
59
0.012552
def validate_headers(spec, data): """Validates headers data and creates the config objects""" validated_data = { spec.VERSION: data[spec.VERSION], spec.KIND: data[spec.KIND], } if data.get(spec.LOGGING): validated_data[spec.LOGGING] = LoggingConfig.from_dict( data[sp...
[ "def", "validate_headers", "(", "spec", ",", "data", ")", ":", "validated_data", "=", "{", "spec", ".", "VERSION", ":", "data", "[", "spec", ".", "VERSION", "]", ",", "spec", ".", "KIND", ":", "data", "[", "spec", ".", "KIND", "]", ",", "}", "if", ...
29.315789
0.001739
def __getSequenceVariants(self, x1, polyStart, polyStop, listSequence) : """polyStop, is the polymorphisme at wixh number where the calcul of combinaisons stops""" if polyStart < len(self.polymorphisms) and polyStart < polyStop: sequence = copy.copy(listSequence) ret = [] pk = self.polymorphisms[polyS...
[ "def", "__getSequenceVariants", "(", "self", ",", "x1", ",", "polyStart", ",", "polyStop", ",", "listSequence", ")", ":", "if", "polyStart", "<", "len", "(", "self", ".", "polymorphisms", ")", "and", "polyStart", "<", "polyStop", ":", "sequence", "=", "cop...
36.6875
0.04485
def convert_lrn(node, **kwargs): """Map MXNet's LRN operator attributes to onnx's LRN operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) alpha = float(attrs.get("alpha", 0.0001)) beta = float(attrs.get("beta", 0.75)) bias = float(attrs.get("knorm",...
[ "def", "convert_lrn", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "alpha", "=", "float", "(", "attrs", ".", "get", "(", "\"alpha\"", ",", "0.0001", ")",...
24.782609
0.001689
def load_country_map_data(): """Loading data for map with country map""" csv_bytes = get_example_data( 'birth_france_data_for_country_map.csv', is_gzip=False, make_bytes=True) data = pd.read_csv(csv_bytes, encoding='utf-8') data['dttm'] = datetime.datetime.now().date() data.to_sql( # pylint...
[ "def", "load_country_map_data", "(", ")", ":", "csv_bytes", "=", "get_example_data", "(", "'birth_france_data_for_country_map.csv'", ",", "is_gzip", "=", "False", ",", "make_bytes", "=", "True", ")", "data", "=", "pd", ".", "read_csv", "(", "csv_bytes", ",", "en...
30.092105
0.00127
def release_readwrite_instance( cls, db_inst, block_number ): """ Release the read/write instance of the blockstack db. This must be called after borrow_readwrite_instance, with the same block number. After this method completes, it's possible to call borrow_readwrite_instance again. ...
[ "def", "release_readwrite_instance", "(", "cls", ",", "db_inst", ",", "block_number", ")", ":", "global", "blockstack_db", ",", "blockstack_db_lastblock", ",", "blockstack_db_lock", "blockstack_db_lock", ".", "acquire", "(", ")", "try", ":", "assert", "blockstack_db",...
33.5
0.009386
def validate_positive_float(option, value): """Validates that 'value' is a float, or can be converted to one, and is positive. """ errmsg = "%s must be an integer or float" % (option,) try: value = float(value) except ValueError: raise ValueError(errmsg) except TypeError: ...
[ "def", "validate_positive_float", "(", "option", ",", "value", ")", ":", "errmsg", "=", "\"%s must be an integer or float\"", "%", "(", "option", ",", ")", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError"...
36
0.001504
def run(self, ipyclient=None, ): """ Run a batch of dstat tests on a list of tests, where each test is a dictionary mapping sample names to {p1 - p4} (and sometimes p5). Parameters modifying the behavior of the run, such as the number of bootstrap replicates (n...
[ "def", "run", "(", "self", ",", "ipyclient", "=", "None", ",", ")", ":", "self", ".", "results_table", ",", "self", ".", "results_boots", "=", "batch", "(", "self", ",", "ipyclient", ")", "## skip this for 5-part test results", "if", "not", "isinstance", "("...
41.714286
0.008929
def _on_outcome(self, outcome, condition): """ Called when the outcome is received for a delivery. :param outcome: The outcome of the message delivery - success or failure. :type outcome: ~uamqp.constants.MessageSendResult """ self._outcome = outcome self._condit...
[ "def", "_on_outcome", "(", "self", ",", "outcome", ",", "condition", ")", ":", "self", ".", "_outcome", "=", "outcome", "self", ".", "_condition", "=", "condition" ]
36.333333
0.008955
def InterpolateKbAttributes(pattern, knowledge_base, ignore_errors=False): """Interpolate all knowledgebase attributes in pattern. Args: pattern: A string with potential interpolation markers. For example: "/home/%%users.username%%/Downloads/" knowledge_base: The knowledge_base to interpolate paramet...
[ "def", "InterpolateKbAttributes", "(", "pattern", ",", "knowledge_base", ",", "ignore_errors", "=", "False", ")", ":", "# TODO(hanuszczak): Control flow feels a bit awkward here because of error", "# handling that tries not to break any functionality. With the new utilities", "# it shoul...
30
0.010758
def apply_template_to_network(template_id, network_id, **kwargs): """ For each node and link in a network, check whether it matches a type in a given template. If so, assign the type to the node / link. """ net_i = db.DBSession.query(Network).filter(Network.id==network_id).one() #There ...
[ "def", "apply_template_to_network", "(", "template_id", ",", "network_id", ",", "*", "*", "kwargs", ")", ":", "net_i", "=", "db", ".", "DBSession", ".", "query", "(", "Network", ")", ".", "filter", "(", "Network", ".", "id", "==", "network_id", ")", ".",...
45
0.011557
def pixel(self, func:PixelFunc, *args, **kwargs)->'ImagePoints': "Equivalent to `self = func_flow(self)`." self = func(self, *args, **kwargs) self.transformed=True return self
[ "def", "pixel", "(", "self", ",", "func", ":", "PixelFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'ImagePoints'", ":", "self", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "transformed", ...
40.6
0.024155
def updateSpec(self, *args, **kwargs): """Updates the spectrogram. First argument can be a filename, or a data array. If no arguments are given, clears the spectrograms. For other arguments, see: :meth:`SpecWidget.updateData<sparkle.gui.plotting.pyqtgraph_widgets.SpecWidget.updateData>` ...
[ "def", "updateSpec", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "[", "0", "]", "is", "None", ":", "self", ".", "specPlot", ".", "clearImg", "(", ")", "elif", "isinstance", "(", "args", "[", "0", "]", ",", "b...
45.333333
0.009009
def _modelmat(self, X, term=-1): """ Builds a model matrix, B, out of the spline basis for each feature B = [B_0, B_1, ..., B_p] Parameters --------- X : array-like of shape (n_samples, m_features) containing the input dataset term : int, optional ...
[ "def", "_modelmat", "(", "self", ",", "X", ",", "term", "=", "-", "1", ")", ":", "X", "=", "check_X", "(", "X", ",", "n_feats", "=", "self", ".", "statistics_", "[", "'m_features'", "]", ",", "edge_knots", "=", "self", ".", "edge_knots_", ",", "dty...
35.166667
0.002307
def all_partitions(mechanism, purview, node_labels=None): """Return all possible partitions of a mechanism and purview. Partitions can consist of any number of parts. Args: mechanism (tuple[int]): A mechanism. purview (tuple[int]): A purview. Yields: KPartition: A partition of...
[ "def", "all_partitions", "(", "mechanism", ",", "purview", ",", "node_labels", "=", "None", ")", ":", "for", "mechanism_partition", "in", "partitions", "(", "mechanism", ")", ":", "mechanism_partition", ".", "append", "(", "[", "]", ")", "n_mechanism_parts", "...
42.780488
0.000557
def wait(self, num_slaves, timeout=0): """his command blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of slaves. If the timeout, specified in milliseconds, is reached, the command returns even ...
[ "def", "wait", "(", "self", ",", "num_slaves", ",", "timeout", "=", "0", ")", ":", "command", "=", "[", "b'WAIT'", ",", "ascii", "(", "num_slaves", ")", ".", "encode", "(", "'ascii'", ")", ",", "ascii", "(", "timeout", ")", ".", "encode", "(", "'as...
39.071429
0.001784
def _plt_handle_figure(plot): r"""Handle the common work (creating an axis if not given, setting the title) of all matplotlib plot commands.""" # Preserve documentation of plot. @functools.wraps(plot) def inner(obj, **kwargs): # Create a figure and an axis if none were passed. if ...
[ "def", "_plt_handle_figure", "(", "plot", ")", ":", "# Preserve documentation of plot.", "@", "functools", ".", "wraps", "(", "plot", ")", "def", "inner", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "# Create a figure and an axis if none were passed.", "if", "k...
27.405405
0.001905
def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): """Create a GridIn property.""" def getter(self): if closed_only and not self._closed: raise AttributeError("can only get %r on a closed file" % field_name...
[ "def", "_grid_in_property", "(", "field_name", ",", "docstring", ",", "read_only", "=", "False", ",", "closed_only", "=", "False", ")", ":", "def", "getter", "(", "self", ")", ":", "if", "closed_only", "and", "not", "self", ".", "_closed", ":", "raise", ...
40.678571
0.000858
def create_pool(batch_service_client, pool_id, resource_files, publisher, offer, sku, task_file, vm_size, node_count): """Creates a pool of compute nodes with the specified OS settings. :param batch_service_client: A Batch service client. :type batch_service_client: `azure.b...
[ "def", "create_pool", "(", "batch_service_client", ",", "pool_id", ",", "resource_files", ",", "publisher", ",", "offer", ",", "sku", ",", "task_file", ",", "vm_size", ",", "node_count", ")", ":", "_log", ".", "info", "(", "'Creating pool [{}]...'", ".", "form...
47.805556
0.000854
def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: # changed for v1.5, see below self.fall = True return True else: return False
[ "def", "match", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "fall", "or", "not", "args", ":", "return", "True", "elif", "self", ".", "value", "in", "args", ":", "# changed for v1.5, see below", "self", ".", "fall", "=", "True", "return"...
32
0.010135
def proximal_gradient(x, f, g, gamma, niter, callback=None, **kwargs): r"""(Accelerated) proximal gradient algorithm for convex optimization. Also known as "Iterative Soft-Thresholding Algorithm" (ISTA). See `[Beck2009]`_ for more information. This solver solves the convex optimization problem:: ...
[ "def", "proximal_gradient", "(", "x", ",", "f", ",", "g", ",", "gamma", ",", "niter", ",", "callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Get and validate input", "if", "x", "not", "in", "f", ".", "domain", ":", "raise", "TypeError", ...
29.71
0.000326
def idcode(msg): """Computes identity (squawk code) from DF5 or DF21 message, bit 20-32. credit: @fbyrkjeland Args: msg (String): 28 bytes hexadecimal message string Returns: string: squawk code """ if df(msg) not in [5, 21]: raise RuntimeError("Message must be Downlin...
[ "def", "idcode", "(", "msg", ")", ":", "if", "df", "(", "msg", ")", "not", "in", "[", "5", ",", "21", "]", ":", "raise", "RuntimeError", "(", "\"Message must be Downlink Format 5 or 21.\"", ")", "mbin", "=", "hex2bin", "(", "msg", ")", "C1", "=", "mbin...
20.666667
0.001284
def client_setname(self, name): """Set the current connection name.""" fut = self.execute(b'CLIENT', b'SETNAME', name) return wait_ok(fut)
[ "def", "client_setname", "(", "self", ",", "name", ")", ":", "fut", "=", "self", ".", "execute", "(", "b'CLIENT'", ",", "b'SETNAME'", ",", "name", ")", "return", "wait_ok", "(", "fut", ")" ]
39.75
0.012346
def generate_dataset_shelve(filename, number_items=1000): """ Generate a dataset with number_items elements. """ if os.path.exists(filename): os.remove(filename) data = shelve.open(filename) names = get_names() totalnames = len(names) #init random seeder random.seed() #ca...
[ "def", "generate_dataset_shelve", "(", "filename", ",", "number_items", "=", "1000", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "os", ".", "remove", "(", "filename", ")", "data", "=", "shelve", ".", "open", "(", "filen...
32.944444
0.016393
def set_primary_ip(self, name, vrid, value=None, disable=False, default=False, run=True): """Set the primary_ip property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. va...
[ "def", "set_primary_ip", "(", "self", ",", "name", ",", "vrid", ",", "value", "=", "None", ",", "disable", "=", "False", ",", "default", "=", "False", ",", "run", "=", "True", ")", ":", "if", "default", "is", "True", ":", "vrrps", "=", "self", ".",...
38.282609
0.001661
def activated(self, item): """Double-click event""" data = self.data.get(id(item)) if data is not None: fname, lineno = data self.sig_edit_goto.emit(fname, lineno, '')
[ "def", "activated", "(", "self", ",", "item", ")", ":", "data", "=", "self", ".", "data", ".", "get", "(", "id", "(", "item", ")", ")", "if", "data", "is", "not", "None", ":", "fname", ",", "lineno", "=", "data", "self", ".", "sig_edit_goto", "."...
35.833333
0.009091
def close_socket(self): """close socket""" self._socket_lock.acquire() self._force_close_session() self._socket_lock.release()
[ "def", "close_socket", "(", "self", ")", ":", "self", ".", "_socket_lock", ".", "acquire", "(", ")", "self", ".", "_force_close_session", "(", ")", "self", ".", "_socket_lock", ".", "release", "(", ")" ]
30.8
0.012658
def coerce_nc3_dtype(arr): """Coerce an array to a data type that can be stored in a netCDF-3 file This function performs the following dtype conversions: int64 -> int32 bool -> int8 Data is checked for equality, or equivalence (non-NaN values) with `np.allclose` with the default keywo...
[ "def", "coerce_nc3_dtype", "(", "arr", ")", ":", "dtype", "=", "str", "(", "arr", ".", "dtype", ")", "if", "dtype", "in", "_nc3_dtype_coercions", ":", "new_dtype", "=", "_nc3_dtype_coercions", "[", "dtype", "]", "# TODO: raise a warning whenever casting the data-typ...
37.8
0.00129
def update_entitlement(owner, repo, identifier, name, token, show_tokens): """Update an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception...
[ "def", "update_entitlement", "(", "owner", ",", "repo", ",", "identifier", ",", "name", ",", "token", ",", "show_tokens", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "data", "=", "{", "}", "if", "name", "is", "not", "None", ":", "data", ...
27.681818
0.001587
def execute(self, commands, encoding='json', **kwargs): """Executes the list of commands on the destination node This method takes a list of commands and sends them to the destination node, returning the results. The execute method handles putting the destination node in enable mode an...
[ "def", "execute", "(", "self", ",", "commands", ",", "encoding", "=", "'json'", ",", "*", "*", "kwargs", ")", ":", "if", "encoding", "not", "in", "(", "'json'", ",", "'text'", ")", ":", "raise", "TypeError", "(", "'encoding must be one of [json, text]'", "...
42.075
0.001161
def bind(self): """Bind and activate HTTP server.""" HTTPServer.__init__(self, (self.host, self.port), HTTPRequestHandler) self.port = self.server_port
[ "def", "bind", "(", "self", ")", ":", "HTTPServer", ".", "__init__", "(", "self", ",", "(", "self", ".", "host", ",", "self", ".", "port", ")", ",", "HTTPRequestHandler", ")", "self", ".", "port", "=", "self", ".", "server_port" ]
34.4
0.011364
def mtr_lm_dense(sz): """Series of architectures for language modeling. We assume infinite training data, so no dropout necessary. You can use languagemodel_wiki_noref_v32k_l1k. (1 epoch = ~46000 steps). TODO(noam): find a large enough dataset for these experiments. Args: sz: an integer Returns: ...
[ "def", "mtr_lm_dense", "(", "sz", ")", ":", "n", "=", "2", "**", "sz", "hparams", "=", "mtf_unitransformer_base", "(", ")", "hparams", ".", "d_model", "=", "1024", "hparams", ".", "max_length", "=", "1024", "hparams", ".", "batch_size", "=", "128", "# Pa...
25.793103
0.020619
def silent_execute(self, code): """Execute code in the kernel without increasing the prompt""" try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
[ "def", "silent_execute", "(", "self", ",", "code", ")", ":", "try", ":", "self", ".", "kernel_client", ".", "execute", "(", "to_text_string", "(", "code", ")", ",", "silent", "=", "True", ")", "except", "AttributeError", ":", "pass" ]
38.666667
0.008439
def _read_txt(path): """Read a txt crashfile >>> new_path = Path(__file__).resolve().parent.parent >>> test_data_path = new_path / 'data' / 'tests' >>> info = _read_txt(test_data_path / 'crashfile.txt') >>> info['node'] # doctest: +ELLIPSIS '...func_preproc_task_machinegame_run_02_wf.carpetplo...
[ "def", "_read_txt", "(", "path", ")", ":", "from", "pathlib", "import", "Path", "lines", "=", "Path", "(", "path", ")", ".", "read_text", "(", ")", ".", "splitlines", "(", ")", "data", "=", "{", "'file'", ":", "str", "(", "path", ")", "}", "traceba...
32.5
0.001358
def clear_tags(self) -> dict: """ Accessor for record tags (metadata) stored in the clear. :return: record tags stored in the clear """ return {t: self.tags[t] for t in (self.tags or {}) if t.startswith('~')} or None
[ "def", "clear_tags", "(", "self", ")", "->", "dict", ":", "return", "{", "t", ":", "self", ".", "tags", "[", "t", "]", "for", "t", "in", "(", "self", ".", "tags", "or", "{", "}", ")", "if", "t", ".", "startswith", "(", "'~'", ")", "}", "or", ...
31.375
0.011628
def get_md5_from_metadata(ase): # type: (blobxfer.models.azure.StorageEntity) -> str """Get MD5 from properties or metadata :param blobxfer.models.azure.StorageEntity ase: Azure Storage Entity :rtype: str or None :return: md5 """ # if encryption metadata is present, check for pre-encryption ...
[ "def", "get_md5_from_metadata", "(", "ase", ")", ":", "# type: (blobxfer.models.azure.StorageEntity) -> str", "# if encryption metadata is present, check for pre-encryption", "# md5 in blobxfer extensions", "md5", "=", "None", "if", "ase", ".", "is_encrypted", ":", "try", ":", ...
34.4
0.001414
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, defaul...
[ "def", "query", "(", "method", "=", "'droplets'", ",", "droplet_id", "=", "None", ",", "command", "=", "None", ",", "args", "=", "None", ",", "http_method", "=", "'get'", ")", ":", "base_path", "=", "six", ".", "text_type", "(", "config", ".", "get_clo...
27.910714
0.002472
def generate(env): """Add Builders and construction variables for applelink to an Environment.""" link.generate(env) env['FRAMEWORKPATHPREFIX'] = '-F' env['_FRAMEWORKPATH'] = '${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, "", __env__)}' env['_FRAMEWORKS'] = '${_concat("-framework ", FRAMEWORKS,...
[ "def", "generate", "(", "env", ")", ":", "link", ".", "generate", "(", "env", ")", "env", "[", "'FRAMEWORKPATHPREFIX'", "]", "=", "'-F'", "env", "[", "'_FRAMEWORKPATH'", "]", "=", "'${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, \"\", __env__)}'", "env", "[", "'_FR...
51.296296
0.009922
def parse(contents, tokens=None): """Parse a string called contents for an AST and return it.""" # Shortcut for users who are interested in tokens if tokens is None: tokens = [t for t in tokenize(contents)] token_index, body = _ast_worker(tokens, len(tokens), 0, None) assert token_index ==...
[ "def", "parse", "(", "contents", ",", "tokens", "=", "None", ")", ":", "# Shortcut for users who are interested in tokens", "if", "tokens", "is", "None", ":", "tokens", "=", "[", "t", "for", "t", "in", "tokenize", "(", "contents", ")", "]", "token_index", ",...
33.833333
0.002398
def get_contrasts(self, names=None, variables=None, **kwargs): ''' Return contrast information for the current block. Args: names (list): Optional list of names of contrasts to return. If None (default), all contrasts are returned. variables (bool): Optional list...
[ "def", "get_contrasts", "(", "self", ",", "names", "=", "None", ",", "variables", "=", "None", ",", "*", "*", "kwargs", ")", ":", "nodes", ",", "kwargs", "=", "self", ".", "_filter_objects", "(", "self", ".", "output_nodes", ",", "kwargs", ")", "return...
49.73913
0.001715
def layer_definition_type(layer): """Returned relevant layer definition based on layer purpose. Returned the the correct definition of layer based on its purpose. For example, if a layer have layer_purpose: exposure, and exposure: roads then it will return definition for exposure_roads. That's why...
[ "def", "layer_definition_type", "(", "layer", ")", ":", "layer_purposes", "=", "[", "'exposure'", ",", "'hazard'", "]", "layer_purpose", "=", "[", "p", "for", "p", "in", "layer_purposes", "if", "p", "in", "layer", ".", "keywords", "]", "if", "not", "layer_...
28.703704
0.001248
def row_structural_typicality(X_L_list, X_D_list, row_id): """Returns how typical the row is (opposite of how anomalous).""" count = 0 assert len(X_L_list) == len(X_D_list) for X_L, X_D in zip(X_L_list, X_D_list): for r in range(len(X_D[0])): for c in range( len(X...
[ "def", "row_structural_typicality", "(", "X_L_list", ",", "X_D_list", ",", "row_id", ")", ":", "count", "=", "0", "assert", "len", "(", "X_L_list", ")", "==", "len", "(", "X_D_list", ")", "for", "X_L", ",", "X_D", "in", "zip", "(", "X_L_list", ",", "X_...
47.428571
0.001477
def generate_slug(text, tail_number=0): from wagtail.core.models import Page """ Returns a new unique slug. Object must provide a SlugField called slug. URL friendly slugs are generated using django.template.defaultfilters' slugify. Numbers are added to the end of slugs for uniqueness. based on...
[ "def", "generate_slug", "(", "text", ",", "tail_number", "=", "0", ")", ":", "from", "wagtail", ".", "core", ".", "models", "import", "Page", "# Empty slugs are ugly (eg. '-1' may be generated) so force non-empty", "if", "not", "text", ":", "text", "=", "'no-title'"...
28.744186
0.000782
def f0Morph(fromWavFN, pitchPath, stepList, outputName, doPlotPitchSteps, fromPitchData, toPitchData, outputMinPitch, outputMaxPitch, praatEXE, keepPitchRange=False, keepAveragePitch=False, sourcePitchDataList=None, minIntervalLength=0.3): ''' Resynthesizes the pi...
[ "def", "f0Morph", "(", "fromWavFN", ",", "pitchPath", ",", "stepList", ",", "outputName", ",", "doPlotPitchSteps", ",", "fromPitchData", ",", "toPitchData", ",", "outputMinPitch", ",", "outputMaxPitch", ",", "praatEXE", ",", "keepPitchRange", "=", "False", ",", ...
42.972973
0.002254
def generate_public_and_private(): """ <Purpose> Generate a pair of ed25519 public and private keys with PyNaCl. The public and private keys returned conform to 'securesystemslib.formats.ED25519PULIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the form: ...
[ "def", "generate_public_and_private", "(", ")", ":", "# Generate ed25519's seed key by calling os.urandom(). The random bytes", "# returned should be suitable for cryptographic use and is OS-specific.", "# Raise 'NotImplementedError' if a randomness source is not found.", "# ed25519 seed keys are f...
33.915254
0.008742
def add(self, name, mech, usage='both', init_lifetime=None, accept_lifetime=None, impersonator=None, store=None): """Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mecha...
[ "def", "add", "(", "self", ",", "name", ",", "mech", ",", "usage", "=", "'both'", ",", "init_lifetime", "=", "None", ",", "accept_lifetime", "=", "None", ",", "impersonator", "=", "None", ",", "store", "=", "None", ")", ":", "if", "store", "is", "not...
45.642857
0.001021