code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_rescue(self): <NEW_LINE> <INDENT> called = {'rescued': False, 'unrescued': False} <NEW_LINE> def fake_rescue(self, context, instance_ref, network_info, image_meta): <NEW_LINE> <INDENT> called['rescued'] = True <NEW_LINE> <DEDENT> self.stubs.Set(nova.virt.fake.FakeDriver, 'rescue', fake_rescue) <NEW_LINE> def f... | Ensure instance can be rescued and unrescued | 625941b9b57a9660fec336ed |
def test_fspl(self): <NEW_LINE> <INDENT> distance = np.array([[1000000]]) <NEW_LINE> lambda_ = np.array([[3e8 / 1e3]]) <NEW_LINE> self.assertTrue(ut.fspl(distance, lambda_)) | Test utility.fspl. | 625941b9925a0f43d2549ce1 |
def finalize_score(puzzle, view, unguessed_consonants, current_score): <NEW_LINE> <INDENT> for ch in range(len(puzzle)): <NEW_LINE> <INDENT> if puzzle[ch] in unguessed_consonants: <NEW_LINE> <INDENT> current_score += CONSONANT_BONUS <NEW_LINE> <DEDENT> <DEDENT> return current_score | (str, str, str, int) -> int
Return the final score by adding CONSONANT_BONUS to current_score for
each letter in view that's also in unguessed_consonants, but is
hidden in view.
>>> finalize_score('banana', 'ba^a^a', 'npr', 3)
7
>>> finalize_score('santiago', 'santiago', 'rp', 2)
2 | 625941b91f5feb6acb0c49c2 |
def get_default_person(self): <NEW_LINE> <INDENT> if not self.db_is_open: <NEW_LINE> <INDENT> LOG.debug("database is closed") <NEW_LINE> <DEDENT> return None | Return the default Person of the database. | 625941b931939e2706e4ccdd |
def test_api_play_quiz(self): <NEW_LINE> <INDENT> payload=dict(previous_questions=[]) <NEW_LINE> response = self.client.post(url_for('quizzes.play_quiz'), json=payload) <NEW_LINE> json_data = response.json['question'] <NEW_LINE> self.assertIsNotNone(json_data['question']) <NEW_LINE> self.assertIsNotNone(json_data['cate... | Quiz Turn: paly a quiz turn | 625941b92c8b7c6e89b35631 |
def is_expired(self): <NEW_LINE> <INDENT> return datetime.utcnow() >= self.expires | Check token expiration with timezone awareness | 625941b95f7d997b87174909 |
def __init__(self, *, confidence_level: str = None, text: str = None, provenance_ids: List[str] = None, location: 'Location' = None) -> None: <NEW_LINE> <INDENT> self.confidence_level = confidence_level <NEW_LINE> self.text = text <NEW_LINE> self.provenance_ids = provenance_ids <NEW_LINE> self.location = location | Initialize a ContractTypes object.
:param str confidence_level: (optional) The confidence level in the
identification of the contract type.
:param str text: (optional) The contract type.
:param List[str] provenance_ids: (optional) Hashed values that you can send
to IBM to provide feedback or receive supp... | 625941b9097d151d1a222cc9 |
def cast(*args): <NEW_LINE> <INDENT> return _itkIntensityWindowingImageFilterPython.itkIntensityWindowingImageFilterIF3IUS3_cast(*args) | cast(itkLightObject obj) -> itkIntensityWindowingImageFilterIF3IUS3 | 625941b90383005118ecf452 |
def __repr__(self): <NEW_LINE> <INDENT> return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1])) | Return a string representation of this object that can
be evaluated as a Python expression. | 625941b923849d37ff7b2eff |
def testLoadListsWithoutRepetitions(self): <NEW_LINE> <INDENT> ld = ListDifference("testdirs/01/in02.txt", "testdirs/01/diff02.txt", "testdirs/01/out02.txt") <NEW_LINE> ld.inputList.sort() <NEW_LINE> ld.differenceList.sort() <NEW_LINE> self.assertEqual(ld.inputList, ["goodbye", "hello", "joe", "john", "karl"]) <NEW_LIN... | Open the list files and load the contents of them as lists but without repetitions | 625941b95166f23b2e1a4fc6 |
def dag_to_str(self, morf_dag): <NEW_LINE> <INDENT> conc_dag = '' <NEW_LINE> for item in morf_dag: <NEW_LINE> <INDENT> num1, num2, (forma, lemat, tag, posp, kwal) = item <NEW_LINE> line_string = '\t'.join((str(num1), str(num2), forma, lemat, tag, ','.join(posp), ','.join(kwal), '0.0', '', '', '' + '\n')) <NEW_LINE> con... | Convert a DAG in the Morfeusz-compliant format to a DAG in the
Concraft-compliant format. | 625941b9f548e778e58cd3e9 |
def get_required_slot_names_by_task(taskname): <NEW_LINE> <INDENT> filename = "task_{}.json".format(taskname) <NEW_LINE> task_config_path = os.path.join(this_file_path, "template", filename) <NEW_LINE> with open(task_config_path) as json_file: <NEW_LINE> <INDENT> data = json.load(json_file) <NEW_LINE> <DEDENT> return d... | read taskname from config json and
then read the slot config file
to get the slot names
:param taskname: current task/story name
:return: the slot names , list[str] | 625941b9be383301e01b52fa |
def createDistanceMatrix(self, distance_function, child_process_chunksize = 15, number_of_cores = None): <NEW_LINE> <INDENT> if number_of_cores is None: <NEW_LINE> <INDENT> number_of_cores = multiprocessing.cpu_count() <NEW_LINE> <DEDENT> print('Creating distance matrix using ', number_of_cores, 'cores.') <NEW_LINE> ge... | Takes a dictionary of KO sets and returns a distance (or similarity) matrix which is basically how many genes do they have in common. | 625941b9f7d966606f6a9e75 |
def test_calls_permissions_for_user(self): <NEW_LINE> <INDENT> check_permissions(self.parent, self.user, False, False) <NEW_LINE> assert self.parent.permissions_for_user.called | Check call to parent page's permissions_for_user method. | 625941b93346ee7daa2b2bd7 |
def index(self): <NEW_LINE> <INDENT> return self.__sent[0].para_index() | Gets the index of the paragraph. | 625941b9711fe17d825421e0 |
def publish(self, subject, message): <NEW_LINE> <INDENT> log.debug('publish(%s, %s)', str(subject), str(message)) <NEW_LINE> for owner in self._subscriptions.keys(): <NEW_LINE> <INDENT> for token in self._subscriptions[owner].keys(): <NEW_LINE> <INDENT> if subject in self._subscriptions[owner][token]: <NEW_LINE> <INDEN... | Send messade to all subscribers
:param subject: message subject
:param message: message data | 625941b9ad47b63b2c509df7 |
def __check_cancel(self): <NEW_LINE> <INDENT> return self.__canceling | Private method. Provides a callback method for internal
code to use to determine whether the current action has been
canceled. | 625941b963f4b57ef0000f90 |
def ResetDisplayList(self): <NEW_LINE> <INDENT> pass | ResetDisplayList. | 625941b97047854f462a127b |
def test_bad_git_url(self): <NEW_LINE> <INDENT> course_key = CourseLocator('org', 'course', 'run') <NEW_LINE> with self.assertRaisesRegexp(GitExportError, unicode(GitExportError.URL_BAD)): <NEW_LINE> <INDENT> git_export_utils.export_to_git(course_key, 'Sillyness') <NEW_LINE> <DEDENT> with self.assertRaisesRegexp(GitExp... | Test several bad URLs for validation | 625941b999cbb53fe6792a55 |
def computeForce(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = self.position - other.position <NEW_LINE> self.force = self.charge * other.charge / r.norm() ** 3 * r <NEW_LINE> <DEDENT> except (AttributeError, TypeError, ValueError): <NEW_LINE> <INDENT> raise TypeError("Tried to compute the force create... | Calcule la force électrostatique de Coulomb exercée par un Ion other
sur self. Masque la méthode de Particle.
Args :
other(Ion): Un autre Ion, source de l'interaction.
Raises :
TypeError si other n'est pas un objet Ion | 625941b931939e2706e4ccde |
def force_long_type(): <NEW_LINE> <INDENT> Marshaller.dispatch[type(0)] = lambda _, v, w: w( "<value><i8>%d</i8></value>" % v) | Since in python3 theres no long type anymore, we have to force the use of long type at xmlrpc here.
:return: | 625941b9b7558d58953c4d89 |
def test_generic_fk(self): <NEW_LINE> <INDENT> class TagSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> tagged_item = serializers.StringRelatedField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Tag <NEW_LINE> fields = ('tag', 'tagged_item') <NEW_LINE> <DEDENT> <DEDENT> serializer = TagSerializer(Ta... | Test a relationship that spans a GenericForeignKey field.
IE. A forward generic relationship. | 625941b94428ac0f6e5ba660 |
def _raw_fields(self, positions, scatterer, medium_wavevec, medium_index, illum_polarization): <NEW_LINE> <INDENT> index_ratio = scatterer.n / medium_index <NEW_LINE> size_parameter = medium_wavevec * scatterer.r <NEW_LINE> rho, phi, z = positions <NEW_LINE> pol_angle = np.arctan2( illum_polarization.values[1], illum_p... | Parameters
----------
positions : (3, N) numpy.ndarray
The (k * rho, phi, z) coordinates, relative to the sphere,
of the points to calculate the fields. Note that the radial
coordinate is rescaled by the wavevector.
scatterer : ``scatterer.Sphere`` object
medium_wavevec : float
medium_index : float
illum_po... | 625941b98a43f66fc4b53ed7 |
def get_command_line_configuration(configuration_schema, command_line_options): <NEW_LINE> <INDENT> command_line_options = command_line_options[1:] <NEW_LINE> command_line_options = " ".join(command_line_options) <NEW_LINE> command_line_options = command_line_options.replace("=", " ") <NEW_LINE> command_line_options = ... | Get configuration, based on the given arguments to the program.
Notes:
* The first argument is omitted, as it's the script path.
* Both '--option=value' and '--option value' formats are supported.
* Both '--<option>' and '-<option>' formats are supported.
Args:
configuration_schema (dict): a match bet... | 625941b9293b9510aa2c3107 |
def get_user(user_id): <NEW_LINE> <INDENT> return User.query.get(user_id) | Return a speciic user from the database. | 625941b9de87d2750b85fbfc |
@api_view(["GET"]) <NEW_LINE> @permission_classes([AllowAny]) <NEW_LINE> def monthly_leaderboard(request): <NEW_LINE> <INDENT> date = datetime.now() <NEW_LINE> month = date.month <NEW_LINE> year = date.year <NEW_LINE> topmonth = ( Trash.objects.values("user__username") .annotate(Sum("weight")) .filter(takeout_date__yea... | This view returns a list of the top 5 of the rankings for low waste given the month. | 625941b916aa5153ce3622e6 |
def conv2D(x, W): <NEW_LINE> <INDENT> return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding = "SAME") | Initialise a 2D Tensorflow convolutional layer based on input vector x and filter vector W
Args:
x: Input matrix of the convolutional layer. Tensorflow variable of unknown dimension
W: Input filter of the convolutional layer. 4D Tensorflow variable of dimension (filter_height, filter_width, nb_input_channels, nb_... | 625941b9d8ef3951e32433ab |
def test_help_for_command_add(): <NEW_LINE> <INDENT> usage_string = ( 'usage: dispass add [-g] [-n] [-s] <labelspec> [<labelspec2>] [...]\n' ' dispass add [-i] [-g] [-h]' ) <NEW_LINE> cmd = DispassCommand(['add', '-h']) <NEW_LINE> assert cmd_output_startswith(cmd, usage_string) <NEW_LINE> cmd = DispassCommand(['a... | commands: get help for add command via all possible combinations | 625941b94e696a04525c92c3 |
def worker_start(self, worker): <NEW_LINE> <INDENT> worker.servers[self.name] = servers = [] <NEW_LINE> for sock in worker.params.sockets: <NEW_LINE> <INDENT> server = self.create_server(worker, sock.sock) <NEW_LINE> server.bind_event('stop', partial(self._stop_worker, worker)) <NEW_LINE> servers.append(server) | Start the worker by invoking the :meth:`create_server` method. | 625941b9851cf427c661a385 |
def get_sequential_model(input_nodes, first_layer, hidden_layer, output_shape, activation_input, activation_hidden, activation_output): <NEW_LINE> <INDENT> model = Sequential() <NEW_LINE> model.add(Dense(first_layer, activation = activation_input, input_shape = input_nodes)) <NEW_LINE> for layer in hidden_layer: <NEW_L... | Define a dense sequential neural network with input_nodes number of input nodes,
hidden_layer a list of hidden layers, output_shape defines output shape. In addition
the types of activation need to be defined. | 625941b94e4d5625662d424b |
def output(self): <NEW_LINE> <INDENT> self.x_imgs = self.prev_layer.output() <NEW_LINE> return numpy.asarray(map( lambda i: tanh(self.b[i] + reduce( lambda res, j: res + conv2d(self.x_imgs[j], self.theta[i]), self.connections[i], 0 )), xrange(0, len(self.connections)) )) | Generate output of this layer | 625941b9cdde0d52a9e52e9d |
def acc(self): <NEW_LINE> <INDENT> AccountDialog(self) | Instantiate account information window. | 625941b9d58c6744b4257acf |
def trap(self, height): <NEW_LINE> <INDENT> stack = [-1] <NEW_LINE> rightmax=0; <NEW_LINE> for i in range(len(height)-1,-1,-1): <NEW_LINE> <INDENT> if rightmax < height[i]: <NEW_LINE> <INDENT> stack.append(i) <NEW_LINE> rightmax = height[i] <NEW_LINE> <DEDENT> <DEDENT> leftmax=0 <NEW_LINE> sum=0 <NEW_LINE> for i in ran... | :type height: List[int]
:rtype: int | 625941b97d43ff24873a2b12 |
def _release(self, event): <NEW_LINE> <INDENT> for zoom_id in self._ids_zoom: <NEW_LINE> <INDENT> self.figure.canvas.mpl_disconnect(zoom_id) <NEW_LINE> <DEDENT> self._ids_zoom = [] <NEW_LINE> if not self._xypress: <NEW_LINE> <INDENT> self._cancel_action() <NEW_LINE> return <NEW_LINE> <DEDENT> last_a = [] <NEW_LINE> for... | the release mouse button callback in zoom to rect mode | 625941b992d797404e303ff8 |
def custom_lookup_rows(self, key, values, fields=[]): <NEW_LINE> <INDENT> db = current.db <NEW_LINE> table = current.s3db.supply_item_category <NEW_LINE> ctable = db.supply_catalog <NEW_LINE> ptable = db.supply_item_category.with_alias("supply_parent_item_category") <NEW_LINE> gtable = db.supply_item_category.with_alia... | Custom lookup method for item category rows, does a
left join with the parent category. Parameters
key and fields are not used, but are kept for API
compatibility reasons.
@param values: the supply_item_category IDs | 625941b97b25080760e392c9 |
def __update_register_features(self, unique_id, feature): <NEW_LINE> <INDENT> if self.__next_feature_index > self.__register_features.shape[0] - len(feature['feature']): <NEW_LINE> <INDENT> self.__register_features = np.concatenate((self.__register_features, np.empty(shape=self.__register_features.shape, dtype=np.float... | Update register features array | 625941b98e71fb1e9831d61c |
def _stack_to_string(self, stack): <NEW_LINE> <INDENT> value_str = " |" <NEW_LINE> while not stack.is_empty(): <NEW_LINE> <INDENT> value_str = F"| {stack.top()} {value_str}" <NEW_LINE> stack.pop() <NEW_LINE> <DEDENT> return value_str | Return a string of the stack values seperated by "|". | 625941b957b8e32f5248330f |
def columns(): <NEW_LINE> <INDENT> con = sqlite3.connect(DB_PATH) <NEW_LINE> cur = con.cursor() <NEW_LINE> cur.execute("SELECT * " "FROM {tbl} " "LIMIT 1".format(tbl=REG_TBL)) <NEW_LINE> names = [description[0] for description in cur.description] <NEW_LINE> cur.close() <NEW_LINE> con.close() <NEW_LINE> return names | list column names
:return list: of column names | 625941b9cb5e8a47e48b791d |
def rhoc_z(self, z): <NEW_LINE> <INDENT> return self.rhoc*(1+z)**3 | :param z:
:return: | 625941b99c8ee82313fbb5e3 |
def results_to_proto(results): <NEW_LINE> <INDENT> results_proto = Results() <NEW_LINE> for result in results: <NEW_LINE> <INDENT> results_proto.results.append(result_to_proto(result)) <NEW_LINE> <DEDENT> return results_proto | Given a list of result dicts, convert it to a tcav.Results proto.
Args:
results: a list of dictionaries returned by tcav.run()
Returns:
TCAV.Results proto | 625941b923849d37ff7b2f00 |
def _is_straight(self): <NEW_LINE> <INDENT> self.hand.sort(key=Card.getRank) <NEW_LINE> _isStraight = True <NEW_LINE> if self.hand[-1].getRank() == 14 and self.hand[0].getRank() == 2: <NEW_LINE> <INDENT> _previousRank = 1 <NEW_LINE> for card in self.hand[:-1]: <NEW_LINE> <INDENT> if not card.getRank() == _previousRank ... | Five cards with consecutive ranks | 625941b91d351010ab85598c |
def test_trust_key(self): <NEW_LINE> <INDENT> ret = {'message': 'Only specify one argument, fingerprint or keyid', 'res': False} <NEW_LINE> ret1 = {'message': 'KeyID 3F0C8 not in GPG keychain', 'res': False} <NEW_LINE> ret2 = {'message': 'Required argument, fingerprint or keyid', 'res': False} <NEW_LINE> ret3 = ('ERROR... | Tests if it set the trust level for a key in GPG keychain | 625941b938b623060ff0ac5e |
def check_brackets(label): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> pushChars, popChars = "<({[", ">)}]" <NEW_LINE> for c in label: <NEW_LINE> <INDENT> if c in pushChars: <NEW_LINE> <INDENT> stack.append(c) <NEW_LINE> <DEDENT> elif c in popChars: <NEW_LINE> <INDENT> if not stack: <NEW_LINE> <INDENT> return False <NEW_... | check if all brackets in *label match, return True / False | 625941b9d164cc6175782bbc |
def __init__(self, instance_of): <NEW_LINE> <INDENT> if not isinstance(instance_of, six.class_types): <NEW_LINE> <INDENT> raise Error('ExternalDependency provider expects to get class, ' + 'got {0} instead'.format(str(instance_of))) <NEW_LINE> <DEDENT> self.instance_of = instance_of <NEW_LINE> self.provide = self.__cal... | Initializer. | 625941b94c3428357757c199 |
def malloc(self, shape, dtype=None, stream=None, fill=None): <NEW_LINE> <INDENT> stream = stream or self.stream <NEW_LINE> dtype = dtype or self.device._default_dtype <NEW_LINE> return self.device.malloc(shape, dtype, fill, stream) | Allocates device memory.
Parameters
----------
shape : tuple
The shape of the array to allocate.
dtype : np.dtype
That data type of the array.
fill : scalar or np.ndarray, optional
Default value to set allocated array to.
stream : c_void_p, optional
CUDA stream to associate the returned obje... | 625941b9a4f1c619b28afeb0 |
def get_hangouts_tokens(cookies, driverpath): <NEW_LINE> <INDENT> tmprinter = TMPrinter() <NEW_LINE> chrome_options = get_chrome_options_args(config.headless) <NEW_LINE> options = { 'connection_timeout': None } <NEW_LINE> tmprinter.out("Starting browser...") <NEW_LINE> driver = webdriver.Chrome( executable_path=driverp... | gets auth and hangout token | 625941b9d268445f265b4ce4 |
def start(self, args): <NEW_LINE> <INDENT> enable_log() <NEW_LINE> self.results = App._init_results(self.config) <NEW_LINE> if args.poll_seconds: <NEW_LINE> <INDENT> self.config.override_monitor_setting( 'poll_seconds', args.poll_seconds ) <NEW_LINE> <DEDENT> if self.config.log_file: <NEW_LINE> <INDENT> set_log_file(se... | Start up all of the application components | 625941b9c432627299f04ab3 |
def dataCleanup(data): <NEW_LINE> <INDENT> classDistribution = defaultdict(list) <NEW_LINE> for i in range(0, len(data)): <NEW_LINE> <INDENT> className = data[i][14] <NEW_LINE> if className not in classDistribution: <NEW_LINE> <INDENT> classDistribution[className] = [] <NEW_LINE> <DEDENT> classDistribution[className].a... | The function creates a dictionary with classes as keys and values as the instances
belonging to that class. The input is train fold dataset.
:param data: train fold
:return: classDistribution : dictionary with classes as keys and instances as values. | 625941b916aa5153ce3622e7 |
def __init__(self): <NEW_LINE> <INDENT> self.logger = logging.getLogger("main.database.DbUtils") | Database utilities | 625941b915baa723493c3de1 |
@app.route("/history") <NEW_LINE> @login_required <NEW_LINE> def history(): <NEW_LINE> <INDENT> rows = db.execute("SELECT * FROM lookups WHERE user_id = :user", user=session["user_id"]) <NEW_LINE> lookups = [] <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> lookups.insert(0,list((row['brand'], row['title'], row['vegan_... | Show history of transactions | 625941b95fcc89381b1e1533 |
def scatterplot(self,plotobj): <NEW_LINE> <INDENT> plt.subplots(1) <NEW_LINE> arr=plotobj.histogram.weights.nonzero() <NEW_LINE> y=arr[1] <NEW_LINE> x=arr[0] <NEW_LINE> cc = plotobj.histogram.weights[x,y] <NEW_LINE> plt.scatter(x,y,s=50, c=cc, label=plotobj.histogram.title) <NEW_LINE> plt.legend() <NEW_LINE> plt.show() | A routine for replotting sparse data as a scatter plot.
plotobj should be a maps[register_number] not a dd(histogram_number) instance. | 625941b92ae34c7f2600cfa1 |
def is_adjacent_to(self, o): <NEW_LINE> <INDENT> assert type(o) is Location, "incorrect type of arg o: should be Location, is {}".format(type(o)) <NEW_LINE> result = _lib.bc_Location_is_adjacent_to(self._ptr, o._ptr) <NEW_LINE> _check_errors() <NEW_LINE> result = bool(result) <NEW_LINE> return result | Determines whether this location is adjacent to the specified location,
including diagonally. Note that squares are not adjacent to themselves,
and squares on different planets are not adjacent to each other. Also,
nothing is adjacent to something not on a map.
:type self: Location
:type o: Location
:rtype: bool | 625941b9de87d2750b85fbfd |
def reachableReactions(rxn, sinks): <NEW_LINE> <INDENT> soup = sinks <NEW_LINE> pending = set(rxn) <NEW_LINE> newPending, newSoup = inSoup(rxn, pending, soup) <NEW_LINE> iteration = 0 <NEW_LINE> while (len(newPending - pending) > 0 or len(newSoup - soup) > 0): <NEW_LINE> <INDENT> pending = newPending <NEW_LINE> soup = ... | Look for reachable reactions. | 625941b999fddb7c1c9de202 |
def read_bytes(self, expected_length): <NEW_LINE> <INDENT> raise NotImplementedError | Read fixed-length bytes | 625941b9d99f1b3c44c67405 |
def __init__(self, chromosomes): <NEW_LINE> <INDENT> super(InMemoryRefReader, self).__init__() <NEW_LINE> self._chroms = {} <NEW_LINE> contigs = [] <NEW_LINE> for i, (contig_name, start, bases) in enumerate(chromosomes): <NEW_LINE> <INDENT> if start < 0: <NEW_LINE> <INDENT> raise ValueError('start={} must be >= for chr... | Initializes an InMemoryRefReader using data from chromosomes.
Args:
chromosomes: List[tuple]. The chromosomes we are caching in memory as a
list of tuples. Each tuple must be exactly three string elements in
length, containing (chromosome name, start, bases).
Raises:
ValueError: If any of the InMemoryChro... | 625941b9d99f1b3c44c67406 |
def b(text: str, func: callable = None, *arg, **kw) -> None: <NEW_LINE> <INDENT> global m <NEW_LINE> m.b(text, func, *arg, **kw) | 【控件:按钮】
向当前页面的最后一行的末尾插入按钮。
text: str
按钮上的文本。
func: callable
返回函数。
当按钮按下时,返回函数被触发,且其执行效果类似于 func(*arg, **kw);
color: str
设置按钮颜色。颜色名可从 https://www.w3schools.com/colors/colors_names.asp 中任意选择,如 "red"。
disabled: bool
设置按钮禁用与否。若为True,则按钮被禁用,无法点击。
popup: str
设置按钮气泡文本。若设置,则当鼠标移到按钮上方的时候,会弹出写有文本的气泡。
... | 625941b94527f215b584c2ca |
@cache.cache('pgcd', expire=3600) <NEW_LINE> def pgcd(a, b): <NEW_LINE> <INDENT> if a < b: <NEW_LINE> <INDENT> return pgcd(b, a) <NEW_LINE> <DEDENT> if b == 0: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return pgcd(b, (a % b)) | the euclidean algorithm | 625941b907d97122c41786fa |
def _calculate_s_powder_over_atoms_core(self, q_indx=None): <NEW_LINE> <INDENT> atoms_items = {} <NEW_LINE> atoms = range(self._num_atoms) <NEW_LINE> self._prepare_data(k_point=q_indx) <NEW_LINE> if PATHOS_FOUND: <NEW_LINE> <INDENT> p_local = ProcessingPool(nodes=AbinsModules.AbinsParameters.threads) <NEW_LINE> result ... | Helper function for _calculate_s_powder_1d.
:returns: Python dictionary with S data | 625941b9379a373c97cfa9b9 |
def position_after(self, a, b): <NEW_LINE> <INDENT> return self.position_at_least(a, b) and not self.position_equal(a, b) | Returns true if position 'a' is after 'b'. | 625941b9be7bc26dc91cd474 |
def identity(payload): <NEW_LINE> <INDENT> user_id = payload['identity'] <NEW_LINE> return UserModel.find_by_id(user_id) | Receives the JWT payload. | 625941b9eab8aa0e5d26d9cd |
def pc_input_buffers_full_avg(self, *args): <NEW_LINE> <INDENT> return _blocks_swig1.vector_sink_i_sptr_pc_input_buffers_full_avg(self, *args) | pc_input_buffers_full_avg(vector_sink_i_sptr self, int which) -> float
pc_input_buffers_full_avg(vector_sink_i_sptr self) -> pmt_vector_float | 625941b91d351010ab85598d |
def sessionattendancelog_save_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'id', 'unknown_base_type' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iterite... | Create or edit a class attendance log # noqa: E501
Allows the user to create or edit a class attendance log. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.sessionattendancelog_save_with_http_info(id, async_req=T... | 625941b9925a0f43d2549ce3 |
def ebi_taxid_to_lineage(tax_id): <NEW_LINE> <INDENT> url = 'http://www.ebi.ac.uk/ena/data/taxonomy/v1/taxon/tax-id/{}' <NEW_LINE> if tax_id == 0 or tax_id == 1: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> response = requests.get(url.format(tax_id), timeout=5) <NEW_LINE> result = json.loads(response.text)... | Returns scientific name and lineage for a given taxid using EBI's taxonomy API
e.g.('Retroviridae', ['Viruses', 'Retro-transcribing viruses']) | 625941b921bff66bcd6847c4 |
def embedding_lookup(input_ids, vocab_size, precision, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False): <NEW_LINE> <INDENT> if input_ids.shape.ndims == 2: <NEW_LINE> <INDENT> input_ids = tf.expand_dims(input_ids, axis=[-1]) <NEW_LINE> <DEDENT> embedding_t... | Looks up words embeddings for id tensor.
Args:
input_ids: int32 Tensor of shape [batch_size, seq_length] containing word
ids.
vocab_size: int. Size of the embedding vocabulary.
embedding_size: int. Width of the word embeddings.
initializer_range: float. Embedding initialization range.
word_embedding_name... | 625941b976d4e153a657e99f |
def checkoutput(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out = su.check_output(*args, **kwargs) <NEW_LINE> out = out.decode('utf-8') <NEW_LINE> <DEDENT> except su.CalledProcessError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return out | Just a wrapper to return utf-8 from check_output | 625941b9d486a94d0b98dfbc |
def preprocess(page): <NEW_LINE> <INDENT> pattern = "([a-zA-Z]+(?:'[a-z]+)?)" <NEW_LINE> tokens_raw = nltk.regexp_tokenize(page, pattern) <NEW_LINE> tokens = [word.lower() for word in tokens_raw] <NEW_LINE> stopwords_list = stopwords.words('english') <NEW_LINE> stopwords_list += list(string.punctuation) <NEW_LINE> stop... | Preprocess a document or page
Tokenize, remove all stopwords from the document, and lemmatize each word. | 625941b9498bea3a759b9920 |
def get_download_ids(keyword, field, size=10000): <NEW_LINE> <INDENT> n_iter = DOWNLOAD_QUERY_SIZE // size <NEW_LINE> results = get_total_results(keyword) <NEW_LINE> if results is None: <NEW_LINE> <INDENT> logger.error("Error retrieving total results. Max number of attempts reached") <NEW_LINE> return <NEW_LINE> <DEDEN... | returns a generator that
yields list of transaction ids in chunksize SIZE
Note: this only works for fields in ES of integer type. | 625941b99b70327d1c4e0c43 |
@APP.route('/') <NEW_LINE> def peyl_page(): <NEW_LINE> <INDENT> return render_template('main.html') | Provides the main.html template | 625941b9507cdc57c6306b43 |
def getExistingUserInfo(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> entry = self._users.next() <NEW_LINE> uid = entry.pw_uid <NEW_LINE> if uid not in self._uids: <NEW_LINE> <INDENT> self._uids.add(uid) <NEW_LINE> return entry | Read and return the next record from C{self._users}, filtering out
any records with previously seen uid values (as these cannot be
found with C{getpwuid} and only cause trouble). | 625941b90383005118ecf454 |
def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> self.q_values = defaultdict(util.Counter) | You can initialize Q-values here... | 625941b971ff763f4b5494fe |
def legendre_old(nu, mu, x): <NEW_LINE> <INDENT> if mu < 0 or mu > nu: <NEW_LINE> <INDENT> raise ValueError('require 0 <= mu <= nu, but mu=%d and nu=%d' % (nu, mu)) <NEW_LINE> <DEDENT> if mu == 0: <NEW_LINE> <INDENT> p_nu = 1.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = 1 <NEW_LINE> if mu... | Compute the associated Legendre polynomial with degree nu and order mu.
This function uses the recursion formula in the degree nu.
(Abramowitz & Stegun, Section 8.5.) | 625941b9f548e778e58cd3eb |
def get_problems(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.__get_problems_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.__get_problems_with_http_info(**kwargs) <NEW_LINE> retu... | get_problems # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_problems(async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str locator:
:param str fields:
:return: ProblemOccurrences
... | 625941b9442bda511e8be295 |
def extract_name_from_unimarc(self, unimarc): <NEW_LINE> <INDENT> data = dict() <NEW_LINE> sort_name_in_progress = [] <NEW_LINE> for (code, key) in ( ('a', 'family'), ('b', 'given'), ('c', 'extra'), ): <NEW_LINE> <INDENT> value = self._xpath1(unimarc, 'ns2:subfield[@code="%s"]' % code) <NEW_LINE> if value is not None a... | Turn a UNIMARC tag into a 4-tuple:
(given name, family name, extra, sort name) | 625941b921bff66bcd6847c5 |
def build(self, data_sources): <NEW_LINE> <INDENT> for data_source in data_sources: <NEW_LINE> <INDENT> with data_source as stream: <NEW_LINE> <INDENT> for source, target in stream: <NEW_LINE> <INDENT> self._add_line(source, is_source=True) <NEW_LINE> self._add_line(target, is_source=False) <NEW_LINE> <DEDENT> <DEDENT>... | It builds a new processor from a collection of data sources.
A data source object must support __enter__ and __exit__ method to open and close the data stream.
The data source object myst also be iterable returning a pair of strings: source and target.
:param data_sources: a collection of data source objects
:return: ... | 625941b956ac1b37e626404f |
def __eq__(self, other: Any) -> bool: <NEW_LINE> <INDENT> return isinstance(other, Bell) and other.index == self.index | Determines if two Bells are equal. | 625941b9b5575c28eb68de6d |
def _argmin(a, positions, shape, dtype): <NEW_LINE> <INDENT> result = numpy.empty((1,), dtype=dtype) <NEW_LINE> pos_nd = numpy.unravel_index(positions[numpy.argmin(a)], shape) <NEW_LINE> for i, pos_nd_i in enumerate(pos_nd): <NEW_LINE> <INDENT> result["pos"][0, i] = pos_nd_i <NEW_LINE> <DEDENT> return result[0] | Find original array position corresponding to the minimum. | 625941b963d6d428bbe4435f |
@pytest.mark.tier(2) <NEW_LINE> @pytest.mark.meta(blockers=[1200783, 1207209]) <NEW_LINE> def test_iso_provision_from_template(provider, vm_name, smtp_test, datastore_init, request, setup_provider): <NEW_LINE> <INDENT> iso_template, host, datastore, iso_file, iso_kickstart, iso_root_password, iso_image_type, vla... | Tests ISO provisioning
Metadata:
test_flag: iso, provision
suite: infra_provisioning | 625941b930c21e258bdfa30d |
def eigvals_3x3(X: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> x00, x01, x02, x10, x11, x12, x20, x21, x22 = X.ravel() <NEW_LINE> b = x00 + x11 + x22 <NEW_LINE> c = x00 * x11 + x00 * x22 - x01 * x10 - x02 * x20 + x11 * x22 - x12 * x21 <NEW_LINE> d = ( -x00 * x11 * x22 + x00 * x12 * x21 + x01 * x10 * x22 - x01 * x12 ... | Eigenvalues of 3-dimensional real square matrix
Args:
X: 3-dimensional square matrix
Returns:
Eigenvalues of `X`
Notes:
This symbolic expression doesn't work for complex eigenvalues
References:
M.J. Kronenbur. A Method for Fast Diagonalization ofa 2x2 or 3x3 Real Symmetric Matrix | 625941b9e64d504609d746b0 |
def test_login_correct_set_to_True(self): <NEW_LINE> <INDENT> tester = app.test_client(self) <NEW_LINE> response = tester.post('/login', data=dict(username="user1"), follow_redirects=True) <NEW_LINE> self.assertEqual(app_info["logged"], True) <NEW_LINE> print("test_login_correct_set_to_True route -- PASS") | Test LOGIN set to True | 625941b9d58c6744b4257ad0 |
def __find_framing_lines(self, orth_lines, frame): <NEW_LINE> <INDENT> min_horz, max_horz = None, None <NEW_LINE> min_vert, max_vert = None, None <NEW_LINE> for rho, theta in orth_lines[0]: <NEW_LINE> <INDENT> if (min_vert is None or abs(rho) < abs(min_vert[0])): <NEW_LINE> <INDENT> min_vert = (rho, theta) <NEW_LINE> <... | Find the framing lines, which are the min/max horizontal and
vertical lines | 625941b9ad47b63b2c509df9 |
def acls(self): <NEW_LINE> <INDENT> return { 1: [ {'rule': { 'dl_type': IPV4_ETH, 'ip_proto': 1, 'actions': { 'allow': 0, 'output': [ {'tunnel': { 'type': 'vlan', 'tunnel_id': 200, 'dp': self.topo.switches_by_id[0], 'port': self.host_port_maps[1][0][0]}} ] } }} ] } | Return ACL config | 625941b997e22403b379ce09 |
def verify_import_function_called_when_import_button_clicked_test(self): <NEW_LINE> <INDENT> with patch('PyQt5.QtWidgets.QDialog.exec'): <NEW_LINE> <INDENT> self.form.on_import_as_new_button_clicked = MagicMock() <NEW_LINE> self.form.exec() <NEW_LINE> self.form.service_type_combo_box.setCurrentIndex(1) <NEW_LINE> self.... | Test that the "on_import_as_new_button_clicked" function is executed when the "Import New" button is clicked | 625941b97047854f462a127d |
def retrieve_potential_adtrust_agents(api): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dl_enabled_masters = api.Command.server_find( ipamindomainlevel=MIN_DOMAIN_LEVEL, all=True)['result'] <NEW_LINE> <DEDENT> except (errors.DatabaseError, errors.NetworkError) as e: <NEW_LINE> <INDENT> logger.error( "Could not retriev... | Retrieve a sorted list of potential AD trust agents
:param api: initialized API instance
:returns: sorted list of FQDNs of masters which are not AD trust agents | 625941b994891a1f4081b918 |
def format_func(args): <NEW_LINE> <INDENT> if args.all and args.branch is not None: <NEW_LINE> <INDENT> print("Only specify branch or all, but not both!") <NEW_LINE> return False <NEW_LINE> <DEDENT> if not args.branch: <NEW_LINE> <INDENT> if args.all: <NEW_LINE> <INDENT> files = get_files_to_check_working_tree() <NEW_L... | Format files command entry point
| 625941b9187af65679ca4f8d |
def photometry(self): <NEW_LINE> <INDENT> self.SNR = [] <NEW_LINE> self.phot_err = [] <NEW_LINE> self.phot_c = [] <NEW_LINE> self.phot = [] <NEW_LINE> self.lam_eff = [] <NEW_LINE> self.lam_c = [] <NEW_LINE> self.lam_err = [] <NEW_LINE> self.tag = [] <NEW_LINE> self.eazytag = [] <NEW_LINE> self.det = [] <NEW_LINE> for F... | Photometry of the SED using the filters available, gives the flux in fnu | 625941b9046cf37aa974cbba |
def commit(self): <NEW_LINE> <INDENT> self.db_connection.commit() | Commit changes from any insert or update statements. | 625941b966673b3332b91f07 |
def validate(self): <NEW_LINE> <INDENT> method_names = sorted([i for i in dir(self) if i.startswith("_validate") and callable(getattr(self, i))]) <NEW_LINE> for method_name in method_names: <NEW_LINE> <INDENT> method = getattr(self, method_name) <NEW_LINE> method() | Validate attributes by running all self._validate_*() methods.
:raises TypeError: if an attribute has invalid type
:raises ValueError: if an attribute contains invalid value | 625941b930dc7b76659017da |
def test_use_short_margin(self): <NEW_LINE> <INDENT> coco_ast = self.get_coco_ast("Semantic { " "forbid ruleset{contains_all([ " "property{name=='margin-right'}," "property{name=='margin-left'}," "property{name=='margin-top'}," "property{name=='margin-bottom'}" "])} message '' }") <NEW_LINE> css_tree = helpers.ParseHel... | Use the shorthand margin property instead | 625941b9d10714528d5ffb4f |
def cal_single_label_accuracy(logits, labels, name=""): <NEW_LINE> <INDENT> pre = tf.argmax(logits, 1, name="predict_{}".format(name)) <NEW_LINE> real = labels <NEW_LINE> correct_prediction = tf.equal(tf.cast(pre, tf.int32), tf.cast(real, tf.int32)) <NEW_LINE> accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.fl... | :param logits:
:param labels:
:param name:
:return: | 625941b9de87d2750b85fbfe |
def _decorator(func): <NEW_LINE> <INDENT> def _wrapper(*args, **kwargs): <NEW_LINE> <INDENT> logline = '{0} {1}'.format(args, kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> log.debug(logline.decode('utf-8', 'replace')) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> log.info( 'Exception occured whil... | Accepts a function and returns wrapped version of that function. | 625941b932920d7e50b2803c |
def save_embedding(embedding, filename, embeddings_path): <NEW_LINE> <INDENT> path = os.path.join(embeddings_path, str(filename)) <NEW_LINE> try: <NEW_LINE> <INDENT> np.save(path, embedding) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(str(e)) | Saves the embedding numpy file to the 'embeddings' folder.
Args:
embedding: numpy array of 128 values after the image is fed to the FaceNet model.
filename: filename of the image file.
embeddings_path: absolute path of the 'embeddings/' folder. | 625941b9cc40096d615957c3 |
def append(self, content): <NEW_LINE> <INDENT> self.content.append(content) | add another string to the content | 625941b9dd821e528d63b01b |
def is_done(self): <NEW_LINE> <INDENT> return self.__is_expired() or self.__has_all_results() | Checks all things to see if it is done
:return: true if expired, or has all results | 625941b96fb2d068a760ef11 |
def framesync_fpath(self, session_id): <NEW_LINE> <INDENT> framesync_fname = "{subject_id}_{session_id}.framesync".format( subject_id=self.subject_id, session_id=session_id) <NEW_LINE> return join(self.raw_gaze_dpath, framesync_fname) | Returns the file path the framesync file. | 625941b9507cdc57c6306b44 |
def calc_distance(tf_idf_ret): <NEW_LINE> <INDENT> result = defaultdict(dict) <NEW_LINE> for fromCategory, fromTokens in tf_idf_ret.items(): <NEW_LINE> <INDENT> for toCategory, toTokens in tf_idf_ret.items(): <NEW_LINE> <INDENT> if fromCategory == toCategory: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for f in fr... | tf_idf のスコアを元に距離を取得します。
ret[str] = float | 625941b9d8ef3951e32433ad |
def __init__(self, message="Sorry, Conflict prevents operation"): <NEW_LINE> <INDENT> ErrorPage.__init__(self, CONFLICT, "Conflict", message) | Construct an object that will return an HTTP 409 Conflict message. | 625941b9be383301e01b52fd |
def getAction(self, gameState): <NEW_LINE> <INDENT> def maxValue(gameState, alpha, beta, depth): <NEW_LINE> <INDENT> v = -9999999.9 <NEW_LINE> for action in gameState.getLegalActions(0): <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(0, action) <NEW_LINE> v = max(v, value(successor, alpha, beta, 1, depth))... | Returns the minimax action using self.depth and self.evaluationFunction | 625941b9b5575c28eb68de6e |
def set_sensor_custom_altitude(self, altitude, aot=-1, water=-1, ozone=-1): <NEW_LINE> <INDENT> self.sensor_altitude = -1 * altitude <NEW_LINE> self.aot = aot <NEW_LINE> self.water = water <NEW_LINE> self.ozone = ozone | Set the altitude of the sensor, along with other variables required for the parameterisation
of the sensor.
Takes optional arguments of `aot`, `water` and `ozone` to specify atmospheric contents underneath
the sensor. If these aren't specified then the water and ozone contents will be interpolated from
the US-1962 sta... | 625941b907f4c71912b112f7 |
def try_include(self, filepath): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filepath) as f: <NEW_LINE> <INDENT> self.scope[self.name] = self <NEW_LINE> exec(compile(f.read(), filepath, "exec"), self.scope) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass | Tries to include another file into current scope.
Arguments:
- filepath (`str`): path to file trying to be included | 625941b945492302aab5e130 |
def balance(self): <NEW_LINE> <INDENT> while self.recNum > self.shpNum: <NEW_LINE> <INDENT> self.null() <NEW_LINE> <DEDENT> while self.recNum < self.shpNum: <NEW_LINE> <INDENT> self.record() | Adds corresponding empty attributes or null geometry records depending
on which type of record was created to make sure all three files
are in synch. | 625941b9711fe17d825421e3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.