code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def add_variance_input_dim_modifier(x): <NEW_LINE> <INDENT> return x * 2
Modify discriminator input dim if using `add_variance` preprocessor.
625941e8f548e778e58cda0b
@app.route('/greet') <NEW_LINE> def greet_person(): <NEW_LINE> <INDENT> person = request.args.get("person") <NEW_LINE> compliment = choice(AWESOMENESS) <NEW_LINE> return render_template("compliment.html", person=person, compliment=compliment)
Greet user.
625941e8099cdd3c635f10e4
def test_detail_page_with_override_values(self): <NEW_LINE> <INDENT> short_description = 'Testing short description' <NEW_LINE> full_description = 'Testing full description' <NEW_LINE> title = 'Testing title' <NEW_LINE> self._assign_user_permission() <NEW_LINE> course_run = factories.CourseRunFactory( course=self.cours...
Test that pages shows the override short description, full description and title.
625941e84f88993c3716c4ee
def rvs(dim): <NEW_LINE> <INDENT> random_state = np.random <NEW_LINE> H = np.eye(dim) <NEW_LINE> D = np.ones((dim,)) <NEW_LINE> for n in range(1, dim): <NEW_LINE> <INDENT> x = random_state.normal(size=(dim - n + 1,)) <NEW_LINE> D[n - 1] = np.sign(x[0]) <NEW_LINE> x[0] -= D[n - 1] * np.sqrt((x * x).sum()) <NEW_LINE> Hx ...
Draw random samples from SO(N) Taken from http://stackoverflow.com/questions/38426349/how-to-create-random-orthonormal-matrix-in-python-numpy
625941e8fff4ab517eb2f8ca
def _set_site(self, site, module: str, param: str, clear_invalid: bool = False): <NEW_LINE> <INDENT> if self._site_set: <NEW_LINE> <INDENT> raise TypeError('The site cannot be set multiple times.') <NEW_LINE> <DEDENT> self._valid_enable = set() <NEW_LINE> self._valid_disable = set() <NEW_LINE> if site is None: <NEW_LIN...
Set the site and valid names. As soon as the site has been not None, any subsequent calls will fail, unless there had been invalid names and a KeyError was thrown. :param site: The associated site :type site: pywikibot.site.APISite :param module: The module name which is used by paraminfo. :param param: The parameter...
625941e8293b9510aa2c371c
def draw_samples_random(self, size=None): <NEW_LINE> <INDENT> return np.random.randint(self.lower, self.upper+1, size)
Returns random samples drawn from distribution.
625941e8046cf37aa974d1ce
def forward_likelihood_vector(obs, exposure=1.0, initial=None, transitions=None, emissions=None): <NEW_LINE> <INDENT> trellis = np.array([x for x in initial]) <NEW_LINE> offset = 0.0 <NEW_LINE> eds = np.array([d.logpmf(obs, exposure) for d in emissions]) <NEW_LINE> try: <NEW_LINE> <INDENT> for t, o in enumerate(obs): <...
Compute the log-likelihood of the sequence of observations using the Forward algorithm We do this in a unbound function so we can parallelize more easily :param obs: Series of observed values
625941e8a17c0f6771cbe4db
def set_interp_ratio(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_filter.gr_fractional_interpolator_cc_sptr_set_interp_ratio(self, *args, **kwargs)
set_interp_ratio(self, float interp_ratio)
625941e8e76e3b2f99f3ac90
def process_image(image, height=args.height, width=args.width): <NEW_LINE> <INDENT> image = tf.io.read_file(image) <NEW_LINE> image = tf.image.decode_image(image, channels=3) <NEW_LINE> image = tf.cast(image, tf.float32) <NEW_LINE> image = image / 255. <NEW_LINE> image = tf.image.resize(image, (height, width)) <NEW_LIN...
process image ops. Args: image: 'input tensor'. height: 'int64' img height. width: 'int64' img width. Returns: tensor
625941e8f9cc0f698b140a83
def create_output_fn(self): <NEW_LINE> <INDENT> self.W_out = theano.shared(self.init_matrix([self.output_dim, self.hidden_dim])) <NEW_LINE> self.b_out = theano.shared(self.init_vector([self.output_dim])) <NEW_LINE> self.params.extend([self.W_out, self.b_out]) <NEW_LINE> def fn(final_state): <NEW_LINE> <INDENT> return T...
Выходная функция для рутовой ноды. :return:
625941e8ac7a0e7691ed454f
def touch(filename): <NEW_LINE> <INDENT> path = pathify(filename) <NEW_LINE> path.touch(exist_ok=True) <NEW_LINE> return path
Creates file if it doesn't exist. Always modifies utime. Returns a Path(filename)
625941e8be8e80087fb210c7
def destroy(self): <NEW_LINE> <INDENT> shutil.rmtree(self.base_location)
This function destroys the repository.
625941e88e05c05ec3eea804
def show_error_case(infr, aids, edge=None, error_edges=None, colorby=None, fnum=1): <NEW_LINE> <INDENT> import plottool_ibeis as pt <NEW_LINE> if error_edges is None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> sub_infr = infr.subgraph(aids) <NEW_LINE> subdf = sub_infr.get_edge_dataframe() <NEW_LINE> mistake_edges = [...
Example
625941e873bcbd0ca4b2c501
def test_edges_no_edges(graph): <NEW_LINE> <INDENT> assert graph.edges() == []
Test edges returns list of all edges in graph even if no edges.
625941e8a8370b7717052d29
def count(self, inputfile_list): <NEW_LINE> <INDENT> for inputfile in inputfile_list: <NEW_LINE> <INDENT> for key, value in self.read_file(inputfile).items(): <NEW_LINE> <INDENT> self.total_words += value <NEW_LINE> if key in self.words_dict: <NEW_LINE> <INDENT> self.words_dict[key] += value <NEW_LINE> <DEDENT> <DEDENT...
Count all words and occurrences from 'self.words_dict' in 'inputfile_list' and print the result
625941e87cff6e4e81117e11
def startTest(self, test): <NEW_LINE> <INDENT> self._test_status[test] = None
Base class override. Called before a test is run. Add the test to the test status tracker, so it can potentially be rerun during stopTest. :param test: The test that is going to be run. :type test: :class:`nose.case.Test`
625941e87047854f462a1890
def _dfs(self, nums, path, res): <NEW_LINE> <INDENT> res.append(path.copy()) <NEW_LINE> if len(nums) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for i in range(len(nums)): <NEW_LINE> <INDENT> if i > 0 and nums[i] == nums[i-1]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> path.append(nums[i]) <NEW_LINE> sel...
nums choose path res 终止条件target :return:
625941e856b00c62f0f14ae8
def get(request): <NEW_LINE> <INDENT> if 'id' not in request.GET: <NEW_LINE> <INDENT> return HttpResponse('') <NEW_LINE> <DEDENT> results = FileUpload.objects.filter(id__exact=request.GET['id']) <NEW_LINE> results = _map_fn(results) <NEW_LINE> return HttpResponse(json.dumps(results))
API endpoint: retrieves specific file by id
625941e8009cb60464c63839
def setUp(self): <NEW_LINE> <INDENT> self.client = app.test_client() <NEW_LINE> app.config['TESTING'] = True <NEW_LINE> with self.client as c: <NEW_LINE> <INDENT> with c.session_transaction() as sess: <NEW_LINE> <INDENT> sess['username'] = 'HillaryForPres'
Set up.
625941e89c8ee82313fbbc02
def run_lstm(strategy: tf.distribute.TPUStrategy, x_train_padded: np.array, x_valid_padded: np.array, y_train: np.array, y_valid: np.array, max_len: int, embedding_size_x: int, embedding_size_y: int, embedding_matrix: np.array, epochs: int) -> tf.keras.models.Sequential: <NEW_LINE> <INDENT> logger.info('build lstm') <N...
create and run lstm on training and testing data
625941e8d99f1b3c44c67a12
def copy(self): <NEW_LINE> <INDENT> copied = Trimesh() <NEW_LINE> copied._data.data = copy.deepcopy(self._data.data) <NEW_LINE> copied.visual._data.data = copy.deepcopy(self.visual._data.data) <NEW_LINE> copied.metadata = copy.deepcopy(self.metadata) <NEW_LINE> if self._center_mass is not None: <NEW_LINE> <INDENT> copi...
Safely get a copy of the current mesh. Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated. Current object will *not* have its cache cleared. Returns --------- copied : trimesh.Trimesh Copy of current mesh
625941e8b545ff76a89142a1
def __export_to_numpy(self, X_train, X_test): <NEW_LINE> <INDENT> if self.__save_to_numpy: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> np.save(os.path.join(self.__numpy_path, self.__npy_filename_train), X_train) <NEW_LINE> np.save(os.path.join(self.__numpy_path, self.__npy_filename_test), X_test) <NEW_LINE> <DEDENT> e...
Saves the dataframes to numpy files Numpy files are much faster to load and can also save time in the future by removing the need of preprocessing on every run even if no changes were made. Args: X_train: numpy array holding the train dataset X_test: numpy array holding the test dataset
625941e892d797404e304618
def getBigrams(self, corpusClean): <NEW_LINE> <INDENT> self.bigram_counts={} <NEW_LINE> for sentence in self.corpusClean: <NEW_LINE> <INDENT> N=len(sentence) <NEW_LINE> for j in range(0,N-1): <NEW_LINE> <INDENT> k=(sentence[j], sentence[j+1]) <NEW_LINE> try: <NEW_LINE> <INDENT> self.bigram_counts[k]+=1 <NEW_LINE> <DEDE...
Usage: @param: sentences = ["this is a sentence1", "this is a sentence2", ..."this is a sentenceN"]
625941e8956e5f7376d712f8
def get_ping_parameter_doc(key: str) -> str: <NEW_LINE> <INDENT> schema, _ = _get_schema(PINGS_ID) <NEW_LINE> return schema["additionalProperties"]["properties"][key]["description"]
Returns documentation about a specific ping parameter.
625941e8442bda511e8be89d
def decode_email_header(header): <NEW_LINE> <INDENT> header = decode_base64_encoded_email_header(header) <NEW_LINE> x = quopri.decodestring(header).decode(DEFAULT_CHARSET) <NEW_LINE> return x
See RFC 1522. Non-ascii email header bodies can be encoded in two different ways, both of which have to be handled: quoted-printable & base64 encoding.
625941e8b830903b967e9d92
def sentence_to_seq(sentence, source_vocab_to_int): <NEW_LINE> <INDENT> unk_id = source_vocab_to_int['UNK'] <NEW_LINE> word_id = [source_vocab_to_int.get(word, unk_id) for word in sentence] <NEW_LINE> return word_id
将句子转化为数字编码
625941e83346ee7daa2b31fb
def add_mds(self, spec): <NEW_LINE> <INDENT> raise NotImplementedError()
Create MDS daemon(s)
625941e8aad79263cf390ed4
def align_vec(v1,v2,unit="deg"): <NEW_LINE> <INDENT> x = get_angle(v1, v2,unit=unit) <NEW_LINE> ax = np.cross(v1,v2) <NEW_LINE> return (ax,x)
Parameters ---------- v1: array(3) vector1 v2: array(3) vector2 unit: {"deg", "rad"} desired unit for the angle, default is "deg" Returns ------- tuple ax: axis for the rotation, x: angle for the rotation
625941e8925a0f43d254a307
def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, weights_path='model_data/yolo4.h5'): <NEW_LINE> <INDENT> K.clear_session() <NEW_LINE> image_input = Input(shape=(None, None, 3)) <NEW_LINE> h, w = input_shape <NEW_LINE> num_anchors = len(anchors) <NEW_LINE> y_true = [Input(shape=(...
create the training model
625941e8e8904600ed9f23c0
def _on_avatarsize_changed(self, value): <NEW_LINE> <INDENT> self.avatar.set_size(value) <NEW_LINE> self.his_avatar.set_size(value) <NEW_LINE> self.repaint()
callback called when config.i_conv_avatar_size changes
625941e8656771135c3ebd00
def do_lambda_form(vals, env, function_type=LambdaProcedure): <NEW_LINE> <INDENT> check_form(vals, 2) <NEW_LINE> formals = vals[0] <NEW_LINE> check_formals(formals) <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> body = vals.second <NEW_LINE> if body.length() == 0: <NEW_LINE> <INDENT> raise SchemeError("lambda expressio...
Evaluate a lambda form with formals VALS[0] and body VALS.second in environment ENV, creating a procedure of type FUNCTION_TYPE (a subtype of Procedure).
625941e8b5575c28eb68e490
def routers_updated(self, context, routers): <NEW_LINE> <INDENT> LOG.debug('Got routers updated notification :%s', routers) <NEW_LINE> if routers: <NEW_LINE> <INDENT> if isinstance(routers[0], dict): <NEW_LINE> <INDENT> routers = [router['id'] for router in routers] <NEW_LINE> <DEDENT> self._update_updated_routers_cach...
Deal with routers modification and creation RPC message.
625941e8fbf16365ca6f665a
def allMotionTrails(self): <NEW_LINE> <INDENT> return cmds.ls(type = "DrawNode")
return all motion trails
625941e8a219f33f34628def
def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance.name = validated_data.get('name', instance.name) <NEW_LINE> instance.phone_number = validated_data.get( 'phone_number', instance.phone_number) <NEW_LINE> instance.save() <NEW_LINE> return instance
Update and return an existing `Contact` instance, given the validated data.
625941e821bff66bcd684dda
def sock(self): <NEW_LINE> <INDENT> return self._sock
Returns the zmq socket object being used for the connection. This can be used to send messages with additional flags etc. Returns: - The underlying zmq socket
625941e8046cf37aa974d1cf
def get_player_balls(self, name): <NEW_LINE> <INDENT> return self._data[name]
returns the list of named player position :param name: the name of the player :return: his balls position
625941e826238365f5f0f301
def sortArrayByParityII(self, A: List[int]) -> List[int]: <NEW_LINE> <INDENT> ou = 0 <NEW_LINE> ji = 1 <NEW_LINE> length = len(A) <NEW_LINE> while ou < length and ji < length: <NEW_LINE> <INDENT> while ou < length and A[ou] % 2 == 0: <NEW_LINE> <INDENT> ou += 2 <NEW_LINE> <DEDENT> if ou < length and ji < length: <NEW_L...
func: 双指针法 param {list} return {list}
625941e85510c4643540f865
def test_in_class_1(self, executed_tests, test_result): <NEW_LINE> <INDENT> executed_tests.append(1) <NEW_LINE> assert test_result
test 1 in class
625941e801c39578d7e752c8
def addCitationPaper(citedPaper, citedAuthor): <NEW_LINE> <INDENT> citingPaper = "Citing Paper %d" % __getNextId() <NEW_LINE> graph.add_node(citingPaper) <NEW_LINE> graph.add_edges_from([(conference, citingPaper), (citingPaper, conference), (citingPaper, citedPaper)]) <NEW_LINE> citationCount, publicationCount = actual...
Helper method to add a 'citation' paper, which is only connected to the conference and the paper it cites
625941e8a8ecb033257d3557
def velocity_tentative_hook(**NS_namespace): <NEW_LINE> <INDENT> pass
Called just prior to solving for tentative velocity.
625941e8ad47b63b2c50a40b
def get_training_deployer(self, pod_spec_mutators=None): <NEW_LINE> <INDENT> pod_spec_mutators = pod_spec_mutators or [] <NEW_LINE> return Job(namespace=self._namespace, pod_spec_mutators=pod_spec_mutators)
Creates a deployer to be used with a training job for IBM Cloud :param pod_spec_mutators: list of functions that is used to mutate the podsspec. (Default value = None) :returns: job for handle all the k8s' template building for a training
625941e863f4b57ef0001598
def test_01_vm_usage(self): <NEW_LINE> <INDENT> self.debug("Stopping the VM: %s" % self.virtual_machine.id) <NEW_LINE> self.virtual_machine.stop(self.apiclient) <NEW_LINE> time.sleep(self.services["sleep"]) <NEW_LINE> self.debug("Destroying the VM: %s" % self.virtual_machine.id) <NEW_LINE> self.virtual_machine.delete(s...
Test Create/Destroy VM and verify usage calculation
625941e8bf627c535bc1365b
def broadcastRegionJoinAndGroupByRight(self, genomicRdd, flankSize=0): <NEW_LINE> <INDENT> return GenomicDataset(self._jvmRdd.broadcastRegionJoinAndGroupByRight(genomicRdd._jvmRdd, flankSize), self.sc)
Performs a broadcast inner join between this RDD and another RDD. In a broadcast join, the left RDD (this RDD) is collected to the driver, and broadcast to all the nodes in the cluster. The key equality function used for this join is the reference region overlap function. Since this is an inner join, all values who do...
625941e8236d856c2ad44c6d
def __init__(self): <NEW_LINE> <INDENT> self.tags = self.recover_state()
Recover the the list of active tags or create a new one
625941e8377c676e91272633
def _insert(lst: list, i: int) -> None: <NEW_LINE> <INDENT> value = lst[i] <NEW_LINE> while i > 0 and lst[i - 1] > value: <NEW_LINE> <INDENT> lst[i] = lst[i - 1] <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> lst[i] = value <NEW_LINE> return None
Move L[i] to where it belongs in L[i + 1] Precondition: L[:i] is sorted from smallest to largest. >>> L = [7, 3, 5, 2] >>> _insert(L, 1) >>> L [3, 7, 5, 2]
625941e88e71fb1e9831dc34
def __init__(self, site=True, **kwargs): <NEW_LINE> <INDENT> self.availableOptions.update({ 'ask': False, 'feed': None, 'whitelist': None, 'versionchecktime': 300, 'autopatroluserns': False }) <NEW_LINE> super(PatrolBot, self).__init__(site, **kwargs) <NEW_LINE> self.recent_gen = True <NEW_LINE> self.user = None <NEW_L...
Constructor. @kwarg feed: The changes feed to work on (Newpages or Recentchanges) @kwarg ask: If True, confirm each patrol action @kwarg whitelist: page title for whitelist (optional) @kwarg autopatroluserns: Takes user consent to automatically patrol @kwarg versionchecktime: Check versionchecktime lapse in sec
625941e863d6d428bbe4497d
def find_max_n(data, n): <NEW_LINE> <INDENT> output = data.nlargest(n) <NEW_LINE> return output
Find the n largest values in an array
625941e891f36d47f21ac984
def get_sheet_names(self): <NEW_LINE> <INDENT> return self.xls_workbook.sheetnames
Get names of sheets contained within path Returns: obj:`list` of `str`: list of sheet names
625941e876e4537e8c351b02
def setFirstPageFrameValue(name, value): <NEW_LINE> <INDENT> doc = XSCRIPTCONTEXT.getDocument() <NEW_LINE> firstPageStyleName = doc.Text.createTextCursor().PageDescName <NEW_LINE> doc.UndoManager.lock() <NEW_LINE> doc.lockControllers() <NEW_LINE> for firstPageVariant in "1234": <NEW_LINE> <INDENT> fullName = "Перв.{}: ...
Установить значение поля форматной рамки первого листа. Имеется четыре стиля для первого листа и у каждого содержится свой набор полей. Они должны иметь одинаковые значения, чтобы при смене стиля значения сохранялись. Атрибуты: name -- имя текстового поля (без первых 4-х символов); value -- новое значение поля.
625941e844b2445a3393251f
def update_guild_counter(num_guilds): <NEW_LINE> <INDENT> return discord.Activity( name=f'D&D 5e in {num_guilds} guilds | ?help', type=discord.ActivityType.playing)
Updates status displaying the number of Discord servers the bot belongs in.
625941e8d486a94d0b98e5d3
def SubMedias(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Obtains all SubMedias known.
625941e807f4c71912b11911
def initAgents(populationSize, length): <NEW_LINE> <INDENT> return [Agent(length) for _ in range(populationSize)]
:param populationSize: the number of random strings in the population :param length: length of each string :return: list of strings that have been initialized
625941e86fb2d068a760f531
def test_orientations(image_stack, experiment, test_crds, controller,multiprocessing_start_method): <NEW_LINE> <INDENT> n_grains = experiment.n_grains <NEW_LINE> chunk_size = controller.get_chunk_size() <NEW_LINE> ncpus = controller.get_process_count() <NEW_LINE> all_angles = evaluate_diffraction_angles(experiment, con...
grand loop precomputing the grown image stack image-stack -- is the image stack to be tested against. experiment -- A bunch of experiment related parameters. controller -- An external object implementing the hooks to notify progress as well as figuring out what to do with results.
625941e8cc0a2c11143dd31f
def deepcopy(self, memo=None): <NEW_LINE> <INDENT> return deepcopy(self, memo)
Return a deep copy of the finite state machine. INPUT: - ``memo`` -- (default: ``None``) a dictionary storing already processed elements. OUTPUT: A new finite state machine. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'A', 0, 1), ('A', 'A', 1, 0)]) sage: deepcopy(F) Finite state machine with 1 st...
625941e84d74a7450ccd4652
def adjust_learning_rate_auto(optimizer, loss_window): <NEW_LINE> <INDENT> minlr = 0.0000001 <NEW_LINE> learning_rate = g_conf.LEARNING_RATE <NEW_LINE> thresh = g_conf.LEARNING_RATE_THRESHOLD <NEW_LINE> decaylevel = g_conf.LEARNING_RATE_DECAY_LEVEL <NEW_LINE> n = 1000 <NEW_LINE> start_point = 0 <NEW_LINE> print ("Loss ...
Adjusts the learning rate every epoch based on the selected schedule
625941e84d74a7450ccd4651
def as_float_array(X, *, copy=True, force_all_finite=True): <NEW_LINE> <INDENT> if isinstance(X, np.matrix) or ( not isinstance(X, np.ndarray) and not sp.issparse(X) ): <NEW_LINE> <INDENT> return check_array( X, accept_sparse=["csr", "csc", "coo"], dtype=np.float64, copy=copy, force_all_finite=force_all_finite, ensure_...
Converts an array-like to an array of floats. The new dtype will be np.float32 or np.float64, depending on the original type. The function can create a copy or modify the argument depending on the argument copy. Parameters ---------- X : {array-like, sparse matrix} copy : bool, default=True If True, a copy of X ...
625941e80383005118ecfa6e
def vprint(self, string, *args, **kwargs): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print(string, *args, **kwargs) <NEW_LINE> sys.stdout.flush()
Verbose printing: Wrapper around `print()` to only call it if `self.verbose` is set to true. Args: string (str): String to be printed if `self.verbose` is `True`. *args: Arguments passed to `print()`. **kwargs: Keyword arguments passed to `print()`.
625941e88da39b475bd65406
def query_dict_with_fallback( data: Dict, query: str, fallback: Any, required_type: Type = None ) -> Any: <NEW_LINE> <INDENT> result = data.get(query) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> return fallback <NEW_LINE> <DEDENT> if required_type is not None: <NEW_LINE> <INDENT> if not isinstance(result, require...
Safely queries a dictionary, returns the queried value if it passes type check and the `fallback` otherwise. Args: data (Dict): The dictionary to query. query (str): The query. fallback (Any): The fallback value to return if the key does not exist or the queried value does not pass the type check. requ...
625941e8711fe17d825427ee
def select_data(self, select_query): <NEW_LINE> <INDENT> self.df = pd.read_sql(select_query, con=self.db_connection) <NEW_LINE> return self.df
Runs select query on database and returns a pandas dataframe :param select_query: SQL query :return: Pandas dataframe
625941e8627d3e7fe0d692df
def subset(self, subset='train'): <NEW_LINE> <INDENT> if isinstance(subset, str): <NEW_LINE> <INDENT> subset = subset.capitalize() <NEW_LINE> attrs = ['{}{}'.format(attr, subset) for attr in ['design', 'target']] <NEW_LINE> X, y = tuple(getattr(self, attr) for attr in attrs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Create a new `donatello.components.data.Dataset` with a (sub)set of the dataset's data. Either by referencing by name (train, test) or passing a payload for :py:func:`donatello.utils.helpers.access` Args: subset (str|dict): attribute to select Returns: Dataset: with same params as current dataset
625941e82eb69b55b151cd43
def deliverable(self): <NEW_LINE> <INDENT> now = util.now() <NEW_LINE> if self.get('Paused', False): return False <NEW_LINE> return (now - self['LastSuccess'] > self['MaxPeriod']) or (len(self['PendingData']) > 0 and (now - self['LastSuccess']) > self['MinPeriod'])
Check if attempt should be called :rvalue boolean: True if a report should be sent
625941e84e4d5625662d485e
@cmd("admins", "ops") <NEW_LINE> def show_admins(cli, nick, chan, rest): <NEW_LINE> <INDENT> admins = [] <NEW_LINE> pl = var.list_players() <NEW_LINE> if (var.LAST_ADMINS and var.LAST_ADMINS + timedelta(seconds=var.ADMINS_RATE_LIMIT) > datetime.now()): <NEW_LINE> <INDENT> cli.notice(nick, ("This command is rate-limited...
Pings the admins that are available.
625941e850812a4eaa59c7aa
def get_message(self, resp): <NEW_LINE> <INDENT> return resp['message']
This method parses the given response and returns string message. Args: resp(dict): Response containing json object for string message. Returns: str: Success message.
625941e821bff66bcd684ddb
def rename(self, image): <NEW_LINE> <INDENT> original_names = {band.name: band.alias for band in self.bands} <NEW_LINE> return geetools.tools.image.renameDict(image, original_names)
Rename bands
625941e8377c676e91272634
def keep_subtree(dep_graph, token_idx): <NEW_LINE> <INDENT> graph = defaultdict(list) <NEW_LINE> roots = [token_idx] <NEW_LINE> for i in dep_graph.descendants(token_idx): <NEW_LINE> <INDENT> graph[i] = list(dep_graph.graph[i]) <NEW_LINE> <DEDENT> for child, label in [(child, label) for child, label in graph[token_idx] ...
Keep the subtree rooted @token_idx.
625941e829b78933be1e5b33
def p_variable(p): <NEW_LINE> <INDENT> if len(p) == 6: <NEW_LINE> <INDENT> name, dims = p[3] <NEW_LINE> params = p[4] <NEW_LINE> if params is not None: <NEW_LINE> <INDENT> p[0] = ast.MethodCall(p[1], name, params, lineno=p.lineno(2), linespan=p.linespan(2)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = ast.Objec...
variable : base_variable_with_function_calls OBJECT_OPERATOR object_property method_or_not variable_properties | base_variable_with_function_calls
625941e85e10d32532c5f3b2
def fit(self): <NEW_LINE> <INDENT> X_train, y_train = self._prepare_train(self.train) <NEW_LINE> self.model.fit(X_train, y_train)
Fit model with training data
625941e8498bea3a759b9f3b
def norma(v: numpy.ndarray) -> numpy.ndarray: <NEW_LINE> <INDENT> s = v.sum() <NEW_LINE> if s == 0: <NEW_LINE> <INDENT> n = numpy.zeros(v.shape) <NEW_LINE> n[0, 0] = 1 <NEW_LINE> return n <NEW_LINE> <DEDENT> return v / s
Normalize vector with respect to 1, i. e. ||v||
625941e8e64d504609d74ccd
def peak_hr(self): <NEW_LINE> <INDENT> self.df['PK_HR'] = self.df['dir_aadt'] * self.df['2015_15-min_Combined'] <NEW_LINE> return self.df
Performs Peak Hour calculations by combining directional aadt values with vehicle hourly volume factors determined by Metro. Args: self.df, a pandas dataframe. Returns: self.df, a pandas dataframe conaining new PK_HR column with completed calculations.
625941e82c8b7c6e89b35c4a
def dict_deep_update(a, b): <NEW_LINE> <INDENT> for key, val in b.items(): <NEW_LINE> <INDENT> if isinstance(a.get(key), dict) and isinstance(val, dict): <NEW_LINE> <INDENT> dict_deep_update(a[key], val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a[key] = val
Deep merge in place of two dicts. For all keys in `b`, override matching keys in `a`. If both `a` and `b` have a dict at a given key, recursively update `a`. :param a: Left hand side dict to update in place :type a: dict :param b: Right hand side with values to pull in :type b: dict
625941e83cc13d1c6d3c7805
def print_file(self, file): <NEW_LINE> <INDENT> root = file.get_source() <NEW_LINE> self.module_name = file.get_path() + "/" + file.get_name() <NEW_LINE> self.visit(root)
Runs the type_checking on an individual file.
625941e84e4d5625662d485f
def __init__(self, friendly_name, period, field, wu_unit=None, ha_unit=None, icon=None): <NEW_LINE> <INDENT> super().__init__( friendly_name=friendly_name, feature='forecast', value=(lambda wu: wu.data['forecast']['simpleforecast'][ 'forecastday'][period][field][wu_unit]) if wu_unit else (lambda wu: wu.data['forecast']...
Constructor. Args: period (int): forecast period number field (string): field name to use as value wu_unit (string): "fahrenheit", "celsius", "degrees" etc. see the example json at: https://www.wunderground.com/weather/api/d/docs?d=data/forecast&MR=1 ha_unit (string): coresponding unit in home...
625941e8e76e3b2f99f3ac92
def getPose(self, dist='cm', angle='deg'): <NEW_LINE> <INDENT> x = 0; y = 0; th = 0 <NEW_LINE> if dist == 'cm': <NEW_LINE> <INDENT> x = self.xPose/10.0; y = self.yPose/10.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = self.xPose; y = self.yPose <NEW_LINE> <DEDENT> if angle == 'deg': <NEW_LINE> <INDENT> th = math.d...
getPose returns the current estimate of the robot's global pose dist may be 'cm' or 'mm' angle may be 'deg' or 'rad'
625941e8ac7a0e7691ed4551
def nFilled(self): <NEW_LINE> <INDENT> return len(self._filled)
Return the number of filled cells.
625941e88a43f66fc4b544ee
def is_package_dir(dirname): <NEW_LINE> <INDENT> if not isinstance(dirname, basestring): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not os.path.isdir(dirname): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> dirname = os.path.abspath(dirname) <NEW_LINE> (parent, dir) = os.path.split(dirname) <NEW_LINE...
Return true if the given directory is a valid package directory (i.e., it names a directory that contains a valid __init__ file, and its name is a valid identifier).
625941e83317a56b8693a0da
def test_pop_volume(self): <NEW_LINE> <INDENT> orders = [15, 0, 0, 0, 0, 0, 0, -2] <NEW_LINE> temperatures = [55, 55, 55, 55, 55, 55, 55, 55] <NEW_LINE> expected = [10, 11, 12, 13, 14, 15, 15, 13] <NEW_LINE> self.run_test(orders, temperatures, expected)
Test a volume to pop.
625941e8b830903b967e9d93
def get_drop_location(self, x, y): <NEW_LINE> <INDENT> x, y = self.CalcUnscrolledPosition(x, y) <NEW_LINE> if x < 0: <NEW_LINE> <INDENT> col = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> col = self.XToCol(x) <NEW_LINE> if col == wx.NOT_FOUND: <NEW_LINE> <INDENT> col = None <NEW_LINE> <DEDENT> <DEDENT> bottom = s...
Return the row and column of the insert point of the drop x - x coordinate relative to the grid window y - y coordinate relative to the grid window returns the row and column of where the drop should be inserted. Returns a column of None if x is not within a column.
625941e8a8370b7717052d2b
def test_triangular_radial_kernel(self): <NEW_LINE> <INDENT> distance = gs.array([[1], [2]], dtype=float) <NEW_LINE> bandwidth = 2 <NEW_LINE> weight = triangular_radial_kernel(distance=distance, bandwidth=bandwidth) <NEW_LINE> result = weight <NEW_LINE> expected = gs.array([[1 / 2], [0]], dtype=float) <NEW_LINE> self.a...
Test the triangular radial kernel.
625941e8d18da76e23532969
def test_delete_project_not_owner(self): <NEW_LINE> <INDENT> self._sign_in(self.user) <NEW_LINE> self.assertRaises( ForbiddenException, self.api.project_delete, IDContainer.combined_message_class(id=self.project.id) )
Delete a project as admin user
625941e8796e427e537b0a58
def convolve_weighted(window, signal, weights): <NEW_LINE> <INDENT> wing = (len(window) - 1) // 2 <NEW_LINE> window_size = len(window) <NEW_LINE> assert window_size == 2 * wing + 1 <NEW_LINE> assert len(weights) + 2 * wing == len(signal) <NEW_LINE> wp = _pad_array(weights, wing) <NEW_LINE> wp = pd.Series(np.concatenate...
Convolve a weighted window over a weighted signal array. Source: https://stackoverflow.com/a/46232913/10049
625941e89c8ee82313fbbc04
def getTicketNumTotal(self): <NEW_LINE> <INDENT> return self.__ticketNumTotal
This function return the user ticketNumTotal
625941e86e29344779a62a9e
def hedge_derivative(tf_delta, tf_session, params ): <NEW_LINE> <INDENT> return tf_session.run(tf_delta, feed_dict=params)
Wrapper executing the computation graph for a given derivative's delta. Args: tf_delta: a tensorflow tensor corresponding to the derivative's delta estimate. tf_session: a tensorflow session which will execute the graph. params: a dictionary {placeholder: value} that will be fed into the session. Returns: ...
625941e83317a56b8693a0db
def rerender_directory(self, directory, maintain_focus=True): <NEW_LINE> <INDENT> selection = self.selection_get() <NEW_LINE> item = self.item(directory) <NEW_LINE> self.delete(*item.get_children()) <NEW_LINE> self._render_directory(directory) <NEW_LINE> if maintain_focus: <NEW_LINE> <INDENT> self.set_selection_with_ex...
Rerender everything below the given directory. Parameters ---------- directory : str maintain_focus : bool maintain the current selection, if any?
625941e8004d5f362079a7be
def get_askbot_template(template, request = None): <NEW_LINE> <INDENT> skin = get_skin(request) <NEW_LINE> if hasattr(request,'LANGUAGE_CODE'): <NEW_LINE> <INDENT> skin.set_language(request.LANGUAGE_CODE) <NEW_LINE> <DEDENT> return skin.get_template(template)
retreives template for the skin request variable will be used in the future to set template according to the user preference or admins preference request variable is used to localize the skin if possible
625941e8293b9510aa2c371f
def test_parameter(self): <NEW_LINE> <INDENT> x = Parameter(2, complex=False) <NEW_LINE> y = Parameter(2, complex=True) <NEW_LINE> z = Parameter(2, imag=True) <NEW_LINE> assert not x.is_complex() <NEW_LINE> assert not x.is_imag() <NEW_LINE> assert y.is_complex() <NEW_LINE> assert not y.is_imag() <NEW_LINE> assert z.is_...
Test the parameter class.
625941e8baa26c4b54cb15a9
def exclude(self, iterable): <NEW_LINE> <INDENT> return list(filter((~self).eval, iterable))
Returns a filtered list of applying ~self to the elements of iterable. This is a similar API to QuerySet.exclude.
625941e88c3a87329515884e
def create_client_authz_resource(self, client_id, payload, skip_exists=False): <NEW_LINE> <INDENT> params_path = {"realm-name": self.realm_name, "id": client_id} <NEW_LINE> data_raw = self.raw_post(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path), data=json.dumps(payload)) <NEW_LINE> return raise_error_from_respo...
Create resources of client. :param client_id: id in ClientRepresentation https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation :param payload: ResourceRepresentation https://www.keycloak.org/docs-api/12.0/rest-api/index.html#_resourcerepresentation :return: Keycloak server response
625941e826238365f5f0f302
def tearDown(self): <NEW_LINE> <INDENT> if 'skip-teardown' in self.conf: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.log_enter_teardown() <NEW_LINE> self.stop_proc_monitor() <NEW_LINE> self.log_end_teardown()
verify that ``server`` and ``scheduler`` are up clean up jobs and reservations
625941e8ff9c53063f47c67f
def ReturnN(self): <NEW_LINE> <INDENT> N=0 <NEW_LINE> for ni in self.data.itervalues(): <NEW_LINE> <INDENT> N+=ni <NEW_LINE> <DEDENT> return N
Returns the total number of strings of length n read.
625941e863b5f9789fde7574
def simple_editor(self, ui, object, name, description, parent): <NEW_LINE> <INDENT> self._low_value, self._high_value, self.is_float = self._get_low_high( ui) <NEW_LINE> return super(RangeEditor, self).simple_editor(ui, object, name, description, parent)
Generates an editor using the "simple" style. Overridden to set the values of the _low_value, _high_value and is_float traits.
625941e8956e5f7376d712fa
def session_refused(self): <NEW_LINE> <INDENT> pass
called when the i2p router refuses a session
625941e83346ee7daa2b31fd
def test(self, test_dataset): <NEW_LINE> <INDENT> char_acc = 0 <NEW_LINE> char_total = 0 <NEW_LINE> word_acc = 0 <NEW_LINE> word_total = 0 <NEW_LINE> for i_data in range(len(test_dataset[0])): <NEW_LINE> <INDENT> X, label = test_dataset[0][i_data], test_dataset[1][i_data] <NEW_LINE> out = [self.d[id] for id in self.crf...
在测试集上对当前模型进行测试
625941e8b830903b967e9d94
def add(self, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._logger.log("adding object %s" % (obj.dn, )) <NEW_LINE> <DEDENT> except ldap.LDAPError as e: <NEW_LINE> <INDENT> self._logger.warn("Unable to add object %s" % (obj.dn, ), 'Err') <NEW_LINE> <DEDENT> return obj
add a new object to the base
625941e8a934411ee3751b22
def do_download_worker(book_list, options, cpus, notification=lambda x,y:x): <NEW_LINE> <INDENT> server = Server(pool_size=cpus) <NEW_LINE> logger.info(options['version']) <NEW_LINE> total = 0 <NEW_LINE> alreadybad = [] <NEW_LINE> logger.info("Adding jobs for URLs:") <NEW_LINE> for book in book_list: <NEW_LINE> <INDENT...
Master job, to launch child jobs to extract ISBN for a set of books This is run as a worker job in the background to keep the UI more responsive and get around the memory leak issues as it will launch a child job for each book as a worker process
625941e87d43ff24873a3131
def field_map(self, field, table): <NEW_LINE> <INDENT> if field.startswith("%s_" % table[:-1]): <NEW_LINE> <INDENT> field = field[len(table):] <NEW_LINE> <DEDENT> if field.startswith("log_"): <NEW_LINE> <INDENT> field = field[4:] <NEW_LINE> <DEDENT> if table == 'services' and field.startswith('host_'): <NEW_LINE> <INDE...
Map query field to tantale known field
625941e84a966d76dd5514a1
def plot_line(self,X,Y,win,title=None, env=None, opts=None,update_mode=None,name=None): <NEW_LINE> <INDENT> opts = {"title":title} if opts == None else opts <NEW_LINE> self.viz.line(X=X,Y=Y,win=win,env=env,opts=opts,update=update_mode,name=name)
:param X: :param Y: :param win: :param title: :param env: :param opts: :param update_mode: :param name: :return:
625941e88a349b6b435e8600
def testCentredDipole75(self): <NEW_LINE> <INDENT> for rdist, qlevel in itertools.product([3,3.5,4,5,6], range(2,5)): <NEW_LINE> <INDENT> ans = Lstar.get_Lstar([-rdist,0,0], self.date, alpha=75, coord_system='SM', Bfield='Lgm_B_cdip', LstarQuality=qlevel) <NEW_LINE> try: <NEW_LINE> <INDENT> self.assertAlmostEqual(rdist...
Unit test for centred dipole - should give known result
625941e84527f215b584c8e0
def disp7(): <NEW_LINE> <INDENT> names_pt = glob.glob("./quiver_points_bor*.txt") <NEW_LINE> names_obs = glob.glob("./Trajectories/obs_data.txt") <NEW_LINE> flag = True <NEW_LINE> names = glob.glob("./Trajectories/trajecto*.txt") <NEW_LINE> for name in names: <NEW_LINE> <INDENT> entry = np.loadtxt(open(name, "rb"), del...
Display the trajectories of robots avoiding an obstacle composed of cells Display the obstacle itself as well as the points on its border
625941e891af0d3eaac9beab
def get_c_next(c): <NEW_LINE> <INDENT> convection = - DT/DX * U * (c[2] - c[1]) <NEW_LINE> diffusion = DT/DX/DX * D * (c[2] - 2*c[1] + c[0]) <NEW_LINE> return c[1] + convection + diffusion
Parameters ------ c: list of float 0:c_i-1,j 1:c_i,j 2:c_i+1,j の3つを収容したリスト Returns ----- float c_i,j+1
625941e8f7d966606f6aa497
def get_image_sources(image_type, hash): <NEW_LINE> <INDENT> base_url = get_absolute_uri(reverse('image', args=(image_type, hash, 'q'))) <NEW_LINE> return { IMAGE_SIZES['q']['verbose']: base_url, IMAGE_SIZES['n']['verbose']: base_url.replace('_q', '_n'), IMAGE_SIZES['z']['verbose']: base_url.replace('_q', '_z'), IMAGE_...
Returns internal URLs to the different image sizes available. We use `string.replace()` to reduce calls to the Django `reverse()` function.
625941e810dbd63aa1bd3030