text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def set_product(self, product_name, product_version): """Set the product name and version that is transmitted as part of our identification According to 'FinTS Financial Transaction Services, Schnittstellenspezifikation, Formals', version 3.0, section C.3.1.3, you should fill this with ...
[ "def", "set_product", "(", "self", ",", "product_name", ",", "product_version", ")", ":", "self", ".", "product_name", "=", "product_name", "self", ".", "product_version", "=", "product_version" ]
53.666667
22.333333
def __msg_curse_header(self, ret, process_sort_key, args=None): """Build the header and add it to the ret dict.""" sort_style = 'SORT' if args.disable_irix and 0 < self.nb_log_core < 10: msg = self.layout_header['cpu'].format('CPU%/' + str(self.nb_log_core)) elif args.disabl...
[ "def", "__msg_curse_header", "(", "self", ",", "ret", ",", "process_sort_key", ",", "args", "=", "None", ")", ":", "sort_style", "=", "'SORT'", "if", "args", ".", "disable_irix", "and", "0", "<", "self", ".", "nb_log_core", "<", "10", ":", "msg", "=", ...
65.228571
29.285714
def vocab_convert(vocab, standard, key=''): """ Converts MagIC database terms (method codes, geologic_types, etc) to other standards. May not be comprehensive for each standard. Terms added to standards as people need them and may not be up-to-date. 'key' can be used to distinguish vocab terms that...
[ "def", "vocab_convert", "(", "vocab", ",", "standard", ",", "key", "=", "''", ")", ":", "places_to_geomagia", "=", "{", "'Egypt'", ":", "\"1\"", ",", "'Japan'", ":", "\"2\"", ",", "'France'", ":", "\"3\"", ",", "'Ukraine'", ":", "\"5\"", ",", "'India'", ...
40.973451
11.345133
def findFirst(self, tableClass, comparison=None, offset=None, sort=None, default=None): """ Usage:: s.findFirst(tableClass [, query arguments except 'limit']) Example:: class YourItemType(Item): a = integer() b = text()...
[ "def", "findFirst", "(", "self", ",", "tableClass", ",", "comparison", "=", "None", ",", "offset", "=", "None", ",", "sort", "=", "None", ",", "default", "=", "None", ")", ":", "limit", "=", "1", "for", "item", "in", "self", ".", "query", "(", "tab...
33.892857
22.392857
def read_cstring(self) -> bool: """ read a double quoted string Read following BNF rule else return False:: '"' -> ['\\' #char | ~'\\'] '"' """ self._stream.save_context() idx = self._stream.index if self.read_char("\"") and self.read_until("\"", "\\"): txt = self._stream[i...
[ "def", "read_cstring", "(", "self", ")", "->", "bool", ":", "self", ".", "_stream", ".", "save_context", "(", ")", "idx", "=", "self", ".", "_stream", ".", "index", "if", "self", ".", "read_char", "(", "\"\\\"\"", ")", "and", "self", ".", "read_until",...
29.857143
11.714286
def search_dashboard_deleted_for_facets(self, **kwargs): # noqa: E501 """Lists the values of one or more facets over the customer's deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass...
[ "def", "search_dashboard_deleted_for_facets", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "search_...
47.666667
21.809524
def currentFolder(self, value): """gets/sets the current folder (folder id)""" if value is not None and value.lower() == self._currentFolder['title']: return if value is None: self._location = self.root self._currentFolder = { 'title': 'roo...
[ "def", "currentFolder", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", "and", "value", ".", "lower", "(", ")", "==", "self", ".", "_currentFolder", "[", "'title'", "]", ":", "return", "if", "value", "is", "None", ":", "self"...
37.766667
11.766667
def file_md5(self, file_name): """Compute MD5 hash of file.""" with open(file_name, "rb") as f: file_contents = f.read() file_hash = hashlib.md5(file_contents).hexdigest() return file_hash
[ "def", "file_md5", "(", "self", ",", "file_name", ")", ":", "with", "open", "(", "file_name", ",", "\"rb\"", ")", "as", "f", ":", "file_contents", "=", "f", ".", "read", "(", ")", "file_hash", "=", "hashlib", ".", "md5", "(", "file_contents", ")", "....
38.5
8.666667
def command(self, rule, **options): """\ direct=False, override=True, inject=False, flags=0 """ options.setdefault("direct", False) options.setdefault("override", True) options.setdefault("inject", False) options.setdefault("flags", 0) if not options["dire...
[ "def", "command", "(", "self", ",", "rule", ",", "*", "*", "options", ")", ":", "options", ".", "setdefault", "(", "\"direct\"", ",", "False", ")", "options", ".", "setdefault", "(", "\"override\"", ",", "True", ")", "options", ".", "setdefault", "(", ...
33.458333
8.75
def clear_system_configuration(self): """Clear the BIOS/UEFI configuration """ biosinfo = self._do_web_request(self._biosurl) rb = biosinfo.get('Actions', {}).get('#Bios.ResetBios', {}) rb = rb.get('target', '') if not rb: raise Exception('BIOS reset not dete...
[ "def", "clear_system_configuration", "(", "self", ")", ":", "biosinfo", "=", "self", ".", "_do_web_request", "(", "self", ".", "_biosurl", ")", "rb", "=", "biosinfo", ".", "get", "(", "'Actions'", ",", "{", "}", ")", ".", "get", "(", "'#Bios.ResetBios'", ...
39.5
16.4
def associate_failure_node(self, parent, child=None, **kwargs): """Add a node to run on failure. =====API DOCS===== Add a node to run on failure. :param parent: Primary key of parent node to associate failure node to. :type parent: int :param child: Primary key of child...
[ "def", "associate_failure_node", "(", "self", ",", "parent", ",", "child", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_assoc_or_create", "(", "'failure'", ",", "parent", ",", "child", ",", "*", "*", "kwargs", ")" ]
40.176471
25.647059
def _translate_sdiv(self, oprnd1, oprnd2, oprnd3): """Return a formula representation of an DIV instruction. """ assert oprnd1.size and oprnd2.size and oprnd3.size assert oprnd1.size == oprnd2.size op1_var = self._translate_src_oprnd(oprnd1) op2_var = self._translate_src...
[ "def", "_translate_sdiv", "(", "self", ",", "oprnd1", ",", "oprnd2", ",", "oprnd3", ")", ":", "assert", "oprnd1", ".", "size", "and", "oprnd2", ".", "size", "and", "oprnd3", ".", "size", "assert", "oprnd1", ".", "size", "==", "oprnd2", ".", "size", "op...
39.809524
18.285714
def load_model(location): """ Load any Turi Create model that was previously saved. This function assumes the model (can be any model) was previously saved in Turi Create model format with model.save(filename). Parameters ---------- location : string Location of the model to load. ...
[ "def", "load_model", "(", "location", ")", ":", "# Check if the location is a dir_archive, if not, use glunpickler to load", "# as pure python model", "# If the location is a http location, skip the check, and directly proceed", "# to load model as dir_archive. This is because", "# 1) exists() d...
44.442105
23.263158
def apply(self, doc): """ Generate MentionCells from a Document by parsing all of its Cells. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): ...
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionCells.apply() must be of type Document\"", ")", "for", "cell", "in", "doc", ".", "cells", ...
33.533333
18.333333
def connect_combo_data(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the userData. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property wi...
[ "def", "connect_combo_data", "(", "instance", ",", "prop", ",", "widget", ")", ":", "def", "update_widget", "(", "value", ")", ":", "try", ":", "idx", "=", "_find_combo_data", "(", "widget", ",", "value", ")", "except", "ValueError", ":", "if", "value", ...
26.921053
20.552632
def is_correct(self): """Check if this object configuration is correct :: * Check if dateranges of timeperiod are valid * Call our parent class is_correct checker :return: True if the configuration is correct, otherwise False if at least one daterange is not correct :rt...
[ "def", "is_correct", "(", "self", ")", ":", "state", "=", "True", "for", "daterange", "in", "self", ".", "dateranges", ":", "good", "=", "daterange", ".", "is_correct", "(", ")", "if", "not", "good", ":", "self", ".", "add_error", "(", "\"[timeperiod::%s...
37.043478
20.782609
def _connect_pipeline(self, pipeline, required_outputs, workflow, subject_inds, visit_inds, filter_array, force=False): """ Connects a pipeline to a overarching workflow that sets up iterators over subjects|visits present in the repository (if required) and repo...
[ "def", "_connect_pipeline", "(", "self", ",", "pipeline", ",", "required_outputs", ",", "workflow", ",", "subject_inds", ",", "visit_inds", ",", "filter_array", ",", "force", "=", "False", ")", ":", "if", "self", ".", "reprocess", "==", "'force'", ":", "forc...
52.371981
19.386473
def get_git_status(self): """ Gets git and init versions and commits since the init version """ ## get git branch self._get_git_branch() ## get tag in the init file self._get_init_release_tag() ## get log commits since <tag> try: self...
[ "def", "get_git_status", "(", "self", ")", ":", "## get git branch", "self", ".", "_get_git_branch", "(", ")", "## get tag in the init file", "self", ".", "_get_init_release_tag", "(", ")", "## get log commits since <tag>", "try", ":", "self", ".", "_get_log_commits", ...
34.724138
17.655172
def export(self, template_file_name, output_file_name, sort="public", data=None, limit=0): """Export ranking to a file. Args: template_file_name (str): where is the template (moustache template) output_file_name (str): where create the file with th...
[ "def", "export", "(", "self", ",", "template_file_name", ",", "output_file_name", ",", "sort", "=", "\"public\"", ",", "data", "=", "None", ",", "limit", "=", "0", ")", ":", "exportedData", "=", "{", "}", "exportedUsers", "=", "self", ".", "__exportUsers",...
33.038462
17.692308
def storage(self, *, resource=None): """ Get an instance to handle file storage (OneDrive / Sharepoint) for the specified account resource :param str resource: Custom resource to be used in this drive object (Defaults to parent main_resource) :return: a representation of OneDri...
[ "def", "storage", "(", "self", ",", "*", ",", "resource", "=", "None", ")", ":", "if", "not", "isinstance", "(", "self", ".", "protocol", ",", "MSGraphProtocol", ")", ":", "# TODO: Custom protocol accessing OneDrive/Sharepoint Api fails here", "raise", "RuntimeError...
45.375
18.8125
def on_menu_criteria_file(self, event): """ read pmag_criteria.txt file and open change criteria dialog """ if self.data_model == 3: dlg = wx.FileDialog( self, message="choose a file in MagIC Data Model 3.0 format", defaultDir=self.WD,...
[ "def", "on_menu_criteria_file", "(", "self", ",", "event", ")", ":", "if", "self", ".", "data_model", "==", "3", ":", "dlg", "=", "wx", ".", "FileDialog", "(", "self", ",", "message", "=", "\"choose a file in MagIC Data Model 3.0 format\"", ",", "defaultDir", ...
51.022727
22.590909
def monitor_session_span_command_source(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span") session = ET.SubElement(monitor, "session") session_number_key = ET.SubE...
[ "def", "monitor_session_span_command_source", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "monitor", "=", "ET", ".", "SubElement", "(", "config", ",", "\"monitor\"", ",", "xmlns", "=", "\"urn...
46.714286
16.928571
def _ResponseToClientsFullInfo(self, response): """Creates a ClientFullInfo object from a database response.""" c_full_info = None prev_cid = None for row in response: (cid, fs, crt, ping, clk, ip, foreman, first, last_client_ts, last_crash_ts, last_startup_ts, client_obj, client_startup_ob...
[ "def", "_ResponseToClientsFullInfo", "(", "self", ",", "response", ")", ":", "c_full_info", "=", "None", "prev_cid", "=", "None", "for", "row", "in", "response", ":", "(", "cid", ",", "fs", ",", "crt", ",", "ping", ",", "clk", ",", "ip", ",", "foreman"...
39.916667
19.6
def get_albums(self, path): """Return the list of all sub-directories of path.""" for name in self.albums[path].subdirs: subdir = os.path.normpath(join(path, name)) yield subdir, self.albums[subdir] for subname, album in self.get_albums(subdir): yield...
[ "def", "get_albums", "(", "self", ",", "path", ")", ":", "for", "name", "in", "self", ".", "albums", "[", "path", "]", ".", "subdirs", ":", "subdir", "=", "os", ".", "path", ".", "normpath", "(", "join", "(", "path", ",", "name", ")", ")", "yield...
42.75
13.375
def isiterable(element, exclude=None): """Check whatever or not if input element is an iterable. :param element: element to check among iterable types. :param type/tuple exclude: not allowed types in the test. :Example: >>> isiterable({}) True >>> isiterable({}, exclude=dict) False ...
[ "def", "isiterable", "(", "element", ",", "exclude", "=", "None", ")", ":", "# check for allowed type", "allowed", "=", "exclude", "is", "None", "or", "not", "isinstance", "(", "element", ",", "exclude", ")", "result", "=", "allowed", "and", "isinstance", "(...
25
21.857143
def supports_version_type(self, version_type=None): """Tests if the given version type is supported. arg: version_type (osid.type.Type): a version Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``...
[ "def", "supports_version_type", "(", "self", ",", "version_type", "=", "None", ")", ":", "# Implemented from template for osid.Metadata.supports_coordinate_type", "from", ".", "osid_errors", "import", "IllegalState", ",", "NullArgument", "if", "not", "version_type", ":", ...
47.555556
20.166667
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None, region=None, key=None, keyid=None, profile=None): ''' Delete objects in a given S3 bucket. Returns {deleted: true} if all objects were deleted and {deleted: false, failed: [key, ...]} otherwise CLI Example: .. ...
[ "def", "delete_objects", "(", "Bucket", ",", "Delete", ",", "MFA", "=", "None", ",", "RequestPayer", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "isinstance...
34.418605
21.906977
def in_degree_iter(self, nbunch=None, t=None): """Return an iterator for (node, in_degree) at time t. The node degree is the number of edges incoming to the node in a given timeframe. Parameters ---------- nbunch : iterable container, optional (default=all nodes) A ...
[ "def", "in_degree_iter", "(", "self", ",", "nbunch", "=", "None", ",", "t", "=", "None", ")", ":", "if", "nbunch", "is", "None", ":", "nodes_nbrs", "=", "self", ".", "_pred", ".", "items", "(", ")", "else", ":", "nodes_nbrs", "=", "(", "(", "n", ...
30.265306
21.102041
def oauth_link_external_id(user, external_id=None): """Link a user to an external id. :param user: A :class:`invenio_accounts.models.User` instance. :param external_id: The external id associated with the user. (Default: ``None``) :raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if...
[ "def", "oauth_link_external_id", "(", "user", ",", "external_id", "=", "None", ")", ":", "try", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "db", ".", "session", ".", "add", "(", "UserIdentity", "(", "id", "=", "external_id", ...
35.666667
15
def connect(self, url): """Connect to the server. :param str url: server URL. """ headers = httputil.HTTPHeaders({'Content-Type': APPLICATION_JSON}) request = httpclient.HTTPRequest(url=url, connect_timeout=self.connect_timeout, ...
[ "def", "connect", "(", "self", ",", "url", ")", ":", "headers", "=", "httputil", ".", "HTTPHeaders", "(", "{", "'Content-Type'", ":", "APPLICATION_JSON", "}", ")", "request", "=", "httpclient", ".", "HTTPRequest", "(", "url", "=", "url", ",", "connect_time...
43.75
17.916667
def index(self, refresh=False): """Indexes this object, using a document from `to_dict()`""" es = connections.get_connection("default") index = self.__class__.search_objects.mapping.index doc_type = self.__class__.search_objects.mapping.doc_type es.index(index, doc_type, ...
[ "def", "index", "(", "self", ",", "refresh", "=", "False", ")", ":", "es", "=", "connections", ".", "get_connection", "(", "\"default\"", ")", "index", "=", "self", ".", "__class__", ".", "search_objects", ".", "mapping", ".", "index", "doc_type", "=", "...
44.888889
10.222222
def default(self, value): """Convert rogue and mysterious data types. Conversion notes: - ``datetime.date`` and ``datetime.datetime`` objects are converted into datetime strings. """ if isinstance(value, datetime): return value.isoformat() elif isins...
[ "def", "default", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", ".", "isoformat", "(", ")", "elif", "isinstance", "(", "value", ",", "date", ")", ":", "dt", "=", "datetime", "(", ...
34.473684
12.052632
def install_kernel_spec(self, app, dir_name, display_name, settings_module, ipython_arguments): """install an IPython >= 3.0 kernelspec that loads corral env Thanks: django extensions """ ksm = app.kernel_spec_manager try_spec_names = ['python3' if s...
[ "def", "install_kernel_spec", "(", "self", ",", "app", ",", "dir_name", ",", "display_name", ",", "settings_module", ",", "ipython_arguments", ")", ":", "ksm", "=", "app", ".", "kernel_spec_manager", "try_spec_names", "=", "[", "'python3'", "if", "six", ".", "...
38.7
18.05
def remove_root(self, model, setter=None): ''' Remove a model as root model from this Document. Changes to this model may still trigger ``on_change`` callbacks on this document, if the model is still referred to by other root models. Args: model (Model) : ...
[ "def", "remove_root", "(", "self", ",", "model", ",", "setter", "=", "None", ")", ":", "if", "model", "not", "in", "self", ".", "_roots", ":", "return", "# TODO (bev) ValueError?", "self", ".", "_push_all_models_freeze", "(", ")", "try", ":", "self", ".", ...
41
24.16129
def all(types, unit, precision, as_json): # pylint: disable=redefined-builtin """Get temperatures of all available sensors""" sensors = W1ThermSensor.get_available_sensors(types) temperatures = [] for sensor in sensors: if precision: sensor.set_precision(precision, persist=False) ...
[ "def", "all", "(", "types", ",", "unit", ",", "precision", ",", "as_json", ")", ":", "# pylint: disable=redefined-builtin", "sensors", "=", "W1ThermSensor", ".", "get_available_sensors", "(", "types", ")", "temperatures", "=", "[", "]", "for", "sensor", "in", ...
39.387097
24.129032
def publish_processed_network_packets( name="not-set", task_queue=None, result_queue=None, need_response=False, shutdown_msg="SHUTDOWN"): """ # Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.acc...
[ "def", "publish_processed_network_packets", "(", "name", "=", "\"not-set\"", ",", "task_queue", "=", "None", ",", "result_queue", "=", "None", ",", "need_response", "=", "False", ",", "shutdown_msg", "=", "\"SHUTDOWN\"", ")", ":", "# these keys need to be cycled to pr...
40.066667
16.609524
def edit_customer(self, id_, **kwargs): """ Edits a customer by ID. All fields available at creation can be updated as well. If you want to update hourly rates retroactively, set the argument `update_hourly_rate_on_time_entries` to True. """ data = self._wrap_dict("custom...
[ "def", "edit_customer", "(", "self", ",", "id_", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "_wrap_dict", "(", "\"customer\"", ",", "kwargs", ")", "return", "self", ".", "patch", "(", "\"/customers/{}.json\"", ".", "format", "(", "id_",...
49.5
17
def build_search_otu_table(self, search_results_list, base_list, output_path): ''' Build an OTU from SequenceSearchResult objects Parameters ---------- search_results_list: list Iterable if SequenceSearchResult objects. e.g. [SequenceSearchRes...
[ "def", "build_search_otu_table", "(", "self", ",", "search_results_list", ",", "base_list", ",", "output_path", ")", ":", "db_count", "=", "self", ".", "_interpret_hits", "(", "search_results_list", ",", "base_list", ")", "self", ".", "_write_results", "(", "db_co...
37.045455
22.409091
def move(self, point: Point) -> 'Location': """ Alter the point stored in the location while preserving the labware. This returns a new Location and does not alter the current one. It should be used like .. code-block:: python >>> loc = Location(Point(1, 1, 1), 'Hi...
[ "def", "move", "(", "self", ",", "point", ":", "Point", ")", "->", "'Location'", ":", "return", "self", ".", "_replace", "(", "point", "=", "self", ".", "point", "+", "point", ")" ]
34.125
20.625
def connect(self, func=None, event=None, set_method=False): """Register a callback function to a given event. To register a callback function to the `spam` event, where `obj` is an instance of a class deriving from `EventEmitter`: ```python @obj.connect def on_spam(arg1...
[ "def", "connect", "(", "self", ",", "func", "=", "None", ",", "event", "=", "None", ",", "set_method", "=", "False", ")", ":", "if", "func", "is", "None", ":", "return", "partial", "(", "self", ".", "connect", ",", "set_method", "=", "set_method", ")...
29.647059
23.823529
def _insert(self, namespace, stream, events, configuration): """ `stream` is the name of a stream and `events` is a list of (TimeUUID, event) to insert. Make room for the events to insert if necessary by deleting the oldest events. Then insert each event in time sorted order. """ max_items =...
[ "def", "_insert", "(", "self", ",", "namespace", ",", "stream", ",", "events", ",", "configuration", ")", ":", "max_items", "=", "configuration", "[", "'max_items'", "]", "for", "_id", ",", "event", "in", "events", ":", "while", "len", "(", "self", ".", ...
44.416667
15.583333
def fw_romaji_lt(full, regular): ''' Generates a lookup table with the fullwidth rōmaji characters on the left side, and the regular rōmaji characters as the values. ''' lt = {} for n in range(len(full)): fw = full[n] reg = regular[n] lt[fw] = reg return lt
[ "def", "fw_romaji_lt", "(", "full", ",", "regular", ")", ":", "lt", "=", "{", "}", "for", "n", "in", "range", "(", "len", "(", "full", ")", ")", ":", "fw", "=", "full", "[", "n", "]", "reg", "=", "regular", "[", "n", "]", "lt", "[", "fw", "...
24.916667
24.25
def _handle_tag_master_disconnected_failback(self, tag, data): ''' Handle a master_disconnected_failback event ''' # if the master disconnect event is for a different master, raise an exception if tag.startswith(master_event(type='disconnected')) and data['master'] != self.opts['...
[ "def", "_handle_tag_master_disconnected_failback", "(", "self", ",", "tag", ",", "data", ")", ":", "# if the master disconnect event is for a different master, raise an exception", "if", "tag", ".", "startswith", "(", "master_event", "(", "type", "=", "'disconnected'", ")",...
53.547826
25.669565
def render_form_errors(form, error_types="non_field_errors", **kwargs): """ Render form errors to a Bootstrap layout """ renderer_cls = get_form_renderer(**kwargs) return renderer_cls(form, **kwargs).render_errors(error_types)
[ "def", "render_form_errors", "(", "form", ",", "error_types", "=", "\"non_field_errors\"", ",", "*", "*", "kwargs", ")", ":", "renderer_cls", "=", "get_form_renderer", "(", "*", "*", "kwargs", ")", "return", "renderer_cls", "(", "form", ",", "*", "*", "kwarg...
40.166667
11.166667
def build_from_dict(self, tax_benefit_system, input_dict): """ Build a simulation from ``input_dict`` This method uses :any:`build_from_entities` if entities are fully specified, or :any:`build_from_variables` if not. :param dict input_dict: A dict represeting the input of ...
[ "def", "build_from_dict", "(", "self", ",", "tax_benefit_system", ",", "input_dict", ")", ":", "input_dict", "=", "self", ".", "explicit_singular_entities", "(", "tax_benefit_system", ",", "input_dict", ")", "if", "any", "(", "key", "in", "tax_benefit_system", "."...
47.733333
31.2
def get(self, label_sn): """ Get tags by a label's sn key :param label_sn: A corresponding label's ``sn`` key. :type label_sn: str or int :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :...
[ "def", "get", "(", "self", ",", "label_sn", ")", ":", "tags", "=", "self", ".", "list", "(", ")", "return", "[", "tag", "for", "tag", "in", "tags", "if", "str", "(", "label_sn", ")", "in", "tag", ".", "get", "(", "'args'", ",", "{", "}", ")", ...
28.909091
20
def from_text_list(name, ttl, rdclass, rdtype, text_rdatas): """Create an RRset with the specified name, TTL, class, and type, and with the specified list of rdatas in text format. @rtype: dns.rrset.RRset object """ if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None)...
[ "def", "from_text_list", "(", "name", ",", "ttl", ",", "rdclass", ",", "rdtype", ",", "text_rdatas", ")", ":", "if", "isinstance", "(", "name", ",", "(", "str", ",", "unicode", ")", ")", ":", "name", "=", "dns", ".", "name", ".", "from_text", "(", ...
34.894737
13.052632
def write( self, mi_cmd_to_write, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True, read_response=True, ): """Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec. Args: mi_cmd_to_write (str or ...
[ "def", "write", "(", "self", ",", "mi_cmd_to_write", ",", "timeout_sec", "=", "DEFAULT_GDB_TIMEOUT_SEC", ",", "raise_error_on_timeout", "=", "True", ",", "read_response", "=", "True", ",", ")", ":", "self", ".", "verify_valid_gdb_subprocess", "(", ")", "if", "ti...
40.298507
23.223881
def get_access_token(self, method='POST', decoder=parse_utf8_qsl, key='access_token', **kwargs): ''' Returns an access token. :param method: A string representation of the HTTP method to be used,...
[ "def", "get_access_token", "(", "self", ",", "method", "=", "'POST'", ",", "decoder", "=", "parse_utf8_qsl", ",", "key", "=", "'access_token'", ",", "*", "*", "kwargs", ")", ":", "r", "=", "self", ".", "get_raw_access_token", "(", "method", ",", "*", "*"...
38.130435
17.782609
def autocorrelation(ts, normalized=False, unbiased=False): """ Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve s...
[ "def", "autocorrelation", "(", "ts", ",", "normalized", "=", "False", ",", "unbiased", "=", "False", ")", ":", "ts", "=", "np", ".", "squeeze", "(", "ts", ")", "if", "ts", ".", "ndim", "<=", "1", ":", "if", "normalized", ":", "ts", "=", "(", "ts"...
41.088889
21.311111
def greedy_trails(subg, odds, verbose): '''Greedily select trails by making the longest you can until the end''' if verbose: print('\tCreating edge map') edges = defaultdict(list) for x,y in subg.edges(): edges[x].append(y) edges[y].append(x) if verbose: print('\tS...
[ "def", "greedy_trails", "(", "subg", ",", "odds", ",", "verbose", ")", ":", "if", "verbose", ":", "print", "(", "'\\tCreating edge map'", ")", "edges", "=", "defaultdict", "(", "list", ")", "for", "x", ",", "y", "in", "subg", ".", "edges", "(", ")", ...
25.5625
16.875
def stratified_kfold(df, n_folds): """ Create stratified k-folds from an indexed dataframe """ sessions = pd.DataFrame.from_records(list(df.index.unique())).groupby(0).apply(lambda x: x[1].unique()) sessions.apply(lambda x: np.random.shuffle(x)) folds = [] for i in range(n_folds): id...
[ "def", "stratified_kfold", "(", "df", ",", "n_folds", ")", ":", "sessions", "=", "pd", ".", "DataFrame", ".", "from_records", "(", "list", "(", "df", ".", "index", ".", "unique", "(", ")", ")", ")", ".", "groupby", "(", "0", ")", ".", "apply", "(",...
47.166667
25.166667
def unauthorize_guest(self, guest_mac): """ Unauthorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff """ cmd = 'unauthorize-guest' js = {'mac': guest_mac} return self._run_command(cmd, params=js)
[ "def", "unauthorize_guest", "(", "self", ",", "guest_mac", ")", ":", "cmd", "=", "'unauthorize-guest'", "js", "=", "{", "'mac'", ":", "guest_mac", "}", "return", "self", ".", "_run_command", "(", "cmd", ",", "params", "=", "js", ")" ]
28.181818
15.090909
def perform_create(self, serializer): """Create a resource.""" with transaction.atomic(): instance = serializer.save() # Assign all permissions to the object contributor. assign_contributor_permissions(instance)
[ "def", "perform_create", "(", "self", ",", "serializer", ")", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "instance", "=", "serializer", ".", "save", "(", ")", "# Assign all permissions to the object contributor.", "assign_contributor_permissions", "(", ...
36.857143
12
def is_instance(state, inst, not_instance_msg=None): """Check whether an object is an instance of a certain class. ``is_instance()`` can currently only be used when chained from ``check_object()``, the function that is used to 'zoom in' on the object of interest. Args: inst (class): The class ...
[ "def", "is_instance", "(", "state", ",", "inst", ",", "not_instance_msg", "=", "None", ")", ":", "state", ".", "assert_is", "(", "[", "\"object_assignments\"", "]", ",", "\"is_instance\"", ",", "[", "\"check_object\"", "]", ")", "sol_name", "=", "state", "."...
34.688889
26.511111
def get_chain(self, use_login=False, use_fork=False): """ Return the :class:`mitogen.parent.CallChain` to use for executing function calls. :param bool use_login: If :data:`True`, always return the chain for the login account rather than any active become user. ...
[ "def", "get_chain", "(", "self", ",", "use_login", "=", "False", ",", "use_fork", "=", "False", ")", ":", "self", ".", "_connect", "(", ")", "if", "use_login", ":", "return", "self", ".", "login_context", ".", "default_call_chain", "# See FORK_SUPPORTED commen...
41.368421
18
def insert(self, index = 0, *widgets): """insert widget in the sprites list at the given index. by default will prepend.""" for widget in widgets: self._add(widget, index) index +=1 # as we are moving forwards self._sort()
[ "def", "insert", "(", "self", ",", "index", "=", "0", ",", "*", "widgets", ")", ":", "for", "widget", "in", "widgets", ":", "self", ".", "_add", "(", "widget", ",", "index", ")", "index", "+=", "1", "# as we are moving forwards", "self", ".", "_sort", ...
38.857143
6.428571
def centroid(self): """ The point in space which is the average of the triangle centroids weighted by the area of each triangle. This will be valid even for non- watertight meshes, unlike self.center_mass Returns ---------- centroid : (3,) float ...
[ "def", "centroid", "(", "self", ")", ":", "# use the centroid of each triangle weighted by", "# the area of the triangle to find the overall centroid", "centroid", "=", "np", ".", "average", "(", "self", ".", "triangles_center", ",", "axis", "=", "0", ",", "weights", "=...
32.666667
17.142857
def loop(self): """ this function will be called every self.dt_set seconds request data tm_wday 0=Monday tm_yday """ today = date.today() # only start new jobs after change the day changed if self._current_day != gmtim...
[ "def", "loop", "(", "self", ")", ":", "today", "=", "date", ".", "today", "(", ")", "# only start new jobs after change the day changed", "if", "self", ".", "_current_day", "!=", "gmtime", "(", ")", ".", "tm_yday", ":", "self", ".", "_current_day", "=", "gmt...
53.669355
28.959677
def _read(self): """ Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise. """ event = self._stick_file.read(self.EVENT_SIZE) (tv_sec, tv_usec, ...
[ "def", "_read", "(", "self", ")", ":", "event", "=", "self", ".", "_stick_file", ".", "read", "(", "self", ".", "EVENT_SIZE", ")", "(", "tv_sec", ",", "tv_usec", ",", "type", ",", "code", ",", "value", ")", "=", "struct", ".", "unpack", "(", "self"...
42.08
15.52
def socket_recvall(socket, length, bufsize=4096): """A helper method to read of bytes from a socket to a maximum length""" data = b"" while len(data) < length: data += socket.recv(bufsize) return data
[ "def", "socket_recvall", "(", "socket", ",", "length", ",", "bufsize", "=", "4096", ")", ":", "data", "=", "b\"\"", "while", "len", "(", "data", ")", "<", "length", ":", "data", "+=", "socket", ".", "recv", "(", "bufsize", ")", "return", "data" ]
36.5
12.5
def get_default_value_by_type(type_, state=None): """ Java specify defaults values for primitive and reference types. This method returns the default value for a given type. :param str type_: Name of type. :return: Default value for this type. """ if...
[ "def", "get_default_value_by_type", "(", "type_", ",", "state", "=", "None", ")", ":", "if", "type_", "in", "[", "'byte'", ",", "'char'", ",", "'short'", ",", "'int'", ",", "'boolean'", "]", ":", "return", "BVS", "(", "'default_value_{}'", ".", "format", ...
49.909091
21.242424
def open(filename, frame='unspecified'): """Create a PointCloud from data saved in a file. Parameters ---------- filename : :obj:`str` The file to load data from. frame : :obj:`str` The frame to apply to the created PointCloud. Returns -...
[ "def", "open", "(", "filename", ",", "frame", "=", "'unspecified'", ")", ":", "data", "=", "BagOfPoints", ".", "load_data", "(", "filename", ")", "return", "PointCloud", "(", "data", ",", "frame", ")" ]
27.388889
16.611111
def setupitems(self): """Lookup available setup items :returns: catalog brains """ query = { "path": { "query": api.get_path(self.setup), "depth": 1, }, } items = api.search(query, "portal_catalog") # filter...
[ "def", "setupitems", "(", "self", ")", ":", "query", "=", "{", "\"path\"", ":", "{", "\"query\"", ":", "api", ".", "get_path", "(", "self", ".", "setup", ")", ",", "\"depth\"", ":", "1", ",", "}", ",", "}", "items", "=", "api", ".", "search", "("...
30
16.727273
def encode(self, s): """ Encode special characters found in string I{s}. @param s: A string to encode. @type s: str @return: The encoded string. @rtype: str """ if isinstance(s, str) and self.needsEncoding(s): for x in self.encodings: ...
[ "def", "encode", "(", "self", ",", "s", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", "and", "self", ".", "needsEncoding", "(", "s", ")", ":", "for", "x", "in", "self", ".", "encodings", ":", "s", "=", "re", ".", "sub", "(", "x", "...
29.833333
10.666667
def __map_entity(self, entity: dal.AssetClass) -> AssetClass: """ maps the entity onto the model object """ mapper = self.__get_mapper() ac = mapper.map_entity(entity) return ac
[ "def", "__map_entity", "(", "self", ",", "entity", ":", "dal", ".", "AssetClass", ")", "->", "AssetClass", ":", "mapper", "=", "self", ".", "__get_mapper", "(", ")", "ac", "=", "mapper", ".", "map_entity", "(", "entity", ")", "return", "ac" ]
41
10
def fcoe_get_interface_input_fcoe_intf_include_stats(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface input = ET.SubElement(fcoe_get_interface, "input") fcoe...
[ "def", "fcoe_get_interface_input_fcoe_intf_include_stats", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcoe_get_interface", "=", "ET", ".", "Element", "(", "\"fcoe_get_interface\"", ")", "config", ...
45.5
18.25
def rename(self, old_label_name, new_label_name): """ Take into account that a label has been renamed """ assert(old_label_name != new_label_name) self._bayes.pop(old_label_name) old_baye_dir = self._get_baye_dir(old_label_name) new_baye_dir = self._get_baye_dir(n...
[ "def", "rename", "(", "self", ",", "old_label_name", ",", "new_label_name", ")", ":", "assert", "(", "old_label_name", "!=", "new_label_name", ")", "self", ".", "_bayes", ".", "pop", "(", "old_label_name", ")", "old_baye_dir", "=", "self", ".", "_get_baye_dir"...
43.75
13.75
def _makedos(self, ax, dos_plotter, dos_options, dos_label=None): """This is basically the same as the SDOSPlotter get_plot function.""" # don't use first 4 colours; these are the band structure line colours cycle = cycler( 'color', rcParams['axes.prop_cycle'].by_key()['color'][4:])...
[ "def", "_makedos", "(", "self", ",", "ax", ",", "dos_plotter", ",", "dos_options", ",", "dos_label", "=", "None", ")", ":", "# don't use first 4 colours; these are the band structure line colours", "cycle", "=", "cycler", "(", "'color'", ",", "rcParams", "[", "'axes...
42.631579
18.789474
def num(value): """Convert a value from one of several bases to an int.""" if re_hex_num.match(value): return int(value, base=16) else: return int(value)
[ "def", "num", "(", "value", ")", ":", "if", "re_hex_num", ".", "match", "(", "value", ")", ":", "return", "int", "(", "value", ",", "base", "=", "16", ")", "else", ":", "return", "int", "(", "value", ")" ]
29.333333
14.333333
def xor_key(first, second, trafaret): """ xor_key - takes `first` and `second` key names and `trafaret`. Checks if we have only `first` or only `second` in data, not both, and at least one. Then checks key value against trafaret. """ trafaret = t.Trafaret._trafaret(trafaret) def check...
[ "def", "xor_key", "(", "first", ",", "second", ",", "trafaret", ")", ":", "trafaret", "=", "t", ".", "Trafaret", ".", "_trafaret", "(", "trafaret", ")", "def", "check_", "(", "value", ")", ":", "if", "(", "first", "in", "value", ")", "^", "(", "sec...
42.826087
27.434783
def to_pb(self): """Converts the column family to a protobuf. :rtype: :class:`.table_v2_pb2.ColumnFamily` :returns: The converted current object. """ if self.gc_rule is None: return table_v2_pb2.ColumnFamily() else: return table_v2_pb2.ColumnFamil...
[ "def", "to_pb", "(", "self", ")", ":", "if", "self", ".", "gc_rule", "is", "None", ":", "return", "table_v2_pb2", ".", "ColumnFamily", "(", ")", "else", ":", "return", "table_v2_pb2", ".", "ColumnFamily", "(", "gc_rule", "=", "self", ".", "gc_rule", ".",...
34.2
15.7
def remove_device(self, path): "Remove a device from the daemon's internal search list." if self.__get_control_socket(): self.sock.sendall("-%s\r\n\x00" % path) self.sock.recv(12) self.sock.close()
[ "def", "remove_device", "(", "self", ",", "path", ")", ":", "if", "self", ".", "__get_control_socket", "(", ")", ":", "self", ".", "sock", ".", "sendall", "(", "\"-%s\\r\\n\\x00\"", "%", "path", ")", "self", ".", "sock", ".", "recv", "(", "12", ")", ...
40.666667
11.333333
def _elapsed_time(begin_time, end_time): """Assuming format YYYY-MM-DD hh:mm:ss Returns the elapsed time in seconds """ bt = _str2datetime(begin_time) et = _str2datetime(end_time) return float((et - bt).seconds)
[ "def", "_elapsed_time", "(", "begin_time", ",", "end_time", ")", ":", "bt", "=", "_str2datetime", "(", "begin_time", ")", "et", "=", "_str2datetime", "(", "end_time", ")", "return", "float", "(", "(", "et", "-", "bt", ")", ".", "seconds", ")" ]
22.9
14
def parse_exposure(self, node): """ Parses <Exposure> @param node: Node containing the <Exposure> element @type node: xml.etree.Element @raise ParseError: Raised when the exposure name is not being defined in the context of a component type. """ if self...
[ "def", "parse_exposure", "(", "self", ",", "node", ")", ":", "if", "self", ".", "current_component_type", "==", "None", ":", "self", ".", "raise_error", "(", "'Exposures must be defined in a component type'", ")", "try", ":", "name", "=", "node", ".", "lattrib",...
31.142857
23.214286
def index(self, value): """ Return the smallest index of the row(s) with this column equal to value. """ for i in xrange(len(self.parentNode)): if getattr(self.parentNode[i], self.Name) == value: return i raise ValueError(value)
[ "def", "index", "(", "self", ",", "value", ")", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ".", "parentNode", ")", ")", ":", "if", "getattr", "(", "self", ".", "parentNode", "[", "i", "]", ",", "self", ".", "Name", ")", "==", "va...
26.555556
12.777778
def _assign_to_field(obj, name, val): 'Helper to assign an arbitrary value to a protobuf field' target = getattr(obj, name) if isinstance(target, containers.RepeatedScalarFieldContainer): target.append(val) elif isinstance(target, containers.RepeatedCompositeFieldContainer): target = ta...
[ "def", "_assign_to_field", "(", "obj", ",", "name", ",", "val", ")", ":", "target", "=", "getattr", "(", "obj", ",", "name", ")", "if", "isinstance", "(", "target", ",", "containers", ".", "RepeatedScalarFieldContainer", ")", ":", "target", ".", "append", ...
39.666667
18.466667
def add_value(self, name, value): """ Add a new value to the list. :param str name: name of the value that is being parsed :param str value: value that is being parsed :raises ietfparse.errors.MalformedLinkValue: if *strict mode* is enabled and a validation error ...
[ "def", "add_value", "(", "self", ",", "name", ",", "value", ")", ":", "try", ":", "if", "self", ".", "_rfc_values", "[", "name", "]", "is", "None", ":", "self", ".", "_rfc_values", "[", "name", "]", "=", "value", "elif", "self", ".", "strict", ":",...
36.3125
19.8125
def bind_port(requested_port): """Bind sockets to an available port, returning sockets and the bound port.""" sockets = tornado.netutil.bind_sockets(requested_port) if requested_port != 0: return sockets, requested_port # Get the actual port number. for s in sockets: host, port = s.getsockname()[:2]...
[ "def", "bind_port", "(", "requested_port", ")", ":", "sockets", "=", "tornado", ".", "netutil", ".", "bind_sockets", "(", "requested_port", ")", "if", "requested_port", "!=", "0", ":", "return", "sockets", ",", "requested_port", "# Get the actual port number.", "f...
30.071429
17.785714
def select(self, domain_or_name, query='', next_token=None, consistent_read=False): """ Returns a set of Attributes for item names within domain_name that match the query. The query must be expressed in using the SELECT style syntax rather than the original SimpleDB query...
[ "def", "select", "(", "self", ",", "domain_or_name", ",", "query", "=", "''", ",", "next_token", "=", "None", ",", "consistent_read", "=", "False", ")", ":", "domain", ",", "domain_name", "=", "self", ".", "get_domain_and_name", "(", "domain_or_name", ")", ...
43.285714
20.485714
def MapByteStream(self, byte_stream, byte_offset=0, **unused_kwargs): """Maps the data type on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. Returns: object: mapped value. Raises: MappingError: i...
[ "def", "MapByteStream", "(", "self", ",", "byte_stream", ",", "byte_offset", "=", "0", ",", "*", "*", "unused_kwargs", ")", ":", "return", "byte_stream", "[", "byte_offset", ":", "byte_offset", "+", "self", ".", "byte_size", "]" ]
30.133333
23.6
def _connect_signals(): """Connect up post_save, post_delete signals for models.""" for index in settings.get_index_names(): for model in settings.get_index_models(index): _connect_model_signals(model)
[ "def", "_connect_signals", "(", ")", ":", "for", "index", "in", "settings", ".", "get_index_names", "(", ")", ":", "for", "model", "in", "settings", ".", "get_index_models", "(", "index", ")", ":", "_connect_model_signals", "(", "model", ")" ]
45
7.2
def submit_task(self, function_descriptor, args, actor_id=None, actor_handle_id=None, actor_counter=0, actor_creation_id=None, actor_creation_dummy_object_id=None, ...
[ "def", "submit_task", "(", "self", ",", "function_descriptor", ",", "args", ",", "actor_id", "=", "None", ",", "actor_handle_id", "=", "None", ",", "actor_counter", "=", "0", ",", "actor_creation_id", "=", "None", ",", "actor_creation_dummy_object_id", "=", "Non...
43.345324
17.503597
def _utc_datetime_to_epoch(self, activity_datetime): """ Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be co...
[ "def", "_utc_datetime_to_epoch", "(", "self", ",", "activity_datetime", ")", ":", "if", "isinstance", "(", "activity_datetime", ",", "str", ")", ":", "activity_datetime", "=", "arrow", ".", "get", "(", "activity_datetime", ")", ".", "datetime", "assert", "isinst...
45.875
23.5
def select(self, limit=0): """Match all tags under the targeted tag.""" if limit < 1: limit = None for child in self.get_descendants(self.tag): if self.match(child): yield child if limit is not None: limit -= 1 ...
[ "def", "select", "(", "self", ",", "limit", "=", "0", ")", ":", "if", "limit", "<", "1", ":", "limit", "=", "None", "for", "child", "in", "self", ".", "get_descendants", "(", "self", ".", "tag", ")", ":", "if", "self", ".", "match", "(", "child",...
28
14.769231
def update_or_create(self, model, **kwargs): '''Update or create a new instance of ``model``. This method can raise an exception if the ``kwargs`` dictionary contains field data that does not validate. :param model: a :class:`StdModel` :param kwargs: dictionary of parame...
[ "def", "update_or_create", "(", "self", ",", "model", ",", "*", "*", "kwargs", ")", ":", "backend", "=", "self", ".", "model", "(", "model", ")", ".", "backend", "return", "backend", ".", "execute", "(", "self", ".", "_update_or_create", "(", "model", ...
44.769231
21.076923
def get_scoreboard(year, month, day): """Return the game file for a certain day matching certain criteria.""" try: data = urlopen(BASE_URL.format(year, month, day) + 'scoreboard.xml') except HTTPError: data = os.path.join(PWD, 'default.xml') return data
[ "def", "get_scoreboard", "(", "year", ",", "month", ",", "day", ")", ":", "try", ":", "data", "=", "urlopen", "(", "BASE_URL", ".", "format", "(", "year", ",", "month", ",", "day", ")", "+", "'scoreboard.xml'", ")", "except", "HTTPError", ":", "data", ...
39.857143
17.428571
def mount(self, mountpoint, app, into_worker=False): """Load application under mountpoint. Example: * .mount('', 'app0.py') -- Root URL part * .mount('/app1', 'app1.py') -- URL part * .mount('/pinax/here', '/var/www/pinax/deploy/pinax.wsgi') * .mount('the...
[ "def", "mount", "(", "self", ",", "mountpoint", ",", "app", ",", "into_worker", "=", "False", ")", ":", "# todo check worker mount -- uwsgi_init_worker_mount_app() expects worker://", "self", ".", "_set", "(", "'worker-mount'", "if", "into_worker", "else", "'mount'", ...
47.103448
35.241379
def reduce_by(fn: Callable[[T1, T1], T1]) -> Callable[[ActualIterable[T1]], T1]: """ >>> from Redy.Collections import Traversal, Flow >>> def mul(a: int, b: int): return a * b >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.reduce_by(mul)].unbox >>> assert x is 6 """ retur...
[ "def", "reduce_by", "(", "fn", ":", "Callable", "[", "[", "T1", ",", "T1", "]", ",", "T1", "]", ")", "->", "Callable", "[", "[", "ActualIterable", "[", "T1", "]", "]", ",", "T1", "]", ":", "return", "lambda", "collection", ":", "functools", ".", ...
40.555556
12.555556
def generate(basename, xml_list): '''generate complete MAVLink Java implemenation''' for xml in xml_list: generate_one(basename, xml) generate_enums(basename, xml) generate_MAVLinkMessage(basename, xml_list) copy_fixed_headers(basename, xml_list[0])
[ "def", "generate", "(", "basename", ",", "xml_list", ")", ":", "for", "xml", "in", "xml_list", ":", "generate_one", "(", "basename", ",", "xml", ")", "generate_enums", "(", "basename", ",", "xml", ")", "generate_MAVLinkMessage", "(", "basename", ",", "xml_li...
39.857143
8.714286
def update_folder_name(self, name, update_folder_data=True): """ Change this folder name :param str name: new name to change to :param bool update_folder_data: whether or not to re-fetch the data :return: Updated or Not :rtype: bool """ if self.root: ...
[ "def", "update_folder_name", "(", "self", ",", "name", ",", "update_folder_data", "=", "True", ")", ":", "if", "self", ".", "root", ":", "return", "False", "if", "not", "name", ":", "return", "False", "url", "=", "self", ".", "build_url", "(", "self", ...
33.029412
22.911765
def listener(self, sock, *args): '''Asynchronous connection listener. Starts a handler for each connection.''' conn, addr = sock.accept() f = conn.makefile(conn) self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO) print(_("Connected")) GObject.io_add_watch(...
[ "def", "listener", "(", "self", ",", "sock", ",", "*", "args", ")", ":", "conn", ",", "addr", "=", "sock", ".", "accept", "(", ")", "f", "=", "conn", ".", "makefile", "(", "conn", ")", "self", ".", "shell", "=", "ShoebotCmd", "(", "self", ".", ...
41.166667
19.5
def update_book(self, id, body, doc_type='book'): ''' Update a book The "body" is merged with the current one. Yes, it is NOT overwritten. In case of concurrency conflict this function could raise `elasticsearch.ConflictError` ''' # note that we ...
[ "def", "update_book", "(", "self", ",", "id", ",", "body", ",", "doc_type", "=", "'book'", ")", ":", "# note that we are NOT overwriting all the _source, just merging", "book", "=", "self", ".", "get_book_by_id", "(", "id", ")", "book", "[", "'_source'", "]", "....
40.4375
19.5625
def query_model(self, model, condition=None, offset=None, limit=None, group_by=None, having=None, order_by=None, fields=None): """ Query all records with limit and offset, it's used for pagination query. """ if self._query is not None: query = self._...
[ "def", "query_model", "(", "self", ",", "model", ",", "condition", "=", "None", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "group_by", "=", "None", ",", "having", "=", "None", ",", "order_by", "=", "None", ",", "fields", "=", "None",...
38.588235
12.117647
def get_unspent(cls, address): """Gets all unspent transaction outputs belonging to an address. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``list`` of :class:`~bit.network.meta.Unspent` """ ...
[ "def", "get_unspent", "(", "cls", ",", "address", ")", ":", "for", "api_call", "in", "cls", ".", "GET_UNSPENT_MAIN", ":", "try", ":", "return", "api_call", "(", "address", ")", "except", "cls", ".", "IGNORED_ERRORS", ":", "pass", "raise", "ConnectionError", ...
33
16.0625
def energy_based_strength_of_connection(A, theta=0.0, k=2): """Energy Strength Measure. Compute a strength of connection matrix using an energy-based measure. Parameters ---------- A : sparse-matrix matrix from which to generate strength of connection information theta : float ...
[ "def", "energy_based_strength_of_connection", "(", "A", ",", "theta", "=", "0.0", ",", "k", "=", "2", ")", ":", "if", "(", "theta", "<", "0", ")", ":", "raise", "ValueError", "(", "'expected a positive theta'", ")", "if", "not", "sparse", ".", "isspmatrix"...
34.186207
21.468966
def mergeActors(actors, tol=0): """ Build a new actor formed by the fusion of the polydatas of input objects. Similar to Assembly, but in this case the input objects become a single mesh. .. hint:: |thinplate_grid| |thinplate_grid.py|_ """ polylns = vtk.vtkAppendPolyData() for a in actors: ...
[ "def", "mergeActors", "(", "actors", ",", "tol", "=", "0", ")", ":", "polylns", "=", "vtk", ".", "vtkAppendPolyData", "(", ")", "for", "a", "in", "actors", ":", "polylns", ".", "AddInputData", "(", "a", ".", "polydata", "(", ")", ")", "polylns", ".",...
32.384615
16.538462
def add(self, name, filt, info='', params=(), setn=None): """ Add filter. Parameters ---------- name : str filter name filt : array_like boolean filter array info : str informative description of the filter params : tup...
[ "def", "add", "(", "self", ",", "name", ",", "filt", ",", "info", "=", "''", ",", "params", "=", "(", ")", ",", "setn", "=", "None", ")", ":", "iname", "=", "'{:.0f}_'", ".", "format", "(", "self", ".", "n", ")", "+", "name", "self", ".", "in...
23.775
16.925
def _write_symlink(self, zf, link_target, link_path): """Package symlinks with appropriate zipfile metadata.""" info = zipfile.ZipInfo() info.filename = link_path info.create_system = 3 # Magic code for symlinks / py2/3 compat # 27166663808 = (stat.S_IFLNK | 0755) << 16 ...
[ "def", "_write_symlink", "(", "self", ",", "zf", ",", "link_target", ",", "link_path", ")", ":", "info", "=", "zipfile", ".", "ZipInfo", "(", ")", "info", ".", "filename", "=", "link_path", "info", ".", "create_system", "=", "3", "# Magic code for symlinks /...
43.222222
6.666667
def dashfn(handle, lenout=_default_len_out): """ Return the name of the DAS file associated with a handle. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dashfn_c.html :param handle: Handle of a DAS file. :type handle: int :param lenout: Length of output file name string. :ty...
[ "def", "dashfn", "(", "handle", ",", "lenout", "=", "_default_len_out", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "namlen", "=", "ctypes", ".", "c_int", "(", "lenout", ")", "fname", "=", "stypes", ".", "stringToCharP", "(", "...
31.888889
13