code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_client_abort(self): <NEW_LINE> <INDENT> if not isinstance(self.mount_a, FuseMount): <NEW_LINE> <INDENT> raise SkipTest("Requires FUSE client to inject client metadata") <NEW_LINE> <DEDENT> require_active = self.fs.get_config("fuse_require_active_mds", service_type="mon").lower() == "true" <NEW_LINE> if not req... | That a client will respect fuse_require_active_mds and error out
when the cluster appears to be unavailable. | 625941ee4f88993c3716c5aa |
def pad_sentences(sentences, padding_word="<PAD/>", max_sent_length=60): <NEW_LINE> <INDENT> sequence_length = max(len(x) for x in sentences) <NEW_LINE> print("setting seq length to min of {} and {}".format( sequence_length, max_sent_length)) <NEW_LINE> sequence_length = min(sequence_length, max_sent_length) <NEW_LINE>... | Pads all sentences to the same length. The length is defined by the min of
the longest sentence and a given max sentence length.
Returns padded sentences. | 625941ee85dfad0860c3b3a5 |
def from_element(self, elt): <NEW_LINE> <INDENT> Container.from_element(self, elt) <NEW_LINE> long_desc_elt = find(elt, 'upnp', 'longDescription') <NEW_LINE> storage_elt = find(elt, 'upnp', 'storageMedium') <NEW_LINE> desc_elt = find(elt, 'dc', 'description') <NEW_LINE> date_elt = find(elt, 'dc', 'date') <NEW_LINE> lan... | Sets the resource properties from an element.
| 625941eea79ad161976cc68e |
def run_hypothesis_during_method( hypo_pool: ThreadPoolExecutor, continuous_hypo_event: threading.Event, strategy: Strategy, schedule: Schedule, experiment: Experiment, journal: Journal, configuration: Configuration, secrets: Secrets, event_registry: EventHandlerRegistry, dry: Dry, ) -> Future: <NEW_LINE> <INDENT> def ... | Run the hypothesis continuously in a background thread and report the
status in the journal when it raised an exception. | 625941ee4d74a7450ccd470e |
def tmp_files(self): <NEW_LINE> <INDENT> return self.tmpdir.list_filepaths() | Return all the input data files produced. | 625941eeb7558d58953c5451 |
def inorderTraversal(self, root): <NEW_LINE> <INDENT> res =[] <NEW_LINE> self.inorder(root, res) <NEW_LINE> return res | :type root: TreeNode
:rtype: List[int] | 625941ee5fcc89381b1e1c0c |
def is_87(self): <NEW_LINE> <INDENT> return self.num == 87 | Verify whether num property is 87 | 625941eed10714528d600232 |
def n_emp_mat(mat, pattern_hash, base=2): <NEW_LINE> <INDENT> if not is_binary(mat): <NEW_LINE> <INDENT> raise ValueError("entries of mat should be either one or zero") <NEW_LINE> <DEDENT> h = hash_from_pattern(mat, base=base) <NEW_LINE> N_emp = np.zeros(len(pattern_hash)) <NEW_LINE> indices = [] <NEW_LINE> for idx_ph,... | Count the occurrences of spike coincidence patterns in the given spike
trains.
Parameters
----------
mat : (N, M) np.ndarray
Binned spike trains of N neurons. Rows and columns correspond
to neurons and temporal bins, respectively.
pattern_hash: list of int
List of hash values, representing the spike coinci... | 625941eec4546d3d9de72f81 |
@tf.function <NEW_LINE> def get_tensor_magic_number(tensor): <NEW_LINE> <INDENT> magic = tf.reshape(tf.io.decode_raw(tf.strings.substr(tensor, 1, 1), tf.uint8), []) <NEW_LINE> return magic | Return the type identifier of a serialized TensorFlow tensor proto.
:param tensor:
:return: | 625941eebf627c535bc13718 |
def remove(self): <NEW_LINE> <INDENT> if len(self.sl_stack) != 0: <NEW_LINE> <INDENT> for i in xrange(0, len(self.sl_stack)): <NEW_LINE> <INDENT> sl = self.sl_stack.pop() <NEW_LINE> try: <NEW_LINE> <INDENT> sl.lines.remove() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.myWidget.Plot.can... | This function removes Streamlines if existent. | 625941ee15fb5d323cde1060 |
def make_deeper_model_v10(input_shape): <NEW_LINE> <INDENT> in0 = Input(shape=[input_shape[1], input_shape[2], input_shape[3]], name='X') <NEW_LINE> conv1 = Conv2D(5, (3, 3), strides=(1, 1), padding='same', activation='relu')(in0) <NEW_LINE> conv2 = Conv2D(25, (3, 3), strides=(1, 1), padding='same', activation='relu')(... | Adding some regularization ton the last map to the first dense layer | 625941ee187af65679ca5668 |
def MaxV( n, m, v, w, chi, phi, a ): <NEW_LINE> <INDENT> D = lambda V: -py.absolute( PlusMinDiff(n,m,V,w,chi,0,a)/V ) <NEW_LINE> F = lambda V: -py.absolute( PlusMinDiff(n,m,V,w,chi,py.pi,a)/V ) <NEW_LINE> optD = optimize.minimize_scalar( D, method='bounded',bounds=(1/n,1) ) <NEW_LINE> optF = optimize.minimize_scalar( F... | Returns velocity at which the difference between right-handed and left-handed photons is maximal. | 625941eeff9c53063f47c739 |
def F5(self): <NEW_LINE> <INDENT> t1 = time.time() <NEW_LINE> self.driver.refresh() <NEW_LINE> self.my_print("{0} F5 the current page, Spend {1} seconds".format(success, time.time() - t1)) | Refresh the current page.
Usage:
driver.F5() | 625941eed4950a0f3b08c890 |
def rvs(self, df, scale, size=1): <NEW_LINE> <INDENT> n, shape = self._process_size(size) <NEW_LINE> dim, df, scale = self._process_parameters(df, scale) <NEW_LINE> eye = np.eye(dim) <NEW_LINE> L, lower = scipy.linalg.cho_factor(scale, lower=True) <NEW_LINE> inv_scale = scipy.linalg.cho_solve((L, lower), eye) <NEW_LINE... | Draw random samples from an inverse Wishart distribution.
Parameters
----------
%(_doc_default_callparams)s
size : integer or iterable of integers, optional
Number of samples to draw (default 1).
Returns
-------
rvs : ndarray
Random variates of shape (`size`) + (`dim`, `dim), where `dim` is
the dimension ... | 625941ee2ae34c7f2600d679 |
def test_creating_child_of_redirect(self): <NEW_LINE> <INDENT> self.client.login(username="admin", password="testpass") <NEW_LINE> rev = revision(is_approved=True, save=True) <NEW_LINE> doc = rev.document <NEW_LINE> doc_first_slug = doc.slug <NEW_LINE> doc._move_tree(new_slug="moved_doc") <NEW_LINE> child_full_slug = d... | While try to create a child of a redirect,
the parent of the child should be redirect's parent. | 625941ee23e79379d52eeaa5 |
def get_course_number(a_text): <NEW_LINE> <INDENT> return | Gets course number from course header in LZK.
:param a_text: with course number type and name
:type a_text: str
:return: course number
:rtype: int
>>> get_course_number("703410 VO/1 VO Introduction into Programming with Python")
703410
>>> get_course_number(" 703410 VO/1 VO Introduction into Programming with Python"... | 625941ee5166f23b2e1a56a2 |
def CreateSiliconDriftDiffusionAtContact(device, region, contact, is_circuit=False): <NEW_LINE> <INDENT> contact_electrons_model = "Electrons - ifelse(NetDoping > 0, {0}, n_i^2/{1})".format(CELEC_MODEL, CHOLE_MODEL) <NEW_LINE> contact_holes_model = "Holes - ifelse(NetDoping < 0, +{1}, +n_i^2/{0})".format(CELEC_MODEL, C... | Restrict electrons and holes to their equilibrium values
Integrates current into circuit | 625941ee66673b3332b925da |
def _bodyDataReceived_DEFERRED_CLOSE(self, data): <NEW_LINE> <INDENT> raise RuntimeError(u"Cannot receive body data after _bodyDataFinished") | It is invalid for data to be delivered after it has been indicated
that the response body has been completely delivered. | 625941ee63f4b57ef0001652 |
def ffprofile2(a, freq=None, window=None): <NEW_LINE> <INDENT> if freq==None: freq=32000 <NEW_LINE> if window==None: window=256 <NEW_LINE> out = [ffcalcfft2(a[x:x+(window-1)],freq) for x in range(len(a))] <NEW_LINE> return out | returns a string of local estimates of the fundamental frequency of a string correcting for harmonics
By default, freq=32000 and window=256. | 625941eee5267d203edce1df |
def setup_module(mod): <NEW_LINE> <INDENT> tgen = Topogen(build_topo, mod.__name__) <NEW_LINE> tgen.start_topology() <NEW_LINE> router_list = tgen.routers() <NEW_LINE> for rname, router in router_list.items(): <NEW_LINE> <INDENT> router.load_config( TopoRouter.RD_ZEBRA, os.path.join(CWD, "{}/zebra.conf".format(rname)) ... | Sets up the pytest environment | 625941ee8e71fb1e9831dcf0 |
def connectionLost(self, reason): <NEW_LINE> <INDENT> self._logger.info("Host %s disconnected (%s)" % (self.transport.getPeer().host, reason)) | What to do when a connection has been lost?
| 625941eed53ae8145f87a7ae |
def define_components(mod): <NEW_LINE> <INDENT> mod.GEN_FUEL_USE_SEGMENTS = Set( mod.FUEL_BASED_GEN, dimen=2) <NEW_LINE> mod.PROJ_FUEL_USE_SEGMENTS = Set( mod.FUEL_BASED_PROJECTS, dimen=2) <NEW_LINE> def PROJ_FUEL_USE_SEGMENTS_default_rule(m, pr): <NEW_LINE> <INDENT> if pr not in m.PROJ_FUEL_USE_SEGMENTS: <NEW_LINE> <I... | This function adds components to a Pyomo abstract model object to
describe fuel consumption in the context of unit commitment. Unless
otherwise stated, all power capacity is specified in units of MW and
all sets and parameters are mandatory.
Typically incremental heat rates tables specify "blocks" where each
block inc... | 625941ee435de62698dfe196 |
def testApplicationThrottlePolicyList(self): <NEW_LINE> <INDENT> pass | Test ApplicationThrottlePolicyList | 625941eeec188e330fd5acdd |
def test_set_checkpoint_restricted_share(cp, org, share, cptime): <NEW_LINE> <INDENT> org.setOrgShareRestriction(share, True, {"from": accounts[0]}) <NEW_LINE> with pytest.reverts("dev: share"): <NEW_LINE> <INDENT> cp.newCheckpoint(share, cptime, {"from": accounts[0]}) | set a checkpoint - restricted share | 625941ee16aa5153ce3629c2 |
def update(self): <NEW_LINE> <INDENT> self._data -= self._diff | Update the data field by SUBTRACTING diff to it.
Note that diff is often used to store the gradients, and most often
we will perform MINIMIZATION. This is why we always do subtraction
here. | 625941ee187af65679ca5669 |
def _GenerateRootGradle(): <NEW_LINE> <INDENT> variables = {'template_type': 'root'} <NEW_LINE> processor = jinja_template.JinjaProcessor(host_paths.DIR_SOURCE_ROOT) <NEW_LINE> return processor.Render(_JINJA_TEMPLATE_PATH, variables) | Returns the data for the root project's build.gradle. | 625941ee29b78933be1e5bee |
def learn(self, experiences, gamma): <NEW_LINE> <INDENT> this_actor_states, other_actor_states, actions, rewards, this_actor_next_states, other_actor_next_states, dones = experiences <NEW_LINE> critic_states = torch.cat((this_actor_states, other_actor_states), dim=1) <NEW_LINE> critic_next_states = torch.cat((this_acto... | Update policy and value parameters using given batch of experience tuples.
Q_targets = r + γ * critic_target(next_state, actor_target(next_state))
where:
actor_target(state) -> action
critic_target(state, action) -> Q-value
Params
======
experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples... | 625941eecad5886f8bd27521 |
def test_create_mondrian_up_to_cube(): <NEW_LINE> <INDENT> pass | Test if create_mondrian correctly creates a file, when the
tree has role and cubes (nothing more) | 625941eeb830903b967e9e4e |
def append_section_title(table, title, top): <NEW_LINE> <INDENT> label = gtk.Label() <NEW_LINE> label.set_markup("<b>"+title+"</b>") <NEW_LINE> label.set_alignment(0.0, 1.0) <NEW_LINE> table.attach(label, 0, 4, top, top+1, gtk.FILL, 0, 0) <NEW_LINE> return label | Adds a title for the current section. | 625941ee099cdd3c635f11a1 |
def set_network_config(self): <NEW_LINE> <INDENT> network_config = dict() <NEW_LINE> network_config['pid'] = self.pid <NEW_LINE> network_config["parties"] = {} <NEW_LINE> network_config = {'pid': self.pid, "parties": {}} <NEW_LINE> for i in range(len(self.parties)): <NEW_LINE> <INDENT> network_config["parties"][i + 1] ... | Return network configuration dict. | 625941ee8a349b6b435e86bb |
def configBorderRouter( self, P_Prefix, P_stable=1, P_default=1, P_slaac_preferred=0, P_Dhcp=0, P_preference=0, P_on_mesh=1, P_nd_dns=0, ): <NEW_LINE> <INDENT> print('%s call configBorderRouter' % self.port) <NEW_LINE> prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix)) <NEW_LINE> print(prefix) <NEW_LINE>... | configure the border router with a given prefix entry parameters
Args:
P_Prefix: IPv6 prefix that is available on the Thread Network
P_stable: true if the default router is expected to be stable network data
P_default: true if border router offers the default route for P_Prefix
P_slaac_preferred: true ... | 625941eeadb09d7d5db6ccd5 |
def calc_flux(self, band): <NEW_LINE> <INDENT> if self.wa[0] > band.wa[0] or self.wa[-1] < band.wa[-1]: <NEW_LINE> <INDENT> msg = "SED does not cover the whole bandpass, extrapolating" <NEW_LINE> warnings.warn(msg) <NEW_LINE> dw = np.median(np.diff(self.wa)) <NEW_LINE> sedwa = np.arange(band.wa[0], band.wa[-1]+dw, dw) ... | Calculate the mean flux for a passband, weighted by the
response and wavelength in the given passband.
Returns the mean flux (erg/s/cm^2/Ang) inside the band. | 625941eea8ecb033257d3614 |
def reverse_port_forward(self, device_port: int, local_port: int) -> "DeviceSetup.Builder": <NEW_LINE> <INDENT> if device_port in self._reverse_forwarded_ports: <NEW_LINE> <INDENT> raise Exception("Attempt to reverse-forward and already reverse-forwarded port") <NEW_LINE> <DEDENT> self._reverse_forwarded_ports[device_p... | reverse forward traffic on remote port to local port
:param device_port: remote device port to forward
:param local_port: port to forward to | 625941eefbf16365ca6f6718 |
def test_blank_mindways_call_fails(self): <NEW_LINE> <INDENT> command = ['ogo', 'calib', 'mindways'] <NEW_LINE> with self.assertRaises(subprocess.CalledProcessError): <NEW_LINE> <INDENT> subprocess.check_output(command, stderr=subprocess.STDOUT) | Calling `ogo calib mindways` fails | 625941ee30c21e258bdfa9ec |
def multi_add(self, items, keys=None): <NEW_LINE> <INDENT> item_keys = [h(i) for i in items] <NEW_LINE> if keys is None: <NEW_LINE> <INDENT> keys = items <NEW_LINE> <DEDENT> if self.root_hash == None: <NEW_LINE> <INDENT> l = Leaf(item_keys[0], keys[0]) <NEW_LINE> self.store[l.identity()] = l <NEW_LINE> b = l.multi_add(... | Add many elements to the Merkle tree.
This is more efficient than adding individual elements.
:param items: Items to add
:param keys:
Example:
>>> t = Tree()
>>> t.multi_add([b"Hello", b"World"])
>>> assert b"Hello" in t and b"World" in t | 625941ee60cbc95b062c6a8d |
def syntax_file_hash(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.syntax_file_path(name)) as syntaxfile: <NEW_LINE> <INDENT> content = syntaxfile.read() <NEW_LINE> hash_ = self.syntax_hash(content) <NEW_LINE> return hash_ <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <IND... | Computes hash value of content of syntax file with given name in ``dirpath``. | 625941eef7d966606f6aa554 |
def processFile(self, filepath): <NEW_LINE> <INDENT> self.workQueue.put((True, filepath)) | 将待处理文件放入队列 | 625941eecdde0d52a9e53581 |
def register(self, func: _T) -> None: <NEW_LINE> <INDENT> self._registry.append(func) <NEW_LINE> self.log.info("Registered event: %s with isr: %s to the registry", self.event_id, func.__name__) | Register an async function to this events registry
:param func: asynchronous endpoint with None rtype
:type func: _T | 625941ee099cdd3c635f11a2 |
def inside(dir, name): <NEW_LINE> <INDENT> dir = abspath(dir) <NEW_LINE> name = abspath(name) <NEW_LINE> return name.startswith(join(dir, '')) | Checks whenever a given file name lies within a folder. | 625941ee30bbd722463cc313 |
def _seek_country(self, ipnum): <NEW_LINE> <INDENT> offset = 0 <NEW_LINE> for depth in range(31, -1, -1): <NEW_LINE> <INDENT> if self._flags & const.MEMORY_CACHE: <NEW_LINE> <INDENT> startIndex = 2 * self._recordLength * offset <NEW_LINE> length = 2 * self._recordLength <NEW_LINE> endIndex = startIndex + length <NEW_LI... | Using the record length and appropriate start points, seek to the
country that corresponds to the converted IP address integer.
@param ipnum: result of ip2long conversion
@type ipnum: int
@return: offset of start of record
@rtype: int | 625941eef9cc0f698b140b40 |
@pytest.mark.parametrize("testname", TESTS) <NEW_LINE> def test_elimination(testname): <NEW_LINE> <INDENT> aa, bb = get_test_input(testname) <NEW_LINE> xx_expected = get_test_output(testname) <NEW_LINE> if xx_expected is None: <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> solvers.gaussian_elim... | Tests elimination. | 625941eeaad79263cf390f93 |
def get_info_box(poet_soup): <NEW_LINE> <INDENT> if poet_soup.select(".infobox")!= None: <NEW_LINE> <INDENT> return poet_soup.select(".infobox") <NEW_LINE> <DEDENT> elif poet_soup.select(".vacrd") != None: <NEW_LINE> <INDENT> return poet_soup.select(".vacrd") <NEW_LINE> <DEDENT> else : return None | get info box : wikipedia have dirty code. somewhere used .infobox and somewhere use .vcard class | 625941eea17c0f6771cbe598 |
def setResultCharArray(self,resultCode,resultValue): <NEW_LINE> <INDENT> return self._rpc("setResultCharArray",resultCode,resultValue) | setResultCharArray(
Integer resultCode: The result code to propagate back to the originating activity, often RESULT_CANCELED (0) or RESULT_OK (-1),
Character[] resultValue)
Sets the result of a script execution. Whenever the script APK is called via startActivityForResult(), the resulting intent will contain SCRIP... | 625941eeb5575c28eb68e54f |
def delete_resource(self, request, response, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resource = self._parent.root[path] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> resource = None <NEW_LINE> <DEDENT> method = getattr(resource, 'render_DELETE', None) <NEW_LINE> if hasattr(method, '__call__'): <N... | Render a DELETE request.
:param request: the request
:param response: the response
:param path: the path
:return: the response | 625941ee99cbb53fe679312e |
def _pieces(self): <NEW_LINE> <INDENT> pieces = [] <NEW_LINE> for s, x in enumerate(self.crossings): <NEW_LINE> <INDENT> y = x <NEW_LINE> l = 2 <NEW_LINE> go = True <NEW_LINE> pieces.append([]) <NEW_LINE> pieces[s].append(x[l]) <NEW_LINE> while go: <NEW_LINE> <INDENT> if y.adjacent[l][1] == 0: <NEW_LINE> <INDENT> piece... | Auxiliary function used by knot_group. Constructs the strands
of the knot from under-crossing to under-crossing. Needed for the
Wirtinger Presentation. | 625941ee627d3e7fe0d6939b |
def checkClientCompat(self, clients, os=None): <NEW_LINE> <INDENT> temp = clients <NEW_LINE> wildcard=1.0 <NEW_LINE> try: <NEW_LINE> <INDENT> if os and self.os not in os: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif os and self.os in os: <NEW_LINE> <INDENT> wildcard=wildcard+.1 <NEW_LINE> <DEDENT> for i in sel... | Check and see if client is compatible with what useragent and operating system that we are | 625941ee004d5f362079a879 |
def _marshal(self): <NEW_LINE> <INDENT> return {'deleted': tuple(self.key.get_path(column=col) for col in self._deleted.keys()), 'changed': tuple(self._columns[key] for key in self._modified.keys())} | Marshal deleted and changed columns. | 625941eebe7bc26dc91cdb3f |
def get_cache_file(): <NEW_LINE> <INDENT> mangled = os.path.realpath(SAGE_SRC).replace(os.sep, '_') <NEW_LINE> return os.path.join(DOT_SAGE, 'cache', "%s-lazy_import_cache.pickle" % mangled) | Returns a per-branch file for caching names of lazily imported modules.
EXAMPLES::
sage: from sage.misc.lazy_import_cache import get_cache_file
sage: get_cache_file()
'...-lazy_import_cache.pickle'
sage: get_cache_file().startswith(DOT_SAGE)
True
sage: 'src' in get_cache_file()
True
It sh... | 625941eeb7558d58953c5452 |
def get_loss(self, session, batch): <NEW_LINE> <INDENT> input_feed = {} <NEW_LINE> input_feed[self.context_ids] = batch.context_ids <NEW_LINE> input_feed[self.context_mask] = batch.context_mask <NEW_LINE> input_feed[self.qn_ids] = batch.qn_ids <NEW_LINE> input_feed[self.qn_mask] = batch.qn_mask <NEW_LINE> input_feed[se... | Run forward-pass only; get loss.
Inputs:
session: TensorFlow session
batch: a Batch object
Returns:
loss: The loss (averaged across the batch) for this batch | 625941ee85dfad0860c3b3a6 |
def TemplateConfigFileQuery(vim, *args, **kwargs): <NEW_LINE> <INDENT> obj = vim.client.factory.create('ns0:TemplateConfigFileQuery') <NEW_LINE> if (len(args) + len(kwargs)) < 0: <NEW_LINE> <INDENT> raise IndexError('Expected at least 1 arguments got: %d' % len(args)) <NEW_LINE> <DEDENT> required = [ ] <NEW_LINE> opti... | This data object type describes the query specification for a template virtual
machine configuration file. | 625941ee26238365f5f0f3bf |
def power_on(self, domain_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> virDomain_obj = self.conn.lookupByName(domain_name) <NEW_LINE> virDomain_obj.create() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass | Powers on the required VM | 625941eebaa26c4b54cb1664 |
def roundup(self, x): <NEW_LINE> <INDENT> return int(math.ceil(x / 10.0)) * 10 | rounds up to the nearest 10
Args:
x ([type]): [description]
Returns:
[type]: [description] | 625941ee0383005118ecfb2a |
def getType(self): <NEW_LINE> <INDENT> return self.type | Get platform type.
@return: Either 'posix', 'win32' or 'java'
@rtype: C{str} | 625941ee656771135c3ebdbf |
def get(self, name): <NEW_LINE> <INDENT> for snap in self.list(): <NEW_LINE> <INDENT> if snap.name == name: <NEW_LINE> <INDENT> return snap <NEW_LINE> <DEDENT> <DEDENT> raise ValueError("Could not find snapshot {}".format(name)) | Get snapshot | 625941ee23849d37ff7b35d5 |
def test_validate_initial_state_transitions(self): <NEW_LINE> <INDENT> with nose.assert_raises(exceptions.MissingStateError): <NEW_LINE> <INDENT> del self.dtm1.transitions[self.dtm1.initial_state] <NEW_LINE> self.dtm1.validate() | Should raise error if the initial state has no transitions. | 625941ee379a373c97cfb090 |
def classify(self, instance): <NEW_LINE> <INDENT> min_distance = INFINITY <NEW_LINE> min_classification = None <NEW_LINE> for example, classification in self.examples: <NEW_LINE> <INDENT> d = self._distance(instance, example) <NEW_LINE> if d < min_distance: <NEW_LINE> <INDENT> min_distance = d <NEW_LINE> min_classifica... | Finds the closest example to the given instance (in terms of Euclidean distance),
and returns its class.
@param instance: A tuple of numerical features.
@return: The nearest neighbor's class. | 625941ee287bf620b61d3faa |
@pytest.fixture <NEW_LINE> def patch_cpanm(mocker): <NEW_LINE> <INDENT> mocker.patch('ansible_collections.community.general.plugins.module_utils.module_helper.AnsibleModule.get_bin_path', return_value='/testbin/cpanm') | Function used for mocking some parts of redhat_subscribtion module | 625941eee64d504609d74d8a |
def testFromTensorsMixed(self): <NEW_LINE> <INDENT> components = (np.array(1), np.array([1, 2, 3]), np.array(37.0), sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 1]]), values=np.array([-1, 1]), d... | Test an dataset that represents a single tuple of tensors. | 625941ee92d797404e3046d7 |
def write(self,text): <NEW_LINE> <INDENT> self.psk.write(text); | Adds some text | 625941ee9b70327d1c4e1322 |
def get_follow_nums(self): <NEW_LINE> <INDENT> return self.userfollowquestion_set.count() | 获取关注者数量 | 625941ee507cdc57c6307232 |
def get_all_files(repdir, pattern, recursively): <NEW_LINE> <INDENT> if not os.path.lexists(repdir): <NEW_LINE> <INDENT> raise EnvironmentError("Invalid directory defined :'" + repdir + "'") <NEW_LINE> <DEDENT> files = [] <NEW_LINE> if recursively: <NEW_LINE> <INDENT> for root, dirnames, filenames in os.walk(repdir): <... | Get all files under repdir and sub-dir (recursively or not).
:param repdir:
:param pattern:
:param recursively:
:return:
:return: list of files with matching pattern | 625941ee5fdd1c0f98dc077f |
def ex_update_access_key( self, access_key_id: str = None, state: str = None, dry_run: bool = False, ): <NEW_LINE> <INDENT> action = "UpdateAccessKey" <NEW_LINE> data = {"DryRun": dry_run} <NEW_LINE> if access_key_id is not None: <NEW_LINE> <INDENT> data.update({"AccessKeyId": access_key_id}) <NEW_LINE> <DEDENT> if sta... | Modifies the status of the specified access key associated with
the account that sends the request.
When set to ACTIVE, the access key is enabled and can be used to
send requests. When set to INACTIVE, the access key is disabled.
:param access_key_id: The ID of the access key. (required)
:type access_key_id... | 625941eebe8e80087fb21184 |
def test_5_not_found_email(self): <NEW_LINE> <INDENT> response = self.app.post( '/api/v1/auth/login', data=json.dumps(self.user5), content_type='application/json') <NEW_LINE> self.assertEqual(response.status_code, 404, msg="Email not found") | Test email not found | 625941ee94891a1f4081bff6 |
def finish_initializing(self, builder): <NEW_LINE> <INDENT> super(DownloadrWindow, self).finish_initializing(builder) <NEW_LINE> self.AboutDialog = AboutDownloadrDialog <NEW_LINE> self.PreferencesDialog = PreferencesDownloadrDialog <NEW_LINE> self.current_directory = os.path.realpath(os.path.expanduser('~')) <NEW_LINE>... | Set up the main window | 625941ee435de62698dfe197 |
def add_splash_ids(splash_mapping_file_pth, conn, db_type='sqlite'): <NEW_LINE> <INDENT> cursor = conn.cursor() <NEW_LINE> cursor.execute("SELECT id, accession FROM library_spectra_meta") <NEW_LINE> accession_d = {row[1]: row[0] for row in cursor} <NEW_LINE> if db_type == 'sqlite': <NEW_LINE> <INDENT> type_sign = '?' <... | Add splash ids to database (in case stored in a different file to the msp files like for MoNA)
Example:
>>> from msp2db.db import get_connection
>>> from msp2db.parse import add_splash_ids
>>> conn = get_connection('sqlite', 'library.db')
>>> add_splash_ids('splash_mapping_file.csv', conn, db_type='sql... | 625941ee090684286d50f239 |
def render(self, answers): <NEW_LINE> <INDENT> total, answered, unanswered = self.calculate(self.question, answers) <NEW_LINE> return self.page(question=self.question, total=total, answered=answered, unanswered=unanswered) | Render statistics as HTML code | 625941ee097d151d1a2233a1 |
def __init__(self, hostname, port): <NEW_LINE> <INDENT> mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> mySocket.bind((hostname, port)) <NEW_LINE> mySocket.listen(5) <NEW_LINE> while True: <NEW_LINE> <INDENT> print('Waitin... | Initialize the web application. | 625941ee7c178a314d6ef9b3 |
def normalise_shelfmark(sm): <NEW_LINE> <INDENT> sm = "".join(sm.split()) <NEW_LINE> sm = re.sub(r',|\.|;|:', r'', sm) <NEW_LINE> sm = re.sub(r'\[|\{', r'\(', sm) <NEW_LINE> sm = re.sub(r'\]|\}', r'\)', sm) <NEW_LINE> sm = sm.replace('_', '-') <NEW_LINE> sm = sm.replace('&', ' & ') <NEW_LINE> sm = re.sub(r'(\d+)', lamb... | Normalize shelfmarks. | 625941eecc0a2c11143dd3dc |
def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6): <NEW_LINE> <INDENT> draw_img = np.copy(img) <NEW_LINE> for bbox in bboxes: <NEW_LINE> <INDENT> cv2.rectangle(draw_img,bbox[0],bbox[1],color=color,thickness=thick) <NEW_LINE> <DEDENT> return draw_img | Returns a copy of the image with drawn bounding boxes
:param img: Image without bounding box information
:param bboxes: Bounding boxes
:param color: Color code of the bounding boxes
:param thick: Thickness of lines from the bounding boxes
:return: Image with bounding box information | 625941ee67a9b606de4a8401 |
@app.route('/routes/<routeTag>') <NEW_LINE> @stats.ratelimit() <NEW_LINE> @utils.gzipped <NEW_LINE> def routes_config(routeTag): <NEW_LINE> <INDENT> params = utils.qs_params( command='routeConfig', data=request.args, r=routeTag ) <NEW_LINE> resp=proxy_pass(params=params) <NEW_LINE> jdata=xmltodict.parse(resp.content... | Returns details about a given routeTag. | 625941ee5e10d32532c5f46f |
def _createLookupTable(tree): <NEW_LINE> <INDENT> lookup = [None] * 256 <NEW_LINE> def recurse(subtree, code, num_of_bits): <NEW_LINE> <INDENT> if len(subtree) == 1: <NEW_LINE> <INDENT> lookup[subtree[0]] = (code, num_of_bits) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> recurse(subtree[0], code << 1, num_of_bits + 1)... | Create a lookup table for a Huffman tree.
The table (list) maps bytes to a tuple (code, num_of_bits),
where `code` is the compact binary representation,
and `num_of_bits` is the number of bits in the representation. | 625941ee5fdd1c0f98dc0780 |
def test_approved_not_present(self): <NEW_LINE> <INDENT> group_request = GroupRequest.objects.create( user=self.create_user(), group=mommy.make('groups.Group'), moderated_by=self.create_superuser(), moderated_at=now(), approved=True ) <NEW_LINE> self.assertNotIn(group_request, GroupRequest.objects.unapproved()) | Approved requests are not returned in unapproved method. | 625941eebf627c535bc13719 |
def get_dict(self): <NEW_LINE> <INDENT> return self._dictionary.copy() | Return copy of word dictionary
:return: dict() | 625941eede87d2750b8602e3 |
def __init__(self, isa=None, coerce=None, check=None, required=False, default=_none, traits=None, extraneous=False, empty_attr=_none, empty=None, doc=None): <NEW_LINE> <INDENT> self.name = None <NEW_LINE> self.class_ = None <NEW_LINE> self.__doc__ = doc <NEW_LINE> super(Property, self).__init__() <NEW_LINE> self.defau... | Declares a new standard Property. Note: if you pass arguments which
are not understood by this constructor, or pass extra property traits
to ``traits``, then the call will be redirected to a sub-class; see
:py:mod:`normalize.property.meta` for more.
Because of this magic, all ``Property`` arguments *must* be passed i... | 625941ee45492302aab5e813 |
@login_required <NEW_LINE> def delete_post(request): <NEW_LINE> <INDENT> post_id = request.POST.get('id', None) <NEW_LINE> response_data = {} <NEW_LINE> try: <NEW_LINE> <INDENT> views_helper.delete_facebook_post(post_id) <NEW_LINE> response_data['status'] = 'success' <NEW_LINE> response_data['message'] = 'Successfully ... | Delete posts on social media | 625941eef8510a7c17cf9c4b |
def find_closest_focus(app, old_node, new_node): <NEW_LINE> <INDENT> old_key = app.get_node_id(old_node) <NEW_LINE> for node in walk_tree(new_node): <NEW_LINE> <INDENT> if old_key == app.get_node_id(node): <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> <DEDENT> if not old_node._parent: <NEW_LINE> <INDENT> return n... | Return the position of the old node in the new tree.
1. Attempts to find the old node in the new tree.
2. Otherwise it walks up the old tree until it
finds a node which is present in the new tree.
3. Otherwise it returns the root node of the new tree.
Arguments:
app (TuiApp):
Tui app instance.
old_... | 625941ee462c4b4f79d1dc1a |
def wait(self, waiting_time=5): <NEW_LINE> <INDENT> time.sleep(waiting_time) | wait for given time | 625941ee167d2b6e312190df |
def get_ifo_t1(self): <NEW_LINE> <INDENT> return self.__ifo_t1 | Returns the IFO code of t1. | 625941eecdde0d52a9e53582 |
def isLocalSE( self ): <NEW_LINE> <INDENT> import DIRAC <NEW_LINE> self.log.verbose( "isLocalSE: Determining whether %s is a local SE." % self.name ) <NEW_LINE> localSEs = getSEsForSite( DIRAC.siteName() )['Value'] <NEW_LINE> if self.name in localSEs: <NEW_LINE> <INDENT> return S_OK( True ) <NEW_LINE> <DEDENT> else: <N... | Test if the Storage Element is local in the current context
| 625941eea79ad161976cc690 |
def get(self, request, label_id): <NEW_LINE> <INDENT> me = self.get_user_profile(request) <NEW_LINE> label = Label.objects.filter(pk=label_id, is_deleted=False).first() <NEW_LINE> if label is None: <NEW_LINE> <INDENT> return self.error(errorcode.MSG_NO_DATA, errorcode.NO_DATA) <NEW_LINE> <DEDENT> formatter = MeLabelSer... | 查看单个标签的详情 | 625941eed10714528d600234 |
def test_030_type_exact(self): <NEW_LINE> <INDENT> q = InitialSIDQuery(self.p, type_="type30", type_regex=False) <NEW_LINE> sids = sorted(str(s) for s in q.results()) <NEW_LINE> self.assertListEqual(["node"], sids) | Initial SID query with context type exact match | 625941eeb7558d58953c5453 |
def calculate_departure_enthalpy(self, p, T, x, fluid_type): <NEW_LINE> <INDENT> self.update_parameters(p, T, x) <NEW_LINE> _f, Z = super().calculate_fugacities_with_minimum_gibbs_energy(p, T, x, fluid_type) <NEW_LINE> h_i = (Z - 1.0) <NEW_LINE> h_ii = self.A / (2 * SQRT_2 * self.B) <NEW_LINE> h_iii = (1.0 - self.TdadT... | :Source: Applied Hydrocarbon Thermodynamics - Volume 1
Practical Thermodynamics tools for solving process engineering problems
Wayne C. Edmister and Byung Ik Lee
This function calculate_departure_enthalpy was based on equation (5.85A) - Edmister
:T: temperature [K]
:x: molar fraction... | 625941ee8a43f66fc4b545aa |
def Envelope(self) -> "GsBox": <NEW_LINE> <INDENT> return _gskernel.GsLinePointSymbol_Envelope(self) | 点符号的矩形范围 | 625941ee5f7d997b87174fe7 |
def __init__(self, common_ctrl, main_ctrl): <NEW_LINE> <INDENT> self.common_ctrl = common_ctrl <NEW_LINE> self.main_ctrl = main_ctrl <NEW_LINE> super(MenuBarView, self).__init__() <NEW_LINE> file_menu = self.addMenu("&File") <NEW_LINE> file_menu.addAction(self.new_project_action()) <NEW_LINE> file_menu.addAction(self.o... | Args:
common_ctrl (auri.controllers.common_controller.CommonController):
main_ctrl (auri.controllers.main_controller.MainController): | 625941ee2eb69b55b151ce02 |
def sample(df: pd.DataFrame, n: int = 2, shape: bool = True, *args, **kwargs): <NEW_LINE> <INDENT> if info: <NEW_LINE> <INDENT> _shape(df) <NEW_LINE> <DEDENT> if isinstance(df, pd.Series): <NEW_LINE> <INDENT> return df.sample(n=n, *args, **kwargs).to_frame() <NEW_LINE> <DEDENT> return df.sample(n=n, *args, **kwargs) | show sample data
This is a wrapper function rather than using e.g. df.sample()
For details of args, kwargs - see help(pd.DataFrame.sample)
Examples
--------
.. code-block::
sample(df)
Parameters
----------
df
dataframe
shape
show shape information as a logger.info() message
*args
arguments for wrap... | 625941ee187af65679ca566a |
def _extended_gcd(self, a: int, b: int) -> tuple[int, int, int]: <NEW_LINE> <INDENT> s, old_s = 0, 1 <NEW_LINE> t, old_t = 1, 0 <NEW_LINE> r, old_r = b, a <NEW_LINE> while r: <NEW_LINE> <INDENT> quotient = old_r // r <NEW_LINE> old_r, r = r, old_r - quotient * r <NEW_LINE> old_s, s = s, old_s - quotient * s <NEW_LINE> ... | Extended Euclidean algorithms to solve Bezout's identity:
a*x + b*y = gcd(x, y)
Finds one particular solution for x, y: s, t
Returns: gcd, s, t | 625941ee3c8af77a43ae3cf2 |
def by_birthdate(self, first_id, second_id): <NEW_LINE> <INDENT> first = self.database.get_person_from_handle(first_id) <NEW_LINE> second = self.database.get_person_from_handle(second_id) <NEW_LINE> birth1 = get_birth_or_fallback(self.database, first) <NEW_LINE> if birth1: <NEW_LINE> <INDENT> date1 = birth1.get_date_ob... | Sort routine for comparing two people by birth dates. If the birth dates
are equal, sorts by name | 625941ee66673b3332b925dc |
def a_re_goaway(self, irc, msg, regex): <NEW_LINE> <INDENT> if not msg.channel: <NEW_LINE> <INDENT> irc.reply("Yell at me in a channel, not in a PM") <NEW_LINE> return <NEW_LINE> <DEDENT> delay = self.registryValue('meek_time') <NEW_LINE> self._reply(irc, msg, 'go-away', thechannel=msg.channel, theduration=delay) <NEW_... | ^(?P<what>go away|fuck off|shut up)$ | 625941eed4950a0f3b08c892 |
def pi(self): <NEW_LINE> <INDENT> self.run_op(op_name='pi', op_func=lambda: math.pi, num_of_args=0) | PI constant | 625941ee460517430c3946c1 |
def from_text(text, origin = root): <NEW_LINE> <INDENT> if not (origin is None or isinstance(origin, Name)): <NEW_LINE> <INDENT> raise ValueError("origin must be a Name or None") <NEW_LINE> <DEDENT> labels = [] <NEW_LINE> label = '' <NEW_LINE> escaping = False <NEW_LINE> seen_non_ascii = False <NEW_LINE> seen_non_ascii... | Convert unicode text into a Name object.
Lables are encoded in IDN ACE form.
@rtype: dns.name.Name object | 625941ee8e71fb1e9831dcf2 |
def turn(self, direction): <NEW_LINE> <INDENT> if direction.upper() == 'LEFT': <NEW_LINE> <INDENT> self.left_wheel.run_to_rel_pos(position_sp=240, speed_sp=300) <NEW_LINE> self.right_wheel.run_to_rel_pos(position_sp=-240, speed_sp=300) <NEW_LINE> self.__change_direction_(-90) <NEW_LINE> <DEDENT> elif direction.upper() ... | Turns the robot 90 degrees in a given direction | 625941eeab23a570cc2506d2 |
def close(*event): <NEW_LINE> <INDENT> root.after(40000, lambda: root.destroy()) <NEW_LINE> pop("Thank you", "Thank you for learning with us!") <NEW_LINE> webbrowser.open( 'http://23eyes.org/fair', new=0, autoraise=False) <NEW_LINE> root.destroy() | close: procedure for closing app
Close the app,
1. show popup,
2. change browser contents,
3. destroy root
:rtype: bool
:param event: Optional
:type event: event | 625941eebe383301e01b59c6 |
def write_gmt_fault_file(fault_dict_list, outfile): <NEW_LINE> <INDENT> print("Writing file %s " % outfile); <NEW_LINE> ofile = open(outfile, 'w'); <NEW_LINE> for fault in fault_dict_list: <NEW_LINE> <INDENT> lons, lats = get_four_corners_lon_lat(fault); <NEW_LINE> ofile.write("> -Z"+str(fault['slip'])+"\n"); <NEW_LINE... | Write the 4 corners of a fault and its slip values into a multi-segment file for plotting in GMT | 625941eed6c5a1020814459a |
def test_get_column_returns_computed(self): <NEW_LINE> <INDENT> insp = inspect(config.db) <NEW_LINE> cols = insp.get_columns("computed_default_table") <NEW_LINE> data = {c["name"]: c for c in cols} <NEW_LINE> for key in ("id", "normal", "with_default"): <NEW_LINE> <INDENT> is_true("computed" not in data[key]) <NEW_LINE... | SPANNER OVERRIDE:
In Spanner all the generated columns are STORED,
meaning there are no persisted and not persisted
(in the terms of the SQLAlchemy) columns. The
method override omits the persistence reflection checks. | 625941eee8904600ed9f2481 |
def test_user_can_login(self): <NEW_LINE> <INDENT> login_resp = post(self.live_server_url + '/api/login/', data={"username": self.username, "password": self.password}) <NEW_LINE> self.assertEqual(login_resp.status_code, 200) <NEW_LINE> self.assertEqual(login_resp.json()['token'], self.token) | Test that an existing user can login at /api/login/ endpoint | 625941eed99f1b3c44c67acf |
def __init__(self, name, maxq, mpi, delta, num_quotes, quote_range): <NEW_LINE> <INDENT> Provider.__init__(self, name, maxq, mpi, delta) <NEW_LINE> self.trader_type = 'MarketMaker' <NEW_LINE> self._num_quotes = num_quotes <NEW_LINE> self._quote_range = quote_range <NEW_LINE> self._position = 0 <NEW_LINE> self._cash_flo... | _num_quotes and _quote_range determine the depth of MM quoting;
_position and _cashflow are stored MM metrics | 625941eed53ae8145f87a7b0 |
def test_2_rider_emails(self): <NEW_LINE> <INDENT> from .. import models <NEW_LINE> url = reverse( 'register:rider-emails', args=('LM', '200', '17Apr2010', 'eb45e7d4-46b5-5efc-9d17-8d25a74fcae0')) <NEW_LINE> with patch.object(models, 'datetime') as mock_datetime: <NEW_LINE> <INDENT> mock_datetime.today.return_value = d... | request for rider's emails for event w/ 2 riders returns list
| 625941eeec188e330fd5acdf |
def plotResolution(self, vmin=30, vmax=90): <NEW_LINE> <INDENT> mask = np.isfinite(self.data.sum(axis=0)) <NEW_LINE> plt.clf() <NEW_LINE> self._show1(self.wavecal_lambda0/self.wavecal_dispersion/2, title='Spectral Resolution per 2 pixels', vmin=vmin, vmax=vmax, mask=mask) | Plot spectral resolution over the FOV | 625941eed99f1b3c44c67ad0 |
def parse_static_op_hours(data_json, eatery_model): <NEW_LINE> <INDENT> today = get_today() <NEW_LINE> for eatery in data_json["eateries"]: <NEW_LINE> <INDENT> if eatery_model.slug == eatery.get("slug", ""): <NEW_LINE> <INDENT> weekdays = {} <NEW_LINE> hours_list = eatery.get("operatingHours", []) <NEW_LINE> dining_ite... | Parses a Cornell Dining json dictionary.
Returns a list of tuples of CampusEateryHour objects for a corresponding CampusEatery object and their unparsed
menu.
Args:
data_json (dict): a valid dictionary from the Cornell Dining json
eatery_model (CampusEatery): the CampusEatery object to which to link the hours... | 625941ee5e10d32532c5f470 |
def match(self, line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not line.startswith( 'Max. memory (cumulated for all children) (KiB): '): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> val = line.split(':')[1].strip() <NEW_LINE> return (self.field, int(val)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> r... | From runsolver. | 625941ee099cdd3c635f11a3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.