code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
def map_data(self, screen_val): <NEW_LINE> <INDENT> self._compute_scale() <NEW_LINE> if self._null_screen_range: <NEW_LINE> <INDENT> return array([self.range.low]) <NEW_LINE> <DEDENT> elif self._null_data_range: <NEW_LINE> <INDENT> return array([self.range.low]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (screen_val - self.low_pos) / self._scale + self.range.low | map_data(screen_val) -> data_val
Overrides AbstractMapper. Maps values from screen space into data space. | 625941b9b5575c28eb68de81 |
def alluniqcharsinstr3(s): <NEW_LINE> <INDENT> r = sorted(s) <NEW_LINE> prev = '' <NEW_LINE> for c in r: <NEW_LINE> <INDENT> if c == prev: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> prev = c <NEW_LINE> <DEDENT> return True | Returns True if the given string contains only unique char, False otherwise
No other data structures are use
>>> print(alluniqcharsinstr2(''))
True
>>> print(alluniqcharsinstr2('abc'))
True
>>> print(alluniqcharsinstr2('aab'))
False | 625941b923849d37ff7b2f15 |
def run(self): <NEW_LINE> <INDENT> if self.id: <NEW_LINE> <INDENT> sys.stdout.buffer.write(b"Content-type: text/plain;charset=utf-8") <NEW_LINE> sys.stdout.buffer.write(b"\n\n") <NEW_LINE> sys.stdout.buffer.write(self.doc.xml.encode("utf-8")) <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> Controller.run(self) | Override router. | 625941b93617ad0b5ed67d83 |
def compute_volume(self): <NEW_LINE> <INDENT> return ConvexHull(self.coords).volume | Computes volume of a general polyhedron based on the convex hull of a set of points
:return: volume of the polyhedron | 625941b98e7ae83300e4ae4f |
def initialize(context): <NEW_LINE> <INDENT> install.register_wikid_plugin_class(context) | Initializer called when used as a Zope 2 product. | 625941b976e4537e8c3514fb |
def states(opts, functions): <NEW_LINE> <INDENT> module_dirs = [ os.path.join(distutils.sysconfig.get_python_lib(), 'salt/states'), ] + opts['states_dirs'] <NEW_LINE> load = Loader(module_dirs, opts) <NEW_LINE> pack = {'name': '__salt__', 'value': functions} <NEW_LINE> return load.gen_functions(pack) | Returns the returner modules | 625941b9d6c5a10208143ecb |
def test_sxz(self): <NEW_LINE> <INDENT> nouns = { 'bass': 'basses', 'bus': 'buses', 'walrus': 'walruses', 'box': 'boxes', 'fax': 'faxes', 'suffix': 'suffixes', 'mailbox': 'mailboxes', 'buzz': 'buzzes', 'waltz': 'waltzes' } <NEW_LINE> for singular, plural in nouns.items(): <NEW_LINE> <INDENT> self.assertEqual(plural4.plural(singular), plural) | parole che finiscono con S, X, o Z | 625941b9099cdd3c635f0ae0 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(BNSConstraints, self).__init__(**kwargs) | Initialize module. | 625941b931939e2706e4ccf3 |
def nitems_written(self, *args, **kwargs): <NEW_LINE> <INDENT> return _blocks_swig5.sample_and_hold_ii_sptr_nitems_written(self, *args, **kwargs) | nitems_written(sample_and_hold_ii_sptr self, unsigned int which_output) -> uint64_t | 625941b99b70327d1c4e0c57 |
def numPairsDivisibleBy60_error(self, time: List[int]) -> int: <NEW_LINE> <INDENT> hm = defaultdict(int) <NEW_LINE> for t in time: <NEW_LINE> <INDENT> hm[t % 60] += 1 <NEW_LINE> <DEDENT> ret = 0 <NEW_LINE> for k, v in hm.items(): <NEW_LINE> <INDENT> if k == 0: <NEW_LINE> <INDENT> ret += (v * (v - 1)) // 2 <NEW_LINE> <DEDENT> elif k <= 60 - k: <NEW_LINE> <INDENT> v2 = hm[60 - k] <NEW_LINE> ret += v2 * v <NEW_LINE> <DEDENT> <DEDENT> return ret | O(N^2) check i, j
Reduce it
O(N) by using hashmap, the key should mod 60
attribution error | 625941b91b99ca400220a934 |
def rates_and_algebraic(t, y): <NEW_LINE> <INDENT> t = np.atleast_1d(t) <NEW_LINE> imax = len(t) <NEW_LINE> y = np.array(y).view(float) <NEW_LINE> ydot = np.zeros_like(y) <NEW_LINE> a = np.zeros((imax, len(alg))) <NEW_LINE> for i in range(imax): <NEW_LINE> <INDENT> ydot[i] = computeRates(t[i], y[i], p) <NEW_LINE> if len(alg): <NEW_LINE> <INDENT> a[i] = computeAlgebraic(p, y[i], np.atleast_1d(t[i])).squeeze() <NEW_LINE> <DEDENT> <DEDENT> return ydot, a | Compute rates and algebraic variables for a given state trajectory.
Unfortunately, the CVODE machinery does not offer a way to return rates and
algebraic variables during integration. This function re-computes the rates
and algebraics at each time step for the given state.
This returns a simple float array;
:meth:`cgp.physmod.cellmlmodel.Cellmlmodel.rates_and_algebraic`
will cast them to structured arrays with named fields.
This version is pure Python;
:func:`~cgp.physmod.cythonize.cythonize`
will generate a faster version. | 625941b97cff6e4e81117809 |
def get_expect_payback_date(due_date): <NEW_LINE> <INDENT> payback_date = due_date + datetime.timedelta(days=1) <NEW_LINE> if payback_date.weekday() in transaction_close_weekday: <NEW_LINE> <INDENT> payback_date = get_next_monday(payback_date) <NEW_LINE> <DEDENT> while is_national_holiday(payback_date): <NEW_LINE> <INDENT> payback_date += datetime.timedelta(days=1) <NEW_LINE> <DEDENT> return payback_date | 从到期日时间计算出赎回日,包含了法定节假日等非到期日顺延规则. | 625941b9f548e778e58cd400 |
def getPresenceReason(self, deviceReport): <NEW_LINE> <INDENT> hasPresenceFailure = deviceReport.hasPresenceFailure(); <NEW_LINE> if hasPresenceFailure: <NEW_LINE> <INDENT> devicePresence, track = deviceReport.getPresence() <NEW_LINE> _, _, _, msg = track <NEW_LINE> return { "status": self.formatStatus(hasPresenceFailure), "message": msg} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | !
| 625941b93539df3088e2e1cf |
def DribbleOn(self, fn): <NEW_LINE> <INDENT> _c.env_dribbleOn(self.__env, fn) | enable dribble on given file | 625941b9566aa707497f43fd |
def all_names(self): <NEW_LINE> <INDENT> assert False, 'must override in subclass' | Iterate over all the names (basestring or multilang) that this
country has. | 625941b9498bea3a759b9934 |
def get_float(key, *default): <NEW_LINE> <INDENT> return get_env(key, *default, coerce=_float) | Return env var cast as float. | 625941b90a366e3fb873e69b |
def execute(self, props, pv_props, context): <NEW_LINE> <INDENT> profile = context.get('profile') or 'default' <NEW_LINE> format_commercial = pv_props.get('format_commercial') <NEW_LINE> if 'codec' in props and format_commercial and 'atmos' in format_commercial.lower(): <NEW_LINE> <INDENT> props['codec'] = [props['codec'], getattr(self.audio_codecs['ATMOS'], profile)] | Execute the rule against properties. | 625941b9711fe17d825421f6 |
def init_es(config={}): <NEW_LINE> <INDENT> global __es <NEW_LINE> __es = ElasticSearchHelper(config) | Set up the default DB instance a call to get_db() will return.
:param config: See DB() docs for config dict fields.
:returns: None. | 625941b999cbb53fe6792a6b |
def test012_get_memmory_details(self): <NEW_LINE> <INDENT> self.lg.info('get /nodes/{nodeid}/mem api.') <NEW_LINE> response = self.nodes_api.get_nodes_nodeid_mem(node_id=self.nodeid) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.lg.info('compare response data with the golden values.') <NEW_LINE> result = self.core0_client.get_nodes_mem() <NEW_LINE> memory_info = response.json() <NEW_LINE> for key in memory_info.keys(): <NEW_LINE> <INDENT> if key in result.keys(): <NEW_LINE> <INDENT> self.assertAlmostEqual(memory_info[key], result[key], msg="different keys%s" % key, delta=10000000) | GAT-012
*GET:/nodes/{nodeid}/mem *
**Test Scenario:**
#. Choose one random node from list of running nodes.
#. get /nodes/{nodeid}/mem api.
#. compare response data with the golden values. | 625941b926238365f5f0ecee |
def coloringSupported(): <NEW_LINE> <INDENT> return True | Returns True if coloring is supported in the current environment,
and False otherwise. | 625941b91b99ca400220a935 |
def _self_shield_dens(self,redshift, temp): <NEW_LINE> <INDENT> T4 = temp/1e4 <NEW_LINE> G12 = self.photo.gH0(redshift)/1e-12 <NEW_LINE> return 6.73e-3 * (self.Gray_ss(redshift) / 2.49e-18)**(-2./3)*(T4)**0.17*(G12)**(2./3)*(self.f_bar/0.17)**(-1./3) | Calculate the critical self-shielding density. Rahmati 202 eq. 13.
gray_opac is a parameter of the UVB used.
gray_opac is in cm^2 (2.49e-18 is HM01 at z=3)
temp is particle temperature in K
f_bar is the baryon fraction. 0.17 is roughly 0.045/0.265
Returns density in atoms/cm^3 | 625941b915baa723493c3df6 |
def normalize_dataset(dataset, minmax): <NEW_LINE> <INDENT> for row in dataset: <NEW_LINE> <INDENT> for i in range(len(row) - 1): <NEW_LINE> <INDENT> row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0]) | normaliza os dados do dataset | 625941b994891a1f4081b92c |
def test_connect_device_serial_number_already_connected(self): <NEW_LINE> <INDENT> n_devices = 2 <NEW_LINE> serial_number = "54321" <NEW_LINE> id1 = AvsIdentity( bytes(str(serial_number), "ascii"), b"Fake Spectrograph 2", AvsDeviceStatus.USB_IN_USE_BY_OTHER.value, ) <NEW_LINE> def mock_getList(a_listSize, a_pRequiredSize, a_pList): <NEW_LINE> <INDENT> a_pList[:] = [self.id0, id1] <NEW_LINE> return n_devices <NEW_LINE> <DEDENT> self.patch.return_value.AVS_GetList.side_effect = mock_getList <NEW_LINE> self.patch.return_value.AVS_UpdateUSBDevices.return_value = n_devices <NEW_LINE> with pytest.raises( RuntimeError, match="Requested AVS device is already in use" ): <NEW_LINE> <INDENT> AvsFiberSpectrograph(serial_number=serial_number) <NEW_LINE> <DEDENT> self.patch.return_value.AVS_UpdateUSBDevices.assert_called_once() <NEW_LINE> self.patch.return_value.AVS_GetList.assert_called_once() <NEW_LINE> self.patch.return_value.AVS_Activate.assert_not_called() | Test that connect raises if the device requested by serial number
claims to already be connected in its AvsIdentity field. | 625941b9d10714528d5ffb64 |
def fight_round(p1, p2, p1move=None, p2move=None): <NEW_LINE> <INDENT> if not p1move: <NEW_LINE> <INDENT> p1move = p1.random_move() <NEW_LINE> <DEDENT> if not p2move: <NEW_LINE> <INDENT> p2move = p2.random_move() <NEW_LINE> <DEDENT> p1sp = random.randint(0, 10) + p1.speed <NEW_LINE> p2sp = random.randint(0, 10) + p2.speed <NEW_LINE> if p1sp > p2sp: <NEW_LINE> <INDENT> if strategy_attack(p1, p2, move=p1move): <NEW_LINE> <INDENT> return p2 <NEW_LINE> <DEDENT> if strategy_attack(p2, p1, move=p2move): <NEW_LINE> <INDENT> return p1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if strategy_attack(p2, p1, move=p2move): <NEW_LINE> <INDENT> return p1 <NEW_LINE> <DEDENT> if strategy_attack(p1, p2, move=p1move): <NEW_LINE> <INDENT> return p2 <NEW_LINE> <DEDENT> <DEDENT> return None | Handles one fight turn.
Returns whoever faints first, or None. | 625941b94a966d76dd550e91 |
def contains(self, item): <NEW_LINE> <INDENT> if self.__elements_type is None or type(item) == self.__elements_type: <NEW_LINE> <INDENT> return item in self.__elements <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StackTypeError("The parameter {0} is not of type {1}.".format(item, self.__elements_type)) | this method checks if a value is contained in the stack
:param item: the value to search for in the stack
:return: True if the value is contained in the list with elements of the stack and False otherwise
:raises StackTypeError: if the type of the Stack object is specified and is different from the type of the 'item'
argument used when calling this method | 625941b9596a89723608994e |
def get_default_branch(self): <NEW_LINE> <INDENT> if self.default_branch: <NEW_LINE> <INDENT> return self.default_branch <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.vcs_repo().fallback_branch | Get the version representing "latest" | 625941b9e8904600ed9f1dad |
def add_node(self, node, parent=None): <NEW_LINE> <INDENT> if not isinstance(node, Node): <NEW_LINE> <INDENT> raise OSError("First parameter must be object of Class::Node.") <NEW_LINE> <DEDENT> if node.identifier in self.nodes: <NEW_LINE> <INDENT> node = self.get_node(node.identifier) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nodes.update({node.identifier : node}) <NEW_LINE> <DEDENT> if parent is None: <NEW_LINE> <INDENT> if self.root is not None: <NEW_LINE> <INDENT> raise MultipleRootError <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.root = node.identifier <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> parent = Node.sanitize_id(parent) <NEW_LINE> <DEDENT> self.__update_fpointer(parent, node.identifier, Node.ADD) <NEW_LINE> self.__update_bpointer(parent, node.identifier, Node.ADD) | Add a new node to tree.
The 'node' parameter refers to an instance of Class::Node | 625941b9c432627299f04ac8 |
def draw_treasure(self): <NEW_LINE> <INDENT> for row in range(ROWS): <NEW_LINE> <INDENT> for col in range(COLUMNS): <NEW_LINE> <INDENT> if self.map.treasure[row][col] != 0: <NEW_LINE> <INDENT> treasure = pygame.image.load(IMG_DIR + 'chest.png') <NEW_LINE> self.screen.blit(treasure, (row*TILE_SIZE, col*TILE_SIZE)) | Draws the treasure chests yet to be opened.
| 625941b98e71fb1e9831d631 |
def put_element_variable_values(self, blockId, name, step, values): <NEW_LINE> <INDENT> self.put_variable_values('EX_ELEM_BLOCK', blockId, name, step, values) <NEW_LINE> return True | store a list of element variable values for a specified element
block, element variable name, and time step
>>> status = exo.put_element_variable_values(elem_blk_id,
... evar_name, time_step, evar_vals)
Parameters
----------
elem_blk_id : int
element block *ID* (not *INDEX*)
<string> evar_name name of element variable
<int> time_step 1-based index of time step
<list<float>> evar_vals
Returns
-------
status : bool
True = successful execution | 625941b9377c676e9127202e |
def openebl(mapping={}): <NEW_LINE> <INDENT> print('> Reading EBL mappings...') <NEW_LINE> with gzip.open(EBL, 'rt', encoding='utf-8', errors='ignore') as data: <NEW_LINE> <INDENT> for line in data.read().splitlines(): <NEW_LINE> <INDENT> lemma, no, trans, olemma, otrans = line.split('\t') <NEW_LINE> if olemma: <NEW_LINE> <INDENT> key = olemma + '[' + otrans + ']' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key = lemma + '[' + otrans + ']' <NEW_LINE> <DEDENT> mapping[key] = lemma.replace("'", 'ʾ') + '_' + no <NEW_LINE> <DEDENT> return mapping | Dictionary-based EBL mappings | 625941b9e64d504609d746c5 |
def dist_convert(distance, units="m"): <NEW_LINE> <INDENT> if units=='m': <NEW_LINE> <INDENT> return miles_to_kilometers(distance) <NEW_LINE> <DEDENT> if units=='k': <NEW_LINE> <INDENT> return kilometers_to_miles(distance) | PARAMETERS
---------
distance : (float)
distance in specified "units"
units : (string)
"m" for miles or "k" for kilometers
RETURNS
---------
distance : (float)
distance in desired units | 625941b92ae34c7f2600cfb6 |
def _get_fourier_filter(size, filter_name): <NEW_LINE> <INDENT> n = np.concatenate((np.arange(1, size / 2 + 1, 2, dtype=int), np.arange(size / 2 - 1, 0, -2, dtype=int))) <NEW_LINE> f = np.zeros(size) <NEW_LINE> f[0] = 0.25 <NEW_LINE> f[1::2] = -1 / (np.pi * n) ** 2 <NEW_LINE> fourier_filter = 2 * np.real(fft(f)) <NEW_LINE> if filter_name == "ramp": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif filter_name == "shepp-logan": <NEW_LINE> <INDENT> omega = np.pi * fftfreq(size)[1:] <NEW_LINE> fourier_filter[1:] *= np.sin(omega) / omega <NEW_LINE> <DEDENT> elif filter_name == "cosine": <NEW_LINE> <INDENT> freq = np.linspace(0, np.pi, size, endpoint=False) <NEW_LINE> cosine_filter = fftshift(np.sin(freq)) <NEW_LINE> fourier_filter *= cosine_filter <NEW_LINE> <DEDENT> elif filter_name == "hamming": <NEW_LINE> <INDENT> fourier_filter *= fftshift(np.hamming(size)) <NEW_LINE> <DEDENT> elif filter_name == "hann": <NEW_LINE> <INDENT> fourier_filter *= fftshift(np.hanning(size)) <NEW_LINE> <DEDENT> elif filter_name is None: <NEW_LINE> <INDENT> fourier_filter[:] = 1 <NEW_LINE> <DEDENT> return fourier_filter[:, np.newaxis] | Construct the Fourier filter.
This computation lessens artifacts and removes a small bias as
explained in [1], Chap 3. Equation 61.
Parameters
----------
size : int
filter size. Must be even.
filter_name : str
Filter used in frequency domain filtering. Filters available:
ramp, shepp-logan, cosine, hamming, hann. Assign None to use
no filter.
Returns
-------
fourier_filter: ndarray
The computed Fourier filter.
References
----------
.. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
Imaging", IEEE Press 1988. | 625941b931939e2706e4ccf4 |
def insertionSortList(self, head): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> sorted_head, sorted_end = head, head <NEW_LINE> current = head.next <NEW_LINE> head.next = None <NEW_LINE> while current: <NEW_LINE> <INDENT> current_next = current.next <NEW_LINE> if current.val < sorted_head.val: <NEW_LINE> <INDENT> current.next = sorted_head <NEW_LINE> sorted_head = current <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sorted_prev, sorted_current = sorted_head, sorted_head.next <NEW_LINE> while sorted_current: <NEW_LINE> <INDENT> if sorted_current.val > current.val: <NEW_LINE> <INDENT> sorted_prev.next = current <NEW_LINE> current.next = sorted_current <NEW_LINE> break <NEW_LINE> <DEDENT> sorted_prev, sorted_current = sorted_current, sorted_current.next <NEW_LINE> <DEDENT> if current.val >= sorted_end.val: <NEW_LINE> <INDENT> current.next = None <NEW_LINE> sorted_end.next = current <NEW_LINE> sorted_end = current <NEW_LINE> <DEDENT> <DEDENT> current = current_next <NEW_LINE> <DEDENT> return sorted_head | :type head: ListNode
:rtype: ListNode | 625941b999fddb7c1c9de217 |
def increment_index(self): <NEW_LINE> <INDENT> self._index += 1 | Increment index.
Increment index value after finished processing the current subfile from
current file. | 625941b9187af65679ca4fa2 |
def model(): <NEW_LINE> <INDENT> model = keras.models.Sequential() <NEW_LINE> model.add(keras.layers.Dense(32, activation='relu')) <NEW_LINE> model.add(keras.layers.Dropout(0.2)) <NEW_LINE> model.add(keras.layers.Dense(64, activation='relu')) <NEW_LINE> model.add(keras.layers.Dropout(0.2)) <NEW_LINE> model.add(keras.layers.Dense(1, activation='sigmoid')) <NEW_LINE> model.compile(optimizer=keras.optimizers.RMSprop(), loss=keras.losses.binary_crossentropy, metrics=['acc']) <NEW_LINE> return model | 定义模型
:return: keras model | 625941b97047854f462a1291 |
def test_predict_2_classes(): <NEW_LINE> <INDENT> check_predictions(MLPClassifier(**KWARGS), X, Y1) <NEW_LINE> check_predictions(MLPClassifier(**KWARGS), X_sp, Y1) | Test binary classification. | 625941b94f88993c3716bef8 |
def str_match(arr, pat, case=True, flags=0, na=np.nan, as_indexer=False): <NEW_LINE> <INDENT> if not case: <NEW_LINE> <INDENT> flags |= re.IGNORECASE <NEW_LINE> <DEDENT> regex = re.compile(pat, flags=flags) <NEW_LINE> if (not as_indexer) and regex.groups > 0: <NEW_LINE> <INDENT> warnings.warn("In future versions of pandas, match will change to" " always return a bool indexer.", UserWarning) <NEW_LINE> <DEDENT> if as_indexer and regex.groups > 0: <NEW_LINE> <INDENT> warnings.warn("This pattern has match groups. To actually get the" " groups, use str.extract.", UserWarning) <NEW_LINE> <DEDENT> if (not as_indexer) and regex.groups > 0: <NEW_LINE> <INDENT> dtype = object <NEW_LINE> def f(x): <NEW_LINE> <INDENT> m = regex.match(x) <NEW_LINE> if m: <NEW_LINE> <INDENT> return m.groups() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> dtype = bool <NEW_LINE> f = lambda x: bool(regex.match(x)) <NEW_LINE> <DEDENT> return _na_map(f, arr, na, dtype=dtype) | Deprecated: Find groups in each string in the Series/Index
using passed regular expression.
If as_indexer=True, determine if each string matches a regular expression.
Parameters
----------
pat : string
Character sequence or regular expression
case : boolean, default True
If True, case sensitive
flags : int, default 0 (no flags)
re module flags, e.g. re.IGNORECASE
na : default NaN, fill value for missing values.
as_indexer : False, by default, gives deprecated behavior better achieved
using str_extract. True return boolean indexer.
Returns
-------
Series/array of boolean values
if as_indexer=True
Series/Index of tuples
if as_indexer=False, default but deprecated
See Also
--------
contains : analagous, but less strict, relying on re.search instead of
re.match
extract : now preferred to the deprecated usage of match (as_indexer=False)
Notes
-----
To extract matched groups, which is the deprecated behavior of match, use
str.extract. | 625941b9004d5f362079a1bb |
def get_content(self, identifier): <NEW_LINE> <INDENT> post_author, post_permlink = resolveIdentifier(identifier) <NEW_LINE> return Post(self, self.rpc.get_content(post_author, post_permlink)) | Get the full content of a post.
:param str identifier: Identifier for the post to upvote Takes
the form ``@author/permlink`` | 625941b98e7ae83300e4ae50 |
def predict_premium(model, X_raw): <NEW_LINE> <INDENT> return predict_expected_claim(model, X_raw) + 2 | Model prediction function: predicts premiums based on the pricing model.
This function outputs the prices that will be offered to the contracts in X_raw.
premium will typically depend on the expected claim predicted in
predict_expected_claim, and will add some pricing strategy on top.
This is the function used in the expected profit leaderboard. Prices output here will
be used in competition with other models, so feel free to use a pricing strategy.
Parameters
----------
model: a Python object that describes your model. This can be anything, as long
as it is consistent with what `fit` outpurs.
X_raw : Pandas dataframe, with the columns described in the data dictionary.
Each row is a different contract. This data has not been processed.
Returns
-------
prices: a one-dimensional Numpy array of the same length as X_raw, with one
price per contract (in same order). These prices must be POSITIVE (>0). | 625941b98c0ade5d55d3e844 |
def parse_server(server, as_string=False): <NEW_LINE> <INDENT> if as_string: <NEW_LINE> <INDENT> return '%s:%d' % parse_server(server) <NEW_LINE> <DEDENT> if not isinstance(server, (list, tuple)): <NEW_LINE> <INDENT> return parse_server(server.split(':')) <NEW_LINE> <DEDENT> if len(server) == 1: <NEW_LINE> <INDENT> return (server[0], DEFAULT.PORT) <NEW_LINE> <DEDENT> elif len(server) == 2: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> port = int(server[1]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ParseError('Port must be a positive integer. Received `%s`' % server[1]) <NEW_LINE> <DEDENT> if port > 0: <NEW_LINE> <INDENT> return (server[0], port) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ParseError('Port must be a positive integer. Received `%d`' % port) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ParseError('Don\'t know what to do with `%s`' % str(server)) | Returns a (server, port) tuple filled with informations taken from the
*server* argument. If *as_string* is set to True, returns a `server:port`
string instead. | 625941b97d847024c06be145 |
def _end_Hsp_identity(self): <NEW_LINE> <INDENT> self._hsp.identities = int(self._value) | Record the number of identities in the alignment (PRIVATE). | 625941b97cff6e4e8111780a |
def poutput(self, msg, end='\n'): <NEW_LINE> <INDENT> if msg is not None and msg != '': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg_str = '{}'.format(msg) <NEW_LINE> first=True <NEW_LINE> for line in msg_str.split('\n'): <NEW_LINE> <INDENT> self.app.win.console.echo(line, style="fore:f5f5f5", ) <NEW_LINE> first=False <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> if self.broken_pipe_warning: <NEW_LINE> <INDENT> sys.stderr.write(self.broken_pipe_warning) | Adata override of cmd2.Cmd.poutput method: print to console.
| 625941b9ec188e330fd5a62a |
def produce_random_port(ip): <NEW_LINE> <INDENT> port = random.randint(20001, 65534) <NEW_LINE> while is_port_used(ip, port): <NEW_LINE> <INDENT> port = random.randint(20001, 65534) <NEW_LINE> <DEDENT> p1 = int(port / 256) <NEW_LINE> p2 = port - p1 * 256 <NEW_LINE> return (p1, p2) | :param ip:主机的ip
生成随机的端口号,且保证端口号未被占用
:return: | 625941b9d7e4931a7ee9dda0 |
def get_project_id(self, project_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = self.server.getGroupsByName(self.session, [project_name]) <NEW_LINE> id = ret[0]['group_id'] <NEW_LINE> return id <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return -1 | Return the project id (formely the group_id) for a particular name
Return -1 if failed | 625941b97b180e01f3dc468a |
@command("kill", chan=False, pm=True, playing=True, silenced=True, phases=("night",), roles=("dullahan",)) <NEW_LINE> def dullahan_kill(wrapper: MessageDispatcher, message: str): <NEW_LINE> <INDENT> var = wrapper.game_state <NEW_LINE> if not TARGETS[wrapper.source] & set(get_players(var)): <NEW_LINE> <INDENT> wrapper.pm(messages["dullahan_targets_dead"]) <NEW_LINE> return <NEW_LINE> <DEDENT> target = get_target(wrapper, re.split(" +", message)[0], not_self_message="no_suicide") <NEW_LINE> if not target: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> orig = target <NEW_LINE> target = try_misdirection(var, wrapper.source, target) <NEW_LINE> if try_exchange(var, wrapper.source, target): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> KILLS[wrapper.source] = target <NEW_LINE> wrapper.pm(messages["player_kill"].format(orig)) | Kill someone at night as a dullahan until everyone on your list is dead. | 625941b926068e7796caeb5d |
def benchmark_fp16_synth_forward_batch16(self): <NEW_LINE> <INDENT> params = self._shared_params()._replace(batch_size=16, use_fp16=True) <NEW_LINE> self._run_benchmark(params) | Tests 1 GPU batch size 16 FP16. | 625941b97b25080760e392df |
def example1(): <NEW_LINE> <INDENT> print("EXAMPLE 1:") <NEW_LINE> lines = filter_blank_lines(SAMPLE_INPUT.split("\n")) <NEW_LINE> result = solve(lines) <NEW_LINE> expected = 0 <NEW_LINE> print(f"'sample-input' -> {result} (expected {expected})") <NEW_LINE> assert result == expected <NEW_LINE> print("= " * 32) | Run example for problem with input lines. | 625941b99c8ee82313fbb5f9 |
def _plotTrendChannel(self, df, ax, xIndex): <NEW_LINE> <INDENT> def _plotLine(twoPoints): <NEW_LINE> <INDENT> x = [] <NEW_LINE> for i in twoPoints.index: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> x_ = xIndex.get_loc(i) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> x_ = None <NEW_LINE> <DEDENT> x.append(x_) <NEW_LINE> <DEDENT> ax.plot(x, twoPoints.values, '-', color='#FF6100', linewidth=2) <NEW_LINE> try: <NEW_LINE> <INDENT> y = twoPoints.values <NEW_LINE> xExtendPoint = xIndex.get_loc(df.index[-1]) <NEW_LINE> yExtendPoint = (y[1] - y[0])/(x[1] - x[0]) * (xExtendPoint - x[1]) + y[1] <NEW_LINE> ax.plot([x[1], xExtendPoint], [y[1], yExtendPoint], '-', color='#FF6100', linewidth=2) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> up, down = DyStockDataML.trendChannel(df, DyStockCommon.rollingWindowW) <NEW_LINE> if up is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> _plotLine(up) <NEW_LINE> _plotLine(down) | 绘制@df的趋势通道
@ax: matplotlib subplot axis
@xIndex: 子图的x坐标值,X轴位时间 | 625941b938b623060ff0ac74 |
def parse_request_from_query_params(params, url): <NEW_LINE> <INDENT> request = f'{url} ' + (' OR '.join(params.keys())) <NEW_LINE> return request | create a string request from the query params
:param params: the parameters we seek data from
:param url: the url of the company we search data for.
:return: string for google request | 625941b93539df3088e2e1d0 |
def _is_null_datelike_scalar(other): <NEW_LINE> <INDENT> return (np.isscalar(other) and (isnull(other) or other == tslib.iNaT)) or other is pd.NaT or other is None | test whether the object is a null datelike, e.g. Nat
but guard against passing a non-scalar | 625941b98c3a873295158243 |
def build_model(): <NEW_LINE> <INDENT> model = Sequential() <NEW_LINE> model.add(Lambda(lambda x: (x / 255.) - 0.5, input_shape=(160, 320, 3))) <NEW_LINE> model.add(Cropping2D(cropping=((50, 20), (0, 0)))) <NEW_LINE> model.add(Convolution2D(16, 5, 5)) <NEW_LINE> model.add(MaxPooling2D((5, 5))) <NEW_LINE> model.add(Dropout(0.1)) <NEW_LINE> model.add(Activation('relu')) <NEW_LINE> model.add(Convolution2D(32, 5, 5)) <NEW_LINE> model.add(MaxPooling2D((5, 5))) <NEW_LINE> model.add(Dropout(0.1)) <NEW_LINE> model.add(Activation('relu')) <NEW_LINE> model.add(Flatten()) <NEW_LINE> model.add(Dense(128)) <NEW_LINE> model.add(Dropout(0.2)) <NEW_LINE> model.add(Activation('relu')) <NEW_LINE> model.add(Dense(1)) <NEW_LINE> model.compile(loss='mse', optimizer='adam') <NEW_LINE> return model | Definition of the Deep Learning model. The following architecture is implemented :
- Normalizaiton layer
- Image cropping layer
- Convolution layer with 16 filters of size (5,5)
- Max Pooling with a filter of size (5,5)
- Dropout with a dropout rate of 10%
- ReLu activation
- Convolution layer with 32 filters of size (5,5)
- Max Pooling with a filter of size (5,5)
- Dropout with a dropout rate of 10%
- ReLu activation
- Dense layer with 128 hidden units
- Dropout with a dropout rate of 20%
- ReLu activation
- Linear layer to compute the output.
The loss function used is Mean Square Error. The optimizer is adam with default parameters.
:return: the keras model | 625941b9fff4ab517eb2f2be |
@click.command() <NEW_LINE> @click.argument('name', default='smile') <NEW_LINE> def emote(name): <NEW_LINE> <INDENT> if name == 'list': <NEW_LINE> <INDENT> list_emoticons() <NEW_LINE> return <NEW_LINE> <DEDENT> string = emoticons.get(name) <NEW_LINE> if not string: <NEW_LINE> <INDENT> print(f"Sorry, {name!r} unknown. Try 'emote list'.") <NEW_LINE> return <NEW_LINE> <DEDENT> xerox.copy(string) | Return named emoticon on the clipboard. | 625941b9ac7a0e7691ed3f5e |
def _row_generator(self, select_cursor, arraysize): <NEW_LINE> <INDENT> outer_cursor = None <NEW_LINE> with select_cursor() as cursor: <NEW_LINE> <INDENT> outer_cursor = cursor <NEW_LINE> rowset = cursor.fetchmany(arraysize) <NEW_LINE> while rowset: <NEW_LINE> <INDENT> for row in rowset: <NEW_LINE> <INDENT> yield row <NEW_LINE> <DEDENT> rowset = cursor.fetchmany(arraysize) <NEW_LINE> <DEDENT> <DEDENT> self.assertTrue(outer_cursor.closed) | Yields individual rows until no more rows exist in query result.
:param select_cursor: Object which delivers closeable psycopg2 cursor
context on call.
:type select_cursor: QueryCursor object. | 625941b9627d3e7fe0d68cd3 |
def TupleTag(group_elem: Tuple[int, int]) -> BaseTag: <NEW_LINE> <INDENT> long_value = group_elem[0] << 16 | group_elem[1] <NEW_LINE> return BaseTag(long_value) | Fast factory for :class:`BaseTag` object with known safe (group, elem)
:class:`tuple` | 625941b966656f66f7cbc02f |
def lazy_property(fn): <NEW_LINE> <INDENT> attr_name = '_lazy_' + fn.__name__ <NEW_LINE> @property <NEW_LINE> def _lazy_property(self): <NEW_LINE> <INDENT> if not hasattr(self, attr_name): <NEW_LINE> <INDENT> setattr(self, attr_name, fn(self)) <NEW_LINE> <DEDENT> return getattr(self, attr_name) <NEW_LINE> <DEDENT> return _lazy_property | Decorator that makes a property lazy-evaluated
From http://stevenloria.com/lazy-evaluated-properties-in-python/ | 625941b963b5f9789fde6f6a |
def get_closest(nums, my_num): <NEW_LINE> <INDENT> pos = bisect_left(nums, my_num) <NEW_LINE> if pos == 0: <NEW_LINE> <INDENT> return nums[0] <NEW_LINE> <DEDENT> if pos == len(nums): <NEW_LINE> <INDENT> return nums[-1] <NEW_LINE> <DEDENT> before = nums[pos - 1] <NEW_LINE> after = nums[pos] <NEW_LINE> if after - my_num < my_num - before: <NEW_LINE> <INDENT> return after <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return before | If two numbers are equally close, return the smaller number. | 625941b9fb3f5b602dac3514 |
def test_get_group_type_education(self): <NEW_LINE> <INDENT> group_entry = MockObjects.mock_group("Some_Group") <NEW_LINE> education_entry = MockObjects.mock_education_entry('Something') <NEW_LINE> group_entry.save() <NEW_LINE> education_entry.save() <NEW_LINE> group_entry.add_entry(education_entry) <NEW_LINE> self.assertEqual(group_entry.get_group_type_str(), "EducationEntry") | Testing get_group_type when group has education entries. | 625941b9d53ae8145f87a0fb |
def overlap_and_add(signal, frame_step, name=None): <NEW_LINE> <INDENT> with ops.name_scope(name, "overlap_and_add", [signal, frame_step]): <NEW_LINE> <INDENT> signal = ops.convert_to_tensor(signal, name="signal") <NEW_LINE> signal.shape.with_rank_at_least(2) <NEW_LINE> frame_step = ops.convert_to_tensor(frame_step, name="frame_step") <NEW_LINE> frame_step.shape.assert_has_rank(0) <NEW_LINE> if not frame_step.dtype.is_integer: <NEW_LINE> <INDENT> raise ValueError("frame_step must be an integer. Got %s" % frame_step.dtype) <NEW_LINE> <DEDENT> signal_shape = array_ops.shape(signal) <NEW_LINE> outer_dimensions = signal_shape[:-2] <NEW_LINE> frame_step_static = tensor_util.constant_value(frame_step) <NEW_LINE> if (frame_step_static is not None and signal.shape.ndims is not None and signal.shape[-1].value is not None): <NEW_LINE> <INDENT> if frame_step_static > signal.shape[-1].value: <NEW_LINE> <INDENT> raise ValueError( "frame_step (%d) must be less than or equal to " "frame_length (%d)" % ( frame_step_static, signal.shape[-1].value)) <NEW_LINE> <DEDENT> if frame_step_static == signal.shape[-1].value: <NEW_LINE> <INDENT> return array_ops.reshape(signal, array_ops.concat( [outer_dimensions, [-1]], 0)) <NEW_LINE> <DEDENT> <DEDENT> signal_rank = array_ops.rank(signal) <NEW_LINE> frames = signal_shape[-2] <NEW_LINE> frame_length = signal_shape[-1] <NEW_LINE> subframe_length = util_ops.gcd(frame_length, frame_step) <NEW_LINE> subframe_step = frame_step // subframe_length <NEW_LINE> subframes_per_frame = frame_length // subframe_length <NEW_LINE> output_size = frame_step * (frames - 1) + frame_length <NEW_LINE> output_subframes = output_size // subframe_length <NEW_LINE> subframe_shape = array_ops.concat( [outer_dimensions, [-1, subframe_length]], 0) <NEW_LINE> subframe_signal = array_ops.reshape(signal, subframe_shape) <NEW_LINE> subframe_signal = _shuffle_to_front(subframe_signal, 2) <NEW_LINE> segment_ids = array_ops.reshape(shape_ops.frame( math_ops.range(output_subframes), subframes_per_frame, subframe_step, pad_end=False), [-1]) <NEW_LINE> result = math_ops.unsorted_segment_sum(subframe_signal, segment_ids, num_segments=output_subframes) <NEW_LINE> result_shape = array_ops.concat([outer_dimensions, [output_size]], 0) <NEW_LINE> return array_ops.reshape(_shuffle_to_front(result, signal_rank - 2), result_shape) | Reconstructs a signal from a framed representation.
Adds potentially overlapping frames of a signal with shape
`[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`.
The resulting tensor has shape `[..., output_size]` where
output_size = (frames - 1) * frame_step + frame_length
Args:
signal: A [..., frames, frame_length] `Tensor`. All dimensions may be
unknown, and rank must be at least 2.
frame_step: An integer or scalar `Tensor` denoting overlap offsets. Must be
less than or equal to `frame_length`.
name: An optional name for the operation.
Returns:
A `Tensor` with shape `[..., output_size]` containing the overlap-added
frames of `signal`'s inner-most two dimensions.
Raises:
ValueError: If `signal`'s rank is less than 2, `frame_step` is not a scalar
integer or `frame_step` is greater than `frame_length`. | 625941b9adb09d7d5db6c618 |
def parallel_coordinates( data_frame=None, dimensions=None, color=None, labels={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, title=None, template=None, width=None, height=None, ): <NEW_LINE> <INDENT> return make_figure(args=locals(), constructor=go.Parcoords) | In a parallel coordinates plot, each row of `data_frame` is represented
by a polyline mark which traverses a set of parallel axes, one for each
of the `dimensions`. | 625941b915fb5d323cde098f |
def get_queue(self, guild_id): <NEW_LINE> <INDENT> queue = self.queues.get(guild_id, Queue()) <NEW_LINE> self.queues.update({guild_id: queue}) <NEW_LINE> return queue | Gets a guild's queue.
If the guild doesn't have one, it'll be generated.
:type guild_id: int
:rtype: asyncio.Queue | 625941b9b57a9660fec33705 |
def selected_staged_paths(self, selection=None): <NEW_LINE> <INDENT> if selection is None: <NEW_LINE> <INDENT> selection = self.selected_paths() <NEW_LINE> <DEDENT> staged = utils.add_parents(main.model().staged) <NEW_LINE> return [p for p in selection if p in staged] | Return selected staged paths. | 625941b92ae34c7f2600cfb7 |
def __rewind__(self): <NEW_LINE> <INDENT> if self._last_offset is not None: <NEW_LINE> <INDENT> self._offset = self._last_offset <NEW_LINE> self.f.seek(self._last_offset) | Rewind to previous offset position | 625941b991f36d47f21ac37b |
def main(event, lambda_context): <NEW_LINE> <INDENT> state_path = os.path.join(CWD, "states.yml") <NEW_LINE> os.environ["LAZYSUSAN_SESSION_STORAGE_BACKEND"] = "memory" <NEW_LINE> app = LazySusanApp(state_path, session_key="JOKES_STATE") <NEW_LINE> response = app.handle(event) <NEW_LINE> return response | Main handler which receives initial request from Lambda.
Route the incoming request based on type LaunchRequest, IntentRequest, etc.).
:attr event: JSON payload which is sent from the Alexa service, containing relevant
info about the request
:attr context: Lambda context | 625941b95f7d997b87174920 |
def pvremove(device): <NEW_LINE> <INDENT> return subproc.check_call( [ 'lvm', 'pvremove', '--force', device, ] ) | Remove LVM physical volume.
| 625941b9507cdc57c6306b59 |
def should_save(self): <NEW_LINE> <INDENT> if super().should_save(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for _, step in self.items(): <NEW_LINE> <INDENT> if step.should_save(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Returns if the step needs to be saved or not.
:return: If self or any of his sub steps should be saved, returns True.
.. seealso::
:class:`TruncableJoblibStepSaver` | 625941b9a05bb46b383ec6b2 |
def test_validate_range_bad(self): <NEW_LINE> <INDENT> t = configtypes.String(minlen=2, maxlen=3) <NEW_LINE> with self.assertRaises(configtypes.ValidationError): <NEW_LINE> <INDENT> t.validate('f') <NEW_LINE> <DEDENT> with self.assertRaises(configtypes.ValidationError): <NEW_LINE> <INDENT> t.validate('fooo') | Test validate with both min/maxlen and a bad string. | 625941b9e1aae11d1e749b39 |
def _get_argtype(self, argument): <NEW_LINE> <INDENT> argtype = type(argument) <NEW_LINE> return argtype <NEW_LINE> if isinstance(argument, builtins.int) and argtype != bool: <NEW_LINE> <INDENT> argtype = int <NEW_LINE> <DEDENT> return argtype | Returns the argument type that will be passed to
the QMetaObject.invokeMethod call.
Most types pass okay, but enums don't so they have
to be coerced to ints. An enum is currently detected
as a type that is not a bool and inherits from int | 625941b9d7e4931a7ee9dda1 |
def start(self,page_num): <NEW_LINE> <INDENT> content = self.__calculate_content(page_num) <NEW_LINE> return content | 返回第一页的内容 | 625941b923e79379d52ee3ed |
def write_to_file(file_name, url): <NEW_LINE> <INDENT> with open(file_name, 'a') as myfile: <NEW_LINE> <INDENT> myfile.write('{}\n'.format(url)) | This function writes the received url to the received file name. | 625941b971ff763f4b549514 |
def bucketSort(arr): <NEW_LINE> <INDENT> buckets = [[] for i in range(101)] <NEW_LINE> for elem in arr: <NEW_LINE> <INDENT> buckets[elem // 10].append(elem) <NEW_LINE> <DEDENT> for lst in buckets: <NEW_LINE> <INDENT> insertSort(lst) <NEW_LINE> <DEDENT> arr.clear() <NEW_LINE> for lst in buckets: <NEW_LINE> <INDENT> arr += lst | 桶排序 | 625941b9b5575c28eb68de83 |
def load_video_from_file(self, filename): <NEW_LINE> <INDENT> cap = cv2.VideoCapture(filename) <NEW_LINE> self.read_buffer = cap | Load a video file into the engine and set a read buffer | 625941b94527f215b584c2e0 |
def get_build_dir(*append): <NEW_LINE> <INDENT> return __get_root('build', *append) | Returns 'build' directory for Desktop.
This is used for temporary (and testing) artifacts.
This is not the root source path. | 625941b95166f23b2e1a4fde |
def __init__(self, filters, strides, relu_leakiness, name): <NEW_LINE> <INDENT> self.filters = filters <NEW_LINE> self.strides = strides <NEW_LINE> self.relu_leakiness = relu_leakiness <NEW_LINE> self.in_filter = None <NEW_LINE> assert len(strides) == len(filters) <NEW_LINE> super(DCGAN.Discriminator, self).__init__(name) | Constructs the discriminator of a DCGAN
Parameters
----------
filters : list or tuple
filters for convolutional layers
strides : list or tuple
strides to be used for convolutions
relu_leakiness : float
leakines of relu nonlinearity
name : string
name of the network | 625941b9462c4b4f79d1d556 |
def to_params(self, p): <NEW_LINE> <INDENT> return np.atleast_1d(p).view(self.dtype).squeeze() | Returns a view of the array ``p`` with named columns corresponding
to the parameters of the lens model: ``log_m200`` and
``log_c`` (both natural logs). | 625941b9435de62698dfdad9 |
def minimumTotal_dp2(self, triangle): <NEW_LINE> <INDENT> dp = [[float('inf')] * len(triangle[-1]) for _ in range(len(triangle))] <NEW_LINE> dp[0][0] = triangle[0][0] <NEW_LINE> for i in range(1, len(triangle)): <NEW_LINE> <INDENT> for j in range(i + 1): <NEW_LINE> <INDENT> if j == 0: <NEW_LINE> <INDENT> dp[i][j] = dp[i-1][0] + triangle[i][j] <NEW_LINE> <DEDENT> elif j == i: <NEW_LINE> <INDENT> dp[i][j] = dp[i-1][j-1] + triangle[i][j] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dp[i][j] = min(dp[i-1][j-1] + triangle[i][j], dp[i-1][j] + triangle[i][j]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return min(dp[-1]) | :type triangle: List[List[int]]
:rtype: int | 625941b93617ad0b5ed67d85 |
def to_future(self, future_ctor=None): <NEW_LINE> <INDENT> future_ctor = future_ctor or rx.config.get("Future") <NEW_LINE> if not future_ctor: <NEW_LINE> <INDENT> raise Exception('Future type not provided nor in rx.config.Future') <NEW_LINE> <DEDENT> source = self <NEW_LINE> future = future_ctor() <NEW_LINE> value = [None] <NEW_LINE> has_value = [False] <NEW_LINE> def on_next(v): <NEW_LINE> <INDENT> value[0] = v <NEW_LINE> has_value[0] = True <NEW_LINE> <DEDENT> def on_error(err): <NEW_LINE> <INDENT> future.set_exception(err) <NEW_LINE> <DEDENT> def on_completed(): <NEW_LINE> <INDENT> if has_value[0]: <NEW_LINE> <INDENT> future.set_result(value[0]) <NEW_LINE> <DEDENT> <DEDENT> source.subscribe(on_next, on_error, on_completed) <NEW_LINE> return future | Converts an existing observable sequence to a Future
Example:
future = rx.Observable.return(42).to_future(RSVP.Promise);
With config:
Rx.config.Promise = RSVP.Promise
promise = rx.Observable.return(42).to_future()
future_ctor -- {Function} [Optional] The constructor of the future.
If not provided, it looks for it in rx.config.Future.
Returns {Future} An future with the last value from the observable
sequence. | 625941b9f548e778e58cd401 |
def __enter__(self): <NEW_LINE> <INDENT> return self | Called upon entering a `with` statement. | 625941b976d4e153a657e9b6 |
def is_float_array(l): <NEW_LINE> <INDENT> if isinstance(l, np.ndarray): <NEW_LINE> <INDENT> if l.dtype.kind == 'f': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Checks if l is a numpy array of floats (any dimension
| 625941b9cc40096d615957d8 |
def pattern_words(p: str, words_file='words_45k.txt'): <NEW_LINE> <INDENT> if not isinstance(p, str) or not isinstance(words_file, str): <NEW_LINE> <INDENT> raise TypeError('Param "p" and "words_file" must be str') <NEW_LINE> <DEDENT> _read_words(words_file) <NEW_LINE> global pattern_map <NEW_LINE> return pattern_map[p] | 获取属于该模式的英语单词
:param p: 模式,如0.1.1.2.3
:param words_file: 单词来源文件
:return: 英语单词列表 | 625941b9f7d966606f6a9e8e |
def _interp1d(x, y, xnew, kind='linear', fill_value=np.nan, _larch=None, **kws): <NEW_LINE> <INDENT> kwargs = {'kind': kind, 'fill_value': fill_value, 'copy': False, 'bounds_error': False} <NEW_LINE> kwargs.update(kws) <NEW_LINE> return interp1d(x, y, **kwargs)(xnew) | interpolate x, y array onto new x values, using one of
linear, quadratic, or cubic interpolation
> ynew = interp1d(x, y, xnew, kind='linear')
arguments
---------
x original x values
y original y values
xnew new x values for values to be interpolated to
kind method to use: one of 'linear', 'quadratic', 'cubic'
fill_value value to use to fill values for out-of-range x values
note: unlike interp, this version will not extrapolate for values of `xnew`
that are outside the range of `x` -- it will use NaN or `fill_value`.
this is a bare-bones wrapping of scipy.interpolate.interp1d.
see also: interp | 625941b985dfad0860c3acde |
def testNestedAssembliesWithVariantSetsChangeReps(self): <NEW_LINE> <INDENT> assemblyNode = self._SetupScene('SetWithModelingVariants_set.usda', '/SetWithModelingVariants_set') <NEW_LINE> varSetAttrName = 'usdVariantSet_modelingVariant' <NEW_LINE> cmds.addAttr(assemblyNode, ln=varSetAttrName, dt='string', internalSet=True) <NEW_LINE> cmds.setAttr('%s.%s' % (assemblyNode, varSetAttrName), 'Cubes', type='string') <NEW_LINE> self._ValidateUnloaded(assemblyNode) <NEW_LINE> cmds.assembly(assemblyNode, edit=True, active='Collapsed') <NEW_LINE> self._ValidateCollapsed(assemblyNode) <NEW_LINE> cmds.assembly(assemblyNode, edit=True, active='Cards') <NEW_LINE> self._ValidateCards(assemblyNode) <NEW_LINE> cmds.assembly(assemblyNode, edit=True, active='Expanded') <NEW_LINE> childNodes = self._GetChildren(assemblyNode) <NEW_LINE> cubesGroupNode = childNodes[0] <NEW_LINE> childNodes = self._GetChildren(cubesGroupNode) <NEW_LINE> cubeOneAssemblyNode = childNodes[0] <NEW_LINE> cmds.assembly(cubeOneAssemblyNode, edit=True, active='Expanded') | This tests that changing representations of a hierarchy of USD
reference assembly nodes in Maya works as expected when the referenced
prims have variant sets. | 625941b9e1aae11d1e749b3a |
def multiquery_dutch(text): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for sentence in text: <NEW_LINE> <INDENT> sent = [] <NEW_LINE> for word in sentence: <NEW_LINE> <INDENT> outcome = freebase_dutch_top(word) <NEW_LINE> if outcome: <NEW_LINE> <INDENT> sent.append((word, outcome)) <NEW_LINE> <DEDENT> <DEDENT> out.append(sent) <NEW_LINE> <DEDENT> return out | Takes a text, calls freebase_dutch_top on each word in it. | 625941b9b545ff76a8913ca4 |
def forward(self, x): <NEW_LINE> <INDENT> return self.linear(self.encode(x), self.encode(self.x_train), self.y_train) | Make prediction with model
:param x: (torch.tensor) Inputs.
:return: (torch.tensor) Predictive distribution (may be tuple) | 625941b9baa26c4b54cb0fa9 |
def test_hessian_is_zero(no_loss_problem: DerivativesTestProblem) -> None: <NEW_LINE> <INDENT> backpack_res = BackpackDerivatives(no_loss_problem).hessian_is_zero() <NEW_LINE> autograd_res = AutogradDerivatives(no_loss_problem).hessian_is_zero() <NEW_LINE> if autograd_res and not backpack_res: <NEW_LINE> <INDENT> warn( "Autograd Hessian diagonal is zero for this input " " while BackPACK implementation implies inputs with non-zero Hessian." ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert backpack_res == autograd_res | Check if the input-output Hessian is (non-)zero.
Note:
`hessian_is_zero` is a global statement that assumes arbitrary inputs.
It can thus happen that the Hessian diagonal is zero for the current
input, but not in general.
Args:
no_loss_problem: Test case whose module is not a loss. | 625941b9e5267d203edcdb26 |
def get(self): <NEW_LINE> <INDENT> templateOps = dict( topoData=self.topoData, valueData=self.valueData ) <NEW_LINE> self.render('index.html', **templateOps) | Serves the index template to the client with topo and value data. | 625941b9f548e778e58cd402 |
def _report_output(test_runner, xml_testsuite, xml_document, stdout, stderr): <NEW_LINE> <INDENT> systemout = xml_document.createElement('system-out') <NEW_LINE> xml_testsuite.appendChild(systemout) <NEW_LINE> systemout_text = xml_document.createCDATASection(stdout) <NEW_LINE> systemout.appendChild(systemout_text) <NEW_LINE> systemerr = xml_document.createElement('system-err') <NEW_LINE> xml_testsuite.appendChild(systemerr) <NEW_LINE> systemerr_text = xml_document.createCDATASection(stderr) <NEW_LINE> systemerr.appendChild(systemerr_text) | Appends the system-out and system-err sections to the XML document. | 625941b94e4d5625662d4262 |
def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.screen = screen <NEW_LINE> self.image = pygame.image.load("images/alien.png").convert_alpha() <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) | 初始化并设置外星人的起始位置 | 625941b98e05c05ec3eea1f7 |
def f8_to_int(a_str: str): <NEW_LINE> <INDENT> return int(Decimal(a_str) * DECIMAL_1E8) | Helper function to convert a legacy string 0.8f to compact int format | 625941b9091ae35668666deb |
def get_extra_metadata(self, backup, volume): <NEW_LINE> <INDENT> return | S3 driver does not use any extra metadata. | 625941b9cdde0d52a9e52eb5 |
def test_demangled_name(self) -> None: <NEW_LINE> <INDENT> self.assertEqual(self.func_entry_c.demangled_name, 'bool_exec') <NEW_LINE> self.assertEqual( self.func_entry_cxx.demangled_name, 'doStuff(int, int)' ) | Test if demangled_name is saved correctly. | 625941b9046cf37aa974cbd0 |
def test_get_host(self): <NEW_LINE> <INDENT> hostname = '127.0.0.1' <NEW_LINE> hosts = self.obj.get_host() <NEW_LINE> self.assertEqual(len(hosts), 3) <NEW_LINE> self.assertEqual(hosts[0]['hostname'], hostname) <NEW_LINE> hosts = self.obj.get_host(condition='hostname = "%s"' % hostname) <NEW_LINE> self.assertEqual(hosts[0]['hostname'], hostname) | Get host from cacti db. | 625941b97d43ff24873a2b2a |
def test_flowcell_project_cycle(self): <NEW_LINE> <INDENT> path = '/root/42BW9AAXX/C1-152/Project_12345_Index1' <NEW_LINE> flowcell, start, stop, project = sequences.get_flowcell_cycle(path) <NEW_LINE> self.assertEqual(flowcell, '42BW9AAXX') <NEW_LINE> self.assertEqual(start, 1) <NEW_LINE> self.assertEqual(stop, 152) <NEW_LINE> self.assertEqual(project, 'Project_12345_Index1') <NEW_LINE> path = '/root/42BW9AAXX/other' <NEW_LINE> self.assertRaises(ValueError, sequences.get_flowcell_cycle, path) | Make sure code to parse directory heirarchy works | 625941b921a7993f00bc7b70 |
def getLowLimitValue(self): <NEW_LINE> <INDENT> return -196 | Returns the controller low limit temperature.
Returns
-------
`float` | 625941b9187af65679ca4fa3 |
def _check_axis(self, number, row, col): <NEW_LINE> <INDENT> for i in range(BOARD_DIMENSION): <NEW_LINE> <INDENT> if self.board[row][i] == number or self.board[i][col] == number: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Checks if the number is on the same vertical or horizontal axis given
the (row, col). | 625941b9293b9510aa2c311f |
def gen_id(length=38): <NEW_LINE> <INDENT> return int(str(uuid.uuid4().int)[:length]) | Not cryptographically safe, should only be used for IDs | 625941b9c4546d3d9de728b7 |
def get_objects_async(spdb_instance, key_list, version=None): <NEW_LINE> <INDENT> loop = asyncio.get_event_loop() <NEW_LINE> tasks = [] <NEW_LINE> for idx, key in enumerate(key_list): <NEW_LINE> <INDENT> task = asyncio.ensure_future(get_single_object_async(key, version, idx)) <NEW_LINE> tasks.append(task) <NEW_LINE> <DEDENT> loop.run_until_complete(asyncio.wait(tasks)) <NEW_LINE> loop.close() <NEW_LINE> data = [x.result() for x in tasks] <NEW_LINE> data.sort(key=operator.itemgetter(0)) <NEW_LINE> _, data = zip(*data) <NEW_LINE> return data | Method to get multiple objects asyncronously using coroutines
Args:
key_list (list(str)): A list of cached-cuboid keys to retrieve from the object store
version: TBD version of the cuboid
Returns:
(list(bytes)): A list of blosc compressed cuboid data | 625941b963f4b57ef0000fa8 |
def test_find_grid_cell_by_coordinates(self): <NEW_LINE> <INDENT> my_grid = self.grid(['a,b,c,d\n', 'e,f,g,h\n', 'i,j,k,l'], x_seperator=',') <NEW_LINE> self.assertEqual(my_grid.find_value(0 ,0), 'a') <NEW_LINE> self.assertEqual(my_grid.find_value(1, 0), 'b') <NEW_LINE> self.assertEqual(my_grid.find_value(2, 0), 'c') <NEW_LINE> self.assertEqual(my_grid.find_value(3, 0), 'd') <NEW_LINE> self.assertEqual(my_grid.find_value(0, 1), 'e') <NEW_LINE> self.assertEqual(my_grid.find_value(1, 1), 'f') <NEW_LINE> self.assertEqual(my_grid.find_value(2, 1), 'g') <NEW_LINE> self.assertEqual(my_grid.find_value(3, 1), 'h') <NEW_LINE> self.assertEqual(my_grid.find_value(0, 2), 'i') <NEW_LINE> self.assertEqual(my_grid.find_value(1, 2), 'j') <NEW_LINE> self.assertEqual(my_grid.find_value(2, 2), 'k') <NEW_LINE> self.assertEqual(my_grid.find_value(3, 2), 'l') | Tests finding a cell in a grid by it's coordinates | 625941b957b8e32f52483326 |
def asBool(*args, **kwargs): <NEW_LINE> <INDENT> pass | asBool() -> bool
Returns the data represented by this handle in the data block. | 625941b9a17c0f6771cbdeda |
def test_execute(self): <NEW_LINE> <INDENT> airflow_key = mock.Mock(spec=tuple) <NEW_LINE> airflow_cmd = mock.Mock(spec=list) <NEW_LINE> self.executor.ecs.run_task.return_value = { 'tasks': [{ 'taskArn': '001', 'lastStatus': '', 'desiredStatus': '', 'containers': [{'name': 'some-ecs-container'}]} ], 'failures': [] } <NEW_LINE> self.assertEqual(0, len(self.executor.pending_tasks)) <NEW_LINE> self.executor.execute_async(airflow_key, airflow_cmd) <NEW_LINE> self.assertEqual(1, len(self.executor.pending_tasks)) <NEW_LINE> self.executor.attempt_task_runs() <NEW_LINE> self.executor.ecs.run_task.assert_called_once() <NEW_LINE> self.assert_botocore_call('RunTask', *self.executor.ecs.run_task.call_args) <NEW_LINE> self.assertEqual(1, len(self.executor.active_workers)) <NEW_LINE> self.assertIn(self.executor.active_workers.task_by_key(airflow_key).task_arn, '001') | Test execution from end-to-end | 625941b944b2445a33931f26 |
def conjugacy_classes_iterator(self): <NEW_LINE> <INDENT> from sage.combinat.partition import Partitions_n <NEW_LINE> from sage.groups.perm_gps.symgp_conjugacy_class import SymmetricGroupConjugacyClass <NEW_LINE> P = Partitions_n(len(self.domain())) <NEW_LINE> for la in reversed(P): <NEW_LINE> <INDENT> yield SymmetricGroupConjugacyClass(self, la) | Iterate over the conjugacy classes of ``self``.
EXAMPLES::
sage: G = SymmetricGroup(5)
sage: list(G.conjugacy_classes_iterator()) == G.conjugacy_classes()
True | 625941b9b5575c28eb68de84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.