code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def cartesian(self, other): <NEW_LINE> <INDENT> v1 = self.toLocalIterator() <NEW_LINE> v2 = other.collect() <NEW_LINE> return self.context.parallelize([(a, b) for a in v1 for b in v2])
cartesian product of this RDD with ``other`` :param RDD other: Another RDD. :rtype: RDD .. note:: This is currently implemented as a local operation requiring all data to be pulled on one machine. Example: >>> from pysparkling import Context >>> rdd = Context().parallelize([1, 2]) >>> sorted(rdd.cartesian(...
625941be07d97122c4178799
def _finalize_axis(self, key): <NEW_LINE> <INDENT> if 'title' in self.handles: <NEW_LINE> <INDENT> self.handles['title'].set_visible(self.show_title) <NEW_LINE> <DEDENT> self.drawn = True <NEW_LINE> if self.subplot: <NEW_LINE> <INDENT> return self.handles['axis'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fig = self...
General method to finalize the axis and plot.
625941bea79ad161976cc058
def get_param_lim(self, parameter, limit, timeout=2.0, return_full = True): <NEW_LINE> <INDENT> response = get_value(self._host, self._port, self._api_v, "detector", "config", parameter, timeout=timeout, return_full=return_full) <NEW_LINE> return response[limit]
Returns the limit max or min of the given parameter :param string parameter: parameter name :param string limit: max or min :param float timeout: communication timeout in seconds :param bool return_full: whether to return the full response dict :returns: max count time in seconds :rtype: float
625941be1d351010ab855a30
def setRandomPolicy( self ): <NEW_LINE> <INDENT> self.movePolicy = RandomMover( self.pieces )
The player should perform random moves
625941be92d797404e30409c
def get_text_coherence_errors(self): <NEW_LINE> <INDENT> text_coherence_errors = [] <NEW_LINE> author = ['i', 'we', 'me', 'myself', 'ourself', 'us', 'our', 'my', 'mine'] <NEW_LINE> reader = ['you', 'yourself', 'your', 'yours'] <NEW_LINE> male = ['he', 'him', 'himself', 'his'] <NEW_LINE> female = ['she', 'her', 'herself...
Return list of text coherence errors Returns: text_coherence_errors(list): list of text coherence errors
625941be99cbb53fe6792afa
def __init__(self, name, addr, size, info): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.addr = addr <NEW_LINE> self.size = size <NEW_LINE> self.symtype = Symbol.typeNameToInt(info["type"]) <NEW_LINE> self.bindtype = Symbol.bindNameToInt(info["bind"])
Create a symbol using values read from the ELF symbol table.
625941bef8510a7c17cf960e
def test_check(self): <NEW_LINE> <INDENT> succ = BlockDev.btrfs_create_volume([self.loop_dev], None, None, None) <NEW_LINE> self.assertTrue(succ) <NEW_LINE> succ = BlockDev.btrfs_check(self.loop_dev) <NEW_LINE> self.assertTrue(succ)
Verify that it's possible to check the btrfs filesystem
625941be009cb60464c632c7
def direct_search(priority): <NEW_LINE> <INDENT> def decorator(searcher): <NEW_LINE> <INDENT> searcher.direct_search_priority = priority <NEW_LINE> return searcher <NEW_LINE> <DEDENT> return decorator
Mark a function as being a direct search provider. :arg priority: A priority to attach to the function. Direct searchers are called in order of increasing priority.
625941be5fc7496912cc3891
def up_block(input_layer, concat_layer, n_features, is_training, keep_prob, name=None, norm_fn=None, **kwargs): <NEW_LINE> <INDENT> normalizer_params = kwargs.get('normalizer_params', normalizer_params_default) if norm_fn is not None else None <NEW_LINE> if normalizer_params is not None and 'is_training' in normalizer_...
Up block consisting of a deconvolution and three convolutions. :param input_layer: input :param concat_layer: layer that is copied for the convolution (usually output of the corresponding down block) :param n_features: number of features that are created by the conv :param is_training: phase :param keep_prob: for drop...
625941be287bf620b61d3979
def __init__(self): <NEW_LINE> <INDENT> self._x = None
The __init__ is documented.
625941be97e22403b379ceac
def SpliceComments(tree): <NEW_LINE> <INDENT> prev_leaf = [None] <NEW_LINE> _AnnotateIndents(tree) <NEW_LINE> def _VisitNodeRec(node): <NEW_LINE> <INDENT> for child in node.children[:]: <NEW_LINE> <INDENT> if isinstance(child, pytree.Node): <NEW_LINE> <INDENT> _VisitNodeRec(child) <NEW_LINE> <DEDENT> else: <NEW_LINE> <...
Given a pytree, splice comments into nodes of their own right. Extract comments from the prefixes where they are housed after parsing. The prefixes that previously housed the comments become empty. Args: tree: a pytree.Node - the tree to work on. The tree is modified by this function.
625941be55399d3f055885c6
def analysis_complete(self): <NEW_LINE> <INDENT> self.start_btn.setEnabled(True) <NEW_LINE> self.pause_btn.setEnabled(False) <NEW_LINE> self.stop_btn.setEnabled(False) <NEW_LINE> self.pause_btn.setText('Pause') <NEW_LINE> self.update_status('Ready')
Slot to run once the analysis worker is finished.
625941be55399d3f055885c7
def read_file(path: str) -> (set, int): <NEW_LINE> <INDENT> rel_file = open(path, 'r', encoding='utf-8') <NEW_LINE> relation = set() <NEW_LINE> rel_list = rel_file.readlines() <NEW_LINE> separator = rel_list[0][1] <NEW_LINE> rel_file.close() <NEW_LINE> for i in range(len(rel_list)): <NEW_LINE> <INDENT> rel_list[i] = re...
Reads relation from file and returns it as a list of tuples and its length.
625941bedd821e528d63b0be
@pytest.mark.manual <NEW_LINE> @pytest.mark.tier(2) <NEW_LINE> def test_dd_multiselect_default_element_is_shouldnt_be_blank_when_loaded_by_another_element(): <NEW_LINE> <INDENT> pass
Polarion: assignee: nansari casecomponent: Services initialEstimate: 1/16h testtype: functional startsin: 5.9 tags: service Bugzilla: 1645555
625941befb3f5b602dac35a4
def check_attempts(card): <NEW_LINE> <INDENT> if card.attempts < settings.MAX_ATTEMPTS: <NEW_LINE> <INDENT> return {"success": True} <NEW_LINE> <DEDENT> card.is_active = False <NEW_LINE> card.save() <NEW_LINE> return {"success": False, "message": ('Your account has been locked ' 'out because of too many ' 'failed login...
Count attempts and check MAX_ATTEMPTS limit
625941be851cf427c661a426
def rvs(self): <NEW_LINE> <INDENT> if self.bins_distributions is None: <NEW_LINE> <INDENT> self.create_poisson_distributions() <NEW_LINE> <DEDENT> return np.r_[[i.rvs(1).sum() for i in self.bins_distributions]]
sample from the distribution of each bin
625941be85dfad0860c3ad6d
def eat_delim(self, d): <NEW_LINE> <INDENT> if not self.match_delim(d): <NEW_LINE> <INDENT> raise BadSyntaxException() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__next_token()
Throws an exception if the current token is not the specified delimiter. Otherwise, moves to the next token.
625941be3346ee7daa2b2c7e
def test_ml_int_ml_id_rename(self): <NEW_LINE> <INDENT> NonString = int() <NEW_LINE> with self.assertRaises(AssertionError): <NEW_LINE> <INDENT> MailingList().rename_list(mailing_list=NonString, name='Fake')
This method tests that an assertion is raised in the MailingList Module when the user enters a mailing_list_id that is incorrect.
625941beadb09d7d5db6c6a5
def get_titles_of_downloaded_albums(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(TITLES_TO_SKIP_FILE, "r", encoding="utf-8", newline="") as input_file: <NEW_LINE> <INDENT> for row in csv.DictReader(input_file): <NEW_LINE> <INDENT> yield row['bookmark-title'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except IOE...
Returns an iterator of the bookmark titles for whom torrents were already downloaded in the previous runs of the program.
625941beaad79263cf390951
def plot_ax(self, ax, what="d", exchange_xy=False, *args, **kwargs): <NEW_LINE> <INDENT> opts = [c.lower() for c in what] <NEW_LINE> cases = {"d": self.dos, "i": self.idos} <NEW_LINE> lines = list() <NEW_LINE> for c in opts: <NEW_LINE> <INDENT> f = cases[c] <NEW_LINE> ls = f.plot_ax(ax, exchange_xy=exchange_xy, *args, ...
Helper function to plot the data on the axis ax. Args: ax: matplotlib axis what: string selecting the quantity to plot: "d" for DOS, "i" for IDOS. chars can be concatenated hence what="id" plots both IDOS and DOS. (default "d"). exchange_xy: True to exchange exis ...
625941be44b2445a33931fae
def test_create_project(): <NEW_LINE> <INDENT> with FakeProjectContext() as ctx: <NEW_LINE> <INDENT> assert os.path.exists(ctx.path) <NEW_LINE> assert os.path.exists(os.path.join(ctx.path, default_project_file)) <NEW_LINE> assert os.path.exists(os.path.join(ctx.path, default_model_conditionsfp)) <NEW_LINE> GSMProject(c...
Create a test project with an example e coli model
625941bebe383301e01b539f
def test(self,my_round,set_to_use='test'): <NEW_LINE> <INDENT> assert set_to_use in ['train', 'test'] <NEW_LINE> if set_to_use == 'train': <NEW_LINE> <INDENT> data = self.train_data <NEW_LINE> <DEDENT> elif set_to_use == 'test': <NEW_LINE> <INDENT> data = self.eval_data <NEW_LINE> <DEDENT> self.model.set_params(self.mo...
Tests self.model on self.test_data. Args: set_to_use. Set to test on. Should be in ['train', 'test']. Return: dict of metrics returned by the model.
625941be283ffb24f3c55818
def delete_object(self, iden, uid, token): <NEW_LINE> <INDENT> self.obj_str.delete_object(uid, token, iden)
Delete a data object. :param iden: Id of the object. :param uid: Identifier for the user. :param token: The token of the user.
625941be293b9510aa2c31ac
def login(self): <NEW_LINE> <INDENT> pass
Login to a terminal, using I/O specific (rather than language-specific) routines. Uses the username and password of the BaseLanguageInput
625941be23849d37ff7b2fa4
def cls_player_sleep(self, mac_player: str, seconds_before_sleep: int) -> None: <NEW_LINE> <INDENT> payload = ( '{"id": 0, "params": ["' + mac_player + '",["sleep","' + str(seconds_before_sleep) + '"]],"method": "slim.request"}' ) <NEW_LINE> self._cls_execute_request(payload) <NEW_LINE> print("Player goind to sleep in:...
player on or off input : mac_player: str, the player mac address, ie: 5a:65:a2:33:80:79 : seconds_before_sleep: number of seconds before sleep returns : None
625941be4e696a04525c9360
def createMountain(x, y, xc, yc, rm, h0max): <NEW_LINE> <INDENT> nx = len(x) <NEW_LINE> ny = len(y) <NEW_LINE> h0 = np.zeros([nx,ny]) <NEW_LINE> for i in xrange(0,nx): <NEW_LINE> <INDENT> for j in xrange(0,ny): <NEW_LINE> <INDENT> dist = np.sqrt((x[i] - xc)**2 + (y[j] - yc)**2) <NEW_LINE> if dist < rm: <NEW_LINE> <INDE...
create the mountain at locations x and y
625941be0c0af96317bb80fc
def _create(self): <NEW_LINE> <INDENT> log_method_call(self, self.name, status=self.status) <NEW_LINE> fd = os.open(self.path, os.O_WRONLY|os.O_CREAT|os.O_TRUNC) <NEW_LINE> os.ftruncate(fd, self.size) <NEW_LINE> os.close(fd)
Create a sparse file.
625941bee5267d203edcdbb3
def handle_getfield_gc(self, op): <NEW_LINE> <INDENT> self.emit_pending_zeros() <NEW_LINE> self.emit_op(op)
See test_zero_ptr_field_before_getfield(). We hope there is no getfield_gc in the middle of initialization code, but there shouldn't be, given that a 'new' is already delayed by previous optimization steps. In practice it should immediately be followed by a bunch of 'setfields', and the 'pending_zeros' optimization w...
625941be5fc7496912cc3892
def get_bgp_instance(self, **kwargs): <NEW_LINE> <INDENT> module = kwargs["module"] <NEW_LINE> conf_str = CE_GET_BGP_INSTANCE <NEW_LINE> xml_str = self.netconf_get_config(module=module, conf_str=conf_str) <NEW_LINE> result = list() <NEW_LINE> if "<data/>" in xml_str: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT...
get_bgp_instance
625941bef9cc0f698b140511
def test_search_insert(): <NEW_LINE> <INDENT> binary_tree = ctypes.CDLL(dll_path) <NEW_LINE> binary_tree.create_binary_tree.restype = ctypes.c_void_p <NEW_LINE> b1 = binary_tree.create_binary_tree(ctypes.c_int(10000)) <NEW_LINE> vals = random.sample(range(-500, 500), random.randint(100, 150)) <NEW_LINE> for val in vals...
Insert random values into tree, test that these values have been inserted and no others
625941be8e05c05ec3eea286
def _check_keyword_parentheses(self, tokens, start): <NEW_LINE> <INDENT> if self._inside_brackets(":") and tokens[start][1] == "for": <NEW_LINE> <INDENT> self._pop_token() <NEW_LINE> <DEDENT> if tokens[start + 1][1] != "(": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> found_and_or = False <NEW_LINE> depth = 0 <NEW_LI...
Check that there are not unnecessary parens after a keyword. Parens are unnecessary if there is exactly one balanced outer pair on a line, and it is followed by a colon, and contains no commas (i.e. is not a tuple). Args: tokens: list of Tokens; the entire list of Tokens. start: int; the position of the keyword in th...
625941be4e4d5625662d42ef
def day11a(): <NEW_LINE> <INDENT> rows = helpers.get_input_strings("day11") <NEW_LINE> length = len(rows) <NEW_LINE> width = len(rows[0]) <NEW_LINE> print(f"Length: {length}, Width: {width}") <NEW_LINE> helpers.print_rows(rows) <NEW_LINE> limit = 4 <NEW_LINE> recurse = False <NEW_LINE> done = False <NEW_LINE> i = 0 <NE...
Day 11a: Seating System.
625941bee5267d203edcdbb4
def _parse_libsvm(scope, model, inputs): <NEW_LINE> <INDENT> return _parse_libsvm_simple_model(scope, model, inputs)
This is a delegate function. It doesn't nothing but invoke the correct parsing function according to the input model's type. :param scope: Scope object :param model: A scikit-learn object (e.g., OneHotEncoder and LogisticRegression) :param inputs: A list of variables :return: The output variables produced by the input ...
625941bed10714528d5ffbf4
def set_text(): <NEW_LINE> <INDENT> if len(sys.argv[1:]) == 0: <NEW_LINE> <INDENT> phrase = 'Hello' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> phrase = sys.argv[1] <NEW_LINE> del sys.argv[1] <NEW_LINE> <DEDENT> return phrase
Must be called before _parse_args() or it will not work
625941be73bcbd0ca4b2bf8a
def remove_watch(self, path, superficial=False): <NEW_LINE> <INDENT> wd = self.__watches.get(path) <NEW_LINE> if wd is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> _LOGGER.debug("Removing watch for watch-handle (%d): [%s]", wd, path) <NEW_LINE> del self.__watches[path] <NEW_LINE> self.remove_watch_with_id(wd, s...
Remove our tracking information and call inotify to stop watching the given path. When a directory is removed, we'll just have to remove our tracking since inotify already cleans-up the watch.
625941be460517430c3940a0
def get_domain_url (self): <NEW_LINE> <INDENT> if isinstance(self.topoAdapter, AbstractRESTAdapter): <NEW_LINE> <INDENT> return self.topoAdapter.URL
:return: Return the configured domain URL extracted from DomainAdapter. :rtype: str
625941be56ac1b37e62640e8
def patch_view(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.process_update_request(request, *args, **kwargs) <NEW_LINE> with transaction.atomic(): <NEW_LINE> <INDENT> self.patch_view_before(request, *args, **kwargs) <NEW_LINE> assert self.form_data.get('id') == self.id and self.id, {'message': '传入参数不正确!', ...
patch请求用与更新部分字段 :param request: :param args: :param kwargs: :return: 更新后的字段
625941be6aa9bd52df036cb7
def detail(self, image_id): <NEW_LINE> <INDENT> url = self._url + '/' + image_id <NEW_LINE> resp = self._sess.get(url) <NEW_LINE> return resp.json
Retreive details of a server image :param server_id: numerical id of image to detail
625941be99fddb7c1c9de2a6
def minimization_loop_closing(pose, loops): <NEW_LINE> <INDENT> pose.dump_pdb('debug/before_minimize.pdb') <NEW_LINE> ft = rosetta.core.kinematics.FoldTree() <NEW_LINE> ft.add_edge(1, 14, 1) <NEW_LINE> ft.add_edge(1, 38, 2) <NEW_LINE> ft.add_edge(1, 48, 3) <NEW_LINE> ft.add_edge(1, 12, -1) <NEW_LINE> ft.add_edge(14, 13...
Close the loops of a pose by minimization.
625941be1f5feb6acb0c4a68
def run_proc(proc, retcode, timeout = None): <NEW_LINE> <INDENT> _register_proc_timeout(proc, timeout) <NEW_LINE> stdout, stderr = proc.communicate() <NEW_LINE> proc._end_time = time.time() <NEW_LINE> if not stdout: <NEW_LINE> <INDENT> stdout = six.b("") <NEW_LINE> <DEDENT> if not stderr: <NEW_LINE> <INDENT> stderr = s...
Waits for the given process to terminate, with the expected exit code :param proc: a running Popen-like object :param retcode: the expected return (exit) code of the process. It defaults to 0 (the convention for success). If ``None``, the return code is ignored. It may also be a tuple ...
625941bed18da76e235323e7
def resize_image(self, name, framesize): <NEW_LINE> <INDENT> displayimg = self.previewtrain[name][0] <NEW_LINE> if framesize: <NEW_LINE> <INDENT> frameratio = float(framesize[0]) / float(framesize[1]) <NEW_LINE> imgratio = float(displayimg.size[0]) / float(displayimg.size[1]) <NEW_LINE> if frameratio <= imgratio: <NEW_...
Resize the training preview image based on the passed in frame size
625941be94891a1f4081b9bc
def __init__(self, window): <NEW_LINE> <INDENT> egg.gui.GridLayout.__init__(self) <NEW_LINE> self._layout.setContentsMargins(0,0,0,0) <NEW_LINE> self._window = window <NEW_LINE> self.button_save = self.place_object(egg.gui.Button("Save")) <NEW_LINE> self.button_load = self.place_object(egg.gui.Button("Load")) <NEW_LINE...
This object is a grid layout containing an image with save / load buttons. You must supply a window object so that it can connect buttons to actions, etc.
625941be796e427e537b04d8
def __init__(self): <NEW_LINE> <INDENT> self._current_date = 0 <NEW_LINE> self._holdings = dict() <NEW_LINE> self._members = dict()
Initializes library inventory/members and sets current date to 0
625941be7d847024c06be1cd
def __init__(self): <NEW_LINE> <INDENT> self.Platforms = None <NEW_LINE> self.LicenseIds = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None
:param Platforms: 平台集合。 :type Platforms: list of str :param LicenseIds: 平台绑定的 license Id 集合。 :type LicenseIds: list of str :param Offset: 分页返回的起始偏移量,默认值:0。 :type Offset: int :param Limit: 分页返回的记录条数,默认值:10。 :type Limit: int
625941bede87d2750b85fca4
def get_coords(image): <NEW_LINE> <INDENT> boxes = [] <NEW_LINE> s3 = aws.get_s3_resource() <NEW_LINE> image_uri = image.get("imageURI") <NEW_LINE> output = { "image_uri": image_uri } <NEW_LINE> positions = image.get("positions") <NEW_LINE> single_box = image.get("single-box") is True <NEW_LINE> text_data = get_text_in...
{"positions": [[25, 31], 100, 110], "height": 768, "width": 1024, "imageURI": "http://aplaceforstuff.co.uk/x/"}
625941be99fddb7c1c9de2a7
def focusInEvent(self, event): <NEW_LINE> <INDENT> self.focused_in.emit(event) <NEW_LINE> super(CodeEdit, self).focusInEvent(event)
Overrides focusInEvent to emits the focused_in signal :param event: QFocusEvent
625941be85dfad0860c3ad6e
def test_qdel_hstry_jobs_rerun(self): <NEW_LINE> <INDENT> a = {'job_history_enable': 'True', 'job_history_duration': '5', 'job_requeue_timeout': '5', 'node_fail_requeue': '5', 'scheduler_iteration': '5'} <NEW_LINE> self.server.manager(MGR_CMD_SET, SERVER, a) <NEW_LINE> j = Job() <NEW_LINE> jid = self.server.submit(j) <...
Test rerunning a history job that was prematurely terminated due to a a downed mom.
625941be56b00c62f0f1456c
def docker_stop(container_name): <NEW_LINE> <INDENT> _logger.info('Stopping container %s', container_name) <NEW_LINE> dstop = subprocess.run(['docker', 'stop', container_name])
Stops the container named container_name
625941be29b78933be1e55c5
def execute(self, sql, parameters = ()): <NEW_LINE> <INDENT> with self.connection.cursor() as cursor: <NEW_LINE> <INDENT> cursor.execute(sql, parameters) <NEW_LINE> self.lastrowid = cursor.lastrowid <NEW_LINE> <DEDENT> self.connection.commit() <NEW_LINE> return self.lastrowid
Execute a general request - Insert, Update, Delete. Parameters ---------- sql : string parameters : set
625941bed6c5a10208143f5d
def addToDatabase(databaseValues, listOfItems, sessionId): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = pymysql.connect(user=databaseValues['user'], host=databaseValues['host'], password=databaseValues['password'], database=databaseValues['name'], port=int(databaseValues['port'])) <NEW_LINE> curs = conn.cursor()...
Adds measurements to the database from a list of values :param databaseValues: a python dictionary containing MySQL connection values Example: {'user': 'root', 'host': '127.0.0.1', 'password': '1234', 'name': 'databasename', 'port': '3306'} :param listOfItems: a dictionary containing channel id's as keys and measuremen...
625941befb3f5b602dac35a5
def set_response_A(self, text): <NEW_LINE> <INDENT> self.response_A = text <NEW_LINE> self.button_A = Button(BLACK, self.x + 10, self.y + 120, self.width -20, 50, "A", text = self.response_A, text_color = WHITE)
Sets the text which will appear in button A
625941be57b8e32f524833ae
@app.route("/") <NEW_LINE> def home(): <NEW_LINE> <INDENT> return render_template("madlib.html")
display madlib story shell choice
625941be30bbd722463cbcd8
def process_data(path_to_event, path_to_time, time_scale=1.0): <NEW_LINE> <INDENT> if not os.path.isfile(path_to_event): <NEW_LINE> <INDENT> raise ValueError("Path {0} does not exist!".format(path_to_event)) <NEW_LINE> <DEDENT> if not os.path.isfile(path_to_time): <NEW_LINE> <INDENT> raise ValueError("Path {0} does not...
Process event and time data into ndarrays: X = [one_hot_Y_j-1 + dt_j-1], Y = [Y_j, dt_j]
625941be1f037a2d8b946114
def test_infrastructure_item_edit_out(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('infrastructure_item_edit', args=[self.item.id])) <NEW_LINE> self.assertRedirects(response, reverse('user_login'))
Testing /infrastructure/item/edit/<item_id>
625941be07f4c71912b11395
def checkForUsageMessage(self, args): <NEW_LINE> <INDENT> if (len(args) < 2) or ("-h" in args) or ("--help" in args): <NEW_LINE> <INDENT> raise RuntimeError(self.USAGE_MESSAGE)
Check arguments and raise RuntimeError containing usage/help message if appropriate. If command line arguments are empty (apart from program name) or "-h" or "--help" was specified, then the exception is raised. Arguments: args -- List of command line arguments given
625941bef7d966606f6a9f16
def update(self, document): <NEW_LINE> <INDENT> document = CollectionHandler.convert_ids(document) <NEW_LINE> return self.collection_handle.update(document)
Updates the given document in database. :param document: Dictionary with _id :return: document
625941be45492302aab5e1d5
def addElementLabel(self, label): <NEW_LINE> <INDENT> if len(label.keys()) != 0: <NEW_LINE> <INDENT> self.useDefault = False
load default values only for new elements with no xmoto_label
625941be566aa707497f4482
def calculate_global_centiles_for_orgs(self, org_type): <NEW_LINE> <INDENT> extra_fields = [] <NEW_LINE> for col in self._get_col_aliases("numerator"): <NEW_LINE> <INDENT> extra_fields.append("num_" + col) <NEW_LINE> <DEDENT> for col in self._get_col_aliases("denominator"): <NEW_LINE> <INDENT> extra_fields.append("deno...
Adds centiles to the already-existing centiles table
625941be96565a6dacc8f5e1
def _version_output(service): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> version_output = check_output([service, VERSION_FLAG]).decode('utf-8').strip() <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> version_output = '' <NEW_LINE> <DEDENT> return version_output
Return the output of the command `service` with the argument '--version'. Args: service (str): The service to check the version of. Returns: str: The output of the command `service` with the argument '--version', or an empty string if the command is not installed. Example: >>> _version_output('snips...
625941bead47b63b2c509e95
def _deobfuscate(self): <NEW_LINE> <INDENT> hashmod = 256 <NEW_LINE> password = base64.b64decode(self.__password).decode('UTF-8') <NEW_LINE> hash_value = self._compute_hash(self.__host + self.__username) % hashmod <NEW_LINE> crypt = chr(hash_value & 0xFF) * len(password) <NEW_LINE> password_final = [] <NEW_LINE> for n ...
Convert the obfuscated string to the actual password in clear text Functionality taken from the perl module VICredStore.pm since the goal was to emulate its behaviour.
625941be32920d7e50b280e2
def generate_batch(): <NEW_LINE> <INDENT> with open(f'{PAPERCUT / "config.properties"}', 'r') as config_file: <NEW_LINE> <INDENT> clean_config = config_file.read() <NEW_LINE> working_config = copy.deepcopy(clean_config) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(DEVICES, 'r') as device_list: <NEW_LINE> <IND...
Main function - Reads the clean 'properties.config' file from the 'papercut_software' folder and creates a working copy to use with the class methods so that a clean copy can be used each loop or restored if something crashes and then calls the methods to get all of the specific info, generate the config file, and t...
625941be4527f215b584c36f
def list_app_keys(self, app_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.list_app_keys_with_http_info(app_id, **kwargs)
List App Keys # noqa: E501 Lists all API keys for a given app. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_app_keys(app_id, async_req=True) >>> result = thread.get() :param async_req bool: execute reques...
625941be29b78933be1e55c6
def __sum_sub_cts(self, ts_sum, ts_new, mult=1, neg=True): <NEW_LINE> <INDENT> if ts_sum is None: <NEW_LINE> <INDENT> ts_sum = np.zeros(len(self.sample_time)) <NEW_LINE> <DEDENT> start_time = ts_new[0, 0] <NEW_LINE> start_charge =ts_new[0, 1] <NEW_LINE> xx = ts_new[:, 0] - start_time <NEW_LINE> yy = ts_new[:, 1] - star...
Args: ts_sum: ts_new: mult: neg:
625941bee76e3b2f99f3a72a
def isValid(text): <NEW_LINE> <INDENT> return bool(re.search(r'\b(story)\b', text, re.IGNORECASE))
Returns True if the input is related to the news. Arguments: text -- user-input, typically transcribed speech
625941be6aa9bd52df036cb8
def test_restore_SessionState_metadata_restores_app_blob(self): <NEW_LINE> <INDENT> obj_repr = copy.copy(self.good_repr) <NEW_LINE> obj_repr['metadata']['app_blob'] = "YmxvYg==" <NEW_LINE> self.resume_fn(self.session, obj_repr) <NEW_LINE> self.assertEqual(self.session.metadata.app_blob, b"blob")
verify that _restore_SessionState_metadata() restores ``title``
625941be4a966d76dd550f22
def retype(self, newtype): <NEW_LINE> <INDENT> SupplyFeed.feed_types[self.type_].remove(self) <NEW_LINE> if not SupplyFeed.feed_types[self.type_]: <NEW_LINE> <INDENT> del SupplyFeed.feed_types[self.type_] <NEW_LINE> <DEDENT> self.type_ = newtype <NEW_LINE> if newtype not in SupplyFeed.feed_types: <NEW_LINE> <INDENT> Su...
Change the type of this SupplyFeed.
625941be32920d7e50b280e3
def get_edge_colors(im): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for x in range(im.size[0]): <NEW_LINE> <INDENT> result.append(im.getpixel((x, 0))) <NEW_LINE> result.append(im.getpixel((x, im.size[1] - 1))) <NEW_LINE> <DEDENT> for y in range(1, im.size[1] - 1): <NEW_LINE> <INDENT> result.append(im.getpixel((0, y))) ...
This function will get the color values of the pixels that are located on the edge of an image :param im: The image of type (:py:class:`~PIL.Image.Image`), of which the pixel values are extracted. :returns: A list of tuples that represent the pixel values.
625941be379a373c97cfaa59
def keyPressEvent(self, event): <NEW_LINE> <INDENT> if event.key() == QtCore.Qt.Key_Delete: <NEW_LINE> <INDENT> self.delete_current_point()
Internal keypress handler
625941bed8ef3951e3243452
def testRestGetTwoPages(self): <NEW_LINE> <INDENT> command = 'test command' <NEW_LINE> rtn_vals1 = [1, 2, 3] <NEW_LINE> rtn_vals2 = [4, 5, 6] <NEW_LINE> req_resp = [{'isLastPage': False, 'nextPageStart': 10, 'values': rtn_vals1}, {'isLastPage': True, 'nextPageStart': 0, 'values': rtn_vals2}] <NEW_LINE> with patch('bb_r...
Test the rest request with 2 page response.
625941becad5886f8bd26eef
def views_in_group(self, group): <NEW_LINE> <INDENT> pass
return [View] Returns all open views in the given group.
625941be099cdd3c635f0b71
def process_datapoint(self, datapoint): <NEW_LINE> <INDENT> timestamp = datapoint.timestamp <NEW_LINE> if self._current_point and self._current_point.timestamp.date() != timestamp.date(): <NEW_LINE> <INDENT> self._first_timestamp = timestamp <NEW_LINE> <DEDENT> self._current_point = datapoint <NEW_LINE> if len...
Accept `datapoint` and prepare to execute next `step`. Datapoint is assumed to be OHLC bar with associated timestamp in corresponding attributes.
625941be236d856c2ad446ec
def generateSubsamples(df,save_folder, nrep = 100, frac = 0.75, seed_entropy = 237262676468864319646780408567402854442,resample=True): <NEW_LINE> <INDENT> if not resample: <NEW_LINE> <INDENT> with open(os.path.join(save_folder, 'samples.pk'), 'rb') as file_name: <NEW_LINE> <INDENT> samples = pickle.load(file_name) <NEW...
Subsample a fraction frac of data, repeat nrep times Save the generated samples as pickled list to save/(river)/samples.pk. Parameters ---------- df: pandas DataFrame, shape (n_samples, n_nodes) The input data. Each row is an observation where some of the nodes have extreme values. frac: a number in [0,1] frac...
625941be7d43ff24873a2bb3
def _disable_complete_on_space(self) -> str: <NEW_LINE> <INDENT> delay_factor = self.select_delay_factor(delay_factor=0) <NEW_LINE> time.sleep(delay_factor * 0.1) <NEW_LINE> command = "environment command-completion space false" <NEW_LINE> self.write_channel(self.normalize_cmd(command)) <NEW_LINE> time.sleep(delay_fact...
SR-OS tries to auto complete commands when you type a "space" character. This is a bad idea for automation as what your program is sending no longer matches the command echo from the device, so we disable this behavior.
625941be8e7ae83300e4aee1
def block_hash_file(self, radosobject): <NEW_LINE> <INDENT> hashes = [] <NEW_LINE> append = hashes.append <NEW_LINE> block_hash = self.block_hash <NEW_LINE> for block in file_sync_read_chunks(radosobject, self.blocksize, 1, 0): <NEW_LINE> <INDENT> append(block_hash(block)) <NEW_LINE> <DEDENT> return hashes
Return the list of hashes (hashes map) for the blocks in a buffered file. Helper method, does not affect store.
625941bef8510a7c17cf9610
def test_get_sun_pitch_yaw(): <NEW_LINE> <INDENT> pitch, yaw = get_sun_pitch_yaw(109, 55.3, time='2021:242') <NEW_LINE> assert np.allclose((pitch, yaw), (60.453385, 29.880125)) <NEW_LINE> pitch, yaw = get_sun_pitch_yaw(238.2, -58.9, time='2021:242') <NEW_LINE> assert np.allclose((pitch, yaw), (92.405603, 210.56582)) <N...
Test that values approximately match those from ORviewer. See slack discussion "ORviewer sun / anti-sun plots azimuthal Sun yaw angle"
625941be99cbb53fe6792afc
def test_102_eab_check(self): <NEW_LINE> <INDENT> payload = 'payload' <NEW_LINE> protected = None <NEW_LINE> result = (403, 'urn:ietf:params:acme:error:externalAccountRequired', 'external account binding required') <NEW_LINE> self.assertEqual(result, self.account._eab_check(protected, payload))
test external account binding payload and but no protected
625941be0383005118ecf4fa
def test_register_noname(self): <NEW_LINE> <INDENT> if self._register_device(noname=True): <NEW_LINE> <INDENT> raise TestSuiteRunningError("The server must not accept registering with no id and name")
Register a device for the current license wih no id nor name. The server should return an error
625941bebe8e80087fb20b5c
def get_transformed(self, transformers): <NEW_LINE> <INDENT> block_structure = self.get_collected() <NEW_LINE> transformers.transform(block_structure) <NEW_LINE> return block_structure
Returns the transformed Block Structure for the root_block_usage_key, getting block data from the cache and modulestore, as needed. Details: Same as the get_collected method, except the transformers' transform methods are also called. Arguments: transformers (BlockStructureTransformers) - Collection of tr...
625941be97e22403b379ceae
def process(self, resp): <NEW_LINE> <INDENT> pass
:param resp: :return:
625941be92d797404e30409f
def bboxes_nms_fast(classes, scores, bboxes, threshold=0.45): <NEW_LINE> <INDENT> pass
Apply non-maximum selection to bounding boxes.
625941bebaa26c4b54cb1038
def save_hdf5(self, filename, force_overwrite=True): <NEW_LINE> <INDENT> with HDF5TrajectoryFile(filename, 'w', force_overwrite=force_overwrite) as f: <NEW_LINE> <INDENT> f.write(coordinates=in_units_of(self.xyz, Trajectory._distance_unit, f.distance_unit), time=self.time, cell_lengths=in_units_of(self.unitcell_lengths...
Save trajectory to MDTraj HDF5 format Parameters ---------- filename : str filesystem path in which to save the trajectory force_overwrite : bool, default=True Overwrite anything that exists at filename, if its already there
625941be9c8ee82313fbb68a
def get_action(self, consumer: Actor) -> Optional[ActionOrHandler]: <NEW_LINE> <INDENT> return actions.ItemAction(consumer, self.parent)
try to return the action for this item
625941be3c8af77a43ae36b3
def db_sent_updater(self, action, sender_id=None, postid=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if action == 'update': <NEW_LINE> <INDENT> day = (datetime.now(timezone.utc) + timedelta(hours=self.credential.Timezone)).day <NEW_LINE> if day != self.day: <NEW_LINE> <INDENT> self.day = day <NEW_LINE> self.db_...
Update self.db_sent :param action: 'update','add' or 'delete' -> str :param sender_id: sender id who has sent the menfess -> str :param postid: tweet id or (sender_id, tweet id) -> str or tuple
625941be460517430c3940a1
def __navigateForward(self): <NEW_LINE> <INDENT> if len(self.__currentHistory) > 0 and self.__currentHistoryLocation < len(self.__currentHistory) - 1: <NEW_LINE> <INDENT> self.__currentHistoryLocation += 1 <NEW_LINE> url = self.__currentHistory[self.__currentHistoryLocation] <NEW_LINE> self.selectUrl(url)
Navigate through the history one step forward.
625941be6fb2d068a760efb0
def testE(self): <NEW_LINE> <INDENT> gr = LognormalRestraint(*self.all) <NEW_LINE> self.m.add_restraint(gr) <NEW_LINE> for i in range(100): <NEW_LINE> <INDENT> map(self.change_value, self.all) <NEW_LINE> e = self.m.evaluate(False) <NEW_LINE> self.assertAlmostEqual(e, self.normal_e(*self.all))
Test LognormalRestraint(23) score
625941be7b25080760e39370
def to_categorical(y): <NEW_LINE> <INDENT> y = LongTensor(y).view(-1, 1) <NEW_LINE> y_onehot = Tensor(y.size(0), 10) <NEW_LINE> y_onehot.zero_() <NEW_LINE> y_onehot.scatter_(1, y, 1) <NEW_LINE> return y_onehot
1-hot encodes a tensor
625941bec4546d3d9de72947
def swissPairings(): <NEW_LINE> <INDENT> standings = [(data[0], data[1]) for data in playerStandings()] <NEW_LINE> if len(standings) < 2: <NEW_LINE> <INDENT> raise KeyError("Looks like we dont have enough players, bring someone on board.") <NEW_LINE> <DEDENT> left = standings[0::2] <NEW_LINE> right = standings[1::2] <N...
Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standing...
625941be5fdd1c0f98dc0148
def make_move(self, direction): <NEW_LINE> <INDENT> super(GameDisplay, self).make_move(direction) <NEW_LINE> self.win.queue_draw()
Carries out a move in the specified direction and queues a display update. @param direction: which direction to move in
625941bebf627c535bc130e4
def check_tie(board): <NEW_LINE> <INDENT> for list in board: <NEW_LINE> <INDENT> for symbol in list: <NEW_LINE> <INDENT> if (symbol != "X") or (symbol != "O"): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if check_win(board) == True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <...
Check the game for a tie, no available locations and no winners. args: board: 3x3 table (list of lists) containing the current state of the game returns: True if there is a tie. False the board is not full yet or there is a winner
625941be0a366e3fb873e72d
def matching(pot): <NEW_LINE> <INDENT> for player in pot.players: <NEW_LINE> <INDENT> if not player.hand: <NEW_LINE> <INDENT> trips = [] <NEW_LINE> pairs = [] <NEW_LINE> for card in player.hole_cards: <NEW_LINE> <INDENT> count = player.hole_cards.count(card) <NEW_LINE> if count == 4: <NEW_LINE> <INDENT> kicker = [x for...
identifies the highest value matching hands eg quads to pairs
625941bea219f33f34628883
def add_route(self, uri_template, resource, **kwargs): <NEW_LINE> <INDENT> if not isinstance(uri_template, compat.string_types): <NEW_LINE> <INDENT> raise TypeError('uri_template is not a string') <NEW_LINE> <DEDENT> if not uri_template.startswith('/'): <NEW_LINE> <INDENT> raise ValueError("uri_template must start with...
Associate a templatized URI path with a resource. Falcon routes incoming requests to resources based on a set of URI templates. If the path requested by the client matches the template for a given route, the request is then passed on to the associated resource for processing. If no route matches the request, control ...
625941bebe383301e01b53a1
def run(self): <NEW_LINE> <INDENT> for scenario in self._scenarios: <NEW_LINE> <INDENT> self.scenario_start() <NEW_LINE> should_continue = None <NEW_LINE> generation_count = 0 <NEW_LINE> while should_continue is None or should_continue: <NEW_LINE> <INDENT> self._run_one_generation( scenario[SIMULATOR_CLASS], scenario[S...
Run several simulation scenarios. Using the configuration: - run first scenario until condition function is satisfied - run next scenario if there is one - use a dictionary as "simulation state" where SomObject instances can pass data from one run to the next one - the simulation state should contain score informa...
625941be26238365f5f0ed80
def get_meshfn_from_dagpath(dagpath): <NEW_LINE> <INDENT> m_dagpath = get_dagpath_from_name(dagpath) <NEW_LINE> return om.MFnMesh(m_dagpath)
return a functionset for a specified dagpath :param dagpath : input dagpath
625941beab23a570cc250096
def order_nodes(qs, **kwargs): <NEW_LINE> <INDENT> select = {} <NEW_LINE> order_by = [] <NEW_LINE> field = kwargs.get('field') <NEW_LINE> if field: <NEW_LINE> <INDENT> select['date_is_null'] = '{0} IS NULL'.format(field) <NEW_LINE> order_by.append('date_is_null') <NEW_LINE> order_by.append(field) <NEW_LINE> <DEDENT> co...
Accepts a queryset (nominally of Node objects) and sorts them by context and/or date. Similar to queryset.order_by() except more fine-grained. Accepts these argument and applies them in order: - context - field (datetime)
625941be167d2b6e31218aac
def main(): <NEW_LINE> <INDENT> gd_list = [ ['001.jpg', 1, 0, 0], ['002.jpg', 0, 1, 0], ['003.jpg', 0, 0, 1], ['004.jpg', 1, 0, 0], ['005.jpg', 1, 0, 0], ] <NEW_LINE> test_list = [ ['001.jpg', 0.5, 0.2, 0.3], ['002.jpg', 0.6, 0.2, 0.3], ['003.jpg', 0.3, 0.2, 0.3], ['004.jpg', 0.2, 0.2, 0.3], ['005.jpg', 0.9, 0.2, 0.3],...
Test Module.
625941be23849d37ff7b2fa6
def on_settings_changed(self, key, udata=None): <NEW_LINE> <INDENT> pass
Handle settings changes
625941befff4ab517eb2f350
def page_size(self): <NEW_LINE> <INDENT> return self.size(height=self.single_page_size, width=self.single_page_size, exact=True)
page size for display: :attr:`SINGLE_PAGE_SIZE` on the long edge
625941becad5886f8bd26ef0
def post(self, request: Request): <NEW_LINE> <INDENT> img = request.FILES.get('img') <NEW_LINE> url = upload(img) <NEW_LINE> context = {"img_url": url} <NEW_LINE> return Response(context)
上传图片 需要字段:img(文件类型)
625941beeab8aa0e5d26da70
def get_url(self): <NEW_LINE> <INDENT> domain = Site.objects.get_current().domain <NEW_LINE> return 'https://{}{}'.format(domain, self.get_url_path())
Return the (actual) absolute URL, with protocol & domain. https://code.djangoproject.com/wiki/ReplacingGetAbsoluteUrl
625941be66673b3332b91fa7
def imust_get_department_data_view(request): <NEW_LINE> <INDENT> ret_data = imust_get_department_data() <NEW_LINE> return success_response(ret_data)
URL[GET]:/data/imust/get_department_data/
625941bef9cc0f698b140514