code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def mutate(self) -> None: <NEW_LINE> <INDENT> mutable_nodes = [] <NEW_LINE> for node in self.nodes: <NEW_LINE> <INDENT> if not node.input_nodes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> mutable_nodes.append(node) <NEW_LINE> <DEDENT> node = random.choice(mutable_nodes) <NEW_LINE> num_inputs = node.num_inputs <NE... | Mutate the bot. | 625941c2e5267d203edcdc31 |
def items_equal(left, right): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return sorted(left) == sorted(right) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False | Returns `True` if items in `left` list are equal to items in
`right` list. | 625941c291af0d3eaac9b9a8 |
def get_integration_specific_email(provider): <NEW_LINE> <INDENT> return getattr(provider, 'integration_specific_email', None) or constants.DEFAULT_CONTACT_EMAIL | Return the edX contact email to use for a particular provider. | 625941c27c178a314d6ef3ee |
def parsePair(self, fA, fB): <NEW_LINE> <INDENT> currFileA = list(csv.reader(open(fA, 'rb'), delimiter='\t')) <NEW_LINE> currFileB = list(csv.reader(open(fB, 'rb'), delimiter='\t')) <NEW_LINE> if self.areVersions(currFileA, currFileB): <NEW_LINE> <INDENT> self.addVersion(fA, fB) <NEW_LINE> self.addVersion(fB, fA) | Parses a pair of files in the stats dir | 625941c266656f66f7cbc13c |
def test_section_rubric_valid(self): <NEW_LINE> <INDENT> rI = baker.make("RubricItem") <NEW_LINE> rI2 = baker.make("RubricItem") <NEW_LINE> f = SectionRubricForm({ 'rI'+str(rI.pk): RUBRIC_GRADES_CHOICES[0][0], 'rI'+str(rI2.pk): RUBRIC_GRADES_CHOICES[1][0], 'section_comment':"You did a good job examining ways to improve... | Tests that SectionRubricForm accepts valid data | 625941c29c8ee82313fbb706 |
def response_for_user_customer(user_customer): <NEW_LINE> <INDENT> return make_response(jsonify({ 'status': 'success', 'customer': user_customer })) | Return the response for when a single customer when requested by the user.
:param user_customer:
:return: | 625941c28e7ae83300e4af5e |
def access_group_initiator_delete(self, access_group, init_id, init_type, flags=0): <NEW_LINE> <INDENT> raise LsmError(ErrorNumber.NO_SUPPORT, "Not supported") | Deletes an initiator from an access group, Raises LsmError on error | 625941c26fb2d068a760f02d |
def test_real_command(self): <NEW_LINE> <INDENT> exit_code = man.run_command([], ['cd']) <NEW_LINE> self.assertEqual(exit_code, 0) | man cd | 625941c24428ac0f6e5ba783 |
def test_submit_results_for_run(self): <NEW_LINE> <INDENT> user = self.F.UserFactory.create( username="foo", permissions=["execution.execute"], ) <NEW_LINE> apikey = self.F.ApiKeyFactory.create(owner=user) <NEW_LINE> envs = self.F.EnvironmentFactory.create_full_set( {"OS": ["OS X", "Linux"]}) <NEW_LINE> pv = self.F.Pro... | Submit results for an existing test run. | 625941c28a349b6b435e8105 |
def __init__(self, base_preprocessor): <NEW_LINE> <INDENT> super(MAMLPreprocessorV2, self).__init__() <NEW_LINE> self._base_preprocessor = base_preprocessor | Construct a Meta-learning feature/label Preprocessor.
Used in conjunction with MetaInputGenerator. Takes a normal preprocessor's
expected inputs and wraps its outputs into meta TensorSpecs for
meta-learning algorithms.
Args:
base_preprocessor: An instance of the base preprocessor class to convert
into Train... | 625941c226238365f5f0edfd |
def threeSumClosest(self, nums, target): <NEW_LINE> <INDENT> ans = float('inf') <NEW_LINE> nums = sorted( nums ) <NEW_LINE> for i in range(len(nums) - 2): <NEW_LINE> <INDENT> p, q = i+1, len(nums) - 1 <NEW_LINE> while p < q: <NEW_LINE> <INDENT> temp = nums[i] + nums[p] + nums[q] <NEW_LINE> if abs( temp - target ) < abs... | :type nums: List[int]
:type target: int
:rtype: int | 625941c2aad79263cf3909d0 |
def reset(): <NEW_LINE> <INDENT> global _SUCCESSORS <NEW_LINE> _INCACHE.clear() <NEW_LINE> _MERGED.clear() <NEW_LINE> _SUCCESSORS = weakref.WeakKeyDictionary() <NEW_LINE> _FSUCC.clear() <NEW_LINE> _MATCHED_FINDINGS.clear() | Deletes the content of all the global data structures of the module,
allowing a fresh restart of every reasoning operations. | 625941c285dfad0860c3adec |
def convert_assets(assets, args, srcdir=None): <NEW_LINE> <INDENT> if srcdir is None: <NEW_LINE> <INDENT> srcdir = acquire_conversion_source_dir() <NEW_LINE> <DEDENT> testfile = 'data/empires2_x1_p1.dat' <NEW_LINE> if not srcdir.joinpath(testfile).is_file(): <NEW_LINE> <INDENT> print("file not found: " + testfile) <NEW... | Perform asset conversion.
Requires original assets and stores them in usable and free formats.
assets must be a filesystem-like object pointing at the game's asset dir.
sourceidr must be None, or point at some source directory.
If gen_extra_files is True, some more files, mostly for debugging purposes,
are created.
... | 625941c2fb3f5b602dac3623 |
def compute_gradient_error(x, x_shape, y, y_shape, x_init_value=None, delta=1e-3, init_targets=None): <NEW_LINE> <INDENT> grad = compute_gradient(x, x_shape, y, y_shape, x_init_value, delta, init_targets) <NEW_LINE> if isinstance(grad, tuple): <NEW_LINE> <INDENT> grad = [grad] <NEW_LINE> <DEDENT> return max(np.fabs(j_t... | Computes the gradient error.
Computes the maximum error for dy/dx between the computed Jacobian and the
numerically estimated Jacobian.
This function will modify the tensors passed in as it adds more operations
and hence changing the consumers of the operations of the input tensors.
This function adds operations to ... | 625941c2a4f1c619b28affd0 |
def test_future_question(self): <NEW_LINE> <INDENT> future_question = create_question(question_text='Future question.', days=5) <NEW_LINE> url = reverse('polls:detail', args=(future_question.id,)) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 404) | Questions with a pub_date in the future aren't displayed on
the index page. | 625941c24527f215b584c3ec |
def test_get_log_info(self): <NEW_LINE> <INDENT> self.classifier._entity_log_sources.append('unit_test_simple_log') <NEW_LINE> logs = self.classifier.get_log_info_for_source() <NEW_LINE> assert_list_equal(logs.keys(), ['unit_test_simple_log']) | StreamClassifier - Load Log Info for Source | 625941c28e05c05ec3eea305 |
def set_is_entanglement(self, entanglement): <NEW_LINE> <INDENT> self._is_entanglement = entanglement | Makes tile to be or not in entanglement | 625941c2099cdd3c635f0bee |
def __init__(self, ssh_host: ConnectionParts = None, ssh_gateway: ConnectionParts = None, autoconnect: bool = False): <NEW_LINE> <INDENT> self._connection = None <NEW_LINE> self._localhost_name = gethostname() <NEW_LINE> self._ssh_host = None <NEW_LINE> self._ssh_gateway = None <NEW_LINE> self.logger = _LOGGER <NEW_LIN... | Apply argued ssh connection arguments. Setup connection if specified.
Keyword Arguments:
ssh_host -- the ssh_host connection info
ssh_gateway -- the ssh_gateway connection info
autoconnect -- If True, try to connect to the remote host | 625941c27b180e01f3dc4793 |
def add_attachments(self,url,attachments,descriptions=None): <NEW_LINE> <INDENT> page = self.wiki_page_from_url(url) <NEW_LINE> if isinstance(attachments,basestring): <NEW_LINE> <INDENT> attachments = [attachments] <NEW_LINE> <DEDENT> default_desc='automated upload' <NEW_LINE> if descriptions is None: <NEW_LINE> <INDEN... | Attach files to wiki page at the given url. | 625941c2498bea3a759b9a42 |
def __init__(self, hass, values, invert_buttons): <NEW_LINE> <INDENT> ZWaveDeviceEntity.__init__(self, values, DOMAIN) <NEW_LINE> self._network = hass.data[zwave.ZWAVE_NETWORK] <NEW_LINE> self._open_id = None <NEW_LINE> self._close_id = None <NEW_LINE> self._current_position = None <NEW_LINE> self._invert_buttons = inv... | Initialize the zwave rollershutter. | 625941c27b180e01f3dc4794 |
def hist(a, bins): <NEW_LINE> <INDENT> n = searchsorted(sort(a), bins) <NEW_LINE> n = concatenate([n, [len(a)]]) <NEW_LINE> n = array(list(map(float, n))) <NEW_LINE> return n[1:] - n[:-1] | Histogram of 'a' defined on the bin grid 'bins'
Usage: h=hist(p,xp) | 625941c207f4c71912b11413 |
def terminal_length(self, n='0'): <NEW_LINE> <INDENT> if self._terminal_length_value: <NEW_LINE> <INDENT> if self._terminal_length_value != int(n): <NEW_LINE> <INDENT> self._terminal_length_value = int(n) <NEW_LINE> return self._terminal_length(n) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._terminal_le... | Sets terminal length of shell | 625941c2566aa707497f44fe |
def test_locate_on_shard(self): <NEW_LINE> <INDENT> nb_obj_to_add = 10 <NEW_LINE> self._create(self.cname) <NEW_LINE> self._add_objects(self.cname, nb_obj_to_add) <NEW_LINE> obj_id_s1 = random.randrange(nb_obj_to_add // 2) <NEW_LINE> obj_name_s1 = 'content_' + str(obj_id_s1) <NEW_LINE> _, chunks_s1 = self.storage.objec... | Check the locate command directly on the shard (with account and cname
of the shard). | 625941c28a43f66fc4b53ff9 |
def rbegin(self) -> "std::vector< double >::reverse_iterator": <NEW_LINE> <INDENT> return _moduleconnectorwrapper.DoubleVector_rbegin(self) | rbegin(DoubleVector self) -> std::vector< double >::reverse_iterator | 625941c27cff6e4e81117918 |
def _print_rg_cov(rghat, fh, log): <NEW_LINE> <INDENT> _print_cov(rghat.hsq1, fh + '.hsq1.cov', log) <NEW_LINE> _print_cov(rghat.hsq2, fh + '.hsq2.cov', log) <NEW_LINE> _print_cov(rghat.gencov, fh + '.gencov.cov', log) | Print covariance matrix of estimates. | 625941c23539df3088e2e2dd |
def prepare_data(self): <NEW_LINE> <INDENT> self.data = np.load(self.name) <NEW_LINE> self.x, self.y = self.data['x'], self.data['y'] <NEW_LINE> self.x_uncal = self.data['x_uncal'] <NEW_LINE> self.nfo = self.data['info'].tolist() <NEW_LINE> self.tstart = self.data['starttime'] <NEW_LINE> self.tstop = self.tstart + self... | Loads the data from the npz file into np.arrays
This initialized: self.data, self.x, self.y, self.nfo
self.tstart, self.tstop, and self.deadtime | 625941c29b70327d1c4e0d66 |
def createTree(nodeList, node): <NEW_LINE> <INDENT> if len(nodeList) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if nodeList[0] == '!': <NEW_LINE> <INDENT> return nodeList[1:] <NEW_LINE> <DEDENT> splitAtt, splitVal, value = nodeList[0].strip().split('-') <NEW_LINE> nodeList = nodeList[1:] <NEW_LINE> if splitAt... | Given the csv file containing the tree in DFS traversal, it returns it as a list.
:param nodeList: list of nodes in the tree in DFS traversal order
:param node: Root node of the tree
:return: remaining nodes in list of nodes in the tree in DFS traversal order | 625941c29b70327d1c4e0d67 |
def test_sysan_sanitization(self): <NEW_LINE> <INDENT> a = models.Test(str(uuid.uuid4())) <NEW_LINE> with self.g.session_scope() as s: <NEW_LINE> <INDENT> a = s.merge(a) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> a.sysan["foo"] = {"bar": "baz"} | It shouldn't be possible to set system annotations keys to
anything but primitive values. | 625941c2fbf16365ca6f6152 |
def get_df_from_table(self, table_name, **kwargs): <NEW_LINE> <INDENT> with self.engine.connect() as conn: <NEW_LINE> <INDENT> return pd.read_sql_table(table_name, conn, **kwargs) | Return a pandas DataFrame of the DB table | 625941c229b78933be1e5642 |
def test_html_output(self): <NEW_LINE> <INDENT> output = hbcal("hbcal -ih -o hebrew -fhtml --molad 1 2 5775") <NEW_LINE> self.assertEqual('יום ' + 'ראשון 30 ' + 'ניסן 5775 07:27 ו4 ' + 'חלקים', output[0]) | Test --molad option | 625941c207d97122c417881a |
def p_primary_expression_4(p): <NEW_LINE> <INDENT> p[0] = ast.StringLitExp(p[1], line_no=str(p.lineno(1) + __start_line_no - 1)) | primary_expression : SCONST_D | 625941c2796e427e537b0556 |
def can_receive(self, hostname, filename): <NEW_LINE> <INDENT> return self.socket_mgr.can_receive(hostname=hostname, filename=filename) | Determine if the load is not too much to allow receiving from another client
| 625941c21b99ca400220aa43 |
def df_traverse(tree, clique_ix=None, func=yield_id): <NEW_LINE> <INDENT> stack = [tree] <NEW_LINE> while stack: <NEW_LINE> <INDENT> tree = stack.pop() <NEW_LINE> yield from func(tree) <NEW_LINE> if tree[0] == clique_ix: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> stack.extend([child for child in revers... | Depth-first traversal with optional early termination
:param tree: tree structure in list format
:param clique_ix: clique id used to terminate traversal
:param func: function controlling component of tree output
Output: Depends on func argument. Default is list of clique ids
[id1, ..., idN] (or [id1, ..., cid]) | 625941c22eb69b55b151c83f |
def diff(self, n=1): <NEW_LINE> <INDENT> def func(value): <NEW_LINE> <INDENT> value = value.astype('float') <NEW_LINE> shifted_value = np.roll(value, n) <NEW_LINE> value = value - shifted_value <NEW_LINE> if n>=0: <NEW_LINE> <INDENT> value[:n]=np.nan <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value[n:]=np.nan <NEW_L... | Take the difference between the current value and
the nth value above it.
Parameters
----------
n: int
Returns
-------
A DataFrame | 625941c2090684286d50ec76 |
def test_get_license(): <NEW_LINE> <INDENT> licenses = pyslurm.licenses().get() <NEW_LINE> assert_true(isinstance(licenses, dict)) | License: Test licenses().get() return type | 625941c2566aa707497f44ff |
def get_element(self, elementinfo, waittime=1): <NEW_LINE> <INDENT> time.sleep(waittime) <NEW_LINE> try: <NEW_LINE> <INDENT> element = self.driver.find_element(elementinfo["type"], elementinfo["value"]) <NEW_LINE> if element == None: <NEW_LINE> <INDENT> self.lg.info("定位元素失败:%s" % elementinfo["desc"]) <NEW_LINE> self.dr... | 获取元素对象,传入元素信息返回元素
:param elementinfo:
:param waittime:
:return: | 625941c250812a4eaa59c2b6 |
def __manglePrivateMemberName(self, privateMemberName, skipCheck=False): <NEW_LINE> <INDENT> assert privateMemberName.startswith("__"), "%r doesn't start with __" % privateMemberName <NEW_LINE> assert not privateMemberName.startswith("___"), "%r starts with ___" % privateMemberName <NEW_LINE> assert... | Mangles the given mangled (private) member name; a mangled member name
is one whose name begins with two or more underscores and ends with one
or zero underscores.
privateMemberName:
The private member name (e.g., "__logger")
skipCheck: Pass True to skip test for presence of the demangled member
... | 625941c2d8ef3951e32434d0 |
def upload(): <NEW_LINE> <INDENT> rsync_project(remote_dir=env.project_path, local_dir='./', delete=True, exclude=['.git', '*.pyc', 'dist', 'build', '.scrapy']) | TODO: allow to upload via git | 625941c2d4950a0f3b08c2e3 |
def test_receiveUnimplemented(self): <NEW_LINE> <INDENT> self.proto.dispatchMessage(transport.MSG_UNIMPLEMENTED, '\x00\x00\x00\xff') <NEW_LINE> self.assertEqual(self.proto.unimplementeds, [255]) | Test that unimplemented messages are received correctly. See
test_sendUnimplemented. | 625941c2d18da76e23532466 |
def send_idle_acknowledgement(self): <NEW_LINE> <INDENT> with open(self.__stepdown_files.idle_ack, "w"): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> os.remove(self.__stepdown_files.permitted) | Signal to the running test that stepdown thread won't continue to run stepdowns. | 625941c2711fe17d82542302 |
def highlight(self): <NEW_LINE> <INDENT> self.highlighted_sprites.append(self) | placeholder method controlling highlight behaviour | 625941c22eb69b55b151c840 |
def number_of_nodes(graph, level): <NEW_LINE> <INDENT> pass | Calculates the number of nodes at given level
:param level:
:param graph: The graph
:return: Total number of nodes at given level | 625941c21d351010ab855aaf |
def average_edge(pollster_edges, pollster_errors): <NEW_LINE> <INDENT> edges = [] <NEW_LINE> weights = [] <NEW_LINE> for pollster in pollster_edges: <NEW_LINE> <INDENT> weight = pollster_to_weight(pollster, pollster_errors) <NEW_LINE> edges.append(pollster_edges[pollster]) <NEW_LINE> weights.append(weight) <NEW_LINE> <... | Given *PollsterEdges* and *PollsterErrors*, returns the average
of these *Edge*s weighted by their respective *PollsterErrors*. | 625941c2d58c6744b4257bf3 |
def ntp_request(host: str) -> Union[None, NTPResponse]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> socket.getaddrinfo(host, "ntp") <NEW_LINE> <DEDENT> except socket.gaierror as error: <NEW_LINE> <INDENT> sys.stderr.write("Cannot resolve host '{}': {}\n".format(host, error)) <NEW_LINE> sys.stderr.flush() <NEW_LINE> re... | Request NTP server host to retrieve attributes | 625941c24e4d5625662d436d |
def get_gen_val(f_map, in_val): <NEW_LINE> <INDENT> if in_val == '': <NEW_LINE> <INDENT> return f_map[''][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ind = int(in_val) <NEW_LINE> return f_map[ind][0] | Return the generalized value from the map. If the value read in is other than the empty
string, the value is cast to an integer.
:param f_map: The generalization map to be used
:param in_val: The value to be generalized; this will always come in as a string but will be
cast to an integer if it is non-empty
:return:... | 625941c2a05bb46b383ec7b6 |
def vector_matches_position_vector(self, vector): <NEW_LINE> <INDENT> matches = True <NEW_LINE> for hyperplane_index, orientation in vector: <NEW_LINE> <INDENT> if self.position_vector[hyperplane_index] == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif self.position_vector[hyperplane_index] != orientation: <N... | tests if input pos vector matches vertex position vector. For input vector not all
position have to be specified.
:param vector: list of tuples (hyperplane_index, orientation)
:return: matches: Boolean that indicates if self.position_vector matches
position vector match. | 625941c216aa5153ce36240b |
def __repr__(self,*args): <NEW_LINE> <INDENT> pass | __repr__(self: object) -> str
Returns the code representation of the object. The default implementation returns
a string which consists of the type and a unique numerical identifier. | 625941c2fff4ab517eb2f3ce |
def get_single_valued_metadata(self): <NEW_LINE> <INDENT> return list() | Return a list of metadata attaining only one value for this type. | 625941c276d4e153a657eac3 |
def iter_switches(self): <NEW_LINE> <INDENT> return <NEW_LINE> yield None | Iterate or generate switches for the <switch> tags under the <switchlist> tag in VPR's architecture
description XML and the <switches> tag under the <switches> tag in VPR's routing resource graph XML.
Each element in the returned iterator/generator should be a `dict` satisfying the JSON schema
'schema/switch.schema.js... | 625941c299cbb53fe6792b7a |
def si_crystal_test(): <NEW_LINE> <INDENT> jobs=[] <NEW_LINE> cwriter=CrystalWriter({ 'xml_name':'../../BFD_Library.xml', 'cutoff':0.2, 'kmesh':(3,3,3), 'spin_polarized':False }) <NEW_LINE> cwriter.set_struct_fromcif(open('structures/si.cif','r').read(),primitive=True) <NEW_LINE> cman=CrystalManager( name='crys', path=... | Simple tests that check PBC is working Crystal, and that QMC can be performed on the result. | 625941c260cbc95b062c64d6 |
def nb_100(data, deveui): <NEW_LINE> <INDENT> output = {} <NEW_LINE> temperature_humidity_parsed = temperature_humidity(data[deveui + "-1"]) <NEW_LINE> output.update(temperature_humidity_parsed) <NEW_LINE> output["pressure"] = round(float(data[deveui + "-2"]["pressure"]) / (1*10**5), 3) <NEW_LINE> output["rssi"] = floa... | reformat nb_100 data | 625941c2c4546d3d9de729c5 |
def __init__( self, field, specification, optional=False, spec_filter=None, immediate_rebind=True, ): <NEW_LINE> <INDENT> super(RequiresBest, self).__init__( field, specification, False, optional, spec_filter, immediate_rebind ) | :param field: The injected field
:param specification: The injected service specification
:param optional: If True, this injection is optional
:param spec_filter: An LDAP query to filter injected services upon
their properties
:param immediate_rebind: If True, the component won't be invalidated
... | 625941c2d18da76e23532467 |
def add_osd_perf_query(self, query: Dict[str, Any]) -> Optional[int]: <NEW_LINE> <INDENT> return self._ceph_add_osd_perf_query(query) | Register an OSD perf query. Argument is a
dict of the query parameters, in this form:
::
{
'key_descriptor': [
{'type': subkey_type, 'regex': regex_pattern},
...
],
'performance_counter_descriptors': [
list, of, descriptor, types
],
'limit': {'order_by': performance_c... | 625941c2046cf37aa974ccdd |
def revoke_security_group(self, group_name, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None): <NEW_LINE> <INDENT> if src_security_group_name: <NEW_LINE> <INDENT> if from_port is None and to_port is None and ip_protocol is None: <NEW_LINE> <IND... | Remove an existing rule from an existing security group.
You need to pass in either src_security_group_name and
src_security_group_owner_id OR ip_protocol, from_port, to_port,
and cidr_ip. In other words, either you are revoking another
group or you are revoking some ip-based rule.
:type group_name: string
:param gro... | 625941c26fece00bbac2d6d0 |
def Solve(dData): <NEW_LINE> <INDENT> m = dData.A.shape[0] <NEW_LINE> n = dData.A.shape[1] <NEW_LINE> dInit = INIT(np.zeros(m), np.ones(n), np.ones(n)) <NEW_LINE> dCone = CONE(gHc, n) <NEW_LINE> return NSSolve(dData, dInit, dCone) | Solve the linear program using non-symmetric cone alg.
Note: This isnt optimal for LP, but used for tests... | 625941c250812a4eaa59c2b7 |
def get(self, key, default=None): <NEW_LINE> <INDENT> with self.__lock: <NEW_LINE> <INDENT> return copy.deepcopy(self.__values.get(key, default)) | Return thread safe copy of value. | 625941c2925a0f43d2549e08 |
def start(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.subscribe() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> self.start() | 启动接收 | 625941c28e05c05ec3eea306 |
def remove_file(self, path): <NEW_LINE> <INDENT> Logger.info('RemoteConection.remove_file: Removing {}'.format(path)) <NEW_LINE> self.sftp.unlink(path) <NEW_LINE> Logger.info('RemoteConection.remove_file: Removed.') | Unlink a remote file. Does not work with directories. | 625941c263b5f9789fde7078 |
def spatial_batchnorm_backward(dout, cache): <NEW_LINE> <INDENT> dx, dgamma, dbeta = None, None, None <NEW_LINE> pass <NEW_LINE> return dx, dgamma, dbeta | Computes the backward pass for spatial batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, k, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, k, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (k,)
- dbeta: Grad... | 625941c2435de62698dfdbdf |
def _set_list_tuple_only_structure(self, key): <NEW_LINE> <INDENT> self.set_neighs([e[0] for e in key]) <NEW_LINE> self.set_sp_rel_pos([e[1] for e in key]) | Set the neighbourhood information in a form of list tuple only
structure.
Parameters
----------
neighs_info: tuple
the neighborhood information for each element `i` and perturbations
`k`. The standards to set that information are:
* [(neighs{any form}, sp_relative_pos{any form})] | 625941c20c0af96317bb817b |
def generate(self, module): <NEW_LINE> <INDENT> if self.module_backend.needs_regeneration(): <NEW_LINE> <INDENT> if not self.check_mode: <NEW_LINE> <INDENT> if self.backup: <NEW_LINE> <INDENT> self.backup_file = module.backup_local(self.path) <NEW_LINE> <DEDENT> self.module_backend.generate_private_key() <NEW_LINE> pri... | Generate a keypair. | 625941c2498bea3a759b9a43 |
@view_config(route_name='api_v1_key_action', request_method='DELETE', renderer='json') <NEW_LINE> def delete_key(request): <NEW_LINE> <INDENT> auth_context = auth_context_from_request(request) <NEW_LINE> key_id = request.matchdict.get('key') <NEW_LINE> if not key_id: <NEW_LINE> <INDENT> raise KeyParameterMissingError()... | Delete key
Delete key. When a key gets deleted, it takes its associations with it
so just need to remove from the server too. If the default key gets
deleted, it sets the next one as default, provided that at least another
key exists. It returns the list of all keys after the deletion,
excluding the private keys (check... | 625941c221a7993f00bc7c80 |
def setUpPloneSite(self, portal): <NEW_LINE> <INDENT> self.applyProfile(portal, 'pmr2.flatmap:default') | Apply the default pmr2.flatmap profile and ensure that the
settings have the tmpdir applied in. | 625941c21f037a2d8b946192 |
def router(paramstring): <NEW_LINE> <INDENT> params = dict(parse_qsl(paramstring)) <NEW_LINE> if params: <NEW_LINE> <INDENT> if params['action'] == 'list_category': <NEW_LINE> <INDENT> list_movies(params['category']) <NEW_LINE> <DEDENT> elif params['action'] == 'list_movie': <NEW_LINE> <INDENT> list_videos(params['movi... | Router function that calls other functions
depending on the provided paramstring
:param paramstring: | 625941c2090684286d50ec77 |
def keyword_param_f(name="name", gender=None): <NEW_LINE> <INDENT> print("keyword params: name={}, gender={}".format(name, gender)) | Keyword parameter is defined by giving it a default value.
Python interpreter won't care order of keyword parameters.
You can omit some parameter ( Then default value will be used). | 625941c238b623060ff0ad81 |
def generate_salt(length=8): <NEW_LINE> <INDENT> chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890./" <NEW_LINE> salt = [random.choice(chars) for i in range(0, length)] <NEW_LINE> return "".join(salt) | Generate a random salt for password hashing
:return: A random salt of the requested length | 625941c28e71fb1e9831d73e |
def eval(self, y_pred, y_true, metadata): <NEW_LINE> <INDENT> raise NotImplementedError | Args:
- y_pred (Tensor): Predicted targets
- y_true (Tensor): True targets
- metadata (Tensor): Metadata
Output:
- results (dict): Dictionary of results
- results_str (str): Pretty print version of the results | 625941c25fc7496912cc3911 |
def sent2vec(model, s): <NEW_LINE> <INDENT> words = s.lower() <NEW_LINE> words = word_tokenize(words) <NEW_LINE> stop_words = stopwords.words('english') <NEW_LINE> words = [w for w in words if not w in stop_words] <NEW_LINE> words = [w for w in words if w.isalpha()] <NEW_LINE> M = [] <NEW_LINE> for w in words: <NEW_LIN... | Sentence to Vector by summing the embeddings | 625941c23617ad0b5ed67e8c |
def is_valid_interfaces(meta): <NEW_LINE> <INDENT> interfaces = meta['input_port_mapping'] <NEW_LINE> for intf in interfaces: <NEW_LINE> <INDENT> if not is_valid(intf): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | :param meta:
:return: boolean | 625941c2cc40096d615958e5 |
def __init__(self, entity: str, location: List[int], value: str, *, confidence: float = None, metadata: dict = None, groups: List['CaptureGroup'] = None, interpretation: 'RuntimeEntityInterpretation' = None, alternatives: List['RuntimeEntityAlternative'] = None, role: 'RuntimeEntityRole' = None) -> None: <NEW_LINE> <IN... | Initialize a RuntimeEntity object.
:param str entity: An entity detected in the input.
:param List[int] location: An array of zero-based character offsets that
indicate where the detected entity values begin and end in the input text.
:param str value: The entity value that was recognized in the user input.
:pa... | 625941c2cc0a2c11143dce24 |
def __init__(self, sampler=None, *args, **kwargs): <NEW_LINE> <INDENT> super(TransitionBatchUpdate, self).__init__(*args, **kwargs) <NEW_LINE> if sampler is None: <NEW_LINE> <INDENT> sampler = TransitionSampler(playback.MapPlayback(1000), 32, 4) <NEW_LINE> <DEDENT> self._sampler = sampler <NEW_LINE> self._n_update = 0 | :param sampler:
:type sampler: TransitionSampler
:param args:
:param kwargs: | 625941c2293b9510aa2c322b |
def userReg(self, code, name, password): <NEW_LINE> <INDENT> code = code.strip() <NEW_LINE> try: <NEW_LINE> <INDENT> data = self.config.get(code, "name") <NEW_LINE> return False, "用户{code}已存在".format(code=code) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> name = name.strip() <... | 注册用户
:param name:
:param password:
:return: | 625941c244b2445a3393202b |
def find_first(word, letter): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> while index < len(word): <NEW_LINE> <INDENT> if word[index] == letter: <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index += 1 <NEW_LINE> <DEDENT> <DEDENT> return -1 | find a character in a string
:param word:
:param letter:
:return: the index if found or -1 if not | 625941c2925a0f43d2549e09 |
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') <NEW_LINE> parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use', default=0, type=int) <NEW_LINE> parser.add_argument('--def', dest='prototxt', help='prototxt file defining the network', default=No... | Parse input arguments | 625941c23cc13d1c6d3c730f |
def eval_object(context, obj, expected_type): <NEW_LINE> <INDENT> result = expected_type.default_value() <NEW_LINE> for name, val in six.iteritems(obj.props): <NEW_LINE> <INDENT> subtype = expected_type[name] <NEW_LINE> ctx.set_property(result, name, eval_rhs(context, val, subtype)) <NEW_LINE> <DEDENT> return result | Evaluate the provided object
:type context: ctx.EvaluationContext
:param context: Evaluation context.
:type obj: ast.JsonObj
:param obj: The expression to evaluate
:type expected_type: type_util.IsType
:param expected_type: The expected type of this computation.
:return: Returns the computed value | 625941c2a8370b7717052834 |
def is_noun(self, word): <NEW_LINE> <INDENT> return self.tagger.is_noun(word) | is noun word | 625941c2b57a9660fec33816 |
def modify_polling_status_line(self, status_line): <NEW_LINE> <INDENT> return status_line | Hook to modify the status line that is printed during polling. | 625941c2656771135c3eb800 |
def InitializeBongardLTM(ltm): <NEW_LINE> <INDENT> for i in range(10): <NEW_LINE> <INDENT> ltm.GetNode(content=PlatonicInteger(magnitude=i)) <NEW_LINE> <DEDENT> for i in (0, 4, 9): <NEW_LINE> <INDENT> ltm.AddEdge(PlatonicInteger(magnitude=i), Square(), edge_type_set={LTMEdge.LTM_EDGE_TYPE_ISA}) | Called if ltm was empty (had no nodes). | 625941c2e76e3b2f99f3a7a2 |
def onResidual(**bvalues): <NEW_LINE> <INDENT> pass | function (target) {
if (!target.hasType('Rock'))
this.damage(target.baseMaxhp / 6, target);
} | 625941c2293b9510aa2c322c |
def on_notify(self, notification): <NEW_LINE> <INDENT> if notification.get('record', False) and self.running: <NEW_LINE> <INDENT> if 'timestamp' not in notification: <NEW_LINE> <INDENT> logger.error("Notification without timestamp will not be saved.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data['notificatio... | Handles recorder notifications
Reacts to notifications:
``recording.should_start``: Starts a new recording session.
fields: 'session_name' change session name
use `/` to att dirs.
start with `/` to ingore the rec base dir and start from root instead.
``recording.should_stop``: St... | 625941c24f6381625f1149d0 |
def set_own_cert(self, cert, key, passwd=None): <NEW_LINE> <INDENT> cert_char = pynng.nng.to_char(cert) <NEW_LINE> key_char = pynng.nng.to_char(key) <NEW_LINE> passwd_char = pynng.nng.to_char(passwd) if passwd is not None else pynng.ffi.NULL <NEW_LINE> err = pynng.lib.nng_tls_config_own_cert(self._tls_config, cert_char... | Configure own certificate and key. | 625941c271ff763f4b54961c |
def find(self, node, f): <NEW_LINE> <INDENT> if node in self._mancache: <NEW_LINE> <INDENT> mapping = self._mancache[node][0] <NEW_LINE> return mapping.get(f), mapping.flags(f) <NEW_LINE> <DEDENT> text = self.revision(node) <NEW_LINE> start, end = self._search(text, f) <NEW_LINE> if start == end: <NEW_LINE> <INDENT> re... | look up entry for a single file efficiently.
return (node, flags) pair if found, (None, None) if not. | 625941c263b5f9789fde7079 |
def run(self) -> None: <NEW_LINE> <INDENT> logging.info("%s", self._name) <NEW_LINE> team_urls = ScrapeFunctions.get_team_list( self.BASE_URL, self._year, self.TEAM_IDS ) <NEW_LINE> logging.info("Found %d teams to scrape", len(team_urls)) <NEW_LINE> for team in team_urls: <NEW_LINE> <INDENT> logging.info("Fetching %s",... | Run the scraper | 625941c266656f66f7cbc13e |
def setEquipments(self,newEquipments): <NEW_LINE> <INDENT> if isinstance(newEquipments, Equipments) or newEquipments is None: <NEW_LINE> <INDENT> self._equipments = newEquipments <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('"equipments" attribute for a Game object must be a list') | Set the Equipments object of the current game
Args:
self: the Game object
newEquipments: An Equipments object that represent all the private equipments of this player
Returns:
The Equipments object
Raises:
TypeError: Raise a TypeError if "newEquipments" is not an Equipments object | 625941c25fc7496912cc3912 |
def test_process_pool_join_futures_timeout(self): <NEW_LINE> <INDENT> pool = ProcessPool(max_workers=1, context=mp_context) <NEW_LINE> for _ in range(2): <NEW_LINE> <INDENT> pool.schedule(long_function) <NEW_LINE> <DEDENT> pool.close() <NEW_LINE> self.assertRaises(TimeoutError, pool.join, 0.4) <NEW_LINE> pool.stop() <N... | Process Pool Spawn TimeoutError is raised if join on long tasks. | 625941c28e7ae83300e4af60 |
def __click_context_action_button(self, button_name): <NEW_LINE> <INDENT> logger.debug('click %s in context-action' %button_name) <NEW_LINE> buttons = self.find_elements(*self.__context_action_buttons_loc) <NEW_LINE> if len(buttons): <NEW_LINE> <INDENT> for button in buttons: <NEW_LINE> <INDENT> if button_name == butto... | Click the button in context-action <div> by the provided name. It is for the row operation on report page
:param button_name: str: button name
:return: | 625941c2e8904600ed9f1ebf |
def lddmm_matching( I, J, m=None, lddmm_steps=1000, lddmm_integration_steps=10, reg_weight=1e-1, learning_rate_pose = 2e-2, fluid_params=[1.0,.1,.01], progress_bar=True ): <NEW_LINE> <INDENT> if m is None: <NEW_LINE> <INDENT> defsh = [I.shape[0], 3] + list(I.shape[2:]) <NEW_LINE> m = torch.zeros(defsh, dtype=I.dtype).t... | Matching image I to J via LDDMM | 625941c28a349b6b435e8107 |
def test_evangelical_church_day(self): <NEW_LINE> <INDENT> all_sessions = self.calendar.all_sessions <NEW_LINE> self.assertNotIn(pd.Timestamp('2019-10-31', tz=UTC), all_sessions) <NEW_LINE> self.assertNotIn(pd.Timestamp('2018-11-02', tz=UTC), all_sessions) <NEW_LINE> self.assertNotIn(pd.Timestamp('2017-10-27', tz=UTC),... | Evangelical Church Day (also known as Halloween) adheres to the
following rule: If October 31st falls on a Tuesday, it is observed the
preceding Friday. If it falls on a Wednesday, it is observed the next
Friday. If it falls on Thu, Fri, Sat, Sun, or Mon then the holiday is
acknowledged that day. | 625941c226238365f5f0ee00 |
def appendTail(self, value): <NEW_LINE> <INDENT> self.in_stack.append(value) | :type value: int
:rtype: None | 625941c2fb3f5b602dac3625 |
def get_rich_menu(self, rich_menu_id, timeout=None): <NEW_LINE> <INDENT> response = self._get( '/v2/bot/richmenu/{rich_menu_id}'.format(rich_menu_id=rich_menu_id), timeout=timeout ) <NEW_LINE> return RichMenuResponse.new_from_json_dict(response.json) | Call get rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu
Get rich menu object through a given rich_menu_id
:param str rich_menu_id: ID of the rich menu
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect ... | 625941c285dfad0860c3adee |
def compute_cphase_exponents_for_fsim_decomposition( fsim_gate: 'cirq.FSimGate', ) -> Sequence[Tuple[float, float]]: <NEW_LINE> <INDENT> def nonempty_intervals( intervals: Sequence[Tuple[float, float]] ) -> Sequence[Tuple[float, float]]: <NEW_LINE> <INDENT> return tuple((a, b) for a, b in intervals if a < b) <NEW_LINE>... | Returns intervals of CZPowGate exponents valid for FSim decomposition.
Ideal intervals associated with the constraints are closed, but due to
numerical error the caller should not assume the endpoints themselves
are valid for the decomposition. See `decompose_cphase_into_two_fsim`
for details on how FSimGate parameter... | 625941c28e05c05ec3eea307 |
def addArg(self, x, args): <NEW_LINE> <INDENT> from QGL.Channels import Qubit <NEW_LINE> if hasattr(x, "__iter__") and not isinstance(x, str) and not isinstance(x, QRegister): <NEW_LINE> <INDENT> for xx in x: <NEW_LINE> <INDENT> self.addArg(xx, args) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(x, QRegister): <NEW_LINE... | Parse one argument to the QRegister constructor. A recursive function. | 625941c23346ee7daa2b2cff |
def test_is_valid_request(self): <NEW_LINE> <INDENT> primitive = C_MOVE() <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> primitive.MessageID = 1 <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> primitive.AffectedSOPClassUID = '1.2' <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> prim... | Test C_MOVE.is_valid_request | 625941c24527f215b584c3ee |
def get_object(self, **kwargs): <NEW_LINE> <INDENT> return StudentAchievement.objects.get(id=self.kwargs['pk']) | Return object for user | 625941c2498bea3a759b9a44 |
def listcomponents(module_location): <NEW_LINE> <INDENT> components = [] <NEW_LINE> counter = 0 <NEW_LINE> LOGGER.info("Searching for components in %s." % module_location) <NEW_LINE> for posloc in os.listdir(module_location): <NEW_LINE> <INDENT> if os.path.isdir(os.path.join(module_location, posloc)) and posloc.startsw... | return a list of components in module_location. | 625941c2cb5e8a47e48b7a41 |
def add_submenu(submenu, title): <NEW_LINE> <INDENT> __GUI_CONTROLLER.menu = dict(submenu=submenu.menu, title=title) | Menu setter.
Provides access to set the private property `__GUI_CONTROLLER.menu`.
Note:
See `__GUI_CONTROLLER.menu` for more information. | 625941c28a43f66fc4b53ffb |
def base_delete_one(self, p_id): <NEW_LINE> <INDENT> result = self._resource.id(p_id).delete({}) <NEW_LINE> self.print_res(result) <NEW_LINE> assert 0 == result.code <NEW_LINE> assert result.data <NEW_LINE> return result | :param p_id:
:return: | 625941c2d6c5a10208143fdd |
def _get_dtype(self, dtype): <NEW_LINE> <INDENT> if dtype not in (np.float32, np.float64, np.complex64, np.complex128): <NEW_LINE> <INDENT> raise TypeError('Array is of an unsupported dtype.') <NEW_LINE> <DEDENT> self.dtype = dtype <NEW_LINE> cuda_dict = {np.float32: 'float', np.float64: 'double', np... | Certify that the dtype is valid, and find the cuda datatype. | 625941c291f36d47f21ac485 |
def test_no_url(self): <NEW_LINE> <INDENT> self.disp.push(events.COMMAND, "pepe", "canal", "foto", "pepe") <NEW_LINE> self.assertEqual(self.answer[0][1], u"pepe: doesn't have configured URL") <NEW_LINE> self.disp.push(events.PRIVATE_MESSAGE, "pepe", "foto pepe") <NEW_LINE> self.assertEqual(self.answer[0][1], u"pepe: do... | No url configured. | 625941c29b70327d1c4e0d69 |
def encode(hrp, witver, witprog): <NEW_LINE> <INDENT> spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M <NEW_LINE> ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec) <NEW_LINE> if decode(hrp, ret) == (None, None): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return ret | Encode a segwit address. | 625941c2cdde0d52a9e52fc5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.