code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def np_state_shape(net, name): <NEW_LINE> <INDENT> np_shape = None <NEW_LINE> p = net["neuron_pools"][name] <NEW_LINE> if "shape" in p: <NEW_LINE> <INDENT> np_shape = [net["agents"]] + p["shape"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> np_shape = [net["agents"], 1, 1, 1] <NEW_LINE> np_shape[1] = np_shape[1] * p.g...
Determine neuron-pool"s 4D state shape. Parameters: ----------- net : dict Complete network dictionary containing all nps, sps, plasts, ifs. name : str The unique string identifier for the neuron-pool.
625941f08a43f66fc4b545e3
def part_02(passport: str) -> bool: <NEW_LINE> <INDENT> passport = passport.split() <NEW_LINE> parsed_passport = {} <NEW_LINE> for item in passport: <NEW_LINE> <INDENT> key = item[:3] <NEW_LINE> value = item[4:] <NEW_LINE> parsed_passport[key] = value <NEW_LINE> <DEDENT> if not is_valid_byr(parsed_passport["byr"]): <NE...
Parse list into dictionary and validate each field. :return: Status of individual passport (true = valid). :rtype: bool
625941f04e4d5625662d4954
def set_data(self,data): <NEW_LINE> <INDENT> self.data = data
seting method for the data attribute
625941f0097d151d1a2233db
def wide_resnet101_2(cfg, **kwargs: Any) -> ResNet: <NEW_LINE> <INDENT> kwargs["width_per_group"] = 64 * 2 <NEW_LINE> return _resnet("wide_resnet101_2", Bottleneck, [3, 4, 23, 3], cfg, **kwargs)
Wide ResNet-101-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-204...
625941f0a79ad161976cc6ca
def timedelta_to_formatted_string(delta): <NEW_LINE> <INDENT> total_seconds = delta.total_seconds() <NEW_LINE> hours, remainder = divmod(total_seconds, 3600) <NEW_LINE> minutes, seconds = divmod(remainder, 60) <NEW_LINE> return "%d:%02d:%02d" % (hours, minutes, seconds)
Format timedelta to string like hours:minutes:seconds Parameters ---------- delta: timedelta timedelta to format Returns ------- string Formatted string
625941f0cb5e8a47e48b8025
def timestep(self): <NEW_LINE> <INDENT> cfl = self.rp.get_param("driver.cfl") <NEW_LINE> k = self.rp.get_param("diffusion.k") <NEW_LINE> xtmp = self.cc_data.grid.dx**2/k <NEW_LINE> ytmp = self.cc_data.grid.dy**2/k <NEW_LINE> dt = cfl*min(xtmp, ytmp) <NEW_LINE> return dt
The diffusion timestep() function computes the timestep using the explicit timestep constraint as the starting point. We then multiply by the CFL number to get the timestep. Since we are doing an implicit discretization, we do not require CFL < 1.
625941f0cdde0d52a9e535bc
def assign_data_source(mock_logsm, table_abscissa=np.array([8.5, 9, 9.5, 10]), table_ordinates=np.array([1, 0.8, 0.35, 0]), seed=default_seed): <NEW_LINE> <INDENT> input_abscissa = np.linspace(table_abscissa.min(), table_abscissa.max(), 100) <NEW_LINE> ordinates = polynomial_from_table(table_abscissa, table_ordinates, ...
Determine the source of observational data that will be used to map colors onto mock galaxies. For entries in the returned ndarray equal to zero, real SDSS objects will be used to map colors onto mock galaxies. For entries in the returned ndarray equal to one, fake SDSS objects will be used. Parameters ---------- moc...
625941f01f037a2d8b946781
def merge_regions(intervals_new, intervals_old): <NEW_LINE> <INDENT> intervals = intervals_old + intervals_new <NEW_LINE> intervals_sorted = sorted(intervals, key=lambda tup: tup[0]) <NEW_LINE> intervals_merged = [] <NEW_LINE> for interval in intervals_sorted: <NEW_LINE> <INDENT> if not intervals_merged: <NEW_LINE> <IN...
Merge intervals by: (1) sorting the intervals in decreasing order, and (2) iterate through intervals, comparing the current interval with the last one. If the interval overlap, merge both intervals into one
625941f066656f66f7cbc731
def get_pixel_height(self): <NEW_LINE> <INDENT> return len(self.get_tiles()) * self.tile_width
Return the height of the map in pixel.
625941f02eb69b55b151ce3c
def shear(z, u, v=0): <NEW_LINE> <INDENT> z, u, v = list(map(np.asanyarray, (z, u, v))) <NEW_LINE> z, u, v = np.broadcast_arrays(z, u, v) <NEW_LINE> m, n = z.shape <NEW_LINE> iup = np.arange(0, m - 1) <NEW_LINE> ilo = np.arange(1, m) <NEW_LINE> z_ave = (z[iup, :] + z[ilo, :]) / 2. <NEW_LINE> vel = np.sqrt(u ** 2 + v **...
Calculates the vertical shear for u, v velocity section. .. math:: \textrm{shear} = \frac{\partial (u^2 + v^2)^{0.5}}{\partial z} Parameters ---------- z : array_like depth [m] u(z) : array_like Eastward velocity [m s :sup:`-1`] v(z) : array_like Northward velocity [m s :sup:`-1`] Returns ------- ...
625941f0fbf16365ca6f6754
def test_user_authentication(self): <NEW_LINE> <INDENT> response = self.client.get(self.home_url) <NEW_LINE> user = response.context.get('user') <NEW_LINE> self.assertTrue(user.is_authenticated)
Create a new request to an arbitrari page. The resulting response should now have a 'user' to its context, after a successful sign up.
625941f07d847024c06be845
def parse_json(self, filename, verbose = False): <NEW_LINE> <INDENT> with open(filename) as f: <NEW_LINE> <INDENT> data = json.load(f) <NEW_LINE> <DEDENT> for idx, agent in enumerate(data['agents'], verbose): <NEW_LINE> <INDENT> self.add_agent(idx, agent, verbose = verbose) <NEW_LINE> <DEDENT> for idx, task in enumerat...
reads json file and loads agents, tasks and parameters
625941f0b545ff76a891439a
def plot_neuron(ax, nrn, neurite_type=NeuriteType.all, plane='xy', soma_outline=True, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA, realistic_diameters=False): <NEW_LINE> <INDENT> plot_soma(ax, nrn.soma, plane=plane, soma_outline=soma_outline, linewidth=linewidth, color=color, alpha=al...
Plots a 2D figure of the neuron, that contains a soma and the neurites. Args: ax(matplotlib axes): on what to plot neurite_type(NeuriteType): an optional filter on the neurite type nrn(neuron): neuron to be plotted soma_outline(bool): should the soma be drawn as an outline plane(str): Any pair of '...
625941f016aa5153ce3629fe
def document_by_year(request, year): <NEW_LINE> <INDENT> if year not in settings.YEARS: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> return redirect_to_year(year)
Redirects to Completed Questionnaire document url for the relevant year
625941f0796e427e537b0b4f
def _getMeta(self): <NEW_LINE> <INDENT> base_url = self.config['base_url'][0] <NEW_LINE> end_url = self.config['end_url'][0] <NEW_LINE> url_whitespace = self.config['url_whitespace'][0] <NEW_LINE> label_case = self.config['label_case'][0] <NEW_LINE> url_case = self.config['url_case'][0] <NEW_LINE> html_class = self.con...
Return meta data or config data.
625941f0a05bb46b383ecda1
def _hash_fallback(self) -> int: <NEW_LINE> <INDENT> return id(self)
Fallback function for :meth:`AbstractDataClass.__hash__` incase of recursive calls.
625941f0f8510a7c17cf9c85
def read(self, settingsReader:object, multiData:object) -> None: <NEW_LINE> <INDENT> if settingsReader.check(): <NEW_LINE> <INDENT> settingsReader.read() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> multiData.reset() <NEW_LINE> try: <NEW_LINE> <INDENT> self.readSMISamples(settingsReader, mul...
Actual data parsing code. Depends on pandas module. :param settingsReader: SettingsReader object to get xml settings tree from. :param multiData: MultiData object to write into. :return:
625941f007d97122c4178e1e
def test_invoice_cant_be_modified_unless_to_be_marked_as_payed(self): <NEW_LINE> <INDENT> condo_user = User.objects.get(username="condo_user") <NEW_LINE> self.client.force_authenticate(user=condo_user) <NEW_LINE> invoice = Invoice.objects.all().first() <NEW_LINE> url = reverse('invoice-detail',kwargs={'pk':invoice.pk})...
Invoice can not be modified, unless to be marked as payed
625941f0aad79263cf390fce
def cleanup_query_results(): <NEW_LINE> <INDENT> logger.info( "Running query results clean up (removing maximum of %d unused results, that are %d days old or more)", settings.QUERY_RESULTS_CLEANUP_COUNT, settings.QUERY_RESULTS_CLEANUP_MAX_AGE, ) <NEW_LINE> unused_query_results = models.QueryResult.unused( settings.QUER...
Job to cleanup unused query results -- such that no query links to them anymore, and older than settings.QUERY_RESULTS_CLEANUP_MAX_AGE (a week by default, so it's less likely to be open in someone's browser and be used). Each time the job deletes only settings.QUERY_RESULTS_CLEANUP_COUNT (100 by default) query results...
625941f00a366e3fb873eda4
def __init__(self, config_filename): <NEW_LINE> <INDENT> self.load_config(config_filename)
Load the configuration file
625941f00fa83653e465753c
def changeDirection(self): <NEW_LINE> <INDENT> if (self.rect.x <= -60 or self.rect.x > size[0] - self.size[0] + 60): <NEW_LINE> <INDENT> self.directionX *= -1 <NEW_LINE> self.animation.flip(True, False) <NEW_LINE> self.rect.x += self.speedX * self.directionX <NEW_LINE> self.rect.y += self.speedY * self.directionY <NEW_...
if the duck got to the border then change its direction and set new speedX and speedY for changing angle of flight
625941f03c8af77a43ae3d2c
def __init__(self): <NEW_LINE> <INDENT> self.stack = []
implement queue with one stack
625941f057b8e32f52483a24
def test_sending_none_message(self): <NEW_LINE> <INDENT> self._setup_notify() <NEW_LINE> common.send_message(self.hass, None) <NEW_LINE> self.hass.block_till_done() <NEW_LINE> assert len(self.events) == 0
Test send with None as message.
625941f0711fe17d825428e3
def euler411(): <NEW_LINE> <INDENT> pass
>>> euler411() 'to-do'
625941f030dc7b7665901ee5
def __setBrush(self): <NEW_LINE> <INDENT> palette = self.palette() <NEW_LINE> if self.selected: <NEW_LINE> <INDENT> self.brush = qt.QBrush(self.selected_color) <NEW_LINE> <DEDENT> elif self.bgcolor is not None: <NEW_LINE> <INDENT> self.brush = qt.QBrush(self.bgcolor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.b...
Selected cells are yellow when not current. The current cell is dark yellow when selected or grey when not selected. Other cells have no bg color by default, unless specified at instantiation (:attr:`bgcolor`)
625941f0187af65679ca56a5
def kayttokerrat(function_used): <NEW_LINE> <INDENT> command = function_used.capitalize() <NEW_LINE> current_date = datetime.datetime.now().strftime("%d/%m/%Y") <NEW_LINE> with open("Data files/Times_used.json") as data_file: <NEW_LINE> <INDENT> data = json.load(data_file) <NEW_LINE> <DEDENT> times = data[command] <NEW...
Keeps a record of how many times most of commands are used. Updates every time some command is used. :param function_used: Name of the function in string format :return: Nothing
625941f0ad47b63b2c50a504
def __init__(self, **kwargs): <NEW_LINE> <INDENT> assert ('sid' in kwargs) <NEW_LINE> assert ('did' in kwargs) <NEW_LINE> assert ('obj_id' in kwargs) <NEW_LINE> self.sid = kwargs['sid'] <NEW_LINE> self.did = kwargs['did'] <NEW_LINE> self.obj_id = kwargs['obj_id'] <NEW_LINE> self.__row_filter = kwargs.get('sql_filter', ...
This method is used to initialize the class and create a proper object name which will be used to fetch the data using namespace name and object name. Args: **kwargs : N number of parameters
625941f0566aa707497f4ae6
def nominalSpeed(self): <NEW_LINE> <INDENT> return self.orbitalSpeedAroundPrimary()
This is the nominal speed of the object at this location. For orbits it is orbital speed; for non-orbits it is the instantaneous speed. [m/s]
625941f0fff4ab517eb2f9c5
def test_destination_package(): <NEW_LINE> <INDENT> request = Mock() <NEW_LINE> request.registry = {"localize": build_localize_config({"localize.translation.destination": "tests:translations"})} <NEW_LINE> result = destination_path(request) <NEW_LINE> assert result == os.path.join(package_path(sys.modules["tests"]), "t...
Testing translation package:path resolve.
625941f0293b9510aa2c3815
def terminate(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = self.redant.wait_for_io_to_complete(self.all_mounts_procs, self.mounts) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception("IO failed on some of the clients") <NEW_LINE> <DEDENT> curr_vol_list = self.redant.get_volume_list(self.server_list[...
The voume created in the test case is destroyed.
625941f08e7ae83300e4b554
def __init__(self, **kwd): <NEW_LINE> <INDENT> super().__init__(**kwd) <NEW_LINE> self.column_names = ["seqname", "start", "end", "nbases", "ambigs", "polymer"] <NEW_LINE> self.columns = 6
summarizes the quality of sequences in an unaligned or aligned fasta-formatted sequence file
625941f026238365f5f0f3fb
def test_pk_set_on_repeated_add_remove(self): <NEW_LINE> <INDENT> pk_sets_sent = [] <NEW_LINE> def handler(signal, sender, **kwargs): <NEW_LINE> <INDENT> if kwargs['action'] in ['pre_add', 'pre_remove']: <NEW_LINE> <INDENT> pk_sets_sent.append(kwargs['pk_set']) <NEW_LINE> <DEDENT> <DEDENT> models.signals.m2m_changed.co...
m2m_changed is always fired, even for repeated calls to the same method, but the behavior of pk_sets differs by action. - For signals related to `add()`, only PKs that will actually be inserted are sent. - For `remove()` all PKs are sent, even if they will not affect the DB.
625941f015baa723493c44ff
def write_spectrum(filename, traj, filetype='txt', comments=''): <NEW_LINE> <INDENT> if filetype in ('rruff', 'txt'): <NEW_LINE> <INDENT> return write_rruff(filename, traj, comments) <NEW_LINE> <DEDENT> if filetype == 'opus': <NEW_LINE> <INDENT> return write_opus(filename, traj, comments) <NEW_LINE> <DEDENT> raise Valu...
Writes a spectrum to file with the specified filetype. Filetype choices are: ('txt', 'rruff', 'opus')
625941f0be7bc26dc91cdb7a
def compatible_types(t1,t2,A_alpha): <NEW_LINE> <INDENT> return float(A_alpha[t1-1][t2-1])<=1
True if t1 and t2 are compatible
625941f0aad79263cf390fcf
def __and__(self, query): <NEW_LINE> <INDENT> return And([self, query]).normalize()
Allows you to use & between query objects to wrap them in an Or query.
625941f0ec188e330fd5ad18
def selection_changed(self, widget): <NEW_LINE> <INDENT> meaning_detail = self.builder.get_object("textview_word_detail") <NEW_LINE> select_word = '' <NEW_LINE> (tree_model, tree_iter) = widget.get_selected() <NEW_LINE> if tree_iter : <NEW_LINE> <INDENT> select_word = tree_model.get_value(tree_iter, COLUMN_WORD) <NEW_L...
单击词条时触发 1、发音 2、显示详细的解释
625941f091f36d47f21aca7e
def delete(name): <NEW_LINE> <INDENT> ret = {'comment': [], 'result': True} <NEW_LINE> if not name: <NEW_LINE> <INDENT> ret['comment'] = 'Job name is required.' <NEW_LINE> ret['result'] = False <NEW_LINE> <DEDENT> if name in __opts__['schedule']: <NEW_LINE> <INDENT> out = __salt__['event.fire']({'job': name, 'func': 'd...
Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1
625941f04428ac0f6e5bad7d
def clearMinimumDateTime(self): <NEW_LINE> <INDENT> pass
clearMinimumDateTime(self)
625941f0e5267d203edce21b
def disableCteCapture(self, resource): <NEW_LINE> <INDENT> args = {} <NEW_LINE> return self._sendRequest('PUT', '/api/cte_capture_resources/' + str(resource) + '/disable', args, False)
disableCteCapture : Detaches an IFC Capture resource from a filter. Sample usage:
625941f03317a56b8693a1cf
def test_with_nonexistent_tag(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('blog:tag', args=['doesnt-exist'])) <NEW_LINE> self.assertEqual(response.status_code, 404)
Looking for a non-existent tag should cause a 404 error.
625941f0a79ad161976cc6cb
def estimate_parameters(self, signal, x1, x2, only_current=False): <NEW_LINE> <INDENT> super()._estimate_parameters(signal) <NEW_LINE> axis = signal.axes_manager.signal_axes[0] <NEW_LINE> centre, height, gamma = _estimate_lorentzian_parameters(signal, x1, x2, only_current) <NEW_LINE> scaling_factor = _get_scaling_facto...
Estimate the Lorentzian by calculating the median (centre) and half the interquartile range (gamma). Note that an insufficient range will affect the accuracy of this method. Parameters ---------- signal : Signal1D instance x1 : float Defines the left limit of the spectral range to use for the estimation. x2 :...
625941f0bd1bec0571d90bb4
def save_grid_to_file(self, num): <NEW_LINE> <INDENT> grid = self._grid.get_grid() <NEW_LINE> width = self._grid.width <NEW_LINE> height = self._grid.height <NEW_LINE> file = open(f'grid{num}.txt', 'w', buffering=1) <NEW_LINE> file.write(str(width) + '\n') <NEW_LINE> file.write(str(height) + '\n') <NEW_LINE> for j in r...
Saves the current grid and its width and height to a txt file named after the given number
625941f0090684286d50f275
def next_package_number_in_shipment(self): <NEW_LINE> <INDENT> if self.packages.exists(): <NEW_LINE> <INDENT> max_number = self.packages.aggregate(max_number=Max('number_in_shipment'))['max_number'] <NEW_LINE> return 1 + max_number <NEW_LINE> <DEDENT> return 1
Return the next package number that should be assigned to a package in this shipment
625941f08e71fb1e9831dd2c
def __init__(self, populations: List[Population], additional_weight_name='w', soma_name='soma'): <NEW_LINE> <INDENT> self.populations = populations <NEW_LINE> self._check_and_add_spike_detector(soma_name) <NEW_LINE> self.population_names = [p.name for p in populations] <NEW_LINE> self.colors = [] <NEW_LINE> self.texts ...
Create a Network Graph :param populations: list of population to create a graph :param additional_weight_name: name of additional weight which is point_process's additional weight (which change with plasticity), if a point_process don't contains this name it will be ignored. In such case only weight f...
625941f0be8e80087fb211bf
def run_train_iter(self, data_batch, epoch): <NEW_LINE> <INDENT> self.scheduler.step(epoch=epoch) <NEW_LINE> if self.current_epoch != epoch: <NEW_LINE> <INDENT> self.current_epoch = epoch <NEW_LINE> <DEDENT> if not self.training: <NEW_LINE> <INDENT> self.train() <NEW_LINE> <DEDENT> x_support_set, x_target_set, y_suppor...
Runs an outer loop update step on the meta-model's parameters. :param data_batch: input data batch containing the support set and target set input, output pairs :param epoch: the index of the current epoch :return: The losses of the ran iteration.
625941f0d18da76e23532a63
def GetInitialized(self): <NEW_LINE> <INDENT> return _ITKOptimizersPython.itkOnePlusOneEvolutionaryOptimizer_GetInitialized(self)
GetInitialized(self) -> bool
625941f0956e5f7376d713f1
def __init__(self, email, password, sheetname, tabname): <NEW_LINE> <INDENT> gc = gspread.login(email, password) <NEW_LINE> spreadsheet = gc.open(sheetname) <NEW_LINE> self.wks = spreadsheet.worksheet(tabname) <NEW_LINE> self.headers = self.wks.row_values(1) <NEW_LINE> self.raw_items = itertools.islice(self.wks.get_all...
Connect to Google and gets access to the Sheet
625941f08e05c05ec3eea8ff
def crunet116(**kwargs): <NEW_LINE> <INDENT> return get_crunet(blocks=116, model_name="crunet116", **kwargs)
CRU-Net-116 model from 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural Networks,' https://www.ijcai.org/proceedings/2018/88. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in...
625941f0b830903b967e9e8a
def test_add_particle_and_particle_list(various_particles): <NEW_LINE> <INDENT> new_particle_list = electron + various_particles <NEW_LINE> assert new_particle_list[0] == electron <NEW_LINE> assert new_particle_list[1:] == various_particles <NEW_LINE> assert isinstance(new_particle_list, ParticleList)
Test that a `Particle` can be added to a `ParticleList` on the right and then return a `ParticleList`.
625941f02ae34c7f2600d6b6
@operation <NEW_LINE> def run(ctx, script_path=None, **kwargs): <NEW_LINE> <INDENT> script_to_run = get_script_to_run(ctx, script_path) <NEW_LINE> if script_to_run: <NEW_LINE> <INDENT> execfile(script_to_run)
Execute python scripts. Parameters: ctx['scripts'] - A dictionary mapping lifecycle events to script paths. script_path - The path to the script relative to the blueprints root directory. Will only be used if the 'scripts' argument is None. Exceptio...
625941f03c8af77a43ae3d2d
def __init__(self, opt=None): <NEW_LINE> <INDENT> if opt is None: <NEW_LINE> <INDENT> opt = {} <NEW_LINE> <DEDENT> FISTA.Options.__init__(self, opt)
Parameters ---------- opt : dict or None, optional (default None) FISTADFT algorithm options
625941f096565a6dacc8fc4f
def parseRandomizationResult(dat): <NEW_LINE> <INDENT> if dat is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> lv1names = [ str(x) for x in dat.keys ] <NEW_LINE> assign = dat[lv1names[0]] <NEW_LINE> summary = dat[lv1names[1]] <NEW_LINE> assignnames = [ str(x) for x in assign.keys ] <NEW_LINE> res = {} <NEW_...
parse the result from R: in R it is a named list: list(assign=assign,summary=table(assign$group)) assign itself is a dataframe in python, this becomes tagged list. **WARNING**: THIS ASSUMES FIXED FORMAT FROM R SIDE; WILL BREAK IF THE R SIDE CHANGES!!! In general, python numpy/list etc is not as very well ...
625941f045492302aab5e84f
def setToggle(self, toggle): <NEW_LINE> <INDENT> self.switch = toggle <NEW_LINE> if self.linkedSetting and self.linkedDict: <NEW_LINE> <INDENT> self.linkedDict[self.linkedSetting] = self.switch <NEW_LINE> <DEDENT> if self.switch: <NEW_LINE> <INDENT> self.switchBrush = self.onBrush <NEW_LINE> self.xPos = self.width() - ...
set ``switch`` to ``toggle``, and update
625941f094891a1f4081c032
def set_RefreshToken(self, value): <NEW_LINE> <INDENT> super(DeleteRouteInputSet, self)._set_input('RefreshToken', value)
Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.)
625941f04f6381625f114fc1
def checkSetiTime(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> logger.debug("Checking to see if SETI should be started/stopped.") <NEW_LINE> existingTime = alienSearch.getTimeFromFile() <NEW_LINE> if existingTime > time.time(): <NEW_LINE> <INDENT> logger.debug("SETI should be running... starting now.") <NEW_L...
Check to see if SETI needs to be stopped or started based on the time file. Run every hour.
625941f0046cf37aa974d2c7
def set_title(title): <NEW_LINE> <INDENT> return f"{OSC}2;{title}{BEL}"
Set terminal title.
625941f0bf627c535bc13755
def sendToClientFromID( clientId, msg ): <NEW_LINE> <INDENT> assert isString( msg ) <NEW_LINE> msg = color.color( msg + "{@") <NEW_LINE> if clientId in clientMsgs: <NEW_LINE> <INDENT> clientMsgs[clientId] = clientMsgs[clientId] + msg <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> clientMsgs[clientId] = msg
Internal use only
625941f0656771135c3ebdfc
def plot(self, param_name, pickup_num): <NEW_LINE> <INDENT> if pickup_num > len(self.Pc): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Pc_nlm = (self.Pc[-1]-self.Pc[0])/(pickup_num-1) <NEW_LINE> pick_idx = lambda i: np.abs(np.asarray(self.Pc)-(Pc_nlm*i + self.Pc[0])).argmin() <NEW_LINE> idx = ...
Plot graph about relationship of param to of and Pc Parameters ---------- param_name: string Parameter name which is a dataset file name e.g. "CSTAR", "GAMMAs", "T_c", "Cp_c" pickup_num: int The number of "Pc" picked up to draw a graph
625941f06e29344779a62b97
def interpolate_matrix_1D(matrix_in, E_array_in, E_array_out, axis=1): <NEW_LINE> <INDENT> if axis not in [0, 1]: <NEW_LINE> <INDENT> raise IndexError("Axis out of bounds. Must be 0 or 1.") <NEW_LINE> <DEDENT> if not (matrix_in.shape[axis] == len(E_array_in)): <NEW_LINE> <INDENT> raise Exception("Shape mismatch between...
Does a one-dimensional interpolation of the given matrix_in along axis
625941f0baa26c4b54cb169f
def test(): <NEW_LINE> <INDENT> print("Prueba del entorno con un agente aleatorio") <NEW_LINE> entornos_o.simulador(DosCuartos(), AgenteAleatorio(['ir_A', 'ir_B', 'limpiar', 'nada']), 100) <NEW_LINE> print("Prueba del entorno con un agente reactivo") <NEW_LINE> entornos_o.simulador(DosCuartos(), AgenteReactivoDoscuarto...
Prueba del entorno y los agentes
625941f07d43ff24873a322b
def _compute_activations_shapes(self): <NEW_LINE> <INDENT> for name, module in self._modules.items(): <NEW_LINE> <INDENT> self._activations_shape[name] = get_output_shape(module) <NEW_LINE> <DEDENT> self._is_shapes = True
Fill the _activations_shape dictionnary with the shapes of the X_l tensors.
625941f0ff9c53063f47c776
def get_random(self, player): <NEW_LINE> <INDENT> new_state = MinesweeperState([self.player]) <NEW_LINE> positions = [[i, j] for i in range(grid_height) for j in range(grid_width)] <NEW_LINE> new_state.discovered = [ [number for number in row] for row in self.discovered ] <NEW_LINE> if not self.prob: <NEW_LINE> <INDENT...
Return a possible bomb configuration, based on the information available to the player
625941f067a9b606de4a843c
def __virtual__(): <NEW_LINE> <INDENT> if not HAS_DEPS: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return 'nagios_json'
Only load if requests is successfully imported
625941f0377c676e9127272c
def direct_parse_key(biom_str, key): <NEW_LINE> <INDENT> base_idx = biom_str.find('"%s":' % key) <NEW_LINE> if base_idx == -1: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_idx = base_idx + len(key) + 3 <NEW_LINE> <DEDENT> cur_idx = start_idx <NEW_LINE> while biom_str[cur_idx] not in...
Returns key:value from the biom string, or "" This method pulls an arbitrary key/value pair out from a BIOM string
625941f082261d6c526aba2e
def format_string(string, *formats): <NEW_LINE> <INDENT> return ''.join([''.join(formats), string, RESET_ALL])
Format a string using any color and format constants from this module. All formats will be reset at the end. :param string: The string to format. :param formats: Any number of color or format constants from this module. :return: The formatted string
625941f0a17c0f6771cbe5d5
def tidy(rc, fqfn, ofn, sizecheck=True): <NEW_LINE> <INDENT> global olines <NEW_LINE> global thebin <NEW_LINE> bname = os.path.basename(fqfn) <NEW_LINE> olog = thebin + bname + "-tvhf.log" <NEW_LINE> if rc == 0: <NEW_LINE> <INDENT> log.info("Conversion was successful") <NEW_LINE> insize = FUT.fileSize(fqfn) <NEW_LINE> ...
tidies up after ffmpeg. rc = ffmpeg returncode
625941f0c432627299f051d0
def select_template(self, template_name_list): <NEW_LINE> <INDENT> if not template_name_list: <NEW_LINE> <INDENT> raise TemplateDoesNotExist("No template names provided") <NEW_LINE> <DEDENT> not_found = [] <NEW_LINE> for template_name in template_name_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.get_t...
Given a list of template names, returns the first that can be loaded.
625941f0a05bb46b383ecda2
def create_model_package_types(): <NEW_LINE> <INDENT> user = tk.get_action('get_site_user')({'ignore_auth': True}, {}) <NEW_LINE> context = {'user': user['name']} <NEW_LINE> try: <NEW_LINE> <INDENT> data = {'id': 'model_package_types'} <NEW_LINE> tk.get_action('vocabulary_show')(context, data) <NEW_LINE> logging.info("...
Create model_package_types vocab and tags, if they don't exist already. Note that you could also create the vocab and tags using CKAN's API, and once they are created you can edit them (e.g. to add and remove possible dataset country code values) using the API.
625941f021bff66bcd684ed3
def test_config_file_demo(self): <NEW_LINE> <INDENT> def _gen(): <NEW_LINE> <INDENT> f = open(PIPELINE_DEMO_CONFIG_FILEPATH) <NEW_LINE> config = json.loads(f.read()) <NEW_LINE> arch = Architecture.from_dict(config) <NEW_LINE> hooks = arch.get_hooks() <NEW_LINE> f.close() <NEW_LINE> return arch, hooks <NEW_LINE> <DEDENT...
Test config file form against demo program to prove general operation
625941f0a219f33f34628ee7
def create_logger(format): <NEW_LINE> <INDENT> formatter = logging.Formatter(fmt=format[0], datefmt=format[1]) <NEW_LINE> logging.getLogger('').setLevel(logging.DEBUG) <NEW_LINE> ch = logging.StreamHandler() <NEW_LINE> ch.setLevel(logging.INFO) <NEW_LINE> ch.setFormatter(formatter) <NEW_LINE> logging.getLogger('').addH...
Constructs output stream logger.
625941f0046cf37aa974d2c8
def __rsub__(self, other): <NEW_LINE> <INDENT> return other + -1. * self
Subtracts this PauliTerm from a Number or PauliTerm. :param other: A PauliTerm object or a Number :returns: A PauliSum object representing the difference of this PauliTerm and term :rtype: PauliSum
625941f085dfad0860c3b3e3
def check_sign_transform_algorithm(self, source): <NEW_LINE> <INDENT> signed_info = source['Signature']['SignedInfo'] <NEW_LINE> trans = signed_info['Reference']['Transforms']['Transform@Algorithm'] <NEW_LINE> if trans != DCP_SETTINGS['xmluri']['enveloped_sig']: <NEW_LINE> <INDENT> self.error("Invalid transform method"...
XML signature transform algorithm check. References: N/A
625941f0dd821e528d63b72a
def gpCovGrads(self): <NEW_LINE> <INDENT> return _ndlml.gp_gpCovGrads(self)
gpCovGrads(gp self)
625941f032920d7e50b2875b
def read_lines(path: Union[str, Path], encoding: str = 'utf-8', line_sep: str = '\n') -> List[str]: <NEW_LINE> <INDENT> return file2str(path, encoding).split(line_sep)
从文本文件中读取每一行,并返回列表
625941f050485f2cf553d322
def divert_end(self): <NEW_LINE> <INDENT> if not self.filename: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> os.lseek(self.fd, os.SEEK_SET, 0) <NEW_LINE> content = os.read(self.fd, 1024) <NEW_LINE> os.dup2(self.savedfd, self.fd) <NEW_LINE> os.close(self.savedfd) <NEW_LINE> os.unlink(self.filename) <NEW_LINE> self....
Restore a previous diversion and return its content.
625941f05fcc89381b1e1c4a
def check_value_set_key(obj_to, obj_from, key, index, flag_verbose = False): <NEW_LINE> <INDENT> if getattr(obj_to, key): <NEW_LINE> <INDENT> if getattr(obj_to, key) != getattr(obj_from, key): <NEW_LINE> <INDENT> setattr(obj_to, key, numpy.nan) <NEW_LINE> DEBUG.verbose(key + " does not match. Set to NaN", flag_verbose ...
checks if a key is set. If it is set, it checks if the values are the same. If not, it gives an error and gives the variable a value numpy.nan. If the value is not set and index == 0, it will set the value. CHANGELOG: 20130208/RB: started the function
625941f0f548e778e58cdb06
@periodic_task(run_every=timedelta(hours=8)) <NEW_LINE> def update_all_corps(): <NEW_LINE> <INDENT> corp_ids = [c.id for c in Corporation.objects.all()] <NEW_LINE> provider = eve_provider_factory() <NEW_LINE> for obj_id in corp_ids: <NEW_LINE> <INDENT> update_corporation.delay(obj_id, provider=provider)
Triggers an update of all Corporation models
625941f055399d3f05588c3e
def transform_param(node, **kwargs): <NEW_LINE> <INDENT> param = etree.Element("param") <NEW_LINE> name = node.get("name") <NEW_LINE> value = node.text <NEW_LINE> param.attrib["name"] = name <NEW_LINE> param.text = value <NEW_LINE> return param
Transforms a RELAX NG param into a new XML structure
625941f08c0ade5d55d3ef46
def test_update_config_same_section(self): <NEW_LINE> <INDENT> cfg2 = BaseConfig({'foo':'foobar'}) <NEW_LINE> self.cfg.update(cfg2) <NEW_LINE> self.assertDictEqual(self.cfg, {'foo':'foobar'}) <NEW_LINE> del cfg2
Test updating configuration with another configuration object whose sections overlap. Note that this will overwrite the first configuration. FIXME: should this be intended behaviour?
625941f08e71fb1e9831dd2d
def add_two_node(self,l1,l2): <NEW_LINE> <INDENT> rst = Node(0) <NEW_LINE> carry = 0 <NEW_LINE> first = rst <NEW_LINE> while(l1 != None and l2 != None): <NEW_LINE> <INDENT> rst.val = (l1.val+l2.val+carry)%10 <NEW_LINE> rst.next = Node(rst.val) <NEW_LINE> if int((l1.val+l2.val)/10) == 0: <NEW_LINE> <INDENT> carry = 0 <N...
总结:if条件写太多,思考是不是反向写一个简单的,包含所有情况的,只是在内部做一点判断;
625941f076d4e153a657f0b8
def search_by_address(self, address, radius=None, query=None, category=None): <NEW_LINE> <INDENT> precondition(isinstance(address, basestring), address) <NEW_LINE> precondition(address != '', address) <NEW_LINE> precondition(radius is None or is_numeric(radius), radius) <NEW_LINE> precondition(query is None or isinstan...
Search for places near the given address, within a radius (in kilometers). The server figures out the latitude and longitude from the street address and then does the same thing as search(), using that deduced latitude and longitude.
625941f0eab8aa0e5d26e0e0
def get_embedding(): <NEW_LINE> <INDENT> return paddle.v2.dataset.common.download(EMB_URL, 'conll05st', EMB_MD5)
Get the trained word vector based on Wikipedia corpus.
625941f0baa26c4b54cb16a0
def append_skipped(self, report): <NEW_LINE> <INDENT> self.class_logger.info("Appending XML report with skip.") <NEW_LINE> longrepr = xml_unescape(report['longrepr']) <NEW_LINE> skipreason = get_skipped_reason(report['longrepr']) <NEW_LINE> self.append(self.Junit.skipped("%s" % longrepr, type="pytest.skip", message=ski...
Append xml reports with skipped TC. Args: report(dict): Skipped report
625941f06aa9bd52df03732e
def distance(self, first_atoms=None, second_atoms=None, cutoff=None, use=None): <NEW_LINE> <INDENT> if cutoff: <NEW_LINE> <INDENT> cutoff = float(cutoff) <NEW_LINE> if cutoff <= 0.0: <NEW_LINE> <INDENT> raise ValueError("Must give a cutoff greater than 0") <NEW_LINE> <DEDENT> self._distance['cutoff'] = cutoff <NEW_LINE...
Define the distance cutoffs. This allows the definition of the cutoff to use, whether or not to use atom-atom or center-center and the sets of atoms to use. If the sets of atoms to use are specified then base are the atoms used for all further calculations. :first_atoms: A list of atoms to use when comparing distance ...
625941f04e4d5625662d4956
def alpha_to_latitude(self, alpha, boundaries_to_use="small_map_boundaries"): <NEW_LINE> <INDENT> north, south = self.get_latitude_boundaries(boundaries_to_use) <NEW_LINE> return north * (1 - alpha) + south * alpha
Convert alpha (fraction of image height) to latitude.
625941f0925a0f43d254a403
def getVDF(TRAIN_CSV): <NEW_LINE> <INDENT> dataframe = pd.read_excel(TRAIN_CSV,header= 0) <NEW_LINE> dataframe = dataframe.drop(axis=1,columns=['Commit URL', 'Sha','URL','Author Name','Author Email','Commit Date','Verification','Author Date']) <NEW_LINE> dataframe = shuffle(dataframe) <NEW_LINE> dataframe = dataframe.a...
Get data from the training sample CSV and perform various cleaning and data preprocessing
625941f07047854f462a1989
def configure(roles, machineguid, controller_addr, ssh): <NEW_LINE> <INDENT> if ssh: <NEW_LINE> <INDENT> j.system.fs.remove("/etc/service/sshd/down") <NEW_LINE> <DEDENT> config = get_config() <NEW_LINE> gid = int(config["environment"]["grid"]["id"]) <NEW_LINE> print("[+] set gid to: %s" % gid) <NEW_LINE> roles = roles....
configures the js7 node.
625941f063b5f9789fde766c
def test_delete_users(app, db_session, example_usernames): <NEW_LINE> <INDENT> for username in example_usernames: <NEW_LINE> <INDENT> db_session.add(User(username=username)) <NEW_LINE> db_session.commit() <NEW_LINE> <DEDENT> delete_users(app.config["DB"], example_usernames[1:]) <NEW_LINE> remaining_usernames = list(zip...
Test the basic functionality of ``delete_users``.
625941f029b78933be1e5c2b
def stop(self): <NEW_LINE> <INDENT> self.rpc.do('stop') <NEW_LINE> self._stopped = True
Quit the program
625941f0498bea3a759ba034
@app.route("/cambioclaveale/<id>", methods=["PUT",]) <NEW_LINE> @jwt_required <NEW_LINE> def cambioclavealetaria(id): <NEW_LINE> <INDENT> usuario_id_jwt = get_jwt_identity() <NEW_LINE> usuario= Usuario.query.get(usuario_id_jwt) <NEW_LINE> admin = usuario.administrador <NEW_LINE> if (admin == True): <NEW_LINE> <INDENT> ...
PUT actualizar la clave de un usuario en particular
625941f0e64d504609d74dc6
@lru_cache() <NEW_LINE> def power_spectrum_cutout_indexes(pow_spec_len, sample_rate, min_freq, max_freq)-> tuple: <NEW_LINE> <INDENT> step = sample_rate / (2 * pow_spec_len) <NEW_LINE> index_l = int(np.round(min_freq // step)) <NEW_LINE> index_h = int(np.round(max_freq // step)) <NEW_LINE> return (index_h - index_l, in...
Returns array size and cutout indexes given min and max frequencies
625941f0187af65679ca56a6
def get_all(jpath, data): <NEW_LINE> <INDENT> tokens = list(TOKENIZER.tokenize(jpath)) <NEW_LINE> tokens.reverse() <NEW_LINE> return list(Token.apply(tokens, data))
Get list of all elements matched by given jpath in the data datastructure. >>> get_all('', 1) [1] >>> get_all('[1]', [1, 2]) [2] >>> get_all('[*]', [1, 2]) [1, 2] >>> get_all('*', [1, 2]) [1, 2] >>> get_all('*[0]', [1, [2, 4], 3]) [2] >>> get_all('*[0]', [1, [2, 4], 3, []]) [2] >>> get_all('*.ziew', [1, {'ziew':2}, [3...
625941f0956e5f7376d713f2
def parse(self): <NEW_LINE> <INDENT> self.ips = [] <NEW_LINE> for file in self.files: <NEW_LINE> <INDENT> rss = feedparser.parse(file) <NEW_LINE> self.date = rss['feed']['updated'] <NEW_LINE> values = self.extract_from_xml(rss) <NEW_LINE> for value in values: <NEW_LINE> <INDENT> entry = self.prepare_entry(ip = value[0]...
Parse the list
625941f066656f66f7cbc733
def cwrite(string, stream=sys.stdout, color=None): <NEW_LINE> <INDENT> if color is None: <NEW_LINE> <INDENT> color = stream.isatty() or _force_color <NEW_LINE> <DEDENT> stream.write(colorize(string, color=color))
Replace all color expressions in string with ANSI control codes and write the result to the string. If color is False, this will write plain text with no color. If True, then it will always write colored output. If not supplied, then it will be set based on stream.isatty().
625941f0ac7a0e7691ed4648
def _output(self, s): <NEW_LINE> <INDENT> self._buffer.append(s)
Add a line of output to the current request buffer. Assumes that the line does *not* end with \r\n.
625941f03346ee7daa2b32f7
def exchange_rates(self): <NEW_LINE> <INDENT> r = requests.get('https://www.cbr-xml-daily.ru/daily_json.js') <NEW_LINE> return r.json()['Valute']
Возвращает ответ сервиса с информацией о валютах в виде: { 'AMD': { 'CharCode': 'AMD', 'ID': 'R01060', 'Name': 'Армянских драмов', 'Nominal': 100, 'NumCode': '051', 'Previous': 14.103, 'Value': 14.0879 }, ... }
625941f0d4950a0f3b08c8cd
def ext_pillar(minion_id, pillar, config_file): <NEW_LINE> <INDENT> if os.path.isfile(config_file): <NEW_LINE> <INDENT> import salt.utils.yaml <NEW_LINE> try: <NEW_LINE> <INDENT> config = _render_template(config_file) or {} <NEW_LINE> opts = salt.utils.yaml.safe_load(config) or {} <NEW_LINE> opts['conf_file'] = config_...
Execute LDAP searches and return the aggregated data
625941f023849d37ff7b3611
def export_contributions(statuses): <NEW_LINE> <INDENT> (review_requests, notreviewed) = _fetch_active_reviews_by_status(statuses) <NEW_LINE> for data in export_from_review_requests(review_requests): <NEW_LINE> <INDENT> yield data <NEW_LINE> <DEDENT> for user_contrib in notreviewed: <NEW_LINE> <INDENT> for data in expo...
Produce a list of dicts, each representing a contribution.
625941f07d847024c06be847
def make_request(self, ride_id, request_data): <NEW_LINE> <INDENT> res = self.get_ride(ride_id) <NEW_LINE> if res.get('Status'): <NEW_LINE> <INDENT> user_requests = res.get('Message').get('Requests') <NEW_LINE> user_requests.append(request_data) <NEW_LINE> return {'Status': True, 'Message': 'Request made successfuly'} ...
Make a request to join a ride. Args: ride_id(int): Unique identifier of the ride owner(str): Name of user who created the ride request_data(dict): request details
625941f0b545ff76a891439c
def IsInside(self, *args): <NEW_LINE> <INDENT> return _itkImageSpatialObjectPython.itkImageSpatialObject3UC_IsInside(self, *args)
IsInside(self, itkPointD3 point, unsigned int depth, char name) -> bool IsInside(self, itkPointD3 point) -> bool
625941f029b78933be1e5c2c