code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def cookieTree(self, root_object, default_state=None): <NEW_LINE> <INDENT> tree_pre = self.tree_pre <NEW_LINE> state_name = '%s-state' % tree_pre <NEW_LINE> set_name = '%s-setstate' % tree_pre <NEW_LINE> req = root_object.REQUEST <NEW_LINE> state = req.get(state_name) <NEW_LINE> if state: <NEW_LINE> <INDENT> setst = re... | Make a tree with state stored in a cookie. | 625941e855399d3f05588b47 |
def not_own_self(self): <NEW_LINE> <INDENT> pass | An element may not directly or indirectly own itself.
.. ocl::
not allOwnedElements()->includes(self) | 625941e86fece00bbac2dbd4 |
def generatePlaylist(server, host, authSign): <NEW_LINE> <INDENT> m3u8_playlist = '#EXTM3U\n' <NEW_LINE> for channel in sorted(channelDictionary, key=lambda channel: int(channel)): <NEW_LINE> <INDENT> m3u8_playlist += ('#EXTINF:-1, ' + channel + ' ' + channelDictionary[channel] + '\n' + 'https://' + server + '.smoothst... | build string of channels in m3u8 format based on
global channelDictionary | 625941e81f5feb6acb0c4fda |
def condense(self, cutoff): <NEW_LINE> <INDENT> if cutoff <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.condense_points(cutoff) <NEW_LINE> while self._condense_pointWithLine_step(cutoff): <NEW_LINE> <INDENT> self.condense_points(cutoff) | Condenses points that are within the cutoff of another point or edge (=line segment)
into a new point. This function modifies this Projection2D object.
The contraction of two points works like documented in
`self.condense_points(self, cutoff)`.
If a node is close to a line segment, a new point is generated between
thi... | 625941e86aa9bd52df037237 |
def test_construct_by_badname_raises(self): <NEW_LINE> <INDENT> samples = [ "spam", "eggs", "15c", "0s", "7q", "99", "c", "5", "" ] <NEW_LINE> for badname in samples: <NEW_LINE> <INDENT> self.assertRaises(ValueError, Card, name=badname) | Test that a card initialized by an invalid name raises
a ValueError exception. | 625941e8d4950a0f3b08c7d9 |
def test(self, dataloader, ss = None): <NEW_LINE> <INDENT> self._net.train(False) <NEW_LINE> num_correct = 0 <NEW_LINE> num_total = 0 <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> for X, y in dataloader: <NEW_LINE> <INDENT> X = X.cuda() <NEW_LINE> y = y.cuda() <NEW_LINE> if ss == 'rot': <NEW_LINE> <INDENT> y_pri... | Compute the test accuracy
Argument:
dataloader Test dataloader
Return:
Test accuracy in percentage | 625941e8283ffb24f3c55d8d |
@login_required <NEW_LINE> def delete(request, id): <NEW_LINE> <INDENT> post_of_interest = get_object_or_404(post, pk=id) <NEW_LINE> if post_of_interest.user_id == request.user: <NEW_LINE> <INDENT> page_type = post_of_interest.page_type <NEW_LINE> post_of_interest.delete() <NEW_LINE> set_page_type_cache(page_type) <NEW... | Deletes a post, returns user to current page | 625941e8a8ecb033257d355c |
def get_cluster_names(self, env): <NEW_LINE> <INDENT> return [self.get_cluster_name(env_name) for env_name in self.envs_from_string(env)] | Returns cluster names for specified environment (* for all environments).
:param env: str environment name or wildcard (* for all environments)
:return: str[] list of cluster names | 625941e8ad47b63b2c50a40f |
@view_config( route_name="groups", renderer="json", request_method="DELETE", permission="root_administration", ) <NEW_LINE> def groups_DELETE(request): <NEW_LINE> <INDENT> msg = _("You cannot remove administrator group from the system") <NEW_LINE> group = GroupService.by_id(request.matchdict.get("group_id")) <NEW_LINE>... | Removes a groups permanently from db | 625941e867a9b606de4a8347 |
def addOption(self, option): <NEW_LINE> <INDENT> self._options.append(option) | Add single option | 625941e8097d151d1a2232e7 |
def test_testing_config(): <NEW_LINE> <INDENT> app = create_app('testing') <NEW_LINE> assert app.config['TESTING'] is True | Development config. | 625941e815baa723493c4409 |
def brackets(self, expr): <NEW_LINE> <INDENT> return r"{{{0}}}".format(expr) | Enclose expr in {...} | 625941e87c178a314d6ef8f7 |
def partial_Id_Obs(Nx, obs_inds): <NEW_LINE> <INDENT> Ny = len(obs_inds) <NEW_LINE> H = direct_obs_matrix(Nx, obs_inds) <NEW_LINE> @name_func(f"Direct obs. at {obs_inds}") <NEW_LINE> @ens_compatible <NEW_LINE> def model(x, t): return x[obs_inds] <NEW_LINE> @name_func(f"Constant matrix\n{H}") <NEW_LINE> def linear(x, t)... | Specify identity observations of a subset of obs. indices.
It is not a function of time.
Parameters
----------
Nx: int
Length of state vector
obs_inds: ndarray
The observed indices.
Returns
-------
Obs: dict
Observation operator including size of the observation space,
observation operator/model and ... | 625941e8377c676e91272637 |
def get_whole_packet(open_sock, amount_of_data=81852): <NEW_LINE> <INDENT> data = ''.encode('utf-8') <NEW_LINE> while True: <NEW_LINE> <INDENT> data += open_sock.recv(amount_of_data) <NEW_LINE> split = data.split(SOCKET_DEL) <NEW_LINE> if len(split) != 2: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Gets the entire packet by checking if the string delimiter is in the bytestream
:param open_sock: the socket you are receiving the packet from
:type open_sock: socket
:param amount_of_data: the max amount of data to receive
:type amount_of_data: int | 625941e826068e7796caf176 |
def _handler_root_file(self, *args, **kwargs): <NEW_LINE> <INDENT> next_state = None <NEW_LINE> result = [] <NEW_LINE> return next_state, (next_state, result) | Handle a file menu command event from root menu.
| 625941e84e696a04525c98de |
def test_start_existing(self, subscription_factory, mocker): <NEW_LINE> <INDENT> subscription = subscription_factory.build() <NEW_LINE> mocked = mocker.patch("squarelet.organizations.models.Organization.customer") <NEW_LINE> mocker.patch("squarelet.organizations.models.Subscription.stripe_subscription") <NEW_LINE> subs... | If there is an existing subscription, do not start another one | 625941e8cc0a2c11143dd322 |
def __init__(self, filename, gssp_exe=None, abund_tab=None, models_dir=None): <NEW_LINE> <INDENT> if gssp_exe is None: <NEW_LINE> <INDENT> gssp_exe = GSSP_EXE <NEW_LINE> <DEDENT> if abund_tab is None: <NEW_LINE> <INDENT> abund_tab = GSSP_ABUNDANCE_TABLES <NEW_LINE> <DEDENT> if models_dir is None: <NEW_LINE> <INDENT> mo... | A python wrapper to the GSSP code (must already be installed)
Parameters:
===========
filename: string
The filename of the (flattened) fits spectrum to fit.
gssp_exe: string (optional)
The full path to the gssp executable file
abund_tab: string (optional)
... | 625941e891f36d47f21ac988 |
def getFacts(self): <NEW_LINE> <INDENT> return self.facts | returns the facts in the data | 625941e8d268445f265b52ff |
def on_event(self, evt, is_final): <NEW_LINE> <INDENT> response = self.response <NEW_LINE> for msg in XmlHelper.message_iter(evt): <NEW_LINE> <INDENT> bars = msg.GetElement('barData').GetElement('barTickData') <NEW_LINE> for i in range(bars.NumValues): <NEW_LINE> <INDENT> bar = bars.GetValue(i) <NEW_LINE> ts = bar.GetE... | this is invoked from in response to COM PumpWaitingMessages - different thread | 625941e81f037a2d8b94668d |
def install(packages, repos=None, yes=None, options=None): <NEW_LINE> <INDENT> manager = MANAGER <NEW_LINE> if options is None: <NEW_LINE> <INDENT> options = [] <NEW_LINE> <DEDENT> elif isinstance(options, str): <NEW_LINE> <INDENT> options = [options] <NEW_LINE> <DEDENT> if not isinstance(packages, basestring): <NEW_LI... | Install one or more RPM packages.
Extra *repos* may be passed to ``yum`` to enable extra repositories at install time.
Extra *yes* may be passed to ``yum`` to validate license if necessary.
Extra *options* may be passed to ``yum`` if necessary
(e.g. ``['--nogpgcheck', '--exclude=package']``).
::
import fabtool... | 625941e85fdd1c0f98dc06c6 |
def dice_loss(data_format="channels_first"): <NEW_LINE> <INDENT> def loss(target, pred): <NEW_LINE> <INDENT> if data_format == "channels_last": <NEW_LINE> <INDENT> pred = tf.transpose(pred, (0, 3, 1, 2)) <NEW_LINE> target = tf.transpose(target, (0, 3, 1, 2)) <NEW_LINE> <DEDENT> smooth = 1.0 <NEW_LINE> iflat = tf.reshap... | dice loss function for tensorflow/keras
calculate dice loss per batch and channel of each sample.
Args:
data_format: either channels_first or channels_last
Returns:
loss_function(y_true, y_pred) | 625941e8adb09d7d5db6cc1d |
def test_get_variation__ignore_user_profile_when_specified(self): <NEW_LINE> <INDENT> user = optimizely_user_context.OptimizelyUserContext(optimizely_client=None, logger=None, user_id="test_user", user_attributes={}) <NEW_LINE> experiment = self.project_config.get_experiment_from_key("test_experiment") <NEW_LINE> with ... | Test that we ignore the user profile service if specified. | 625941e8c4546d3d9de72ec9 |
def main(indicator): <NEW_LINE> <INDENT> coindata.cache(indicator) <NEW_LINE> data = coindata.get(indicator) <NEW_LINE> coindata.utils.dump_json(data, indicator + '.json') | Write indicator as indicator.json | 625941e83539df3088e2e7dc |
def run(self, ansatz, hamiltonian, initial_params, shots = 10000, eng = None): <NEW_LINE> <INDENT> types = [QubitOperator, list, int] <NEW_LINE> args = [hamiltonian, initial_params, shots] <NEW_LINE> argstr = ['hamiltonian', 'initial_params', 'shots'] <NEW_LINE> for Type, arg in zip(types, args): <NEW_LINE> <INDENT> if... | Main function. Applies the VQE algorithm with the given parameters and arguments
using the minimizing function set up in self.__init__(). Finds the parameters
that create the best ansatz state with lowest possible expectation value for the
Hamiltonian.
Parameters:
:ansatz: (function: params, engine -> qureg) func... | 625941e8d6c5a102081444df |
def extract_timedistance(self, response): <NEW_LINE> <INDENT> summary = response.json()["route_summary"] <NEW_LINE> return round(summary["total_time"]), summary["total_distance"] | Extract value from json. | 625941e856ac1b37e6264657 |
def extend_python_path(environ, additional_paths): <NEW_LINE> <INDENT> python_path = environ["PYTHONPATH"].split(os.pathsep) if "PYTHONPATH" in environ else [] <NEW_LINE> python_path.extend(additional_paths) <NEW_LINE> environ["PYTHONPATH"] = os.pathsep.join(sorted(set(python_path), key=python_path.index)) | Create or extend a PYTHONPATH variable with the frozen environment we are bootstrapping with. | 625941e8cc0a2c11143dd323 |
def _get_presence(role_id, place_id): <NEW_LINE> <INDENT> profile = _get_my_profile() <NEW_LINE> role = _get_role(role_id) <NEW_LINE> if role is None: <NEW_LINE> <INDENT> raise ActionException('role not found') <NEW_LINE> <DEDENT> place = _get_place(place_id) <NEW_LINE> if place is None: <NEW_LINE> <INDENT> raise Actio... | true if a Role is in a Place | 625941e815baa723493c440a |
def fail_json(self, **kwargs): <NEW_LINE> <INDENT> self.add_path_info(kwargs) <NEW_LINE> assert 'msg' in kwargs, "implementation error -- msg to explain the error is required" <NEW_LINE> kwargs['failed'] = True <NEW_LINE> self.do_cleanup_files() <NEW_LINE> do_finish(False, kwargs) | return from the module, with an error message | 625941e8b5575c28eb68e495 |
def transform(self, X): <NEW_LINE> <INDENT> Xp = list(X) <NEW_LINE> Xfit = np.zeros((len(Xp), len(self.diagrams_))) <NEW_LINE> if len(self.diagrams_) == len(Xp) and np.all([np.array_equal(self.diagrams_[i], Xp[i]) for i in range(len(Xp))]): <NEW_LINE> <INDENT> if self.kernel_approx is not None: <NEW_LINE> <INDENT> Xfit... | Compute all persistence weighted Gaussian kernel values between the persistence diagrams that were stored after calling the fit() method, and a given list of (possibly different) persistence diagrams.
Parameters:
X (list of n x 2 numpy arrays): input persistence diagrams.
Returns:
Xfit (numpy array of shape (... | 625941e84d74a7450ccd4656 |
def subcall_return_success_handler(syscall_id, syscall_object, pid): <NEW_LINE> <INDENT> logging.debug('Entering subcall return success handler') <NEW_LINE> if syscall_object.ret[0] == -1: <NEW_LINE> <INDENT> logging.debug('Handling unsuccessful call') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.debug('Handli... | This probably should be here. This badly named handler simply takes a
socket subcall situation, validates the file descriptor involved, no-ops
the call, and applies the return conditions from the system call object.
For several socket calls, this is all that's required so we don't need to
write individual handlers tha... | 625941e8a4f1c619b28b04bf |
def credit(self, money_raised: str): <NEW_LINE> <INDENT> raise_money_decimal = decimal.Decimal(money_raised) <NEW_LINE> if not (raise_money_decimal > 0): <NEW_LINE> <INDENT> raise AssertionError("Incorrect credit value") <NEW_LINE> <DEDENT> Wallet.objects.filter(name=self.name).update(money=F("money") + raise_money_dec... | Increase money in wallet by given amount
:param money_raised: "str"
:return: "OK" | 625941e8be7bc26dc91cda88 |
def _get_adjusted_bar(x, bar_width, series_index, num_plots): <NEW_LINE> <INDENT> adjust = (-0.5 * num_plots - 1 + series_index) * bar_width <NEW_LINE> return [x_val + adjust for x_val in x] | Adjust the list 'x' to take the multiple series into account. Each series
should be shifted such that the middle series lies at the appropriate x-axis
tick with the other bars around it. For example, if we had four series
(i.e. four bars per x value), we want to shift the left edges of the bars as
such:
Bar 1: -2 * wi... | 625941e8de87d2750b860228 |
def tell(self, obs_key, obs_val): <NEW_LINE> <INDENT> if obs_key is None or obs_key == '': <NEW_LINE> <INDENT> self.logger.error("%s: state key passed is empty.", self.service_name) <NEW_LINE> raise ValueError("%s: state key passed is empty." % self.service_name) <NEW_LINE> <DEDENT> ack_val = self._net_client.client_se... | Tell (update) the environment with given observation K/V.
Observations are provided to the environment, and is used to produce evidence. | 625941e8ff9c53063f47c682 |
def test_handleMissingMapTitle(self): <NEW_LINE> <INDENT> myLayer, _ = load_layer('population_padang_1.asc') <NEW_LINE> myMap = Map(IFACE) <NEW_LINE> myMap.setImpactLayer(myLayer) <NEW_LINE> myTitle = myMap.getMapTitle() <NEW_LINE> myExpectedTitle = None <NEW_LINE> myMessage = 'Expected: %s\nGot:\n %s' % (myExpectedTit... | Missing map title from the keywords fails gracefully | 625941e816aa5153ce362909 |
def destination(self): <NEW_LINE> <INDENT> return self._metadata['destination'] | Return destination file path (pointer to file
to be replaced). | 625941e85f7d997b87174f2d |
def roll_init(character): <NEW_LINE> <INDENT> return randint(1, 1000) | Rolls a number between 1-1000 to determine initiative.
Args:
character (obj): The character to determine initiative for
Returns:
initiative (int): The character's place in initiative - higher
numbers go first.
Notes:
By default, does not reference the character and simply returns
a random integer... | 625941e8a8370b7717052d2e |
def test_invalid_type(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, _csdl2test.texture_get_format, 42) | Raises TypeError on invalid type | 625941e80a366e3fb873ecaf |
def predict(self,x): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for model_name in self.listModelName: <NEW_LINE> <INDENT> sub_model_res = [] <NEW_LINE> for sub_model in self.train_model[model_name]: <NEW_LINE> <INDENT> sub_model_res.append(pd.DataFrame(sub_model.predict(x))) <NEW_LINE> <DEDENT> sub_model_res = pd.concat(s... | 预测: | 625941e8ac7a0e7691ed4554 |
def dump(data, fp, charset='utf-8', errors='strict'): <NEW_LINE> <INDENT> fp.write(dumps(data, charset, errors)) | Write a PHP-serialized representation of obj to the open file object
`fp`. Unicode strings are encoded to `charset` with the error handling
of `errors`.
`fp` must have a `write()` method that accepts a single string argument.
It can thus be a file object opened for writing, a `StringIO` object, or
any other custom ob... | 625941e871ff763f4b549b25 |
def Change(self, newstr): <NEW_LINE> <INDENT> self.teststr = newstr | Shanges teststr to new value
Args:
newstr = string | 625941e873bcbd0ca4b2c506 |
def about(self): <NEW_LINE> <INDENT> txt = "This plugin allows fetching of remote data from\n"+ "multiple sources of public data using the pandas\n"+ "datareader. See https://pandas-datareader.readthedocs.io\n"+ "version: %s" %self.version <NEW_LINE> return txt | About this plugin | 625941e84c3428357757c7b6 |
def update_properties(self, **kwds): <NEW_LINE> <INDENT> if hasattr(self, 'properties'): <NEW_LINE> <INDENT> for key, value in list(self.properties.items()): <NEW_LINE> <INDENT> if "Event #" in key: continue <NEW_LINE> if isinstance(value, str): <NEW_LINE> <INDENT> self.event_lines[self.property_lines[key]] = "\t%s = %... | Update properties (required if self.properties assignment changed!) | 625941e8b545ff76a89142a6 |
def test_create_service_enabled_str_true(self): <NEW_LINE> <INDENT> ref = self.new_service_ref() <NEW_LINE> ref['enabled'] = 'True' <NEW_LINE> self.post('/services', body={'service': ref}, expected_status=400) | Call ``POST /services``. | 625941e8dd821e528d63b636 |
def UpdateLineBuffCfg(self): <NEW_LINE> <INDENT> util.Log("[Launch][info] LineBuffer config updated") <NEW_LINE> val = self._bufftxt.GetValue() <NEW_LINE> if self._bufftxt.IsInBounds(val): <NEW_LINE> <INDENT> cfg = Profile_Get(handlers.CONFIG_KEY, default=dict()) <NEW_LINE> cval = cfg.get('linebuffer', DEFAULT_LINEBUFF... | Update the line buffer configuration | 625941e85e10d32532c5f3b6 |
def __int__(self): <NEW_LINE> <INDENT> return int() | int KDialog.CaptionFlags.__int__() | 625941e8e64d504609d74cd1 |
def MFCC(windowed_frame, sampling_rate): <NEW_LINE> <INDENT> spectrum = np.fft.fft(windowed_frame) <NEW_LINE> power_spectrum = np.square(np.abs(spectrum))/len(spectrum) <NEW_LINE> triangle_filters = get_filter_bank(sampling_rate, len(spectrum)) <NEW_LINE> S = triangle_filters.dot(power_spectrum) <NEW_LINE> S = np.where... | Calculates the MFCC vector of single frame
:param windowed_frame: windowed frame of audio input
:return: MFCC vector | 625941e8eab8aa0e5d26dfeb |
def extract_floor_size(overview_details): <NEW_LINE> <INDENT> for od in overview_details: <NEW_LINE> <INDENT> overview_item_key = unicode(od[0].text.lower()) <NEW_LINE> if (overview_item_key == conf.FLOOR_SIZE_OVERVIEW_ITEM): <NEW_LINE> <INDENT> floor_size = od[1].text.strip().split(' ')[0] <NEW_LINE> return floor_size | Get the floor size from the list of overview items | 625941e88e05c05ec3eea80a |
@register.tag <NEW_LINE> def breadcrumb_url_widget(parser, token): <NEW_LINE> <INDENT> bits = token.split_contents() <NEW_LINE> if len(bits)==2: <NEW_LINE> <INDENT> return breadcrumb_widget(parser, token) <NEW_LINE> <DEDENT> title = bits.pop(1) <NEW_LINE> token.contents = ' '.join(bits) <NEW_LINE> url_node = url(parser... | Same as breadcrumb
but instead of url context variable takes in all the
arguments URL tag takes.
Examples:
{% breadcrumb "Title of breadcrumb" person_detail person.id %}
{% breadcrumb person.name person_detail person.id %} | 625941e82c8b7c6e89b35c4e |
def msg(self, channel, data = ' '): <NEW_LINE> <INDENT> self.raw('PRIVMSG %s :%s\r\n' % (channel, data)) | Send a message, data, to channel
Example: self.msg('#bbot', 'Hello world!') | 625941e863f4b57ef000159d |
def resolve_conflicts(self): <NEW_LINE> <INDENT> neighbours = self.nodes <NEW_LINE> new_chain = None <NEW_LINE> max_length = len(self.chain) <NEW_LINE> for node in neighbours: <NEW_LINE> <INDENT> response = requests.get('http://{0}/chain'.format(node)) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> leng... | consensus algorithm, resolves conflicts by replacing
local chain with longest chain | 625941e815fb5d323cde0fa7 |
def mergecent(x_1,var_1,cnt_1,x_2,var_2,cnt_2): <NEW_LINE> <INDENT> cnt_r = cnt_1+cnt_2; <NEW_LINE> x_r = [0.0]*len(x_1) <NEW_LINE> var_r = [0.0]*len(x_1) <NEW_LINE> for i in xrange(len(x_1)): <NEW_LINE> <INDENT> x_r[i] = (cnt_1*x_1[i] + cnt_2*x_2[i] ) / float(cnt_r) <NEW_LINE> var_r[i] += cnt_1*( (x_r[i]-x_1[i])**2 +... | this is our old friend, weighted mean and variance combiner | 625941e88e7ae83300e4b460 |
def change_status(self, status) -> None: <NEW_LINE> <INDENT> assert isinstance(status, str) <NEW_LINE> self._status = status <NEW_LINE> self._status_timer = self.STATUS_TIMEOUT | Changes the status message displayed in the footer.
:param status the status message to display | 625941e8cb5e8a47e48b7f35 |
def in_corner(size, radius, x, y, base_offset=0): <NEW_LINE> <INDENT> x -= base_offset <NEW_LINE> y -= base_offset <NEW_LINE> center = (0, 0) <NEW_LINE> if x < radius and y < radius: <NEW_LINE> <INDENT> center = (radius, radius) <NEW_LINE> <DEDENT> elif x < radius and y > size - radius: <NEW_LINE> <INDENT> center = (ra... | judge whether a point is corner of icon | 625941e8460517430c39460a |
def client_factory(): <NEW_LINE> <INDENT> logger.debug("Creating client for: %s", threading.current_thread()) <NEW_LINE> client = ModbusTcpClient(MODBUS_IP, port=MODBUS_PORT) <NEW_LINE> client.connect() <NEW_LINE> return client | Creates an instance of the Modbus client. | 625941e829b78933be1e5b38 |
def validate_base(self): <NEW_LINE> <INDENT> if 'base' in self.raw_config: <NEW_LINE> <INDENT> base = self.raw_config['base'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base = os.path.dirname(self.source_file) <NEW_LINE> <DEDENT> with self.catch_validation_error('base'): <NEW_LINE> <INDENT> base_path = os.path.dirna... | Validates that path is a valid directory. | 625941e8b830903b967e9d97 |
def move (self, direction): <NEW_LINE> <INDENT> if direction == SLIDE_UP and self.cury < 1: <NEW_LINE> <INDENT> self.cury += 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> elif direction == SLIDE_DOWN and self.cury > 0: <NEW_LINE> <INDENT> self.cury -= 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> elif direction == SLIDE_... | Moving direction is actually the opposite of what is passed.
We are moving the hole position, so if you slice a piece down into the hole,
that hole is actually moving up. | 625941e823e79379d52ee9ef |
def add_all_elements(self) -> None: <NEW_LINE> <INDENT> self.add_all_software_systems() <NEW_LINE> self.add_all_people() | Add all software systems and all people to this view. | 625941e8a8370b7717052d2f |
def get_triangles_slice(self, slice_number=0): <NEW_LINE> <INDENT> if self._number_of_split_slices == 1: <NEW_LINE> <INDENT> return self.triangles.load() <NEW_LINE> <DEDENT> slice_number = int(slice_number) <NEW_LINE> start_idx, end_idx = self._get_slice_triangle_boundaries(slice_number) <NEW_LINE> return self.triangle... | Read split-triangles slice, to be used by WebGL visualizer. | 625941e87cff6e4e81117e17 |
def stop(self): <NEW_LINE> <INDENT> if self.spotify and self.spotify.is_playing(): <NEW_LINE> <INDENT> dev = self.get_default_device() <NEW_LINE> self.dev_id = dev['id'] <NEW_LINE> if self.dev_id: <NEW_LINE> <INDENT> self.pause(None) <NEW_LINE> self.dev_id = None <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> self... | Stop playback. | 625941e85fcc89381b1e1b54 |
def db_for_read(self, model, **hints): <NEW_LINE> <INDENT> if model._meta.app_label == 'digitalization': <NEW_LINE> <INDENT> return 'pluss' <NEW_LINE> <DEDENT> return 'default' | Point all operations on pluss models to 'plussdb' | 625941e83c8af77a43ae3c37 |
def remove_node(self, node): <NEW_LINE> <INDENT> self._nodes.remove(node) <NEW_LINE> try: <NEW_LINE> <INDENT> del self._edges[node] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for key in self.nodes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._edges[key].remove(node) <NEW_LIN... | remove a node from the graph.
raise a KeyError if the node doesn't exist in the graph. | 625941e83346ee7daa2b3201 |
def fixed_length_record_reader(record_bytes, header_bytes=0, footer_bytes=0, hop_bytes=0, container="", shared_name="", name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> record_bytes = _execute.make_int(record_bytes, "record_byte... | A Reader that outputs fixed-length records from a file.
Args:
record_bytes: An `int`. Number of bytes in the record.
header_bytes: An optional `int`. Defaults to `0`.
Number of bytes in the header, defaults to 0.
footer_bytes: An optional `int`. Defaults to `0`.
Number of bytes in the footer, defaults to... | 625941e83eb6a72ae02ec97b |
def _maybe_refresh_metadata(self): <NEW_LINE> <INDENT> ttl = self.cluster.ttl() <NEW_LINE> wait_for_in_progress_ms = self.config['request_timeout_ms'] if self._metadata_refresh_in_progress else 0 <NEW_LINE> metadata_timeout = max(ttl, wait_for_in_progress_ms) <NEW_LINE> if metadata_timeout > 0: <NEW_LINE> <INDENT> retu... | Send a metadata request if needed.
Returns:
int: milliseconds until next refresh | 625941e8004d5f362079a7c2 |
def test_aws_policy_exact_adjustment(self): <NEW_LINE> <INDENT> mock_client = MagicMock() <NEW_LINE> mock_client.describe_policies.return_value = { "ScalingPolicies": [ { "PolicyType": "SimpleScaling", "PolicyName": "Change nothing", "AdjustmentType": "ExactCapacity", "ScalingAdjustment": 1 } ] } <NEW_LINE> mock_group ... | Test that AWS Policy fails safely if its tries to exactly adjust to the current size | 625941e8287bf620b61d3ef2 |
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> shamt = 0 <NEW_LINE> leng = len(nums) <NEW_LINE> i = 0 <NEW_LINE> while i < leng - shamt: <NEW_LINE> <INDENT> j = 1 <NEW_LINE> stdrd = nums[i+shamt] <NEW_LINE> try: <NEW_LINE> <INDENT> while nums[i+shamt+j] == stdrd: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> <DEDENT> <D... | :type nums: List[int]
:rtype: int | 625941e8d6c5a102081444e0 |
def batchify(data, bsz, device): <NEW_LINE> <INDENT> nbatch = data.size(0) // bsz <NEW_LINE> data = data.narrow(0, 0, nbatch * bsz) <NEW_LINE> data = data.view(bsz, -1).t().contiguous() <NEW_LINE> return data.to(device) | Starting from sequential data, batchify arranges the dataset into columns.
For instance, with the alphabet as the sequence and batch size 4, we'd get
┌ a g m s ┐
│ b h n t │
│ c i o u │
│ d j p v │
│ e k q w │
└ f l r x ┘.
These columns are treated as independent by the model, which means that the
dependence of e. g. '... | 625941e8e8904600ed9f23c6 |
def test_enqueue_multipart_download_stream(self): <NEW_LINE> <INDENT> s3handler = S3StreamHandler( self.session, self.params, runtime_config=runtime_config(multipart_threshold=5)) <NEW_LINE> s3handler.executor = mock.Mock() <NEW_LINE> fileinfo = FileInfo('filename', operation_name='download', is_stream=True) <NEW_LINE>... | This test ensures the right calls are made in ``_enqueue_tasks()``
if the file should be a multipart download. | 625941e8d10714528d60017a |
def sub(): <NEW_LINE> <INDENT> translated = SP_MINUS_ONE + "A=M" + LINE_BREAK + "D=M" + LINE_BREAK + "A=A-1" + LINE_BREAK + "M=M-D" + LINE_BREAK <NEW_LINE> return translated | SP--
D = *SP
A = *SP--
D = M - D
*SP = D
:return: line in asm code | 625941e8a934411ee3751b26 |
def test_gitlog_courseteam_access(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.mkdir(getattr(settings, 'GIT_REPO_DIR')) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._setstaff_login() <NEW_LINE> self._add_edx4edx() <NEW_LINE> self.user.is_staff = False <NEW_LINE> self.u... | Ensure course team users are allowed to access only their own course. | 625941e84a966d76dd5514a5 |
def get_security_groups(): <NEW_LINE> <INDENT> data = securitygroup.get_security_groups() <NEW_LINE> security_groups = data.get("SecurityGroups") <NEW_LINE> return security_groups | Get data about security groups. | 625941e87d43ff24873a3135 |
@app.route('/clean', method=['OPTIONS', 'POST'], name="clean") <NEW_LINE> def clean(): <NEW_LINE> <INDENT> params = json.loads(request.body.read()) <NEW_LINE> structure = params['structure'] <NEW_LINE> dim = params.get('dim', 2) <NEW_LINE> cgen = params.get('cgen', False) <NEW_LINE> response.content_type = 'text/plain'... | Implements Marvin 4 js clean2D/3D web service. Recomputes 2D/3D coordinates of given compound. The compound is in
Marvin's *.mrv format. Dim is an optional parameter specifying if 2D or 3D coordinates should be computed
| 625941e8c432627299f050db |
def convert_to_f(temp_c): <NEW_LINE> <INDENT> return temp_c * 9.0 / 5.0 + 32.0 | Convert Celcius to Fahrenheit | 625941e8f7d966606f6aa49b |
def get_device_virtual_cpu_price(device): <NEW_LINE> <INDENT> cpu_price = device.processor_set.all().aggregate( db.Sum('model__group__price'))['model__group__price__sum'] or 0 <NEW_LINE> if not cpu_price: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> group = ComponentModelGroup.objects.get(name='Default CPU') <NEW_LINE>... | Calculate the price of a single virtual cpu for virtual servers inside. | 625941e8379a373c97cfafd9 |
def determine_action(query): <NEW_LINE> <INDENT> action_term_orders = [] <NEW_LINE> def match_syns(syns, ac): <NEW_LINE> <INDENT> pos_syn = -1 <NEW_LINE> for syn in syns: <NEW_LINE> <INDENT> if syn in query: <NEW_LINE> <INDENT> ato_index = query.index(syn) <NEW_LINE> if pos_syn == -1: <NEW_LINE> <INDENT> action_term_or... | Determine the intended action of the user
Eliminates the cases where a string may match keywords from multiple action categories
:param query: A string, the normalised user query
:return: An OperationType enum, the action to perform | 625941e891af0d3eaac9beaf |
def get_shfe_daily(date = None): <NEW_LINE> <INDENT> day = ct.convert_date(date) if date is not None else datetime.date.today() <NEW_LINE> try: <NEW_LINE> <INDENT> json_data = json.loads(urlopen(Request(ct.SHFE_DAILY_URL % (day.strftime('%Y%m%d')), headers=ct.SIM_HAEDERS)).read().decode('utf8')) <NEW_LINE> <DEDENT> exc... | 获取上期所日交易数据
Parameters
------
date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
Return
-------
DataFrame
上期所日交易数据(DataFrame):
symbol 合约代码
date 日期
open 开盘价
high 最高价
low 最低价
... | 625941e84a966d76dd5514a6 |
def ell_map_from_double_predictor(predictor, step_interval_msec=0, lag_threshold_msec=0, function_prefix=""): <NEW_LINE> <INDENT> ell_map = None <NEW_LINE> try: <NEW_LINE> <INDENT> model = ell.model.Model() <NEW_LINE> builder = ell.model.ModelBuilder() <NEW_LINE> inputShape = predictor.GetInputShape() <NEW_LINE> output... | Wraps an ell.DoubleNeuralNetworkPredictor into an ell.model.Map
Optional parameters:
step_interval_msec - step interval for the model (set 0 for no interval)
lag_threshold_msec - how long to fall behind before sending a lag
callback (applies when step_interval_msec > 0)
function_prefi... | 625941e8435de62698dfe0df |
def harris_corner_detector(im): <NEW_LINE> <INDENT> derivative_filter = np.array([[1, 0, -1]]) <NEW_LINE> i_x_derivative = convolve(im, derivative_filter) <NEW_LINE> i_y_derivative = convolve(im, derivative_filter.transpose()) <NEW_LINE> height, width = im.shape <NEW_LINE> M = np.ndarray((height, width, 2, 2)) <NEW_LIN... | Detects harris corners.
Make sure the returned coordinates are x major!!!
:param im: A 2D array representing an image.
:return: An array with shape (N,2), where ret[i,:] are the [x,y] coordinates of the ith corner points. | 625941e885dfad0860c3b2ee |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, RuleTargetSection): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941e8a219f33f34628df5 |
def interface_hundredgigabitethernet_ip_interface_fo_ospf_conf_ospf_interface_config_md5_authentication_key_table_key_id(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete... | Auto Generated Code
| 625941e856ac1b37e6264658 |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkScalarChanAndVeseDenseLevelSetImageFilterPython.itkScalarChanAndVeseDenseLevelSetImageFilterIF3IF3IF3_Superclass_Superclass_GetPointer(self) | GetPointer(self) -> itkScalarChanAndVeseDenseLevelSetImageFilterIF3IF3IF3_Superclass_Superclass | 625941e85510c4643540f86b |
def convert_to_minutes(num_hours): <NEW_LINE> <INDENT> minutes = num_hours * 60 <NEW_LINE> return minutes | (int) -> int
Return the number of minutes there are in num_hours.
>>> convert_to_minutes(2)
120 | 625941e82ae34c7f2600d5c3 |
def affine_backward(dout, cache): <NEW_LINE> <INDENT> x, w, b = cache <NEW_LINE> dx, dw, db = None, None, None <NEW_LINE> N = x.shape[0] <NEW_LINE> D = w.shape[0] <NEW_LINE> dx = np.dot(dout, w.T).reshape(x.shape) <NEW_LINE> dw = np.dot(x.reshape(N, D).T, dout) <NEW_LINE> db = np.sum(dout, axis=0) <NEW_LINE> return dx,... | Computes the backward pass for an affine layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
- b: Biases, of shape (M,)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Grad... | 625941e86fece00bbac2dbd6 |
def add(self, item): <NEW_LINE> <INDENT> for bfilter in self.blooms: <NEW_LINE> <INDENT> if not bfilter.check(item): <NEW_LINE> <INDENT> bfilter.add(item) <NEW_LINE> break | Add an item hash to the filter(s) | 625941e8d4950a0f3b08c7db |
def get_brightness(self) -> Optional[int]: <NEW_LINE> <INDENT> if "dimming" in self.pilotResult: <NEW_LINE> <INDENT> return percent_to_hex(self.pilotResult["dimming"]) <NEW_LINE> <DEDENT> return None | Get the value of the brightness 0-255. | 625941e8a8ecb033257d355e |
def __init__(self, token=None, beta_host=False, version="v1"): <NEW_LINE> <INDENT> self.__token = None <NEW_LINE> if token is not None: <NEW_LINE> <INDENT> self.__token = token <NEW_LINE> <DEDENT> if beta_host: <NEW_LINE> <INDENT> self.__host = "https://beta.bookalope.net" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ... | Initializes a Bookalope client instance.
:param str token: The user's authentication token provided by Bookalope.
:param bool beta_host: True to use Bookalope's beta services, False for production.
:param int version: Use the given version of the API.
:raises TokenError: If the given token is an invalid Bookalope tok... | 625941e826068e7796caf178 |
def load_mod2(self): <NEW_LINE> <INDENT> widget = Mod2(self) <NEW_LINE> self.setCentralWidget(widget) | carga modulo marcas | 625941e8eab8aa0e5d26dfec |
@_cached <NEW_LINE> def tutte_polynomial(G, edge_selector=None, cache=None): <NEW_LINE> <INDENT> R = ZZ['x, y'] <NEW_LINE> if G.num_edges() == 0: <NEW_LINE> <INDENT> return R.one() <NEW_LINE> <DEDENT> G = G.relabel(inplace=False) <NEW_LINE> G.allow_loops(True) <NEW_LINE> G.allow_multiple_edges(True) <NEW_LINE> if edge_... | Return the Tutte polynomial of the graph `G`.
INPUT:
- ``edge_selector`` (optional; method) this argument allows the user
to specify his own heuristic for selecting edges used in the deletion
contraction recurrence
- ``cache`` -- (optional; dict) a dictionary to cache the Tutte
polynomials generated in the rec... | 625941e8bf627c535bc13662 |
def firstUniqChar(self, s): <NEW_LINE> <INDENT> multiplicity = defaultdict(int) <NEW_LINE> for letter in s: <NEW_LINE> <INDENT> multiplicity[letter] += 1 <NEW_LINE> <DEDENT> for index, letter in enumerate(s): <NEW_LINE> <INDENT> if multiplicity[letter] == 1: <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> <DEDENT>... | :type s: str
:rtype: int | 625941e88e71fb1e9831dc3a |
def GetDB(self): <NEW_LINE> <INDENT> return self._dbpool | Create data pool object and database connection.
returns the datapool object | 625941e897e22403b379d42e |
def stacklists(arg): <NEW_LINE> <INDENT> if isinstance(arg, (tuple, list)): <NEW_LINE> <INDENT> return stack(list(map(stacklists, arg))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return arg | Recursively stack lists of tensors to maintain similar structure.
This function can create a tensor from a shaped list of scalars:
Examples
--------
>>> from theano.tensor import stacklists, scalars, matrices
>>> from theano import function
>>> a, b, c, d = scalars('abcd')
>>> X = stacklists([[a, b], [c, d]])
>>> f =... | 625941e891f36d47f21ac98a |
def pprint(self): <NEW_LINE> <INDENT> return pprint.pprint(self.__repr__()) | Pretty-prints the decision tree | 625941e8d268445f265b5301 |
def search_eigen(hint: str = '/usr/include/eigen3'): <NEW_LINE> <INDENT> if os.path.exists(hint): <NEW_LINE> <INDENT> return hint <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" | Search for the eigen3 library.
see: http://eigen.tuxfamily.org/index.php?title=Main_Page#Documentation | 625941e8ab23a570cc250619 |
def auth_recv(self): <NEW_LINE> <INDENT> id_r = auth_data = None <NEW_LINE> for p in self.packets[-1].payloads: <NEW_LINE> <INDENT> if p._type == payloads.Type.IDr: <NEW_LINE> <INDENT> id_r = p <NEW_LINE> logger.debug('Got responder ID: {}'.format(dump(bytes(p)))) <NEW_LINE> <DEDENT> if p._type == payloads.Type.AUTH: <... | Handle peer's IKE_AUTH response. | 625941e830bbd722463cc25b |
def solve(self, board): <NEW_LINE> <INDENT> if not any(board): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.n = len(board) <NEW_LINE> self.m = len(board[0]) <NEW_LINE> coor_list = [] <NEW_LINE> for i in range(self.n): <NEW_LINE> <INDENT> if board[i][0] == 'O': <NEW_LINE> <INDENT> coor_list.append((i, 0)) <NEW_LI... | :type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead. | 625941e863d6d428bbe44983 |
def __getitem__(self, key): <NEW_LINE> <INDENT> if hasattr(self, key): <NEW_LINE> <INDENT> return getattr(self, key) <NEW_LINE> <DEDENT> raise KeyError | 中括号操作支持
| 625941e88c3a873295158853 |
def maml_task(data_inner, data_outer, model, optimizer, criterion, create_graph): <NEW_LINE> <INDENT> original_parameters = model.state_dict(keep_vars=True) <NEW_LINE> device = next(model.parameters()).device <NEW_LINE> train_res = Res() <NEW_LINE> for i, (input, output) in enumerate(data_inner): <NEW_LINE> <INDENT> in... | Adapt model parameters to task and use adapted params to predict new samples
Arguments:
data_inner (iterable): list of input-output for task adaptation.
data_outer (iterable): list of input-output for task validation.
model (torch.nn.Module): task learner.
optimizer (maml.optim): optimizer for inner lo... | 625941e876e4537e8c351b09 |
def SetFilterDimensionality(self, *args): <NEW_LINE> <INDENT> return _itkDiscreteGaussianImageFilterPython.itkDiscreteGaussianImageFilterID2ID2_SetFilterDimensionality(self, *args) | SetFilterDimensionality(self, unsigned int _arg) | 625941e83539df3088e2e7de |
def firstprint(self, word_to_print=None): <NEW_LINE> <INDENT> log.debug('Logging that word: %s will be printed' % (word_to_print)) <NEW_LINE> print ('%s' % (word_to_print)) | Module print on screen words that user provide. Next do the shell
action and write that word to the file i user home catalog. | 625941e8d6c5a102081444e1 |
def calc_rek_mult(rek_response): <NEW_LINE> <INDENT> rek_json = json.loads(rek_response) <NEW_LINE> smiles = list(map(lambda e: float(e['Confidence']), [y for y in rek_json['Smiles'] if y['Value']])) <NEW_LINE> emotions = list(map(lambda e: float(e['Confidence']), [y for sublist in rek_json['Emotions'] for y in sublist... | Calculate a single value multiplier from a rekognition response
(array of smile and happy emotion confidence values) | 625941e87b25080760e398e9 |
def phaseFirstOrder(self, fromPos, toPos, phi1, degree = True, noChangeOnResonance=False, pivot = 0, scale= "Hz"): <NEW_LINE> <INDENT> self.checkToPos(toPos) <NEW_LINE> phaseValues = np.linspace(0,phi1,num=len(self.frequency)) <NEW_LINE> if noChangeOnResonance == True: <NEW_LINE> <INDENT> pivot = 0 <NEW_LINE> <DEDENT> ... | This should only be applied to Fourier transformed spectral data
It will lead to a zero phase shift at the upper end of the spectrum and to a
phase shift of phi1 at the lower end, linear interpolation inbetween.
this is the spinsight convention.
If a pivot is provided the phase will not be changed at the pivot, but th... | 625941e88e05c05ec3eea80b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.