Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
8,900
def treeAggregate(self, zeroValue, seqOp, combOp, depth=2): if depth < 1: raise ValueError("Depth cannot be smaller than 1 but got %d." % depth) if self.getNumPartitions() == 0: return zeroValue def aggregatePartition(iterator): acc = zeroValue ...
Aggregates the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeAggregate(0, add, add) -5 >>> rdd.tr...
8,901
def spkopa(filename): filename = stypes.stringToCharP(filename) handle = ctypes.c_int() libspice.spkopa_c(filename, ctypes.byref(handle)) return handle.value
Open an existing SPK file for subsequent write. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopa_c.html :param filename: The name of an existing SPK file. :type filename: str :return: A handle attached to the SPK file opened to append. :rtype: int
8,902
def __execute_scale(self, surface, size_to_scale_from): x = size_to_scale_from[0] * self.__scale[0] y = size_to_scale_from[1] * self.__scale[1] scaled_value = (int(x), int(y)) self.image = pygame.transform.scale(self.image, scaled_value) self.__resize...
Execute the scaling operation
8,903
def run_tasks(cls): now = timezone.now() tasks = cls.objects.filter(enabled=True) for task in tasks: if task.next_run == HAS_NOT_RUN: task.calc_next_run() if task.next_run < now: if (task.start_running < now): i...
Internal task-runner class method, called by :py:func:`sisy.consumers.run_heartbeat`
8,904
def transform_streams_for_comparison(outputs): new_outputs = [] for output in outputs: if (output.output_type == ): new_outputs.append({ : , output.name: output.text, }) else: new_outputs.append(output) ret...
Makes failure output for streams better by having key be the stream name
8,905
def return_secondary_learner(self): estimator = self.base_learner_origin.return_estimator() estimator = estimator.set_params(**self.secondary_learner_hyperparameters) return estimator
Returns secondary learner using its origin and the given hyperparameters Returns: est (estimator): Estimator object
8,906
def ltrimboth (l,proportiontocut): lowercut = int(proportiontocut*len(l)) uppercut = len(l) - lowercut return l[lowercut:uppercut]
Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., conservatively slices off proportiontocut). ...
8,907
def get_host_cache(service_instance=None): * ret_dict = {} host_ref = _get_proxy_target(service_instance) hostname = __proxy__[]()[] hci = salt.utils.vmware.get_host_cache(host_ref) if not hci: log.debug(%s\, hostname) ret_dict[] = False return ret_dict ret...
Returns the host cache configuration on the proxy host. service_instance Service instance (vim.ServiceInstance) of the vCenter/ESXi host. Default is None. .. code-block:: bash salt '*' vsphere.get_host_cache
8,908
def get_html_text_editor( name, id=None, content=, textual_content=None, width=, height=, enabled=True, file_upload_url=None, toolbar_set="Basic", custom_configurations_path=, ln=None): ln = default_ln(ln) if textual_c...
Returns a wysiwyg editor (CKEditor) to embed in html pages. Fall back to a simple textarea when the library is not installed, or when the user's browser is not compatible with the editor, or when 'enable' is False, or when javascript is not enabled. NOTE that the output also contains a hidden field na...
8,909
def switch_toggle(context, ain): context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: if actor.get_state(): actor.switch_off() click.echo("State for {} is now OFF".format(ain)) else: actor.switch_on() click.echo("State f...
Toggle an actor's power state
8,910
def _remove_event_source(awsclient, evt_source, lambda_arn): event_source_obj = _get_event_source_obj(awsclient, evt_source) if event_source_obj.exists(lambda_arn): event_source_obj.remove(lambda_arn)
Given an event_source dictionary, create the object and remove the event source.
8,911
def systemd( state, host, name, running=True, restarted=False, reloaded=False, command=None, enabled=None, daemon_reload=False, ): if daemon_reload: yield yield _handle_service_control( name, host.fact.systemd_status, , running, restarted, reloaded, command, ...
Manage the state of systemd managed services. + name: name of the service to manage + running: whether the service should be running + restarted: whether the service should be restarted + reloaded: whether the service should be reloaded + command: custom command to pass like: ``/etc/rc.d/<name> <co...
8,912
def validateDocumentFinal(self, ctxt): if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o ret = libxml2mod.xmlValidateDocumentFinal(ctxt__o, self._o) return ret
Does the final step for the document validation once all the incremental validation steps have been completed basically it does the following checks described by the XML Rec Check all the IDREF/IDREFS attributes definition for validity
8,913
def get_serializer(self, instance=None, data=None, many=False, partial=False): serializers = { : NodeRequestListSerializer, : VoteRequestListSerializer, : CommentRequestListSerializer, : RatingRequestListSerializer, } ...
Return the serializer instance that should be used for validating and deserializing input, and for serializing output.
8,914
def raise_(type_, value=None, traceback=None): if type_.__traceback__ is not traceback: raise type_.with_traceback(traceback) raise type_
Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be pretty carefull with tracebacks. If it is possible, use sys.exc_info...
8,915
def FDMT(data, f_min, f_max, maxDT, dataType): nint, nbl, nchan, npol = data.shape niters = int(np.log2(nchan)) assert nchan in 2**np.arange(30) and nint in 2**np.arange(30), "Input dimensions must be a power of 2" logger.info(.format(data.shape)) data = FDMT_initialization(data, f_min, f_ma...
This function implements the FDMT algorithm. Input: Input visibility array (nints, nbl, nchan, npol) f_min,f_max are the base-band begin and end frequencies. The frequencies should be entered in MHz maxDT - the maximal delay (in time bins) of the maximal dispersion. ...
8,916
def split_no_wd_params(layer_groups:Collection[nn.Module])->List[List[nn.Parameter]]: "Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest." split_params = [] for l in layer_groups: l1,l2 = [],[] for c in l.children(): if isinsta...
Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest.
8,917
async def ensure_process(self): with (await self.state[]): if not in self.state: cmd = self.get_cmd() server_env = os.environ.copy() server_env.update(self.get_env()) ...
Start the process
8,918
def load_auth_from_file(filename): with open(filename) as auth_file: lines = auth_file.read().splitlines() lines = [line.strip() for line in lines if len(line) != 0] if len(lines) == 2: credentials = (lines[0], lines[1]) elif len(lines) == 1: user_pass = ...
Initializes the auth settings for accessing MyAnimelist through its official API from a given filename. :param filename The name of the file containing your MyAnimeList credentials REQUIREMENTS: The file must... ...username for your MAL account. ...
8,919
def setFixedHeight(self, height): super(XViewPanelItem, self).setFixedHeight(height) self._dragLabel.setFixedHeight(height) self._titleLabel.setFixedHeight(height) self._searchButton.setFixedHeight(height) self._closeButton.setFixedHeight(height)
Sets the fixed height for this item to the inputed height amount. :param height | <int>
8,920
def rpc_call(self, request, method=None, params=None, **kwargs): args = [] kwargs = dict() if isinstance(params, dict): kwargs.update(params) else: args = list(as_tuple(params)) method_key = "{0}.{1}".format(self.scheme_name, method) if m...
Call a RPC method. return object: a result
8,921
def play(self, call_params): path = + self.api_version + method = return self.request(path, method, call_params)
REST Play something on a Call Helper
8,922
def sub_article_folders(self): l = list() for p in Path.sort_by_fname( Path(self.dir_path).select_dir(recursive=False) ): af = ArticleFolder(dir_path=p.abspath) try: if af.title is not None: l.append(af) ...
Returns all valid ArticleFolder sitting inside of :attr:`ArticleFolder.dir_path`.
8,923
def importance(self, attribute, examples): gain_counter = OnlineInformationGain(attribute, self.target) for example in examples: gain_counter.add(example) return gain_counter.get_gain()
AIMA implies that importance should be information gain. Since AIMA only defines it for binary features this implementation was based on the wikipedia article: http://en.wikipedia.org/wiki/Information_gain_in_decision_trees
8,924
def DEFAULT_RENAMER(L, Names=None): if isinstance(L,dict): Names = L.keys() LL = L.values() else: if Names == None: Names = range(len(L)) else: assert len(Names) == len(L) LL = L commons = Commons([l.dtype.names for l in LL]) D = {} ...
Renames overlapping column names of numpy ndarrays with structured dtypes Rename the columns by using a simple convention: * If `L` is a list, it will append the number in the list to the key associated with the array. * If `L` is a dictionary, the algorithm will append the string r...
8,925
def request_issuance(self, csr): action = LOG_ACME_REQUEST_CERTIFICATE() with action.context(): return ( DeferredContext( self._client.post( self.directory[csr], csr, content_type=DER_CONTENT_TYPE, ...
Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes. .. seealso:: `txacme.util.csr_for_names` ...
8,926
def build(self, tag, **kwargs): self.push_log("Building image .".format(tag)) set_raise_on_error(kwargs) try: return super(DockerFabricClient, self).build(tag, **kwargs) except DockerStatusError as e: error(e.message)
Identical to :meth:`dockermap.client.base.DockerClientWrapper.build` with additional logging.
8,927
def print_math(math_expression_lst, name = "math.html", out=, formatter = lambda x: x): try: shutil.rmtree() except: pass pth = get_cur_path()+print_math_template_path shutil.copytree(pth, ) html_loc = None if out == "html": html_loc = pth+"standalone_index.html" if out =...
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 ...
8,928
def generateXY(self, **kwargs): print(" .format(self.fnamenoext, self.wcs.extname, util._ptime()[0])) if self.pars[]: sigma = self._compute_sigma() else: sigma = self.pars[] skymode = sigma**2 log.inf...
Generate source catalog from input image using DAOFIND-style algorithm
8,929
def to_line_string(self, closed=True): from imgaug.augmentables.lines import LineString if not closed or len(self.exterior) <= 1: return LineString(self.exterior, label=self.label) return LineString( np.concatenate([self.exterior, self.exterior[0:1, :]], axis=0),...
Convert this polygon's `exterior` to a ``LineString`` instance. Parameters ---------- closed : bool, optional Whether to close the line string, i.e. to add the first point of the `exterior` also as the last point at the end of the line string. This has no eff...
8,930
def open(safe_file): if os.path.isdir(safe_file) or os.path.isfile(safe_file): return SentinelDataSet(safe_file) else: raise IOError("file not found: %s" % safe_file)
Return a SentinelDataSet object.
8,931
def quaternion_from_euler(angles, order=): angles = np.asarray(angles, dtype=float) quat = quaternion_from_axis_rotation(angles[0], order[0])\ * (quaternion_from_axis_rotation(angles[1], order[1]) * quaternion_from_axis_rotation(angles[2], order[2])) quat.normalize(inplace=True) ...
Generate a quaternion from a set of Euler angles. Args: angles (array_like): Array of Euler angles. order (str): Order of Euler rotations. 'yzy' is default. Returns: Quaternion: Quaternion representation of Euler rotation.
8,932
def _extract_from_url(self, url): m = re.search(re_pub_date, url) if m: return self.parse_date_str(m.group(0)) return None
Try to extract from the article URL - simple but might work as a fallback
8,933
def checkout(self, ref, cb=None): if self.is_api: return self._checkout_api(ref, cb=cb) else: return self._checkout_fs(ref, cb=cb)
Checkout a bundle from the remote. Returns a file-like object
8,934
def fromrandom(shape=(10, 50, 50), npartitions=1, seed=42, engine=None): seed = hash(seed) def generate(v): random.seed(seed + v) return random.randn(*shape[1:]) return fromlist(range(shape[0]), accessor=generate, npartitions=npartitions, engine=engine)
Generate random image data. Parameters ---------- shape : tuple, optional, default=(10, 50, 50) Dimensions of images. npartitions : int, optional, default=1 Number of partitions. seed : int, optional, default=42 Random seed.
8,935
def draw(self, scr): numHeaderRows = 1 scr.erase() vd().refresh() if not self.columns: return color_current_row = CursesAttr(colors.color_current_row, 5) disp_column_sep = options.disp_column_sep rowattrs = {} colattrs = {} ...
Draw entire screen onto the `scr` curses object.
8,936
def hashify_files(files: list) -> dict: return {filepath.replace(, ): hash_tree(filepath) for filepath in listify(files)}
Return mapping from file path to file hash.
8,937
def all_referenced_targets(self, result): if __debug__: from .property import Property assert is_iterable_typed(result, (VirtualTarget, Property)) deps = self.build_properties().dependency() all_targets = self.sources_ + deps r = [] ...
Returns all targets referenced by this subvariant, either directly or indirectly, and either as sources, or as dependency properties. Targets referred with dependency property are returned a properties, not targets.
8,938
def makevAndvPfuncs(self,policyFunc): mCount = self.aXtraGrid.size pCount = self.pLvlGrid.size MedCount = self.MedShkVals.size temp_grid = np.tile(np.reshape(self.aXtraGrid,(mCount,1,1)),(1,pCount,MedCount)) aMinGrid = np.tile(np.reshape(self.mL...
Constructs the marginal value function for this period. Parameters ---------- policyFunc : function Consumption and medical care function for this period, defined over market resources, permanent income level, and the medical need shock. Returns ------- ...
8,939
def statisticalInefficiency(A_n, B_n=None, fast=False, mintime=3, fft=False): A_n = np.array(A_n) if fft and B_n is None: return statisticalInefficiency_fft(A_n, mintime=mintime) if B_n is not None: B_n = np.array(B_n) else: B_n = np.array(A_n) N = A_n....
Compute the (cross) statistical inefficiency of (two) timeseries. Parameters ---------- A_n : np.ndarray, float A_n[n] is nth value of timeseries A. Length is deduced from vector. B_n : np.ndarray, float, optional, default=None B_n[n] is nth value of timeseries B. Length is deduced fr...
8,940
def _get_ctypes(self): ctypes = [] for related_object in self.model._meta.get_all_related_objects(): model = getattr(related_object, , related_object.model) ctypes.append(ContentType.objects.get_for_model(model).pk) if model.__subclasses__(): ...
Returns all related objects for this model.
8,941
def VarintReader(buf, pos=0): result = 0 shift = 0 while 1: b = buf[pos] result |= (ORD_MAP_AND_0X7F[b] << shift) pos += 1 if not ORD_MAP_AND_0X80[b]: return (result, pos) shift += 7 if shift >= 64: raise rdfvalue.DecodeError("Too many bytes when decoding varint.")
A 64 bit decoder from google.protobuf.internal.decoder.
8,942
def read(self, fp): "Reads a dictionary from an input stream." base_size = struct.unpack(str("=I"), fp.read(4))[0] self._units.fromfile(fp, base_size)
Reads a dictionary from an input stream.
8,943
def pancake_sort(arr): len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1): index_max = arr.index(max(arr[0:cur])) if index_max+1 != cur: if index_max != 0: arr[:index_max+1] = rever...
Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2)
8,944
def iterate_pubmed_identifiers(graph) -> Iterable[str]: return ( data[CITATION][CITATION_REFERENCE].strip() for _, _, data in graph.edges(data=True) if has_pubmed(data) )
Iterate over all PubMed identifiers in a graph. :param pybel.BELGraph graph: A BEL graph :return: An iterator over the PubMed identifiers in the graph
8,945
def runcode(code): for line in code: print(+line) exec(line,globals()) print() return ans
Run the given code line by line with printing, as list of lines, and return variable 'ans'.
8,946
def generic_pst(par_names=["par1"],obs_names=["obs1"],addreg=False): if not isinstance(par_names,list): par_names = list(par_names) if not isinstance(obs_names,list): obs_names = list(obs_names) new_pst = pyemu.Pst("pest.pst",load=False) pargp_data = populate_dataframe(["pargp"], ne...
generate a generic pst instance. This can used to later fill in the Pst parts programatically. Parameters ---------- par_names : (list) parameter names to setup obs_names : (list) observation names to setup Returns ------- new_pst : pyemu.Pst
8,947
def main(argv=None): if argv is None: argv = sys.argv[1:] cli = CommandLineTool() return cli.run(argv)
Main command line interface.
8,948
def get_record(self, path=None, no_pdf=False, test=False, refextract_callback=None): xml_doc = self.get_article(path) rec = create_record() title = self.get_title(xml_doc) if title: record_add_field(rec, , subfields=[(, title)]) (journal, d...
Convert a record to MARCXML format. :param path: path to a record. :type path: string :param test: flag to determine if it is a test call. :type test: bool :param refextract_callback: callback to be used to extract unstructured references. It ...
8,949
def separate(self): collections = [] start = None end = None for index in self.indexes: if start is None: start = index end = start continue if index != (end + 1): collections.append( ...
Return contiguous parts of collection as separate collections. Return as list of :py:class:`~clique.collection.Collection` instances.
8,950
def cover(ctx, html=False): params = if html else with ctx.cd(ROOT): ctx.run(.format(params), pty=True)
Run tests suite with coverage
8,951
def get_fernet(): global _fernet log = LoggingMixin().log if _fernet: return _fernet try: from cryptography.fernet import Fernet, MultiFernet, InvalidToken global InvalidFernetToken InvalidFernetToken = InvalidToken except BuiltinImportError: log.warnin...
Deferred load of Fernet key. This function could fail either because Cryptography is not installed or because the Fernet key is invalid. :return: Fernet object :raises: airflow.exceptions.AirflowException if there's a problem trying to load Fernet
8,952
def draw_linecollection(data, obj): content = [] edgecolors = obj.get_edgecolors() linestyles = obj.get_linestyles() linewidths = obj.get_linewidths() paths = obj.get_paths() for i, path in enumerate(paths): color = edgecolors[i] if i < len(edgecolors) else edgecolors[0] s...
Returns Pgfplots code for a number of patch objects.
8,953
async def start(self): self._command_task.start() try: await self._cleanup_old_connections() except Exception: await self.stop() raise iotile_id = next(iter(self.adapter.devices)) self.device = self.adapter.devices[iotile_i...
Start serving access to devices over bluetooth.
8,954
def satisfies(self, other): return ( self.dependency.name == other.dependency.name and self.relation(other) == SetRelation.SUBSET )
Returns whether this term satisfies another.
8,955
def configure_mongodb(self): self._display_info("Trying default configuration") host = "localhost" database_name = "INGInious" should_ask = True if self.try_mongodb_opts(host, database_name): should_ask = self._ask_boolean( "Successfully con...
Configure MongoDB
8,956
def dist(self): underlying_dist = self.underlying_dist if self._execution_strategy != NailgunTaskBase.HERMETIC: jdk_home_symlink = os.path.relpath( os.path.join(self._zinc_factory.get_options().pants_workdir, ), get_buildroot()) with self._lock: ...
Return the `Distribution` selected for Zinc based on execution strategy. :rtype: pants.java.distribution.distribution.Distribution
8,957
def imgmin(self): if not hasattr(self, ): imgmin = _np.min(self.images[0]) for img in self.images: imin = _np.min(img) if imin > imgmin: imgmin = imin self._imgmin = imgmin return _np.min(self.image)
Lowest value of input image.
8,958
def get_path(self): path = deque() __, node = self.get_focus() while not node.is_root(): stats = node.get_value() path.appendleft(hash(stats)) node = node.get_parent() return path
Gets the path to the focused statistics. Each step is a hash of statistics object.
8,959
def SetupDisplayDevice(self, type, state, percentage, energy, energy_full, energy_rate, time_to_empty, time_to_full, is_present, icon_name, warning_level): if not self.api1: raise dbus.exceptions.DBusException( , name=MOCK_IFACE + ) ...
Convenience method to configure DisplayDevice properties This calls Set() for all properties that the DisplayDevice is defined to have, and is shorter if you have to completely set it up instead of changing just one or two properties. This is only available when mocking the 1.0 API.
8,960
def save_user(self, idvalue, options=None): options = options or {} data = options.copy() data[] = idvalue return self.api_post(, data)
save user by a given id http://getstarted.sailthru.com/api/user
8,961
def configure_threecolor_image(self): order = {: 0, : 1, : 2} self.image = np.zeros((self.shape[0], self.shape[1], 3)) for color, var in self.multicolorvars.items(): channel = var.get() self.image[:, :, order[color]] = self.data[channel] ...
configures the three color image according to the requested parameters :return: nothing, just updates self.image
8,962
def add(self, data, conn_type, squash=True): if data in self.children: return data if not squash: self.children.append(data) return data if self.connector == conn_type: if (isinstance(data, QBase) and not data.negated and ...
Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. R...
8,963
def get_all_dhcp_options(self, dhcp_options_ids=None): params = {} if dhcp_options_ids: self.build_list_params(params, dhcp_options_ids, ) return self.get_list(, params, [(, DhcpOptions)])
Retrieve information about your DhcpOptions. :type dhcp_options_ids: list :param dhcp_options_ids: A list of strings with the desired DhcpOption ID's :rtype: list :return: A list of :class:`boto.vpc.dhcpoptions.DhcpOptions`
8,964
def adopt(self, grab): self.load_config(grab.config) self.doc = grab.doc.copy(new_grab=self) for key in self.clonable_attributes: setattr(self, key, getattr(grab, key)) self.cookies = deepcopy(grab.cookies)
Copy the state of another `Grab` instance. Use case: create backup of current state to the cloned instance and then restore the state from it.
8,965
def dropdb(self, name): if self.readonly: raise s_exc.IsReadOnly() while True: try: if not self.dbexists(name): return db = self.initdb(name) self.dirty = True self.xact.drop(db.db, dele...
Deletes an **entire database** (i.e. a table), losing all data.
8,966
def assign(self, node): child_object = self.translate(node.child) child_object.prefix = \ .format(name=node.name, attributes=.join(node.attributes.names)) return child_object
Translate an assign node into SQLQuery. :param node: a treebrd node :return: a SQLQuery object for the tree rooted at node
8,967
def refresh(self): if self.object_id is None: url = self.build_url(self._endpoints.get()) else: url = self.build_url( self._endpoints.get().format(id=self.object_id)) response = self.con.get(url) if not response: return False...
Updates this drive with data from the server :return: Success / Failure :rtype: bool
8,968
def do_EOF(self, args): if _debug: ConsoleCmd._debug("do_EOF %r", args) return self.do_exit(args)
Exit on system end of file character
8,969
def is_same_as(self, other_databox, headers=True, columns=True, header_order=True, column_order=True, ckeys=True): d = other_databox if not hasattr(other_databox, ): return False if headers: if not len(self.hkeys) == len(d...
Tests that the important (i.e. savable) information in this databox is the same as that of the other_databox. Parameters ---------- other_databox Databox with which to compare. headers=True Make sure all header elements match. columns=True...
8,970
def is_allowed(func): @wraps(func) def _is_allowed(user, *args, **kwargs): password = kwargs.pop(, None) if user.check_password(password): return func(user, *args, **kwargs) else: raise NotAllowedError() sig = inspect.signature(func) parms = lis...
Check user password, when is correct, then run decorated function. :returns: decorated function
8,971
def song(self): song = self._connection.request( , {: [-9, 9], : dict([(artist, ) for artist in self._artists]), : self._radio, : self._recent_artists, : self._connection.session.queue, : 0.75, : self....
:class:`Song` object of next song to play
8,972
def _predict(self, features): from sklearn.exceptions import NotFittedError try: prediction = self.kernel.predict_classes(features)[:, 0] except NotFittedError: raise NotFittedError( "{} is not fitted yet. Call with appropriate " ...
Predict matches and non-matches. Parameters ---------- features : numpy.ndarray The data to predict the class of. Returns ------- numpy.ndarray The predicted classes.
8,973
def to_categorical(y, nb_classes, num_classes=None): if num_classes is not None: if nb_classes is not None: raise ValueError("Should not specify both nb_classes and its deprecated " "alias, num_classes") warnings.warn("`num_classes` is deprecated. Switch to `nb_classes`." ...
Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to nb_classes). :param nb_classes: nb_classes: total number of classes. :param num_classses: depricated version...
8,974
def register_pubkey(self): p = pkcs_os2ip(self.dh_p) g = pkcs_os2ip(self.dh_g) pn = dh.DHParameterNumbers(p, g) y = pkcs_os2ip(self.dh_Ys) public_numbers = dh.DHPublicNumbers(y, pn) s = self.tls_session s.server_kx_pubkey = public_numbers.public_key(def...
XXX Check that the pubkey received is in the group.
8,975
def url_read_text(url, verbose=True): r data = url_read(url, verbose) text = data.decode() return text
r""" Directly reads text data from url
8,976
def manage_service_check_result_brok(self, b): host_name = b.data.get(, None) service_description = b.data.get(, None) if not host_name or not service_description: return service_id = host_name+"/"+service_description logger.debug("service check result: %s"...
A service check result brok has just arrived ...
8,977
def _get_qe(self, key, obj): if key in self._cached: return self._cached[key] qe = create_query_engine(obj, self._class) self._cached[key] = qe return qe
Instantiate a query engine, or retrieve a cached one.
8,978
def get_assessment_part_ids_by_banks(self, bank_ids): id_list = [] for assessment_part in self.get_assessment_parts_by_banks(bank_ids): id_list.append(assessment_part.get_id()) return IdList(id_list)
Gets the list of ``AssessmentPart Ids`` corresponding to a list of ``Banks``. arg: bank_ids (osid.id.IdList): list of bank ``Ids`` return: (osid.id.IdList) - list of assessment part ``Ids`` raise: NullArgument - ``bank_ids`` is ``null`` raise: OperationFailed - unable to complete r...
8,979
def public_key_sec(self): if self.is_coinbase(): return None opcodes = ScriptTools.opcode_list(self.script) if len(opcodes) == 2 and opcodes[0].startswith("[30"): sec = h2b(opcodes[1][1:-1]) return sec return None
Return the public key as sec, or None in case of failure.
8,980
def read(self, filename=None): self._init_filename(filename) data = odict() with open(self.real_filename) as ndx: current_section = None for line in ndx: line = line.strip() if len(line) == 0: continue ...
Read and parse index file *filename*.
8,981
def draw(self): if self.hidden: return False if self.background_color is not None: render.fillrect(self.surface, self.background_color, rect=pygame.Rect((0, 0), self.frame.size)) for child in self.children: if not child....
Do not call directly.
8,982
def set(self, column, value, useMethod=True, **context): col = self.schema().column(column, raise_=False) if col is None: collector = self.schema().collector(column) if collector: my_context = self.context() for k, v in my_c...
Sets the value for this record at the inputted column name. If the columnName provided doesn't exist within the schema, then the ColumnNotFound error will be raised. :param columnName | <str> value | <variant> :return <bool> changed
8,983
def dump_xearth_markers(markers, name=): output = [] for identifier, point in markers.items(): line = [ % (point.latitude, point.longitude), ] if hasattr(point, ) and point.name: if name == : line.append( % (identifier, point.name)) elif name == : ...
Generate an Xearth compatible marker file. ``dump_xearth_markers()`` writes a simple Xearth_ marker file from a dictionary of :class:`trigpoints.Trigpoint` objects. It expects a dictionary in one of the following formats. For support of :class:`Trigpoint` that is:: {500936: Trigpoint(52.06603...
8,984
def git_checkout(repo_dir, ref, branch=None): command = [, , ] if branch: command.extend([, .format(branch)]) command.append(ref) return execute_git_command(command, repo_dir=repo_dir)
Do a git checkout of `ref` in `repo_dir`. If branch is specified it should be the name of the new branch.
8,985
def setup(self, settings): self.extract = tldextract.TLDExtract() self.redis_conn = redis.Redis(host=settings[], port=settings[], db=settings.get()) try: self.redis_conn.info() self.logg...
Setup redis and tldextract
8,986
def result(self): self.__result.sort(cmp = self.__cmp, key = self.__key, reverse = self.__reverse) return self.__result
Formats the result.
8,987
def make_opfields( cls ): opfields = {} for opname in SERIALIZE_FIELDS.keys(): opcode = NAME_OPCODES[opname] opfields[opcode] = SERIALIZE_FIELDS[opname] return opfields
Calculate the virtulachain-required opfields dict.
8,988
def allowed_values(self): data = clips.data.DataObject(self._env) lib.EnvSlotAllowedValues( self._env, self._cls, self._name, data.byref) return tuple(data.value) if isinstance(data.value, list) else ()
A tuple containing the allowed values for this Slot. The Python equivalent of the CLIPS slot-allowed-values function.
8,989
def get_next(self, label): while self._get_current_label() != label: self._skip_section() return self._read_section()
Get the next section with the given label
8,990
def to_array(self): array = super(Chat, self).to_array() array[] = int(self.id) array[] = u(self.type) if self.title is not None: array[] = u(self.title) if self.username is not None: array[] = u(self.username) if self.first_nam...
Serializes this Chat to a dictionary. :return: dictionary representation of this object. :rtype: dict
8,991
def create_hosted_zone(self, name, caller_reference=None, comment=None): body = xml_generators.create_hosted_zone_writer( connection=self, name=name, caller_reference=caller_reference, comment=comment ) root = self._send_request( ...
Creates and returns a new hosted zone. Once a hosted zone is created, its details can't be changed. :param str name: The name of the hosted zone to create. :keyword str caller_reference: A unique string that identifies the request and that allows failed create_hosted_zone requests t...
8,992
def i18n_install(lc=None): log.debug(.format(lc=lc)) if lc is None: lc = i18n_system_locale() if lc is None: log.debug() translator = gettext.NullTranslations() else: child_locales = i18n_support_locale(lc) log.debug( .format(domain=proje...
Install internationalization support for the clients using the specified locale. If there is no support for the locale, the default locale will be used. As last resort, a null translator will be installed. :param lc: locale to install. If None, the system default locale will be used.
8,993
def from_long(self, number): if not isinstance(number, baseinteger): raise TypeError("number can only be an instance of type baseinteger") self._call("fromLong", in_p=[number])
Make PCI address from long. in number of type int
8,994
def buckets_insert(self, bucket, project_id=None): args = {: project_id if project_id else self._project_id} data = {: bucket} url = Api._ENDPOINT + (Api._BUCKET_PATH % ) return datalab.utils.Http.request(url, args=args, data=data, credentials=self._credentials)
Issues a request to create a new bucket. Args: bucket: the name of the bucket. project_id: the project to use when inserting the bucket. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error performing the operation.
8,995
def get_route(self, file_id): title = % self.__class__.__name__ input_fields = { : file_id, } for key, value in input_fields.items(): if value: object_title = % (title, key, str(value)) self.fields.val...
a method to retrieve route information for file on telegram api :param file_id: string with id of file in a message send to bot :return: dictionary of response details with route details in [json][result]
8,996
def _equivalent_node_iterator_helper(self, node: BaseEntity, visited: Set[BaseEntity]) -> BaseEntity: for v in self[node]: if v in visited: continue if self._has_no_equivalent_edge(node, v): continue visited.add(v) yield ...
Iterate over nodes and their data that are equal to the given node, starting with the original.
8,997
def monte_carlo_vol(self, ndraws=10000, rstate=None, return_overlap=True): if rstate is None: rstate = np.random samples = [self.sample(rstate=rstate, return_q=True) for i in range(ndraws)] qsum = sum([q for (x, idx, q) i...
Using `ndraws` Monte Carlo draws, estimate the volume of the *union* of ellipsoids. If `return_overlap=True`, also returns the estimated fractional overlap with the unit cube.
8,998
def read_wave(path): with contextlib.closing(wave.open(path, )) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width == 2 sample_rate = wf.getframerate() assert sample_rate in (8000, 16000, 32000) ...
Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate).
8,999
def bytes_available(device): bytes_avail = 0 if isinstance(device, alarmdecoder.devices.SerialDevice): if hasattr(device._device, "in_waiting"): bytes_avail = device._device.in_waiting else: bytes_avail = device._device.inWaiting() elif isinstance(device, alarmd...
Determines the number of bytes available for reading from an AlarmDecoder device :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: int