code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_next_header_ipv6_incrementation_dot1q_disabled(self, tg): <NEW_LINE> <INDENT> iface = tg.ports[0] <NEW_LINE> packet_count = 5 <NEW_LINE> stream_id = tg.set_stream(IP6, count=packet_count, nh_increment=(3, 5), iface=iface) <NEW_LINE> tg.start_sniff([iface], sniffing_time=5, src_filter="00:00:0a:00:02:08") <NEW_...
Check next header incrementation. Count == Increment count. Dot1Q disabled.
625941e776d4e153a657ef9b
def update_step( body_system: BodySystem, delta_time: float, patches: list[plt.Circle] ) -> None: <NEW_LINE> <INDENT> body_system.update_system(delta_time) <NEW_LINE> for patch, body in zip(patches, body_system.bodies): <NEW_LINE> <INDENT> patch.center = (body.position_x, body.position_y)
Memperbarui sistem tubuh dan menerapkan perubahan ke daftar yang digunakan untuk plotting
625941e74a966d76dd55147c
def __on_resp(self, recv): <NEW_LINE> <INDENT> recv = ''.join((self.__recv_buf, recv)) <NEW_LINE> idx = 0 <NEW_LINE> for future, connect_count, trans, count in self.__cmd_env: <NEW_LINE> <INDENT> ok, payload, recv = decode_resp_ondemand(recv, connect_count, trans, count) <NEW_LINE> if not ok: <NEW_LINE> <INDENT> break ...
:param recv: 收到的buf
625941e791f36d47f21ac95f
def draw_record_name(mainboard): <NEW_LINE> <INDENT> mainboard.write_file(mainboard.filename_2, True) <NEW_LINE> mainboard.update_name() <NEW_LINE> mainboard.update_record() <NEW_LINE> mainboard.blit_text_score() <NEW_LINE> mainboard.blit_score()
Draw name of beater and its score.
625941e7435de62698dfe0b5
def execute(self): <NEW_LINE> <INDENT> for pilot in self._game.pilots_by_skill(): <NEW_LINE> <INDENT> pilot.active = True <NEW_LINE> pilot.chosen_maneuver.apply(pilot) <NEW_LINE> if pilot.can_perform_action(): <NEW_LINE> <INDENT> chosen_action = self._game.player(pilot.faction).choose_action(pilot) <NEW_LINE> <DEDENT> ...
Run the Activation phase
625941e730bbd722463cc230
def leer_archivo(nombre): <NEW_LINE> <INDENT> elemento_dict = {} <NEW_LINE> with open(nombre) as f: <NEW_LINE> <INDENT> s = f.read() <NEW_LINE> elemento = {} <NEW_LINE> elemento_key = '' <NEW_LINE> for line in s.splitlines(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> k,v = line.split("=") <NEW_LINE> k = k.strip() <N...
Funcion que leer la ruta de un archivo por parámetro y crear un diccionario donde, la clave es el símbolo del elemento y el valor de cada clave es un diccionario, con todas las propiedades del elemento.
625941e7aad79263cf390eb0
def get_player_total_time(self, player_name): <NEW_LINE> <INDENT> if player_name == self.player1: <NEW_LINE> <INDENT> return self.player1_total_time <NEW_LINE> <DEDENT> return self.player2_total_time
Returns the total time of a player. Arg: player_name: A string containing the player name to get the time for. Returns: A float specifying the player's total time.
625941e7a4f1c619b28b0497
def bye(self, name): <NEW_LINE> <INDENT> print("Bye " + name)
Funcion retorna adios concatenado con el parametro name :param name: :return:
625941e73c8af77a43ae3c0e
def iround(x): <NEW_LINE> <INDENT> return int(round(x))
Round floating point number and cast to int.
625941e70fa83653e4657421
def mergeReport(self): <NEW_LINE> <INDENT> reportInstance = Report(self.stepName) <NEW_LINE> ReportReader.xmlToJobReport(reportInstance, os.path.join(self.workingDir, self.merge_report_file)) <NEW_LINE> return reportInstance
_mergeReport_ read the merge report
625941e7be383301e01b58e5
def merge(self, base, head, meta=None, merge_options=None): <NEW_LINE> <INDENT> schema = JSONValue(self.schema) <NEW_LINE> if base is None: <NEW_LINE> <INDENT> base = JSONValue(undef=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base = JSONValue(base) <NEW_LINE> <DEDENT> head = JSONValue(head) <NEW_LINE> if merge...
Merge head into base. base -- Old JSON document you are merging into. head -- New JSON document for merging into base. merge_options -- Optional dictionary with merge options. Keys of merge_options must be names of the strategies. Values must be dictionaries of merge options as in the mergeOptions schema element. Opt...
625941e7099cdd3c635f10c1
def __init__( self, organization_id, full_name=None, data=None, name=None, display_name=None, lifecycle_state=OrgLifecycleState.UNSPECIFIED): <NEW_LINE> <INDENT> super(Organization, self).__init__( resource_id=organization_id, resource_type=resource.ResourceType.ORGANIZATION, name=name, display_name=display_name, lifec...
Initialize. Args: organization_id (int): The organization id. full_name (str): The full resource name and ancestory. data (str): Resource representation of the organization. name (str): The organization's unique GCP name, with the format "organizations/{id}". display_name (str): The organiz...
625941e7566aa707497f49cb
def test_hello_with_macronated_name(): <NEW_LINE> <INDENT> assert hello("Ātaahua") == "Hello, Ātaahua!"
Test with a macronated name supplied.
625941e7cdde0d52a9e5349f
def gen_tasks(self): <NEW_LINE> <INDENT> yield self.group_task() <NEW_LINE> if not self.__formula_as_data_URIs: <NEW_LINE> <INDENT> self.site.scan_posts() <NEW_LINE> formulae = [] <NEW_LINE> for formula_collector in self.site.latex_formula_collectors: <NEW_LINE> <INDENT> for formula_data in formula_collector(): <NEW_LI...
Generate doit tasks.
625941e7596a897236089f23
def get_prediction( self, start: Optional[DateLike] = None, end: Optional[DateLike] = None, dynamic: Union[bool, DateLike] = False, **kwargs: Dict[str, Any], ): <NEW_LINE> <INDENT> pred = self._model_result.get_prediction( start=start, end=end, dynamic=dynamic, **kwargs ) <NEW_LINE> seasonal_prediction = self._get_seas...
In-sample prediction and out-of-sample forecasting Parameters ---------- start : int, str, or datetime, optional Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. en...
625941e77d43ff24873a310c
def assign_role_for_collection( committer_id, collection_id, assignee_id, new_role): <NEW_LINE> <INDENT> _assign_role( committer_id, assignee_id, new_role, collection_id, ACTIVITY_TYPE_COLLECTION) <NEW_LINE> if new_role in [ROLE_OWNER, ROLE_EDITOR]: <NEW_LINE> <INDENT> subscription_services.subscribe_to_collection( ass...
Assign `assignee_id` to the given role and subscribes the assignee to future collection updates. The caller should ensure that assignee_id corresponds to a valid user in the system. Args: - committer_id: str. The user_id of the user who is performing the action. - collection_id: str. The collection id. - assignee_id:...
625941e7cad5886f8bd27441
def read_raster_band(source_file): <NEW_LINE> <INDENT> gdal.AllRegister <NEW_LINE> raster_data = gdal.Open(str(source_file), GA_ReadOnly) <NEW_LINE> if raster_data is None: <NEW_LINE> <INDENT> raise IOError('Unable to open raster') <NEW_LINE> <DEDENT> raster_params = GDALParameters() <NEW_LINE> raster_params.set_driver...
read input raster band based on GDAL
625941e744b2445a339324fb
def UpdateUser_Role(): <NEW_LINE> <INDENT> testRole()
Updates a Zoom all user's role based on tkinter drop down list values Args: None Returns: None
625941e71f037a2d8b946665
def turn_off(self): <NEW_LINE> <INDENT> hub.session.set_smartplug_state(self._device_label, False) <NEW_LINE> self._state = False <NEW_LINE> self._change_timestamp = time()
Set smartplug status off.
625941e78e05c05ec3eea7e1
def prime_power_qudit_CC(graph, node, t, a, copy=True): <NEW_LINE> <INDENT> new_graph = copy_graph(graph) if copy else graph <NEW_LINE> n, c = node <NEW_LINE> if c != t: <NEW_LINE> <INDENT> new_graph.add_edge((n, c), (n, t), weight=1) <NEW_LINE> <DEDENT> new_graph = prime_qudit_LC(new_graph, (n, c), a, copy=False) <NEW...
Returns graph after controlled complementation
625941e731939e2706e4d2cc
def add(self, alias, fname): <NEW_LINE> <INDENT> if callable(fname): <NEW_LINE> <INDENT> self._add_function(alias, fname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> placeholders = _get_placeholders(fname) <NEW_LINE> if len(placeholders) == 0: <NEW_LINE> <INDENT> self._add_fname(alias, fname) <NEW_LINE> <DEDENT> else...
Add a new filename. Parameters ---------- alias : str A short alias for the full filename. This alias can later be used to retrieve the filename. Aliases can not start with '_' or a number. fname : str | function The full filename. Either a string, optionally containing placeholders, or a function ...
625941e7b5575c28eb68e46d
def download(self): <NEW_LINE> <INDENT> p = urlparse(self._client.endpoint) <NEW_LINE> url = '{}://{}/dl/autobackup/{}'.format(p.scheme,p.netloc,self.data['filename']) <NEW_LINE> r = self._client._s.get(url, stream=True) <NEW_LINE> return r.raw
download the backup referenced by the current record Unifi doesn't make this easy since it's relative to the controller and not the site
625941e71f037a2d8b946666
def on_popup(self, event): <NEW_LINE> <INDENT> itemId = event.GetId() <NEW_LINE> menu = event.GetEventObject() <NEW_LINE> menuItem = menu.FindItemById(itemId) <NEW_LINE> if menuItem.GetItemLabel() == _("Play selected url"): <NEW_LINE> <INDENT> self.play_selected_url(self)
Evaluate the label string of the menu item selected and starts the related process
625941e7b7558d58953c5373
def set_fit_weight(self, energy, counts, emin, emax, ewid=0.050): <NEW_LINE> <INDENT> ewin = ftwindow(energy, xmin=emin, xmax=emax, dx=ewid, window='hanning') <NEW_LINE> self.fit_window = ewin <NEW_LINE> fit_wt = 0.5 + savitzky_golay(np.sqrt(counts+1.0), 25, 1) <NEW_LINE> self.fit_weight = 1.0/fit_wt
set weighting factor to smoothed square-root of data
625941e7e64d504609d74ca9
def createObjects( self ): <NEW_LINE> <INDENT> p = list(map( self.canvas.tfm.transform, self.globalCoords )) <NEW_LINE> self.itemid = self.canvas.create_polygon(p, fill=self.colorstr, outline=self.colorstr)
computes pixel coordinates and then creates the canvas objects
625941e726068e7796caf14f
def compound_sig_poisson(self): <NEW_LINE> <INDENT> t0 = time.time() <NEW_LINE> f_in2out = 2. <NEW_LINE> rh_th = 10. * self.sigma1 <NEW_LINE> n_inner, area_inner = self.poisson_inner_number_count(self.sigma1) <NEW_LINE> r_i = f_in2out * self.sigma1 <NEW_LINE> r_o = self.sigma3 <NEW_LINE> n_outer, area_outer = self.pois...
Compound the Poisson significance map: s12 inside (s23 > sigma_th) and s13 outside (s23 < sigma_th)
625941e715baa723493c43e2
def view_polygons(polygons): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> ax = plt.axes(projection="3d") <NEW_LINE> collections = _make_collections(polygons, opacity=0.5) <NEW_LINE> for c in collections: <NEW_LINE> <INDENT> ax.add_collection3d(c) <NEW_LINE> <DEDENT> limits = _get_limits(polygons=polygons) <NEW_LINE> ax....
Display a collection of polygons for inspection. :param polygons: A dict keyed by colour, containing Polygon3D objects to show in that colour.
625941e74d74a7450ccd462d
def ddrobject( page, obj ): <NEW_LINE> <INDENT> t = template.loader.get_template('wikiprox/ddr-object.html') <NEW_LINE> return t.render({ 'page': page, 'object': obj, 'MEDIA_URL': settings.MEDIA_URL, 'DDR_MEDIA_URL': settings.DDR_MEDIA_URL, })
DDR object in sidebar
625941e7f548e778e58cd9e8
def pushback_generator(iterator): <NEW_LINE> <INDENT> for value in iterator: <NEW_LINE> <INDENT> back = yield value <NEW_LINE> if back is not None: <NEW_LINE> <INDENT> yield back <NEW_LINE> yield back
Generator which allows to push back a previously picked item for example: gen = pushback_generator(range(10)) print next(gen) print next(gen) v = next(gen) print v gen.send(v) print next(gen) :param iterator: :return:
625941e750812a4eaa59c786
def verify_grades_in_csv(self, students_grades): <NEW_LINE> <INDENT> def merge_dicts(*dicts): <NEW_LINE> <INDENT> return dict([item for d in dicts for item in d.items()]) <NEW_LINE> <DEDENT> def user_partition_group(user): <NEW_LINE> <INDENT> group_config_hdr_tpl = 'Experiment Group ({})' <NEW_LINE> return { group_conf...
Verify that the grades CSV contains the expected grades data. Arguments: students_grades (iterable): An iterable of dictionaries, where each dict maps a student to another dict representing their grades we expect to see in the CSV. For example: [student_a: {'grade': 1.0, 'HW': 1.0}]
625941e73317a56b8693a0b6
def __ne__(self, other): <NEW_LINE> <INDENT> return self.__eq__(other) == False
Inverse of __eq___
625941e74f88993c3716c4cc
def __init__(self, path, size_guidance=None, compression_bps=NORMAL_HISTOGRAM_BPS, purge_orphaned_data=True): <NEW_LINE> <INDENT> size_guidance = size_guidance or DEFAULT_SIZE_GUIDANCE <NEW_LINE> sizes = {} <NEW_LINE> for key in DEFAULT_SIZE_GUIDANCE: <NEW_LINE> <INDENT> if key in size_guidance: <NEW_LINE> <INDENT> siz...
Construct the `EventAccumulator`. Args: path: A file path to a directory containing tf events files, or a single tf events file. The accumulator will load events from this path. size_guidance: Information on how much data the EventAccumulator should store in memory. The DEFAULT_SIZE_GUIDANCE tries not to s...
625941e7c432627299f050b2
def encode_nodes(nodes): <NEW_LINE> <INDENT> n = [] <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> n.extend([node.nid, dotted_quad_to_num(node.ip), node.port]) <NEW_LINE> <DEDENT> return pack("!" + "20sIH" * len(nodes), *n)
"编码"nodes 与decode_dodes相反
625941e72eb69b55b151cd1f
def connect_database(username, password, database, host, port="3306"): <NEW_LINE> <INDENT> mydb = mysql.connector.connect( host=host, user=username, password=password, port=port, database=database ) <NEW_LINE> mycursor = mydb.cursor() <NEW_LINE> return mydb, mycursor
Create connection to a MySQL database. :param username: Name of the user :param password: User's password :param database: Name of the database to connect. :param host: IP address of the MySQL server. :param port: Port to which MySQL server is listening, default is 3306 (default MySQL server port) :return: database con...
625941e7d7e4931a7ee9e388
def sftp_put(self, src, dest): <NEW_LINE> <INDENT> client, proxy = self.connect() <NEW_LINE> transport = client.get_transport() <NEW_LINE> try: <NEW_LINE> <INDENT> sftp = paramiko.SFTPClient.from_transport(transport) <NEW_LINE> if not transport.active: <NEW_LINE> <INDENT> sftp = scp.SCPClient(transport) <NEW_LINE> <DED...
Puts a file to the remote server Arguments: - src: Source local file to copy. - dest: Destination path in the remote server.
625941e744b2445a339324fc
def shell_context(): <NEW_LINE> <INDENT> return {"db": db, "User": user.model.User}
Shell context objects.
625941e7cb5e8a47e48b7f0d
def __ask_input(string): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> input_data = input(string) <NEW_LINE> <DEDENT> except (KeyboardInterrupt, EOFError): <NEW_LINE> <INDENT> print("\nBye!") <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> return input_data
Ask input from user with 'string'.
625941e7956e5f7376d712d5
def append_data(self, file_path: str, data: bytes) -> None: <NEW_LINE> <INDENT> file_client = self._container.get_file_client(file_path) <NEW_LINE> offset: int = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> offset = file_client.get_file_properties().size <NEW_LINE> <DEDENT> except ResourceNotFoundError: <NEW_LINE> <INDENT> lo...
Append data to the file.
625941e7d53ae8145f87a6d0
def _new_pool(self, scheme, host, port): <NEW_LINE> <INDENT> pool_cls = self.pool_classes_by_scheme[scheme] <NEW_LINE> kwargs = self.connection_pool_kw <NEW_LINE> if scheme == 'http': <NEW_LINE> <INDENT> kwargs = self.connection_pool_kw.copy() <NEW_LINE> for kw in SSL_KEYWORDS: <NEW_LINE> <INDENT> kwargs.pop(kw, None) ...
Create a new :class:`ConnectionPool` based on host, port and scheme. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization.
625941e791af0d3eaac9be86
def _check_control_put_method(ctrl, client, obj, body): <NEW_LINE> <INDENT> ctrl_obj = obj["@controls"][ctrl] <NEW_LINE> href = ctrl_obj["href"] <NEW_LINE> method = ctrl_obj["method"].lower() <NEW_LINE> encoding = ctrl_obj["encoding"].lower() <NEW_LINE> schema = ctrl_obj["schema"] <NEW_LINE> assert method == "put" <NEW...
Checks a PUT type control from a JSON object be it root document or an item in a collection. In addition to checking the "href" attribute, also checks that method, encoding and schema can be found from the control. Also validates a valid user against the schema of the control to ensure that they match. Finally checks t...
625941e760cbc95b062c69ad
def reduce(self, func: Callable[[V, T], V], initializer: Optional[V]=None): <NEW_LINE> <INDENT> if initializer is None: <NEW_LINE> <INDENT> return reduce(func, self.array) <NEW_LINE> <DEDENT> return reduce(func, self.array, initializer)
Short-hand for reduce function Example: >>> _([5, 2, 1, 2, 3]).reduce(lambda a, b: a + b) 13 >>> _([5, 2, 1, 2, 3]).reduce(lambda a, b: a + b, 10) 23 >>> _(["first", "second", "three"]).reduce(lambda a, b: a + "-" + b) 'first-second-three'
625941e73317a56b8693a0b7
def kSmallestPairs(self, nums1, nums2, k): <NEW_LINE> <INDENT> import heapq <NEW_LINE> visited = set() <NEW_LINE> resultant = [] <NEW_LINE> if not nums1 or not nums2: <NEW_LINE> <INDENT> return resultant <NEW_LINE> <DEDENT> queue = [(nums1[0] + nums2[0], (0,0))] <NEW_LINE> while queue and k: <NEW_LINE> <INDENT> _, (i, ...
:type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
625941e7596a897236089f24
def _build_basic_executors(): <NEW_LINE> <INDENT> type_info = ( (bool, capi.c_call_b, ("bool",)), (rffi.CHAR, capi.c_call_c, ("char", "unsigned char", "signed char")), (rffi.SHORT, capi.c_call_h, ("short", "short int", "unsigned short", "unsigned short int")), (rffi.INT, capi.c_call_i...
NOT_RPYTHON
625941e7627d3e7fe0d692bb
def cancel(self): <NEW_LINE> <INDENT> self._cancelled = True
Cancels the current job.
625941e77cff6e4e81117def
def main(args): <NEW_LINE> <INDENT> total_example = 0 <NEW_LINE> data = json.load(open(args.data_file)) <NEW_LINE> print("total dialogs:", len(data)) <NEW_LINE> null_doc = convert_to_tgt(TOKEN_NOCHOSEN, TOKEN_NOCHOSEN) <NEW_LINE> with open(args.out_file, "w") as out_f: <NEW_LINE> <INDENT> out_f.write(f"src\tknowledge\t...
Main function.
625941e771ff763f4b549afd
def can_traverse_dir(self, src_node, dest_node): <NEW_LINE> <INDENT> src_node, dest_node = self.get_index_from_node(src_node), self.get_index_from_node(dest_node) <NEW_LINE> return self.adjacency_matrix[src_node][dest_node] != 0
Check if two nodes can be accesed from each other :src_node: Source Node :dest_node: Destination Node :return: Boolea, true if accessible, false otherwise
625941e78a43f66fc4b544ca
def get_ner(text): <NEW_LINE> <INDENT> document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) <NEW_LINE> response = google_language_service_client.analyze_entities( document=document, encoding_type='UTF32') <NEW_LINE> ner_result = _transform_ner_api_resp(response.entities) <NEW_LINE> return ner_r...
Get NER chunks from text @return { 'person': [], 'location': [], 'organization': [] }
625941e756b00c62f0f14ac6
def escapeAmp(html): <NEW_LINE> <INDENT> return html.replace("&concept", "&amp;concept")
Replaces & with its HTML escaped form &amp;
625941e7b57a9660fec33cf4
def stats(): <NEW_LINE> <INDENT> pass
Return a dictionary with interesting keys and values about the global state of this object.
625941e7167d2b6e31218ffe
def id_formater(fn, ln, appelation, city, year): <NEW_LINE> <INDENT> x=appelation+'. '+ ln+', '+ fn+' ('+ city+', '+str(year)+')' <NEW_LINE> return x
name,name,name,name,int-> str,str,name,name,int
625941e7fb3f5b602dac3b01
def _get_ordered_codex_label_list_repr(self): <NEW_LINE> <INDENT> repr_strings = [] <NEW_LINE> for codex_label in self.ordered_codex_label_list: <NEW_LINE> <INDENT> (codex, label) = codex_label <NEW_LINE> repr_string = '(%i, %s)' % (codex, label) <NEW_LINE> repr_strings.append(repr_string) <NEW_LINE> <DEDENT> reprs_str...
Returns a repr of the ordered codex label list: str
625941e7ff9c53063f47c65b
def prep_level(self): <NEW_LINE> <INDENT> self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.ai_settings.bg_color) <NEW_LINE> self.level_rect = self.level_image.get_rect() <NEW_LINE> self.level_rect.right = self.score_rect.right <NEW_LINE> self.level_rect.top = self.score_rect.bottom...
Turn level into rendered image
625941e792d797404e3045f6
def B(self): <NEW_LINE> <INDENT> self.__operation(1)
B operation. Rotate Back side by clockwise 90 degree. See: https://en.wikipedia.org/wiki/Rubik%27s_Cube
625941e756ac1b37e6264630
def run(self, tokens, vocab): <NEW_LINE> <INDENT> if self.mxlen < 0: <NEW_LINE> <INDENT> self.mxlen = self.max_seen <NEW_LINE> <DEDENT> vec1d = pads(self.mxlen, dtype=int) <NEW_LINE> i = 0 <NEW_LINE> for i, atom in enumerate(self._next_element(tokens, vocab)): <NEW_LINE> <INDENT> if i == self.mxlen: <NEW_LINE> <INDENT>...
Convert an iterable token stream to an integer padded up to the maximum length `mxlen) :param tokens: An iterable token stream :param vocab: A word-to-integer index :return: A (padded) vector and the valid (unpadded length)
625941e76e29344779a62a7a
def get_strategy_parameters(self, strategy_name): <NEW_LINE> <INDENT> strategy = self.strategies[strategy_name] <NEW_LINE> strategy_config = self.strategy_setting.get(strategy_name, {}) <NEW_LINE> d = {} <NEW_LINE> d.update({'auto_init': strategy_config.get('auto_init', False)}) <NEW_LINE> d.update({'auto_start': strat...
Get parameters of a strategy.
625941e7a934411ee3751afe
def make_time_cube(time, cube): <NEW_LINE> <INDENT> time_elapsed = time - datetime.datetime(1970, 1, 1) <NEW_LINE> t_hours = float(time_elapsed.days * 24 + time_elapsed.seconds / (60 * 60)) <NEW_LINE> return iris.cube.Cube(t_hours, standard_name = 'time', units = Unit('hours since 1970-01-01 00:00:00', calendar='gregor...
Make scalar cube of datetime object :param time: datetime object :param cube: arbitrary cube :return: scalar cube
625941e7656771135c3ebcde
def logout(self, session): <NEW_LINE> <INDENT> session.add(self) <NEW_LINE> self.authenticated = False <NEW_LINE> self.active = False <NEW_LINE> session.commit()
Adds this instance back to the session passed in, logs it out, and saves it to the db. Important: caller might want to remove this instance from the database session so it can behave properly in Flask-Login.
625941e721a7993f00bc8161
def get_courseid_title(self, line): <NEW_LINE> <INDENT> courseid = '' <NEW_LINE> line_course = line.product.course <NEW_LINE> if line_course: <NEW_LINE> <INDENT> courseid = "{}|".format(line_course.id) <NEW_LINE> <DEDENT> return courseid + line.product.title
Get CourseID & Title from basket item Arguments: line: basket item Returns: Concatenated string containing course id & title if exists.
625941e78e7ae83300e4b438
def list_roles(self): <NEW_LINE> <INDENT> resp = self.call( 'ListRoles', ) <NEW_LINE> return [Role(role) for role in resp['roles']]
Return a list of roles.
625941e7d4950a0f3b08c7b2
def one_to_three_learning(self, res_S, res_TB, res_TE, kd_mask_s, kd_mask_b, kd_mask_e, bleu_ENS_gt_S, bleu_ENS_gt_TB, f1score_ENS_gt_TE): <NEW_LINE> <INDENT> assert self.model_TE is not None <NEW_LINE> NLL_S, logit_S, prob_S = res_S <NEW_LINE> NLL_TB, logit_TB, prob_TB = res_TB <NEW_LINE> NLL_TE, logit_TE, prob_TE = r...
one-to-three learning, one for ensemble model, three for model_S, model_TB and model_TE
625941e7d4950a0f3b08c7b3
def uniquePaths(self, m, n): <NEW_LINE> <INDENT> dp = [[0] * (n + 1) for i in range(m + 1)] <NEW_LINE> dp[1][1] = 1 <NEW_LINE> for i in range(1, m + 1): <NEW_LINE> <INDENT> for j in range(1, n + 1): <NEW_LINE> <INDENT> dp[i][j] += dp[i][j-1] + dp[i-1][j] <NEW_LINE> <DEDENT> <DEDENT> return dp[m][n]
:type m: int :type n: int :rtype: int
625941e785dfad0860c3b2c6
def seed_source(): <NEW_LINE> <INDENT> if node_count < 3: <NEW_LINE> <INDENT> print('The node_count given is less than three and is invalid. This value must be three or greater.') <NEW_LINE> raise ValueError <NEW_LINE> <DEDENT> s = Instance.seeder(manual_seed=True, num=seed) <NEW_LINE> inst = Instance(relative_edges=re...
Generate an instance from a given integer as a seed. This allows reproducibility in terms of the seed used. random_source will also generate a seed, but the seed is random and not known until after generation. This can be recorded and stored for the purpose of reproducibility in the same way.
625941e738b623060ff0b257
def make_executable(self): <NEW_LINE> <INDENT> mode = _os.stat(self.name).st_mode <NEW_LINE> mode |= (mode & 0o444) >> 2 <NEW_LINE> _os.chmod(self.name, mode)
change the stat of the object's file name to be executable Example: -rw-rw-rw- becomes -rwxrwxrwx -rw------ becomes -rwx------
625941e77b25080760e398c0
def HasCurrent(self): <NEW_LINE> <INDENT> pass
HasCurrent(self: ConduitSizeSettingIterator) -> bool Identifies whether the iterator has a current item. There is no current item if the iterator has not started yet or has been done. Returns: True if there is a current item.
625941e7f8510a7c17cf9b69
def print_detailed_results(self, is_thing=None, print_digits=3): <NEW_LINE> <INDENT> raise NotImplementedError('Not implemented in subclass.')
Prints out a detailed breakdown of metric results. Args: is_thing: A boolean array of length num_categories. `is_thing[category_id]` will say whether that category is a "thing" rather than "stuff." print_digits: Number of significant digits to print in computed metrics.
625941e7d18da76e23532945
def maximusWork(self): <NEW_LINE> <INDENT> print(inspect.stack()[0][3]) <NEW_LINE> if self.hasOpen == False : <NEW_LINE> <INDENT> print("请先打开图像!") <NEW_LINE> return <NEW_LINE> <DEDENT> self.destImg = maximus(self.srcImg) <NEW_LINE> self.showResultPic() <NEW_LINE> self.label_2.setText("处理结果: 一维最大熵") <NEW_LINE> pass
对原图像使用一维最大熵 算法 阈值检测 ,并且将结果显示在处理图像栏
625941e7b545ff76a891427f
def send_typing_notification( self, chat_thread_id, send_typing_notification_request=None, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 404: ResourceNotFoundError, 409: ResourceExistsError, 401: lambda response: ClientAuthenticationError(response=response, model=self._deseriali...
Posts a typing event to a thread, on behalf of a user. Posts a typing event to a thread, on behalf of a user. :param chat_thread_id: Id of the thread. :type chat_thread_id: str :param send_typing_notification_request: Details of the typing notification request. :type send_typing_notification_request: ~azure.communica...
625941e75e10d32532c5f38f
def steer_right(self): <NEW_LINE> <INDENT> self.rotate_right(self.steering_force) <NEW_LINE> self.steered_this_frame = True
Steers the car to the right
625941e730dc7b7665901dcc
def configure_website(self, bucket): <NEW_LINE> <INDENT> ws = bucket.Website() <NEW_LINE> ws.put(WebsiteConfiguration={ 'ErrorDocument': { 'Key': 'error.html' }, 'IndexDocument': { 'Suffix': 'index.html' } })
Configure Website.
625941e755399d3f05588b21
def load_index_fold(self, i_fold: int) -> np.array: <NEW_LINE> <INDENT> return list(self.cv.split(self.X_train, self.y_train))[i_fold]
クロスバリデーションでのfoldを指定して対応するレコードのインデックスを返す :param i_fold: foldの番号 :return: foldに対応するレコードのインデックス
625941e76fece00bbac2dbae
def userParser(self, cur ): <NEW_LINE> <INDENT> if(cur): <NEW_LINE> <INDENT> curParsed = {} <NEW_LINE> for row in cur: <NEW_LINE> <INDENT> jobInfo = {} <NEW_LINE> jobInfo = self.userTupleParser(row) <NEW_LINE> curParsed[ jobInfo["userId"] ] = jobInfo <NEW_LINE> <DEDENT> return curParsed <NEW_LINE> <DEDENT> else: <NEW_L...
Parser for the tuples from the Users table.
625941e79b70327d1c4e1241
def test_evaluate_fail_all_except_has_errors(self): <NEW_LINE> <INDENT> event = {} <NEW_LINE> whitelist = [] <NEW_LINE> for item in CLOUDTRAIL_LOGGING["fail_all"]["flaggedResources"]: <NEW_LINE> <INDENT> output = self._evaluate_invariant_assertions(event, item, whitelist) <NEW_LINE> self._evaluate_failed_status_asserti...
Non-applicable case
625941e71f5feb6acb0c4fb3
def cmd_set_argument_description(self, cmd_name, arg_descriptions): <NEW_LINE> <INDENT> data_dict = {"action": "setargumentdescr", "object": "cmd", "values": ";".join([cmd_name, ";".join(arg_descriptions)])} <NEW_LINE> response = self.network.make_request(HTTPVerb.POST, params=self.config.vars["params"], data=data_dict...
This method is used to set the argument description for a command :param cmd_name: Name of the command :type cmd_name: str :param arg_descriptions: Descriptions of the description :type arg_descriptions: list of str :return: Returns True if the operation was successful :rtype: bool
625941e730bbd722463cc232
def __write_words(self, word_size, content, background_color, word_color, x, y, word_style='GB2313.ttf'): <NEW_LINE> <INDENT> font = pygame.font.Font(word_style, word_size) <NEW_LINE> text_surface_obj = font.render(content, True, word_color, background_color) <NEW_LINE> text_rect_obj = text_surface_obj.get_rect() <NEW_...
write words on the screen :param word_size: the size of the words :param content: content :param background_color: background color such as (255,255,255) => write background :param word_color: word color such as (0,0,0) => black words :param x: x coordinate :param y: y coordinate :param word_style: you can choose word...
625941e7e8904600ed9f239e
def compute_distances_two_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> for j in xrange(num_train): <NEW_LINE> <INDENT> dists[i][j]= np.sqrt(np.sum((self....
Compute the distance between each test point in X and each training point in self.X_train using a nested loop over both the training data and the test data. Inputs: - X: A numpy array of shape (num_test, D) containing test data. Returns: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] is th...
625941e7956e5f7376d712d6
def count_gt_25g(L, n=2500): <NEW_LINE> <INDENT> return sum(np.array(L) > n)
count the number of elements in L > n :param L: :param n: :return:
625941e73346ee7daa2b31da
@app.route('/') <NEW_LINE> def display_error(): <NEW_LINE> <INDENT> return 'The application directory has not been mounted in the right place'
Display a single string in the browser
625941e7090684286d50f156
def read(self, blocking=False): <NEW_LINE> <INDENT> if blocking: <NEW_LINE> <INDENT> GPIO.wait_for_edge(self.d_in, GPIO.RISING) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return GPIO.input(self.d_in)
Read the current value of the sensor if blocking is true, wait for rising edge before returning Return either 0 or 1
625941e7e64d504609d74caa
def test_run_available(self): <NEW_LINE> <INDENT> cmd = dnf.cli.commands.updateinfo.UpdateInfoCommand(self.cli) <NEW_LINE> tests.support.command_run(cmd, []) <NEW_LINE> self.assertEqual(self._stdout.getvalue(), 'Updates Information Summary: available\n' ' 1 Security notice(s)\n', 'incorrect output')
Test running with available advisories.
625941e7507cdc57c6307150
def __init__(self): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> self.ERROR = Storage( REPORTLAB_ERROR = T("%(module)s not installed") % dict(module="ReportLab"), NO_RECORDS = T("No records in this resource"), XLWT_ERROR = T("%(module)s not installed") % dict(module="xlwt"), )
Constructor @param manager: the S3ResourceController @todo 2.3: error message completion
625941e726238365f5f0f2df
def except_keys(dic, keys): <NEW_LINE> <INDENT> ret = dic.copy() <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del ret[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return ret
Return a copy of the dict without the specified keys. :: >>> except_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]) {'B': 2}
625941e7cdde0d52a9e534a1
def validate_arguments(func, args, kwargs, drop_extra=True): <NEW_LINE> <INDENT> parser = _parse_signature(func) <NEW_LINE> args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:5] <NEW_LINE> if missing: <NEW_LINE> <INDENT> raise ArgumentValidationError(tuple(missing)) <NEW_LINE> <DEDENT> elif (extra o...
Check if the function accepts the arguments and keyword arguments. Returns a new ``(args, kwargs)`` tuple that can savely be passed to the function without causing a `TypeError` because the function signature is incompatible. If `drop_extra` is set to `True` (which is the default) any extra positional or keyword argum...
625941e77cff6e4e81117df0
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941e7d268445f265b52d9
def testWordWithinAnother(self): <NEW_LINE> <INDENT> for pattern, text, expected_result in self.values: <NEW_LINE> <INDENT> actual_result = formatter.apply_tag_to_pattern(pattern, 'tag', text) <NEW_LINE> self.assertEqual(expected_result, actual_result)
Test the formatting of dummy tags around word patterns in the text with the word inside another
625941e76aa9bd52df037212
def get_profiler_by_type(type_id): <NEW_LINE> <INDENT> assert _is_initialized() <NEW_LINE> ids = _MANAGER.profilers.get_plugin_ids_by_type(type_id) <NEW_LINE> cls, cfg = _MANAGER.profilers.get_plugin_by_id(ids[0]) <NEW_LINE> return cls(), cfg
Get a profiler instance that supports the specified content type. :param type_id: content type :type type_id: str :return: tuple of Profiler instance and dictionary configuration :rtype: tuple (Profiler, dict) :raise: PluginNotFound if no profiler corresponds to the id
625941e7711fe17d825427cc
def get_homework(db,cls_id): <NEW_LINE> <INDENT> return db.query(table.HomeWork).filter_by(class_id=cls_id).all()
获取当前班级的所有已布置的作业 :param db: :param cls_id: :return:
625941e7f8510a7c17cf9b6a
def vegperiod(T, tempthres=5): <NEW_LINE> <INDENT> BeginOfSpring = pd.to_datetime('20.03.'+T.index[-1].year, format='%d.%m.%Y', tz='UTC') <NEW_LINE> BeginOfSummer = pd.to_datetime('20.06.'+T.index[-1].year, format='%d.%m.%Y', tz='UTC') <NEW_LINE> BeginnOfFall = pd.to_datetime('22.09.'+T.index[-1].year, format='%d.%m.%...
routine determines beginning and end of the period of vegetation based on mean and minimum daily temperature time series and time of the year following the method provided by Menzel et al. 2003 (cc) seibert@kit.edu and jackisch@kit.edu 2016 Menzel A, Jakobi G, Ahas R, Scheifinger H & Estrella N 2003: Variations of...
625941e78e05c05ec3eea7e3
def _dummyDataGen(x1, counts=100): <NEW_LINE> <INDENT> while counts > 0: <NEW_LINE> <INDENT> x2 = counts * 36 <NEW_LINE> yield { 'x1': x1, 'x2': x2, 'y1': math.sin(x2 / 360 * math.pi) + x1 / 1000, 'y2': math.cos(x2 / 360 * math.pi) + x1 / 1000, 'y3': math.radians(x2 / 360 * math.pi) + x1 / 2000, } <NEW_LINE> counts -= ...
Dummy data generator used for self test The return value is in the form of a dictionary
625941e78c0ade5d55d3ee29
def on_data(self, action, data): <NEW_LINE> <INDENT> action = action.decode('ascii') <NEW_LINE> if not isinstance(data, (list, vim.List)): <NEW_LINE> <INDENT> data = _unicode(data) <NEW_LINE> <DEDENT> if action == 'complete': <NEW_LINE> <INDENT> return self._do_complete(data) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT...
Callback when received data. :param action: action bind to this data (bytes) :param data: data is a complete action item (bytes, list) :rtype: list
625941e731939e2706e4d2ce
def log_event(self, source, *args, **kwargs): <NEW_LINE> <INDENT> log_event(source, *args, **kwargs)
Pass-through for :func:`log_event`
625941e7cb5e8a47e48b7f0e
def iswap_compiler(self, gate, args): <NEW_LINE> <INDENT> q1, q2 = gate.targets <NEW_LINE> pulse_info = [] <NEW_LINE> pulse_name = "sz" + str(q1) <NEW_LINE> coeff = self.wq[q1] - self.params["w0"] <NEW_LINE> pulse_info += [(pulse_name, coeff)] <NEW_LINE> pulse_name = "sz" + str(q2) <NEW_LINE> coeff = self.wq[q2] - self...
Compiler for the ISWAP gate
625941e721bff66bcd684db9
def restore(backup_dir): <NEW_LINE> <INDENT> idx = os.path.basename(backup_dir) <NEW_LINE> docs_file = os.path.join(backup_dir, '%s.docs' % idx) <NEW_LINE> if not os.path.isfile(docs_file): <NEW_LINE> <INDENT> raise RuntimeError("Failed to find docs file %s" % docs_file) <NEW_LINE> <DEDENT> mapping_file = os.path.join(...
Restore ES index from backup docs and mapping.
625941e7b7558d58953c5375
def get_host_settings(self): <NEW_LINE> <INDENT> return [ { 'url': "http://localhost:8181", 'description': "No description provided", } ]
Gets an array of host settings :return: An array of host settings
625941e7c4546d3d9de72ea3
def addDataset(self, **datasetParams): <NEW_LINE> <INDENT> datasetPSet = getattr(self.data, "dataset", None) <NEW_LINE> if datasetPSet == None: <NEW_LINE> <INDENT> self.data.dataset = CfgTypes.untracked(CfgTypes.PSet()) <NEW_LINE> datasetPSet = self.data.dataset <NEW_LINE> <DEDENT> for key, value in datasetParams.items...
_addDataset_ Add Dataset information to this cfg file. Each key, value pair provided in dataset Params is added as an untracked string to the datasets PSet in a PSet named entryName
625941e715baa723493c43e3
def add_subscription( channel, secret, composer_data, collector_data, metadata): <NEW_LINE> <INDENT> pass
Add a subscription and return it. Raises ValueError if subscription already exists.
625941e76fece00bbac2dbaf
def verify_signature_and_timestamp(keyid, signed, signature, args): <NEW_LINE> <INDENT> f = tempfile.NamedTemporaryFile(mode='w', delete=False) <NEW_LINE> f.write(signature) <NEW_LINE> f.close() <NEW_LINE> verified = gpg.verify_data(f.name, signed) <NEW_LINE> if not verified.valid: <NEW_LINE> <INDENT> sys.exit("Not a v...
Is the signature valid and the signature timestamp within range as well?
625941e74527f215b584c8bd
def test_text_to_matrix_spaces(): <NEW_LINE> <INDENT> text = "1 2 3\n4 5 6\n" <NEW_LINE> mat = text_to_matrix(text) <NEW_LINE> assert(np.all(mat == [[1, 2, 3], [4, 5, 6]]))
Check that text_to_matrix works with space separated data
625941e74f6381625f114ea6
def _create_cd_drives(cd_drives, controllers=None, parent_ref=None): <NEW_LINE> <INDENT> cd_drive_specs = [] <NEW_LINE> keys = range(-3000, -3050, -1) <NEW_LINE> if cd_drives: <NEW_LINE> <INDENT> devs = [dvd['adapter'] for dvd in cd_drives] <NEW_LINE> log.trace('Creating cd/dvd drives {0}'.format(devs)) <NEW_LINE> for ...
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the CD/DVD drives to be created for a virtual machine cd_drives CD/DVD drive properties controllers CD/DVD drive controllers (IDE, SATA) parent_ref Parent object reference
625941e7ac7a0e7691ed452f
def create(self): <NEW_LINE> <INDENT> settings = dict() <NEW_LINE> settings['card'] = None <NEW_LINE> settings['method'] = 'post' <NEW_LINE> self.render('card/config.html', **settings)
Show configuration form for device.
625941e729b78933be1e5b11
def get_sample_attrs(self): <NEW_LINE> <INDENT> attrs = dict() <NEW_LINE> attrs['md5'] = self.hashes.md5 <NEW_LINE> attrs['sha1'] = self.hashes.sha1 <NEW_LINE> attrs['sha256'] = self.hashes.sha256 <NEW_LINE> attrs['sha512'] = self.hashes.sha512 <NEW_LINE> attrs['ssdeep'] = self.hashes.ssdeep <NEW_LINE> attrs['size'] = ...
Trying to get attributes of the sample.
625941e7be383301e01b58e8