code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_project_flag_search_by_user(self): <NEW_LINE> <INDENT> flag = create_flagged_project(self.session) <NEW_LINE> flag_add = utilities.flag_project( self.session, flag.project, "This is a duplicate.", "cthulhu@redhat.com", "user_openid_id", ) <NEW_LINE> flag_add.state = "closed" <NEW_LINE> self.session.add(flag_ad... | Assert that 'ProjectFlag.search' returns correct project
if from date is provided. | 625941e83317a56b8693a0e2 |
def diffusion() -> None: <NEW_LINE> <INDENT> instance = Instance({ Operator.O_I: ['state_out'], Operator.S: ['state_in'], Operator.O_F: ['final_state_out']}) <NEW_LINE> while instance.reuse_instance(): <NEW_LINE> <INDENT> t_max = instance.get_setting('t_max', 'float') <NEW_LINE> dt = instance.get_setting('dt', 'float')... | A simple diffusion model on a 1d grid.
The state of this model is a 1D grid of concentrations. It sends
out the state on each timestep on `state_out`, and can receive an
updated state on `state_in` at each state update. | 625941e84c3428357757c7bb |
def require_valid_url_fragment( name: str, name_type: str, allowed_length: int ) -> None: <NEW_LINE> <INDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise ValidationError( '%s field must be a string. Received %s.' % (name_type, name)) <NEW_LINE> <DEDENT> if name == '': <NEW_LINE> <INDENT> raise ValidationErr... | Generic URL fragment validation.
Args:
name: str. The name to validate.
name_type: str. A human-readable string, like 'topic url fragment'.
This will be shown in error messages.
allowed_length: int. Allowed length for the name.
Raises:
ValidationError. Name is not a string.
ValidationError... | 625941e89f2886367277ad1f |
def formatSize(bytes, unit = 'm'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bytes = float(bytes) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("传入的字节格式不对") <NEW_LINE> return "Error" <NEW_LINE> <DEDENT> kb = bytes / 1024 <NEW_LINE> M = kb / 1024 <NEW_LINE> G = M / 1024 <NEW_LINE> if unit == 'b' or unit == 'b... | :param bytes:
:param unit= 'b','k','m','g'
:return: 'b','k','m','g' | 625941e83346ee7daa2b3205 |
def get(self, request, content_type_id, object_id): <NEW_LINE> <INDENT> r = ApiResponseData() <NEW_LINE> object_query_filter = {'content_type_id': content_type_id, 'object_id': object_id} <NEW_LINE> likes = Likes.objects.filter(**object_query_filter).prefetch_related('user').order_by('id') <NEW_LINE> r.count = likes.co... | Get the list of user who like an Object. | 625941e83539df3088e2e7e1 |
def SNR(poisson_values): <NEW_LINE> <INDENT> left_poisson1 = np.asarray(poisson_values[0]) <NEW_LINE> left_poisson2 = np.asarray(poisson_values[1]) <NEW_LINE> right_poisson1 = np.asarray(poisson_values[2]) <NEW_LINE> right_poisson2 = np.asarray(poisson_values[3]) <NEW_LINE> numerator = np.sum(np.subtract(left_poisson1,... | Calculates the SNR based on the equation in Energy window optimization for X-Ray K-edge tomographic imaging, by
Meng et al
:param poisson_values: Takes the poisson array from the 'calc_4_poisson' function
:return: The SNR | 625941e83eb6a72ae02ec97f |
def _set_layerOrder(self, value, **kwargs): <NEW_LINE> <INDENT> self.raiseNotImplementedError() | This is the environment implementation of
:attr:`BaseFont.layerOrder`. **value** will
be a **list** of :ref:`type-string` representing
layer names. The list will have been normalized
with :func:`normalizers.normalizeLayerOrder`.
Subclasses must override this method. | 625941e8b5575c28eb68e49a |
def test_text_get(self): <NEW_LINE> <INDENT> subject = MetadataSubjectTest.objects.get(pk=1) <NEW_LINE> self.assertEqual( subject.metadata['text']['single'], 'moof!' ) <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> subject.metadata['text']['notakey'] <NEW_LINE> <DEDENT> with self.assertRaises(KeyError... | Tests whether getting textual metadata works. | 625941e830c21e258bdfa938 |
def get_heading_enumeration(self): <NEW_LINE> <INDENT> chapter_number = self.__registered[:] <NEW_LINE> while chapter_number and chapter_number[-1] == 0: <NEW_LINE> <INDENT> chapter_number = chapter_number[:-1] <NEW_LINE> <DEDENT> return chapter_number if chapter_number else [0] | Return current number/enumeration as shown in table of contents.
The result is a list of integers representing the current heading. | 625941e8d8ef3951e32439d3 |
def cyview(query, dataset='HMDB', connections='targets', name='', database=DATABASE): <NEW_LINE> <INDENT> from py2cytoscape.data.cyrest_client import CyRestClient <NEW_LINE> from py2cytoscape.data.style import Style <NEW_LINE> qc = parseinputquery(query) <NEW_LINE> print(qc) <NEW_LINE> if dataset.upper() == 'HMDB': <NE... | See HMDB/DrugBank graphs with Cytoscape runing on your local machine
`
:param query: Query to select HMDB or DrugBank entries
:param dataset: HMDB or DrugBank, not case sensitive
:param connections: Connection type for DrugBank entries
:param name: Name of the graph on Cytoscape, query is used as de... | 625941e8283ffb24f3c55d92 |
def test_lineno(n, lineno, index): <NEW_LINE> <INDENT> if index != -1: <NEW_LINE> <INDENT> b, e = lineno[index] <NEW_LINE> if b<=n and ((e==-1) or n<=e): <NEW_LINE> <INDENT> return True, index <NEW_LINE> <DEDENT> <DEDENT> for i, v in enumerate(lineno): <NEW_LINE> <INDENT> b, e = lineno[i] <NEW_LINE> if b<=n and ((e==-1... | last status | 625941e8baa26c4b54cb15b1 |
def area(self): <NEW_LINE> <INDENT> return self.height * self.width | Compute the zone area, in square kilometers | 625941e88a349b6b435e8608 |
def test_loss_generator(path): <NEW_LINE> <INDENT> for line in open(path): <NEW_LINE> <INDENT> tokens = line.strip().split() <NEW_LINE> if len(tokens) == 7: <NEW_LINE> <INDENT> yield math.log10(float(tokens[5])) | This function generates testing losses.
@param path a path to a log file | 625941e8f7d966606f6aa49f |
def generate_random_sample_points(self, n_sample): <NEW_LINE> <INDENT> x = np.random.uniform(self.xmin, self.xmax, n_sample) <NEW_LINE> y = np.random.uniform(self.ymin, self.ymax, n_sample) <NEW_LINE> return x + 1j*y | Generate n_sample points, distributed randomly over rectangle. | 625941e80c0af96317bb867d |
def primesList(N): <NEW_LINE> <INDENT> primesList = [] <NEW_LINE> for i in range(2, N + 1): <NEW_LINE> <INDENT> for j in range(2, i): <NEW_LINE> <INDENT> if i % j == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> primesList.append(i) <NEW_LINE> <DEDENT> <DEDENT> return primesList | N: an integer | 625941e8d53ae8145f87a6fd |
def get_user_details(self, response): <NEW_LINE> <INDENT> user_data = response <NEW_LINE> email = user_data.get('email', '') <NEW_LINE> username = user_data['username'] <NEW_LINE> name = user_data.get('displayName', '') <NEW_LINE> fullname, first_name, last_name = self.get_user_names(name) <NEW_LINE> return {'username'... | Return user details from Sketchfab account | 625941e8fb3f5b602dac3b2e |
def train_on_batch(self, *args, batch_weight=None): <NEW_LINE> <INDENT> if batch_weight is None: <NEW_LINE> <INDENT> batch_weight = [1.0] * len(args[0]) <NEW_LINE> <DEDENT> feed_dict = {ph: arg for ph, arg in zip(self.ph_train_list, args)} <NEW_LINE> feed_dict[self.ph_batch_weight] = batch_weight <NEW_LINE> self.sess.r... | Train the neural network on a batch of rollouts
Args:
args: training arguments. Different in each child class.
e.g., in A3C, args = states, actions, advantages, target_values
in DQN, args = states, actions, target_values
batch_weight: sample weight to be applied on each rollout | 625941e8236d856c2ad44c76 |
def redirect_to(self, url_or_endpoint, **kwargs): <NEW_LINE> <INDENT> if '/' in url_or_endpoint: <NEW_LINE> <INDENT> url = url_or_endpoint <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = self.url_for(url_or_endpoint, **kwargs) <NEW_LINE> <DEDENT> return redirect(self.make_absolute_url(url)) | Redirect to given URL (made absolute if needed).
Assumes that a given string with no slashes in it is an endpoint name
instead of a URL; resolves it with given kwargs. | 625941e80c0af96317bb867e |
def chooseSerieHeader(self): <NEW_LINE> <INDENT> return self.getSeriesHeaders()[self.chooseSerieIndex()] | Method: Interactive selection of the desired serie header.
Print a list of all Series specifying: index, Name, Channel number and Tag, and stack dimensions X, Y, Z, T,...
Promt for selecting a Serie number. | 625941e84428ac0f6e5bac8c |
def prep_net(self): <NEW_LINE> <INDENT> for r in range(self.rows): <NEW_LINE> <INDENT> for c in range(self.cols): <NEW_LINE> <INDENT> grid = np.zeros(self.dims, np.bool) <NEW_LINE> grid[r, c] = GF.nom_chs_mask[r, c] <NEW_LINE> frep = self.feature_rep(grid) <NEW_LINE> for _ in range(self.pp['prep_net']): <NEW_LINE> <IND... | Pre-train net on nominal chs | 625941e85fc7496912cc3e14 |
def hoverEvent(self, ev): <NEW_LINE> <INDENT> if (self.translatable) and (not ev.isExit()) and ev.acceptDrags(QtCore.Qt.LeftButton): <NEW_LINE> <INDENT> self.setMouseHover(True) <NEW_LINE> self.sigHoverEvent.emit(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setMouseHover(False) | Redefine hoverEvent
Partly to ensure that roi does not accept any mouse clicks | 625941e855399d3f05588b4d |
def list(self, reservation_status=values.unset, limit=None, page_size=None): <NEW_LINE> <INDENT> return list(self.stream(reservation_status=reservation_status, limit=limit, page_size=page_size, )) | Lists ReservationInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param ReservationInstance.Status reservation_status: Filter by a worker's reservation status
:param int limit: Upper limit for the number of records to return.... | 625941e876d4e153a657efc9 |
def test_schemes_view_extended_search(self): <NEW_LINE> <INDENT> scheme = SchemeFactory(status=models.Scheme.STATUS_PUBLISHED) <NEW_LINE> resp = self.client.get("/fi/", {"extended_search": False, "status": models.Scheme.STATUS_CLOSED}) <NEW_LINE> self.assertContains(resp, scheme.title) | Assert extended search controls are not used to filter the results when
extended_search is False. | 625941e801c39578d7e752d1 |
def test_that_when_disassociating_stages_to_an_api_key_that_exists_the_disassociate_api_key_stagekeys_method_returns_true(self): <NEW_LINE> <INDENT> self.conn.update_api_key.retuen_value = None <NEW_LINE> result = boto_apigateway.disassociate_api_key_stagekeys(apiKey='88883333amaa1ZMVGCoLeaTrQk8kzOC36vCgRcT2', stagekey... | Test True for returned value of 'associated' | 625941e8d8ef3951e32439d4 |
def p_me(Z, win): <NEW_LINE> <INDENT> if np.count_nonzero(Z) > 0.75*win**2: <NEW_LINE> <INDENT> glcm = greycomatrix(Z, [5], [0], 256, symmetric=True, normed=True) <NEW_LINE> cont = greycoprops(glcm, 'contrast') <NEW_LINE> diss = greycoprops(glcm, 'dissimilarity') <NEW_LINE> homo = greycoprops(glcm, 'homogeneity') <NEW_... | loop to standard deviation | 625941e8d7e4931a7ee9e3b5 |
@pytest.fixture(name="fetch_data") <NEW_LINE> def mock_controller_fetch_data(): <NEW_LINE> <INDENT> with patch("pylinky.client.LinkyClient.fetch_data", return_value={}): <NEW_LINE> <INDENT> yield | Mock a successful get data. | 625941e882261d6c526ab93d |
def __init__(self, n, m, val=0): <NEW_LINE> <INDENT> assert n > 0 and m > 0 <NEW_LINE> self.rows = [[val]*m for i in range(n)] | Create an n-by-m matrix of val's.
Inner representation: list of lists (rows) | 625941e86fece00bbac2dbda |
def calc_jsc(input_illumination, qe): <NEW_LINE> <INDENT> if not isinstance(input_illumination, Spectrum): <NEW_LINE> <INDENT> raise TypeError("input_illumination should be a subclass of Spectrum") <NEW_LINE> <DEDENT> if not isinstance(qe, Spectrum): <NEW_LINE> <INDENT> raise TypeError("qe should be an instance of Spec... | Calculate Jsc from given QE and illumination
:param input_illumination: illumination spectrum
:type input_illumination: Illumination
:param qe: QE
:type qe: Spectrum
:return: value of Jsc (A/m^2) | 625941e81f5feb6acb0c4fdf |
def sd_init(self): <NEW_LINE> <INDENT> data = {'command': 'init'} <NEW_LINE> self._post('/api/printer/sd', json=data, ret=False) | Initializes the printer's SD card, making it available for use.
This also includes an initial retrieval of the list of files currently
stored on the SD card, so after issuing files(location=sd) a retrieval
of the files on SD card will return a successful result.
If OctoPrint detects the availability of a SD card on th... | 625941e85fdd1c0f98dc06cb |
def merge(self, nums1, m, nums2, n): <NEW_LINE> <INDENT> while m > 0 and n > 0: <NEW_LINE> <INDENT> if nums1[m-1] > nums2[n-1]: <NEW_LINE> <INDENT> nums1[m+n-1] = nums1[m-1] <NEW_LINE> m -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nums1[m+n-1] = nums2[n-1] <NEW_LINE> n -= 1 <NEW_LINE> <DEDENT> <DEDENT> while n >... | :type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead. | 625941e899cbb53fe679307b |
def sample(train_sample=True): <NEW_LINE> <INDENT> if train_sample: <NEW_LINE> <INDENT> sample_idx = randint(train_samples) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sample_idx = randint(low=train_samples, high=n_samples) <NEW_LINE> <DEDENT> image_pil = Image.open("data/images/sample_{}.jpg".format(sample_idx)) <NE... | A function to get the relevant image, question, and answers for a sample from the training or validation set. | 625941e85510c4643540f86f |
def flush(self): <NEW_LINE> <INDENT> timeout = self.timeout <NEW_LINE> self.timeout = 0.1 * u.second <NEW_LINE> init_time = time.time() <NEW_LINE> while time.time() - init_time < 1.0: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.read() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDEN... | Flushes the serial input cache.
This device outputs a terminator after each output line.
The serial input cache is flushed by repeatedly reading
until a terminator is not found. | 625941e8d4950a0f3b08c7df |
def locate_error(meta_function: MetaFunction, use_color=util.system_supports_color()) -> SimpleFunction: <NEW_LINE> <INDENT> def with_location(*args, call_state, **kwargs): <NEW_LINE> <INDENT> new_e = None <NEW_LINE> try: <NEW_LINE> <INDENT> return meta_function(*args, call_state=call_state, **kwargs) <NEW_LINE> <DEDEN... | Wrap the given MetaFunction with an error handler that adds location information to any
exception raised therein.
Usage:
cmp = locate_error(a | b | c)
cmp() | 625941e867a9b606de4a834d |
def replaceSpaceByAppend(self, s): <NEW_LINE> <INDENT> string = list(s) <NEW_LINE> string_replace = [] <NEW_LINE> for c in string: <NEW_LINE> <INDENT> if c == ' ': <NEW_LINE> <INDENT> string_replace.append('%') <NEW_LINE> string_replace.append('2') <NEW_LINE> string_replace.append('0') <NEW_LINE> <DEDENT> else: <NEW_LI... | s使用append 事假复杂度为O(n),现行事假年内
| 625941e845492302aab5e75e |
def register_class_for_version_tracking(cls): <NEW_LINE> <INDENT> return cls | Transparent decorator class used for registering a class with version
monitoring.
Args:
cls: class to decorate
Returns: decorated class | 625941e826068e7796caf17c |
def test_action(): <NEW_LINE> <INDENT> assert constants.Action.stand == constants.Action(1) <NEW_LINE> assert constants.Action.walk == constants.Action(2) | Test constants.Action.
| 625941e8711fe17d825427f7 |
def _call_it(params): <NEW_LINE> <INDENT> instance, name, args = params <NEW_LINE> kwargs = {} <NEW_LINE> return getattr(instance, name)(*args, **kwargs) | indirect caller for instance methods | 625941e83346ee7daa2b3206 |
def jacobian(self, axis): <NEW_LINE> <INDENT> q_x, q_y, q_z, q_w = self <NEW_LINE> if axis == 'x': <NEW_LINE> <INDENT> return 2 * numpy.array([[0., -2*q_y, -2*q_z, 0.], [q_y, q_x, q_w, q_z], [q_z, -q_w, q_x, -q_y]]) <NEW_LINE> <DEDENT> elif axis == 'y': <NEW_LINE> <INDENT> return 2 * numpy.array([[q_y, q_x, -q_w, -q_z]... | Return jacobian matrix for positive rotation along axis | 625941e876e4537e8c351b0c |
def index_closest(val, l): <NEW_LINE> <INDENT> if isinstance(l, dict): <NEW_LINE> <INDENT> return min(list(l.items()), key=lambda x: abs(x[1] - val))[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return min(enumerate(l), key=lambda x: abs(x[1] - val))[0] | finds in a list the index of the closest existing value from a given value
Works also with dict and tuples. | 625941e830dc7b7665901df8 |
def show_highstate(queue=False, **kwargs): <NEW_LINE> <INDENT> conflict = _check_queue(queue, kwargs) <NEW_LINE> if conflict is not None: <NEW_LINE> <INDENT> return conflict <NEW_LINE> <DEDENT> pillar_override = kwargs.get('pillar') <NEW_LINE> pillar_enc = kwargs.get('pillar_enc') <NEW_LINE> if pillar_enc is None ... | Retrieve the highstate data from the salt master and display it
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_highstate | 625941e83eb6a72ae02ec980 |
def test_cut(self): <NEW_LINE> <INDENT> self.component.set_selection(1, 3) <NEW_LINE> self.component.cut() <NEW_LINE> self.assertEnamlInSync(self.component, 'value', 'a') | Remove selected text and add it to the clipboard.
| 625941e89b70327d1c4e126e |
def test(): <NEW_LINE> <INDENT> import journal <NEW_LINE> channel = journal.help(name="tests.journal.help") <NEW_LINE> channel.device = journal.trash() <NEW_LINE> channel.log("hello world!") <NEW_LINE> return | Exercise the simplest non-trivial use case | 625941e8460517430c39460f |
def add_graph(self, g): <NEW_LINE> <INDENT> return self.graph(g) | alias of graph for consistency | 625941e807d97122c4178d2d |
@pytest.fixture <NEW_LINE> def saved_backlog(backlog, path): <NEW_LINE> <INDENT> backlog.save(path=path) <NEW_LINE> return backlog, path | Get a Backlog and a path to a file where it has been saved. | 625941e80a50d4780f66732c |
def _syntax_style_changed(self): <NEW_LINE> <INDENT> if self.syntax_style: <NEW_LINE> <INDENT> self._highlighter.set_style(self.syntax_style) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._highlighter.set_style_sheet(self.style_sheet) | Set the style for the syntax highlighter.
| 625941e876e4537e8c351b0d |
def start(self): <NEW_LINE> <INDENT> if self.starttime is not None: <NEW_LINE> <INDENT> raise RuntimeError('cannot start more than once without stopping') <NEW_LINE> <DEDENT> self.starttime = self.now() | Start the timer. | 625941e8462c4b4f79d1db66 |
def convert_fits_to_fits(args=None): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Convert FITS files to HDF5 files in HDFITS format.') <NEW_LINE> parser.add_argument('-x', '--extension', dest='ext', type=str, default='fits', help='File extension of FITS files. Defaults to .fits') <NEW_LINE> parser.... | Read a FITS file into the in-memory IDI format then back out into a FITS file
An input and output directory must be specified, and all files with a matching
extension will be converted. Command line options set the compression algorithm
and other run-time settings. | 625941e8d486a94d0b98e5dd |
def validate_diff(self): <NEW_LINE> <INDENT> assert self.is_valid() <NEW_LINE> diff_file = self.cleaned_data['diff'] <NEW_LINE> parent_diff_file = self.cleaned_data.get('parent_diff') <NEW_LINE> validation_info = self.cleaned_data.get('validation_info') <NEW_LINE> check_diff_size(diff_file, parent_diff_file) <NEW_LINE>... | Validate the DiffCommit.
This will attempt to parse the given diff (and optionally parent
diff) into :py:class:`FileDiffs
<reviewboard.diffviewer.models.filediff.FileDiff>`. This will not
result in anything being committed to the database.
Returns:
tuple:
A 2-tuple containing the following:
* A list of t... | 625941e823849d37ff7b3522 |
def get_pkglist(self): <NEW_LINE> <INDENT> pkglist = [] <NEW_LINE> for collection in self.collections.all(): <NEW_LINE> <INDENT> for pkg in collection.packages.all().order_by("sum"): <NEW_LINE> <INDENT> nevra = (pkg.name, pkg.epoch, pkg.version, pkg.release, pkg.arch) <NEW_LINE> pkglist.append(nevra) <NEW_LINE> <DEDENT... | Return NEVRAs of all packages from advisory collections.
Returns:
pkglist(list): list of tuples with NEVRA info | 625941e80a50d4780f66732d |
def lengthOfLongestSubstring( s): <NEW_LINE> <INDENT> ar = [] <NEW_LINE> for i in range(0, len(s)): <NEW_LINE> <INDENT> if s[i] not in ar: <NEW_LINE> <INDENT> ar.append(s[i]) <NEW_LINE> <DEDENT> <DEDENT> return len(ar) | :type s: str
:rtype: int | 625941e8bde94217f3683283 |
def update(self): <NEW_LINE> <INDENT> updated_squares = self.game.updated_squares <NEW_LINE> while updated_squares: <NEW_LINE> <INDENT> sq = updated_squares[-1] <NEW_LINE> if sq.is_flagged: <NEW_LINE> <INDENT> self.game_canvas.create_image(self.box_size * (sq.col + 0.5), self.box_size * (sq.row + 0.5), image=self.flag_... | Updates each square's image if it is in the self.game.updated_squares list.
:return: | 625941e8925a0f43d254a312 |
def chunk(l, n): <NEW_LINE> <INDENT> return [l[pos:pos + n] for pos in range(0, len(l), n)] | Creates n-sized chunks from l.
| 625941e8851cf427c661a9a1 |
def getUserData(self): <NEW_LINE> <INDENT> item = self.item.attrib <NEW_LINE> favorite = False <NEW_LINE> try: <NEW_LINE> <INDENT> playcount = int(item['viewCount']) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> playcount = None <NEW_LINE> <DEDENT> if playcount: <NEW_LINE> <INDENT> played = True <NEW_LINE> <DEDENT> e... | Returns a dict with None if a value is missing
{
'Favorite': favorite, # False, because n/a in Plex
'PlayCount': playcount,
'Played': played, # True/False
'LastPlayedDate': lastPlayedDate,
'Resume': resume, # Resume time in seconds
'Runt... | 625941e88da39b475bd65410 |
def nsmallest(self, n=5, keep='first'): <NEW_LINE> <INDENT> return self._n_largest_or_smallest(n=n, keep=keep, largest=False) | Returns a new Series of the *n* smallest element.
| 625941e8b5575c28eb68e49b |
def __move_deadline(self, deadline, text, form): <NEW_LINE> <INDENT> feedback_set_ids = self.__get_last_feedbackset_ids_from_posted_group_ids(form) <NEW_LINE> now_without_sec_and_micro = timezone.now().replace(microsecond=0) <NEW_LINE> with transaction.atomic(): <NEW_LINE> <INDENT> group_models.FeedbackSet.objects ... | Moves the deadline of the last ``FeedbackSet`` for the selected ``AssignmentGroups``.
Args:
deadline: The new deadline.
text: comment text.
form: posted form. | 625941e84d74a7450ccd465c |
def canonise_organisation_name(org_name): <NEW_LINE> <INDENT> if not org_name: <NEW_LINE> <INDENT> return org_name <NEW_LINE> <DEDENT> canonised_name = organisation_name_mapping.get(org_name.strip()) or org_name <NEW_LINE> return canonised_name | Takes a variant on an organisation name and returns the canonical
name, which should match what is on DGU. | 625941e8f548e778e58cda16 |
def check_move(self, target, direction): <NEW_LINE> <INDENT> directions = ["left", "right", "up", "down"] <NEW_LINE> if direction not in directions: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if target == "#": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if target == "Z": <NEW_LINE> <INDENT> return Fa... | Check if desired move is valid
Args:
target - The entity that will be performing the move
direction - The direction in terms of the dungeon realm
(available directions - 'left', 'right', 'up', 'down')
Map Legend:
# - Dungeon wall
Z - Dungeon boundary | 625941e8566aa707497f49f9 |
def test_view(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('makeReports:import-slo',kwargs={"report":self.rpt.pk})+"?dp="+str(self.inDp.pk)+"&year="+str(self.rpt.year)) <NEW_LINE> self.assertEquals(response.status_code,200) <NEW_LINE> self.assertContains(response,"SLO") <NEW_LINE> self.assertContains(r... | Tests response and that expected SLO shows up from search | 625941e855399d3f05588b4e |
def _get_view_function(url, method='GET'): <NEW_LINE> <INDENT> adapter = app.url_map.bind('localhost') <NEW_LINE> try: <NEW_LINE> <INDENT> match = adapter.match(url, method=method) <NEW_LINE> <DEDENT> except RequestRedirect as e: <NEW_LINE> <INDENT> return _get_view_function(e.new_url, method) <NEW_LINE> <DEDENT> excep... | Match a url and return the view and arguments
it will be called with, or None if there is no view.
@see https://stackoverflow.com/questions/38488134/get-the-flask-view-function-that-matches-a-url | 625941e8cad5886f8bd2746f |
@outlet <NEW_LINE> def Print(log): <NEW_LINE> <INDENT> sys.stdout.write(log) <NEW_LINE> sys.stdout.flush() | Send logs directly to ``sys.stdout`` | 625941e8627d3e7fe0d692e8 |
def separation(self, position): <NEW_LINE> <INDENT> return self.center_skydir.separation(position) | Angular distance between the center of the region and the given position.
Parameters
----------
position : `astropy.coordinates.SkyCoord`
Sky coordinate we want the angular distance to.
Returns
-------
sep : `~astropy.coordinates.Angle`
The on-sky separation between the given coordinate and the region center. | 625941e85f7d997b87174f33 |
def elfheader(self, *arg): <NEW_LINE> <INDENT> (name, ) = normalize_argv(arg, 1) <NEW_LINE> if name == 'got': <NEW_LINE> <INDENT> name = '.got' <NEW_LINE> <DEDENT> result = peda.elfheader(name) <NEW_LINE> if len(result) == 0: <NEW_LINE> <INDENT> warning_msg("%s not found, did you specify the FILE to debug?" % (name if ... | Get headers information from debugged ELF file
Usage:
MYNAME [header_name] | 625941e8627d3e7fe0d692e9 |
def _purge(request): <NEW_LINE> <INDENT> i = Index(name='snippets') <NEW_LINE> i.purge() <NEW_LINE> return HttpResponse('Done') | Debug view for purging all documents from the snippets search index | 625941e830c21e258bdfa939 |
def count_queue(red, which): <NEW_LINE> <INDENT> prms = ru.queue_summary(red) <NEW_LINE> if which == 'records': <NEW_LINE> <INDENT> cnt = prms['numRecords'] <NEW_LINE> <DEDENT> elif which == 'active': <NEW_LINE> <INDENT> cnt = prms['lenActive'] <NEW_LINE> <DEDENT> elif which == 'inactive': <NEW_LINE> <INDENT> cnt = prm... | Count the number of items in the queue. | 625941e86fb2d068a760f53c |
def build_all_zone_content(fab_obj): <NEW_LINE> <INDENT> content = {'defined-configuration': dict()} <NEW_LINE> wd = content['defined-configuration'] <NEW_LINE> temp_content = build_alias_content(fab_obj) <NEW_LINE> if temp_content is not None: <NEW_LINE> <INDENT> wd.update(dict(alias=temp_content.get('defined-configur... | Builds the zonecfg structure to be converted to JSON and sent to a switch, 'brocade-zone/defined-configuration'
:param fab_obj: Fabric object
:type fab_obj: FabricObj
:return: Dict of requests
:rtype: dict | 625941e8d164cc61757831e6 |
def read_gpaw_pdos(filename, npts=50001, width=1e-3, ref='vbm'): <NEW_LINE> <INDENT> from gpaw import GPAW <NEW_LINE> calc = GPAW(filename) <NEW_LINE> if ref is None: <NEW_LINE> <INDENT> ref_energy = 0 <NEW_LINE> <DEDENT> elif ref.lower() == 'vbm': <NEW_LINE> <INDENT> ref_energy, _ = calc.get_homo_lumo() <NEW_LINE> <DE... | Read orbital-projected DOS from GPAW with minimal broadening.
This requires GPAW to be installed and on your PYTHONPATH!
Args:
filename (str): Path to GPAW calculation file. This should be a .gpw
file generated with ``calc.write('myfilename.gpw')``.
npts (int): Number of DOS samples
width (float):... | 625941e8ac7a0e7691ed455a |
def cosine_distance_matrix(df, scale_end=True, to_similar=False): <NEW_LINE> <INDENT> return _distance_matrix(cosine_distances, df, scale_end, to_similar) | 余弦距离: 与cosine_distances_xy的区别主要是,非两两distance计算,只有一个矩阵的输入,
且输入必须为pd.DataFrame or np.array or 多层迭代序列[[],[]],注意需要理解数据的测距目的来分析
是否需要进行scale_start,进行和不进行scale_start的结果将完全不一样,在功能需求及数据理解的情况下
选择是否进行scale_start
eg:
input:
tsla bidu noah sfun goog vips aapl
2014-07-25 2... | 625941e8004d5f362079a7c7 |
def test_valid_blacklisted_token_logout(self): <NEW_LINE> <INDENT> from app.main.model.database import BlacklistToken <NEW_LINE> resp_register = register_user(self) <NEW_LINE> data_register = json.loads(resp_register.data.decode()) <NEW_LINE> self.assertTrue(data_register['status'] == 'success') <NEW_LINE> self.assertT... | Test for logout after a valid token gets blacklisted | 625941e850812a4eaa59c7b4 |
def progress(ch): <NEW_LINE> <INDENT> if showProgress: <NEW_LINE> <INDENT> import sys <NEW_LINE> sys.stdout.write(ch) <NEW_LINE> sys.stdout.flush() | display characters and flush to stdout immediately | 625941e871ff763f4b549b2b |
def bwrite(stream, obj): <NEW_LINE> <INDENT> handle = None <NEW_LINE> if not hasattr(stream, "write"): <NEW_LINE> <INDENT> stream = handle = open(stream, "wb") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> stream.write(bencode(obj)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if handle: <NEW_LINE> <INDENT> handle.c... | Encode a given object to a file or stream.
| 625941e821bff66bcd684de5 |
def test_hi_examples(self): <NEW_LINE> <INDENT> hi_translator = Translator(lang="hi") <NEW_LINE> self.assertEqual(hi_translator.translate(123), "१२३") <NEW_LINE> self.assertEqual(hi_translator.translate(76.05), "६७.०५") | Hindi - Test the "hi" examples provided in the readme file
| 625941e88e7ae83300e4b465 |
def write(self, output): <NEW_LINE> <INDENT> if self._isnewline: <NEW_LINE> <INDENT> self._isnewline = False <NEW_LINE> self._write_raw(self._indent_str * self._il) <NEW_LINE> <DEDENT> self._write_raw(output) | Print the given line to output,
indenting if necessary. | 625941e815fb5d323cde0fad |
def extract_link(): <NEW_LINE> <INDENT> root = flask_request.url_root.lower() <NEW_LINE> raw_link = flask_request.url[len(root):] <NEW_LINE> link = cut_roots(raw_link, root) <NEW_LINE> link = urlparse(link).geturl() <NEW_LINE> return raw_link, link | Extract a correct URL from the URL provided | 625941e8a17c0f6771cbe4e7 |
def OrdinaryForward(SellRate,BuyRate,deliverydate,LockedRate,currentRate,Now): <NEW_LINE> <INDENT> Now = strTodate(Now,'%Y-%m-%d %H:%M:%S') <NEW_LINE> deliverydate = strTodate(deliverydate+' 16:30:00','%Y-%m-%d %H:%M:%S') <NEW_LINE> T = (deliverydate - Now).total_seconds() <NEW_LINE> T = T/1.0/60/60/24 <NEW_LINE> if T<... | 普通远期:公司在未来某个时刻(交割日)以锁定汇率卖出币种买入另一个币种
买入一单位外币的定价
CurrencySell:卖出货币
CurrencyBuy:买入货币
SellRate:卖出货币利率
BuyRate:买入货币拆借利率
deliverydate:交割日期
LockedRate:锁定汇率
currentRate:实时汇率 | 625941e8b57a9660fec33d22 |
def MoveKeyUp(self, key): <NEW_LINE> <INDENT> if (key == pygame.K_UP): <NEW_LINE> <INDENT> self.y_change =0 <NEW_LINE> <DEDENT> elif (key == pygame.K_DOWN): <NEW_LINE> <INDENT> self.y_change =0 | Responds to a key-up event and stops movement accordingly | 625941e8b7558d58953c53a2 |
def SafeGetStatistics(band, approxok, force): <NEW_LINE> <INDENT> if force is False and not HAS_GETSTATS_FORCE_BUG: <NEW_LINE> <INDENT> raise RuntimeError('it is not safe to use gada.Band.GetStatistics ' 'with the "force" parameter set to false with this ' 'version of GDAL (%s)' % gdal.VersionInfo()) <NEW_LINE> <DEDENT... | Retriewe statistics form a GDAL raster band in a safe way.
If it is not possible to get statistics (e.g. because the force
flag is set to false and statistics are not available, or because
the approxok is set and there are too many nodata elements in the
raster band) then a tuple of four None is returned.
:param appr... | 625941e894891a1f4081bf43 |
def get_package_sources(self): <NEW_LINE> <INDENT> for config in self.sources.get('local', []): <NEW_LINE> <INDENT> self.fetch_local_package(config=config) <NEW_LINE> <DEDENT> for config in self.sources.get('s3', []): <NEW_LINE> <INDENT> self.fetch_s3_package(config=config) <NEW_LINE> <DEDENT> for config in self.source... | Make remote python packages available for local use. | 625941e8d18da76e23532973 |
def to_dev(self, dev_count): <NEW_LINE> <INDENT> return SemanticVersion( self._major, self._minor, self._patch, dev_count=dev_count) | Return a development version of this semver.
:param dev_count: The number of commits since the last release. | 625941e863f4b57ef00015a3 |
def deserialize(self, value, **kwargs): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(value, six.string_types): <NEW_LINE> <INDENT> currency = value[:3] <NEW_LINE> amount = value[3:] <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> if set(va... | Deserialize the amount.
:param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50
or {"currency": "EUR", "amount": "35.50"}
:return: A paylogic Amount object.
:raises ValidationError: when amount can"t be deserialzied
:raises ValidationError: when amount has m... | 625941e88e7ae83300e4b466 |
def index_functional_areas(request): <NEW_LINE> <INDENT> query = Group.get_curated() <NEW_LINE> template = 'groups/areas.html' <NEW_LINE> return list_groups(request, template, query) | Lists all curated groups. | 625941e8be383301e01b5914 |
def saveLogs(priorsByCameras, camera_base, mode="a"): <NEW_LINE> <INDENT> with open("%s_%s.json", mode): <NEW_LINE> <INDENT> json.dump(priorsByCameras[camera_base]) | Simple logger to dump prior dictonary into json.
Args:
priorsByCameras (dict): dictionary of prior probabilities.
camera_base (str): base camera name
mode (str): "a" or "w".
Returns:
NoneType | 625941e8167d2b6e3121902c |
def test_tyrosine_instantaneous(self): <NEW_LINE> <INDENT> integrator = openmmtools.integrators.VelocityVerletIntegrator(self.timestep) <NEW_LINE> mc_titration = MonteCarloTitration(self.system, self.temperature, self.pH, self.prmtop, self.cpin_filename, integrator, debug=False, pressure=None, ncmc_steps_per_trial=0, i... | Run tyrosine in implicit solvent with an instanteneous state switch. | 625941e8aad79263cf390edf |
def _get_variable_dict_data(dict, field): <NEW_LINE> <INDENT> Var, data = dict[field], dict[field]['data'][:] <NEW_LINE> return Var, data | Return variable dictionary and data of specfied field. | 625941e85fcc89381b1e1b5a |
def test_RegionTable(self): <NEW_LINE> <INDENT> l = [Region([11, 1, 1634, 7207, -1]), Region([11, 2, 1634, 7207, 872])] <NEW_LINE> rt = RegionTable(11, l) <NEW_LINE> self.assertEqual(rt.numRegions, 2) <NEW_LINE> self.assertEqual(rt.toList(), [(11, 1, 1634, 7207, -1), (11, 2, 1634, 7207, 872)]) | Test class RegionTable. | 625941e88c3a873295158858 |
def _start_timer_reload(self, interval=1) -> None: <NEW_LINE> <INDENT> thread = threading.Thread(target=self._timer_reload) <NEW_LINE> thread.start() | Start a thread that reloads the target every `interval` seconds. | 625941e8fbf16365ca6f6665 |
def read_game_progress(): <NEW_LINE> <INDENT> level = 0 <NEW_LINE> return level | read_game_progress | 625941e8d99f1b3c44c67a1e |
def test_MCNoCollFuncStates(): <NEW_LINE> <INDENT> error = 1e-8 <NEW_LINE> N = 10 <NEW_LINE> a = destroy(N) <NEW_LINE> H = [a.dag() * a, [a.dag() * a, const_H1_coeff]] <NEW_LINE> psi0 = basis(N, 9) <NEW_LINE> c_op_list = [] <NEW_LINE> tlist = np.linspace(0, 10, 100) <NEW_LINE> mcdata = mcsolve(H, psi0, tlist, c_op_list... | Monte-carlo: Constant H (func format) with no collapse ops (states) | 625941e830c21e258bdfa93a |
def shortest_path(LB, UB, verbose=False): <NEW_LINE> <INDENT> pathlength = len(LB) <NEW_LINE> assert len(UB) == pathlength, "Upper and lower bounds must have the same length." <NEW_LINE> x0 = 0 <NEW_LINE> y0 = _startpos(LB, UB) <NEW_LINE> if isinstance(y0, tuple): <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDE... | Find an optimal path through a fence of vertical intervals. "Optimal" means
the shortest path from left to right with minimal vertical movement.
Intervals are equally spaced for simplicity, but that's not necessary
for the algorithm to work.
Arguments:
LB, UB : lower and upper bounds for the path. Must be sequences ... | 625941e84a966d76dd5514ab |
def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> if os.path.isdir(self.path): <NEW_LINE> <INDENT> raise FyleSystemError("Item {0} is a directory".format(self.path)) | Creates new File instance by given path to file
raise FileSystemError if there exists directory with the same path | 625941e8d53ae8145f87a6fe |
def vsHasField(self, name): <NEW_LINE> <INDENT> return self._vs_fields.get(name) != None | Test whether this structure contains a field with the
given name....
Example:
if x.vsHasField('woot'):
print 'STRUCT HAS WOOT FIELD!' | 625941e8796e427e537b0a62 |
def load_all(self): <NEW_LINE> <INDENT> pass | 统一加载数据,并处理一些前置数据
| 625941e8435de62698dfe0e4 |
def order_flush_new(a_row, a_session: session): <NEW_LINE> <INDENT> a_row.ShippedDate = "" <NEW_LINE> row_prt(a_row, "order_flush_new - default values supplied") | Called from module init on before_flush | 625941e85e10d32532c5f3bd |
def create_needle_cline(query_seq_path, target_seq_path, outfile_path, gapopen, gapextend): <NEW_LINE> <INDENT> needle_cline = Applications.NeedleCommandline( asequence=query_seq_path, bsequence=target_seq_path, outfile=outfile_path, gapopen=gapopen, gapextend=gapextend) <NEW_LINE> return needle_cline | Helper function that retrieves the Needle cline command.
:param query_seq_path: Path to sequence A for pairwise alignment.
:type query_seq_path: Path
:param target_seq_path: Path to sequence B for pairwise alignment.
:type target_seq_path: Path
:param outfile_path: Path to write the alignment.
:type outfile_path: Path | 625941e8293b9510aa2c3729 |
def get_webserver(server): <NEW_LINE> <INDENT> if server not in account_cache: <NEW_LINE> <INDENT> connect(server) <NEW_LINE> <DEDENT> return account_cache[server]["web_server"].lower() + ".webfaction.com" | The web server name (something like web535.webfaction.com) | 625941e8baa26c4b54cb15b3 |
def auth_add(method): <NEW_LINE> <INDENT> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.current_user: <NEW_LINE> <INDENT> if is_prived(self.userinfo.role, ROLE_CFG['add']): <NEW_LINE> <INDENT> return method(self, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> kwd = { 'info': 'No role',... | role for add. | 625941e823849d37ff7b3523 |
@register.inclusion_tag('reviews/review_form_mobile.html', takes_context=True) <NEW_LINE> def render_review_form_mobile(context, beer): <NEW_LINE> <INDENT> if context.has_key('preview'): <NEW_LINE> <INDENT> preview = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> preview = False <NEW_LINE> <DEDENT> return { 'user':... | Renders the review form for a given beer for mobile (Omits City)
{% render_review_form_mobile beer %} | 625941e87d847024c06be758 |
def nfs_service_destroy(self): <NEW_LINE> <INDENT> return self.request( "nfs-service-destroy", { }, { } ) | Delete an NFS configuration. | 625941e80c0af96317bb867f |
def nn_cost_function(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lmbd): <NEW_LINE> <INDENT> m, _ = X.shape <NEW_LINE> Y = np.zeros((m, num_labels)) <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> Y[i, y[i]-1] = 1 <NEW_LINE> <DEDENT> theta1 = nn_params[:hidden_layer_size*(input_layer_size+1)].res... | Compute J(θ) and ∂J/∂θ
:param nn_params: initial_parameters
:param input_layer_size: 400
:param hidden_layer_size: 25
:param num_labels: 10
:param X: X.shape = (5000, 400)
:param y: y.shape = (5000, )
:param lmbd:
:return: | 625941e8507cdc57c630717d |
@click.group(cls=ClickAliasedGroup) <NEW_LINE> def archive(): <NEW_LINE> <INDENT> pass | Configure package archive settings. | 625941e88e71fb1e9831dc3f |
def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets): <NEW_LINE> <INDENT> collisions = pygame.sprite.groupcollide(bullets,aliens,True,True) <NEW_LINE> if collisions: <NEW_LINE> <INDENT> for aliens in collisions.values(): <NEW_LINE> <INDENT> stats.score += ai_settings.alien_points * l... | REspond to bullet-alien collisions. | 625941e8ab23a570cc25061e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.