text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def unregisterFilter(self, column): """Unregister filter on a column of the table. @param column: The column header. """ if self._filters.has_key(column): del self._filters[column]
[ "def", "unregisterFilter", "(", "self", ",", "column", ")", ":", "if", "self", ".", "_filters", ".", "has_key", "(", "column", ")", ":", "del", "self", ".", "_filters", "[", "column", "]" ]
29.375
0.020661
def visual_isolines(hemi, retinotopy='any', visual_area=Ellipsis, mask=None, surface='midgray', weights=Ellipsis, min_weight=0.05, eccentricity_range=None, polar_angle_range=None, eccentricity_lines=8, polar_angle_lines=8, max_step_scale=1....
[ "def", "visual_isolines", "(", "hemi", ",", "retinotopy", "=", "'any'", ",", "visual_area", "=", "Ellipsis", ",", "mask", "=", "None", ",", "surface", "=", "'midgray'", ",", "weights", "=", "Ellipsis", ",", "min_weight", "=", "0.05", ",", "eccentricity_range...
59.970803
0.011255
def _kmp_find(self, needle, haystack, lst = None): """find with KMP-searching. needle is an integer array, reprensenting a pattern. haystack is an integer array, reprensenting the input sequence. if lst is None, return the first position found or -1 if no match found. If it's a list, will return a list of all positio...
[ "def", "_kmp_find", "(", "self", ",", "needle", ",", "haystack", ",", "lst", "=", "None", ")", ":", "if", "lst", "!=", "None", ":", "return", "self", ".", "_kmp_search_all", "(", "haystack", ",", "needle", ")", "else", ":", "return", "self", ".", "_k...
128.5
0.019342
def draw_graph( g, fmt='svg', prg='dot', options={} ): """ Draw an RDF graph as an image """ # Convert RDF to Graphviz buf = StringIO() rdf2dot( g, buf, options ) gv_options = options.get('graphviz',[]) if fmt == 'png': gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ] meta...
[ "def", "draw_graph", "(", "g", ",", "fmt", "=", "'svg'", ",", "prg", "=", "'dot'", ",", "options", "=", "{", "}", ")", ":", "# Convert RDF to Graphviz", "buf", "=", "StringIO", "(", ")", "rdf2dot", "(", "g", ",", "buf", ",", "options", ")", "gv_optio...
33.9
0.030593
def create_upload(self, project_id, path_data, hash_data, remote_filename=None, storage_provider_id=None): """ Create a chunked upload id to pass to create_file_chunk_url to create upload urls. :param project_id: str: uuid of the project :param path_data: PathData: holds file system data...
[ "def", "create_upload", "(", "self", ",", "project_id", ",", "path_data", ",", "hash_data", ",", "remote_filename", "=", "None", ",", "storage_provider_id", "=", "None", ")", ":", "upload_response", "=", "self", ".", "_create_upload", "(", "project_id", ",", "...
70.846154
0.009646
def _hangul_char_to_jamo(syllable): """Return a 3-tuple of lead, vowel, and tail jamo characters. Note: Non-Hangul characters are echoed back. """ if is_hangul_char(syllable): rem = ord(syllable) - _JAMO_OFFSET tail = rem % 28 vowel = 1 + ((rem - tail) % 588) // 28 lead =...
[ "def", "_hangul_char_to_jamo", "(", "syllable", ")", ":", "if", "is_hangul_char", "(", "syllable", ")", ":", "rem", "=", "ord", "(", "syllable", ")", "-", "_JAMO_OFFSET", "tail", "=", "rem", "%", "28", "vowel", "=", "1", "+", "(", "(", "rem", "-", "t...
35.666667
0.001517
def E(poly, dist=None, **kws): """ Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Defines the space the expected v...
[ "def", "E", "(", "poly", ",", "dist", "=", "None", ",", "*", "*", "kws", ")", ":", "if", "not", "isinstance", "(", "poly", ",", "(", "distributions", ".", "Dist", ",", "polynomials", ".", "Poly", ")", ")", ":", "print", "(", "type", "(", "poly", ...
27.634921
0.000555
def setup_logging(config_path=None, log_level=logging.INFO, formatter='standard'): """Setup logging configuration """ config = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': ...
[ "def", "setup_logging", "(", "config_path", "=", "None", ",", "log_level", "=", "logging", ".", "INFO", ",", "formatter", "=", "'standard'", ")", ":", "config", "=", "{", "'version'", ":", "1", ",", "'disable_existing_loggers'", ":", "False", ",", "'formatte...
27.791667
0.000724
def ipoib_interfaces(): """Return a list of IPOIB capable ethernet interfaces""" interfaces = [] for interface in network_interfaces(): try: driver = re.search('^driver: (.+)$', subprocess.check_output([ 'ethtool', '-i', interface]), re.M).group(1) ...
[ "def", "ipoib_interfaces", "(", ")", ":", "interfaces", "=", "[", "]", "for", "interface", "in", "network_interfaces", "(", ")", ":", "try", ":", "driver", "=", "re", ".", "search", "(", "'^driver: (.+)$'", ",", "subprocess", ".", "check_output", "(", "[",...
30.470588
0.001873
def rate_slack(self, max_rate): """ The maximum time interval that can be stolen to this fragment while keeping it respecting the given max rate. For ``REGULAR`` fragments this value is the opposite of the ``rate_lack``. For ``NONSPEECH`` fragments this value is equal to...
[ "def", "rate_slack", "(", "self", ",", "max_rate", ")", ":", "if", "self", ".", "fragment_type", "==", "self", ".", "REGULAR", ":", "return", "-", "self", ".", "rate_lack", "(", "max_rate", ")", "elif", "self", ".", "fragment_type", "==", "self", ".", ...
37.375
0.002174
def get_user_client(user_or_contact): """Returns the client of the contact of a Plone user If the user passed in has no contact or does not belong to any client, returns None. :param: Plone user or contact :returns: Client the contact of the Plone user belongs to """ if not user_or_contact...
[ "def", "get_user_client", "(", "user_or_contact", ")", ":", "if", "not", "user_or_contact", "or", "ILabContact", ".", "providedBy", "(", "user_or_contact", ")", ":", "# Lab contacts cannot belong to a client", "return", "None", "if", "not", "IContact", ".", "providedB...
32.125
0.001259
def parse_property(parser, event, node): #pylint: disable=unused-argument """Parse CIM/XML PROPERTY Element and return CIMProperty""" name = _get_required_attribute(node, 'NAME') cim_type = _get_required_attribute(node, 'TYPE') class_origin = _get_attribute(node, 'CLASSORIGIN') propagated = _get_a...
[ "def", "parse_property", "(", "parser", ",", "event", ",", "node", ")", ":", "#pylint: disable=unused-argument", "name", "=", "_get_required_attribute", "(", "node", ",", "'NAME'", ")", "cim_type", "=", "_get_required_attribute", "(", "node", ",", "'TYPE'", ")", ...
30.565217
0.002068
def center(self, X): """ Center `X` in PCA space. """ X = X.copy() inan = numpy.isnan(X) if self.mu is None: X_ = numpy.ma.masked_array(X, inan) self.mu = X_.mean(0).base self.sigma = X_.std(0).base reduce(lambda y,x: setitem(x[...
[ "def", "center", "(", "self", ",", "X", ")", ":", "X", "=", "X", ".", "copy", "(", ")", "inan", "=", "numpy", ".", "isnan", "(", "X", ")", "if", "self", ".", "mu", "is", "None", ":", "X_", "=", "numpy", ".", "ma", ".", "masked_array", "(", ...
32.928571
0.008439
def build_sensors_list(self, type): """Build the sensors list depending of the type. type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT output: a list """ ret = [] if type == SENSOR_TEMP_UNIT and self.init_temp: input_list = self.stemps self.stemps = psut...
[ "def", "build_sensors_list", "(", "self", ",", "type", ")", ":", "ret", "=", "[", "]", "if", "type", "==", "SENSOR_TEMP_UNIT", "and", "self", ".", "init_temp", ":", "input_list", "=", "self", ".", "stemps", "self", ".", "stemps", "=", "psutil", ".", "s...
35.3125
0.001723
def show_instances(server, cim_class): """ Display the instances of the CIM_Class defined by cim_class. If the namespace is None, use the interop namespace. Search all namespaces for instances except for CIM_RegisteredProfile """ if cim_class == 'CIM_RegisteredProfile': for inst in serve...
[ "def", "show_instances", "(", "server", ",", "cim_class", ")", ":", "if", "cim_class", "==", "'CIM_RegisteredProfile'", ":", "for", "inst", "in", "server", ".", "profiles", ":", "print", "(", "inst", ".", "tomof", "(", ")", ")", "return", "for", "ns", "i...
39.347826
0.001079
def _auto_scroll(self, *args): """ Scroll to the end of the text view """ adj = self['scrollable'].get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size())
[ "def", "_auto_scroll", "(", "self", ",", "*", "args", ")", ":", "adj", "=", "self", "[", "'scrollable'", "]", ".", "get_vadjustment", "(", ")", "adj", ".", "set_value", "(", "adj", ".", "get_upper", "(", ")", "-", "adj", ".", "get_page_size", "(", ")...
47.5
0.010363
def get_file(self,pattern): ''' returns a flag array of the data loaded from a given file pattern :parameter pattern: pattern to match in the file list. ''' flag=[fnmatch.fnmatch(l,pattern) for l in self.filelist] id=self.fid_list.compress(flag) ...
[ "def", "get_file", "(", "self", ",", "pattern", ")", ":", "flag", "=", "[", "fnmatch", ".", "fnmatch", "(", "l", ",", "pattern", ")", "for", "l", "in", "self", ".", "filelist", "]", "id", "=", "self", ".", "fid_list", ".", "compress", "(", "flag", ...
35.6
0.024658
def undelete_alert(self, id, **kwargs): # noqa: E501 """Undelete a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.undelete_alert(id, async_req...
[ "def", "undelete_alert", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "undelete_aler...
40.333333
0.002307
def _createDatabase( self ): """Private method to create the SQLite database file.""" # create experiment metadata table command = """ CREATE TABLE {tn} ( {k} INT PRIMARY KEY NOT NULL, START_TIME INT NOT NULL, ...
[ "def", "_createDatabase", "(", "self", ")", ":", "# create experiment metadata table", "command", "=", "\"\"\"\n CREATE TABLE {tn} (\n {k} INT PRIMARY KEY NOT NULL,\n START_TIME INT NOT NULL,\n END_TIM...
44.9
0.010905
def parse_samblaster(self, f): """ Go through log file looking for samblaster output. If the Grab the name from the RG tag of the preceding bwa command """ dups_regex = "samblaster: (Removed|Marked) (\d+) of (\d+) \((\d+.\d+)%\) read ids as duplicates" input_file_regex = "samblas...
[ "def", "parse_samblaster", "(", "self", ",", "f", ")", ":", "dups_regex", "=", "\"samblaster: (Removed|Marked) (\\d+) of (\\d+) \\((\\d+.\\d+)%\\) read ids as duplicates\"", "input_file_regex", "=", "\"samblaster: Opening (\\S+) for read.\"", "rgtag_name_regex", "=", "\"\\\\\\\\tID:(...
44.195122
0.008639
def parallel_starfeatures_lcdir(lcdir, outdir, lc_catalog_pickle, neighbor_radius_arcsec, fileglob=None, maxobjects=None, deredd...
[ "def", "parallel_starfeatures_lcdir", "(", "lcdir", ",", "outdir", ",", "lc_catalog_pickle", ",", "neighbor_radius_arcsec", ",", "fileglob", "=", "None", ",", "maxobjects", "=", "None", ",", "deredden", "=", "True", ",", "custom_bandpasses", "=", "None", ",", "l...
38.561321
0.001312
def attachfile(self, idlist, attachfile, description, **kwargs): """ Attach a file to the given bug IDs. Returns the ID of the attachment or raises XMLRPC Fault if something goes wrong. attachfile may be a filename (which will be opened) or a file-like object, which must provide...
[ "def", "attachfile", "(", "self", ",", "idlist", ",", "attachfile", ",", "description", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "attachfile", ",", "str", ")", ":", "f", "=", "open", "(", "attachfile", ",", "\"rb\"", ")", "elif", "...
41.643836
0.000643
def copy(self, memo=None, which=None): """ Returns a (deep) copy of the current parameter handle. All connections to parents of the copy will be cut. :param dict memo: memo for deepcopy :param Parameterized which: parameterized object which started the copy process [default: se...
[ "def", "copy", "(", "self", ",", "memo", "=", "None", ",", "which", "=", "None", ")", ":", "#raise NotImplementedError, \"Copy is not yet implemented, TODO: Observable hierarchy\"", "if", "memo", "is", "None", ":", "memo", "=", "{", "}", "import", "copy", "# the n...
46.115385
0.017157
def run(macro, output_files=[], force_close=True): """ Runs Fiji with the suplied macro. Output of Fiji can be viewed by setting environment variable `DEBUG=fijibin`. Parameters ---------- macro : string or list of strings IJM-macro(s) to run. If list of strings, it will be joined with ...
[ "def", "run", "(", "macro", ",", "output_files", "=", "[", "]", ",", "force_close", "=", "True", ")", ":", "if", "type", "(", "macro", ")", "==", "list", ":", "macro", "=", "' '", ".", "join", "(", "macro", ")", "if", "len", "(", "macro", ")", ...
36.804878
0.000968
def _multitaper_spectrum(self, clm, k, convention='power', unit='per_l', lmax=None, taper_wt=None): """ Return the multitaper spectrum estimate and standard error for an input SHCoeffs class instance. """ if lmax is None: lmax = clm.lmax ...
[ "def", "_multitaper_spectrum", "(", "self", ",", "clm", ",", "k", ",", "convention", "=", "'power'", ",", "unit", "=", "'per_l'", ",", "lmax", "=", "None", ",", "taper_wt", "=", "None", ")", ":", "if", "lmax", "is", "None", ":", "lmax", "=", "clm", ...
37.378378
0.002114
def browserfamilies(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the browsers used to open links in your emails. This is only recorded when Link Tracking is enabled for that email. """ return self.call("GET", "/stats/outbound/clicks/browserfamilies", tag=t...
[ "def", "browserfamilies", "(", "self", ",", "tag", "=", "None", ",", "fromdate", "=", "None", ",", "todate", "=", "None", ")", ":", "return", "self", ".", "call", "(", "\"GET\"", ",", "\"/stats/outbound/clicks/browserfamilies\"", ",", "tag", "=", "tag", ",...
58.666667
0.008403
def human_readable_number(number, suffix=""): """ Format the given number into a human-readable string. Code adapted from http://stackoverflow.com/a/1094933 :param variant number: the number (int or float) :param string suffix: the unit of the number :rtype: string """ for unit in ["",...
[ "def", "human_readable_number", "(", "number", ",", "suffix", "=", "\"\"", ")", ":", "for", "unit", "in", "[", "\"\"", ",", "\"K\"", ",", "\"M\"", ",", "\"G\"", ",", "\"T\"", ",", "\"P\"", ",", "\"E\"", ",", "\"Z\"", "]", ":", "if", "abs", "(", "nu...
33.466667
0.001938
def address_(): ''' Get the many addresses of the Bluetooth adapter CLI Example: .. code-block:: bash salt '*' bluetooth.address ''' ret = {} cmd = 'hciconfig' out = __salt__['cmd.run'](cmd).splitlines() dev = '' for line in out: if line.startswith('hci'): ...
[ "def", "address_", "(", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'hciconfig'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ".", "splitlines", "(", ")", "dev", "=", "''", "for", "line", "in", "out", ":", "if", "line", ".", ...
24.733333
0.001297
def change_port_speed(self, hardware_id, public, speed): """Allows you to change the port speed of a server's NICs. :param int hardware_id: The ID of the server :param bool public: Flag to indicate which interface to change. True (default) means the public interface....
[ "def", "change_port_speed", "(", "self", ",", "hardware_id", ",", "public", ",", "speed", ")", ":", "if", "public", ":", "return", "self", ".", "client", ".", "call", "(", "'Hardware_Server'", ",", "'setPublicNetworkInterfaceSpeed'", ",", "speed", ",", "id", ...
43.37037
0.001671
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a list with :class:`~gpx.Waypoint` objects. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1....
[ "def", "import_locations", "(", "self", ",", "gpx_file", ")", ":", "self", ".", "_gpx_file", "=", "gpx_file", "data", "=", "utils", ".", "prepare_xml_read", "(", "gpx_file", ",", "objectify", "=", "True", ")", "try", ":", "self", ".", "metadata", ".", "i...
35.942029
0.001177
def get_config(workflow): """ Obtain configuration object Does not fail :return: ReactorConfig instance """ try: workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] return workspace[WORKSPACE_CONF_KEY] except KeyError: # The plugin did not run or was not s...
[ "def", "get_config", "(", "workflow", ")", ":", "try", ":", "workspace", "=", "workflow", ".", "plugin_workspace", "[", "ReactorConfigPlugin", ".", "key", "]", "return", "workspace", "[", "WORKSPACE_CONF_KEY", "]", "except", "KeyError", ":", "# The plugin did not ...
33.705882
0.001698
def list_from_args(args): """ Flatten list of args So as to accept either an array Or as many arguments For example: func(['x', 'y']) func('x', 'y') """ # Empty args if not args: return [] # Get argument type arg_type = type(args[0]) is_list = arg_type in LIS...
[ "def", "list_from_args", "(", "args", ")", ":", "# Empty args", "if", "not", "args", ":", "return", "[", "]", "# Get argument type", "arg_type", "=", "type", "(", "args", "[", "0", "]", ")", "is_list", "=", "arg_type", "in", "LIST_TYPES", "# Check that the a...
21.742857
0.001258
def prune_existing_features(project, force=False): """Prune existing features""" if not force and not project.on_master_after_merge(): raise SkippedValidationTest('Not on master') out = project.build() X_df, y, features = out['X_df'], out['y'], out['features'] proposed_feature = get_propose...
[ "def", "prune_existing_features", "(", "project", ",", "force", "=", "False", ")", ":", "if", "not", "force", "and", "not", "project", ".", "on_master_after_merge", "(", ")", ":", "raise", "SkippedValidationTest", "(", "'Not on master'", ")", "out", "=", "proj...
37.666667
0.001439
def _bsd_addif(br, iface): ''' Internal, adds an interface to a bridge ''' kernel = __grains__['kernel'] if kernel == 'NetBSD': cmd = _tool_path('brconfig') brcmd = 'add' else: cmd = _tool_path('ifconfig') brcmd = 'addem' if not br or not iface: retur...
[ "def", "_bsd_addif", "(", "br", ",", "iface", ")", ":", "kernel", "=", "__grains__", "[", "'kernel'", "]", "if", "kernel", "==", "'NetBSD'", ":", "cmd", "=", "_tool_path", "(", "'brconfig'", ")", "brcmd", "=", "'add'", "else", ":", "cmd", "=", "_tool_p...
26.058824
0.002179
def pformat(arg, width=79, height=24, compact=True): """Return pretty formatted representation of object as string. Whitespace might be altered. """ if height is None or height < 1: height = 1024 if width is None or width < 1: width = 256 npopt = numpy.get_printoptions() n...
[ "def", "pformat", "(", "arg", ",", "width", "=", "79", ",", "height", "=", "24", ",", "compact", "=", "True", ")", ":", "if", "height", "is", "None", "or", "height", "<", "1", ":", "height", "=", "1024", "if", "width", "is", "None", "or", "width"...
31.170213
0.000662
def email_quoted_txt2html(text, tabs_before=0, indent_txt='>>', linebreak_txt="\n", indent_html=('<div class="commentbox">', "</div>"), linebreak_html='<br/>', inde...
[ "def", "email_quoted_txt2html", "(", "text", ",", "tabs_before", "=", "0", ",", "indent_txt", "=", "'>>'", ",", "linebreak_txt", "=", "\"\\n\"", ",", "indent_html", "=", "(", "'<div class=\"commentbox\">'", ",", "\"</div>\"", ")", ",", "linebreak_html", "=", "'<...
37.236364
0.000238
def _parametersAsIndex( self, ps ): """Private method to turn a parameter dict into a string suitable for keying a dict. ps: the parameters as a hash returns: a string key""" k = "" for p in sorted(ps.keys()): # normalise the parameters v = ps[p] ...
[ "def", "_parametersAsIndex", "(", "self", ",", "ps", ")", ":", "k", "=", "\"\"", "for", "p", "in", "sorted", "(", "ps", ".", "keys", "(", ")", ")", ":", "# normalise the parameters", "v", "=", "ps", "[", "p", "]", "k", "=", "k", "+", "\"{p}=[[{v}]]...
34.181818
0.020725
def _create_container(context, path, l_mtime, size): """ Creates container for segments of file with `path` """ new_context = context.copy() new_context.input_ = None new_context.headers = None new_context.query = None container = path.split('/', 1)[0] + '_segments' cli_put_container...
[ "def", "_create_container", "(", "context", ",", "path", ",", "l_mtime", ",", "size", ")", ":", "new_context", "=", "context", ".", "copy", "(", ")", "new_context", ".", "input_", "=", "None", "new_context", ".", "headers", "=", "None", "new_context", ".",...
32.428571
0.002141
def clear_jobs(): '''Clear old jobs :param days: Jobs for how many days should be kept (default: 10) :type days: integer :statuscode 200: no error :statuscode 403: not authorized to delete jobs :statuscode 409: an error occurred ''' if not is_authorized(): return json.dumps({'e...
[ "def", "clear_jobs", "(", ")", ":", "if", "not", "is_authorized", "(", ")", ":", "return", "json", ".", "dumps", "(", "{", "'error'", ":", "'not authorized'", "}", ")", ",", "403", ",", "headers", "days", "=", "flask", ".", "request", ".", "args", "....
28.2
0.002288
def make_report(isodate='today'): """ Build a HTML report with the computations performed at the given isodate. Return the name of the report, which is saved in the current directory. """ if isodate == 'today': isodate = date.today() else: isodate = date(*time.strptime(isodate, '...
[ "def", "make_report", "(", "isodate", "=", "'today'", ")", ":", "if", "isodate", "==", "'today'", ":", "isodate", "=", "date", ".", "today", "(", ")", "else", ":", "isodate", "=", "date", "(", "*", "time", ".", "strptime", "(", "isodate", ",", "'%Y-%...
36.466667
0.000593
def _smart_get_initialized_channel_for_service(self, metadata, filter_by, is_try_initailize = True): ''' - filter_by can be sender or signer ''' channels = self._get_initialized_channels_for_service(self.args.org_id, self.args.service_id) group_id = metadata.get_group_id(self.ar...
[ "def", "_smart_get_initialized_channel_for_service", "(", "self", ",", "metadata", ",", "filter_by", ",", "is_try_initailize", "=", "True", ")", ":", "channels", "=", "self", ".", "_get_initialized_channels_for_service", "(", "self", ".", "args", ".", "org_id", ",",...
65.125
0.01261
def build_keys(request, database_name, collection_name): """Perform the map/reduce to refresh the keys form. The display the custom report screen""" build_keys_with_mapreduce(database_name, collection_name) messages.success(request, _( "Successfully completed MapReduce operation. " "K...
[ "def", "build_keys", "(", "request", ",", "database_name", ",", "collection_name", ")", ":", "build_keys_with_mapreduce", "(", "database_name", ",", "collection_name", ")", "messages", ".", "success", "(", "request", ",", "_", "(", "\"Successfully completed MapReduce ...
51.875
0.00237
def _parse_saved_model(path): """Reads the savedmodel.pb file containing `SavedModel`.""" # Based on tensorflow/python/saved_model/loader.py implementation. path_to_pb = _get_saved_model_proto_path(path) file_content = tf_v1.gfile.Open(path_to_pb, "rb").read() saved_model = saved_model_pb2.SavedModel() try:...
[ "def", "_parse_saved_model", "(", "path", ")", ":", "# Based on tensorflow/python/saved_model/loader.py implementation.", "path_to_pb", "=", "_get_saved_model_proto_path", "(", "path", ")", "file_content", "=", "tf_v1", ".", "gfile", ".", "Open", "(", "path_to_pb", ",", ...
43.818182
0.018293
def change_frozen_attr(self): """Changes frozen state of cell if there is no selection""" # Selections are not supported if self.grid.selection: statustext = _("Freezing selections is not supported.") post_command_event(self.main_window, self.StatusBarMsg, ...
[ "def", "change_frozen_attr", "(", "self", ")", ":", "# Selections are not supported", "if", "self", ".", "grid", ".", "selection", ":", "statustext", "=", "_", "(", "\"Freezing selections is not supported.\"", ")", "post_command_event", "(", "self", ".", "main_window"...
34.533333
0.001878
def load_dataset(dataset_key, force_update=False, auto_update=False, profile='default', **kwargs): """Load a dataset from the local filesystem, downloading it from data.world first, if necessary. This function returns an object of type `LocalDataset`. The object allows access to meteda...
[ "def", "load_dataset", "(", "dataset_key", ",", "force_update", "=", "False", ",", "auto_update", "=", "False", ",", "profile", "=", "'default'", ",", "*", "*", "kwargs", ")", ":", "return", "_get_instance", "(", "profile", ",", "*", "*", "kwargs", ")", ...
42.27027
0.000625
def calculate_stats(self, data): """Calculate the stats data for our process level data. :param data: The collected stats data to report on :type data: dict """ timestamp = data['timestamp'] del data['timestamp'] # Iterate through the last poll results ...
[ "def", "calculate_stats", "(", "self", ",", "data", ")", ":", "timestamp", "=", "data", "[", "'timestamp'", "]", "del", "data", "[", "'timestamp'", "]", "# Iterate through the last poll results", "stats", "=", "self", ".", "consumer_stats_counter", "(", ")", "co...
35.766667
0.001815
def _find_table_group(h5file, ifo=None): """Find the right `h5py.Group` within the given `h5py.File` """ exclude = ('background',) if ifo is None: try: ifo, = [key for key in h5file if key not in exclude] except ValueError as exc: exc.args = ("PyCBC live HDF5 file...
[ "def", "_find_table_group", "(", "h5file", ",", "ifo", "=", "None", ")", ":", "exclude", "=", "(", "'background'", ",", ")", "if", "ifo", "is", "None", ":", "try", ":", "ifo", ",", "=", "[", "key", "for", "key", "in", "h5file", "if", "key", "not", ...
39.944444
0.001359
def thumb(self, size=BIGTHUMB): '''Get a thumbnail as string or None if the file isnt an image size would be one of JFSFile.BIGTHUMB, .MEDIUMTHUMB, .SMALLTHUMB or .XLTHUMB''' if not self.is_image(): return None if not size in (self.BIGTHUMB, self.MEDIUMTHUMB, self.SMALLTHUMB...
[ "def", "thumb", "(", "self", ",", "size", "=", "BIGTHUMB", ")", ":", "if", "not", "self", ".", "is_image", "(", ")", ":", "return", "None", "if", "not", "size", "in", "(", "self", ".", "BIGTHUMB", ",", "self", ".", "MEDIUMTHUMB", ",", "self", ".", ...
54.090909
0.014876
def PublishEvent(cls, event_name, msg, token=None): """Publish the message into all listeners of the event. We send the message to all event handlers which contain this string in their EVENT static member. This allows the event to be sent to multiple interested listeners. Args: event_name: A...
[ "def", "PublishEvent", "(", "cls", ",", "event_name", ",", "msg", ",", "token", "=", "None", ")", ":", "cls", ".", "PublishMultipleEvents", "(", "{", "event_name", ":", "[", "msg", "]", "}", ",", "token", "=", "token", ")" ]
36.117647
0.001587
def endInstance(self): """ Finalise the instance definition started by startInstance(). """ if self.currentInstance is None: return allInstances = self.root.findall('.instances')[0].append(self.currentInstance) self.currentInstance = None
[ "def", "endInstance", "(", "self", ")", ":", "if", "self", ".", "currentInstance", "is", "None", ":", "return", "allInstances", "=", "self", ".", "root", ".", "findall", "(", "'.instances'", ")", "[", "0", "]", ".", "append", "(", "self", ".", "current...
36.875
0.009934
def parse (cls, line, lineno, log, cmddict=None): """Parses the SeqDelay from a line of text. Warning and error messages are logged via the SeqMsgLog log. """ delay = -1 token = line.split()[0] start = line.find(token) pos = SeqPos(line, lineno, start + 1, start + len(token)) try: ...
[ "def", "parse", "(", "cls", ",", "line", ",", "lineno", ",", "log", ",", "cmddict", "=", "None", ")", ":", "delay", "=", "-", "1", "token", "=", "line", ".", "split", "(", ")", "[", "0", "]", "start", "=", "line", ".", "find", "(", "token", "...
30.625
0.011881
def global_lppooling(attrs, inputs, proto_obj): """Performs global lp pooling on the input.""" p_value = attrs.get('p', 2) new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
[ "def", "global_lppooling", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "p_value", "=", "attrs", ".", "get", "(", "'p'", ",", "2", ")", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'global_pool'", ...
63.111111
0.008681
def get_default_project_id(): """ Get default project id from config or environment var. Returns: the project id if available, or None. """ # Try getting default project id from gcloud. If it fails try config.json. try: proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)...
[ "def", "get_default_project_id", "(", ")", ":", "# Try getting default project id from gcloud. If it fails try config.json.", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'gcloud'", ",", "'config'", ",", "'list'", ",", "'--format'", ",", "'value(core....
34.225806
0.014665
def generate2(func, args_gen, kw_gen=None, ntasks=None, ordered=True, force_serial=False, use_pool=False, chunksize=None, nprocs=None, progkw={}, nTasks=None, verbose=None): r""" Interfaces to either multiprocessing or futures. Esentially maps ``args_gen`` onto ``func`` using poo...
[ "def", "generate2", "(", "func", ",", "args_gen", ",", "kw_gen", "=", "None", ",", "ntasks", "=", "None", ",", "ordered", "=", "True", ",", "force_serial", "=", "False", ",", "use_pool", "=", "False", ",", "chunksize", "=", "None", ",", "nprocs", "=", ...
43.89083
0.000389
def resolve_tv_show(self, title, year=None): """Tries to find a movie with a given title and year""" r = self.search_tv_show(title) return self._match_results(r, title, year)
[ "def", "resolve_tv_show", "(", "self", ",", "title", ",", "year", "=", "None", ")", ":", "r", "=", "self", ".", "search_tv_show", "(", "title", ")", "return", "self", ".", "_match_results", "(", "r", ",", "title", ",", "year", ")" ]
39
0.01005
def newDocComment(self, content): """Creation of a new node containing a comment within a document. """ ret = libxml2mod.xmlNewDocComment(self._o, content) if ret is None:raise treeError('xmlNewDocComment() failed') __tmp = xmlNode(_obj=ret) return __tmp
[ "def", "newDocComment", "(", "self", ",", "content", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNewDocComment", "(", "self", ".", "_o", ",", "content", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewDocComment() failed'", ")", "_...
42.714286
0.013115
def update_status(dbfile,status_file,nas_addr): ''' update status db ''' try: total = 0 params = [] for sid, su in parse_status_file(status_file, nas_addr).items(): if 'session_id' in su and 'inbytes' in su and 'outbytes' in su: params.append((su['inbytes...
[ "def", "update_status", "(", "dbfile", ",", "status_file", ",", "nas_addr", ")", ":", "try", ":", "total", "=", "0", "params", "=", "[", "]", "for", "sid", ",", "su", "in", "parse_status_file", "(", "status_file", ",", "nas_addr", ")", ".", "items", "(...
37.466667
0.012153
def dmxData(self, data: tuple): """ For legacy devices and to prevent errors, the length of the DMX data is normalized to 512 """ newData = [0]*512 for i in range(0, min(len(data), 512)): newData[i] = data[i] self._dmxData = tuple(newData) # in theory ...
[ "def", "dmxData", "(", "self", ",", "data", ":", "tuple", ")", ":", "newData", "=", "[", "0", "]", "*", "512", "for", "i", "in", "range", "(", "0", ",", "min", "(", "len", "(", "data", ")", ",", "512", ")", ")", ":", "newData", "[", "i", "]...
43.5
0.009009
def init_fundamental_types(self): """Registers all fundamental typekind handlers""" for _id in range(2, 25): setattr(self, TypeKind.from_id(_id).name, self._handle_fundamental_types)
[ "def", "init_fundamental_types", "(", "self", ")", ":", "for", "_id", "in", "range", "(", "2", ",", "25", ")", ":", "setattr", "(", "self", ",", "TypeKind", ".", "from_id", "(", "_id", ")", ".", "name", ",", "self", ".", "_handle_fundamental_types", ")...
45.2
0.008696
def bulk_create_datetimes(date_start: DateTime, date_end: DateTime, **kwargs) -> List[DateTime]: """Bulk create datetime objects. This method creates list of datetime objects from ``date_start`` to ``date_end``. You can use the following keyword arguments:...
[ "def", "bulk_create_datetimes", "(", "date_start", ":", "DateTime", ",", "date_end", ":", "DateTime", ",", "*", "*", "kwargs", ")", "->", "List", "[", "DateTime", "]", ":", "dt_objects", "=", "[", "]", "if", "not", "date_start", "and", "not", "date_end", ...
32.564103
0.002294
def is_false(entity, prop, name): "bool: True if the value of a property is False." return is_not_empty(entity, prop, name) and name in entity._data and not bool(getattr(entity, name))
[ "def", "is_false", "(", "entity", ",", "prop", ",", "name", ")", ":", "return", "is_not_empty", "(", "entity", ",", "prop", ",", "name", ")", "and", "name", "in", "entity", ".", "_data", "and", "not", "bool", "(", "getattr", "(", "entity", ",", "name...
63.333333
0.010417
def compare(self, lhs_value, rhs_value): """Compare left- and right-size of: value <op> value. :param lhs_value: Value to left of operator :param rhs_value: Value to right of operator :return: True if the comparison is valid :rtype: bool """ if self.is_eq(): ...
[ "def", "compare", "(", "self", ",", "lhs_value", ",", "rhs_value", ")", ":", "if", "self", ".", "is_eq", "(", ")", ":", "# simple {field:value}", "return", "lhs_value", "is", "not", "None", "and", "lhs_value", "==", "rhs_value", "if", "self", ".", "is_neq"...
38.790698
0.001754
def dict_to_json(xcol, ycols, labels, value_columns): """ Converts a list of dicts from datamodel query results to google chart json data. :param xcol: The name of a string column to be used has X axis on chart :param ycols: A list with the names of series co...
[ "def", "dict_to_json", "(", "xcol", ",", "ycols", ",", "labels", ",", "value_columns", ")", ":", "json_data", "=", "dict", "(", ")", "json_data", "[", "'cols'", "]", "=", "[", "{", "'id'", ":", "xcol", ",", "'label'", ":", "as_unicode", "(", "labels", ...
35.540541
0.00074
def delete(self, event): """Abort running task if it exists.""" super(CeleryReceiver, self).delete(event) AsyncResult(event.id).revoke(terminate=True)
[ "def", "delete", "(", "self", ",", "event", ")", ":", "super", "(", "CeleryReceiver", ",", "self", ")", ".", "delete", "(", "event", ")", "AsyncResult", "(", "event", ".", "id", ")", ".", "revoke", "(", "terminate", "=", "True", ")" ]
42.75
0.011494
def get_base_url(config, url): """ Look through config and try to find best matching base for 'url' config - result of read_config() or read_global_config() url - artifactory url to search the base for """ if not config: return None # First, try to search for the best match for...
[ "def", "get_base_url", "(", "config", ",", "url", ")", ":", "if", "not", "config", ":", "return", "None", "# First, try to search for the best match", "for", "item", "in", "config", ":", "if", "url", ".", "startswith", "(", "item", ")", ":", "return", "item"...
28.210526
0.001805
def echo(params, source, delay, strength): ''' Create an echo :param params: :param source: :param delay: :param strength: :return: ''' source = create_buffer(params, source) delay = create_buffer(params, delay) strength = create_buffer(params, strength) output = source[:...
[ "def", "echo", "(", "params", ",", "source", ",", "delay", ",", "strength", ")", ":", "source", "=", "create_buffer", "(", "params", ",", "source", ")", "delay", "=", "create_buffer", "(", "params", ",", "delay", ")", "strength", "=", "create_buffer", "(...
26.055556
0.002058
def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None): """Check to see if the units contain E&M units This function supports unyt's ability to convert data to and from E&M electromagnetic units. However, this support is limited and only very simple unit expressions can be readil...
[ "def", "_check_em_conversion", "(", "unit", ",", "to_unit", "=", "None", ",", "unit_system", "=", "None", ",", "registry", "=", "None", ")", ":", "em_map", "=", "(", ")", "if", "unit", "==", "to_unit", "or", "unit", ".", "dimensions", "not", "in", "em_...
45.3
0.000432
def check_auto_merge_labeler(repo: GithubRepository, pull_id: int ) -> Optional[CannotAutomergeError]: """ References: https://developer.github.com/v3/issues/events/#list-events-for-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/events" ...
[ "def", "check_auto_merge_labeler", "(", "repo", ":", "GithubRepository", ",", "pull_id", ":", "int", ")", "->", "Optional", "[", "CannotAutomergeError", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/{}/events\"", "\"?access_token={}\"", ".", "f...
40.071429
0.00087
def get_assignments( self, gradebook_id='', simple=False, max_points=True, avg_stats=False, grading_stats=False ): """Get assignments for a gradebook. Return list of assignments for a given gradebook, specified by a py:...
[ "def", "get_assignments", "(", "self", ",", "gradebook_id", "=", "''", ",", "simple", "=", "False", ",", "max_points", "=", "True", ",", "avg_stats", "=", "False", ",", "grading_stats", "=", "False", ")", ":", "# These are parameters required for the remote API ca...
38.306122
0.000779
def create_unsigned_tx(inputs, outputs, change_address=None, include_tosigntx=False, verify_tosigntx=False, min_confirmations=0, preference='high', coin_symbol='btc', api_key=None): ''' Create a new transaction to sign. Doesn't ask for or involve private keys. Behind the scenes, blockcypher ...
[ "def", "create_unsigned_tx", "(", "inputs", ",", "outputs", ",", "change_address", "=", "None", ",", "include_tosigntx", "=", "False", ",", "verify_tosigntx", "=", "False", ",", "min_confirmations", "=", "0", ",", "preference", "=", "'high'", ",", "coin_symbol",...
38.985816
0.001951
def record_event(self, event): """Records the ``KindleEvent`` `event` in the store """ with open(self._path, 'a') as file_: file_.write(str(event) + '\n')
[ "def", "record_event", "(", "self", ",", "event", ")", ":", "with", "open", "(", "self", ".", "_path", ",", "'a'", ")", "as", "file_", ":", "file_", ".", "write", "(", "str", "(", "event", ")", "+", "'\\n'", ")" ]
37.2
0.010526
def _exec_ipmitool(driver_info, command): """Execute the ipmitool command. This uses the lanplus interface to communicate with the BMC device driver. :param driver_info: the ipmitool parameters for accessing a node. :param command: the ipmitool command to be executed. """ ipmi_cmd = ("ipmitoo...
[ "def", "_exec_ipmitool", "(", "driver_info", ",", "command", ")", ":", "ipmi_cmd", "=", "(", "\"ipmitool -H %(address)s\"", "\" -I lanplus -U %(user)s -P %(passwd)s %(cmd)s\"", "%", "{", "'address'", ":", "driver_info", "[", "'address'", "]", ",", "'user'", ":", "driv...
32.318182
0.001366
def _setContent(self): '''create string representation of operation. ''' kwstring = 'kw = {}' tCheck = 'if isinstance(request, %s) is False:' % self.inputName bindArgs = '' if self.encodingStyle is not None: bindArgs = 'encodingStyle="%s", ' %self.encodingStyl...
[ "def", "_setContent", "(", "self", ")", ":", "kwstring", "=", "'kw = {}'", "tCheck", "=", "'if isinstance(request, %s) is False:'", "%", "self", ".", "inputName", "bindArgs", "=", "''", "if", "self", ".", "encodingStyle", "is", "not", "None", ":", "bindArgs", ...
43.121951
0.009122
def crypto_bloom_filter(record, # type: Sequence[Text] tokenizers, # type: List[Callable[[Text, Optional[Text]], Iterable[Text]]] schema, # type: Schema keys # type: Sequence[Sequence[bytes]] ): # type...
[ "def", "crypto_bloom_filter", "(", "record", ",", "# type: Sequence[Text]", "tokenizers", ",", "# type: List[Callable[[Text, Optional[Text]], Iterable[Text]]]", "schema", ",", "# type: Schema", "keys", "# type: Sequence[Sequence[bytes]]", ")", ":", "# type: (...) -> Tuple[bitarray, T...
42.658537
0.001118
def _load_architectures(self, family): """Load in all of the architectural overlays for this family. An architecture adds configuration information that is used to build a common set of source code for a particular hardware and situation. They are stackable so that you can specify a chip and a ...
[ "def", "_load_architectures", "(", "self", ",", "family", ")", ":", "if", "\"architectures\"", "not", "in", "family", ":", "raise", "InternalError", "(", "\"required architectures key not in build_settings.json for desired family\"", ")", "for", "key", ",", "val", "in",...
53.428571
0.009198
def read_metadata_by_name(self, name, metadata_key, caster=None): """Read process metadata using a named identity. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param func caster: A casting callable to apply to ...
[ "def", "read_metadata_by_name", "(", "self", ",", "name", ",", "metadata_key", ",", "caster", "=", "None", ")", ":", "file_path", "=", "self", ".", "_metadata_file_path", "(", "name", ",", "metadata_key", ")", "try", ":", "metadata", "=", "read_file", "(", ...
42.846154
0.010545
def token_getter(remote, token=''): """Retrieve OAuth access token. Used by flask-oauthlib to get the access token when making requests. :param remote: The remote application. :param token: Type of token to get. Data passed from ``oauth.request()`` to identify which token to retrieve. (Default...
[ "def", "token_getter", "(", "remote", ",", "token", "=", "''", ")", ":", "session_key", "=", "token_session_key", "(", "remote", ".", "name", ")", "if", "session_key", "not", "in", "session", "and", "current_user", ".", "is_authenticated", ":", "# Fetch key fr...
32.928571
0.001054
def _set_initial_contents(self, contents): """Sets the file contents and size. Called internally after initial file creation. Args: contents: string, new content of file. Returns: True if the contents have been changed. Raises: IOError:...
[ "def", "_set_initial_contents", "(", "self", ",", "contents", ")", ":", "contents", "=", "self", ".", "_encode_contents", "(", "contents", ")", "changed", "=", "self", ".", "_byte_contents", "!=", "contents", "st_size", "=", "len", "(", "contents", ")", "if"...
32.518519
0.002212
def get(self, name): """Returns the specified interfaces STP configuration resource The STP interface resource contains the following * name (str): The interface name * portfast (bool): The spanning-tree portfast admin state * bpduguard (bool): The spanning-tree bpd...
[ "def", "get", "(", "self", ",", "name", ")", ":", "if", "not", "isvalidinterface", "(", "name", ")", ":", "return", "None", "config", "=", "self", ".", "get_block", "(", "r'^interface\\s%s$'", "%", "name", ")", "resp", "=", "dict", "(", ")", "resp", ...
38.16129
0.001649
def set_data(self, post_data): """ Update (patch) the current instance's data on the NuHeat API """ params = { "serialnumber": self.serial_number } self._session.request(config.THERMOSTAT_URL, method="POST", data=post_data, params=params)
[ "def", "set_data", "(", "self", ",", "post_data", ")", ":", "params", "=", "{", "\"serialnumber\"", ":", "self", ".", "serial_number", "}", "self", ".", "_session", ".", "request", "(", "config", ".", "THERMOSTAT_URL", ",", "method", "=", "\"POST\"", ",", ...
36.375
0.010067
def update_campaign_archive(self, campaign_id, **kwargs): # noqa: E501 """Archive a campaign. # noqa: E501 This command will archive a campaign. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True ...
[ "def", "update_campaign_archive", "(", "self", ",", "campaign_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ...
46.142857
0.002022
def _add_edus_to_tree(parented_tree, edus): """replace EDU indices with the text of the EDUs in a parented tree. Parameters ---------- parented_tree : nltk.ParentedTree a parented tree that only contains EDU indices as leaves edus : list(list(unicode)) a list of EDUs, wh...
[ "def", "_add_edus_to_tree", "(", "parented_tree", ",", "edus", ")", ":", "for", "i", ",", "child", "in", "enumerate", "(", "parented_tree", ")", ":", "if", "isinstance", "(", "child", ",", "nltk", ".", "Tree", ")", ":", "_add_edus_to_tree", "(", "child", ...
31.85
0.001524
def mol_supplier(lines, no_halt, assign_descriptors): """Yields molecules generated from CTAB text Args: lines (iterable): CTAB text lines no_halt (boolean): True: shows warning messages for invalid format and go on. False: throws an exception for it and stop parsing. ...
[ "def", "mol_supplier", "(", "lines", ",", "no_halt", ",", "assign_descriptors", ")", ":", "def", "sdf_block", "(", "lns", ")", ":", "mol", "=", "[", "]", "opt", "=", "[", "]", "is_mol", "=", "True", "for", "line", "in", "lns", ":", "if", "line", "....
34.451613
0.00091
def np2gdal_dtype(d): """ Get GDAL RasterBand datatype that corresponds with NumPy datatype Input should be numpy array or numpy dtype """ dt_dict = gdal_array.codes if isinstance(d, (np.ndarray, np.generic)): d = d.dtype #This creates dtype from another built-in type #d ...
[ "def", "np2gdal_dtype", "(", "d", ")", ":", "dt_dict", "=", "gdal_array", ".", "codes", "if", "isinstance", "(", "d", ",", "(", "np", ".", "ndarray", ",", "np", ".", "generic", ")", ")", ":", "d", "=", "d", ".", "dtype", "#This creates dtype from anoth...
31.090909
0.008511
def update(self, actions=values.unset): """ Update the TaskActionsInstance :param dict actions: The JSON string that specifies the actions that instruct the Assistant on how to perform the task :returns: Updated TaskActionsInstance :rtype: twilio.rest.autopilot.v1.assistant.tas...
[ "def", "update", "(", "self", ",", "actions", "=", "values", ".", "unset", ")", ":", "return", "self", ".", "_proxy", ".", "update", "(", "actions", "=", "actions", ",", ")" ]
41
0.009547
def heartbeat(queue_name, task_id, owner, message, index): """Sets the heartbeat status of the task and extends its lease. The task's lease is extended by the same amount as its last lease to ensure that any operations following the heartbeat will still hold the lock for the original lock period. ...
[ "def", "heartbeat", "(", "queue_name", ",", "task_id", ",", "owner", ",", "message", ",", "index", ")", ":", "task", "=", "_get_task_with_policy", "(", "queue_name", ",", "task_id", ",", "owner", ")", "if", "task", ".", "heartbeat_number", ">", "index", ":...
37.844444
0.000572
def regularize_array(A): """ Takes an np.ndarray as an input. - If the array is one-dimensional, it's assumed to be an array of input values. - If the array is more than one-dimensional, its last index is assumed to curse over spatial dimension. Either way, the return value is at least tw...
[ "def", "regularize_array", "(", "A", ")", ":", "if", "not", "isinstance", "(", "A", ",", "np", ".", "ndarray", ")", ":", "A", "=", "np", ".", "array", "(", "A", ",", "dtype", "=", "float", ")", "else", ":", "A", "=", "np", ".", "asarray", "(", ...
24
0.010386
def match_aspect_to_viewport(self): """Updates Camera.aspect to match the viewport's aspect ratio.""" viewport = self.viewport self.aspect = float(viewport.width) / viewport.height
[ "def", "match_aspect_to_viewport", "(", "self", ")", ":", "viewport", "=", "self", ".", "viewport", "self", ".", "aspect", "=", "float", "(", "viewport", ".", "width", ")", "/", "viewport", ".", "height" ]
50.25
0.009804
def play(self, source, *, after=None): """Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stop...
[ "def", "play", "(", "self", ",", "source", ",", "*", ",", "after", "=", "None", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "ClientException", "(", "'Not connected to voice.'", ")", "if", "self", ".", "is_playing", "(", ...
35.552632
0.002161
def tokenize_words(self, text): """Tokenize an input string into a list of words (with punctuation removed).""" return [ self.strip_punctuation(word) for word in text.split(' ') if self.strip_punctuation(word) ]
[ "def", "tokenize_words", "(", "self", ",", "text", ")", ":", "return", "[", "self", ".", "strip_punctuation", "(", "word", ")", "for", "word", "in", "text", ".", "split", "(", "' '", ")", "if", "self", ".", "strip_punctuation", "(", "word", ")", "]" ]
42.333333
0.011583
def itermonthdays(cls, year, month): """Similar to itermonthdates but returns day number instead of NepDate object """ for day in NepCal.itermonthdates(year, month): if day.month == month: yield day.day else: yield 0
[ "def", "itermonthdays", "(", "cls", ",", "year", ",", "month", ")", ":", "for", "day", "in", "NepCal", ".", "itermonthdates", "(", "year", ",", "month", ")", ":", "if", "day", ".", "month", "==", "month", ":", "yield", "day", ".", "day", "else", ":...
36.125
0.010135
def convert_chain( txtfiles, headers, h5file, chunksize): """Converts chain in plain text format into HDF5 format. Keyword arguments: txtfiles -- list of paths to the plain text chains. headers -- name of each column. h5file -- where to put the resulting HDF5 file. ...
[ "def", "convert_chain", "(", "txtfiles", ",", "headers", ",", "h5file", ",", "chunksize", ")", ":", "h5", "=", "h5py", ".", "File", "(", "h5file", ",", "'w'", ")", "for", "h", "in", "headers", ":", "h5", ".", "create_dataset", "(", "h", ",", "shape",...
28.391304
0.002221
def __build_markable_token_mapper(self, coreference_layer=None, markable_layer=None): """ Creates mappings from tokens to the markable spans they belong to and the coreference chains these markables are part of. Returns ------- tok2m...
[ "def", "__build_markable_token_mapper", "(", "self", ",", "coreference_layer", "=", "None", ",", "markable_layer", "=", "None", ")", ":", "tok2markables", "=", "defaultdict", "(", "set", ")", "markable2toks", "=", "defaultdict", "(", "list", ")", "markable2chains"...
44.695652
0.001428
def configmaps(namespace='default', **kwargs): ''' Return a list of kubernetes configmaps defined in the namespace CLI Examples:: salt '*' kubernetes.configmaps salt '*' kubernetes.configmaps namespace=default ''' cfg = _setup_conn(**kwargs) try: api_instance = kubernet...
[ "def", "configmaps", "(", "namespace", "=", "'default'", ",", "*", "*", "kwargs", ")", ":", "cfg", "=", "_setup_conn", "(", "*", "*", "kwargs", ")", "try", ":", "api_instance", "=", "kubernetes", ".", "client", ".", "CoreV1Api", "(", ")", "api_response",...
32.807692
0.002278
def list_nodes(self): """List the Ironic nodes UUID.""" self.add_environment_file(user='stack', filename='stackrc') ret, _ = self.run("ironic node-list --fields uuid|awk '/-.*-/ {print $2}'", user='stack') # NOTE(Gonéri): the good new is, the order of the nodes is preserved and follow th...
[ "def", "list_nodes", "(", "self", ")", ":", "self", ".", "add_environment_file", "(", "user", "=", "'stack'", ",", "filename", "=", "'stackrc'", ")", "ret", ",", "_", "=", "self", ".", "run", "(", "\"ironic node-list --fields uuid|awk '/-.*-/ {print $2}'\"", ","...
60.571429
0.009302
def on_message(self, websocket, message): '''Handle websocket incoming messages ''' waiter = self._waiter self._waiter = None encoded = json.loads(message) event = encoded.get('event') channel = encoded.get('channel') data = json.loads(encoded.get('data'))...
[ "def", "on_message", "(", "self", ",", "websocket", ",", "message", ")", ":", "waiter", "=", "self", ".", "_waiter", "self", ".", "_waiter", "=", "None", "encoded", "=", "json", ".", "loads", "(", "message", ")", "event", "=", "encoded", ".", "get", ...
40.481481
0.001787
def paste(self,e): u"""Paste windows clipboard. Assume single line strip other lines and end of line markers and trailing spaces""" #(Control-v) if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert(False) txt=txt.split("\n")[0].strip("...
[ "def", "paste", "(", "self", ",", "e", ")", ":", "#(Control-v)\r", "if", "self", ".", "enable_win32_clipboard", ":", "txt", "=", "clipboard", ".", "get_clipboard_text_and_convert", "(", "False", ")", "txt", "=", "txt", ".", "split", "(", "\"\\n\"", ")", "[...
49
0.024499
def nla_put_msecs(msg, attrtype, msecs): """Add msecs Netlink attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L737 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). msecs -- number of msecs (in...
[ "def", "nla_put_msecs", "(", "msg", ",", "attrtype", ",", "msecs", ")", ":", "if", "isinstance", "(", "msecs", ",", "c_uint64", ")", ":", "pass", "elif", "isinstance", "(", "msecs", ",", "c_ulong", ")", ":", "msecs", "=", "c_uint64", "(", "msecs", ".",...
30.4
0.001595
def add_comment(self, page_id, text): """ Add comment into page :param page_id :param text """ data = {'type': 'comment', 'container': {'id': page_id, 'type': 'page', 'status': 'current'}, 'body': {'storage': {'value': text, 'representation...
[ "def", "add_comment", "(", "self", ",", "page_id", ",", "text", ")", ":", "data", "=", "{", "'type'", ":", "'comment'", ",", "'container'", ":", "{", "'id'", ":", "page_id", ",", "'type'", ":", "'page'", ",", "'status'", ":", "'current'", "}", ",", "...
38.3
0.010204
def build_keras_model(): """ Define a convnet model in Keras 1.2.2 """ from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D keras_model = Sequential() keras_model.add(Convolution2D(32, 3, 3,...
[ "def", "build_keras_model", "(", ")", ":", "from", "keras", ".", "models", "import", "Sequential", "from", "keras", ".", "layers", "import", "Dense", ",", "Dropout", ",", "Activation", ",", "Flatten", "from", "keras", ".", "layers", "import", "Convolution2D", ...
35.869565
0.001181