code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def query(self, core, query, sort="", start="", rows="", default_field="", search_fields="", return_fields="", highlight_fields="", omit_header=True): <NEW_LINE> <INDENT> params = { "q": query, "wt": "json", "df": default_field, "omitHeader": "true" if omit_header else "false", "hl.fragsize": 200 } <NEW_LINE> if sort i... | Returns the response body from Solr corresponding to the given query.
See https://lucene.apache.org/solr/guide/6_6/common-query-parameters.html
and https://lucene.apache.org/solr/guide/6_6/highlighting.html
for common query parameters and parameter formatting.
Params (See Solr docs link above for details):
core (s... | 625941eb099cdd3c635f1155 |
def array_or_list( self, prof, asarray ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if asarray == 1: <NEW_LINE> <INDENT> if isinstance( prof, N.ndarray ): <NEW_LINE> <INDENT> return self.__picklesave_array( prof ) <NEW_LINE> <DEDENT> if type( prof ) is str: <NEW_LINE> <INDENT> return list( prof ) <NEW_LINE> <DEDENT>... | Convert to array or list depending on asarray option
Beware: empty lists will be upgraded to empty Float arrays.
:param prof: profile
:type prof: list OR array
:param asarray: 1.. autodetect type, 0.. force list, 2.. force array
:type asarray: 2|1|0
:return: profile
:rtype: list OR array
:raise ProfileError: | 625941eb63f4b57ef0001607 |
def sigma(self, x, y): <NEW_LINE> <INDENT> return (((y - self(x)) ** 2).mean()) ** 0.5 | Return the RMS of the fit | 625941eb23849d37ff7b3588 |
@click.group() <NEW_LINE> def cli(): <NEW_LINE> <INDENT> pass | auto_dungeon_master
Lorem Ipsum | 625941ebbaa26c4b54cb1617 |
def test_subclass_items(self): <NEW_LINE> <INDENT> x = np.arange(5) <NEW_LINE> xcsub = ComplicatedSubArray(x) <NEW_LINE> mxcsub = masked_array(xcsub, mask=[True, False, True, False, False]) <NEW_LINE> self.assertTrue(isinstance(xcsub[1], ComplicatedSubArray)) <NEW_LINE> self.assertTrue(isinstance(xcsub[1,...], Complica... | test that getter and setter go via baseclass | 625941eb5166f23b2e1a5656 |
def get_flow_data_dict(self, wf_user_id, flow_code): <NEW_LINE> <INDENT> flowData = self.resolve_flow_data_for_user(wf_user_id, flow_code) <NEW_LINE> flowDataDict = _jsf.decode64dict(flowData.data) <NEW_LINE> logger.debug('wf.get_flow_data_dict :: __wfData: {}'.format(self.__wfData)) <NEW_LINE> if self.__wfData['data']... | Get flow data dictionary for user and flow code
@param wf_user_id: Workflow user id
@param flow_code: flowCode
@return: flow_data_dict : Dictionary | 625941eb507cdc57c63071e4 |
def test_has_vertical(self): <NEW_LINE> <INDENT> has_sequence = self._is_in_any_scenario('vertical_demo') <NEW_LINE> self.assertTrue(has_sequence) | Make sure at least one scenario contains a vertical | 625941eb7047854f462a1901 |
def response_full_d(key): <NEW_LINE> <INDENT> def wrapper(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def authorize_and_call(*args, **kwargs): <NEW_LINE> <INDENT> r = func(*args, **kwargs) <NEW_LINE> if args[0].response_full: <NEW_LINE> <INDENT> return r <NEW_LINE> <DEDENT> if type(key) is bool: <NEW_LINE> <INDE... | Wrap method of class for returning full response or only one key
:param key: key for return / bool
:return: mixed / bool | 625941eb2eb69b55b151cdb4 |
def from_cuboids(cuboids, domains): <NEW_LINE> <INDENT> cubs = simplify(cuboids) <NEW_LINE> if check(cubs, domains): <NEW_LINE> <INDENT> return Core(cubs, domains) <NEW_LINE> <DEDENT> midpoints = [] <NEW_LINE> for cuboid in cubs: <NEW_LINE> <INDENT> midpoints.append(list(map(lambda x, y: 0.5*(x + y), cuboid._p_min, cub... | Create a core from possibly non-intersecting cuboids by applying the repair mechanism. | 625941eba17c0f6771cbe54c |
def wipdo(f): <NEW_LINE> <INDENT> return attr('wipdo')(f) | decorator for nose attr. | 625941eb5510c4643540f8d4 |
def onNewAmazonCollectionEvent(self, event): <NEW_LINE> <INDENT> return AmazonKinds.SearchByKeyword(self.itsView) | Called when a NewAmazonCollection Search by Keyword Event is triggered.
@type event: BlockEvent
@param event: The BlockEvent triggered on NewAmazonCollection command
@rtype: AmazonCollection or C{None}
@return: AmazonCollection for the search keyword or C{None}
if search results == 0 | 625941eb9f2886367277ad86 |
def expandLandscapeHeightsMatrix(self, dn, dm): <NEW_LINE> <INDENT> if self.n + dn < 1 or self.n + dn > 30: return <NEW_LINE> if self.m + dm < 1 or self.m + dm > 30: return <NEW_LINE> self.n += dn <NEW_LINE> landscapeHeightsMatrix = list(islice(chain(self.landscapeHeightsMatrix, repeat([0]*self.m)), self.n)) <NEW_LINE>... | Changes landscape size for dn columns and dm rows | 625941eb85dfad0860c3b359 |
def __init__(self, method, cmd, model, inpath=None, outpath=None, _logger=None, **kwargs): <NEW_LINE> <INDENT> if self._validate('method', method, self._validate_method): <NEW_LINE> <INDENT> self.method = method <NEW_LINE> <DEDENT> if self._validate('command', cmd, self._validate_command, method=method): <NEW_LINE> <IN... | Class to handle farming out and managing distance calculations.
Args:
method (str): Name of method to use to calculate distances.
Accepted values are `RAxML`, `PhyML`, `Generic`. Additional
support for other formats might be extended later.
cmd (str): Command (if executable is on system PATH) ... | 625941eb50812a4eaa59c819 |
def land(self, pos: dict, airfields: list, landing_radius: float) -> None: <NEW_LINE> <INDENT> self.landed = True <NEW_LINE> self.update_pos(pos) <NEW_LINE> for item in airfields: <NEW_LINE> <INDENT> airfield = _to_airfield(item) <NEW_LINE> if airfield.coal_id == self.coal_id and airfield.is_in_range(landing_radius, po... | Посадка | 625941eb91f36d47f21ac9f5 |
def feed_forward(self, input_mask): <NEW_LINE> <INDENT> self.input_outputs = input_mask <NEW_LINE> self.hidden_outputs = np.dot(input_mask, self.matrix_wih) <NEW_LINE> self.hidden_outputs = self.sigmoid(self.hidden_outputs) <NEW_LINE> self.output_ouputs = np.dot(self.hidden_outputs, self.matrix_who) <NEW_LINE> self.out... | All the possible input outputs are set to 1. | 625941ebbd1bec0571d90b2c |
def info_vbmeta_image(self, args): <NEW_LINE> <INDENT> self.image_gen.info_vbmeta_image(args.tool_version, args.vendor_bundle, args.image, args.output) | Implements 'info_vbmeta_image' sub-command | 625941ebab23a570cc250684 |
def is_first_of_month(day, is_leap_year): <NEW_LINE> <INDENT> months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] <NEW_LINE> if is_leap_year: <NEW_LINE> <INDENT> months[2] += 1 <NEW_LINE> <DEDENT> total = 0 <NEW_LINE> month = 0 <NEW_LINE> while(day > total): <NEW_LINE> <INDENT> total = total + months[month] <NEW_... | Given an integer 1-366, returns whether or not
that given int is the first of the month in a given year. | 625941eb4c3428357757c822 |
def q4(self): <NEW_LINE> <INDENT> ans = sorted() <NEW_LINE> return ans | 依據使用角色數量列出名字, 提示: sort | 625941eb15fb5d323cde1014 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('This is an abstract class!') | Notify the instantiator that this class is abstract. | 625941ebaad79263cf390f46 |
def get_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None, timeout=None, **kwargs): <NEW_LINE> <INDENT> url = '{0}/setGameScore'.format(self.base_url) <NEW_LINE> data = {'user_id': user_id} <NEW_LINE> if chat_id: <NEW_LINE> <INDENT> data['chat_id'] = chat_id <NEW_LINE> <DEDENT> if me... | Use this method to get data for high score tables.
Args:
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
Returns:
list[:class:`telegram.GameHighScore`]: Scores of the sp... | 625941ebcad5886f8bd274d6 |
def expand_action(data): <NEW_LINE> <INDENT> if isinstance(data, string_types): <NEW_LINE> <INDENT> return '{"index":{}}', data <NEW_LINE> <DEDENT> data = data.copy() <NEW_LINE> op_type = data.pop('_op_type', 'index') <NEW_LINE> action = {op_type: {}} <NEW_LINE> for key in ('_index', '_parent', '_percolate', '_routing'... | From one document or action definition passed in by the user extract the
action/data lines needed for elasticsearch's
:meth:`~elasticsearch.Elasticsearch.bulk` api. | 625941eb8a349b6b435e8670 |
def count_encoding(train: pd.DataFrame, test: pd.DataFrame, col_definition: dict): <NEW_LINE> <INDENT> n_train = len(train) <NEW_LINE> train = pd.concat([train, test], sort=False).reset_index(drop=True) <NEW_LINE> for f in col_definition['encode_col']: <NEW_LINE> <INDENT> count_map = train[f].value_counts().to_dict() <... | col_definition: encode_col | 625941eba4f1c619b28b052a |
def set_status_idle(self): <NEW_LINE> <INDENT> self._status = SpiderStatus.IDLE | 改变状态为闲置
:return: None | 625941ebbe7bc26dc91cdaf4 |
def gen_kernel_matrix(self, X): <NEW_LINE> <INDENT> self.kernel_matrix = np.ones((self.num_train, self.num_train)) <NEW_LINE> for i in range(self.num_train): <NEW_LINE> <INDENT> x_i = X[i] <NEW_LINE> for j in range(i, self.num_train): <NEW_LINE> <INDENT> x_j = X[j] <NEW_LINE> self.kernel_matrix[i, j] = self.evaluate_ke... | Generate Kernel Matrix | 625941eb004d5f362079a82d |
def get_file_object(self): <NEW_LINE> <INDENT> logger.error("_FileServerItem with data file UUID '%s' does not return file objects", self.data_file.uuid) <NEW_LINE> return False | Return visualization file object appropriate for this file type.
A placeholder method to be overridden by subclasses. | 625941eb956e5f7376d71369 |
def nitems_read(self, *args, **kwargs): <NEW_LINE> <INDENT> return _blocks_swig2.add_const_cc_sptr_nitems_read(self, *args, **kwargs) | nitems_read(add_const_cc_sptr self, unsigned int which_input) -> uint64_t | 625941ebc4546d3d9de72f36 |
def _createmap_for_next_level(self, person, level, curlevel): <NEW_LINE> <INDENT> if level < curlevel: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if person not in self.markers_by_level[curlevel]: <NEW_LINE> <INDENT> self.markers_by_level[curlevel].append(person) <NEW_LINE> <DEDENT> <DEDENT>... | if maximum generation is not reached, show next level. | 625941ebd268445f265b536c |
def process_payload(filep): <NEW_LINE> <INDENT> vector = [] <NEW_LINE> for line in filep: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> if vector: <NEW_LINE> <INDENT> line = " ".join(vector) <NEW_LINE> sys.stdout.write("%s\n" % line) <NEW_LINE> sys.stdout.write("\n") <NEW_LINE> <DE... | Process payload | 625941eb56b00c62f0f14b5a |
def get_url(chart: Slice, extra_filters: Optional[Dict[str, Any]] = None) -> str: <NEW_LINE> <INDENT> with app.test_request_context(): <NEW_LINE> <INDENT> baseurl = ( "{SUPERSET_WEBSERVER_PROTOCOL}://" "{SUPERSET_WEBSERVER_ADDRESS}:" "{SUPERSET_WEBSERVER_PORT}".format(**app.config) ) <NEW_LINE> return f"{baseurl}{chart... | Return external URL for warming up a given chart/table cache. | 625941eb30c21e258bdfa9a0 |
def parse_service_id(service_id): <NEW_LINE> <INDENT> return service_id.split(':')[3:][0] | **Parse the the serviceID string**
Parses only the serviceID portion of the service ID string
:param service_id: Full device type string
:return: Parsed service ID
:rtype: str | 625941eb4a966d76dd551512 |
def shuffle(self): <NEW_LINE> <INDENT> random.shuffle(self.cards) | Shuffles the deck, using Python's random module
post: randomizes the order of cards in self | 625941ebde87d2750b860296 |
def makeDirectoryWithLog(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> except OSError as ex: <NEW_LINE> <INDENT> if ex.args[1] == "Permission denied": <NEW_LINE> <INDENT> logger.error("Could not create {0}. You don't have permission!" .format(path)) <NEW_LINE> <DEDENT> elif e... | Creates the folders (including parent folders) for a given path. This
should log if there was a success or failure. | 625941eb4e4d5625662d48ce |
def render_view(self, clear=True): <NEW_LINE> <INDENT> self.draw_colorbar() <NEW_LINE> if clear: self.axes.clear() <NEW_LINE> self.axes.pcolor(self.dc.view, cmap=mpl.cm.Dark2, edgecolors='k', linewidths=0.5, vmin=0.0, vmax=50.0) <NEW_LINE> tmp1 = self.dc.nrows <NEW_LINE> tmp2 = self.dc.ncols <NEW_LINE> self.axes.set_yl... | ARGUMENTS
clear - If true, then the axes clear method is called, else it is not called | 625941eb97e22403b379d499 |
@pytest.mark.parametrize("pre,post", role_name, ids=pytest_ids(role_name)) <NEW_LINE> def test_positive_roles_by_name(pre, post): <NEW_LINE> <INDENT> assert existence(pre, post, component) | Test all roles are existing post upgrade by their name
:id: upgrade-0ee07ffb-ae2b-4b98-ad0a-5a0db568fc1e
:expectedresults: All roles should be retained post upgrade | 625941eba17c0f6771cbe54d |
def print_result_map(self): <NEW_LINE> <INDENT> if not self._result_map: <NEW_LINE> <INDENT> _log.debug("Result map is empty.") <NEW_LINE> return <NEW_LINE> <DEDENT> print("\n" + "+" * 72) <NEW_LINE> print("{0:33} ==> {1:>33}".format("Unknown word", "Suggestion")) <NEW_LINE> print("-" * 72) <NEW_LINE> for word, suggest... | Prints a file's typos and suggestions for misspelled words in a table format. | 625941eb7b180e01f3dc4cf0 |
def parse_set_on_set(self, string): <NEW_LINE> <INDENT> command = 'set_on_set' <NEW_LINE> words = string[:-1].split(', ') <NEW_LINE> if string[-1] != '.': <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> arguments = [] <NEW_LINE> for word in words: <NEW_LINE> <INDENT> word = word.replace('on(','') <NEW_LINE> word = ... | For input of the form: on(a,B), on(B,fasd).
:param string:
:return: | 625941ec379a373c97cfb044 |
def log_histogram(self, tag, array, step): <NEW_LINE> <INDENT> self.writer.add_histogram(tag, array, step) | Log histogram of numpy array of values.
| 625941ec0a50d4780f667394 |
def GetXData(): <NEW_LINE> <INDENT> return zlib.decompress( ) | Returns the raw image data for the close button
@return: raw image data | 625941ec851cf427c661aa08 |
def shootWave(player): <NEW_LINE> <INDENT> sonicWavesFromPlayer = [sprite for sprite in c.attackGroup if sprite.firingPlayerNumber == player.playerNumber] <NEW_LINE> if len(sonicWavesFromPlayer) < 2 and player.playerState in [c.PlayerStates.MOVING, c.PlayerStates.SWINGING, c.PlayerStates.FINISHED_SWINGING]: <NEW_LINE> ... | Create a sonic wave sprite in front of the player who pressed the shoot button, assuming that player does
not already have two sonic wave sprites active.
Args:
player: The PlayerSprite object for the player who is shooting a sonic wave. | 625941ecd268445f265b536d |
def has(service_name): <NEW_LINE> <INDENT> return service_name in __galicaster_context | Checks if the service of the given service name is in the App Context.
Args:
service_name (str): the name of the service whose belonging to context is going to be checked. | 625941ec24f1403a9260105f |
def any(x, axis=None, keepdims=False): <NEW_LINE> <INDENT> if axis is not None and axis < 0: <NEW_LINE> <INDENT> axis = axis % len(x.get_shape()) <NEW_LINE> <DEDENT> x = tf.cast(x, tf.bool) <NEW_LINE> x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims) <NEW_LINE> return tf.cast(x, tf.int8) | Bitwise reduction (logical OR).
Return array of int8 (0s and 1s). | 625941ec15fb5d323cde1015 |
def get_device_internal(self, device, *arg, **kwargs): <NEW_LINE> <INDENT> result = self.get_internals(*arg, name=device, **kwargs) <NEW_LINE> return self._sand_down(result) | Get internal(s) of one device
:param device: str or list,
:param arg: str for one internal value, list for special internal values, empty for all internal values
:param kwargs: use keyword arguments from :py:meth:`Fhem.get` function
:return: str, int, float when only specific value requested else dict | 625941ec7d43ff24873a31a2 |
def format_global_vars_id(self, member): <NEW_LINE> <INDENT> msg = 'Context cannot store values as global.' <NEW_LINE> raise RuntimeError(msg) | Shapes are not allowed to store in the global namespace so raise.
| 625941ec711fe17d8254285e |
def move_top(self): <NEW_LINE> <INDENT> pass | Move camera to up | 625941ec67a9b606de4a83b4 |
def subarraysWithKDistinct(self, A: List[int], K: int) -> int: <NEW_LINE> <INDENT> def subarraysWithKDistinct_faster(): <NEW_LINE> <INDENT> counter = {} <NEW_LINE> res = i = diffNum = leftForward = 0 <NEW_LINE> for j in range(len(A)): <NEW_LINE> <INDENT> if A[j] not in counter: <NEW_LINE> <INDENT> diffNum += 1 <NEW_LIN... | p992 hard 滑动窗口
解题:子数组不同数字刚好为K个,转化为最大(或最小)为K个的问题
faster 的写法值得看看 | 625941ec1d351010ab856018 |
def _calculate(self, detectors, calibration_params, distance): <NEW_LINE> <INDENT> wks = WorkspaceFactory.Instance().create('Workspace2D', len(detectors), 3, 3) <NEW_LINE> for detector in detectors: <NEW_LINE> <INDENT> det_index = detector - detectors[0] <NEW_LINE> x_data = [] <NEW_LINE> for peak in range(3): <NEW_LINE... | Calculates resolution for given detectors.
@param detectors List of detector numbers
@param calibration_params Parameters from calibration fits
@param distance List of distances for detectors (L for backscattering, L1 for forward scattering)
@return Workspace containing resolution parameters per detector | 625941ec24f1403a92601060 |
def version_string(): <NEW_LINE> <INDENT> if not _PACKAGED_VERSION.startswith('@@'): <NEW_LINE> <INDENT> return _PACKAGED_VERSION <NEW_LINE> <DEDENT> return __VERSION__ | Extract a version string from cloud-init. | 625941ecd53ae8145f87a763 |
def fitlinewidth(data, bold=False): <NEW_LINE> <INDENT> units = 220 <NEW_LINE> for char in remove_accents(data): <NEW_LINE> <INDENT> if char in charwidths: <NEW_LINE> <INDENT> units += charwidths[char] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> units += charwidths['0'] <NEW_LINE> <DEDENT> <DEDENT> if bold: <NEW_LINE... | Try to autofit Arial 10 | 625941ec7b25080760e39954 |
def create(self, request): <NEW_LINE> <INDENT> serializer = self.serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.validated_data.get('name') <NEW_LINE> message = f'Hello {name}' <NEW_LINE> return Response({message: message}) <NEW_LINE> <DEDENT> else: <NEW_LI... | create a new hello message | 625941ec30c21e258bdfa9a1 |
def loadvars(self): <NEW_LINE> <INDENT> if path.isfile(self.uservar_file): <NEW_LINE> <INDENT> with open(self.uservar_file, 'r') as fp: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.uservar = json.load(fp) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.uservar = {} | Load user vars from json file | 625941ec097d151d1a223355 |
def add_action(self, time_step, action): <NEW_LINE> <INDENT> self.book[time_step]['action'] = action | record action to the trade book
:param time_step: index for time step
:param action: int, change in the position | 625941ecd99f1b3c44c67a83 |
def test_polymorphic_type(self): <NEW_LINE> <INDENT> belongs = BelongsTo(target_klass=self.klass, id='bar', polymorphic=True) <NEW_LINE> self.assertEqual('bar_type', belongs.polymorphic_type()) | should return #{id}_type if it is polymorphic | 625941ec5f7d997b87174f9a |
def test_ma1(self): <NEW_LINE> <INDENT> self.driver.get(self.host + "/index.html") <NEW_LINE> t1 = self.driver.find_element_by_id("question1") <NEW_LINE> btn_check = t1.find_element_by_tag_name('button') <NEW_LINE> self.assertIsNotNone(btn_check) <NEW_LINE> try: <NEW_LINE> <INDENT> btn_check.click() <NEW_LINE> <DEDENT>... | Multiple Answer: Nothing selected, Check button clicked | 625941ec67a9b606de4a83b5 |
def split_lists_out(dictionary): <NEW_LINE> <INDENT> without_lists = {} <NEW_LINE> with_lists = {} <NEW_LINE> for key, value in dictionary.items(): <NEW_LINE> <INDENT> if isinstance(value, list): <NEW_LINE> <INDENT> with_lists[key] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> without_lists[key] = value <NEW_LI... | Splits given dictionary into two, first the mappings were the value
is not a list, and the second the mappings whose values are lists. | 625941ec9c8ee82313fbbc75 |
def create_context_list(self, context, data = None): <NEW_LINE> <INDENT> raise NotImplementedError | Generates a list of context trios from a context that is a trio of
lists
For a list-type rule, we need to create a list of contexts to pass on
to the sub-rule. Often, we need to match up the entries in the
RMR lists by name or id and then apply the sub-rule to each trio of entries.
This method is responsible for creat... | 625941ec3539df3088e2e849 |
def advanced_solve_ellipse(img, center, lengths, angle, phase_width, radius, num_points=500): <NEW_LINE> <INDENT> x = np.linspace(-5,5,20) <NEW_LINE> y = np.linspace(-5, 5, 20) <NEW_LINE> pol =[[convert(img, angle=None, lengths=None, center=np.add(center[x1,y1]), phase_width=phase_width, radius=radius) for x1 in x]for ... | This is a method in development. Better at optimizing angular correlations
This method is in development. Due to the fact that an ellipse will have maximum 2-fold symmetry when the center
is correctly determined and maximum 2*n-fold symmetry when the major/ minor axes as well as the angle of rotation
is correct. This ... | 625941ec0a366e3fb873ed1d |
def add_repo_to_path(ti): <NEW_LINE> <INDENT> src_dir = ti.xcom_pull(None, key="src_dir") <NEW_LINE> sys.path.append(src_dir) | Helper function for adding the cloned repo to the python path. | 625941ec462c4b4f79d1dbcd |
def submit_mds(self, mds): <NEW_LINE> <INDENT> submitted,failed = [],[] <NEW_LINE> guids = list(mds) <NEW_LINE> total = len(guids) <NEW_LINE> count = 0 <NEW_LINE> for guid in guids: <NEW_LINE> <INDENT> count+=1 <NEW_LINE> print("\n\tPosting '{}' to metadata service".format(guid)) <NEW_LINE> mds_api = "{}/mds/metadata/{... | Submit metadata to the metadata service (MDS) API. | 625941ec442bda511e8be90f |
def add_last_trajectory(self, last_trajectory): <NEW_LINE> <INDENT> self._update_model_posterior(last_trajectory) <NEW_LINE> for observation in last_trajectory: <NEW_LINE> <INDENT> observation = observation.clone() <NEW_LINE> if observation.action.shape[-1] > self.dynamical_model.dim_action[0]: <NEW_LINE> <INDENT> obse... | Add last trajectory to learning algorithm. | 625941ec56ac1b37e62646c3 |
def J(self): <NEW_LINE> <INDENT> return _vocoder_swig.cvsd_decode_bs_J(self) | J(cvsd_decode_bs self) -> int | 625941ec7d847024c06be7be |
def test_add_smack(testapp, fill_the_db): <NEW_LINE> <INDENT> testapp.post('/login', params={'username': 'amos', 'password': 'password'}) <NEW_LINE> response = testapp.get('/add_smack', status=200) <NEW_LINE> assert len(response.html.find_all('form')) == 1 | Test that add_smack route shows form. | 625941ec32920d7e50b286d3 |
def test_preferences_post_auth(testapp): <NEW_LINE> <INDENT> preference_order = { 'preference_order': ["anger", "joy"], } <NEW_LINE> global token <NEW_LINE> testapp.authorization = ('Bearer', token) <NEW_LINE> response = testapp.post('/api/v1/preferences/', json.dumps(preference_order)) <NEW_LINE> assert response.statu... | Tests authenticated user posting new prefs
| 625941eccdde0d52a9e53535 |
@register.simple_tag(takes_context=True) <NEW_LINE> def get_permission(context, method, *args, **kwargs): <NEW_LINE> <INDENT> request = context.get('request', None) <NEW_LINE> perm_handler = request.forum_permission_handler if request else PermissionHandler() <NEW_LINE> allowed_methods = inspect.getmembers(perm_handler... | This will return a boolean indicating if the considered permission is
granted for the passed user.
Usage::
{% get_permission 'can_access_moderation_panel' request.user as var %} | 625941ec1f5feb6acb0c5047 |
def uniquePathsWithObstacles(self, obstacleGrid): <NEW_LINE> <INDENT> ans = [[0] * (len(obstacleGrid[0])+1) for _ in range(len(obstacleGrid)+1)] <NEW_LINE> ans[len(obstacleGrid)][len(obstacleGrid[0])-1] = 1 <NEW_LINE> for i in range(len(obstacleGrid)-1, -1, -1): <NEW_LINE> <INDENT> for j in range(len(obstacleGrid[0])-1... | :type obstacleGrid: List[List[int]]
:rtype: int | 625941ec50485f2cf553d29a |
def coords_float(coord, ne): <NEW_LINE> <INDENT> ddmm, s = coord.split('.', 1) <NEW_LINE> val = int(ddmm[:-2]) + int(ddmm[-2:])/60. + float('0.'+s)/60. <NEW_LINE> if ne in ('S', 'W'): <NEW_LINE> <INDENT> val *= -1 <NEW_LINE> <DEDENT> return val | Convert coordinates to DMS.
:param coord: coordinates as a string
:param ne: longitude/latitude indicator
:return: coordinate value | 625941ecb57a9660fec33d89 |
def test_transformer_base_class(self): <NEW_LINE> <INDENT> test = partial(self._base, Transformer()) <NEW_LINE> test('a = 0', 'a = 0') <NEW_LINE> test('a = b', 'a = b') <NEW_LINE> test('if t == u-1: a = b,f(c)', 'if t == u-1: a = b,f(c)') <NEW_LINE> code = 'if t == u: a,b = [1]+[2]\nreturn sum(b,a)' <NEW_LINE> a = pars... | Transformer base class | 625941ec8e05c05ec3eea877 |
def value(self): <NEW_LINE> <INDENT> value = TextBox.value(self) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return int(value) | Returns the integer value of the input | 625941ec55399d3f05588bb6 |
def test_build_q_yields_roughly_gctmpca_default(self): <NEW_LINE> <INDENT> aa_order = 'ACDEFGHIKLMNPQRSTVWY' <NEW_LINE> q = build_rate_matrix(DSO78_matrix,DSO78_freqs,aa_order=aa_order) <NEW_LINE> expected = [] <NEW_LINE> for row_aa in aa_order: <NEW_LINE> <INDENT> expected.append([default_gctmpca_aa_sub_matrix[row_aa]... | build_rate_matrix: from DSO78 data yields Yeang's default Q
| 625941ec1b99ca400220afb2 |
def _calc_shape(self): <NEW_LINE> <INDENT> sh = self.parent.shape <NEW_LINE> for ax, st in zip(sh.spatial_axes, sh.strides): <NEW_LINE> <INDENT> sh = sh.updateshape(ax, st, mode='mult') <NEW_LINE> <DEDENT> sh = sh.updateshape('b', 1) <NEW_LINE> new_strides = np.ones(len(sh.spatial_axes), np.int) <NEW_LINE> new_offsets ... | Calculate and set self.shape. | 625941ecaad79263cf390f47 |
def set_rating_method(self, item_name): <NEW_LINE> <INDENT> self.click_element(self.rating_method_kendo_dropdown_arrow_locator) <NEW_LINE> self.set_value_into_input_field(self.search_rating_method_input_field_locator, value=item_name) <NEW_LINE> self.wait_for_ajax_spinner_load() <NEW_LINE> rating_method_locator = (By.X... | Implementing set rating method functionality
:param item_name:
:return: | 625941ec925a0f43d254a37a |
def rxFifoEmpty(self): <NEW_LINE> <INDENT> return _pyupm_nrf24l01.NRF24L01_rxFifoEmpty(self) | rxFifoEmpty(NRF24L01 self) -> bool
Parameters:
self: upm::NRF24L01 * | 625941ecd164cc617578324d |
def __init__(self, db_path: str) -> None: <NEW_LINE> <INDENT> self._process = None <NEW_LINE> self._client = None <NEW_LINE> self._start_mongod(db_path) <NEW_LINE> self._connect() | Start MongoDB client and connect to db. | 625941ec30bbd722463cc2c7 |
def record_global_event(event): <NEW_LINE> <INDENT> global events <NEW_LINE> events.append("run") | Add a global event. Useful for testing function calls across pickling. | 625941ec99cbb53fe67930e3 |
def weekday_of_birth_date(date): <NEW_LINE> <INDENT> return(calendar.day_name[date.weekday()]) | Takes a date object and returns the corresponding weekday string | 625941ece5267d203edce195 |
def product_update_validator(json_data): <NEW_LINE> <INDENT> pay_load = ['name', 'inventory', 'price'] <NEW_LINE> def keycheck(expected_pay_load, give_pay_load): <NEW_LINE> <INDENT> for item in give_pay_load.keys(): <NEW_LINE> <INDENT> if item not in expected_pay_load: <NEW_LINE> <INDENT> msg = 'The field {} is not req... | Product update user input validator | 625941ecfbf16365ca6f66cd |
def game_canvas(request): <NEW_LINE> <INDENT> filename = request.get_full_path().split('/game_')[1] <NEW_LINE> context= {'js_name':filename} <NEW_LINE> return render(request, 'games/game.html', context) | finds related js file to retrieve game and provides a canvas to play game on. | 625941eca219f33f34628e60 |
def _place_dot(digits, power): <NEW_LINE> <INDENT> if power > 0: <NEW_LINE> <INDENT> out = digits + '0' * power <NEW_LINE> <DEDENT> elif power < 0: <NEW_LINE> <INDENT> power = abs(power) <NEW_LINE> precision = len(digits) <NEW_LINE> if power < precision: <NEW_LINE> <INDENT> out = digits[:-power] + '.' + digits[-power:]... | places the dot in the correct spot in the digits
if the dot is outside the range of the digits zeros will be added
ex:
_place_dot(123, 2) => 12300
_place_dot(123, -2) => 1.23
_place_dot(123, 3) => 0.123
_place_dot(123, 5) => 0.00123
created by William Rusnack
github.com/BebeSparkelSparkel
... | 625941ec44b2445a33932590 |
def set(self, symbiform): <NEW_LINE> <INDENT> if not isinstance(symbiform, TensorFieldParal): <NEW_LINE> <INDENT> raise TypeError("the argument must be a tensor field with " + "values on a parallelizable domain") <NEW_LINE> <DEDENT> if symbiform._tensor_type != (0,2): <NEW_LINE> <INDENT> raise TypeError("the argument m... | Define the metric from a field of symmetric bilinear forms.
INPUT:
- ``symbiform`` -- instance of
:class:`~sage.manifolds.differentiable.tensorfield_paral.TensorFieldParal`
representing a field of symmetric bilinear forms
EXAMPLE::
sage: M = Manifold(2, 'M')
sage: X.<x,y> = M.chart()
sage: s = M.sym... | 625941ec462c4b4f79d1dbce |
def test_sample(self) -> None: <NEW_LINE> <INDENT> for e in range(self.num_epochs): <NEW_LINE> <INDENT> batch_indices = [] <NEW_LINE> for j in self.graph_sampler: <NEW_LINE> <INDENT> batch_indices.append(j) <NEW_LINE> <DEDENT> batch = torch.stack(batch_indices) <NEW_LINE> assert batch.shape == (self.num_samples,) <NEW_... | Test drawing samples from GraphSampler. | 625941ec4e696a04525c994c |
def get_context(self, request, **kwargs): <NEW_LINE> <INDENT> context = dict( admin.admin_site.each_context(request), title='Add a CA certificate', ) <NEW_LINE> return context | Return a default context. | 625941ec3346ee7daa2b326e |
def load(name): <NEW_LINE> <INDENT> test_dir = os.path.dirname(__file__) <NEW_LINE> fn = os.path.join(test_dir,name) <NEW_LINE> return gpxpy.parse(open(fn,'r')) | Read a gpx file by name from tests directory | 625941ecf7d966606f6aa509 |
def include(self, path): <NEW_LINE> <INDENT> return os.path.join(os.sep, self.path(path)) | encrypt paths for snapshots.take_snapshot include list. | 625941ecd10714528d6001e7 |
def resolve(self, container: object) -> object: <NEW_LINE> <INDENT> raise NotImplementedError() | Resolve the target dependency
This method is called by the DI framework in order to remove the
indirection level at target construction. The only positional argument
it receives is the DI container used as source. | 625941ec3617ad0b5ed683f5 |
def disable_offloading(self, nailgun_node_id, iface, offloading=False): <NEW_LINE> <INDENT> ifaces = self.client.get_node_interfaces(nailgun_node_id) <NEW_LINE> for i in ifaces: <NEW_LINE> <INDENT> if i['name'] == iface: <NEW_LINE> <INDENT> target_iface = i <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if 'interface_pr... | Disable offloading for the corresponding interfaces
:param nailgun_node_id: int, naigun node id
:param iface: str, interface name
:param offloading: bool, enable or disable offloading | 625941ecd99f1b3c44c67a84 |
def is_valid_indexed_attestation(state: BeaconState, indexed_attestation: IndexedAttestation) -> bool: <NEW_LINE> <INDENT> indices = indexed_attestation.attesting_indices <NEW_LINE> if not len(indices) <= MAX_VALIDATORS_PER_COMMITTEE: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not indices == sorted(indices... | Check if ``indexed_attestation`` has valid indices and signature. | 625941ec046cf37aa974d241 |
def is_domain_resolvable(name, rrtype): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resolver = dns.resolver.get_default_resolver() <NEW_LINE> resolver.timeout = 2.0 <NEW_LINE> resolver.lifetime = 4.0 <NEW_LINE> answers = resolver.query(name, rrtype) <NEW_LINE> return len(answers) != 0 <NEW_LINE> <DEDENT> except Except... | Check whether the given domain has any records of the given type | 625941ecbde94217f36832eb |
def peek(self, col): <NEW_LINE> <INDENT> if col < 0 or col > 6: <NEW_LINE> <INDENT> raise errors.InvalidColumnError('Invalid column.') <NEW_LINE> <DEDENT> for y in xrange(5, -1, -1): <NEW_LINE> <INDENT> cell = self._board[col][y] <NEW_LINE> if cell != 0: <NEW_LINE> <INDENT> return cell <NEW_LINE> <DEDENT> <DEDENT> retu... | Returns the token value at the top of the given column | 625941ec287bf620b61d3f5f |
def change_gap_limit(self, value): <NEW_LINE> <INDENT> if value >= self.gap_limit: <NEW_LINE> <INDENT> self.gap_limit = value <NEW_LINE> self.storage.put('gap_limit', self.gap_limit) <NEW_LINE> return True <NEW_LINE> <DEDENT> elif value >= self.min_acceptable_gap(): <NEW_LINE> <INDENT> addresses = self.get_receiving_ad... | This method is not called in the code, it is kept for console use | 625941ec44b2445a33932591 |
def press(self, callback, button): <NEW_LINE> <INDENT> self._callback = callback <NEW_LINE> now_ms = time.time() * 1000 <NEW_LINE> if self._button != button: <NEW_LINE> <INDENT> self._reset(button) <NEW_LINE> <DEDENT> elif now_ms - self._ms_last_click > self._ms_threshold: <NEW_LINE> <INDENT> self._click_counter = 1 <N... | Process a button press. | 625941ece8904600ed9f2434 |
def get_sunspot(lag=2): <NEW_LINE> <INDENT> with open('data/sunspot.dat', 'r') as data: <NEW_LINE> <INDENT> read_data = data.read() <NEW_LINE> <DEDENT> R = read_data.split('\n') <NEW_LINE> D = list() <NEW_LINE> for element in R: <NEW_LINE> <INDENT> set = element.split(' ') <NEW_LINE> feature = list() <NEW_LINE> for e... | Import the sunspot data set.
Args:
lag (int): The dimension of the lag space matrix (default 2).
Yields:
year (ndarray): A year label for the observations (with lag).
reading (ndarray): The recorded sunspot activity (with lag).
X (ndarray): A lag space matrix of dimension: (N-d) x d.
Examples:
... | 625941ec004d5f362079a82e |
def get_image_ids_of_instance( self, instanceId ): <NEW_LINE> <INDENT> request = Request( self.ApiKey, self.secretKey ) <NEW_LINE> dic_opt = {'command':'listVirtualMachines'} <NEW_LINE> create_request = request.createURL( dic_opt ) <NEW_LINE> sign = request.generateApiSignature( create_request ) <NEW_... | Return the bootImageId of a given instanceId | 625941ec4527f215b584c950 |
def find_matches(self, points, descriptors): <NEW_LINE> <INDENT> points = np.transpose(points) <NEW_LINE> proj, _ = self.project(self.transform(points)) <NEW_LINE> proj = proj.transpose() <NEW_LINE> return self.feature.find_matches(proj, descriptors) | Match to points from world frame.
Args:
points: a list/array of points. shape: (N, 3)
descriptors: a list of feature descriptors. length: N
Returns:
List of successfully matched (queryIdx, trainIdx) pairs. | 625941ec5fc7496912cc3e7c |
def coding_problem_32(exchange_matrix): <NEW_LINE> <INDENT> pass | Suppose you are given a table of currency exchange rates, represented as a 2D array. Determine whether there is a
possible arbitrage: that is, whether there is some sequence of trades you can make, starting with some amount A of
any currency, so that you can end up with some amount greater than A of that currency.
Ther... | 625941ec99fddb7c1c9de88d |
def ultimate_out(self, files, mass): <NEW_LINE> <INDENT> self.files = files <NEW_LINE> for f in files: <NEW_LINE> <INDENT> cws = files[f] <NEW_LINE> files[f] = self.gen_extended(cws) <NEW_LINE> <DEDENT> for f in files: <NEW_LINE> <INDENT> cws = list(files[f]) <NEW_LINE> files[f] = self.gen_combined_cw(cws) <NEW_LINE> <... | Extend CWs where necessary and put in bold center words.
:return: dictionary of filenames and extended CWs
:param files: dictionary of filenames and CWs | 625941ec8a349b6b435e8671 |
def f_join(*fpaths): <NEW_LINE> <INDENT> return f_expand(os.path.join(*fpaths)) | join file paths and expand special symbols like `~` for home dir | 625941ec6e29344779a62b0f |
def setMinStep(self,status) : <NEW_LINE> <INDENT> controlPy._setMinStep(self.cppPvt,status) | Set the status.
status The status. | 625941ecec188e330fd5ac93 |
def getstate(self) -> StateType: <NEW_LINE> <INDENT> return (self._list[:], self._index) | Returns an object capturing the current internal state of the generator.
This object can be passed to setstate() to restore the state. It is a
tuple containing a list of self._LIST_SIZE integers and an
index in this list (index value being then in range(0,self._LIST_SIZE). | 625941ec66656f66f7cbc6ac |
def test_list_reverse(self): <NEW_LINE> <INDENT> self.assertEqual(reverse('authors:list'), '/authors/') | authors:list should reverse to /authors/. | 625941eca8370b7717052d9c |
def stdout_logger(name, level): <NEW_LINE> <INDENT> sth_sysout = logging.StreamHandler(sys.stdout) <NEW_LINE> return config_logger(sth_sysout, name, level) | Création d'un logger sur la sortie standard
:param name: nom du logger
:param level: niveau
:return: logger | 625941ec63b5f9789fde75e5 |
def update(self): <NEW_LINE> <INDENT> self._data.update() <NEW_LINE> if self._sensor_type == 'total_cameras': <NEW_LINE> <INDENT> self._state = len(self._data.cameras) <NEW_LINE> <DEDENT> elif self._sensor_type == 'captured_today': <NEW_LINE> <INDENT> self._state = len(self._data.captured_today) <NEW_LINE> <DEDENT> eli... | Get the latest data and updates the state. | 625941eca05bb46b383ecd1b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.