code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def select_size_color(self): <NEW_LINE> <INDENT> pass
如果遇到需要选颜色尺寸才能加入购物车的情况再就写个方法
625941e0b57a9660fec33c0b
def keras_builder(dims): <NEW_LINE> <INDENT> model = Sequential() <NEW_LINE> dropout = 0.2 <NEW_LINE> assert len(dims) >= 3 <NEW_LINE> model.add(Dense(units=dims[1], activation='relu', input_dim=dims[0], kernel_constraint=max_norm(4.), bias_constraint=max_norm(4.))) <NEW_LINE> model.add(Dropout(dropout)) <NEW_LINE> for...
Builder for the keras model. This function is parsed to the KerasClassifier constructor
625941e01b99ca400220ae35
def get_modules(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s=os.path.dirname(modules.__file__) <NEW_LINE> ret=[name for _, name, _ in pkgutil.iter_modules([s])] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise SwarmModuleException('an error occurred when try to get modules, please check' ' modu...
Returns: return a list consist of module name. Raises: SwarmModuleException: An error occurred when try to get modules or no available module.
625941e0cdde0d52a9e533b8
def register_advance_device_controller(self, advDeviceController): <NEW_LINE> <INDENT> pass
Register the advance device controller developer want to expose to external user advDeviceControllerName - The advance device controller name advDeviceController - The advance device controller class
625941e0046cf37aa974d0c7
def generate_pyramid_anchors(batch_size,resolution, image_shape, smallest_anchor_scale): <NEW_LINE> <INDENT> anchors = [] <NEW_LINE> anchor_scale = smallest_anchor_scale <NEW_LINE> for i in range(len(resolution)): <NEW_LINE> <INDENT> reso = resolution[i] <NEW_LINE> anchor = generate_anchors(scales=anchor_scale, ratios=...
:param resolution: 一个int列表,其长度等于feature_map的层级个数,由底层到高层,依次是缩放比。对于resnet50而言,是 [8, 16, 32, 64, 128] :param image_shape: 二元组,(gao ,kuan)输入图片的大小 :param smallest_anchor_scale: 最底层feature map上面每个像素对应的anchor大小 :return: 所有的anchor,由底层到高层拼接起来,形状是[批数, 个数,(x1, y1, x2, y2)],相对于输入图片的像素坐标
625941e094891a1f4081be2d
def langmuirProbeSimulation(V=_np.arange(-150,151,1),A_probe=0.00032258,V_plasma=50,T_elec=30,T_ion=30,density=1e18,ionMassNumber=2.014102,plot=True): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> eV=1.60218e-19; <NEW_LINE> q=1.6e-19; <NEW_LINE> amu=1.66054e-27; <NEW_LINE> m_elec=9.109e-31; <NEW_LINE> T_elec*=eV <N...
Produces a langmuir probe I-V plot based on several known values Parameters ---------- V : numpy.ndarray voltage array from some negative value to some positive value A_probe : float probe area in m^2 V_plasma : float plasma voltage in volts T_elec : float electron temperature in eV T_ion : float i...
625941e0596a897236089e3f
def fold_whitespace(s): <NEW_LINE> <INDENT> def isblank(l): <NEW_LINE> <INDENT> return not l or l.isspace() <NEW_LINE> <DEDENT> paras = ['' if blank else ' '.join(lines) for blank, lines in itertools.groupby(s.strip().splitlines(), isblank)] <NEW_LINE> return '\n'.join(paras)
Apply whitespace folding (kind of like YAML does normally). This comes after applying Jinja templates so that Jinja blocks don't leave extra line breaks around.
625941e00383005118ecf964
def testUndefinedPattern(self): <NEW_LINE> <INDENT> program = unicode("妖妖夢妖妖夢", 'utf-8') <NEW_LINE> self.assertEqual(YYY.YYYtoBF(program), '.')
'妖妖夢妖妖夢' is read as '妖妖夢妖夢'
625941e0d486a94d0b98e4c9
def on_camera_cancel_clicked(self, widget): <NEW_LINE> <INDENT> self.hide()
When the Cancel button is clicked, just hide the dialog.
625941e03539df3088e2e6cd
def forward(self, input, state=None): <NEW_LINE> <INDENT> input_shape = input.shape <NEW_LINE> input = self.input_layer(input.view(-1, input_shape[-1])).view( *(input_shape[:-1] + (-1,)) ) <NEW_LINE> input = torch.stack([input, torch.zeros_like(input)], -1) <NEW_LINE> if self.batch_first: <NEW_LINE> <INDENT> input = to...
forward pass through the RNN Args: input (torch.tensor): A 4-dimensional torch float tensor with the real and imaginary part stored in the last dimension of the tensor; i.e. with shape (batch_size, sequence_length, feature_size, 2) if self.batch_first==True (sequence_length,...
625941e0f7d966606f6aa38b
def reverse( self, query, exactly_one=True, timeout=None, language=False, ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lat, lon = [ x.strip() for x in self._coerce_point_to_string(query).split(',') ] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("Must be a coordinate pair or Point") <NE...
Returns a reverse geocoded location. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param bool exactly_one: Return one result or a list...
625941e0287bf620b61d3de4
def ready(self): <NEW_LINE> <INDENT> from instrument.tasks import ( run_instruments_handling_func, run_instrument_simulators_func, run_power_usage_instrument_simulators_func ) <NEW_LINE> scheduler = django_rq.get_scheduler('default') <NEW_LINE> for job in scheduler.get_jobs(): <NEW_LINE> <INDENT> if "instrument" in str...
On django runtime, load up the following code.
625941e08a349b6b435e84f5
def extract(corpus_file, common_words_file=None, min_candidate_len=2, max_candidate_len=5, least_cnt_threshold=5, solid_rate_threshold=0.018, entropy_threshold=1.92, all_words=False, save_file=None): <NEW_LINE> <INDENT> return WordExtract(corpus_file, common_words_file=common_words_file, min_candidate_len=min_candidate...
Extract chinese words from corpus. Args: corpus_file: string, input corpus file (required) common_words_file: string, common words dic file [common.dic] min_candidate_len: int, min candidate word length [2] max_candidate_len: int, max candidate word length [5] least_cnt_threshold: int, least word co...
625941e00fa83653e465733b
def add_back_to_place(self): <NEW_LINE> <INDENT> if self.is_box: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> place = Preferences.get_default_place() <NEW_LINE> if not place: <NEW_LINE> <INDENT> log.error("archiving box {}: we are expecting to find a default place.".format(self.pk)) <NEW_LINE> return <NEW_LINE> <DEDENT...
For a box, add the copies back to the default place. Case of a box that we archive, we need to put the books back in the stock. Return: bool.
625941e04428ac0f6e5bab77
def test_hinge_expr_to_grb_expr1(self): <NEW_LINE> <INDENT> aff = AffExpr(np.ones((1,1)), np.ones((1,1))) <NEW_LINE> hinge = HingeExpr(aff) <NEW_LINE> model = grb.Model() <NEW_LINE> prob = Prob(model) <NEW_LINE> grb_var = model.addVar(lb=-1 * GRB.INFINITY, ub=GRB.INFINITY, name='x') <NEW_LINE> grb_vars = np.array([[grb...
min max(0, x+1) st. x == -4
625941e0b57a9660fec33c0c
def save_notes_list(self): <NEW_LINE> <INDENT> save_notes_list(self.notes, self.notes_list_path())
Save the list of notes.
625941e07c178a314d6ef7e8
def constant_folding(self, cf_state): <NEW_LINE> <INDENT> super().constant_folding(cf_state) <NEW_LINE> left = self._left.constant_folding(cf_state) <NEW_LINE> right = self._right.constant_folding(cf_state) <NEW_LINE> if left is not None and right is not None: <NEW_LINE> <INDENT> return IntScalar(left.value + right.val...
Optimizes code using constant folding and constant propagation. :type cf_state: util.ConstantFoldingState.ConstantFoldingState :rtype: entity.Scalar.IntScalar | entity.Scalar.CharScalar
625941e0dc8b845886cb58b9
def observeUpdate(self, observation, gameState): <NEW_LINE> <INDENT> pacman = gameState.getPacmanPosition() <NEW_LINE> tmp = self.beliefs.copy() <NEW_LINE> for i in self.allPositions: <NEW_LINE> <INDENT> tmp[i] = self.getObservationProb(observation, pacman, i, self.getJailPosition()) * self.beliefs[i] <NEW_LINE> <DEDEN...
Update beliefs based on the distance observation and Pacman's position. The observation is the noisy Manhattan distance to the ghost you are tracking. self.allPositions is a list of the possible ghost positions, including the jail position. You should only consider positions that are in self.allPositions. The update...
625941e04a966d76dd551395
def remove_app(self, app): <NEW_LINE> <INDENT> self.session.delete(app) <NEW_LINE> self.session.commit()
Remove an app from the database.
625941e031939e2706e4d1e8
def build_decoders(decoder_num, input_layer, encoded_layer, head_num, hidden_dim, attention_activation=None, feed_forward_activation='relu', dropout_rate=0.0, trainable=True, use_adapter=False, adapter_units=None, adapter_activation='relu'): <NEW_LINE> <INDENT> last_layer = input_layer <NEW_LINE> for i in range(decoder...
Get decoders. :param decoder_num: Number of decoder components. :param input_layer: Input layer. :param encoded_layer: Encoded layer from encoder. :param head_num: Number of heads in multi-head self-attention. :param hidden_dim: Hidden dimension of feed forward layer. :param attention_activation: Activation for multi-...
625941e0d10714528d60006a
def initgame(self): <NEW_LINE> <INDENT> global cellsize <NEW_LINE> global offset <NEW_LINE> global cols <NEW_LINE> global rows <NEW_LINE> rows = defrow + (2 * self.optionscreen.difficulty) <NEW_LINE> if not IPad: <NEW_LINE> <INDENT> rows -= 3 <NEW_LINE> <DEDENT> cellsize = self.size.h / (rows + 2) <NEW_LINE> cols = int...
initialize system options and start a new game.
625941e063b5f9789fde7469
def get_sytem_type(info): <NEW_LINE> <INDENT> from mne.io.constants import FIFF <NEW_LINE> chs = info.get('chs') <NEW_LINE> coil_types = set([ch['coil_type'] for ch in chs]) <NEW_LINE> channel_types = set([ch['kind'] for ch in chs]) <NEW_LINE> has_4D_mag = FIFF.FIFFV_COIL_MAGNES_MAG in coil_types <NEW_LINE> ctf_other_t...
Function to get type of the system used to record the processed MEG data
625941e0b830903b967e9c8a
@handle_shape_dtype(transform_output=False) <NEW_LINE> def convert_to_dim(xyz): <NEW_LINE> <INDENT> x = xyz[:, 0] <NEW_LINE> y = xyz[:, 1] <NEW_LINE> z = xyz[:, 2] <NEW_LINE> M = np.linalg.norm([x, y, z], axis=0) <NEW_LINE> D = np.degrees(np.arctan2(y, x)) % 360 <NEW_LINE> I = np.degrees(np.arcsin(z / M)) <NEW_LINE> ou...
Converts a numpy array of [d,i,m] values (i.e. [[d1,i1,m1], [d2,i2,m2]]) into an numpy array with [[x1,y1,z1], [x2,y2,z2]] Reshape allows to pass an [[d1,d2],[i1,i2],[m1,m2]] array instead. Args: xyz: Returns: np.array: **out** -- The output array is in the same shape and type as the intype array
625941e016aa5153ce3627fb
def validate_key(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> confirmation = models.EmailConfirmation.objects.select_related( "email__user" ).get(key=key) <NEW_LINE> <DEDENT> except models.EmailConfirmation.DoesNotExist: <NEW_LINE> <INDENT> raise serializers.ValidationError( _("The provided verification key...
Validate the provided confirmation key. Returns: str: The validated confirmation key. Raises: serializers.ValidationError: If there is no email confirmation with the given key or the confirmation has expired.
625941e03cc13d1c6d3c76fb
def _deep_update(old: dict, new: dict) -> None: <NEW_LINE> <INDENT> for key, value in new.items(): <NEW_LINE> <INDENT> if key in old: <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> _deep_update(old[key], value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> old[key] = value <NEW_LINE> <DEDENT> <DEDE...
Update "old" dict with values found in "new" dict at the right hierarchy level. Examples: >>> old = {'l1': {'l2': {'a': 'A', 'b': 'B'}}, 'c': 'CC'} >>> new = {'l1': {'l2': {'a': 'AA', 'b': 'BB'}, 'd': 'DD'}} >>> _deep_update(old, new) >>> old['l1']['l2']['a'], old['l1']['l2']['b'], old['c'], old['l1']['d'] ('AA', 'BB'...
625941e066656f66f7cbc52f
def __lookupReadsWithoutCache(self,startbp,endbp,chrom): <NEW_LINE> <INDENT> tempcutf = {} <NEW_LINE> tempcutr = {} <NEW_LINE> for alignedread in self.samfile.fetch(chrom, max(startbp, 0), endbp): <NEW_LINE> <INDENT> if not alignedread.is_unmapped: <NEW_LINE> <INDENT> if alignedread.is_reverse: <NEW_LINE> <INDENT> a = ...
Loads reads from the BAM file directly from disk, ignoring the cache (private method) Args: startbp (int): The start of the interval endbp (int): The end of the interval chrom (str): The chromosome
625941e050812a4eaa59c6a1
def start(self) -> NoReturn: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._wait_until_true( lambda: self.num_workers_expected == self._get_num_workers_running(), timeout=self.master_timeout, ) <NEW_LINE> while True: <NEW_LINE> <INDENT> if not self.gunicorn_master_proc.is_running(): <NEW_LINE> <INDENT> sys.exit(1) ...
Starts monitoring the webserver.
625941e0004d5f362079a6b4
def pars_xml(source, sep="unit"): <NEW_LINE> <INDENT> unit = {} <NEW_LINE> result = [] <NEW_LINE> context = etree.iterparse(StringIO(source)) <NEW_LINE> for action, elem in context: <NEW_LINE> <INDENT> if not elem.text: <NEW_LINE> <INDENT> text = "None" <NEW_LINE> <DEDENT> elif (elem.tag != sep): <NEW_LINE> <INDENT> te...
Преобразовывает xml-строку в кортеж В качестве специального разделителя использует переменную sep
625941e04527f215b584c7d6
def parse_scenesfile_maia(filename): <NEW_LINE> <INDENT> from datetime import datetime <NEW_LINE> import re <NEW_LINE> filename = os.path.basename(filename) <NEW_LINE> if not filename: <NEW_LINE> <INDENT> raise ValueError("No file %r" % filename) <NEW_LINE> <DEDENT> match = re.match(r"\S\S\SCT_(\S\S\S)_\S\S_(\d+)_S(\d+...
Parse maia file: # viiCT_npp_DB_20120817_S035411_E035535_DES_N_La052_Lo-027_00001.h5
625941e0097d151d1a2231da
def __init__(self, minval=0, maxval=None, seed=None, dtype=dtypes.float16, num_valid_mantissa_bits=4): <NEW_LINE> <INDENT> if dtype not in (dtypes.float16,): <NEW_LINE> <INDENT> raise ValueError("dtype: %s not supported" % dtype.name) <NEW_LINE> <DEDENT> super(_MaskedRandomUniformInitializer, self).__init__( minval=min...
Constructor. Args: minval: A python scalar or a scalar tensor. Lower bound of the range of random values to generate. maxval: A python scalar or a scalar tensor. Upper bound of the range of random values to generate. Defaults to 1 for float types. seed: A Python integer. Used to create random seeds. See...
625941e0fb3f5b602dac3a1a
def quickSort_time_save(self, filename="datos/quickSort.csv", start=5, stop=100, step=5): <NEW_LINE> <INDENT> results = self.quickSort_timing(start, stop, step) <NEW_LINE> with open(filename, 'w', newline='') as csvfile: <NEW_LINE> <INDENT> writer = csv.writer(csvfile, delimiter=';',quotechar='|', quoting=csv.QUOTE_MIN...
Método guardar del quickSort *Guarda los tiempos de corrida del quickSort
625941e0eab8aa0e5d26dedc
def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.register_request( requests.SaveProductName, text=test_requests.TestSaveProductName.RESPONSE ) <NEW_LINE> self.register_request( requests.UpdateProductOnSalesChannel, json=test_requests.TestUpdateOnSalesChannel.RESPONSE, ) <NEW_LINE> self.register_requ...
Register request URI and call method.
625941e0ad47b63b2c50a301
def blank_lines(freq, tau, reffreqs, v0, dv): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for ref in reffreqs: <NEW_LINE> <INDENT> lm0, lmf = get_line_mask(freq, ref, v0, dv0) <NEW_LINE> freq = np.concatenate((freq[:lm0], freq[lmf:])) <NEW_LINE> tau = np.concatenate((tau[:lm0], tau[lmf:])) <NEW_LINE> <DEDENT> <DEDENT>...
Blanks the lines in a spectra. :param freq: Frequency axis of the spectra. :type freq: array, MHz :param tau: Optical depth axis of the spectra. :type tau: array :param reffreqs: List with the reference frequency of the lines. Should be the rest frequency. :type reffreqs: list :param v0: Velocity shift to apply to the...
625941e0b5575c28eb68e386
def reward(self, state: np.ndarray, action: int, new_state: np.ndarray) -> float: <NEW_LINE> <INDENT> return float(np.all(state == self._goal))
Returns +1.0 reward if state is the goal and 0.0 otherwise.
625941e0d164cc61757830d2
def update_forecast(forecast_id, *, name=None, extra_parameters=None): <NEW_LINE> <INDENT> _call_procedure( 'update_forecast', forecast_id, name, extra_parameters)
Update forecast metadata. Parameters ---------- forecast_id: String UUID of the forecast to update. **kwargs Fields to update. If none, field will not be changed.
625941e032920d7e50b28556
def parameterNames(self): <NEW_LINE> <INDENT> for propertyName, value in vars(self.__class__).items(): <NEW_LINE> <INDENT> if( (propertyName.startswith('__') or propertyName.endswith('__')) ==False ): <NEW_LINE> <INDENT> if( repr(value).find('property')!=-1): <NEW_LINE> <INDENT> yield propertyName
returns a generator object to iterate over the names of the parameter
625941e0851cf427c661a88f
def put(a, indices, values, mode='raise'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return a.put(indices, values, mode=mode) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return narray(a, copy=False).put(indices, values, mode=mode)
Set storage-indexed locations to corresponding values. This function is equivalent to `MaskedArray.put`, see that method for details. See Also -------- MaskedArray.put
625941e05166f23b2e1a54dc
def get_major_version(version, separator="."): <NEW_LINE> <INDENT> major = version.split(separator)[0] <NEW_LINE> if not major.isdigit(): <NEW_LINE> <INDENT> raise ValueError("Major version must be numerical") <NEW_LINE> <DEDENT> return "{0}{1}0{1}0".format(major, separator)
Figures out a major version from a regular version. It does so by constructing a version starting from the major digit and adding zero's to it. Args: version: version to check against separator: version separator Returns: major version
625941e092d797404e30450e
def _generate_examples(self, filepath): <NEW_LINE> <INDENT> with open(filepath, "rb") as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> line_dict = json.loads(line) <NEW_LINE> id_ = line_dict["UID"] + "_" + line_dict["pairID"] <NEW_LINE> feats = { "sentence_good": line_dict["sentence_good"], "sentence_bad": ...
Yields examples.
625941e082261d6c526ab827
def checkOrientationDefined(mesh): <NEW_LINE> <INDENT> for edge in mesh.edges: <NEW_LINE> <INDENT> if not hasattr(edge, 'orientedHalfEdge'): <NEW_LINE> <INDENT> print("ERROR: Edges do not have orientedHalfEdge defined. Cannot proceed") <NEW_LINE> exit() <NEW_LINE> <DEDENT> <DEDENT> for he in mesh.halfEdges: <NEW_LINE> ...
Verify that edges have oriented halfedges and halfedges have orientation signs
625941e05e10d32532c5f2a8
@click.group() <NEW_LINE> @click.option('-v', '--verbose', count=True, help='Turn on debug logging') <NEW_LINE> def cli(verbose): <NEW_LINE> <INDENT> floyd.floyd_host = "http://127.0.0.1:8080" <NEW_LINE> floyd.floyd_web_host = "https://127.0.0.1:3000" <NEW_LINE> floyd.tus_server_endpoint = "http://127.0.0.1:1080" <NEW_...
Floyd CLI interacts with FloydHub server and executes your commands. More help is available under each command listed below.
625941e03539df3088e2e6ce
def merge_sort(num_list, start, end): <NEW_LINE> <INDENT> if start + 1 < end: <NEW_LINE> <INDENT> middle = (start + end) // 2 <NEW_LINE> merge_sort(num_list, start, middle) <NEW_LINE> merge_sort(num_list, middle, end) <NEW_LINE> merge(num_list, start, end, middle)
split recursively the list into 2 sublist, end it ends when sublist contains only one element, and then start merge operation :param num_list: list of numbers :param start: start index in list :param end: end index (not included) :return: list sorted in range start and end index
625941e07b180e01f3dc4b7a
def set_inmemory(self,val): <NEW_LINE> <INDENT> if type(val) is not bool: <NEW_LINE> <INDENT> raise TypeError('Input value must be boolean') <NEW_LINE> <DEDENT> self.inmemory = val
Sets inmemory attribute to either True or False
625941e097e22403b379d31e
@mock.patch('garecovery.two_of_three.bitcoincore.AuthServiceProxy') <NEW_LINE> def test_invalid_mnemonic(mock_bitcoincore): <NEW_LINE> <INDENT> mock_bitcoincore.return_value = AuthServiceProxy('testnet_txs') <NEW_LINE> args = [ '2of3', '--network=testnet', '--key-search-depth=5', '--search-subaccounts=10', '--destinati...
Test invalid mnemonic
625941e0a05bb46b383ecba2
def rand_string(size=12): <NEW_LINE> <INDENT> return ''.join(random.choice(ascii_lowercase+digits) for x in range(size))
Generates quazi-unique sequence from random digits and letters.
625941e0cb5e8a47e48b7e28
def do_wake(self, argument): <NEW_LINE> <INDENT> self.write("Wake up!")
A seriously worded instruction to end sleeping. Usage: wake
625941e030dc7b7665901ce6
def quat_to_list(quat): <NEW_LINE> <INDENT> if isinstance(quat, Quaternion): <NEW_LINE> <INDENT> return [quat.x, quat.y, quat.z, quat.w] <NEW_LINE> <DEDENT> elif isinstance(quat, ndarray): <NEW_LINE> <INDENT> return [quat[0], quat[1], quat[2], quat[3]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("quat...
convert a geometry_msgs/Quaternion or numpy.ndarray in list [x, y, z, w] :param quat: a geometry_msgs/Quaternion or numpy.ndarray :return: the corresponding quaternion [x, y, z, w]
625941e0dd821e528d63b529
def test_touch(self): <NEW_LINE> <INDENT> name = os.path.join(integration.TMP, 'touch_test') <NEW_LINE> ret = self.run_state('file.touch', name=name) <NEW_LINE> self.assertTrue(os.path.isfile(name)) <NEW_LINE> result = self.state_result(ret) <NEW_LINE> self.assertTrue(result) <NEW_LINE> os.remove(name)
file.touch
625941e030c21e258bdfa823
def del_address(self, addr): <NEW_LINE> <INDENT> with self.addr_lock: <NEW_LINE> <INDENT> for addr_pos in range(len (self.addr)): <NEW_LINE> <INDENT> if str(self.addr[addr_pos]) == addr: <NEW_LINE> <INDENT> del self.addr[addr_pos] <NEW_LINE> break
delete an address (string) for the configured addresses on the interface
625941e0eab8aa0e5d26dedd
def get_readonly_fields(self, request, obj=None): <NEW_LINE> <INDENT> return DEFAULT_READONLY + list(self.readonly_fields)
Define default readonly fields.
625941e001c39578d7e751bf
def _waitForTask(self, tasks, progress_msgs=None, abort_event=None): <NEW_LINE> <INDENT> if type(tasks) != type([]): <NEW_LINE> <INDENT> tasks = [tasks] <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> if isAlive(tasks) == False: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if not progress_msgs is None: <NEW_LINE> ...
Waits for the given thread to finish reporting the thread progress thru the queue progress_msgs and handles the cancellation if cancelled thru the progress dialog FIXME: use of queue is not safe enough, call to empty() is unreliable according to python doc and may block, needs better solution for passing data between t...
625941e0656771135c3ebbf6
def figure_1d(self): <NEW_LINE> <INDENT> self.mat_plot_1d.plot_yx( y=self.y, x=self.x, visuals_1d=self.get_visuals_1d(), auto_labels=AutoLabels(), )
Plots the plotter's y and x values in 1D.
625941e0167d2b6e31218f18
def get_cursor_at_y(self, y): <NEW_LINE> <INDENT> return self.move_cursor if self.move_cursor is not None else QCursor(Qt.SizeHorCursor)
Get an override cursor for an y coordinate given that the x == self.x :param y: A y coordinate. :return: QCursor or None.
625941e03317a56b86939fd4
def classFactory(iface): <NEW_LINE> <INDENT> from .poly_generation import Polygon_Generator <NEW_LINE> return Polygon_Generator(iface)
Load Polygon_Generator class from file Polygon_Generator. :param iface: A QGIS interface instance. :type iface: QgisInterface
625941e038b623060ff0b171
def get_links(resource, rel=RelationType.DOWN, media_type=None): <NEW_LINE> <INDENT> links = [] <NEW_LINE> for link in resource.findall('{http://www.vmware.com/vcloud/v1.5}Link'): <NEW_LINE> <INDENT> link_rel = link.get('rel') <NEW_LINE> link_media_type = link.get('type') <NEW_LINE> if link_rel == rel.value: <NEW_LINE>...
Returns all the links of the specified rel and type in the resource. :param lxml.objectify.ObjectifiedElement resource: the resource with the links. :param RelationType rel: the rel of the desired link. :param str media_type: media type of content. :return: list of lxml.objectify.ObjectifiedElement objects, where...
625941e056b00c62f0f149df
def create_result(): <NEW_LINE> <INDENT> print("Creating result object with handlers:", SHELL_OUTPUT_HANDLERS) <NEW_LINE> global result_object <NEW_LINE> result_object = Result(stream=sys.stdout, descriptions=None, outputs=SHELL_OUTPUT_HANDLERS, main_test=None) <NEW_LINE> result_object.startTestRun()
Initialize the global result object for running tests in the shell.
625941e0ac7a0e7691ed444a
def get_filter_backquote(word): <NEW_LINE> <INDENT> if word.find('`') != -1: <NEW_LINE> <INDENT> space = '' <NEW_LINE> word = word.replace('`', '') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> space = ' ' <NEW_LINE> <DEDENT> return (space, word)
Checks a word for backquotes.
625941e04d74a7450ccd4548
def replace_audit_sink(self, name, body, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.replace_audit_sink_with_http_info(name, body, **kwargs)
replace_audit_sink # noqa: E501 replace the specified AuditSink # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_audit_sink(name, body, async_req=True) >>> result = thread.get() :param async_req bool: exec...
625941e056ac1b37e626454d
def image2array(filename, shape=None): <NEW_LINE> <INDENT> im = Image.open(filename).convert('1', dither=Image.NONE) <NEW_LINE> im = im.resize(shape, Image.ANTIALIAS) <NEW_LINE> pattern = np.array(im) <NEW_LINE> return pattern
Read image file into a bool array. Parameters ---------- filename : string Name of the image file. size : tuple If given, the image is resized to the shape
625941e0851cf427c661a890
def SubscriberFeaturesStart(builder): <NEW_LINE> <INDENT> return Start(builder)
This method is deprecated. Please switch to Start.
625941e096565a6dacc8fa4e
def logTransform(df,xcol, ycol): <NEW_LINE> <INDENT> non_0=df[(df[xcol]!=0) & (df[ycol]!=0)] <NEW_LINE> return np.log(non_0[xcol]), np.log(non_0[ycol])
Drop 0 values and return x and y log transformed.
625941e08e71fb1e9831db2b
def sharpe_ratio(returns, risk_free=0, period=DAILY): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ann_factor = ANNUALIZATION_FACTORS[period] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError( "period cannot be '{}'. " "Must be '{}', '{}', '{}', or '{}'".format( period, DAILY, WEEKLY, MONTHLY, Q...
Determines the annualized Sharpe ratio of a strategy. Parameters ---------- returns : pd.Series Returns of the strategy, noncumulative. period : str, optional - defines the periodicity of the 'returns' data for purposes of annualization. Can be 'yearly', 'quarterly', 'monthly', 'weekly' or 'daily'. - se...
625941e0925a0f43d254a1fe
def get_mixed(unique=False): <NEW_LINE> <INDENT> weights = np.ones(7) <NEW_LINE> return get_weighted_mixed(weights, unique)
Builds mixed system, unique specifies whether to put something in the usually zero block to mimic the TTB matrix in the C++ code.
625941e021bff66bcd684cd3
def telnet_connect(host, port): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return telnetlib.Telnet(host, port, 0.1) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None
Connect to a listening telnet server. :param host: Telnet server IP address. :type host: str :param port: Telnet server listening port. :type port: int :return: Telnet session or None
625941e06fb2d068a760f426
def main(): <NEW_LINE> <INDENT> word_list = ['0UTD00R5', '1NL1NE', '0NL1NE', '1NPUT', '501L', '01L5', ] <NEW_LINE> for word in word_list: <NEW_LINE> <INDENT> print(Corrections.correct(word))
Correct Mistakes Main function.
625941e063f4b57ef0001493
def __init__(self, cwid, name, dept): <NEW_LINE> <INDENT> self.cwid = cwid <NEW_LINE> self.name = name <NEW_LINE> self.dept = dept <NEW_LINE> self.courses = {}
create instance of Instructor class
625941e05510c4643540f75f
def parse_clause(clause, compiler): <NEW_LINE> <INDENT> from geoalchemy.base import SpatialElement, WKTSpatialElement, WKBSpatialElement, DBSpatialElement, GeometryBase <NEW_LINE> if hasattr(clause, '__clause_element__'): <NEW_LINE> <INDENT> return clause.__clause_element__() <NEW_LINE> <DEDENT> elif isinstance(clause,...
This method is used to translate a clause element (geometries, functions, ..). According to the type of the clause, a conversion to the database geometry type is added or the column clause (column name) or the cascaded clause element is returned.
625941e023e79379d52ee8e3
def validate_data(age, investment_Amount, intent_request): <NEW_LINE> <INDENT> if age is not None: <NEW_LINE> <INDENT> age = parse_int(age) <NEW_LINE> if age < 0: <NEW_LINE> <INDENT> return build_validation_result( False, "age", "You should be at least born to use this service. " "please come back at a later date.", ) ...
Validates the data (age, investment amount, or intent request) provided by the user.
625941e023849d37ff7b3411
def _expand_is_accepted_like(x): <NEW_LINE> <INDENT> with tf.name_scope('expand_is_accepted_like'): <NEW_LINE> <INDENT> expand_shape = tf.concat([ tf.shape(is_accepted), tf.ones([tf.rank(x) - tf.rank(is_accepted)], dtype=tf.int32), ], axis=0) <NEW_LINE> multiples = tf.concat([ tf.ones([tf.rank(is_accepted)], dtype=tf.i...
Helper to expand `is_accepted` like the shape of some input arg.
625941e0ab23a570cc250509
def mysize(ndarray): <NEW_LINE> <INDENT> dims = ndarray.shape <NEW_LINE> if len(dims) == 2 and (dims[0]==1 or dims[1]==1): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return len(dims)
Returns the number of dimensions of a numpy ndarray
625941e0627d3e7fe0d691d5
@command.add_sub <NEW_LINE> @argument('sample') <NEW_LINE> @argument('vcf', help='VCF or gzipped VCF') <NEW_LINE> @argument('-m', '--method', choices=['pearson', 'spearman', 'linear', 't', 'welch', 'logistic']) <NEW_LINE> @argument('-s', '--sex', choices=['both', 'male', 'female'], default='both') <NEW_LINE> @argument(...
Assume autosomals Output TSV: chrom start end name (regino_type, strand, region_id, region_name) <= need gene annotation file # basic sample info call_rate : change with min_cnq alt_sample : alt_rate : cns : nsample # pearson (cor) cor pvalue # linear (sta...
625941e0ec188e330fd5ab1c
def __init__(self, title="", entrylang="", defilang=""): <NEW_LINE> <INDENT> self.init(title, entrylang, defilang)
Initialize a Dschictionary. Parameters: title -- Title entrylang -- Language of entries defilang -- Language of definitions
625941e04e696a04525c97d0
def request( self, method, url, params=None, data=None, files=None, json=None, timeout=None, headers=None, session=None, ): <NEW_LINE> <INDENT> logger.debug( "Starting request to url: %s with params: %s, data: %s", url, params, data ) <NEW_LINE> request_headers = self._get_headers(headers=headers) <NEW_LINE> timeout = ...
Send a request with the given data as json to the given URL. Args: method: HTTP method url: The url to send the request to. params: Dictionary of values to format url. data: files: json: timeout: headers: extra headers to add to the request. Returns: Request response if successful,...
625941e08e05c05ec3eea6fb
def cutoffs_below(self, f): <NEW_LINE> <INDENT> mm, nn = np.meshgrid(np.arange(2 * f * self.x / c), np.arange(2 * f * self.y / c), indexing='ij') <NEW_LINE> ff = c / 2 * (mm**2 / self.x**2 + nn**2 / self.y**2)**(1/2) <NEW_LINE> TE_cutoffs = ff[ff < f][1:] <NEW_LINE> TM_cutoffs = ff[1:,1:][ff[1:,1:] < f] <NEW_LINE> cuto...
Return the cutoff frequencies of all propagating modes below frequency f in Hz for an x by y rectangular waveguide. A mode is not considered to be propagating exactly at its cutoff frequency.
625941e04e696a04525c97d1
def GetPrincipalAxes(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIUS3_GetPrincipalAxes(self)
GetPrincipalAxes(self) -> itkMatrixD33
625941e0a05bb46b383ecba3
def take_dot_proc(self, dot: DoT): <NEW_LINE> <INDENT> dot_proc_damage: Damage = dot.damage <NEW_LINE> dot_proc_damage = self._calculate_level_difference_damage(damage_to_deal=dot_proc_damage, target_level=dot.level, inverse=True) <NEW_LINE> if dot_proc_damage.phys_dmg: <NEW_LINE> <INDENT> dot_proc_damage = self._apply...
this method damages the entity for the dot's proc
625941e02ae34c7f2600d4b5
def compute_item_matrix(items, empty=None, *args, **kwargs) : <NEW_LINE> <INDENT> info = _find_optimal(list(map(len, items)), *args, **kwargs) <NEW_LINE> nrow, ncol = info['rows_numbers'], info['columns_numbers'] <NEW_LINE> return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range...
Returns a nested list, and info to columnize items Parameters ---------- items list of strings to columize empty : (default None) default value to fill list if needed separator_size : int (default=2) How much caracters will be used as a separation between each columns. displaywidth : int (default=80) ...
625941e055399d3f05588a3a
def get_interface_by_name(self, name): <NEW_LINE> <INDENT> for i in self.interfaces: <NEW_LINE> <INDENT> if i.name == name: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> for u in i.sub_interfaces: <NEW_LINE> <INDENT> if u.name == name: <NEW_LINE> <INDENT> return u <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None
Find an interface by name Parameters ---------- name : string. The name of the interface to find Return ------ Return the corresponding interface if found else return None.
625941e09f2886367277ac0f
def number_of_alerts(self, baseurl=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if baseurl is not None: <NEW_LINE> <INDENT> params['baseurl'] = baseurl <NEW_LINE> <DEDENT> return next(self.zap._request(self.zap.base + 'core/view/numberOfAlerts/', params).itervalues())
Gets the number of alerts, optionally filtering by URL
625941e0d53ae8145f87a5ee
def is_monopod(self, corner): <NEW_LINE> <INDENT> dual_weights_doubled = self.dual_weights_doubled(corner) <NEW_LINE> return dual_weights_doubled[0] > 0 and dual_weights_doubled[1] == 0 and dual_weights_doubled[2] == 0
Return if the lamination looks like a monopod with respect to the given corner.
625941e0be7bc26dc91cd97e
@app.after_request <NEW_LINE> def after_request(response): <NEW_LINE> <INDENT> response.headers.add('Access-Control-Allow-Origin', '*') <NEW_LINE> response.headers.add('Access-Control-Allow-Headers', 'Content-Type') <NEW_LINE> response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') <NEW_LINE> respon...
For to allow us to host the server (REST API) and the client (e.g. AngularJS app) on different domains and different sub-domains. :param response: response that we need wrap :type response: flask.wrappers.Response :return: wrapped response :rtype flask.wrappers.Response
625941e02eb69b55b151cc38
def __init__(self, input_dim, output_dim, dropout=0.0): <NEW_LINE> <INDENT> super(Conv2dSubsampling, self).__init__() <NEW_LINE> self.input_dim = input_dim <NEW_LINE> self.output_dim = output_dim <NEW_LINE> self.in_conv_weight = nn.Parameter(torch.Tensor(output_dim, 1, 3, 3)) <NEW_LINE> self.in_conv_bias = nn.Parameter...
:param input_dim: the log mel feature (normally 40) :param output_dim: network size (512) :param dropout: dropout rate
625941e0090684286d50f06f
def init_app(self, application): <NEW_LINE> <INDENT> self._application = application <NEW_LINE> if 'HOST' in application.config: <NEW_LINE> <INDENT> self._hostname = application.config['HOST'] <NEW_LINE> <DEDENT> loader = ChoiceLoader([ PackageLoader('flask_fool'), self._application.jinja_loader ]) <NEW_LINE> self._app...
Extension initializer method. Configures the given application with this extension by adding the request proxy method as before handler. :param application: Application to configure.
625941e05fcc89381b1e1a45
def delJob(self, id, deadjob): <NEW_LINE> <INDENT> self.log.debug("Received delJob(%d, %d) request" % (id, deadjob)) <NEW_LINE> return self.jobQueue.delJob(id, deadjob)
delJob - Delete a job @param id: Id of job to delete @param deadjob - If 0, move the job from the live queue to the dead queue. If non-zero, remove the job from the dead queue and discard. Use with caution!
625941e07d43ff24873a3027
def set_color(self, color): <NEW_LINE> <INDENT> if color != self._color: <NEW_LINE> <INDENT> self.stale = True <NEW_LINE> <DEDENT> self._color = color
Set the color of the line ACCEPTS: any matplotlib color
625941e060cbc95b062c68c8
def GetLine(self): <NEW_LINE> <INDENT> return _lldb.SBLineEntry_GetLine(self)
GetLine(self) -> uint32_t
625941e0d58c6744b4257fe3
def _get_enabled(self): <NEW_LINE> <INDENT> return self._enabled
return the value of self.enabled
625941e026068e7796caf068
def arrow_up(self): <NEW_LINE> <INDENT> self.move_cursors((0 ,-1))
Move cursors up.
625941e0656771135c3ebbf7
def set_average(label): <NEW_LINE> <INDENT> driver_scorer.set_average(users_average_dict[label]) <NEW_LINE> pass
Get average for this user :param label: str :return:
625941e07c178a314d6ef7e9
def __init__(self, collection: str = None): <NEW_LINE> <INDENT> super(IdentifiableMongoDbPersistence, self).__init__(collection) <NEW_LINE> self._auto_generate_id: bool = True
Creates a new instance of the persistence component. :param collection: (optional) a collection name.
625941e08c3a873295158743
def getLastBody(): <NEW_LINE> <INDENT> lastId = _system.cubitWrapper.get_last_id('body') <NEW_LINE> try: <NEW_LINE> <INDENT> return _system.cubitWrapper.body(lastId) <NEW_LINE> <DEDENT> except RuntimeError as e: <NEW_LINE> <INDENT> raise _system.AdvCubitException('Cannot retrieve last created body:\n' + str(e))
Retrieve the last created body :return: The last body created within Cubit
625941e0627d3e7fe0d691d6
def test_upgrade_actions(self, mock_scandir): <NEW_LINE> <INDENT> file1 = self.build_entry('dpkg.log.upgrades') <NEW_LINE> mock_scandir.return_value = [file1] <NEW_LINE> actions = list(aptrollback.get_actions('2014-01-01 00:00:00')) <NEW_LINE> self.assertEqual(len(actions), 1)
get_actions evaluates upgrade actions
625941e0aad79263cf390dcb
def pil_to_pixbuf(im, keep_orientation=False): <NEW_LINE> <INDENT> if im.mode.startswith('RGB'): <NEW_LINE> <INDENT> has_alpha = im.mode == 'RGBA' <NEW_LINE> <DEDENT> elif im.mode in ('LA', 'P'): <NEW_LINE> <INDENT> has_alpha = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> has_alpha = False <NEW_LINE> <DEDENT> tar...
Return a pixbuf created from the PIL <im>.
625941e015fb5d323cde0e99
def add_weights_column(self, data): <NEW_LINE> <INDENT> total_market_cap = data.loc[:self.crypto_number,['marketcapusd']].astype(float).sum()[0] <NEW_LINE> log(4, "Total market cap: %d" % total_market_cap) <NEW_LINE> reweight_factor = 1 <NEW_LINE> weights_sum = 0 <NEW_LINE> weight_cap = self.weight_cap_perc / 100.0 <NE...
Calcola il peso di ciascuna coin.
625941e01b99ca400220ae37
def on_bind_field(self, field_name, field_obj): <NEW_LINE> <INDENT> if field_obj.data_key is None: <NEW_LINE> <INDENT> field_obj.data_key = to_pascal_case(field_name)
Bind PascalCase in the config with with snake_case in Python. For example, subnet_id in the code is automatically bind with SubnetId in the config file. The bind can be overwritten by specifying data_key. For example, `EBS` in the config file is not PascalCase, we have to bind it with ebs manually.
625941e0d18da76e2353285f
def __init__(self, train_list, test_list, dataset_root, options=_DEFAULT_DAVIS16_OPTIONS): <NEW_LINE> <INDENT> if not options['in_memory'] and options['data_aug']: <NEW_LINE> <INDENT> sys.stderr.write('Online data augmentation not supported when the data is not stored in memory!') <NEW_LINE> sys.exit() <NEW_LINE> <DEDE...
Initialize the Dataset object Args: train_list: TXT file or list with the paths of the images to use for training (Images must be between 0 and 255) test_list: TXT file or list with the paths of the images to use for testing (Images must be between 0 and 255) dataset_root: Path to the root of the Database Options: in...
625941e044b2445a33932418
def get_metadata(self): <NEW_LINE> <INDENT> return self._metadata
gets the image object's metadata :return: ImageMetadata class. This will be a concrete implementation of AbstractImageMetadata, and will match the ImageMetadata class associated with the particular concrete implementation of the Abstract Image. For example GeotiffImageObject will have a GeotiffImageMetadata.
625941e073bcbd0ca4b2c3fa
def get_merged_buffers(ptr): <NEW_LINE> <INDENT> weechat_version = int(weechat.info_get("version_number", "") or 0) <NEW_LINE> hdata = weechat.hdata_get("buffer") <NEW_LINE> buffers = weechat.hdata_get_list(hdata, "gui_buffers") <NEW_LINE> if weechat_version >= 0x03040000: <NEW_LINE> <INDENT> buffer = weechat.hdata_sea...
Get a list of buffers which are merged with "ptr".
625941e0f8510a7c17cf9a83
def complete(self, text=None, line_buffer=None, cursor_pos=None): <NEW_LINE> <INDENT> if cursor_pos is None: <NEW_LINE> <INDENT> cursor_pos = len(line_buffer) if text is None else len(text) <NEW_LINE> <DEDENT> if PY3: <NEW_LINE> <INDENT> latex_text = text if not line_buffer else line_buffer[:cursor_pos] <NEW_LINE> late...
Find completions for the given text and line context. Note that both the text and the line_buffer are optional, but at least one of them must be given. Parameters ---------- text : string, optional Text to perform the completion on. If not given, the line buffer is split using the instance's CompletionSpli...
625941e094891a1f4081be2f
def main(): <NEW_LINE> <INDENT> time_start = time.time() <NEW_LINE> random.seed(args.random_seed) <NEW_LINE> output_dir = os.path.expanduser(args.output_dir) <NEW_LINE> nlp.utils.mkdir(output_dir) <NEW_LINE> if args.sentencepiece: <NEW_LINE> <INDENT> logging.info('loading vocab file from sentence piece model: %s', args...
Main function.
625941e0498bea3a759b9e33