text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_library_mapping(logger, prod_folder, token, host): """ returns a pair of library mappings, the first mapping library uri to a library name for all libraries in the production folder, and the second mapping library name to info for libraries in the production folder with parsable versions ...
[ "def", "get_library_mapping", "(", "logger", ",", "prod_folder", ",", "token", ",", "host", ")", ":", "res", "=", "requests", ".", "get", "(", "host", "+", "'/api/1.2/libraries/list'", ",", "auth", "=", "(", "'token'", ",", "token", ")", ",", ")", "if", ...
37.611111
16.833333
def address(self, num): """Search for company addresses by company number. Args: num (str): Company number to search on. """ url_root = "company/{}/registered-office-address" baseuri = self._BASE_URI + url_root.format(num) res = self.session.get(baseuri) ...
[ "def", "address", "(", "self", ",", "num", ")", ":", "url_root", "=", "\"company/{}/registered-office-address\"", "baseuri", "=", "self", ".", "_BASE_URI", "+", "url_root", ".", "format", "(", "num", ")", "res", "=", "self", ".", "session", ".", "get", "("...
32.545455
13.909091
def get_composition_form_for_create(self, composition_record_types): """Gets the composition form for creating new compositions. A new form should be requested for each create transaction. arg: composition_record_types (osid.type.Type[]): array of composition record types ...
[ "def", "get_composition_form_for_create", "(", "self", ",", "composition_record_types", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.get_resource_form_for_create_template", "for", "arg", "in", "composition_record_types", ":", "if", "not", "isin...
47.722222
18.888889
def request_ufp_ride(api_client): """Use an UberRidesClient to request a ride and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. Returns The unique ID of the requested ride. """ try: estimate = api...
[ "def", "request_ufp_ride", "(", "api_client", ")", ":", "try", ":", "estimate", "=", "api_client", ".", "estimate_ride", "(", "product_id", "=", "UFP_PRODUCT_ID", ",", "start_latitude", "=", "START_LAT", ",", "start_longitude", "=", "START_LNG", ",", "end_latitude...
27.125
15.05
def comports(vid_pid=None, include_all=False, check_available=True, only_available=False): ''' .. versionchanged:: 0.9 Add :data:`check_available` keyword argument to optionally check if each port is actually available by attempting to open a temporary connection. A...
[ "def", "comports", "(", "vid_pid", "=", "None", ",", "include_all", "=", "False", ",", "check_available", "=", "True", ",", "only_available", "=", "False", ")", ":", "df_comports", "=", "_comports", "(", ")", "# Extract USB product and vendor IDs from `hwid` entries...
40.876289
22.092784
def _create_text_node(self, root, name, value, cdata=False): ''' Creates and adds a text node @param root:Element Root element @param name:str Tag name @param value:object Text value @param cdata:bool A value indicating whether to use CDATA or not. @return:Node ...
[ "def", "_create_text_node", "(", "self", ",", "root", ",", "name", ",", "value", ",", "cdata", "=", "False", ")", ":", "if", "is_empty_or_none", "(", "value", ")", ":", "return", "if", "type", "(", "value", ")", "==", "date", ":", "value", "=", "date...
31.482759
18.517241
def AsDict(self, dt=True): """ A dict representation of this Comment instance. The return value uses the same key names as the JSON representation. Args: dt (bool): If True, return dates as python datetime objects. If False, return dates as ISO strings. ...
[ "def", "AsDict", "(", "self", ",", "dt", "=", "True", ")", ":", "data", "=", "{", "}", "if", "self", ".", "body", ":", "data", "[", "'body'", "]", "=", "self", ".", "body", "if", "self", ".", "posted_at", ":", "data", "[", "'posted_at'", "]", "...
26.565217
20.913043
def verify(self, msg, sig, key): """ Verify a message signature :param msg: The message :param sig: A signature :param key: A ec.EllipticCurvePublicKey to use for the verification. :raises: BadSignature if the signature can't be verified. :return: True ""...
[ "def", "verify", "(", "self", ",", "msg", ",", "sig", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "ec", ".", "EllipticCurvePublicKey", ")", ":", "raise", "TypeError", "(", "\"The public key must be an instance of \"", "\"ec.EllipticCurvePub...
35.870968
15.677419
def _load_plugin_entrypoints(self): """Load the modules for the psyplot plugins Yields ------ pkg_resources.EntryPoint The entry point for the psyplot plugin module""" from pkg_resources import iter_entry_points def load_plugin(ep): if plugins_en...
[ "def", "_load_plugin_entrypoints", "(", "self", ")", ":", "from", "pkg_resources", "import", "iter_entry_points", "def", "load_plugin", "(", "ep", ")", ":", "if", "plugins_env", "==", "[", "'no'", "]", ":", "return", "False", "elif", "ep", ".", "module_name", ...
35.212121
19.363636
def create_insight(self, project_key, **kwargs): """Create a new insight :param project_key: Project identifier, in the form of projectOwner/projectid :type project_key: str :param title: Insight title :type title: str :param description: Insight description. ...
[ "def", "create_insight", "(", "self", ",", "project_key", ",", "*", "*", "kwargs", ")", ":", "request", "=", "self", ".", "__build_insight_obj", "(", "lambda", ":", "_swagger", ".", "InsightCreateRequest", "(", "title", "=", "kwargs", ".", "get", "(", "'ti...
41.259259
14.148148
def _get_binding_info(hostheader='', ipaddress='*', port=80): ''' Combine the host header, IP address, and TCP port into bindingInformation format. ''' ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', '')) return ret
[ "def", "_get_binding_info", "(", "hostheader", "=", "''", ",", "ipaddress", "=", "'*'", ",", "port", "=", "80", ")", ":", "ret", "=", "r'{0}:{1}:{2}'", ".", "format", "(", "ipaddress", ",", "port", ",", "hostheader", ".", "replace", "(", "' '", ",", "'...
35.857143
33.571429
def optimize(args): """ Gatys et al. CVPR 2017 ref: Image Style Transfer Using Convolutional Neural Networks """ if args.cuda: ctx = mx.gpu(0) else: ctx = mx.cpu(0) # load the content and style target content_image = utils.tensor_load_rgbimage(args.content_image,ctx, size=...
[ "def", "optimize", "(", "args", ")", ":", "if", "args", ".", "cuda", ":", "ctx", "=", "mx", ".", "gpu", "(", "0", ")", "else", ":", "ctx", "=", "mx", ".", "cpu", "(", "0", ")", "# load the content and style target", "content_image", "=", "utils", "."...
40.269231
19
def tryParenthesisBeforeBrace(self, block, column): """ Character at (block, column) has to be a '{'. Now try to find the right line for indentation for constructs like: if (a == b and c == d) { <- check for ')', and find '(', then return its indentation Returns input par...
[ "def", "tryParenthesisBeforeBrace", "(", "self", ",", "block", ",", "column", ")", ":", "text", "=", "block", ".", "text", "(", ")", "[", ":", "column", "-", "1", "]", ".", "rstrip", "(", ")", "if", "not", "text", ".", "endswith", "(", "')'", ")", ...
50.727273
18.363636
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] ...
[ "def", "render_linked_css", "(", "self", ",", "css_files", ":", "Iterable", "[", "str", "]", ")", "->", "str", ":", "paths", "=", "[", "]", "unique_paths", "=", "set", "(", ")", "# type: Set[str]", "for", "path", "in", "css_files", ":", "if", "not", "i...
33.047619
15.952381
def _add_cpu_percent(self, cur_read): """Compute cpu percent basing on the provided utilisation """ for executor_id, cur_data in cur_read.items(): stats = cur_data['statistics'] cpus_limit = stats.get('cpus_limit') cpus_utilisation = stats.get('cpus_utilisatio...
[ "def", "_add_cpu_percent", "(", "self", ",", "cur_read", ")", ":", "for", "executor_id", ",", "cur_data", "in", "cur_read", ".", "items", "(", ")", ":", "stats", "=", "cur_data", "[", "'statistics'", "]", "cpus_limit", "=", "stats", ".", "get", "(", "'cp...
48.666667
9.777778
def is_restricted(self): """ Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices. """ return ( not hasattr(self.choices, 'queryset') or ...
[ "def", "is_restricted", "(", "self", ")", ":", "return", "(", "not", "hasattr", "(", "self", ".", "choices", ",", "'queryset'", ")", "or", "self", ".", "choices", ".", "queryset", ".", "count", "(", ")", ">", "settings", ".", "FOREIGN_KEY_MAX_SELECBOX_ENTR...
44.333333
26.555556
def ball(center, radius=1., bdy=True): '''Returns the indicator function of a ball. :param center: A vector-like numpy array, defining the center of the ball.\n len(center) fixes the dimension. :param radius: Float or int, the radius of the ball :param bdy: Bool, Wh...
[ "def", "ball", "(", "center", ",", "radius", "=", "1.", ",", "bdy", "=", "True", ")", ":", "center", "=", "_np", ".", "array", "(", "center", ")", "# copy input parameter", "dim", "=", "len", "(", "center", ")", "if", "bdy", ":", "def", "ball_indicat...
31.022727
23.613636
def dump(self): """Dump parsed environment variables to a dictionary of simple data types (numbers and strings). """ schema = _dict2schema(self._fields)() dump_result = schema.dump(self._values) return dump_result.data if MARSHMALLOW_VERSION_INFO[0] < 3 else dump_result
[ "def", "dump", "(", "self", ")", ":", "schema", "=", "_dict2schema", "(", "self", ".", "_fields", ")", "(", ")", "dump_result", "=", "schema", ".", "dump", "(", "self", ".", "_values", ")", "return", "dump_result", ".", "data", "if", "MARSHMALLOW_VERSION...
44.571429
14.142857
def from_json_format(conf): '''Convert fields of parsed json dictionary to python format''' if 'fmode' in conf: conf['fmode'] = int(conf['fmode'], 8) if 'dmode' in conf: conf['dmode'] = int(conf['dmode'], 8)
[ "def", "from_json_format", "(", "conf", ")", ":", "if", "'fmode'", "in", "conf", ":", "conf", "[", "'fmode'", "]", "=", "int", "(", "conf", "[", "'fmode'", "]", ",", "8", ")", "if", "'dmode'", "in", "conf", ":", "conf", "[", "'dmode'", "]", "=", ...
38.333333
14
def event_from_item(self, sequenced_item): """ Reconstructs domain event from stored event topic and event attrs. Used in the event store when getting domain events. """ assert isinstance(sequenced_item, self.sequenced_item_class), ( self.sequenced_item_class, type(se...
[ "def", "event_from_item", "(", "self", ",", "sequenced_item", ")", ":", "assert", "isinstance", "(", "sequenced_item", ",", "self", ".", "sequenced_item_class", ")", ",", "(", "self", ".", "sequenced_item_class", ",", "type", "(", "sequenced_item", ")", ")", "...
39.714286
20.571429
def modification_time(self): """dfdatetime.DateTimeValues: modification time or None if not available.""" if self._stat_info is None: return None timestamp = int(self._stat_info.st_mtime) return dfdatetime_posix_time.PosixTime(timestamp=timestamp)
[ "def", "modification_time", "(", "self", ")", ":", "if", "self", ".", "_stat_info", "is", "None", ":", "return", "None", "timestamp", "=", "int", "(", "self", ".", "_stat_info", ".", "st_mtime", ")", "return", "dfdatetime_posix_time", ".", "PosixTime", "(", ...
37.714286
16
def set_default(self, channels=None): '''Setting default voltage ''' if not channels: channels = self._ch_cal.keys() for channel in channels: self.set_voltage(channel, self._ch_cal[channel]['default'], unit='V')
[ "def", "set_default", "(", "self", ",", "channels", "=", "None", ")", ":", "if", "not", "channels", ":", "channels", "=", "self", ".", "_ch_cal", ".", "keys", "(", ")", "for", "channel", "in", "channels", ":", "self", ".", "set_voltage", "(", "channel"...
37.285714
15
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optio...
[ "def", "find_records", "(", "self", ",", "check", ",", "keys", "=", "None", ")", ":", "matches", "=", "self", ".", "_match", "(", "check", ")", "if", "keys", ":", "return", "[", "self", ".", "_extract_subdict", "(", "rec", ",", "keys", ")", "for", ...
31.157895
19.421053
def create_string(self, key, value): """Create method of CRUD operation for string data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write. """ data = None ...
[ "def", "create_string", "(", "self", ",", "key", ",", "value", ")", ":", "data", "=", "None", "if", "key", "is", "not", "None", "and", "value", "is", "not", "None", ":", "if", "isinstance", "(", "value", ",", "(", "bool", ",", "list", ",", "int", ...
37.25
18.55
def set_temperature(self, target_temperature): """ Set the target temperature. """ try: target_temperature = float(target_temperature) except Exception as err: LOG.debug("Thermostat.set_temperature: Exception %s" % (err,)) return False self.writeNodeDa...
[ "def", "set_temperature", "(", "self", ",", "target_temperature", ")", ":", "try", ":", "target_temperature", "=", "float", "(", "target_temperature", ")", "except", "Exception", "as", "err", ":", "LOG", ".", "debug", "(", "\"Thermostat.set_temperature: Exception %s...
44.25
16.875
def _node_name(self, concept): """Return a standardized name for a node given a Concept.""" if (# grounding threshold is specified self.grounding_threshold is not None # The particular eidos ontology grounding (un/wdi/fao) is present and concept.db_refs[self.grounding...
[ "def", "_node_name", "(", "self", ",", "concept", ")", ":", "if", "(", "# grounding threshold is specified", "self", ".", "grounding_threshold", "is", "not", "None", "# The particular eidos ontology grounding (un/wdi/fao) is present", "and", "concept", ".", "db_refs", "["...
53.923077
17.461538
def convert_csv_str_to_list(csv_str: str) -> list: """Convert CSV str to list""" csv_str = re.sub("^\s*{", "", csv_str) csv_str = re.sub("}\s*$", "", csv_str) r = csv.reader([csv_str]) row = list(r)[0] new = [] for col in row: col = re.sub('^\s*"?\s*', "", col) col = re.sub(...
[ "def", "convert_csv_str_to_list", "(", "csv_str", ":", "str", ")", "->", "list", ":", "csv_str", "=", "re", ".", "sub", "(", "\"^\\s*{\"", ",", "\"\"", ",", "csv_str", ")", "csv_str", "=", "re", ".", "sub", "(", "\"}\\s*$\"", ",", "\"\"", ",", "csv_str...
26.285714
15.785714
def _check_authentication(self, request, request_args, request_kwargs): """ Checks a request object to determine if that request contains a valid, and authenticated JWT. It returns a tuple: 1. Boolean whether the request is authenticated with a valid JWT 2. HTTP status c...
[ "def", "_check_authentication", "(", "self", ",", "request", ",", "request_args", ",", "request_kwargs", ")", ":", "try", ":", "is_valid", ",", "status", ",", "reasons", "=", "self", ".", "_verify", "(", "request", ",", "request_args", "=", "request_args", "...
33.076923
18.923077
def disaggregate_radiation(self, method='pot_rad', pot_rad=None): """ Disaggregate solar radiation. Parameters ---------- method : str, optional Disaggregation method. ``pot_rad`` Calculates potential clear-sky hourly radiation and scales...
[ "def", "disaggregate_radiation", "(", "self", ",", "method", "=", "'pot_rad'", ",", "pot_rad", "=", "None", ")", ":", "if", "self", ".", "sun_times", "is", "None", ":", "self", ".", "calc_sun_times", "(", ")", "if", "pot_rad", "is", "None", "and", "metho...
38.295455
23.386364
def set_of(*generators): """ Generates a set consisting solely of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators. """ class SetOfGenerators(ArbitraryInterface): """ A closure class around the generators spec...
[ "def", "set_of", "(", "*", "generators", ")", ":", "class", "SetOfGenerators", "(", "ArbitraryInterface", ")", ":", "\"\"\"\n A closure class around the generators specified above, which\n generates a set of the generators.\n \"\"\"", "@", "classmethod", "def", ...
30.4375
14.9375
def cts_error(self, error_name, message=None): """ Create a CTS Error reply :param error_name: Name of the error :param message: Message of the Error :return: CTS Error Response with information (XML) """ self.nautilus_extension.logger.info( "CTS error thrown...
[ "def", "cts_error", "(", "self", ",", "error_name", ",", "message", "=", "None", ")", ":", "self", ".", "nautilus_extension", ".", "logger", ".", "info", "(", "\"CTS error thrown {} for {} ({})\"", ".", "format", "(", "error_name", ",", "request", ".", "query_...
34
11.5
def parse_known_chained(self, args=None): """ Parse the argument directly to the function used for setup This function parses the command line arguments to the function that has been used for the :meth:`setup_args` method. Parameters ---------- args: list ...
[ "def", "parse_known_chained", "(", "self", ",", "args", "=", "None", ")", ":", "ns", ",", "remainder", "=", "self", ".", "parse_known_args", "(", "args", ")", "kws", "=", "vars", "(", "ns", ")", "return", "self", ".", "_parse2subparser_funcs", "(", "kws"...
28.107143
23.535714
def _apply(self, plan): '''Required function of manager.py to actually apply a record change. :param plan: Contains the zones and changes to be made :type plan: octodns.provider.base.Plan :type return: void ''' desired = plan.desired changes = plan....
[ "def", "_apply", "(", "self", ",", "plan", ")", ":", "desired", "=", "plan", ".", "desired", "changes", "=", "plan", ".", "changes", "self", ".", "log", ".", "debug", "(", "'_apply: zone=%s, len(changes)=%d'", ",", "desired", ".", "name", ",", "len", "("...
36.157895
22.473684
def get_hex(self, signed=True): """ Given all the data the user has given so far, make the hex using pybitcointools """ total_ins_satoshi = self.total_input_satoshis() if total_ins_satoshi == 0: raise ValueError("Can't make transaction, there are zero inputs") ...
[ "def", "get_hex", "(", "self", ",", "signed", "=", "True", ")", ":", "total_ins_satoshi", "=", "self", ".", "total_input_satoshis", "(", ")", "if", "total_ins_satoshi", "==", "0", ":", "raise", "ValueError", "(", "\"Can't make transaction, there are zero inputs\"", ...
40
27.121951
def default(cls) -> 'PrecalculatedTextMeasurer': """Returns a reasonable default PrecalculatedTextMeasurer.""" if cls._default_cache is not None: return cls._default_cache if pkg_resources.resource_exists(__name__, 'default-widths.json.xz'): import lzma with ...
[ "def", "default", "(", "cls", ")", "->", "'PrecalculatedTextMeasurer'", ":", "if", "cls", ".", "_default_cache", "is", "not", "None", ":", "return", "cls", ".", "_default_cache", "if", "pkg_resources", ".", "resource_exists", "(", "__name__", ",", "'default-widt...
52.142857
19.047619
def _create_port_profile(self, handle, profile_name, vlan_id, vnic_type, ucsm_ip, trunk_vlans, qos_policy): """Creates a Port Profile on the UCS Manager. Significant parameters set in the port profile are: 1. Port profile name - Should match what was set in vif_deta...
[ "def", "_create_port_profile", "(", "self", ",", "handle", ",", "profile_name", ",", "vlan_id", ",", "vnic_type", ",", "ucsm_ip", ",", "trunk_vlans", ",", "qos_policy", ")", ":", "port_profile_dest", "=", "(", "const", ".", "PORT_PROFILESETDN", "+", "const", "...
40.16129
19.064516
def prepare_mosaic(self, image, fov_deg, name=None): """Prepare a new (blank) mosaic image based on the pointing of the parameter image """ header = image.get_header() ra_deg, dec_deg = header['CRVAL1'], header['CRVAL2'] data_np = image.get_data() #dtype = data_n...
[ "def", "prepare_mosaic", "(", "self", ",", "image", ",", "fov_deg", ",", "name", "=", "None", ")", ":", "header", "=", "image", ".", "get_header", "(", ")", "ra_deg", ",", "dec_deg", "=", "header", "[", "'CRVAL1'", "]", ",", "header", "[", "'CRVAL2'", ...
41.246914
21.185185
def advth(step): """Theoretical advection. This compute the theoretical profile of total advection as function of radius. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array` and None: the theoretical ad...
[ "def", "advth", "(", "step", ")", ":", "rbot", ",", "rtop", "=", "misc", ".", "get_rbounds", "(", "step", ")", "rmean", "=", "0.5", "*", "(", "rbot", "+", "rtop", ")", "rad", "=", "step", ".", "rprof", "[", "'r'", "]", ".", "values", "+", "rbot...
29.625
18.458333
def f_remove_link(self, name): """ Removes a link from from the current group node with a given name. Does not delete the link from the hard drive. If you want to do this, checkout :func:`~pypet.trajectory.Trajectory.f_delete_links` """ if name not in self._links: r...
[ "def", "f_remove_link", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_links", ":", "raise", "ValueError", "(", "'No link with name `%s` found under `%s`.'", "%", "(", "name", ",", "self", ".", "_full_name", ")", ")", "self", ...
40.727273
24.454545
def AdaptiveFilter(model="lms", **kwargs): """ Function that filter data with selected adaptive filter. **Args:** * `d` : desired value (1 dimensional array) * `x` : input matrix (2-dimensional array). Rows are samples, columns are input arrays. **Kwargs:** * Any ...
[ "def", "AdaptiveFilter", "(", "model", "=", "\"lms\"", ",", "*", "*", "kwargs", ")", ":", "# check if the filter size was specified", "if", "not", "\"n\"", "in", "kwargs", ":", "raise", "ValueError", "(", "'Filter size is not defined (n=?).'", ")", "# create filter ac...
30.192308
19.192308
def get_fallback_languages(self, language_code=None, site_id=None): """ Find out what the fallback language is for a given language choice. .. versionadded 1.5 """ choices = self.get_active_choices(language_code, site_id=site_id) return choices[1:]
[ "def", "get_fallback_languages", "(", "self", ",", "language_code", "=", "None", ",", "site_id", "=", "None", ")", ":", "choices", "=", "self", ".", "get_active_choices", "(", "language_code", ",", "site_id", "=", "site_id", ")", "return", "choices", "[", "1...
36.25
20.25
def camel_to_snake(self, s): """Constructs nice dir name from class name, e.g. FooBar => foo_bar. :param s: The string which should be converted to snake_case. """ return self._underscore_re2.sub(r'\1_\2', self._underscore_re1.sub(r'\1_\2', s)).lower()
[ "def", "camel_to_snake", "(", "self", ",", "s", ")", ":", "return", "self", ".", "_underscore_re2", ".", "sub", "(", "r'\\1_\\2'", ",", "self", ".", "_underscore_re1", ".", "sub", "(", "r'\\1_\\2'", ",", "s", ")", ")", ".", "lower", "(", ")" ]
46.666667
22.833333
def vm_info(name, call=None): ''' Retrieves information for a given virtual machine. A VM name must be supplied. .. versionadded:: 2016.3.0 name The name of the VM for which to gather information. CLI Example: .. code-block:: bash salt-cloud -a vm_info my-vm ''' if c...
[ "def", "vm_info", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The vm_info action must be called with -a or --action.'", ")", "server", ",", "user", ",", "password", "=", "_get_xml_rpc...
24.96875
22.78125
def _get_settings_class(): """ Get the AUTH_ADFS setting from the Django settings. """ if not hasattr(django_settings, "AUTH_ADFS"): msg = "The configuration directive 'AUTH_ADFS' was not found in your Django settings" raise ImproperlyConfigured(msg) cls = django_settings.AUTH_ADFS.g...
[ "def", "_get_settings_class", "(", ")", ":", "if", "not", "hasattr", "(", "django_settings", ",", "\"AUTH_ADFS\"", ")", ":", "msg", "=", "\"The configuration directive 'AUTH_ADFS' was not found in your Django settings\"", "raise", "ImproperlyConfigured", "(", "msg", ")", ...
42.888889
16
def image_set_aspect(aspect=1.0, axes="gca"): """ sets the aspect ratio of the current zoom level of the imshow image """ if axes is "gca": axes = _pylab.gca() e = axes.get_images()[0].get_extent() axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)
[ "def", "image_set_aspect", "(", "aspect", "=", "1.0", ",", "axes", "=", "\"gca\"", ")", ":", "if", "axes", "is", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "e", "=", "axes", ".", "get_images", "(", ")", "[", "0", "]", ".", "get_...
33.5
11.75
def upload_function_zip(self, location, zip_path, project_id=None): """ Uploads zip file with sources. :param location: The location where the function is created. :type location: str :param zip_path: The path of the valid .zip file to upload. :type zip_path: str ...
[ "def", "upload_function_zip", "(", "self", ",", "location", ",", "zip_path", ",", "project_id", "=", "None", ")", ":", "response", "=", "self", ".", "get_conn", "(", ")", ".", "projects", "(", ")", ".", "locations", "(", ")", ".", "functions", "(", ")"...
46.333333
22.6
def close( self ): """Append a closing tag unless element has only opening tag.""" if self.tag in self.parent.twotags: self.parent.content.append( "</%s>" % self.tag ) elif self.tag in self.parent.onetags: raise ClosingError( self.tag ) elif self.parent.mode == '...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "tag", "in", "self", ".", "parent", ".", "twotags", ":", "self", ".", "parent", ".", "content", ".", "append", "(", "\"</%s>\"", "%", "self", ".", "tag", ")", "elif", "self", ".", "tag", "...
45.333333
15.666667
def picard_index_ref(picard, ref_file): """Provide a Picard style dict index file for a reference genome. """ dict_file = "%s.dict" % os.path.splitext(ref_file)[0] if not file_exists(dict_file): with file_transaction(picard._config, dict_file) as tx_dict_file: opts = [("REFERENCE", r...
[ "def", "picard_index_ref", "(", "picard", ",", "ref_file", ")", ":", "dict_file", "=", "\"%s.dict\"", "%", "os", ".", "path", ".", "splitext", "(", "ref_file", ")", "[", "0", "]", "if", "not", "file_exists", "(", "dict_file", ")", ":", "with", "file_tran...
44.4
10.2
def read_index(self, fh, indexed_fh, rec_iterator=None, rec_hash_func=None, parse_hash=str, flush=True, no_reindex=True, verbose=False): """ Populate this index from a file. Input format is just a tab-separated file, one record per line. The last column is the file location...
[ "def", "read_index", "(", "self", ",", "fh", ",", "indexed_fh", ",", "rec_iterator", "=", "None", ",", "rec_hash_func", "=", "None", ",", "parse_hash", "=", "str", ",", "flush", "=", "True", ",", "no_reindex", "=", "True", ",", "verbose", "=", "False", ...
43.476636
23.214953
def city(name=None): """ Store the city that will be queried against. >>> three.city('sf') """ info = find_info(name) os.environ['OPEN311_CITY_INFO'] = dumps(info) return Three(**info)
[ "def", "city", "(", "name", "=", "None", ")", ":", "info", "=", "find_info", "(", "name", ")", "os", ".", "environ", "[", "'OPEN311_CITY_INFO'", "]", "=", "dumps", "(", "info", ")", "return", "Three", "(", "*", "*", "info", ")" ]
22.777778
13.666667
def trace(function, *args, **k) : """Decorates a function by tracing the begining and end of the function execution, if doTrace global is True""" if doTrace : print ("> "+function.__name__, args, k) result = function(*args, **k) if doTrace : print ("< "+function.__name__, args, k, "->", result) return result
[ "def", "trace", "(", "function", ",", "*", "args", ",", "*", "*", "k", ")", ":", "if", "doTrace", ":", "print", "(", "\"> \"", "+", "function", ".", "__name__", ",", "args", ",", "k", ")", "result", "=", "function", "(", "*", "args", ",", "*", ...
38.625
15.375
def can_recommend(self, client_data, extra_data={}): """The Curated recommender will always be able to recommend something""" self.logger.info("Curated can_recommend: {}".format(True)) return True
[ "def", "can_recommend", "(", "self", ",", "client_data", ",", "extra_data", "=", "{", "}", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Curated can_recommend: {}\"", ".", "format", "(", "True", ")", ")", "return", "True" ]
44.8
11.8
def get_params_for_field(self, field_name, sort_type=None): """ If sort_type is None - inverse current sort for field, if no sorted - use asc """ if not sort_type: if self.initial_sort == field_name: sort_type = 'desc' if self.initial_sort_type == 'asc' else '...
[ "def", "get_params_for_field", "(", "self", ",", "field_name", ",", "sort_type", "=", "None", ")", ":", "if", "not", "sort_type", ":", "if", "self", ".", "initial_sort", "==", "field_name", ":", "sort_type", "=", "'desc'", "if", "self", ".", "initial_sort_ty...
47.333333
19.666667
def validate_empty_values(self, data): """ Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned ...
[ "def", "validate_empty_values", "(", "self", ",", "data", ")", ":", "if", "self", ".", "read_only", ":", "return", "(", "True", ",", "self", ".", "get_default", "(", ")", ")", "if", "data", "is", "empty", ":", "if", "getattr", "(", "self", ".", "root...
34.407407
15.888889
def bind(self, instance_id: str, binding_id: str, details: BindDetails) -> Binding: """Binding the instance see openbrokerapi documentation """ # Find the instance instance = self._backend.find(instance_id) # Find or create the binding b...
[ "def", "bind", "(", "self", ",", "instance_id", ":", "str", ",", "binding_id", ":", "str", ",", "details", ":", "BindDetails", ")", "->", "Binding", ":", "# Find the instance", "instance", "=", "self", ".", "_backend", ".", "find", "(", "instance_id", ")",...
33.357143
17.214286
def get_question(self): """Gets the question. return: (osid.assessment.Question) - the question raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ question_map = dict(self._my_map['question']) que...
[ "def", "get_question", "(", "self", ")", ":", "question_map", "=", "dict", "(", "self", ".", "_my_map", "[", "'question'", "]", ")", "question_map", "[", "'learningObjectiveIds'", "]", "=", "self", ".", "_my_map", "[", "'learningObjectiveIds'", "]", "return", ...
40.307692
18.307692
def QueueResponse(self, response, timestamp=None): """Queues the message on the flow's state.""" if timestamp is None: timestamp = self.frozen_timestamp self.response_queue.append((response, timestamp))
[ "def", "QueueResponse", "(", "self", ",", "response", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "self", ".", "frozen_timestamp", "self", ".", "response_queue", ".", "append", "(", "(", "response", ",",...
43.2
7.8
def serialize(self, m): '''Serialize the macaroon in JSON format indicated by the version field. @param macaroon the macaroon to serialize. @return JSON macaroon. ''' from pymacaroons import macaroon if m.version == macaroon.MACAROON_V1: return self._serializ...
[ "def", "serialize", "(", "self", ",", "m", ")", ":", "from", "pymacaroons", "import", "macaroon", "if", "m", ".", "version", "==", "macaroon", ".", "MACAROON_V1", ":", "return", "self", ".", "_serialize_v1", "(", "m", ")", "return", "self", ".", "_serial...
35.5
15.5
def json_response(data, status=200): """Return a JsonResponse. Make sure you have django installed first.""" from django.http import JsonResponse return JsonResponse(data=data, status=status, safe=isinstance(data, dict))
[ "def", "json_response", "(", "data", ",", "status", "=", "200", ")", ":", "from", "django", ".", "http", "import", "JsonResponse", "return", "JsonResponse", "(", "data", "=", "data", ",", "status", "=", "status", ",", "safe", "=", "isinstance", "(", "dat...
57.25
10.5
def update_scenario(scenario,update_data=True,update_groups=True,flush=True,**kwargs): """ Update a single scenario as all resources already exist, there is no need to worry about negative IDS flush = True flushes to the DB at the end of the function. flush = False does not ...
[ "def", "update_scenario", "(", "scenario", ",", "update_data", "=", "True", ",", "update_groups", "=", "True", ",", "flush", "=", "True", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", "scen", "=", "_get...
37.268657
20.492537
def to_sql(self, frame, name, if_exists='fail', index=True, index_label=None, schema=None, chunksize=None, dtype=None, method=None): """ Write records stored in a DataFrame to a SQL database. Parameters ---------- frame: DataFrame name: stri...
[ "def", "to_sql", "(", "self", ",", "frame", ",", "name", ",", "if_exists", "=", "'fail'", ",", "index", "=", "True", ",", "index_label", "=", "None", ",", "schema", "=", "None", ",", "chunksize", "=", "None", ",", "dtype", "=", "None", ",", "method",...
46.087719
21.385965
def save_form(self, request, form, change): """ Super class ordering is important here - user must get saved first. """ OwnableAdmin.save_form(self, request, form, change) return DisplayableAdmin.save_form(self, request, form, change)
[ "def", "save_form", "(", "self", ",", "request", ",", "form", ",", "change", ")", ":", "OwnableAdmin", ".", "save_form", "(", "self", ",", "request", ",", "form", ",", "change", ")", "return", "DisplayableAdmin", ".", "save_form", "(", "self", ",", "requ...
44.833333
14.5
def run(data, samples, noreverse, maxindels, force, ipyclient): """ run the major functions for clustering within samples """ ## list of samples to submit to queue subsamples = [] ## if sample is already done skip for sample in samples: ## If sample not in state 2 don't try to cluster it. ...
[ "def", "run", "(", "data", ",", "samples", ",", "noreverse", ",", "maxindels", ",", "force", ",", "ipyclient", ")", ":", "## list of samples to submit to queue", "subsamples", "=", "[", "]", "## if sample is already done skip", "for", "sample", "in", "samples", ":...
36.3125
19.55
def independence_day(year, observed=None): '''July 4th''' day = 4 if observed: if calendar.weekday(year, JUL, 4) == SAT: day = 3 if calendar.weekday(year, JUL, 4) == SUN: day = 5 return (year, JUL, day)
[ "def", "independence_day", "(", "year", ",", "observed", "=", "None", ")", ":", "day", "=", "4", "if", "observed", ":", "if", "calendar", ".", "weekday", "(", "year", ",", "JUL", ",", "4", ")", "==", "SAT", ":", "day", "=", "3", "if", "calendar", ...
20.833333
22.5
def _eval_all_one_hot(fn, dist, name=None): """OneHotCategorical helper computing probs, cdf, etc over its support.""" with tf.compat.v1.name_scope(name, 'eval_all_one_hot'): event_size = dist.event_shape_tensor()[-1] batch_ndims = tf.size(input=dist.batch_shape_tensor()) # Reshape `eye(d)` to: `[d] + [...
[ "def", "_eval_all_one_hot", "(", "fn", ",", "dist", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "'eval_all_one_hot'", ")", ":", "event_size", "=", "dist", ".", "event_shape_tensor", "("...
48.333333
12.6
def connect_with_username_and_password(cls, url=None, username=None, password=None): """ Returns an object that makes requests to the API, authenticated with a short-lived token retrieved from username and password. If username or password is n...
[ "def", "connect_with_username_and_password", "(", "cls", ",", "url", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "from", ".", "v4_client", "import", "LuminosoClient", "as", "v4LC", "if", "username", "is", "None", ":", ...
40.275862
22.275862
def get_sync_info(self, name, key=None): """Get mtime/size when this target's current dir was last synchronized with remote.""" peer_target = self.peer if self.is_local(): info = self.cur_dir_meta.dir["peer_sync"].get(peer_target.get_id()) else: info = peer_target...
[ "def", "get_sync_info", "(", "self", ",", "name", ",", "key", "=", "None", ")", ":", "peer_target", "=", "self", ".", "peer", "if", "self", ".", "is_local", "(", ")", ":", "info", "=", "self", ".", "cur_dir_meta", ".", "dir", "[", "\"peer_sync\"", "]...
43.083333
16.25
def partition_horizontal(thelist, n): """ Break a list into ``n`` peices, but "horizontally." That is, ``partition_horizontal(range(10), 3)`` gives:: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] Clear as mud? """ try: n = int(n) thelis...
[ "def", "partition_horizontal", "(", "thelist", ",", "n", ")", ":", "try", ":", "n", "=", "int", "(", "n", ")", "thelist", "=", "list", "(", "thelist", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "[", "thelist", "]", "newli...
25.952381
17.47619
def get_free_memory(): """Return current free memory on the machine. Currently supported for Windows, Linux, MacOS. :returns: Free memory in MB unit :rtype: int """ if 'win32' in sys.platform: # windows return get_free_memory_win() elif 'linux' in sys.platform: # li...
[ "def", "get_free_memory", "(", ")", ":", "if", "'win32'", "in", "sys", ".", "platform", ":", "# windows", "return", "get_free_memory_win", "(", ")", "elif", "'linux'", "in", "sys", ".", "platform", ":", "# linux", "return", "get_free_memory_linux", "(", ")", ...
25.411765
14.352941
def format(self, fmt, **kwargs): """ Hooks compute to generate a value from a format string. """ def compute(self): values = {} try: for name, field in kwargs.iteritems(): values[name] = reduce(getattr, field.split('.'), self.c...
[ "def", "format", "(", "self", ",", "fmt", ",", "*", "*", "kwargs", ")", ":", "def", "compute", "(", "self", ")", ":", "values", "=", "{", "}", "try", ":", "for", "name", ",", "field", "in", "kwargs", ".", "iteritems", "(", ")", ":", "values", "...
32.5625
15.9375
def has_privileges(self, body, user=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-has-privileges.html>`_ :arg body: The privileges to test :arg user: Username """ if body in SKIP_IN_PATH: raise ValueErr...
[ "def", "has_privileges", "(", "self", ",", "body", ",", "user", "=", "None", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self...
37.2
20.533333
def renderThumbnail(self, relpath=""): """renderThumbnail() is called to render a thumbnail of the DP (e.g. in Data Product tables).""" # no thumbnail -- return empty string if self.thumbnail is None: return "" # else thumbnail is same as full image (because image was small e...
[ "def", "renderThumbnail", "(", "self", ",", "relpath", "=", "\"\"", ")", ":", "# no thumbnail -- return empty string", "if", "self", ".", "thumbnail", "is", "None", ":", "return", "\"\"", "# else thumbnail is same as full image (because image was small enough), insert directl...
57.4
13.133333
def set(self, property_dict): """Attempts to set the given properties of the object. An example of this is setting the nickname of the object:: cdb.set({"nickname": "My new nickname"}) note that there is a convenience property `cdb.nickname` that allows you to get/set the nic...
[ "def", "set", "(", "self", ",", "property_dict", ")", ":", "self", ".", "metadata", "=", "self", ".", "db", ".", "update", "(", "self", ".", "path", ",", "property_dict", ")", ".", "json", "(", ")" ]
45.888889
26
def applet_remove_tags(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /applet-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags """ return DXHTTPRequest('/%s/removeTags' % objec...
[ "def", "applet_remove_tags", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/removeTags'", "%", "object_id", ",", "input_params", ",", "always_retr...
52.857143
33.714286
def is_extension_type(arr): """ Check whether an array-like is of a pandas extension class instance. Extension classes include categoricals, pandas sparse objects (i.e. classes represented within the pandas library and not ones external to it like scipy sparse matrices), and datetime-like arrays. ...
[ "def", "is_extension_type", "(", "arr", ")", ":", "if", "is_categorical", "(", "arr", ")", ":", "return", "True", "elif", "is_sparse", "(", "arr", ")", ":", "return", "True", "elif", "is_datetime64tz_dtype", "(", "arr", ")", ":", "return", "True", "return"...
25.245614
22.649123
def genlet(generator_function=None, prime=True): """ Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink` :param generator_function: the generator function to convert :type generator_function: generator :param prime: advance the generator to the next/first yield :type...
[ "def", "genlet", "(", "generator_function", "=", "None", ",", "prime", "=", "True", ")", ":", "if", "generator_function", "is", "None", ":", "return", "GeneratorLink", ".", "wraplet", "(", "prime", "=", "prime", ")", "elif", "not", "callable", "(", "genera...
31.459459
18.972973
def proj_l2ball(b, s, r, axes=None): r""" Project :math:`\mathbf{b}` into the :math:`\ell_2` ball of radius :math:`r` about :math:`\mathbf{s}`, i.e. :math:`\{ \mathbf{x} : \|\mathbf{x} - \mathbf{s} \|_2 \leq r \}`. Note that ``proj_l2ball(b, s, r)`` is equivalent to :func:`.prox.proj_l2` ``(b - ...
[ "def", "proj_l2ball", "(", "b", ",", "s", ",", "r", ",", "axes", "=", "None", ")", ":", "d", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "b", "-", "s", ")", "**", "2", ",", "axis", "=", "axes", ",", "keepdims", "=", "True", "...
31.321429
19.714286
def pdf(cls, uuid): """Return a PDF of the invoice identified by the UUID This is a raw string, which can be written to a file with: ` with open('invoice.pdf', 'w') as invoice_file: invoice_file.write(recurly.Invoice.pdf(uuid)) ` """ url = ur...
[ "def", "pdf", "(", "cls", ",", "uuid", ")", ":", "url", "=", "urljoin", "(", "base_uri", "(", ")", ",", "cls", ".", "member_path", "%", "(", "uuid", ",", ")", ")", "pdf_response", "=", "cls", ".", "http_request", "(", "url", ",", "headers", "=", ...
36.230769
22.846154
def enroll_users_in_course(cls, enterprise_customer, course_id, course_mode, emails): """ Enroll existing users in a course, and create a pending enrollment for nonexisting users. Args: enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment course...
[ "def", "enroll_users_in_course", "(", "cls", ",", "enterprise_customer", ",", "course_id", ",", "course_mode", ",", "emails", ")", ":", "existing_users", ",", "unregistered_emails", "=", "cls", ".", "get_users_by_email", "(", "emails", ")", "successes", "=", "[", ...
41.236842
27.394737
def search_image(name=None, path=['.']): """ look for the image real path, if name is None, then return all images under path. @return system encoded path string FIXME(ssx): this code is just looking wired. """ name = strutils.decode(name) for image_dir in path: if not os.path.isdir...
[ "def", "search_image", "(", "name", "=", "None", ",", "path", "=", "[", "'.'", "]", ")", ":", "name", "=", "strutils", ".", "decode", "(", "name", ")", "for", "image_dir", "in", "path", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "ima...
34
13.047619
def cleanup_files(self): """Clean up files, remove builds.""" logger.debug('Cleaning up...') with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source()
[ "def", "cleanup_files", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Cleaning up...'", ")", "with", "indent_log", "(", ")", ":", "for", "req", "in", "self", ".", "reqs_to_cleanup", ":", "req", ".", "remove_temporary_source", "(", ")" ]
36.833333
6.833333
def _spoken_representation(message): """ Returns 2 lines of spoken representation of a message like: M O R S E C O D E (space) -- --- .-. ... . (space) -.-. --- -.. . """ lst_lst_char = _split_message(message) s = _spoken_representation_L1(lst_lst_char) ...
[ "def", "_spoken_representation", "(", "message", ")", ":", "lst_lst_char", "=", "_split_message", "(", "message", ")", "s", "=", "_spoken_representation_L1", "(", "lst_lst_char", ")", "s", "+=", "'\\n'", "+", "_spoken_representation_L2", "(", "lst_lst_char", ")", ...
31.333333
14
def method(func): """Wrap a function as a method.""" attr = abc.abstractmethod(func) attr.__imethod__ = True return attr
[ "def", "method", "(", "func", ")", ":", "attr", "=", "abc", ".", "abstractmethod", "(", "func", ")", "attr", ".", "__imethod__", "=", "True", "return", "attr" ]
26.4
13.2
def attr_list(args): '''Retrieve names of all attributes attached to a given object, either an entity (if entity type+name is provided) or workspace (if not)''' args.attributes = None result = attr_get(args) names = result.get("__header__",[]) if names: names = names[1:] else: ...
[ "def", "attr_list", "(", "args", ")", ":", "args", ".", "attributes", "=", "None", "result", "=", "attr_get", "(", "args", ")", "names", "=", "result", ".", "get", "(", "\"__header__\"", ",", "[", "]", ")", "if", "names", ":", "names", "=", "names", ...
32.818182
19.727273
def _search_type_in_type_comment(self, code): """ For more info see: https://www.python.org/dev/peps/pep-0484/#type-comments >>> AssignmentProvider()._search_type_in_type_comment('type: int') ['int'] """ for p in self.PEP0484_TYPE_COMMENT_PATTERNS: match = p....
[ "def", "_search_type_in_type_comment", "(", "self", ",", "code", ")", ":", "for", "p", "in", "self", ".", "PEP0484_TYPE_COMMENT_PATTERNS", ":", "match", "=", "p", ".", "search", "(", "code", ")", "if", "match", ":", "return", "[", "match", ".", "group", ...
34.909091
15
def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None, weight_angles=True, onlyreal=False, padding=(True, True), padfac=1.75, padval=None, intp_order=2, dtype=None, num_cores=ncores, save_memory=False, ...
[ "def", "backpropagate_3d", "(", "uSin", ",", "angles", ",", "res", ",", "nm", ",", "lD", "=", "0", ",", "coords", "=", "None", ",", "weight_angles", "=", "True", ",", "onlyreal", "=", "False", ",", "padding", "=", "(", "True", ",", "True", ")", ","...
35.724138
20.3125
def get_inc(self, native=False): """ Get include directories of Windows SDK. """ if self.sdk_version == 'v7.0A': include = os.path.join(self.sdk_dir, 'include') if os.path.isdir(include): logging.info(_('using include: %s'), include) ...
[ "def", "get_inc", "(", "self", ",", "native", "=", "False", ")", ":", "if", "self", ".", "sdk_version", "==", "'v7.0A'", ":", "include", "=", "os", ".", "path", ".", "join", "(", "self", ".", "sdk_dir", ",", "'include'", ")", "if", "os", ".", "path...
41.710526
14.131579
def setup(dist, attr, value): """A hook for simplifying ``vcversioner`` use from distutils. This hook, when installed properly, allows vcversioner to automatically run when specifying a ``vcversioner`` argument to ``setup``. For example:: from setuptools import setup setup( setup_re...
[ "def", "setup", "(", "dist", ",", "attr", ",", "value", ")", ":", "dist", ".", "metadata", ".", "version", "=", "find_version", "(", "*", "*", "value", ")", ".", "version" ]
29.526316
25
def get_running_id(self): """Send a HTTP request to the satellite (GET /identity) Used to get the daemon running identifier that allows to know if the daemon got restarted This is called on connection initialization or re-connection If the daemon is notreachable, this function will rai...
[ "def", "get_running_id", "(", "self", ")", ":", "former_running_id", "=", "self", ".", "running_id", "logger", ".", "info", "(", "\" get the running identifier for %s %s.\"", ",", "self", ".", "type", ",", "self", ".", "name", ")", "# An exception is raised in this...
43.292683
24.121951
def check_token_auth(self, token): """ Check to see who this is and if their token gets them into the system. """ serializer = self.get_signature() try: data = serializer.loads(token) except BadSignature: log.warning('Received bad token si...
[ "def", "check_token_auth", "(", "self", ",", "token", ")", ":", "serializer", "=", "self", ".", "get_signature", "(", ")", "try", ":", "data", "=", "serializer", ".", "loads", "(", "token", ")", "except", "BadSignature", ":", "log", ".", "warning", "(", ...
33.384615
13.461538
def listar_por_equip(self, equip_id): """Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': <...
[ "def", "listar_por_equip", "(", "self", ",", "equip_id", ")", ":", "if", "equip_id", "is", "None", ":", "raise", "InvalidParameterError", "(", "u'O id do equipamento não foi informado.')", "", "url", "=", "'ambiente/equip/'", "+", "str", "(", "equip_id", ")", "+",...
34.125
17.9375
def hincrby(self, name, key, amount=1): """ Increment the value of the field. :param name: str the name of the redis key :param increment: int :param field: str :return: Future() """ with self.pipe as pipe: return pipe.hincrby(self.redis_k...
[ "def", "hincrby", "(", "self", ",", "name", ",", "key", ",", "amount", "=", "1", ")", ":", "with", "self", ".", "pipe", "as", "pipe", ":", "return", "pipe", ".", "hincrby", "(", "self", ".", "redis_key", "(", "name", ")", ",", "self", ".", "membe...
32.230769
10.846154
def get(self, obj_id, byte_range=None): '''Download and return a file object or a specified byte_range from it. See HTTP Range header (rfc2616) for possible byte_range formats, Examples: "0-499" - byte offsets 0-499 (inclusive), "-500" - final 500 bytes.''' kwz = dict() if byte_range: kwz['headers'] = dict(...
[ "def", "get", "(", "self", ",", "obj_id", ",", "byte_range", "=", "None", ")", ":", "kwz", "=", "dict", "(", ")", "if", "byte_range", ":", "kwz", "[", "'headers'", "]", "=", "dict", "(", "Range", "=", "'bytes={}'", ".", "format", "(", "byte_range", ...
63.285714
31
def _upstart_is_disabled(name): ''' An Upstart service is assumed disabled if a manual stanza is placed in /etc/init/[name].override. NOTE: An Upstart service can also be disabled by placing "manual" in /etc/init/[name].conf. ''' files = ['/etc/init/{0}.conf'.format(name), '/etc/init/{0}.ove...
[ "def", "_upstart_is_disabled", "(", "name", ")", ":", "files", "=", "[", "'/etc/init/{0}.conf'", ".", "format", "(", "name", ")", ",", "'/etc/init/{0}.override'", ".", "format", "(", "name", ")", "]", "for", "file_name", "in", "filter", "(", "os", ".", "pa...
42
18.666667
def _calc_size_stats(self): """ get the size in bytes and num records of the content """ self.total_records = 0 self.total_length = 0 self.total_nodes = 0 if type(self.content['data']) is dict: self.total_length += len(str(self.content['data'])) ...
[ "def", "_calc_size_stats", "(", "self", ")", ":", "self", ".", "total_records", "=", "0", "self", ".", "total_length", "=", "0", "self", ".", "total_nodes", "=", "0", "if", "type", "(", "self", ".", "content", "[", "'data'", "]", ")", "is", "dict", "...
45.684211
21.368421
def copy(self): '''Returns a copy of this namespace. Note: we truly create a copy of the dictionary but keep _macros and _blocks. ''' return Namespace(self.dictionary.copy(), self._macros, self._blocks)
[ "def", "copy", "(", "self", ")", ":", "return", "Namespace", "(", "self", ".", "dictionary", ".", "copy", "(", ")", ",", "self", ".", "_macros", ",", "self", ".", "_blocks", ")" ]
34.714286
23.285714
def _set_drop_monitor(self, v, load=False): """ Setter method for drop_monitor, mapped from YANG variable /interface/ethernet/qos/drop_monitor (container) If this variable is read-only (config: false) in the source YANG file, then _set_drop_monitor is considered as a private method. Backends looking...
[ "def", "_set_drop_monitor", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
77.954545
36.318182
def calculateValues(self): """ Overloads the calculate values method to calculate the values for this axis based on the minimum and maximum values, and the number of steps desired. :return [<variant>, ..] """ if self.maximum() <= self.minimum(...
[ "def", "calculateValues", "(", "self", ")", ":", "if", "self", ".", "maximum", "(", ")", "<=", "self", ".", "minimum", "(", ")", ":", "return", "[", "]", "max_labels", "=", "self", ".", "maximumLabelCount", "(", ")", "seconds", "=", "(", "self", ".",...
33
17.636364
def init_db_conn(connection_name, connection_string, scopefunc=None): """ Initialize a postgresql connection by each connection string defined in the configuration file """ engine = create_engine(connection_string) session = scoped_session(sessionmaker(), scopefunc=scopefunc) session.configu...
[ "def", "init_db_conn", "(", "connection_name", ",", "connection_string", ",", "scopefunc", "=", "None", ")", ":", "engine", "=", "create_engine", "(", "connection_string", ")", "session", "=", "scoped_session", "(", "sessionmaker", "(", ")", ",", "scopefunc", "=...
43.888889
13.222222
def get_enrollments(self, course_id=None, usernames=None): """ List all course enrollments. Args: course_id (str, optional): If used enrollments will be filtered to the specified course id. usernames (list, optional): List of usernames to filter enrollmen...
[ "def", "get_enrollments", "(", "self", ",", "course_id", "=", "None", ",", "usernames", "=", "None", ")", ":", "params", "=", "{", "}", "if", "course_id", "is", "not", "None", ":", "params", "[", "'course_id'", "]", "=", "course_id", "if", "usernames", ...
39.73913
23.652174