code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def get_file_size(file_object): position = file_object.tell() file_object.seek(0, 2) file_size = file_object.tell() file_object.seek(position, 0) return file_size
Returns the size, in bytes, of a file. Expects an object that supports seek and tell methods. Args: file_object (file_object) - The object that represents the file Returns: (int): size of the file, in bytes
def _readse(self, pos): codenum, pos = self._readue(pos) m = (codenum + 1) // 2 if not codenum % 2: return -m, pos else: return m, pos
Return interpretation of next bits as a signed exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code.
def fetch_class(full_class_name): (module_name, class_name) = full_class_name.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, class_name)
Fetches the given class. :param string full_class_name: Name of the class to be fetched.
def tree_render(request, upy_context, vars_dictionary): page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
It renders template defined in upy_context's page passed in arguments
def remove_object_from_list(self, obj, list_element): list_element = self._handle_location(list_element) if isinstance(obj, JSSObject): results = [item for item in list_element.getchildren() if item.findtext("id") == obj.id] elif isinstance(obj, (int, basestrin...
Remove an object from a list element. Args: obj: Accepts JSSObjects, id's, and names list_element: Accepts an Element or a string path to that element
def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int: if v1._version > v2._version: return 1 elif v1._version == v2._version: return 0 else: return -1
Compares two instances.
def frequency(self, context): channels = self._manager.spectral_window_table.getcol(MS.CHAN_FREQ) return channels.reshape(context.shape).astype(context.dtype)
Frequency data source
def view_assets_by_site(token, dstore): taxonomies = dstore['assetcol/tagcol/taxonomy'].value assets_by_site = dstore['assetcol'].assets_by_site() data = ['taxonomy mean stddev min max num_sites num_assets'.split()] num_assets = AccumDict() for assets in assets_by_site: num_assets += {k: [le...
Display statistical information about the distribution of the assets
def forwards(apps, schema_editor): Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='movie'): ev.kind = 'cinema' ev.save() for ev in Event.objects.filter(kind='play'): ev.kind = 'theatre' ev.save()
Change Events with kind 'movie' to 'cinema' and Events with kind 'play' to 'theatre'. Purely for more consistency.
def get_subgraph_from_edge_list(graph, edge_list): node_list = get_vertices_from_edge_list(graph, edge_list) subgraph = make_subgraph(graph, node_list, edge_list) return subgraph
Transforms a list of edges into a subgraph.
def captcha_refresh(request): if not request.is_ajax(): raise Http404 new_key = CaptchaStore.pick() to_json_response = { 'key': new_key, 'image_url': captcha_image_url(new_key), 'audio_url': captcha_audio_url(new_key) if settings.CAPTCHA_FLITE_PATH else None } return ...
Return json with new captcha for ajax refresh request
def getMapScale(self, latitude, level, dpi=96): dpm = dpi / 0.0254 return self.getGroundResolution(latitude, level) * dpm
returns the map scale on the dpi of the screen
def reinit_configurations(self, request): now = timezone.now() changed_resources = [] for resource_model in CostTrackingRegister.registered_resources: for resource in resource_model.objects.all(): try: pe = models.PriceEstimate.objects.get(scope=re...
Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed.
def postprocess_subject(self, entry): if type(entry.subject) not in [str, unicode]: subject = u' '.join([unicode(k) for k in entry.subject]) else: subject = entry.subject entry.subject = [k.strip().upper() for k in subject.split(';')]
Parse subject keywords. Subject keywords are usually semicolon-delimited.
def reset(self, configuration: dict) -> None: self.clean(0) self.backend.store_config(configuration)
Whenever there was anything stored in the database or not, purge previous state and start new training process from scratch.
def stop_listening(self): self._halt_threads = True for name, queue_waker in self.recieved_signals.items(): q, wake_event = queue_waker wake_event.set()
Stop listener threads for acquistion queues
def _set_mpl_backend(self, backend, pylab=False): import traceback from IPython.core.getipython import get_ipython generic_error = ( "\n" + "="*73 + "\n" "NOTE: The following error appeared when setting " "your Matplotlib backend!!\n" + "="*73 + "\n\n" ...
Set a backend for Matplotlib. backend: A parameter that can be passed to %matplotlib (e.g. 'inline' or 'tk').
def define_new(cls, name, members, is_abstract=False): m = OrderedDict(cls._members) if set(m.keys()) & set(members.keys()): raise ValueError("'members' contains keys that overlap with parent") m.update(members) dct = { '_members' : m, '_is_abstract': ...
Define a new struct type derived from the current type. Parameters ---------- name: str Name of the struct type members: {member_name : type} Dictionary of struct member types. is_abstract: bool If set, marks the struct as abstract.
def format_single_dict(dictionary, output_name): output_payload = {} if dictionary: for (k, v) in dictionary.items(): output_payload[output_name + '[' + k + ']'] = v return output_payload
Currently used for metadata fields
def abort_keepalive_pings(self) -> None: assert self.state is State.CLOSED exc = ConnectionClosed(self.close_code, self.close_reason) exc.__cause__ = self.transfer_data_exc for ping in self.pings.values(): ping.set_exception(exc) if self.pings: pings_hex =...
Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed.
def verification_digit(numbers): a = sum(numbers[::2]) b = a * 3 c = sum(numbers[1::2]) d = b + c e = d % 10 if e == 0: return e return 10 - e
Returns the verification digit for a given numbre. The verification digit is calculated as follows: * A = sum of all even-positioned numbers * B = A * 3 * C = sum of all odd-positioned numbers * D = B + C * The results is the smallset number N, such that (D + N) % 10 ==...
def map_unicode_string(self, unicode_string, ignore=False, single_char_parsing=False, return_as_list=False, return_can_map=False): if unicode_string is None: return None ipa_string = IPAString(unicode_string=unicode_string, ignore=ignore, single_char_parsing=single_char_parsing) retu...
Convert the given Unicode string, representing an IPA string, to a string containing the corresponding mapped representation. Return ``None`` if ``unicode_string`` is ``None``. :param str unicode_string: the Unicode string to be parsed :param bool ignore: if ``True``, ignore Unicode ch...
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict): if self.delayed_parser_instantiation: try: app = config_manager._get_option('admin.application') source = "%s%s" % (app.value.app_name, file_name_extension) self.config_obj = co...
Return a nested dictionary representing the values in the ini file. In the case of this ValueSource implementation, both parameters are dummies.
def day_fraction(time): hour = int(time.split(":")[0]) minute = int(time.split(":")[1]) return hour/24 + minute/1440
Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python day_fraction("18:30")
def _idx_to_bits(self, i): bits = bin(i)[2:].zfill(self.nb_hyperplanes) return [-1.0 if b == "0" else 1.0 for b in bits]
Convert an group index to its bit representation.
def run(self, change): if self._formats is None: self.setup() entry = self.entry for fmt in self._formats: fmt.run(change, entry) self.clear()
runs the report format instances in this reporter. Will call setup if it hasn't been called already
def sheets(self): data = Dict() for src in [src for src in self.zipfile.namelist() if 'xl/worksheets/' in src]: name = os.path.splitext(os.path.basename(src))[0] xml = self.xml(src) data[name] = xml return data
return the sheets of data.
def get_coherent_next_tag(prev_label: str, cur_label: str) -> str: if cur_label == "O": return "O" if prev_label == cur_label: return f"I-{cur_label}" else: return f"B-{cur_label}"
Generate a coherent tag, given previous tag and current label.
def values(self): dtypes = [col.dtype for col in self.columns] if len(set(dtypes)) > 1: dtype = object else: dtype = None return np.array(self.columns, dtype=dtype).T
Return data in `self` as a numpy array. If all columns are the same dtype, the resulting array will have this dtype. If there are >1 dtypes in columns, then the resulting array will have dtype `object`.
def validate(self, sources): if not isinstance(sources, Root): raise Exception("Source object expected") parameters = self.get_uri_with_missing_parameters(sources) for parameter in parameters: logging.getLogger().warn('Missing parameter "%s" in uri of method "%s" in versi...
Validate the format of sources
def add_ref(self, ref): self.refs[ref.insn_addr].append(ref) self.data_addr_to_ref[ref.memory_data.addr].append(ref)
Add a reference to a memory data object. :param CodeReference ref: The reference. :return: None
def dasopr(fname): fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.dasopr_c(fname, ctypes.byref(handle)) return handle.value
Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int
def average_price(quantity_1, price_1, quantity_2, price_2): return (quantity_1 * price_1 + quantity_2 * price_2) / \ (quantity_1 + quantity_2)
Calculates the average price between two asset states.
def lookup_controller(obj, remainder, request=None): if request is None: warnings.warn( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, r...
Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully.
def new_tag(self, name: str, category: str=None) -> models.Tag: new_tag = self.Tag(name=name, category=category) return new_tag
Create a new tag.
def get_atoms(self, ligands=True, pseudo_group=False, inc_alt_states=False): atoms = itertools.chain( *(list(m.get_atoms(inc_alt_states=inc_alt_states)) for m in self.get_monomers(ligands=ligands, pseudo_group=pseudo_group))) return ...
Flat list of all the `Atoms` in the `Assembly`. Parameters ---------- ligands : bool, optional Include ligand `Atoms`. pseudo_group : bool, optional Include pseudo_group `Atoms`. inc_alt_states : bool, optional Include alternate sidechain conf...
def list_security_groups_in_vpc(self, vpc_id=None): log = logging.getLogger(self.cls_logger + '.list_security_groups_in_vpc') if vpc_id is None and self.vpc_id is not None: vpc_id = self.vpc_id else: msg = 'Unable to determine VPC ID to use to create the Security Group' ...
Lists security groups in the VPC. If vpc_id is not provided, use self.vpc_id :param vpc_id: (str) VPC ID to list security groups for :return: (list) Security Group info :raises: AWSAPIError, EC2UtilError
def get_locations(self, ip, detailed=False): if isinstance(ip, str): ip = [ip] seek = map(self._get_pos, ip) return [self._parse_location(elem, detailed=detailed) if elem > 0 else False for elem in seek]
Returns a list of dictionaries with location data or False on failure. Argument `ip` must be an iterable object. Amount of information about IP contained in the dictionary depends upon `detailed` flag state.
def history_add(self, value): if self._history_max_size is None or self.history_len() < self._history_max_size: self._history.append(value) else: self._history = self._history[1:] + [value]
Add a value in the history
def _apply_transformation(inputs): ts, transformation, extend_collection, clear_redo = inputs new = ts.append_transformation(transformation, extend_collection, clear_redo=clear_redo) o = [ts] if new: o.extend(new) return o
Helper method for multiprocessing of apply_transformation. Must not be in the class so that it can be pickled. Args: inputs: Tuple containing the transformed structure, the transformation to be applied, a boolean indicating whether to extend the collection, and a boolean indicat...
def populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ): with open(RELEASE_README_FILE, "r") as file_obj: template = file_obj.read() contents = template.format( version=version, circleci_build=circleci_build, appveyor_build=appveyor_build...
Populates ``README.rst`` with release-specific data. This is because ``README.rst`` is used on PyPI. Args: version (str): The current version. circleci_build (Union[str, int]): The CircleCI build ID corresponding to the release. appveyor_build (str): The AppVeyor build ID c...
def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None): url = "{url_base}/resource/{pid}/files/".format(url_base=self.url_base, pid=pid) params = {} close_fd = self._prepareFileForUpload(params, resour...
Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string representing path to file to be uploaded as part of the new resource :param resource_filename: ...
def component_doi(soup): component_doi = [] object_id_tags = raw_parser.object_id(soup, pub_id_type = "doi") component_list = components(soup) position = 1 for tag in object_id_tags: component_object = {} component_object["doi"] = doi_uri_to_doi(tag.text) component_object["po...
Look for all object-id of pub-type-id = doi, these are the component DOI tags
def create_geometry(self, input_geometry, upper_depth, lower_depth): self._check_seismogenic_depths(upper_depth, lower_depth) if not isinstance(input_geometry, Point): if not isinstance(input_geometry, np.ndarray): raise ValueError('Unrecognised or unsupported geometry ' ...
If geometry is defined as a numpy array then create instance of nhlib.geo.point.Point class, otherwise if already instance of class accept class :param input_geometry: Input geometry (point) as either i) instance of nhlib.geo.point.Point class ii) numpy.ndarr...
def config_babel(app): " Init application with babel. " babel.init_app(app) def get_locale(): return request.accept_languages.best_match(app.config['BABEL_LANGUAGES']) babel.localeselector(get_locale)
Init application with babel.
def post_article_content(self, content, url, max_pages=25): params = { 'doc': content, 'max_pages': max_pages } url = self._generate_url('parser', {"url": url}) return self.post(url, post_params=params)
POST content to be parsed to the Parser API. Note: Even when POSTing content, a url must still be provided. :param content: the content to be parsed :param url: the url that represents the content :param max_pages (optional): the maximum number of pages to parse and combine...
def _expand_users(device_users, common_users): expected_users = deepcopy(common_users) expected_users.update(device_users) return expected_users
Creates a longer list of accepted users on the device.
def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []): width = data.shape[dimOrder.index('w')] height = data.shape[dimOrder.index('h')] return generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms)
Generates a set of sliding windows for the specified dataset.
def call_fan(tstat): old_fan = tstat.fan tstat.write({ 'fan': not old_fan, }) def restore(): tstat.write({ 'fan': old_fan, }) return restore
Toggles the fan
def camera_to_rays(camera): half = np.radians(camera.fov / 2.0) half *= (camera.resolution - 2) / camera.resolution angles = util.grid_linspace(bounds=[-half, half], count=camera.resolution) vectors = util.unitize(np.column_stack(( np.sin(angles), np.ones(...
Convert a trimesh.scene.Camera object to ray origins and direction vectors. Will return one ray per pixel, as set in camera.resolution. Parameters -------------- camera : trimesh.scene.Camera Camera with transform defined Returns -------------- origins : (n, 3) float Ray or...
def generate_filename(self, requirement): return FILENAME_PATTERN % (self.config.cache_format_revision, requirement.name, requirement.version, get_python_version())
Generate a distribution archive filename for a package. :param requirement: A :class:`.Requirement` object. :returns: The filename of the distribution archive (a string) including a single leading directory component to indicate the cache format revision.
def _auth(url): user = __salt__['config.get']('solr.user', False) password = __salt__['config.get']('solr.passwd', False) realm = __salt__['config.get']('solr.auth_realm', 'Solr') if user and password: basic = _HTTPBasicAuthHandler() basic.add_password( realm=realm, uri=url, ...
Install an auth handler for urllib2
def set_edge_weight(self, edge, wt): self.set_edge_properties(edge, weight=wt ) if not self.DIRECTED: self.set_edge_properties((edge[1], edge[0]) , weight=wt )
Set the weight of an edge. @type edge: edge @param edge: One edge. @type wt: number @param wt: Edge weight.
def parseArgsPy26(): from gsmtermlib.posoptparse import PosOptionParser, Option parser = PosOptionParser(description='Simple script for sending SMS messages') parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_option(...
Argument parser for Python 2.6
def type(self, newtype): self._type = newtype if self.is_multi: for sibling in self.multi_rep.siblings: sibling._type = newtype
If the feature is a multifeature, update all entries.
def regexp_extract(str, pattern, idx): r sc = SparkContext._active_spark_context jc = sc._jvm.functions.regexp_extract(_to_java_column(str), pattern, idx) return Column(jc)
r"""Extract a specific group matched by a Java regex, from the specified string column. If the regex did not match, or the specified group did not match, an empty string is returned. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_extract('str', r'(\d+)-(\d+)', 1).alias('d')).c...
def read_config(file_name): dirname = os.path.dirname( os.path.abspath(file_name) ) dirname = os.path.relpath(dirname) def custom_str_constructor(loader, node): return loader.construct_scalar(node).encode('utf-8') yaml.add_constructor(u'tag:yaml.org,2002:str', custom_str_constructor)...
Read YAML file with configuration and pointers to example data. Args: file_name (str): Name of the file, where the configuration is stored. Returns: dict: Parsed and processed data (see :func:`_process_config_item`). Example YAML file:: html: simple_xml.xml first: ...
def set_data(self, index, value): acces, field = self.get_item(index), self.header[index.column()] self.beginResetModel() self.set_data_hook(acces, field, value) self.endResetModel()
Uses given data setter, and emit modelReset signal
def code(self): if self._code is not None: return self._code elif self._defcode is not None: return self._defcode return 200
The HTTP response code associated with this ResponseObject. If instantiated directly without overriding the code, returns 200 even if the default for the method is some other value. Can be set or deleted; in the latter case, the default will be restored.
def cli(ctx): level = logger.level try: level_to_name = logging._levelToName except AttributeError: level_to_name = logging._levelNames level_name = level_to_name.get(level, level) logger.debug('Verbosity set to {}.'.format(level_name)) if ctx.invoked_subcommand is None: ...
CLI for maildirs content analysis and deletion.
def gen_for(self, node, target, local_iter, local_iter_decl, loop_body): local_target = "__target{0}".format(id(node)) local_target_decl = self.types.builder.IteratorOfType(local_iter_decl) if node.target.id in self.scope[node] and not hasattr(self, 'yields'): local_type = "auto&&" ...
Create For representation on iterator for Cxx generation. Examples -------- >> "omp parallel for" >> for i in xrange(10): >> ... do things ... Becomes >> "omp parallel for shared(__iterX)" >> for(decltype(__iterX)::iterator __targetX = __iterX.begin...
def submit(self, stanza): body = _encode(**stanza) self.service.post(self.path, body=body) return self
Adds keys to the current configuration stanza as a dictionary of key-value pairs. :param stanza: A dictionary of key-value pairs for the stanza. :type stanza: ``dict`` :return: The :class:`Stanza` object.
def _output_tags(self): for class_name, properties in sorted(self.resources.items()): for key, value in sorted(properties.items()): validator = self.override.get_validator(class_name, key) if key == 'Tags' and validator is None: print("from troposp...
Look for a Tags object to output a Tags import
def get_supported_currency_choices(api_key): import stripe stripe.api_key = api_key account = stripe.Account.retrieve() supported_payment_currencies = stripe.CountrySpec.retrieve(account["country"])[ "supported_payment_currencies" ] return [(currency, currency.upper()) for currency in supported_payment_currenci...
Pull a stripe account's supported currencies and returns a choices tuple of those supported currencies. :param api_key: The api key associated with the account from which to pull data. :type api_key: str
def vary_name(name: Text): snake = re.match(r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$', name) if not snake: fail('The project name is not a valid snake-case Python variable name') camel = [x[0].upper() + x[1:] for x in name.split('_')] return { 'project_name_snake': name, 'project_name_c...
Validates the name and creates variations
def print_math(math_expression_lst, name = "math.html", out='html', formatter = lambda x: x): try: shutil.rmtree('viz') except: pass pth = get_cur_path()+print_math_template_path shutil.copytree(pth, 'viz') html_loc = None if out == "html": html_loc = pth+"standalone_index.html" if o...
Converts LaTeX math expressions into an html layout. Creates a html file in the directory where print_math is called by default. Displays math to jupyter notebook if "notebook" argument is specified. Args: math_expression_lst (list): A list of LaTeX math (string) to be rendered by KaTeX ...
def least_upper_bound(*intervals_to_join): assert len(intervals_to_join) > 0, "No intervals to join" all_same = all(x.bits == intervals_to_join[0].bits for x in intervals_to_join) assert all_same, "All intervals to join should be same" if len(intervals_to_join) == 1: return i...
Pseudo least upper bound. Join the given set of intervals into a big interval. The resulting strided interval is the one which in all the possible joins of the presented SI, presented the least number of values. The number of joins to compute is linear with the number of intervals to join. ...
def get_callee_account( global_state: GlobalState, callee_address: str, dynamic_loader: DynLoader ): environment = global_state.environment accounts = global_state.accounts try: return global_state.accounts[callee_address] except KeyError: log.debug("Module with address " + callee_ad...
Gets the callees account from the global_state. :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Account belonging to callee
def get_report(self): ostr = '' ostr += "target\tquery\tcnt\ttotal\n" poss = ['-','A','C','G','T'] for target in poss: for query in poss: ostr += target+ "\t"+query+"\t"+str(self.matrix[target][query])+"\t"+str(self.alignment_length)+"\n" return ostr
Another report, but not context based
def _autorestart_components(self, bundle): with self.__instances_lock: instances = self.__auto_restart.get(bundle) if not instances: return for factory, name, properties in instances: try: self.instantiate(factory, name, pro...
Restart the components of the given bundle :param bundle: A Bundle object
def get_access_token(self): if self.token_info and not self.is_token_expired(self.token_info): return self.token_info['access_token'] token_info = self._request_access_token() token_info = self._add_custom_values_to_token_info(token_info) self.token_info = token_info ...
If a valid access token is in memory, returns it Else feches a new token and returns it
def _get_pos(self, key): p = bisect(self.runtime._keys, self.hashi(key)) if p == len(self.runtime._keys): return 0 else: return p
Get the index of the given key in the sorted key list. We return the position with the nearest hash based on the provided key unless we reach the end of the continuum/ring in which case we return the 0 (beginning) index position. :param key: the key to hash and look for.
def storage_volume_templates(self): if not self.__storage_volume_templates: self.__storage_volume_templates = StorageVolumeTemplates(self.__connection) return self.__storage_volume_templates
Gets the StorageVolumeTemplates API client. Returns: StorageVolumeTemplates:
def rename_datastore(datastore_ref, new_datastore_name): ds_name = get_managed_object_name(datastore_ref) log.trace("Renaming datastore '%s' to '%s'", ds_name, new_datastore_name) try: datastore_ref.RenameDatastore(new_datastore_name) except vim.fault.NoPermission as exc: log.exception(e...
Renames a datastore datastore_ref vim.Datastore reference to the datastore object to be changed new_datastore_name New datastore name
def generic_visit(self, node): assert isinstance(node, ast.expr) res = self.assign(node) return res, self.explanation_param(self.display(res))
Handle expressions we don't have custom code for.
def get_hw_virt_ex_property(self, property_p): if not isinstance(property_p, HWVirtExPropertyType): raise TypeError("property_p can only be an instance of type HWVirtExPropertyType") value = self._call("getHWVirtExProperty", in_p=[property_p]) return value
Returns the value of the specified hardware virtualization boolean property. in property_p of type :class:`HWVirtExPropertyType` Property type to query. return value of type bool Property value. raises :class:`OleErrorInvalidarg` Invalid property.
def files(self): self._check_session() status, data = self._rest.get_request('files') return data
Get list of files, for this session, on server.
def _perform_radius_auth(self, client, packet): try: reply = client.SendPacket(packet) except Timeout as e: logging.error("RADIUS timeout occurred contacting %s:%s" % ( client.server, client.authport)) return False except Exception as e: ...
Perform the actual radius authentication by passing the given packet to the server which `client` is bound to. Returns True or False depending on whether the user is authenticated successfully.
def neighbor_difference(self): differences = np.zeros(self.num_neurons) num_neighbors = np.zeros(self.num_neurons) distance, _ = self.distance_function(self.weights, self.weights) for x, y in self.neighbors(): differences[x] += distance[x, y] num_neighbors[x] += 1...
Get the euclidean distance between a node and its neighbors.
def iter_format_modules(lang): if check_for_language(lang): format_locations = [] for path in CUSTOM_FORMAT_MODULE_PATHS: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if ...
Does the heavy lifting of finding format modules.
def get_interface(self, interface='eth0'): LOG.info("RPC: get_interface interfae: %s" % interface) code, message, data = agent_utils.get_interface(interface) return agent_utils.make_response(code, message, data)
Interface info. ifconfig interface
def get_currency_aggregate_by_symbol(self, symbol: str) -> CurrencyAggregate: currency = self.get_by_symbol(symbol) result = self.get_currency_aggregate(currency) return result
Creates currency aggregate for the given currency symbol
def get_bit_width(self, resource): datatype = resource.datatype if "uint" in datatype: bit_width = int(datatype.split("uint")[1]) else: raise ValueError("Unsupported datatype: {}".format(datatype)) return bit_width
Method to return the bit width for blosc based on the Resource
def Emailer(recipients, sender=None): import smtplib hostname = socket.gethostname() if not sender: sender = 'lggr@{0}'.format(hostname) smtp = smtplib.SMTP('localhost') try: while True: logstr = (yield) try: smtp.sendmail(sender, recipients, l...
Sends messages as emails to the given list of recipients.
def next(self): return self.iterator.next(task=self.task, timeout=self.timeout, block=self.block)
Returns a result if availble within "timeout" else raises a ``TimeoutError`` exception. See documentation for ``NuMap.next``.
async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None: if parameters is None: parameters = [] await self._execute(self._cursor.execute, sql, parameters)
Execute the given query.
def run(self): while True: try: self.perform_iteration() except Exception: traceback.print_exc() pass time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)
Run the reporter.
def startup(api=None): def startup_wrapper(startup_function): apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function) apply_to_api.add_startup_handler(startup_function) return startup_function return startup_wrapper
Runs the provided function on startup, passing in an instance of the api
def register(): signals.article_generator_finalized.connect(link_source_files) signals.page_generator_finalized.connect(link_source_files) signals.page_writer_finalized.connect(write_source_files)
Calls the shots, based on signals
def standardize(self, axis=1): if axis == 1: return self.map(lambda x: x / std(x)) elif axis == 0: stdval = self.std().toarray() return self.map(lambda x: x / stdval) else: raise Exception('Axis must be 0 or 1')
Divide by standard deviation either within or across records. Parameters ---------- axis : int, optional, default = 0 Which axis to standardize along, within (1) or across (0) records
def path(self, *args: typing.List[str]) -> typing.Union[None, str]: if not self._project: return None return environ.paths.clean(os.path.join( self._project.source_directory, *args ))
Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :return: An absolute path to the specified file or directory within the ...
def open(self): self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device.connect((self.host, self.port)) if self.device is None: print "Could not open socket for %s" % self.host
Open TCP socket and set it as escpos device
def _dictionary(self): retval = {} for variant in self._override_order: retval.update(self._config[variant]) return retval
A dictionary representing the loaded configuration.
def GetDefaultContract(self): try: return self.GetContracts()[0] except Exception as e: logger.error("Could not find default contract: %s" % str(e)) raise
Get the default contract. Returns: contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception. Raises: Exception: if no default contract is found. Note: Prints a warning to the console if the default contract c...
def join_filter(sep, seq, pred=bool): return sep.join([text_type(i) for i in seq if pred(i)])
Join with a filter.
def get_attachments(self): attachments = [] for attachment in self.context.getAttachment(): attachment_info = self.get_attachment_info(attachment) attachments.append(attachment_info) for analysis in self.context.getAnalyses(full_objects=True): for attachment i...
Returns a list of attachments info dictionaries Original code taken from bika.lims.analysisrequest.view
def fit(self, X, y=None): if self.normalize: X = normalize(X) self._check_force_weights() random_state = check_random_state(self.random_state) X = self._check_fit_data(X) ( self.cluster_centers_, self.labels_, self.inertia_, ...
Compute mixture of von Mises Fisher clustering. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features)
def all(self, axis=None, *args, **kwargs): nv.validate_all(args, kwargs) values = self.sp_values if len(values) != len(self) and not np.all(self.fill_value): return False return values.all()
Tests whether all elements evaluate True Returns ------- all : bool See Also -------- numpy.all
def _encrypt_data_key( self, data_key: DataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text] ) -> NoReturn: raise NotImplementedError("CountingMasterKey does not support encrypt_data_key")
Encrypt a data key and return the ciphertext. :param data_key: Unencrypted data key :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey` or :class:`aws_encryption_sdk.structures.DataKey` :param algorithm: Algorithm object which directs how this Master Key will encrypt t...
def __dict_to_pod_spec(spec): spec_obj = kubernetes.client.V1PodSpec() for key, value in iteritems(spec): if hasattr(spec_obj, key): setattr(spec_obj, key, value) return spec_obj
Converts a dictionary into kubernetes V1PodSpec instance.