code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def read_in_characters_lines(): <NEW_LINE> <INDENT> with open(r"the_office_lines_scripts.csv", "r", encoding='utf-8') as csvfile: <NEW_LINE> <INDENT> csv_f = csv.reader(csvfile) <NEW_LINE> for _, _, _, _, line_text, speaker, _ in csv_f: <NEW_LINE> <INDENT> speaker = speaker.lower() <NEW_LINE> if speaker in character_li...
Stores all characters' lines into a dictionary
625941d09f2886367277a9f8
def get_nnn_shells(self, dr=0.1): <NEW_LINE> <INDENT> nnn = [] <NEW_LINE> T_nnn = [] <NEW_LINE> N_nnn = np.empty(self._nsites, dtype=int) <NEW_LINE> try: <NEW_LINE> <INDENT> pbcdist = self._nblist.get_pbc_distances_and_translations <NEW_LINE> for i in range(self._nsites): <NEW_LINE> <INDENT> nn_i = self._nn[i] <NEW_LIN...
Calculate shells of next nearest neighbors and store them in `nnn'. Note: This routine requires cells that are actually large enough to contain the next-nearest neighbor shells.
625941d01d351010ab855c87
def random_date(self): <NEW_LINE> <INDENT> admin_option = AdminOption.objects.get() <NEW_LINE> start = admin_option.window_start <NEW_LINE> end = admin_option.window_end <NEW_LINE> return start + datetime.timedelta( seconds=random.randint(0, int((end - start).total_seconds())))
Generate a random datetime in our window
625941d0baa26c4b54cb128a
def t_input(list2: [Path], third_string: str) -> [Path]: <NEW_LINE> <INDENT> real_final_list = [] <NEW_LINE> sub_filelist = [] <NEW_LINE> final_filelist = [] <NEW_LINE> for sub_file in list2: <NEW_LINE> <INDENT> if sub_file.is_file(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not str(sub_file).endswith('.DS_Store...
Prints all the paths of the text files that contain a specific input
625941d001c39578d7e74fa7
def start(self, mode, ports=DEFAULT_PORTS): <NEW_LINE> <INDENT> if self._satellites: <NEW_LINE> <INDENT> logger.warn( "Cannot startup satellites because they are already running.") <NEW_LINE> return <NEW_LINE> <DEDENT> logger.info("Starting up mock satellite group.") <NEW_LINE> self.__init__(mode, ports=ports)
Restarts the group of mock satellites. Should only be called if the group is currently shutdown. Parameters ---------- mode : str Mode deteremines the response characteristics, like timing, of the mock satellites. Can be 'typical', 'slow_succeed', or 'slow_fail'. ports : list of int Ports the mock satellit...
625941d05e10d32532c5f092
def rotate(self, matrix): <NEW_LINE> <INDENT> n = len(matrix) <NEW_LINE> for t in range(n//2): <NEW_LINE> <INDENT> for i in range(t,n-t-1): <NEW_LINE> <INDENT> x = i <NEW_LINE> y = t <NEW_LINE> a = matrix[y][n-1-x] <NEW_LINE> matrix[y][n-1-x] = matrix[x][y] <NEW_LINE> b = matrix[n-1-x][n-1-y] <NEW_LINE> matrix[n-1-x][n...
:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
625941d0d268445f265b4fd9
def smooth(x, window_len=11, window="hanning"): <NEW_LINE> <INDENT> if x.ndim != 1: <NEW_LINE> <INDENT> raise ValueError("smooth only accepts 1 dimension arrays.") <NEW_LINE> <DEDENT> if x.size < window_len: <NEW_LINE> <INDENT> raise ValueError("Input vector needs to be bigger than window size.") <NEW_LINE> <DEDENT> if...
Smooth things.
625941d03617ad0b5ed68063
def reset_vars(self, k): <NEW_LINE> <INDENT> self.k = k <NEW_LINE> self.clusters = np.array([[float("inf"), 0, 0]]*self.data.shape[0], dtype=object) <NEW_LINE> self.prev_centroids = np.array([])
Set all clusters back to start Set prev centroids to nothing
625941d0be8e80087fb20dad
@pytest.yield_fixture(scope="class") <NEW_LINE> def db(): <NEW_LINE> <INDENT> db_path = "tests/test.sqlite" <NEW_LINE> DbSession.create_test_db(db_path) <NEW_LINE> yield <NEW_LINE> os.remove(db_path)
Session-wide test database.
625941d0de87d2750b85fefe
def test_4_delete_hdfs_service_instance(self): <NEW_LINE> <INDENT> step("Stop HDFS instance") <NEW_LINE> self.instance_hdfs.stop() <NEW_LINE> self.instance_hdfs.ensure_stopped() <NEW_LINE> step("Delete HDFS instance") <NEW_LINE> self.instance_hdfs.delete() <NEW_LINE> step("Ensure HDFS instance deleted properly") <NEW_L...
<b>Description:</b> Delete HDFS instance and check if it is deleted. <b>Input data:</b> HDFS instance <b>Expected results:</b> HDFS instance is deleted. <b>Steps:</b> 1. Delete HDFS instance 2. Verify if HDFS instance is deleted
625941d07cff6e4e81117af1
def computed_untuned_score(self): <NEW_LINE> <INDENT> self.learner.fit(self.X_merged, self.Y_merged) <NEW_LINE> Y_predict = self.learner.predict(self.X_test) <NEW_LINE> self.untuned_test_score = 0 <NEW_LINE> if self.goal == "accuracy": <NEW_LINE> <INDENT> self.untuned_test_score = accuracy_score(self.Y_test, Y_predict)...
Calculate untuned score. Must be called before the tuning
625941d0293b9510aa2c3401
def applyPersistence(self,imgs,coeffs): <NEW_LINE> <INDENT> if not len(imgs)==len(coeffs): <NEW_LINE> <INDENT> raise GalSimIncompatibleValuesError("The length of 'imgs' and 'coeffs' must be the same", imgs=imgs, coeffs=coeffs) <NEW_LINE> <DEDENT> for img,coeff in zip(imgs,coeffs): <NEW_LINE> <INDENT> self += coeff*img
Applies the effects of persistence to the `Image` instance. Persistence refers to the retention of a small fraction of the signal after resetting the imager pixel elements. The persistence signal of a previous exposure is left in the pixel even after several detector resets. This effect is most likely due to charge tr...
625941d05fcc89381b1e182b
def __bool__(self): <NEW_LINE> <INDENT> return _pypl.plValuesVector___bool__(self)
__bool__(plValuesVector self) -> bool
625941d0097d151d1a222fc5
def getVecIndexList(self): <NEW_LINE> <INDENT> return _osgUtil.Hit_getVecIndexList(self)
getVecIndexList(Hit self) -> vectorGLint
625941d03d592f4c4ed1d1d8
def test_dc_rdma_write_stream(self): <NEW_LINE> <INDENT> self.create_players(Mlx5DcStreamsRes, qp_count=2, send_ops_flags=e.IBV_QP_EX_WITH_RDMA_WRITE) <NEW_LINE> u.rdma_traffic(**self.traffic_args, new_send=True, send_op=e.IBV_QP_EX_WITH_RDMA_WRITE)
Check good flow of DCS. Calculate stream_id for DCS test by setting same stream id twice for WR and after increase it. Setting goes by loop and after stream_id is more than number of concurrent streams + 1 then stream_id returns to 1. :raises SkipTest: In case DCI is not supported with HW
625941d02c8b7c6e89b3592c
def move_key(self, key, flag: bool): <NEW_LINE> <INDENT> if flag: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass
flag:True = 移动到首 False = 移动到末尾
625941d0236d856c2ad44947
def __init__(self, id, properties={}, flag_to1=False): <NEW_LINE> <INDENT> super(Dbf1toN_Left, self).__init__(id, properties) <NEW_LINE> self.flag_to1 = flag_to1
Constructor.
625941d0f8510a7c17cf9867
def earningspershare(self): <NEW_LINE> <INDENT> id = 207 <NEW_LINE> eps = [] <NEW_LINE> for x in range(4): <NEW_LINE> <INDENT> e = float(str(self.summary[12].find("span",{"data-reactid":str(id)}).text)) <NEW_LINE> eps.append(e) <NEW_LINE> id += 2 <NEW_LINE> <DEDENT> return eps
Return the eps values over the last 4 years.
625941d08c0ade5d55d3eb27
def enabled(self, repository_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> enabled = self[repository_id]["enabled"][0] <NEW_LINE> return enabled.strip().lower() == "true" <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return self._DEFAULT_ENABLED_VALUE
Return whether the repository is enabled or disabled. @param repository_id: the repository identifier @type repository_id: string @return: the repository status @rtype: bool
625941d071ff763f4b5497f8
def equals(before, after, vals=None, **kwds): <NEW_LINE> <INDENT> errors = kwds['error'] if 'error' in kwds else True <NEW_LINE> variants = kwds['variants'] if 'variants' in kwds else None <NEW_LINE> vars = kwds['variables'] if 'variables' in kwds else 'x' <NEW_LINE> _vars = get_variables(after, vars) <NEW_LINE> locals...
check if equations before and after are equal at the given vals Inputs: before -- an equation string after -- an equation string vals -- a dict with variable names as keys and floats as values Additional Inputs: variables -- a list of variable names locals -- a dict with variable names as keys and...
625941d031939e2706e4cfd5
def init(self): <NEW_LINE> <INDENT> if self.net is None: <NEW_LINE> <INDENT> self.net = NetManager(self.conf_path, self.loop, self.event_notify)
子类才调用
625941d045492302aab5e430
def geolytica(location, **kwargs): <NEW_LINE> <INDENT> return get(location, provider='geolytica', **kwargs)
Geolytica (Geocoder.ca) Provider :param location: Your search location you want geocoded.
625941d0dc8b845886cb56a1
def _check_mntners(self, mntner_pk_list: List[str], source: str) -> Tuple[bool, List[RPSLMntner]]: <NEW_LINE> <INDENT> mntner_pk_set = set(mntner_pk_list) <NEW_LINE> mntner_objs: List[RPSLMntner] = [ m for m in self._mntner_db_cache if m.pk() in mntner_pk_set and m.source() == source ] <NEW_LINE> mntner_pks_to_resolve:...
Check whether authentication passes for a list of maintainers. Returns True if at least one of the mntners in mntner_list passes authentication, given self.passwords and self.keycert_obj_pk. Updates and checks self._mntner_db_cache to prevent double retrieval of maintainers.
625941d0be8e80087fb20dae
def login_redirect(referer=None): <NEW_LINE> <INDENT> if referer is None: <NEW_LINE> <INDENT> referer = request.values.get('referer') <NEW_LINE> <DEDENT> if referer: <NEW_LINE> <INDENT> from six.moves.urllib.parse import urlparse <NEW_LINE> blacklist = [url_for('webaccount.register'), url_for('webaccount.logout'), url_...
Redirect to url after login.
625941d0435de62698dfddb9
def _format_for_json(data): <NEW_LINE> <INDENT> if isinstance(data, (int, float, str)): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> elif isinstance(data, _AssociationDict): <NEW_LINE> <INDENT> return dict(data) <NEW_LINE> <DEDENT> elif isinstance(data, _AssociationList): <NEW_LINE> <INDENT> return list(data) <N...
Format into json and load lazy-loading attr to prevent stall
625941d094891a1f4081bc15
def test_createCombineArchiveFromDirectory(): <NEW_LINE> <INDENT> omexPath = tempfile.NamedTemporaryFile(suffix="omex") <NEW_LINE> directory = os.path.join(TESTDATA_DIR, "utils", "omex_from_zip") <NEW_LINE> omex.combineArchiveFromDirectory(omexPath=omexPath.name, directory=directory) <NEW_LINE> assert omexPath is not N...
Testing if COMBINE archive can be created from directory.
625941d04e4d5625662d4543
def set_auth(self, user, password): <NEW_LINE> <INDENT> self.user = bytearray() <NEW_LINE> self.user.extend(map(ord, user)) <NEW_LINE> self.password = bytearray() <NEW_LINE> if password != None: <NEW_LINE> <INDENT> self.password.extend(map(ord, password)) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN...
Set user/password for authentication.
625941d0e5267d203edcde08
def set_device_action_cmd_param(device): <NEW_LINE> <INDENT> nodemap = device.remote_port.nodemap <NEW_LINE> trigger_selector = nodemap.get_node("TriggerSelector").get() <NEW_LINE> trigger_selector.set_symbolic_value("FrameStart") <NEW_LINE> print(" TriggerSelector = FrameStart") <NEW_LINE> trigger_mode = nodemap.get_n...
Set device action command parameters.
625941d094891a1f4081bc16
def __init__(self, ident=None, participant_token: Token = None): <NEW_LINE> <INDENT> super().__init__(ident) <NEW_LINE> self.__participant_token = participant_token <NEW_LINE> self.__pronoun = False
Default constructor, initializes object fields with new instances.
625941d07cff6e4e81117af2
def sequence_padding(seqs_): <NEW_LINE> <INDENT> max_sequence = max(list(map(len, seqs_))) <NEW_LINE> padded_sequence = [i + [0] * (max_sequence - len(i)) if len(i) < max_sequence else i for i in seqs_] <NEW_LINE> return padded_sequence
Padding the seq with same length for RNN :param seqs_: taking batch of without padded seqs as argument ex : [[278698,3442], [194661] , [1098,2341,77]] :return: padded with zeros with max len of seq in batch ex : [ [278698,3442,0] , [194661,0,0] ,[1098,2341,77]] :raise: if seq is not 2 dimen...
625941d007f4c71912b115ef
def struct_to_string_streaming_fns( tu, namespace, struct, structname, extras, out_h, out_cpp, ): <NEW_LINE> <INDENT> out_h.write( f'\n') <NEW_LINE> out_h.write( f'/* Writes {structname}\'s members, labelled and inside (...), to a stream. */\n') <NEW_LINE> out_h.write( f'FZ_FUNCTION std::ostream& operator<< (std::ostre...
Writes operator<< functions for streaming text representation of C struct members. Should be called at top-level (i.e. not inside 'namespace mupdf {...}') in out_h and out_cpp.
625941d0d53ae8145f87a3db
def __init_url(self): <NEW_LINE> <INDENT> portals_self_url = "{}/portals/self".format(self._url) <NEW_LINE> params = { "f" :"json" } <NEW_LINE> res = self._get(url=portals_self_url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) <NEW_LINE> if "helperSer...
loads the information into the class
625941d0004d5f362079a49f
def room_6_item_handler(current_room, verb, item_name, feature): <NEW_LINE> <INDENT> player = current_room.get_player() <NEW_LINE> general_item_handler(current_room, verb, item_name, feature) <NEW_LINE> save_object_state(current_room)
Handle room 6, washroom, player and item interactions. Args: current_room (:obj:`Room`): The current room the player is in. verb (str): The action the user would like to take. item_name: The name of the item the user would like to use.
625941d0ac7a0e7691ed4237
def test_sum_of_energy(self): <NEW_LINE> <INDENT> obk = CechaEnergii(lw_kw.Dm_Energy) <NEW_LINE> obk.cumulative_init() <NEW_LINE> self.assertEqual(obk.cumulative_value, 0.0) <NEW_LINE> obk.cumulative_update(1) <NEW_LINE> self.assertEqual(obk.cumulative_value, 1.0) <NEW_LINE> obk.cumulative_update(3) <NEW_LINE> self.ass...
TestEnergyFeatures:
625941d0fff4ab517eb2f5a8
def get_files(path: str) -> List: <NEW_LINE> <INDENT> files = [] <NEW_LINE> for file in os.listdir(path): <NEW_LINE> <INDENT> if os.path.isfile(os.path.join(path, file)): <NEW_LINE> <INDENT> files.append(file) <NEW_LINE> <DEDENT> <DEDENT> return sorted(files, reverse=True)
Returns list of files inside the path directory
625941d08da39b475bd650e1
def _from_tree_results(self, tree): <NEW_LINE> <INDENT> self._from_tree_type_changes(tree) <NEW_LINE> self._from_tree_default(tree, 'dictionary_item_added') <NEW_LINE> self._from_tree_default(tree, 'dictionary_item_removed') <NEW_LINE> self._from_tree_value_changed(tree) <NEW_LINE> if self.ignore_order: <NEW_LINE> <IND...
Populate this object by parsing an existing reference-style result dictionary. :param tree: A TreeResult :return:
625941d05e10d32532c5f093
@app.route("/student_infor_form") <NEW_LINE> def student_infor_form(): <NEW_LINE> <INDENT> return render_template("student_infor_form.html")
Form to fill out new student.
625941d0e76e3b2f99f3a976
def create_transition(oracle, method='trn'): <NEW_LINE> <INDENT> mat, hist, n = _create_trn_mat_symbolic(oracle, method) <NEW_LINE> return mat, hist, n
Create a transition matrix based on oracle links
625941d0fbf16365ca6f6332
def __init__(self, camera, default_color=None): <NEW_LINE> <INDENT> self._camera = camera <NEW_LINE> self._dims = camera.resolution <NEW_LINE> self._buffer_dims = _round_buffer_dims(self._dims) <NEW_LINE> self._buffer = Image.new('RGBA', self._buffer_dims) <NEW_LINE> self._overlay = None <NEW_LINE> self._draw = ImageDr...
Initializes Annotator parameters. Args: camera: picamera.PiCamera camera object to overlay on top of. default_color: PIL.ImageColor (with alpha) default for the drawn content.
625941d0d58c6744b4257dcc
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> common.config.add_argument(parser) <NEW_LINE> parser.add_argument( "instrument", type=common.args.instrument, help="The instrument to get candles for" ) <NEW_LINE> parser.add_argument( "--mid", action='store_true', help="Get midpoint-based ca...
Create an API context, and use it to fetch candles for an instrument. The configuration for the context is parsed from the config file provided as an argumentV
625941d076d4e153a657ec9d
def encode_ansi(*codes: int) -> str: <NEW_LINE> <INDENT> return f"\033[{';'.join([str(abs(code)) for code in codes])}m"
Encodes the ANSI code into an ANSI escape sequence. >>> encode_ansi(30) '\x1b[30m' Support defining multiple codes: >>> encode_ansi(1, 33) '\x1b[1;33m' All numbers are treated as positive; the sign doesn't matter: >>> encode_ansi(-31) '\x1b[31m' :param codes: ANSI codes :return: ANSI escaped sequence
625941d05fdd1c0f98dc03a0
def _compute_sigma(self, scaled_residuals=False): <NEW_LINE> <INDENT> grad_fcn = self.solver_object.gradF() <NEW_LINE> grad_fcn.setInput(self.xx_init, casadi.NLP_SOLVER_X0) <NEW_LINE> grad_fcn.setInput(self.get_par_vals(scaled_residuals=scaled_residuals), casadi.NLP_SOLVER_P) <NEW_LINE> grad_fcn.evaluate() <NEW_LINE> g...
Computes the objective scaling factor sigma. Parameters:: scaled_residuals -- If True, return sigma for the equation scaled NLP.
625941d0b7558d58953c507f
def send_message(word, word_eol, userdata): <NEW_LINE> <INDENT> if not(word[0] == "65293" and word[1] == "0"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> msg = hexchat.get_info('inputbox') <NEW_LINE> if msg is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> hexchat.command("settext %s" % greentext(msg))
Gets the inputbox's text, perform substitutions and replaces it. This function is called every time a key is pressed. It will stop if that key isn't ENTER (without modifiers, e.g. SHIFT + ENTER), or if the input box is empty.
625941d0498bea3a759b9c1b
def searchFirst(pattern, haystack): <NEW_LINE> <INDENT> for x in search(pattern, haystack): <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> return None
Return a (index, Match) pair or None if there is no match.
625941d056ac1b37e626433a
def create_offer(name=u"Dùmϻϒ offer", offer_type="Site", max_basket_applications=None, range=None, condition=None, benefit=None, priority=0, status=None, start=None, end=None): <NEW_LINE> <INDENT> if range is None: <NEW_LINE> <INDENT> range, __ = models.Range.objects.get_or_create( name=u"All products räñgë", includes_...
Helper method for creating an offer
625941d038b623060ff0af5a
def parse_subsets(subsets: list): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for subset in subsets: <NEW_LINE> <INDENT> subset = str(subset) <NEW_LINE> if subset.count("-") == 1: <NEW_LINE> <INDENT> start, end = subset.split("-") <NEW_LINE> compref = commonprefix([start, end]) <NEW_LINE> if compref and compref[-1].isdigit...
Parse subsets written in short format
625941d0379a373c97cfacb1
def test_model_str_method(self): <NEW_LINE> <INDENT> self.assertIn(str(self.instance.action), str(self.instance)) <NEW_LINE> self.assertIn(str(self.instance.condition), str(self.instance)) <NEW_LINE> self.assertIn(str(self.instance.target_model), str(self.instance))
Test model `__str__` method
625941d01f037a2d8b94636a
def select_next(self): <NEW_LINE> <INDENT> comps = [] <NEW_LINE> for comp in self.comps: <NEW_LINE> <INDENT> children = comp.parent.children <NEW_LINE> index = children.index(comp) + 1 <NEW_LINE> if index > len(children) - 1: <NEW_LINE> <INDENT> index = 0 <NEW_LINE> <DEDENT> comps.append(children[index]) <NEW_LINE> <DE...
For each component in the selection, return the component that appears one after in the parent's list of children.
625941d096565a6dacc8f838
def add_legend(self): <NEW_LINE> <INDENT> self.ax.legend( loc="upper center", bbox_to_anchor=(0.5, -0.1), fancybox=True, shadow=True, ncol=5, )
Add legend to show in figure.
625941d0a8ecb033257d3239
def get_science_segments(ifo, cp, start_time, end_time, out_dir, tag=None): <NEW_LINE> <INDENT> segValidSeg = segments.segment([start_time,end_time]) <NEW_LINE> sciSegName = cp.get_opt_tags( "workflow-segments", "segments-%s-science-name" %(ifo.lower()), [tag]) <NEW_LINE> sciSegUrl = cp.get_opt_tags( "workflow-segments...
Obtain science segments for the selected ifo Parameters ----------- ifo : string The string describing the ifo to obtain science times for. start_time : gps time (either int/LIGOTimeGPS) The time at which to begin searching for segments. end_time : gps time (either int/LIGOTimeGPS) The time at which to sto...
625941d0f548e778e58cd6ea
def sanitize(s): <NEW_LINE> <INDENT> for c in """ \t!@#$%^&*()\\;,<>"'[]{}~|""": <NEW_LINE> <INDENT> s = s.replace(c, '_') <NEW_LINE> <DEDENT> return s
Removes shell metacharacters from a string.
625941d0fb3f5b602dac3800
def test_008_file_console(self): <NEW_LINE> <INDENT> rmlog() <NEW_LINE> fileSpecs = [{"filename": LOGFILE, "level": logging.DEBUG, "format": "console"}] <NEW_LINE> termSpecs = {"color": True, "splitLines": True, "level": logging.WARNING} <NEW_LINE> Logger.init(LOGDIR, termSpecs=termSpecs, fileSpecs=fileSpecs) <NEW_LINE...
Remove log and test console-like formatting
625941d0b7558d58953c5080
def rouletteWheelSelection(self): <NEW_LINE> <INDENT> if len(self.selectionProbabilities) == 0: <NEW_LINE> <INDENT> self.calculateRankingProbabilities() <NEW_LINE> <DEDENT> parents = [self.population[0]] <NEW_LINE> while len(parents) + self.keepSize < self.populationSize: <NEW_LINE> <INDENT> randomProbability = random(...
A roulette wheel selection method using ranked selection The method is implemented based on the description in: http://dx.doi.org/10.1002/0471671746.ch1 It calculates the probability of a chromosome being selected for pairing as a function of its rank (i.e. position in the population). It use a rank probability measu...
625941d0be383301e01b55f1
def _set_signaled_bandwidth(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass( v, base=RestrictedClassType( base_type=long, restriction_dict={"range": ["0..18446744073709551615"]}, int_size=64, ), is_leaf=...
Setter method for signaled_bandwidth, mapped from YANG variable /network_instances/network_instance/mpls/lsps/constrained_path/tunnels/tunnel/bandwidth/state/signaled_bandwidth (oc-mplst:bandwidth-kbps) If this variable is read-only (config: false) in the source YANG file, then _set_signaled_bandwidth is co...
625941d031939e2706e4cfd6
def delta_in_hms(self): <NEW_LINE> <INDENT> hours = int(self.delta / (60 * 60)) <NEW_LINE> minutes = int((self.delta % (60 * 60)) / 60) <NEW_LINE> seconds = self.delta % 60 <NEW_LINE> return "{}h {:>02}m {:>05.2f}s".format(hours, minutes, seconds)
Get time detla in a human readable format
625941d023e79379d52ee6d0
def start(self, addr_record, conn_params, on_done): <NEW_LINE> <INDENT> if self._state != self._STATE_INIT: <NEW_LINE> <INDENT> raise AMQPConnectorWrongState( 'Already in progress or finished; state={}'.format(self._state)) <NEW_LINE> <DEDENT> self._addr_record = addr_record <NEW_LINE> self._conn_params = conn_params <...
Asynchronously perform a single TCP/[SSL]/AMQP connection attempt. :param tuple addr_record: a single resolved address record compatible with `socket.getaddrinfo()` format. :param pika.connection.Parameters conn_params: :param callable on_done: Function to call upon completion of the workflow: `on_done(pika.co...
625941d0a4f1c619b28b01a4
def update_student_listbox(): <NEW_LINE> <INDENT> students_list.clear() <NEW_LINE> for student in student_list: <NEW_LINE> <INDENT> students_list.append(student.get_name())
Display all students in a listbox.
625941d0596a897236089c2d
def remove_all_but_first_runs(self, restored_runs): <NEW_LINE> <INDENT> logger.info("Restored runs %d", restored_runs) <NEW_LINE> logger.info("%s %s", self.instance_order, len(self.instance_order)) <NEW_LINE> if len(self.instance_order) == restored_runs: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN...
Delete all but the first *restored_runs* instances. Useful to delete all unnecessary entries after a crash in order to restart. Parameters ---------- int : restored runs The number of instance runs to restore. In contrast to most other arguments, this argument is 1-based.
625941d04e696a04525c95b8
@mode <NEW_LINE> def files(opt): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for data in get_data(opt): <NEW_LINE> <INDENT> for fileinfo in data["files"]: <NEW_LINE> <INDENT> text = os.path.join(data["path"], fileinfo.name) <NEW_LINE> for i in opt.show_time or []: <NEW_LINE> <INDENT> x = { "a": fileinfo[stat.ST_ATIME + 1]...
Dumps files :param argparse.Namespace opt: command line options
625941d016aa5153ce3625e4
def no_multiquery(self): <NEW_LINE> <INDENT> return self._options.get('no_multiquery', None)
Turn multiquery optimization off; default is on.
625941d0236d856c2ad44948
def cropimage_to_match(fitsfile1, fitsfile2): <NEW_LINE> <INDENT> ralim, declim = getbounds( fitsfile2 ) <NEW_LINE> xlim, ylim = cropimage( fitsfile1, ralim, declim) <NEW_LINE> return( xlim, ylim )
Crop fitsfile1 so that it matches fitsfile2 :param fitsfile1: :param fitsfile2: :return:
625941d055399d3f05588821
def delete(self, **kwargs): <NEW_LINE> <INDENT> response = self._requester.request( "DELETE", "courses/{}/quizzes/{}/groups/{}".format( self.course_id, self.quiz_id, self.id ), _kwargs=combine_kwargs(**kwargs), ) <NEW_LINE> return response.status_code == 204
Get details of the quiz group with the given id. :calls: `DELETE /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id <https://canvas.instructure.com/doc/api/quiz_question_groups.html#method.quizzes/quiz_groups.destroy>`_ :returns: True if the result was successful (Status code of 204) :rtype: bool
625941d08e05c05ec3eea4e2
def get_bindable(obj, base): <NEW_LINE> <INDENT> if not isinstance(obj, types.FunctionType): <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> closurevars = getclosurevars(obj) <NEW_LINE> if '__class__' in closurevars.nonlocals: <NEW_LINE> <INDENT> obj = replace_class_closure(obj, base) <NEW_LINE> <DEDENT> return obj
attr : dict of inspect.Attribute base : type Returns a obj/function that can properly be moved to another class. Largely this deals with Python 3 and super() binding the class via a closure.
625941d04f6381625f114ba8
def test_n_clients_activation_reverse_order(self): <NEW_LINE> <INDENT> self.register_n_users(DEFAULT_NUMBER_OF_CLIENTS_FOR_TESTS) <NEW_LINE> mails = self.get_n_activation_mails(DEFAULT_NUMBER_OF_CLIENTS_FOR_TESTS) <NEW_LINE> for i in range(DEFAULT_NUMBER_OF_CLIENTS_FOR_TESTS - 1, -1, -1): <NEW_LINE> <INDENT> activation...
in this test we register multiple clients and activate them in reverse order to prove that using an activation link doesn't invalidate another one :return:
625941d0f7d966606f6aa171
def CopyFromDateTimeString(self, time_string): <NEW_LINE> <INDENT> date_time_values = self._CopyDateTimeFromString(time_string) <NEW_LINE> year = date_time_values.get('year', 0) <NEW_LINE> month = date_time_values.get('month', 0) <NEW_LINE> day_of_month = date_time_values.get('day_of_month', 0) <NEW_LINE> hours = date_...
Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time...
625941d05fc7496912cc3aeb
def tiecorrect(xranks): <NEW_LINE> <INDENT> rankbincount = np.bincount(np.asarray(xranks,dtype=int)) <NEW_LINE> nties = rankbincount[rankbincount > 1] <NEW_LINE> ntot = float(len(xranks)); <NEW_LINE> tiecorrection = 1 - (nties**3 - nties).sum()/(ntot**3 - ntot) <NEW_LINE> return tiecorrection
should be equivalent of scipy.stats.tiecorrect
625941d04428ac0f6e5ba95f
def test_push_new_notebook(self): <NEW_LINE> <INDENT> notebook = factories.NotebookFactory.create( action=const.ACTION_CREATE, stack='stack', ) <NEW_LINE> guid = 'guid' <NEW_LINE> self.note_store.createNotebook.return_value.guid = guid <NEW_LINE> self.sync.push() <NEW_LINE> pushed = self.note_store.createNotebook.call_...
Test push new notebook
625941d0ad47b63b2c50a0ec
def clone(self): <NEW_LINE> <INDENT> return PeakIndex(np.array(self.mz_array), np.array(self.intensity_array), self.peaks.clone())
Create a deep copy of `self` Returns ------- PeakIndex
625941d026068e7796caee4c
def is_triangle(s1, s2, s3): <NEW_LINE> <INDENT> if (s1 + s2 > s3) and (s2 + s3 > s1) and (s1 + s3 > s2): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
Return 1 if sides s1, s2, s3 may belong to a triangle, and 0 otherwise.
625941d02ae34c7f2600d29e
def main(): <NEW_LINE> <INDENT> primes = list(prime_sieve(10**5)) <NEW_LINE> for number in triangle_numbers(10**5): <NEW_LINE> <INDENT> if divisors(number, primes) > 500: <NEW_LINE> <INDENT> print("{} is the number".format(number)) <NEW_LINE> break
prints the first triangle number with more than 500 divisors.
625941d0097d151d1a222fc6
def create_storage_import( self, storage: str, source: str, source_location=None ) -> StorageImport: <NEW_LINE> <INDENT> if source not in ("http_import", "direct_upload"): <NEW_LINE> <INDENT> raise Exception(f"invalid storage import source: {source}") <NEW_LINE> <DEDENT> url = f'/storage/{storage}/import' <NEW_LINE> bo...
Creates an import task to import data into an existing storage. Source types: http_import or direct_upload.
625941d073bcbd0ca4b2c1e3
def __init__(self, card, action_log, configurator): <NEW_LINE> <INDENT> CardExtension.__init__(self, card, action_log, configurator) <NEW_LINE> self.card = card <NEW_LINE> self.weight = editor.Property(str(self.data.weight or u'')) <NEW_LINE> self.weight.validate(self.validate_weight) <NEW_LINE> self.action_button = co...
In: - ``target`` -- Card instance
625941d06aa9bd52df036f12
def mse(y_true, y_pred): <NEW_LINE> <INDENT> return np.mean((y_true - y_pred)**2)
calculate the mean squared errors. :param y_true: the true target value :param y_pred: the predicted target value :return: the mean squared errors
625941d044b2445a33932202
def main(_): <NEW_LINE> <INDENT> d = build_hyperparameter_dict(FLAGS) <NEW_LINE> hps = hps_dict_to_obj(d) <NEW_LINE> kind = FLAGS.kind <NEW_LINE> train_set = valid_set = None <NEW_LINE> if kind in ["train", "posterior_sample_and_average", "posterior_push_mean", "prior_sample", "write_model_params"]: <NEW_LINE> <INDENT>...
Get this whole shindig off the ground.
625941d03539df3088e2e4b8
def _npads(X, npad, ratio=1.): <NEW_LINE> <INDENT> n_time = X.shape[0] <NEW_LINE> bad_msg = 'npad must be "auto" or an integer' <NEW_LINE> if isinstance(npad, str): <NEW_LINE> <INDENT> if npad != 'auto': <NEW_LINE> <INDENT> raise ValueError(bad_msg) <NEW_LINE> <DEDENT> min_add = min(n_time // 8, 100) * 2 <NEW_LINE> npa...
Calculate padding parameters.
625941d024f1403a92600cd2
def load_train_data(): <NEW_LINE> <INDENT> df = pd.read_csv(TRAIN_DATA_PATH, names=DATA_COLUMNS, delimiter='\t') <NEW_LINE> return reindex(df)
Load the train dataset as a Pandas DataFrame.
625941d0711fe17d825424d8
def test_claim_action_team_member(self): <NEW_LINE> <INDENT> review = self.makeTeamReview() <NEW_LINE> albert = self.factory.makePerson() <NEW_LINE> removeSecurityProxy(albert).join(review.reviewer) <NEW_LINE> login_person(albert) <NEW_LINE> view = create_initialized_view(self.bmp, '+index') <NEW_LINE> view.claim_actio...
Claiming a review works for members of the requested team.
625941d0187af65679ca528c
def add_socket(self, peer, on_request): <NEW_LINE> <INDENT> if not isinstance(peer, peersocket.PeerSocket): <NEW_LINE> <INDENT> raise TypeError("expected PeerSocket, got %s" % type(peer)) <NEW_LINE> <DEDENT> if peer in self._peer_streams: <NEW_LINE> <INDENT> L.warning("This socket (%s:%d) is already managed by this " "...
Adds a new socket to manage. :peer a `PeerSocket` object to read from :on_request a function that accepts and processes a generic message on the socket on_request(recv_socket, recv_data) This is called when data is received but there is no expecting handler, as is typica...
625941d0fb3f5b602dac3801
def set_Password(self, value): <NEW_LINE> <INDENT> super(RetrieveCellListInputSet, self)._set_input('Password', value)
Set the value of the Password input for this Choreo. ((optional, password) Deprecated (retained for backward compatibility only).)
625941d0498bea3a759b9c1c
def indexify(self, words: List[str]) -> List[int]: <NEW_LINE> <INDENT> if not (isinstance(words, list) and all(isinstance(word, str) for word in words)): <NEW_LINE> <INDENT> raise TypeError("`words` must be list of str") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return [self._vocab.index(word) for word in words] <NE...
Translates words into indices based on this instance's internal vocabulary mapping. It is the caller's responsibility to handle SOS and EOS. Parameters ---------- words : list of str Words present in this instance's vocabulary. Returns ------- indices : list of int Indices corresponding to mappings from `wor...
625941d0a219f33f34628ad6
def select_from_db(field, value): <NEW_LINE> <INDENT> result_coll = (item for item in database if item[field] == value) <NEW_LINE> return _format_output(tuple(item for item in result_coll))
Функция возвращает таблицу (строка) с релевантными результатами, где переданное значение встречается в переданном ключе. Форматирование результатов выполняет вспомогательная функция _format_output
625941d0b830903b967e9a78
def add_operation(self): <NEW_LINE> <INDENT> number = self.number.text().replace('.', '') <NEW_LINE> phonenumber = self.verification_number(number) <NEW_LINE> if phonenumber.operator.slug == 'orange': <NEW_LINE> <INDENT> self.send_orange(phonenumber) <NEW_LINE> <DEDENT> elif phonenumber.operator.slug == 'malitel': <NEW...
add operation
625941d0377c676e91272316
@pytest.mark.nonparallel <NEW_LINE> def test_mcapp_create_validation(admin_mc, admin_pc, custom_catalog, remove_resource, restore_rancher_version): <NEW_LINE> <INDENT> c_name = random_str() <NEW_LINE> custom_catalog(name=c_name) <NEW_LINE> client = admin_mc.client <NEW_LINE> server_version = "2.0.0" <NEW_LINE> set_serv...
Test create validation of multi cluster apps. This test will set the rancher version explicitly and attempt to create apps with rancher version requirements
625941d0be383301e01b55f2
def convert_tokens_to_string(self, tokens): <NEW_LINE> <INDENT> text = "".join(tokens) <NEW_LINE> text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors) <NEW_LINE> return text
Converts a sequence of tokens (string) in a single string.
625941d023e79379d52ee6d1
def openSelect(self): <NEW_LINE> <INDENT> self.k_sheet = self._para_data.sheet_by_index(0) <NEW_LINE> self.b_sheet = self._para_data.sheet_by_index(1) <NEW_LINE> self.data_node_list = self._data_data.sheet_names() <NEW_LINE> para_node_list_temp = self.k_sheet.col_values(0) <NEW_LINE> para_node_list_temp2 = map(int,para...
打开selectSheet窗口,(与UI里面类似),并传递参数。 :return:
625941d050812a4eaa59c48e
def config(bot, event, cmd=None, *args): <NEW_LINE> <INDENT> if cmd == 'get' or cmd is None: <NEW_LINE> <INDENT> config_args = list(args) <NEW_LINE> value = bot.config.get_by_path(config_args) if config_args else dict(bot.config) <NEW_LINE> <DEDENT> elif cmd == 'set': <NEW_LINE> <INDENT> config_args = list(args[:-1]) <...
Displays or modifies the configuration Parameters: /bot config get [key] [subkey] [...] /bot config set [key] [subkey] [...] [value] /bot config append [key] [subkey] [...] [value] /bot config remove [key] [subkey] [...] [value]
625941d01d351010ab855c89
def get_stateful_column(self, column): <NEW_LINE> <INDENT> if column not in self.column_map: <NEW_LINE> <INDENT> self.column_map[column] = StatefulColumn(self, column) <NEW_LINE> <DEDENT> return self.column_map[column]
Returns a StatefulColumn for the given Column instance. If one has already been created, it will be returned.
625941d038b623060ff0af5b
def total_density(r, r_w, p, T): <NEW_LINE> <INDENT> rho_d = dry_air_density(r, p, T) <NEW_LINE> rho = rho_d * ( 1. + r + r_w) <NEW_LINE> return rho
Calculates total density of moist air with hydrometeors. Parameters ---------- r : numpy array mixing ratio i.e. vapor mass per dry air mass in [kg / kg] r_w : numpy array mixing ratio of condensed water i.e. condensed water mass per dry air mass in [kg / kg] p : numpy array total gas pressure [Pa] T : ...
625941d001c39578d7e74fa9
def get_type(self): <NEW_LINE> <INDENT> return self._name
Returns: string: Type of :class:`Config` class instance - stored in :attr:`_name`.
625941d010dbd63aa1bd2d11
def __checkCreate(self) -> str: <NEW_LINE> <INDENT> return self.__checkMachineReady()
Checks the state of a deploy for an user or cache
625941d05fdd1c0f98dc03a1
def __init__(self, language_code='en', stemmer=None): <NEW_LINE> <INDENT> if stemmer is not None: <NEW_LINE> <INDENT> self.stem = stemmer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stem = xapian.Stem(language_code)
Create a new highlighter for the specified language.
625941d03eb6a72ae02ec64c
def test_loop_jumps(self): <NEW_LINE> <INDENT> env_in = static.SpektakelValidator.environment_default() <NEW_LINE> node, env_out, dec, err = validate("break # Must fail, because no loop.\n" "continue # Must fail, because no loop.\n" "while True:\n" " break\n" "while False:\n" " continue\n" "for x in items:\n" " ...
Tests the validation of 'break' and 'continue'.
625941d0287bf620b61d3bd1
def minWindow(self, s, t): <NEW_LINE> <INDENT> def decr_or_remove(a, v): <NEW_LINE> <INDENT> if v not in a: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if a[v] == 1: <NEW_LINE> <INDENT> del a[v] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a[v]-=1 <NEW_LINE> <DEDENT> <DEDENT> dt = Counter(t) <NEW_LINE> st = set(t) ...
:type s: str :type t: str :rtype: str
625941d05166f23b2e1a52c7
def getfin_sina(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.__alldata.shape[0]>0: <NEW_LINE> <INDENT> return self.__alldata <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.readcsv() <NEW_LINE> return self.__alldata
读入新浪的个股全部数据信息
625941d024f1403a92600cd3
def create_power_level_table(serial, width=300, height=300): <NEW_LINE> <INDENT> return [[calculate_cell_power_level(x, y, serial) for y in range(width)] for x in range(height)]
Create the width x height power level matrix that is generated by serial. :param serial: program input :param width: the width of the table :param height: the height of the table :return: A width x height array of power levels
625941d07b25080760e395c7
def plot_optimal_policies(δ, ρ, γ, rh, rl, xaxis="δ", yaxis="γ", prec=100, riskyoptcolor="orange", cautiousoptcolor="blue", ax=None): <NEW_LINE> <INDENT> params = {"δ": δ, "ρ": ρ, "γ": γ, "rh": rh, "rl": rl} <NEW_LINE> x = np.linspace(0, params[xaxis], prec) <NEW_LINE> y = np.linspace(0, params[yaxis], prec) <NEW_LINE>...
Colorcode parameterregions according to where which policy is optimal. Parameters ---------- δ : float the collapse probability δ ρ : float the recovery probability ρ γ : float the discount factor rh : float the high reward rl : float the low reward xaxis : string the parameter to be plotted on...
625941d0be7bc26dc91cd76c
def test_shelve(tmpdir): <NEW_LINE> <INDENT> test_string = 'test information' <NEW_LINE> tmp_cache = str(tmpdir) <NEW_LINE> with tempfile.NamedTemporaryFile('w', delete=False) as f: <NEW_LINE> <INDENT> f.write(test_string) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> file_data = sg.get_data(f.name, tmp_cache) <NEW_LINE...
Test if shelve can be caches information retrieved after file is deleted
625941d0cad5886f8bd27147
def findMin(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if len(nums) == 1: <NEW_LINE> <INDENT> return nums[0] <NEW_LINE> <DEDENT> if(nums[-1] > nums[0]): <NEW_LINE> <INDENT> return nums[0] <NEW_LINE> <DEDENT> if(nums[-1] < nums[-2]): <NEW_LINE> <INDENT> return nu...
:type nums: List[int] :rtype: int
625941d0435de62698dfddbb
def iter_files(self): <NEW_LINE> <INDENT> for file_dict in self.files: <NEW_LINE> <INDENT> file = File(self, file_dict.get('name')) <NEW_LINE> yield file
Generator for iterating over files in an item. :rtype: generator :returns: A generator that yields :class:`internetarchive.File <File>` objects.
625941d045492302aab5e432
def get_user(self, user_id: int, insert_token: str) -> User: <NEW_LINE> <INDENT> user = UserQuery.get_user_by_id(user_id) <NEW_LINE> if ( user is None or user.yandex_disk_token is None ): <NEW_LINE> <INDENT> raise MissingData() <NEW_LINE> <DEDENT> db_insert_token = None <NEW_LINE> try: <NEW_LINE> <INDENT> db_insert_tok...
:param user_id: DB id of needed user. :param insert_token: User will be returned only in case when provided insert token matchs with one from DB. This means you are allowed to modify this DB user. Insert token of that user can be modified in futher by some another operation, so, you should call this function once and r...
625941d0dd821e528d63b316