code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def check_active_state_using_class(web_gui, get_value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> text_button = web_gui.find_element_by_id(get_value) <NEW_LINE> text_value = text_button.get_attribute("class") <NEW_LINE> if "deactivated" in text_value: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_L...
To check enabled state based on the class value using id :param web_gui: web driver after initializing page :type web_gui : string :param get_value : web element id for the enabled element :type get_value : string :raises Exception : If error thrown returns None :return : boolean True/False based on state :rtype : boo...
625941c6ac7a0e7691ed40e8
def send_broadcast_message(self, message, sender=SENDER): <NEW_LINE> <INDENT> message_dict = { "sender": sender, "message": message } <NEW_LINE> message = json.dumps(message_dict) <NEW_LINE> packed_header = self._pack_header(command_id=4, message=message) <NEW_LINE> self.socket.sendall(packed_header + message.encode('u...
发送群聊内容,给所有已连接服务器的hub发送指令
625941c65510c4643540f401
def _get_ann_df(self): <NEW_LINE> <INDENT> if self.data_q is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> df_ann = self.data_q.loc[:, pd.IndexSlice[:, self.ANN_DATE_FIELD_NAME]] <NEW_LINE> df_ann.columns = df_ann.columns.droplevel(level='field') <NEW_LINE> return df_ann
Query announcement date of financial statements of all securities. Returns ------- df_ann : pd.DataFrame or None Index is date, column is symbol. If no quarterly data available, return None.
625941c666656f66f7cbc1c3
def _evaluate_resource_member(self, key): <NEW_LINE> <INDENT> if isinstance(self._data[key], EvaluatedResource): <NEW_LINE> <INDENT> self._data[key] = self._data[key].resource
! @brief Run lazy evaluation on EvaluatedResource objects.
625941c6e8904600ed9f1f44
def __init__(self): <NEW_LINE> <INDENT> self._action_group = None <NEW_LINE> self._bookmarks = None <NEW_LINE> self._conf = None <NEW_LINE> self._search_entry = None <NEW_LINE> self._side_container = None <NEW_LINE> self._side_vbox = None <NEW_LINE> self._tree_view = None <NEW_LINE> self._uim_id = None <NEW_LINE> self....
Initialize a :class:`BookmarksExtension` object.
625941c65e10d32532c5ef40
def __eq__(self, o): <NEW_LINE> <INDENT> return super().__eq__(o) and self.typ == o.typ and self.key == o.key
Two Entries are equal if they have the same fields, type, and key.
625941c6566aa707497f4584
def solveNQueens(self, n): <NEW_LINE> <INDENT> self.number = n <NEW_LINE> self.ans = [] <NEW_LINE> self.solution = [0] * n <NEW_LINE> self.col_occupation = 0 <NEW_LINE> self.diagnal_left_occupation = 0 <NEW_LINE> self.diagnal_right_occupation = 0 <NEW_LINE> self.dfs(0) <NEW_LINE> return self.ans
:type n: int :rtype: List[List[str]]
625941c696565a6dacc8f6e5
def select_all_text(self, event): <NEW_LINE> <INDENT> self.frame.control.SelectAll()
Description: Selects all the text in the editor input_param: event - Select All Event input_type: Event instance
625941c67b25080760e39473
def print_report(file): <NEW_LINE> <INDENT> vowel = 'aeiou' <NEW_LINE> consonant = 'bcdfghjklmnpqrstvwxyz' <NEW_LINE> count = 0 <NEW_LINE> vowel_count = 0 <NEW_LINE> consonant_count = 0 <NEW_LINE> whitespace_count = 0 <NEW_LINE> punct_count = 0 <NEW_LINE> file_read = open(file, 'r') <NEW_LINE> for line in file_read: <N...
This function takes a file and sends an accurate report based on the total number of vowels, total number of consonants, total number of white spaces, total number of punctuation characters, total number of characters, percent of vowels, percent of consonants, percent of white spaces, and percent of punctuation charact...
625941c676e4537e8c35168b
def parse_algorithms(alg_list,weighttype,outfile,for_lib=False): <NEW_LINE> <INDENT> for i, alg in enumerate(alg_list): <NEW_LINE> <INDENT> s = parse_algorithm(alg,i, weighttype,for_lib) <NEW_LINE> outfile.write(s) <NEW_LINE> <DEDENT> return
alg_list is a list of Algorithm elements as found by the parser. Each element of the list represents an individual algorithm.
625941c6d53ae8145f87a28c
def backref_listeners(attribute, key, uselist): <NEW_LINE> <INDENT> parent_token = attribute.impl.parent_token <NEW_LINE> def _acceptable_key_err(child_state, initiator): <NEW_LINE> <INDENT> raise ValueError( "Object %s not associated with attribute of " "type %s" % (orm_util.state_str(child_state), manager_of_class(in...
Apply listeners to synchronize a two-way relationship.
625941c6091ae35668666f7a
def argument( name: str, dest: str | None = None, nargs: int = 1, transform_func: Callable | None = None, type_: Type | None = None, container_cls: Type | None = None, concat: bool = False, type_error: str = ARGUMENT_TYPE_ERROR, count_error: str = ARGUMENT_COUNT_ERROR, transform_error: str = ARGUMENT_TRANSFORM_ERROR, )...
Add argument to command. :param name: argument name :type name: :class:`str` :param dest: destination name to assign value :type dest: :class:`str` :param nargs: :class:`str` :type nargs: :class:`int` :param transform_func: function for transform value to correct type :type transform_func: :class:`Callable` :param typ...
625941c6a05bb46b383ec83c
def test_user_auth_with_wrong_name(self): <NEW_LINE> <INDENT> r = self.service_request(method='POST', path='/tokens', assert_status=401, as_json={ 'passwordCredentials': { 'username': 'this-is-completely-wrong', 'password': 'secrete'}})
Authenticating with an unknown username returns a 401
625941c64a966d76dd551028
def test_identical_functions(self): <NEW_LINE> <INDENT> reporter = SimpleReporter( pkgs=[PackageAPI(BASE_PACKAGE), PackageAPI(BASE_PACKAGE2)], errors_allowed=0 ) <NEW_LINE> reporter._check_function_args() <NEW_LINE> errors = reporter.errors <NEW_LINE> self.assertTrue(len(errors) == 0)
SimpleReporter should not create any errors if the shared function is the same in both packages.
625941c63c8af77a43ae37b9
def remove_user(self, name): <NEW_LINE> <INDENT> self.system.users.remove({"user": name}, safe=True)
Remove user `name` from this :class:`Database`. User `name` will no longer have permissions to access this :class:`Database`. :Paramaters: - `name`: the name of the user to remove
625941c65fcc89381b1e16d8
def toolIP2DSpcNegDetailedTrackGradeFactory(name, useBTagFlagsDefaults = True, **options): <NEW_LINE> <INDENT> if useBTagFlagsDefaults: <NEW_LINE> <INDENT> defaults = { 'OutputLevel' : BTaggingFlags.OutputLevel, 'TrackSummaryTool' : None, 'useSharedHitInfo' : True, 'useDetailSharedHitInfo' : True...
Sets up a IP2DSpcNegDetailedTrackGradeFactory tool and returns it. The following options have BTaggingFlags defaults: OutputLevel default: BTaggingFlags.OutputLevel TrackSummaryTool default: None useSharedHitInfo default: True useDetailSharedHitInfo ...
625941c645492302aab5e2dc
def _text_changed(self, text): <NEW_LINE> <INDENT> if not self.hasFocus(): <NEW_LINE> <INDENT> self._before = text
Reset 'before' value when changing via Python
625941c6d99f1b3c44c675aa
def digits(x): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> float(x) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return numpy.nan <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return numpy.nan <NEW_LINE> <DEDENT> x = numpy.absolute(x) <NEW_LINE> return int(numpy.math.ceil(numpy.math.log10(x))...
Returns amount of digits of x.
625941c671ff763f4b5496a3
def p_factor2(p): <NEW_LINE> <INDENT> p[0] = factor2(Number(p[1]),"factor2")
factor : NUMBER
625941c6656771135c3eb887
def collect(verbose=True): <NEW_LINE> <INDENT> return self.collect(verbose=verbose)
Collect static from blueprints.
625941c6b545ff76a8913e30
def test_remove_html_tags_attr(self): <NEW_LINE> <INDENT> self.assertEqual(tokenize_v2( '<a href="https://google.com">hello</a>'), ['hello']) <NEW_LINE> self.assertEqual(tokenize_v2( '<a href="https://google.com" rel="nofollow" >hello</a>'), ['hello'])
Test for removing html tags with attributes.
625941c6d4950a0f3b08c36a
def get_store(self, key): <NEW_LINE> <INDENT> return self._ceph_get_store(key)
Retrieve the value of a persistent KV store entry :param key: String :return: Byte string or None
625941c6d6c5a10208144064
def _merge_dict(origin, override): <NEW_LINE> <INDENT> if isinstance(origin, dict) and isinstance(override, dict): <NEW_LINE> <INDENT> for k, v in six.iteritems(override): <NEW_LINE> <INDENT> if k in origin: <NEW_LINE> <INDENT> origin[k] = _merge_dict(origin[k], override[k]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Merge simple dict recursively. If the node is non-dict, return itself, otherwise recurse down for each item.
625941c6be383301e01b54a2
@app.route("/thanks") <NEW_LINE> def say_thanks(): <NEW_LINE> <INDENT> return render_template("thanks.html")
Thank user for buying a book.
625941c6379a373c97cfab5e
def parse_request_args(list_of_args, req=None, strict=False): <NEW_LINE> <INDENT> if "application/json" != request.mimetype: <NEW_LINE> <INDENT> raise NotAcceptable(description="Request must have Content-Type: application/json") <NEW_LINE> <DEDENT> parser = flask_restful.reqparse.RequestParser(namespace_class=dict, bun...
Parses the arguments given. :param list_of_args: List of arguments :param req: The request context (defaults to flask.request) :param strict: Should all parameters be present? :type list_of_args list[flask_restful.reqparse.Argument] :type req flask.request :type strict bool :return: The dictionary containing the arg...
625941c66fb2d068a760f0b6
def retain_layer(self, layername, detach=None, retain_grad=None, clone=None): <NEW_LINE> <INDENT> self.retain_layers([layername], detach=detach, retain_grad=retain_grad, clone=clone)
Pass a fully-qualified layer name (E.g., module.submodule.conv3) to hook that layer and retain its output each time the model is run. A pair (layername, aka) can be provided, and the aka will be used as the key for the retained value instead of the layername.
625941c67b25080760e39474
def tos(self, m="fract", scale=False): <NEW_LINE> <INDENT> def rescale(vec): <NEW_LINE> <INDENT> if not scale: return vec <NEW_LINE> vec = np.array(vec) <NEW_LINE> abs_dens = np.abs(np.array([v for v in vec if v != 0.0])) <NEW_LINE> if len(abs_dens) == 0: return vec <NEW_LINE> d = min(v for v in abs_dens if v != 0) <NE...
Return string with fractional or cartesian coords depending on mode `m` in ("fract", "cart", "fracart")
625941c630c21e258bdfa4b6
def start_heartbeat_thread() -> None: <NEW_LINE> <INDENT> config = HealthCheckConfig() <NEW_LINE> thread = Thread(target=emit_heartbeats, args=(config, mq_connector)) <NEW_LINE> thread.setDaemon(True) <NEW_LINE> thread.start()
Configures and startes background thead for emiting liveness signs.
625941c60a50d4780f666eab
def get_date(self): <NEW_LINE> <INDENT> date = self.metadata['date'] <NEW_LINE> return date
return date unformatted from metadata-table
625941c631939e2706e4ce86
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.full_clean() <NEW_LINE> try: <NEW_LINE> <INDENT> super().save(*args, **kwargs) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._save_initial_asset_status()
Validate either asset code, serial number are provided and an existing status is given
625941c6f548e778e58cd597
@gateway.command() <NEW_LINE> @click.pass_context <NEW_LINE> @click.argument('host', nargs=1) <NEW_LINE> def enable(ctx, host): <NEW_LINE> <INDENT> state(ctx, host, True)
enable a gateway. Args: ctx (Context): Click context host (str): Gateway IP address
625941c6596a897236089adc
def get(): <NEW_LINE> <INDENT> session.forget(response) <NEW_LINE> if request.vars.id: <NEW_LINE> <INDENT> row=db(db.orig_to_short.id==request.vars.id).select(db.orig_to_short.originalurl).first() <NEW_LINE> if row: <NEW_LINE> <INDENT> redirect(row.originalurl)
get original url by id
625941c6a934411ee37516ae
def create_netcdf(nc_name, image, template, start_dt, channel, source, sat_name): <NEW_LINE> <INDENT> nc_name = os.path.abspath(nc_name) <NEW_LINE> template = os.path.abspath(template) <NEW_LINE> if not os.path.exists(template): <NEW_LINE> <INDENT> log.error("Template does not exist %s" % template) <NEW_LINE> raise Val...
Copy a template file to destination and fill it with the provided image data. WARNING: Timing information is not added
625941c6b545ff76a8913e31
def insertion_policy(workflow): <NEW_LINE> <INDENT> makespan = 0 <NEW_LINE> sorted_tasks = workflow.sort_tasks('rank') <NEW_LINE> solution = Solution(workflow.env.machines) <NEW_LINE> for task in sorted_tasks: <NEW_LINE> <INDENT> if task == list(sorted_tasks)[0]: <NEW_LINE> <INDENT> m, w = min( task.calculated_runtime....
Allocate tasks to machines following the insertion based policy outline in Tocuoglu et al.(2002)
625941c60c0af96317bb8202
def test_init_with_iter(): <NEW_LINE> <INDENT> from src.bst import BinTree <NEW_LINE> new_tree = BinTree([3, 2, 1, 4, 5]) <NEW_LINE> assert new_tree._root.val == 3 <NEW_LINE> assert new_tree._root.left.val == 2 <NEW_LINE> assert new_tree._root.right.val == 4 <NEW_LINE> assert new_tree._root.left.left.val == 1 <NEW_LINE...
Test to see if instantiating with an iterable works.
625941c632920d7e50b281e9
def agregarizq(self, elemento): <NEW_LINE> <INDENT> self.izq = elemento
genera un hijo del lado izquierdo :param elemento: nodo :return:
625941c6f8510a7c17cf9716
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chapel.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure ...
Run administrative tasks.
625941c68c0ade5d55d3e9d4
def surface_3D(x, y, z, tooltips=None, axes_names=['x','y','z'], log_axes=(False,False,False)): <NEW_LINE> <INDENT> data = [go.Surface( x=x, y=y, z=z, text=tooltips, colorscale='Viridis', opacity=1 )] <NEW_LINE> layout = go.Layout( title='3D surface', autosize=False, width=900, height=600, margin=dict(l=0, r=0, b=0, t=...
plot a 3D surface using plotly Parameters should be of the form: ``` X = np.arange(...) Y = np.arange(...) X, Y = np.meshgrid(X, Y) Z = f(X,Y) ``` Args: tooltips: an array with the same length as the number of points, containing a string to display beside them log_axes: whether the `x,y,z` axes should...
625941c6d486a94d0b98e160
def main(): <NEW_LINE> <INDENT> for i in input(): <NEW_LINE> <INDENT> if i == ' ': <NEW_LINE> <INDENT> print() <NEW_LINE> <DEDENT> elif 'A' <= i <= 'Z': <NEW_LINE> <INDENT> print('*' * (ord(i)-ord('A')+1)) <NEW_LINE> <DEDENT> elif 'a' <= i <= 'z': <NEW_LINE> <INDENT> print('*' * (ord(i)-ord('a')+1))
Main function
625941c6287bf620b61d3a7f
def _func_cmp(func1, func2): <NEW_LINE> <INDENT> if func1 == func2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if func1 == _empty_func: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif func2 == _empty_func: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for ann1, ann2 in zip(*[_get_annotations(f...
Compares two functions by their signatures. Arguments: func1, func2: Functions that are supported by inspect.signature. Both must have same number of arguments. Returns: True if func1's argument annotation types have stronger or as strong types than func2's ones. False else.
625941c630dc7b7665901982
def __init__(self, api_version=None, kind=None, name=None, uid=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration.get_default_copy() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_...
V1BoundObjectReference - a model defined in OpenAPI
625941c64428ac0f6e5ba80c
def utterance_remainder(self): <NEW_LINE> <INDENT> utt = self.data.get("utterance", None) <NEW_LINE> if utt and "__tags__" in self.data: <NEW_LINE> <INDENT> for token in self.data["__tags__"]: <NEW_LINE> <INDENT> utt = utt.replace(token["key"], "") <NEW_LINE> <DEDENT> <DEDENT> return normalize(utt)
For intents get the portion not consumed by Adapt. For example: if they say 'Turn on the family room light' and there are entity matches for "turn on" and "light", then it will leave behind " the family room " which is then normalized to "family room". Returns: str: Leftover words or None if not an utterance.
625941c6442bda511e8be434
def activateAlarm(self, zones=None): <NEW_LINE> <INDENT> if zones is not None: <NEW_LINE> <INDENT> if type(zones) == str: <NEW_LINE> <INDENT> zones = [zones] <NEW_LINE> <DEDENT> self.setSensorsZone(zones) <NEW_LINE> <DEDENT> self.settings['settings']['alarmState'] = "armed" <NEW_LINE> for sensor, sensorvalue in self.se...
Activates the alarm
625941c6ec188e330fd5a7bc
def loadData(self): <NEW_LINE> <INDENT> if self.filePath.endswith(".png"): <NEW_LINE> <INDENT> print ("png files not yet supported") <NEW_LINE> return None <NEW_LINE> <DEDENT> elif self.filePath.endswith(".txt"): <NEW_LINE> <INDENT> print ("Loading .txt") <NEW_LINE> data = np.loadtxt(self.filePath) <NEW_LINE> <DEDENT> ...
Loads the data This looks at the file extension and loads it appropiately
625941c67d43ff24873a2cba
@register_translation <NEW_LINE> def translate_sqrty_to_ty(gate: SqrtY) -> Iterator[YPow]: <NEW_LINE> <INDENT> (q0,) = gate.qubits <NEW_LINE> yield YPow(0.5, q0)
Translate sqrt-Y gate to YPow
625941c60a50d4780f666eac
def onNegotiateSession(username, host, port, accepted): <NEW_LINE> <INDENT> pass
Callback method for incoming requests to start a peer-to-peer session. The username, host, and port of the requesting peer is provided as input.
625941c694891a1f4081bac3
def test_choice_stringify(self): <NEW_LINE> <INDENT> choice = Choice(choice_text="This is a choice") <NEW_LINE> self.assertEqual(repr(choice), "<Choice: This is a choice>") <NEW_LINE> self.assertEqual(str(choice), "This is a choice")
Ensure the choice stringifies properly there's nothing else on this model class to test..
625941c60383005118ecf5fe
def test_basics_c(self): <NEW_LINE> <INDENT> self.do_basics( _crc8 )
Test basic functionality of the extension module.
625941c6009cb60464c633cd
def __contains__(self, session): <NEW_LINE> <INDENT> return session in self.sessions
A session is considered to exist if the current user attached to the session matches. In SMC, an administrative account must be unique even if it only exists in a specific domain. :rtype: bool
625941c63eb6a72ae02ec4f4
def multiply(self, A, B): <NEW_LINE> <INDENT> n, m, l = len(A), len(A[0]), len(B[0]) <NEW_LINE> if m != len(B): <NEW_LINE> <INDENT> raise Exception("Len of A, B not valid") <NEW_LINE> <DEDENT> C = [[0 for _ in range(l)] for _ in range(n)] <NEW_LINE> for i,row in enumerate(A): <NEW_LINE> <INDENT> for j, eleA in enumerat...
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
625941c632920d7e50b281ea
def build_obs_model(self): <NEW_LINE> <INDENT> for iState in range(self.par.n): <NEW_LINE> <INDENT> self.pitchDistr.append(norm(loc=0, scale=1)) <NEW_LINE> if iState % self.par.nSPP == 2: <NEW_LINE> <INDENT> self.init = np.append(self.init, np.float64(1.0 / (self.par.nS * self.par.nPPS))) <NEW_LINE> <DEDENT> else: <NEW...
build gmms for pitch observations
625941c630c21e258bdfa4b7
def from_avro(col, topic, schema_registry_url): <NEW_LINE> <INDENT> jvm_gateway = SparkContext._active_spark_context._gateway.jvm <NEW_LINE> abris_avro = jvm_gateway.za.co.absa.abris.avro <NEW_LINE> naming_strategy = getattr( getattr(abris_avro.read.confluent.SchemaManager, "SchemaStorageNamingStrategies$"), "MODULE$" ...
avro deserialize :param col: column name "key" or "value" :param topic: kafka topic :param schema_registry_url: schema registry http address :return:
625941c6c4546d3d9de72a4d
def set_omega(self, omega): <NEW_LINE> <INDENT> self.omega = omega
Manually set rotation speed of planet (rad/s).
625941c6090684286d50ecff
def configure_optimizers(self): <NEW_LINE> <INDENT> return torch.optim.AdamW(self.parameters(), lr=self.lr)
Configure the optimizer for training.
625941c656ac1b37e62641ed
def unmute_shape_keys(self): <NEW_LINE> <INDENT> for shape in self.shape_keys_list: <NEW_LINE> <INDENT> self.obj.data.shape_keys.key_blocks[shape].mute = False <NEW_LINE> <DEDENT> self.obj.active_shape_key_index += 0
Unmute all shape keys.
625941c62c8b7c6e89b357dc
def all_s3_bucket_public_access_block_disableds_true(self): <NEW_LINE> <INDENT> del self.block_configuration["xmlns"] <NEW_LINE> for block in self.block_configuration: <NEW_LINE> <INDENT> if not self.block_configuration[block]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Iterates over blocks and checks if True.
625941c667a9b606de4a7ed6
def test_updateDefaultCollectionFor(self): <NEW_LINE> <INDENT> criterion = getCollectionLinkCriterion(self.folder) <NEW_LINE> self.assertFalse(criterion.default) <NEW_LINE> dashcoll_id = self.folder.invokeFactory('DashboardCollection', 'dashcoll', title='Dashboard Collection') <NEW_LINE> dashcoll = getattr(self.folder,...
This method will define the default collection used by the collection-link widget defined in a faceted enabled folder.
625941c67d43ff24873a2cbb
@pytest.mark.parametrize("swap_groups, expected_output", [ ([["cations"], ["anions"], ["atoms"], ["all"]], [["cations", 1.0], ["anions", 1.0], ["atoms", 1.0], ["all", 1.0]]), ([["Sr-X"], ["Ti-X"], ["O-X"]], [["Sr-X", 1.0], ["Ti-X", 1.0], ["O-X", 1.0]]), ([], []), ]) <NEW_LINE> def test_initialise_default_swap_weighting...
GIVEN a set of swap groups WHEN we call "initialise_default_swap_weightings()" THEN we return a list of weightings assigning each swap group equal probability. Parameters ---------- None Returns ------- None --------------------------------------------------------------------------- Paul Sharp 25/10/2017
625941c6a79ad161976cc160
def test_4_rotations(): <NEW_LINE> <INDENT> A = [[0,1,2], [3,4,5], [6,7,8]] <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> rotate_90(A) <NEW_LINE> <DEDENT> assert A == [[0,1,2], [3,4,5], [6,7,8]]
4 rotations should is idempotent operation
625941c657b8e32f524834b5
def __init__(self, file_path: SomeSubstitutionsType) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> ensure_argument_type( file_path, (str, Substitution, Iterable), 'file_path', 'LoadFile') <NEW_LINE> self.file_path = normalize_to_list_of_substitutions(file_path)
Create a LoadFile substitution.
625941c699fddb7c1c9de3ac
def buildTree(self, preorder, inorder): <NEW_LINE> <INDENT> if not preorder: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> root_val = preorder[0] <NEW_LINE> idx = inorder.index(root_val) <NEW_LINE> root = TreeNode(root_val) <NEW_LINE> root.left = self.buildTree(preorder[1:1+idx], inorder[:idx]) <NEW_LINE> root.ri...
:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
625941c6379a373c97cfab5f
def extract_names(filename): <NEW_LINE> <INDENT> year = re.findall(r'Popularity in (\d{4})<', filename.read()) <NEW_LINE> names_ranks = re.findall(r'>(\d+)</td><td>(\w+)</td><td>(\w+)<', filename.read()) <NEW_LINE> male_names = {} <NEW_LINE> female_names = {} <NEW_LINE> for rank, male, female in names_ranks: <NEW_LINE>...
Given a file name for baby.html, returns a list starting with the year string followed by the name-rank strings in alphabetical order. ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
625941c610dbd63aa1bd2bbf
def get_size_field(self): <NEW_LINE> <INDENT> return self.repeated_info.size_field if self.repeated_info else None
Returns the size field.
625941c65166f23b2e1a5174
def setConcurWarn(self, state: bool) -> None: <NEW_LINE> <INDENT> return
Enable concurrency warning.
625941c621a7993f00bc7d08
def load_keypair(filename): <NEW_LINE> <INDENT> with open(filename, 'rt') as f: <NEW_LINE> <INDENT> j = json.load(f) <NEW_LINE> <DEDENT> public = j['public'] <NEW_LINE> secret = j['secret'] <NEW_LINE> return (secret, '0x' + public)
Loads keypair from a file. :param str filename: File name :return: The loaded keypair :rtype: (str, str)
625941c6cdde0d52a9e5304d
def _predict(self, X): <NEW_LINE> <INDENT> return sum(map(lambda node: node.predict(X)*node.lr, self.nodes))
Predict Y values for a given X array without postprocessing results.
625941c6099cdd3c635f0c76
def problem_21(): <NEW_LINE> <INDENT> return sum(filter( lambda x: x != sum(_int.proper_divisors(x)) and x == sum(_int.proper_divisors(sum(_int.proper_divisors(x)))), range(2, 10000)))
Amicable numbers 亲和数
625941c699fddb7c1c9de3ad
def sandra_collide(self,junk): <NEW_LINE> <INDENT> if self.x < junk.x < (self.x + junk.width) and self.y < junk.y < (self.y+ junk.height): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
this function checks to see if the object Sandra collides with the space junks (specifically checking for overlapping positions)
625941c6507cdc57c6306cf3
def test_project_1(self): <NEW_LINE> <INDENT> test_project_name = "Test Project" <NEW_LINE> test_body = "Test Body" <NEW_LINE> test_project = Project(title=test_project_name, body=test_body) <NEW_LINE> test_pk_id = test_project.pk_id <NEW_LINE> with self.app.app_context(): <NEW_LINE> <INDENT> self.db.session.add(test_p...
Creates a project in the Project table, checks if stored values match intended values.
625941c60a366e3fb873e834
def validate_crt_2(): <NEW_LINE> <INDENT> X = [0] * 3 <NEW_LINE> Y = [0] * 3 <NEW_LINE> for i in range(3): <NEW_LINE> <INDENT> X[i], Y[i] = map(int, input().split()) <NEW_LINE> <DEDENT> r, m = crt(X, Y) <NEW_LINE> if m == -1: <NEW_LINE> <INDENT> print(-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(r if r > 0 e...
yukicoder No.186 https://yukicoder.me/problems/no/186
625941c62eb69b55b151c8c8
def matchandsort(component_globs, target_paths): <NEW_LINE> <INDENT> targetpath_globs, subpath_glob = split_arg_globs(component_globs) <NEW_LINE> mpcons = MTP.constructor(targetpath_globs, subpath_glob) <NEW_LINE> def notNone(x): return x is not None <NEW_LINE> return sorted(filter(notNone, map(mpcons, target_paths)))
Taking a list of component_globs (each with implied `*` at end) and list of target_paths, return a sorted list of MatchingPaths.
625941c6711fe17d82542389
def move_line_get(self, cr, uid, invoice_id, context=None): <NEW_LINE> <INDENT> res = [] <NEW_LINE> super(account_invoice_tax, self).move_line_get(cr, uid, invoice_id) <NEW_LINE> tax_invoice_ids = self.search(cr, uid, [ ('invoice_id', '=', invoice_id)], context=context) <NEW_LINE> for inv_t in self.browse(cr, uid, tax_...
Super to function, to add partner_id in dict, this to create the line corresponding to tax with the partner to this, this when the line of tax is to register cost of to broker
625941c663f4b57ef0001138
def get_storage_pool_statistics(self, protection_domain, storage_pool, props): <NEW_LINE> <INDENT> if not protection_domain: <NEW_LINE> <INDENT> raise ValueError( 'Invalid protection_domain parameter, protection_domain=%s' % protection_domain) <NEW_LINE> <DEDENT> if not storage_pool: <NEW_LINE> <INDENT> raise ValueErro...
Returns the requested statistics on a storage pool. :param: protection_domain. Name of the protection domain :param: storage_pool. Name of the storage pool :param: props. Array of property names to query :return: dict of storage pool properties
625941c67047854f462a1426
def zero_arg_urls(self): <NEW_LINE> <INDENT> F = functions.Functions() <NEW_LINE> fn_name = self.path.lstrip('/').split('/')[0].split('.')[0] <NEW_LINE> if (fn_name[0] in string.ascii_letters and any([i in string.ascii_letters + string.digits + '_' for i in fn_name]) and fn_name in F.funcs): <NEW_LINE> <INDENT> content...
If path, less '.html' is a valid function name, then check functions.Functions; if found there, run it as a function.
625941c697e22403b379cfb5
def GetServiceCommands(self, serviceName=''): <NEW_LINE> <INDENT> return self.generateAPIRequest(OrderedDict([('method_name', 'GetServiceCommands'), ('serviceName', serviceName)]))
Retrieves driver commands and parameters for a specified service. :param str serviceName: Specify the service name. :rtype: ResourceCommandListInfo
625941c6dc8b845886cb554f
def averageOfLevels(self, root): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> levelnode = deque([]) <NEW_LINE> levelnode.append(root) <NEW_LINE> while levelnode: <NEW_LINE> <INDENT> length = len(levelnode) <NEW_LINE> levelsum = 0 <NEW_LINE> for _ in range(length...
:type root: TreeNode :rtype: List[float]
625941c6cad5886f8bd26ff5
def __gt__(self, other): <NEW_LINE> <INDENT> if self.x == other.x: <NEW_LINE> <INDENT> if self.y > other.y: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> elif self.x > other.x: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Defines the > operator for Point objects. Two Points p and q satisfy p > q if and only if p.x > q.x or p.x == q.x and p.y > q.y.
625941c64c3428357757c344
def setToken(self, loadtoken): <NEW_LINE> <INDENT> log.debug( "Force setting of private token. Not using the wallet database!") <NEW_LINE> self.clear_local_token() <NEW_LINE> if isinstance(loadtoken, dict): <NEW_LINE> <INDENT> Wallet.token = loadtoken <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("toke...
This method is strictly only for in memory token that are passed to Wallet/Morphene with the ``token`` argument
625941c656b00c62f0f14674
def stepDenoisedCurrent_old(self, state, action): <NEW_LINE> <INDENT> assert state.ndim == 3 and action.ndim == 2 <NEW_LINE> action = np.clip(action, self.min_action, self.max_action / 2)[:, :, np.newaxis] <NEW_LINE> u = action * self.putter_length <NEW_LINE> deceleration = 5 / 7 * self.friction * 9.81 <NEW_LINE> t = u...
Computes steps without noise.
625941c62eb69b55b151c8c9
def random_crop_and_pad_image_and_labels(image, labels, size): <NEW_LINE> <INDENT> combined = tf.concat([image, labels], axis=2) <NEW_LINE> image_shape = tf.shape(image) <NEW_LINE> combined_pad = tf.image.pad_to_bounding_box( combined, 0, 0, tf.maximum(size[0], image_shape[0]), tf.maximum(size[1], image_shape[1])) <NEW...
Randomly crops `image` together with `labels`. Args: image: A Tensor with shape [D_1, ..., D_K, N] labels: A Tensor with shape [D_1, ..., D_K, M] size: A Tensor with shape [K] indicating the crop size. Returns: cropped_image, cropped_label
625941c6293b9510aa2c32b3
def recv_msg(sock): <NEW_LINE> <INDENT> raw_msglen = recvall(sock, 4) <NEW_LINE> if not raw_msglen: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> msglen = struct.unpack('>I', raw_msglen)[0] <NEW_LINE> return pickle.loads(recvall(sock, msglen))
Receive the message.
625941c624f1403a92600b83
def identify_nominal_columns(data: pd.DataFrame, include=['object', 'category']): <NEW_LINE> <INDENT> nominal_columns = list(data.select_dtypes(include=include).columns) <NEW_LINE> return nominal_columns
Given a dataset, identify categorical columns. Parameters: ----------- dataset : a pandas dataframe include : which column types to filter by; default: ['object', 'category']) Returns: -------- categorical_columns : a list of categorical columns Example: -------- >> df = pd.DataFrame({'col1': ['a', 'b', 'c', 'a'], '...
625941c65fcc89381b1e16d9
def knn_learn(nneighbors=1, data_train=np.array([]), target_train=np.array([]), data_test=np.array([])): <NEW_LINE> <INDENT> clf = ngb.KNeighborsClassifier(nneighbors).fit(data_train, target_train) <NEW_LINE> targets = clf.predict(data_test) <NEW_LINE> return targets
estimate position using the K neareast neighbors (KNN) technique Parameters ---------- nneighbors : int default = 1 data_train : numpy.ndarray default = array([]) target_train : numpy.ndarray default = array([]) data_test : numpy.ndarray default = array([]) Returns ------- targets : numpy.ndarray
625941c696565a6dacc8f6e7
def test_retrieve_subset_ordered_asc_in(self): <NEW_LINE> <INDENT> model_filter_in = ModelFilter(ModelFacadeMessage.message, ["Hello world 2", "Hello world 3"], ModelFilter.IN) <NEW_LINE> model_sort = ModelSort(ModelFacadeMessage.message, ModelSort.ASC) <NEW_LINE> records = self.model_facade.get_records_paged(1, 2, fil...
This test case ensures a subset of records is retrieved correctly when order expression and in filter are specified.
625941c6bde94217f3682e0d
def cross_replica_mean(t, num_shards_per_group=None): <NEW_LINE> <INDENT> num_shards = tpu_function.get_tpu_context().number_of_shards <NEW_LINE> if not num_shards: <NEW_LINE> <INDENT> return t <NEW_LINE> <DEDENT> if not num_shards_per_group: <NEW_LINE> <INDENT> return tf.tpu.cross_replica_sum(t) / tf.cast(num_shards, ...
Calculates the average value of input tensor across TPU replicas.
625941c6462c4b4f79d1d6ec
def _parse_cidict(self, cidict): <NEW_LINE> <INDENT> if not isinstance(cidict, dict): <NEW_LINE> <INDENT> raise TypeError('expected dict, got {}'.format(type(cidict).__name__)) <NEW_LINE> <DEDENT> self._cidict = cidict <NEW_LINE> self._pipeline_various_tweaks() <NEW_LINE> self._job_scan_apply_stages() <NEW_LINE> self._...
Fill missing but deductable information into the *cidict* and store it in self.
625941c66e29344779a6262f
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x....
serialize message into buffer :param buff: buffer, ``StringIO``
625941c623e79379d52ee581
def load_objects(d): <NEW_LINE> <INDENT> session.add_all(db_load(d, Base.classes()))
Load all objects from a dictionary d.
625941c6ec188e330fd5a7bd
def reverse(x): <NEW_LINE> <INDENT> if x > 0: <NEW_LINE> <INDENT> x = int(str(x)[::-1]) <NEW_LINE> <DEDENT> if x < 0: <NEW_LINE> <INDENT> x = -1 * int(str(x * (-1))[::-1]) <NEW_LINE> <DEDENT> if (x > pow(2, 31) - 1) or (x < -1 * pow(2, 31)): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return x
:type x: int :rtype: int
625941c61f037a2d8b94621a
def update_borrower_info_step2(self, req, form): <NEW_LINE> <INDENT> argd = wash_urlargd(form, {'borrower_id': (int, None), 'name': (str, ''), 'email': (str, ''), 'phone': (str, ''), 'address': (str, ''), 'mailbox': (str, ''), 'ln': (str, "en")}) <NEW_LINE> name = argd['name'] <NEW_LINE> email = argd['email'] <NEW_LINE...
http://cds.cern.ch/admin2/bibcirculation/update_borrower_info_step2
625941c6cc40096d6159596c
def __init__(self, systemtray_icon=None, parent=None): <NEW_LINE> <INDENT> super(Window, self).__init__(parent) <NEW_LINE> self.systemtray_icon = systemtray_icon <NEW_LINE> self.statusBar() <NEW_LINE> self.widget = MainWidget(self) <NEW_LINE> self.setCentralWidget(self.widget) <NEW_LINE> self.resize(500, 200) <NEW_LINE...
Init window.
625941c626238365f5f0ee88
def get_free_number(min_nr, max_nr, nr_list, nr_sorted=False): <NEW_LINE> <INDENT> if not nr_sorted: <NEW_LINE> <INDENT> nr_list = sorted(nr_list) <NEW_LINE> <DEDENT> free_nr = -1 <NEW_LINE> if min_nr >= 0 and min_nr <= max_nr: <NEW_LINE> <INDENT> nr_list_length = len(nr_list) <NEW_LINE> index = 0 <NEW_LINE> number = m...
Returns the first number in the range min_nr..max_nr that is not in nr_list In the range min_nr to max_nr, finds and returns a number that is not in the supplied list of numbers. min_nr and max_nr must be >= 0, and nr_list must be a list of integer numbers @param min_nr: range start, >= 0 @param max_nr: range e...
625941c6e64d504609d7485b
def verify(wheelfile): <NEW_LINE> <INDENT> warn_signatures() <NEW_LINE> wf = WheelFile(wheelfile) <NEW_LINE> sig_name = wf.distinfo_name + '/RECORD.jws' <NEW_LINE> try: <NEW_LINE> <INDENT> sig = json.loads(native(wf.zipfile.open(sig_name).read())) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise WheelErro...
Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents.
625941c6adb09d7d5db6c7ac
def test_aline_delta(self): <NEW_LINE> <INDENT> result = aline.delta('p', 'q') <NEW_LINE> expected = 20.0 <NEW_LINE> self.assertEqual(result, expected) <NEW_LINE> result = aline.delta('a', 'A') <NEW_LINE> expected = 0.0 <NEW_LINE> self.assertEqual(result, expected)
Test aline for computing the difference between two segments
625941c6bd1bec0571d9064b
def get_hil_reservations(): <NEW_LINE> <INDENT> resdata_dict_list = [] <NEW_LINE> resdata_dict_list, stdout_data, stderr_data = exec_scontrol_show_cmd('reservation', None) <NEW_LINE> for resdata_dict in resdata_dict_list: <NEW_LINE> <INDENT> if resdata_dict and is_hil_reservation(resdata_dict['ReservationName'], None):...
Get a list of all Slurm reservations, return that subset which are HIL reservations
625941c6090684286d50ed00
def GetData(transaction_attr): <NEW_LINE> <INDENT> pass
:param transaction_attr:
625941c67d847024c06be2d6
def get(self, key): <NEW_LINE> <INDENT> return self.doc[key]
Return the data of given key :param key: The property name :type key: string
625941c6a05bb46b383ec83f
def encode(self, longUrl): <NEW_LINE> <INDENT> self.db[self.id]=longUrl <NEW_LINE> surl = 'http://tinyurl.com/'+self.__base__(self.id) <NEW_LINE> self.id+=1 <NEW_LINE> return surl
Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
625941c673bcbd0ca4b2c092
def test(self): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for func in self.configurations(): <NEW_LINE> <INDENT> model = func() <NEW_LINE> start = time() <NEW_LINE> model.fit(self.set.train_feat, self.set.train_labl) <NEW_LINE> fit_end = time() <NEW_LINE> predicted = self.predict_classic(model) <NEW_LINE> predict_end...
Run the algorithm and return the accuracy of its predictions
625941c626068e7796caecf9
def estimar_lineas(self, txt, ancho_linea): <NEW_LINE> <INDENT> lineas_fisicas = 0 <NEW_LINE> for linea_logica in txt.split("\n"): <NEW_LINE> <INDENT> lineas_fisicas += len(linea_logica)//ancho_linea + 1 <NEW_LINE> <DEDENT> return lineas_fisicas
Estima cuántas líneas de papel puede utilizar el texto dado, contando cuántas líneas lógicas tiene y asumiendo que en cada línea física caben `ancho_linea` caracteres.
625941c682261d6c526ab4b9