code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def left_strip(data): <NEW_LINE> <INDENT> out = {"high": [], "low": [], "open": [], "close": [], "volume": [], "unix": []} <NEW_LINE> begin = False <NEW_LINE> for idx, item in enumerate(data["volume"]): <NEW_LINE> <INDENT> if item or begin: <NEW_LINE> <INDENT> begin = True <NEW_LINE> out["high"].append(data["high"][idx... | Remove no volume candles in beginning of dataset | 625941c330c21e258bdfa461 |
def is_goal_state(state): <NEW_LINE> <INDENT> return state.state == GOAL_STATE | Whether current state is the goal state
| 625941c3dd821e528d63b170 |
def create(self, ml_model_dto: MLModelDTO): <NEW_LINE> <INDENT> self.name = ml_model_dto.name <NEW_LINE> self.source = ml_model_dto.source <NEW_LINE> self.dockerhub_url = ml_model_dto.dockerhub_url <NEW_LINE> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> return self | Creates and saves the current model to the DB | 625941c3a8ecb033257d3093 |
def constrain_encoding(self): <NEW_LINE> <INDENT> accept_encoding = self.headers.get("accept-encoding") <NEW_LINE> if accept_encoding: <NEW_LINE> <INDENT> self.headers["accept-encoding"] = ( ', '.join( e for e in {"gzip", "identity", "deflate", "br", "zstd"} if e in accept_encoding ) ) | Limits the permissible Accept-Encoding values, based on what we can
decode appropriately. | 625941c391f36d47f21ac4b6 |
def _change_setting4( self ): <NEW_LINE> <INDENT> self.settings[ "smooth_scrolling" ] = not self.settings[ "smooth_scrolling" ] <NEW_LINE> self._set_controls_values() | changes settings #4 | 625941c3ac7a0e7691ed4095 |
def interior_decorator(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> with Timer(timer): <NEW_LINE> <INDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return wrapper | The actual function wrapper. | 625941c31d351010ab855ae2 |
def size(self, ctype=gu.PEDESTALS) : <NEW_LINE> <INDENT> if self.pbits & 128 : print(self.msgw() % 'size (%s)' % gu.dic_calib_type_to_name[ctype]) <NEW_LINE> if ctype == gu.COMMON_MODE : return self.cbase.size_cm <NEW_LINE> else : <NEW_LINE> <INDENT> self.retrieve_shape() <NEW_LINE> return self._size | Returns size
| 625941c3d7e4931a7ee9dee3 |
def list_by_resource( self, resource_group_name, vault_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "20... | The List operation gets information about the private endpoint connections associated with the
vault.
:param resource_group_name: Name of the resource group that contains the key vault.
:type resource_group_name: str
:param vault_name: The name of the key vault.
:type vault_name: str
:keyword callable cls: A custom ty... | 625941c3004d5f362079a2fa |
def benchmark_data(self, agent, world): <NEW_LINE> <INDENT> reward = 0 <NEW_LINE> collisions = 0 <NEW_LINE> occupied_landmarks = 0 <NEW_LINE> min_dists = 0 <NEW_LINE> for l in world.landmarks: <NEW_LINE> <INDENT> dists = [np.sqrt(np.sum(np.square(a.state.p_pos - l.state.p_pos))) for a in world.agents] <NEW_LINE> min_di... | Returns data for benchmarking purposes.
Args:
agent (multiagent_particle_env.core.Agent): Agent object
world (multiagent_particle_env.core.World): World object with agents and landmarks
Returns:
(tuple) The agent's reward, number of collisions, total minimum distance to landmarks,
and number o... | 625941c32c8b7c6e89b35787 |
def start_external_search(self, selection, state: "State", paths: List[Path]): <NEW_LINE> <INDENT> def letter_split(q): <NEW_LINE> <INDENT> return r"[*/'_~]*".join((re.escape(c) for c in list(q))) <NEW_LINE> <DEDENT> sub_queries = state.query.split(" ") <NEW_LINE> queries = [(q, re.compile(letter_split(q), re.IGNORECAS... | Zim internal search is not able to find out text with markup.
Ex:
'economical' is not recognized as 'economi**cal**' (however highlighting works great),
as 'economi[[inserted link]]cal'
as 'any text with [[http://economical.example.com|link]]'
This fullt... | 625941c33eb6a72ae02ec49e |
def formatDist(distance, mapunits): <NEW_LINE> <INDENT> if mapunits == 'metres': <NEW_LINE> <INDENT> mapunits = 'meters' <NEW_LINE> <DEDENT> outunits = mapunits <NEW_LINE> distance = float(distance) <NEW_LINE> divisor = 1.0 <NEW_LINE> if mapunits == 'meters': <NEW_LINE> <INDENT> if distance > 2500.0: <NEW_LINE> <INDENT... | Formats length numbers and units in a nice way.
Formats length numbers and units as a function of length.
>>> formatDist(20.56915, 'metres')
(20.57, 'm')
>>> formatDist(6983.4591, 'metres')
(6.983, 'km')
>>> formatDist(0.59, 'feet')
(0.59, 'ft')
>>> formatDist(8562, 'feet')
(1.622, 'miles')
>>> formatDist(0.48963, 'd... | 625941c3462c4b4f79d1d696 |
def update(self, params={}): <NEW_LINE> <INDENT> return self.__update__( 'CardTimeLog', params ) | Updates the card time log.
:param params: Dictionary with parametrs for request.
Full list of avalible parameters is avalible on
https://faq.kaiten.io/docs/api#card-time-logs,-not-stable-yet-patch
:type params: dict | 625941c301c39578d7e74e01 |
def new_get_model(model_identifier): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return models.get_model(model_identifier) <NEW_LINE> <DEDENT> except (LookupError, TypeError): <NEW_LINE> <INDENT> raise base.DeserializationError( "Invalid model identifier: '%s'" % model_identifier) | Helper to look up a model from an "app_label.model_name" string.
From | 625941c37cff6e4e8111794c |
def ReloadDeviceOs(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("ReloadDeviceOs", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.ReloadDeviceOsResponse() <NEW_L... | 重装操作系统
:param request: Request instance for ReloadDeviceOs.
:type request: :class:`tencentcloud.bm.v20180423.models.ReloadDeviceOsRequest`
:rtype: :class:`tencentcloud.bm.v20180423.models.ReloadDeviceOsResponse` | 625941c39f2886367277a854 |
def MigrateV2(self, v2Item, log): <NEW_LINE> <INDENT> itemBody = v2Item.get_or_add_child(qtiv2.content.ItemBody) <NEW_LINE> if self.GotPosition(): <NEW_LINE> <INDENT> log.append( "Warning: discarding absolute positioning information on presentation") <NEW_LINE> <DEDENT> if self.InlineChildren(): <NEW_LINE> <INDENT> p =... | Presentation maps to the main content in itemBody. | 625941c3a4f1c619b28b0003 |
def get_mo_overlap_matrix(mo_a,mo_b,ao_overlap_matrix,numproc=1): <NEW_LINE> <INDENT> if isinstance(mo_a, MOClass): <NEW_LINE> <INDENT> mo_a = mo_a.get_coeffs() <NEW_LINE> <DEDENT> elif isinstance(mo_a,dict): <NEW_LINE> <INDENT> mo_a = numpy.array(mo_a['coeffs']) <NEW_LINE> <DEDENT> if isinstance(mo_b, MOClass): <NEW_L... | Computes the overlap of two sets of molecular orbitals.
**Parameters:**
mo_a : numpy.ndarray with shape = (NMO,NAO), dict, or MOClass instance
Contains the molecular orbital coefficients of all `Bra` orbitals.
mo_b : numpy.ndarray with shape = (NMO,NAO), dict, or MOClass instance
Contains the molecular orbital ... | 625941c38e71fb1e9831d770 |
def Efield_static_uniform(x): <NEW_LINE> <INDENT> Ex = 0 <NEW_LINE> Ey = 0 <NEW_LINE> Ez = 0.1 <NEW_LINE> return np.array((Ex, Ey, Ez)) | To simplify the example, impose a constant, uniform E field | 625941c3b7558d58953c4edd |
def _update_figure(self): <NEW_LINE> <INDENT> self._axes.clear() <NEW_LINE> if (self._parameters['x_axis'].list != [] and self._parameters['y_axis'].list != []): <NEW_LINE> <INDENT> tb = self._tb_dict[self._parameters['tb'].selected]['tb'] <NEW_LINE> ts = (self._tb_ts_dict[self._parameters['tb'].selected] [self._parame... | Update figure. | 625941c37047854f462a13d2 |
def test_update_page_state(self): <NEW_LINE> <INDENT> pageStateObj = PageState() <NEW_LINE> response = self.client.open( '/rui-support/page-state/{keycloakId}'.format(keycloakId='keycloakId_example'), method='PATCH', data=json.dumps(pageStateObj), content_type='application/ld+json') <NEW_LINE> self.assert200(response, ... | Test case for update_page_state
Updates the page state for a user session | 625941c3287bf620b61d3a2b |
def purchase(self, ticker, fromMidPrice=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.hTicks.append(ticker) <NEW_LINE> if fromMidPrice: <NEW_LINE> <INDENT> self.midTicks.remove(ticker) <NEW_LINE> tPrice = fromMidPrice <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tPrice = ticker.AP <NEW_LINE> self.qTicks.rem... | "Purchases" the stock by removing it from the Queue, placing it on the Holding table
Args:
ticker (Tick): Tick object of ticker we're actually purchasing
Returns:
None | 625941c36aa9bd52df036d69 |
def _refresh_locale_store(self, lang): <NEW_LINE> <INDENT> self._localeStore.clear() <NEW_LINE> locales = localization.get_language_locales(lang) <NEW_LINE> for locale in locales: <NEW_LINE> <INDENT> if self._only_existing_locales and not localization.locale_has_translation(locale): <NEW_LINE> <INDENT> continue <NEW_LI... | Refresh the localeStore with locales for the given language. | 625941c3b7558d58953c4ede |
def compute_buckets(self): <NEW_LINE> <INDENT> from collections import defaultdict <NEW_LINE> dicts = pan, pap, pbm, pbq = defaultdict(list), defaultdict(list), defaultdict(list), defaultdict(list) <NEW_LINE> for dic, lis in zip(dicts, (self.an, self.ap, self.bm, self.bq)): <NEW_LINE... | Compute buckets for the fours sets of parameters.
We guarantee that any two equal Mod objects returned are actually the
same, and that the buckets are sorted by real part (an and bq
descendending, bm and ap ascending).
>>> from sympy.simplify.hyperexpand import IndexQuadruple
>>> from sympy.abc import y
>>> from symp... | 625941c3d164cc6175782d14 |
def eliminate(self, *vs): <NEW_LINE> <INDENT> for v in vs: <NEW_LINE> <INDENT> for f in self.N(v): <NEW_LINE> <INDENT> fac = self.node[f] <NEW_LINE> i = fac['vars'].index(v) <NEW_LINE> fac['vars'].remove(v) <NEW_LINE> if len(fac['pmf'].shape) > 1: <NEW_LINE> <INDENT> fac['pmf'] = sum( fac['pmf'], axis=i ) <NEW_LINE> <D... | vs : [var] | 625941c38a349b6b435e8139 |
def findPorts(self): <NEW_LINE> <INDENT> com_port_combo = [] <NEW_LINE> for port in serialutils.enumerate_serial_ports(): <NEW_LINE> <INDENT> com_port_combo.append(port) <NEW_LINE> <DEDENT> return com_port_combo | Search for available Ports | 625941c3435de62698dfdc12 |
def get_and_organise_product_codes(self): <NEW_LINE> <INDENT> if self.sale_info["note"]: <NEW_LINE> <INDENT> self.notes.append(self.sale_info["note"]) <NEW_LINE> <DEDENT> for product in self.sale_info["line_items"]: <NEW_LINE> <INDENT> if product["product_id"] == "549e099d-a641-7141-c907-cdd9d0266175": <NEW_LINE> <INDE... | Go through products on sale organise into pre-checks, actual repairs, extract passcode/data/notification preferences | 625941c367a9b606de4a7e81 |
def contour(self, *args, **kwargs): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> plt.gca().set_aspect('equal') <NEW_LINE> plt.tricontour(self.triang, self.values, *args, **kwargs) <NEW_LINE> plt.colorbar() <NEW_LINE> plt.show() | Show contours of values. | 625941c356ac1b37e6264199 |
def stat_sum(self): <NEW_LINE> <INDENT> return Dataset.stat_sum(self) | Total likelihood given the current model parameters. | 625941c3293b9510aa2c325e |
def size(lst): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return lt.size(lst) <NEW_LINE> <DEDENT> except Exception as exp: <NEW_LINE> <INDENT> error.reraise (exp, 'TADList->size: ') | Informa el número de elementos de la lista.
Args
lst: La lista a examinar
Raises:
Exception | 625941c307d97122c417884e |
def __init__(self,original): <NEW_LINE> <INDENT> self.original_frame=original <NEW_LINE> tk.Toplevel.__init__(self) <NEW_LINE> self.geometry("400x300") <NEW_LINE> self.title("newAccount") <NEW_LINE> newusername=StringVar() <NEW_LINE> newpassword=StringVar() <NEW_LINE> def createact(*args): <NEW_LINE> <INDENT> newact=[]... | Constructor | 625941c3e76e3b2f99f3a7d4 |
def save_credential(credential): <NEW_LINE> <INDENT> Credential.save_credentials(credential) | function that saves a newly created credential | 625941c35510c4643540f3af |
def __init__(self, message = None, previous = None, code = 0): <NEW_LINE> <INDENT> ConsoleException.__init__(self, 127, message, previous, code); | Constructor.
@param string message The internal exception message
@param Exception previous The previous exception
@param integer code The internal exception code | 625941c3f548e778e58cd543 |
def __init__(self, keyid=None, comptage='1', date_envoi=None, sms=None, num=None, emetteur=None, tracker=None, smslong='999', nostop=None, ucs2=None): <NEW_LINE> <INDENT> self.swagger_types = { 'keyid': 'str', 'comptage': 'str', 'date_envoi': 'str', 'sms': 'str', 'num': 'str', 'emetteur': 'str', 'tracker': 'str', 'smsl... | ComptageRequest - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941c32eb69b55b151c874 |
def test_retrieve_list_no_redirect_if_logged_in(self): <NEW_LINE> <INDENT> self.client.login(username="user", password="abcd123456") <NEW_LINE> response = self.client.get("/payee-payer/retrieve-payee-payer-list/") <NEW_LINE> self.assertEqual(str(response.context['user']), 'user') <NEW_LINE> self.assertEqual(response.st... | Checks that request is redirected if user is not logged in | 625941c329b78933be1e5675 |
def as_command(self): <NEW_LINE> <INDENT> return "(dynamic test case)" | Provide base method. | 625941c3cdde0d52a9e52ff8 |
def get_cl_parameters(argv): <NEW_LINE> <INDENT> program_function = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> opts, args = getopt.getopt(argv, "hf:b:r:", ["help", "function=", "b_qcd=", "qcd_ratio="]) <NEW_LINE> <DEDENT> except getopt.GetoptError as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> usage() <NEW_LINE> sys.exit... | Extracts the command line parameters.
:param argv:
:return: | 625941c3442bda511e8be3e1 |
def load_data_file_dark(filename): <NEW_LINE> <INDENT> filename_dark = filename.with_suffix(".dark13.txt") <NEW_LINE> counts_dark = load_csv(filename_dark) <NEW_LINE> return counts_dark | Load a dark pixel file from a spectrum filename. | 625941c3091ae35668666f28 |
def _findfieldnameindex(self, fieldname): <NEW_LINE> <INDENT> return self.fields.index(fieldname) | Internal use only. | 625941c33eb6a72ae02ec49f |
def compare_files(service, downloaded_file, used_file): <NEW_LINE> <INDENT> LOG.debug(f'Comparing downloaded via {service} file with original file ...') <NEW_LINE> assert filecmp.cmp(downloaded_file, used_file, shallow=False), 'Files are not equal. | FAIL | ' <NEW_LINE> LOG.info(f'{service} Downloaded file is equal to ... | Compare Downloaded file with original. | 625941c3adb09d7d5db6c757 |
def euler(self, bestside): <NEW_LINE> <INDENT> if np.allclose(bestside[0], np.array([0, 0, -1]), atol=VECTOR_TOL): <NEW_LINE> <INDENT> rotation_axis = [1, 0, 0] <NEW_LINE> phi = np.pi <NEW_LINE> <DEDENT> elif np.allclose(bestside[0], np.array([0, 0, 1]), atol=VECTOR_TOL): <NEW_LINE> <INDENT> rotation_axis = [1, 0, 0] <... | Calculating euler rotation parameters and rotational matrix.
Args:
bestside (np.array): vector of the best orientation (3 x 3).
Returns:
rotation axis, rotation angle, rotational matrix. | 625941c3379a373c97cfab0a |
def serialize(self): <NEW_LINE> <INDENT> json_dict = [] <NEW_LINE> for dessert in self.desserts: <NEW_LINE> <INDENT> json_dict.append(dessert.serialize()) <NEW_LINE> <DEDENT> return json_dict | Convert dessert list data to a list of dictionaries,
which will play nice with JSON | 625941c38a43f66fc4b5402d |
def test_format_count_gt_total(self): <NEW_LINE> <INDENT> ctr = Counter(stream=self.tty.stdout, total=10, desc='Test', unit='ticks') <NEW_LINE> ctr.count = 50 <NEW_LINE> ctr.start = time.time() - 50 <NEW_LINE> rtn = ctr.format(width=80) <NEW_LINE> self.assertEqual(len(rtn), 80) <NEW_LINE> self.assertRegex(rtn, r'Test 5... | Counter should fall back to no-total format if count is greater than total | 625941c376e4537e8c351637 |
def Email_Search(mail, emailAddressToSearch, numDaysToSearchBeforeToday=0): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> listOfUIDLists = [] <NEW_LINE> FullUIDListRaw = [] <NEW_LINE> while i <= numDaysToSearchBeforeToday: <NEW_LINE> <INDENT> date_search = datetime.strftime(datetime.now() - timedelta(i), "%d %b %Y") <NEW_LINE> ... | Default:
Searches all emails from the current day's date,
creates a list of email uids of all the emails matching the search criteria
Parameters:
----------
mail : object
emailAddressToSearch : str
numDaysToSearchBeforeToday : int
Default : 0 -> Searches the current date only
> 0 -> Searches that many ... | 625941c3e64d504609d74806 |
def test_permanent_redirect(self): <NEW_LINE> <INDENT> response = RedirectView.as_view(url='/bar/')( DummyRequest(path='/foo/', method='GET') ) <NEW_LINE> self.assertEqual(response.status_code, 301) <NEW_LINE> self.assertEqual(response.location, '/bar/') | Default is a permanent redirect | 625941c3a219f33f34628932 |
def compute_one_vertex_feature_score(self, object_tracker): <NEW_LINE> <INDENT> return object_tracker.tracker_feature_score() | Compute and return the feature (or appearance) score of one
vertex (tracker). | 625941c39c8ee82313fbb73b |
def add_armor(self, armor): <NEW_LINE> <INDENT> armory = self.armors.append(armor) <NEW_LINE> return armory | This method will add the armor object that is passed in to the list of armor objects definied in the initializer as self.armors. | 625941c3627d3e7fe0d68e15 |
def get_alb_target_groups(alb_arn): <NEW_LINE> <INDENT> target_group_descriptions = ALB_CLIENT.describe_target_groups(LoadBalancerArn=alb_arn)[ 'TargetGroups'] <NEW_LINE> return [tg_desc['TargetGroupArn'] for tg_desc in target_group_descriptions] | Takes an application load balancer amazon resource name and returns a list
of target group amazon resource names.
args:
alb_arn - the amazon resource name of an ALB | 625941c3d8ef3951e3243504 |
def inverse(x: int, n: int) -> int: <NEW_LINE> <INDENT> (divider, inv, _) = extended_gcd(x, n) <NEW_LINE> if divider != 1: <NEW_LINE> <INDENT> raise NotRelativePrimeError(x, n, divider) <NEW_LINE> <DEDENT> return inv | Returns the inverse of x % n under multiplication, a.k.a x^-1 (mod n)
>>> inverse(7, 4)
3
>>> (inverse(143, 4) * 143) % 4
1 | 625941c326068e7796caeca2 |
def set_encoder_enable(self, id): <NEW_LINE> <INDENT> for i in self._parse_id(id): <NEW_LINE> <INDENT> self._write_bytes(self._REG_ENCODER1_EN + 5 * (i - 1), [0x01]) | @brief Set dc motor encoder enable
@param id: list Encoder list, items in range 1 to 2, or id = self.ALL | 625941c326068e7796caeca3 |
def set_fee_per_period(self, fee, alias_type): <NEW_LINE> <INDENT> storage = Storage() <NEW_LINE> keys = self.options() <NEW_LINE> key = keys[3] <NEW_LINE> key = concat(key, alias_type) <NEW_LINE> storage.delete(key) <NEW_LINE> storage.save(key, fee) <NEW_LINE> ConfigurationUpdatedEvent(key, fee) <NEW_LINE> return True | :param fee:
:param type:
sets fee per period for given type
| 625941c324f1403a92600b2e |
def get_cash_flow(self, **kwargs): <NEW_LINE> <INDENT> def format(out): <NEW_LINE> <INDENT> results = {} <NEW_LINE> for symbol in out: <NEW_LINE> <INDENT> if out[symbol]: <NEW_LINE> <INDENT> results[symbol] = pd.DataFrame.from_dict( {d["reportDate"]: d for d in out[symbol]["cashflow"]}, orient="index", ) <NEW_LINE> <DE... | Cash Flow
Pulls cash flow data. Available quarterly (4 quarters) or annually
(4 years).
Reference: https://iexcloud.io/docs/api/#cash-flow
Data Weighting: ``1000`` per symbol per period
Parameters
----------
period: str, default 'quarter', optional
Allows you to specify annual or quarterly cash flows.
Value... | 625941c35fdd1c0f98dc01f9 |
def _set_safi_name(self, v, load=False): <NEW_LINE> <INDENT> parent = getattr(self, "_parent", None) <NEW_LINE> if parent is not None and load is False: <NEW_LINE> <INDENT> raise AttributeError( "Cannot set keys directly when" + " within an instantiated list" ) <NEW_LINE> <DEDENT> if hasattr(v, "_utype"): <NEW_LINE> <I... | Setter method for safi_name, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/interfaces/interface/afi_safi/af/safi_name (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_safi_name is considered as a private
method. Backends looking to popula... | 625941c3099cdd3c635f0c22 |
def __init__(self, centre: Tuple[int, int]) -> None: <NEW_LINE> <INDENT> self._centre = int(centre[0]), int(centre[1]) <NEW_LINE> self._name = None <NEW_LINE> self._point = None <NEW_LINE> self._ne = None <NEW_LINE> self._nw = None <NEW_LINE> self._se = None <NEW_LINE> self._sw = None | Initialize this QuadTree instance.
=== Precondition ===
- <centre> must contain only positive integers or zero.
>>> tree = QuadTree((100, 100))
>>> tree.__getattribute__('_centre') == (100, 100)
True
>>> tree.is_empty()
True
Runtime: O(1) | 625941c30fa83653e4656f83 |
def convert_to_id(vocab, sentences): <NEW_LINE> <INDENT> return np.stack([[vocab[word] if word in vocab else vocab[UNK_TOKEN] for word in sentence] for sentence in sentences]) | DO NOT CHANGE
Convert sentences to indexed
:param vocab: dictionary, word --> unique index
:param sentences: list of lists of words, each representing padded sentence
:return: list of list of integers, with each row representing the word indices in the corresponding sentences | 625941c3d6c5a10208144010 |
def __iter__(self): <NEW_LINE> <INDENT> for s in self._list: <NEW_LINE> <INDENT> yield s | !Iterates over the set's elements in order. | 625941c31d351010ab855ae3 |
def swissPairings(tournament): <NEW_LINE> <INDENT> standings = playerStandings(tournament) <NEW_LINE> id_names = [(elem[0], elem[1]) for elem in standings] <NEW_LINE> return [(elem[0][0], elem[0][1], elem[1][0], elem[1][1]) for elem in zip(id_names[::2], id_names[1::2])] | Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a player adjacent
to him or her in the standing... | 625941c3aad79263cf390a05 |
def test_pushn_fail(self): <NEW_LINE> <INDENT> pass | no way to test this function's failure (pass) | 625941c3d486a94d0b98e10c |
def get_raw_x_intensities(self): <NEW_LINE> <INDENT> return self.__get_generic_array_numpy(GenotypeCalls.__ID_RAW_X, uint16) | Returns:
The raw x intensities of assay bead types as a list of integers | 625941c37d43ff24873a2c66 |
def fix_python_cmd(cmd, env=None): <NEW_LINE> <INDENT> if cmd[0] == 'python': <NEW_LINE> <INDENT> cmd = cmd[1:] <NEW_LINE> <DEDENT> elif cmd[0].endswith('.py'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cmd <NEW_LINE> <DEDENT> if sys.platform == 'win32': <NEW_LINE> <INDENT> python_ex... | Returns a fixed command line to explicitly invoke python if cmd is running
'python' or a '.py' script.
This will probe $PATH in `env` to see if there's an available python in the
current $PATH (allowing tasks to bring their own python). If there's no python
(or python.exe) in $PATH, this will fall back to sys.executab... | 625941c382261d6c526ab463 |
def get_response(self, environ): <NEW_LINE> <INDENT> resp = super(HTTPExceptionMixin, self).get_response(environ) <NEW_LINE> if is_json_request(environ.get('HTTP_ACCEPT')): <NEW_LINE> <INDENT> resp.mimetype = environ['HTTP_ACCEPT'] <NEW_LINE> <DEDENT> return resp | Return a json response for a json request
otherwise an html response | 625941c316aa5153ce36243f |
@cliutils.arg('instance_id', metavar='<instance_id>', help="Instance to remove the virtual interface from") <NEW_LINE> @cliutils.arg('interface_id', metavar='<interface_id>', help='ID of the virtual interface to delete') <NEW_LINE> def do_virtual_interface_delete(cs, args): <NEW_LINE> <INDENT> cs.os_virtual_interfacesv... | Removes the specified virtual interface from an instance | 625941c30383005118ecf5ab |
def get_name(self): <NEW_LINE> <INDENT> return lib.appnet_application_get_name(self._as_parameter_) | get application name | 625941c37d847024c06be281 |
def gradient(self, x): <NEW_LINE> <INDENT> xm = x[1:-1] <NEW_LINE> xm_m1 = x[:-2] <NEW_LINE> xm_p1 = x[2:] <NEW_LINE> der = numpy.zeros(x.shape, x.dtype) <NEW_LINE> der[1:-1] = 200. * (xm - xm_m1**2.) - 400. * (xm_p1 - xm**2.) * xm - 2. * (1. - xm) <NEW_LINE> der[0] = -400. * x[0] * (x[1] - x[0]**2.) - 2. * (1. - x[0])... | Evaluates the gradient of the function | 625941c37c178a314d6ef423 |
def selectiveDescendantGen(self, openOnly=False): <NEW_LINE> <INDENT> if not openOnly or self.isExpanded(): <NEW_LINE> <INDENT> for child in self.childList: <NEW_LINE> <INDENT> yield child <NEW_LINE> for node in child.selectiveDescendantGen(openOnly): <NEW_LINE> <INDENT> yield node | Return a generator to step through nodes in this branch.
Does not include the root node.
Arguments:
openOnly -- if True, only include children open in the current view | 625941c3bf627c535bc13195 |
def test_bm_response(self): <NEW_LINE> <INDENT> xyz = (.05,0,1) <NEW_LINE> self.ant.select_chans([0]) <NEW_LINE> resp = self.ant.bm_response(xyz, pol='x') <NEW_LINE> self.assertAlmostEqual(resp, n.sqrt(n.exp(-1)), 3) <NEW_LINE> resp = self.ant.bm_response(xyz, pol='y') <NEW_LINE> self.assertAlmostEqual(resp, n.sqrt(n.e... | Test the Antenna beam response | 625941c332920d7e50b28195 |
def __init__(self, acc_metric='accuracy_score', num_cv=5, **kwargs): <NEW_LINE> <INDENT> self.run_types = {} <NEW_LINE> for k in kwargs: <NEW_LINE> <INDENT> self.run_types[k] = kwargs.get(k, None) <NEW_LINE> <DEDENT> self.acc_metric = acc_metric <NEW_LINE> self.num_cv = num_cv <NEW_LINE> self.summary_df_cv = None <NEW_... | kwargs: *something* must be passed for each type or it will be ignored.
Can have just check, just ignore, just params, or any combination thereof.
kwarg inputs:
bucket: check, ignore, bucket_list.
min_max_scale: check, ignore, feature_range.
one_hot_encode: check, ignore, categories, bucket_list.
raw: ... | 625941c399cbb53fe6792bae |
def test_no_arguments(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> recipe() | No arguments | 625941c367a9b606de4a7e82 |
def getUsernameFromSiteDB_wrapped(logger, quiet = False): <NEW_LINE> <INDENT> from CRABClient.UserUtilities import getUsernameFromSiteDB <NEW_LINE> username = None <NEW_LINE> msg = "Retrieving username from SiteDB..." <NEW_LINE> if quiet: <NEW_LINE> <INDENT> logger.debug(msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN... | Wrapper function for getUsernameFromSiteDB,
catching exceptions and printing messages. | 625941c30a50d4780f666e58 |
def read_global_config() -> Dict[Text, Any]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return rasa.utils.io.read_config_file(GLOBAL_USER_CONFIG_PATH) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return {} | Read global Rasa configuration. | 625941c3d268445f265b4e35 |
def wind_LC(lcName,deckLineSet,vectWindDeck,windwardPileSet,vectWindwardPile,leewardPileSet=None,vectLeewardPile=None): <NEW_LINE> <INDENT> preprocessor=deckLineSet.getPreprocessor <NEW_LINE> lc=lcases.LoadCase(preprocessor,lcName,"default","constant_ts") <NEW_LINE> lc.create() <NEW_LINE> lc.addLstLoads([loads.UniformL... | Return the dead load case (asphalt, sidewalk, barriers, ...)
:param lcName: load case name
:param deckLineSet: set of lines to apply wind on deck.
:param vectWindDeck: components [vx,vy] of the uniform linear load due to wind on deck.
:param windwardPileSet:set of lines to apply on piles windward.
:param vectWindward... | 625941c345492302aab5e289 |
def get(self, counter): <NEW_LINE> <INDENT> return self.counts[counter] | Return total count associated with group | 625941c36e29344779a625db |
def __init__(self, orig: str, url: str = "https://api.bart.gov/", key: str = "MW9S-E7SL-26DU-VV8V", json: str = "y", cmd: str = "etd"): <NEW_LINE> <INDENT> BartAPI.__init__(self, url, key,json,cmd) <NEW_LINE> self.response = self.get_train_estimates(orig=orig) <NEW_LINE> self.station_list = [] <NEW_LINE> if self.respon... | Constructor for class. It performs the rest operation on the URL and get the response back
It also set the variable which retrieves current time and all the destination station details
:param orig: Origin station
:param url: URL
:param key: Key to validate request
:param json: Whether response is needed in JSON or not.... | 625941c3627d3e7fe0d68e16 |
def glob_files_locally(folder_path, pattern): <NEW_LINE> <INDENT> pattern = os.path.join(folder_path, pattern.lstrip('/')) if pattern else None <NEW_LINE> len_folder_path = len(folder_path) + 1 <NEW_LINE> for root, _, files in os.walk(folder_path): <NEW_LINE> <INDENT> for f in files: <NEW_LINE> <INDENT> full_path = os.... | glob files in local folder based on the given pattern | 625941c3009cb60464c6337a |
def __init__(self, array_size, readnoise, dark_current, gain): <NEW_LINE> <INDENT> self.array_size = array_size <NEW_LINE> self.readnoise = readnoise <NEW_LINE> self.gain = gain <NEW_LINE> self.dark_current = dark_current <NEW_LINE> self.tint = 1.0 <NEW_LINE> self.coadds = 1 <NEW_LINE> self.fowler = 1 <NEW_LINE> self.s... | array_size - in units of pixels (2D)
readnoise - in units of electrons per read
dark_current - in units of electrons per second per pixel
gain - in units of electrons per DN | 625941c3656771135c3eb834 |
def doRollover(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super().doRollover() <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._mail_summary() <NEW_LINE> self._log_state.last_rollover = time() | Overridden method. Perform all inherited behavior and mail any content
just rolled out of the current log file. | 625941c332920d7e50b28196 |
def get_recording_requests(self): <NEW_LINE> <INDENT> requests = {} <NEW_LINE> for site in self.record_sites: <NEW_LINE> <INDENT> requests[site] = RecordingRequest(time_start=self.time_start, time_stop=self.time_stop, conditions=self.exp_conditions, record_variable=site) <NEW_LINE> <DEDENT> return requests | Returns a RecordingRequest object or a dictionary of RecordingRequest
objects with unique keys representing the recordings that are required
from the simulation controller | 625941c3c4546d3d9de729f9 |
def errorString(self): <NEW_LINE> <INDENT> return QString() | QString QStateMachine.errorString() | 625941c350812a4eaa59c2ea |
def inception_v4(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = InceptionV4(**kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> model.load_state_dict(model_zoo.load_url(model_urls['inceptionv4'])) <NEW_LINE> <DEDENT> for param in model.parameters(): <NEW_LINE> <INDENT> param.requires_grad = True <NEW_LINE... | InceptionV4 model architecture from the
`"Inception-v4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941c3ff9c53063f47c1bb |
def print_options(): <NEW_LINE> <INDENT> print('---------- Documentation bot ----------') <NEW_LINE> print('---------------------------------------------') <NEW_LINE> print('The application must be executed with at ') <NEW_LINE> print('least one argument, accepted arguments are: ') <NEW_LINE> print('help ... | Function utilized to print possible commandline options for this application | 625941c3287bf620b61d3a2c |
def get_or_bust(data_dict, keys): <NEW_LINE> <INDENT> if isinstance(keys, basestring): <NEW_LINE> <INDENT> keys = [keys] <NEW_LINE> <DEDENT> import ckan.logic.schema as schema <NEW_LINE> schema = schema.create_schema_for_required_keys(keys) <NEW_LINE> data_dict, errors = _validate(data_dict, schema) <NEW_LINE> if error... | Return the value(s) from the given data_dict for the given key(s).
Usage::
single_value = get_or_bust(data_dict, 'a_key')
value_1, value_2 = get_or_bust(data_dict, ['key1', 'key2'])
:param data_dict: the dictionary to return the values from
:type data_dict: dictionary
:param keys: the key(s) for the value(s... | 625941c3d164cc6175782d15 |
def extract_total_num(self, smiles_list): <NEW_LINE> <INDENT> return len(smiles_list) | Extracts total number of data which can be parsed
We can use this method to determine the value fed to `target_index`
option of `parse` method. For example, if we want to extract input
feature from 10% of whole dataset, we need to know how many samples
are in a file. The returned value of this method may not to be sam... | 625941c3090684286d50ecab |
def tshark_supports_json(tshark_version): <NEW_LINE> <INDENT> return tshark_version >= LooseVersion("2.2.0") | Returns boolean indicating json support. | 625941c35166f23b2e1a5120 |
def fetch_stream_from_url(url, config, data=None, handlers=None): <NEW_LINE> <INDENT> return_code, return_message, response = open_url(url, config, data=data, handlers=handlers) <NEW_LINE> if return_code and return_code == http_client_.OK: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | Returns data retrieved from a URL.
@param url: URL to attempt to open
@type url: basestring
@param config: SSL context configuration
@type config: Configuration
@param data: HTTP POST data
@type data: str
@param handlers: list of custom urllib2 handlers to add to the request
@type handlers: iterable
@return: data retri... | 625941c3507cdc57c6306c9e |
@shared_task <NEW_LINE> def update_resource_from_row(row): <NEW_LINE> <INDENT> r = Resource(url=row[0]) <NEW_LINE> r._hash = row[1] <NEW_LINE> r.protocol = row[2] <NEW_LINE> r.contenttype = row[3] <NEW_LINE> r.host = row[4] <NEW_LINE> r.port = row[5] <NEW_LINE> r.path = row[6] <NEW_LINE> r.lastFetchDateTime = row[7] <N... | ORM lookup then update
No input validation and foolishly assumes the lookup won't miss. | 625941c3711fe17d82542336 |
def get_qd_conf_value(userid=None, mode='coupon', key='promotion_url', **kw): <NEW_LINE> <INDENT> def _get_default(): <NEW_LINE> <INDENT> if 'default' in kw: <NEW_LINE> <INDENT> return kw['default'] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> default_key = kw.get('default_key', 0) <NEW_LINE> if mode: <NEW_LINE> <INDEN... | 获取物料的链接
会区分渠道id返回url
Args:
userid: 商户userid.
mode: coupon,红包的物料链接; card,集点的物料链接.
key: qd_conf的key值 | 625941c3d4950a0f3b08c318 |
def _RunGsUtilWithAnalyticsOutput(self, cmd, expected_status=0): <NEW_LINE> <INDENT> stderr = self.RunGsUtil(['-d'] + cmd, return_stderr=True, expected_status=expected_status, env_vars={'GSUTIL_TEST_ANALYTICS': '2'}) <NEW_LINE> return METRICS_LOG_RE.search(stderr).group() | Runs the gsutil command to check for metrics log output.
The env value is set so that the metrics collector in the subprocess will
use testing parameters and output the metrics collected to the debugging
log, which lets us check for proper collection in the stderr.
Args:
cmd: The command to run, as a list.
expect... | 625941c3f8510a7c17cf96c3 |
def add(self, word, excerpt, freq, difficulty): <NEW_LINE> <INDENT> token = word.token <NEW_LINE> self.least_freq = min(freq, self.least_freq) <NEW_LINE> self.tokens.add(token) <NEW_LINE> self.token_with_difficulty[token] = difficulty <NEW_LINE> self.token_with_lang_freq[token] = freq <NEW_LINE> self.token_with_movie_f... | Add a word with meta data to the report. | 625941c3aad79263cf390a06 |
def reset(self): <NEW_LINE> <INDENT> self.state = {'blocks':np.zeros((self.num_row,self.num_col)), 'X':0} <NEW_LINE> self.pos_list = [[0,self.min_y]] <NEW_LINE> self.close() <NEW_LINE> self.generateNewRow() <NEW_LINE> self.generateNewRow() <NEW_LINE> self.render_blocks = self.state['blocks'].copy() <NEW_LINE> return se... | Reset the environment | 625941c3bd1bec0571d905f6 |
def setParent(self, parent): <NEW_LINE> <INDENT> self.parent=parent <NEW_LINE> self._addPrerequisites() | Sets the parent Page to add requisites on css and js files | 625941c3c4546d3d9de729fa |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> return create_packages_and_items(self.shipment, self.cleaned_data['name'], self.cleaned_data['description'], self.cleaned_data['package_quantity'], {}) | :return: QuerySet of the packages that were created. | 625941c338b623060ff0adb5 |
def test_run_environment(self): <NEW_LINE> <INDENT> infile = 'test.in' <NEW_LINE> outdir = 'path/to/out' <NEW_LINE> sample_name = 'test' <NEW_LINE> environment = 'test.sh' <NEW_LINE> fn = ps.general.run_mbased( infile, outdir, sample_name, environment=environment, is_phased=False, num_sim=1000000, threads=6, shell=Fals... | Test to make sure the function at least runs with an environment | 625941c34d74a7450ccd418b |
def stats_data(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.backend.hap_process.servers_stats( self.backend.name, self.backend.iid, self._sid)[self.name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.backend.hap_process.servers_stats( self.backend.name)... | Return stats data
Check documentation of ``stats_data`` method in :class:`_Frontend`.
:rtype: ``utils.CSVLine`` object | 625941c3eab8aa0e5d26db1f |
def get_last_option(sct): <NEW_LINE> <INDENT> c = ConfigParser.ConfigParser() <NEW_LINE> items={} <NEW_LINE> try: <NEW_LINE> <INDENT> if not c.read( os.path.join(os.getenv("CONFIG_DIR"),'trace.ini')): <NEW_LINE> <INDENT> c.write(open(os.path.join(os.getenv("CONFIG_DIR"),'trace.ini'), "w")) <NEW_LINE> raise <NEW_LINE> <... | get sct last key value. | 625941c366673b3332b92058 |
def stocGradAscent1(dataMat, classLabels, numIters=150): <NEW_LINE> <INDENT> m,n = shape(dataMat) <NEW_LINE> weights = ones(n) <NEW_LINE> for j in range(numIters): <NEW_LINE> <INDENT> dataIndex = range(m) <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> alpha = 4 / (1.0 + j + i) + 0.1 <NEW_LINE> randIndex = int(random... | 改进的随机梯度算法
设置迭代次数;每次更新选择的训练样本是随机的
学习率alpha随着迭代次数的增加,逐渐减小
:param dataMat:
:param classLabels:
:param numIters:
:return: | 625941c371ff763f4b549650 |
def get_word_count(string): <NEW_LINE> <INDENT> return len(string.split(sep = ' ')) | Returns the number of words in a string
Input:
- string - The string to validate | 625941c30c0af96317bb81af |
def initialize_chain(test_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join("cache", "node0")): <NEW_LINE> <INDENT> devnull = open("/dev/null", "w+") <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> datadir=initialize_datadir("cache", i) <NEW_LINE> args = [ os.getenv("BITCOIND", "blibraryd"), "-keypool=1", "... | Create (or copy from cache) a 200-block-long chain and
4 wallets.
blibraryd and blibrary-cli must be in search path. | 625941c3b830903b967e98d4 |
def generate_DeepConvLSTM_model( x_shape, class_number, filters, lstm_dims, learning_rate=0.01, regularization_rate=0.01, metrics=['accuracy']): <NEW_LINE> <INDENT> dim_length = x_shape[1] <NEW_LINE> dim_channels = x_shape[2] <NEW_LINE> output_dim = class_number <NEW_LINE> weightinit = 'lecun_uniform' <NEW_LINE> model ... | Generate a model with convolution and LSTM layers.
See Ordonez et al., 2016, http://dx.doi.org/10.3390/s16010115
Parameters
----------
x_shape : tuple
Shape of the input dataset: (num_samples, num_timesteps, num_channels)
class_number : int
Number of classes for classification task
filters : list of ints
n... | 625941c399fddb7c1c9de359 |
@define(ns, 'dump_stack') <NEW_LINE> def dumpStack( cat ) : <NEW_LINE> <INDENT> cat.output( str(cat.stack), cat.ns.info_colour ) | dump_stack : (-- -> --)
desc:
Non-destructively dumps the entire contents of the stack to the console
Most useful if stack output in the REPL is turned off
Example: dump_stack
tags:
debug,console,stack,dump,display | 625941c34f88993c3716c030 |
def remove_symbol_from_dist(dist, index): <NEW_LINE> <INDENT> if type(dist) is not Distribution: <NEW_LINE> <INDENT> raise TypeError("remove_symbol_from_dist got an object ot type {0}".format(type(dist))) <NEW_LINE> <DEDENT> new_prob = dist.prob.copy() <NEW_LINE> new_prob[index]=0 <NEW_LINE> new_prob /= sum(new_prob) <... | prob is a ndarray representing a probability distribution.
index is a number between 0 and and the number of symbols ( len(prob)-1 )
return the probability distribution if the element at 'index' was no longer available | 625941c3e8904600ed9f1ef2 |
def read_from_file(): <NEW_LINE> <INDENT> with open("object_data.csv", 'r') as data: <NEW_LINE> <INDENT> file_data = pd.read_csv(data, header=None) <NEW_LINE> for i in list(file_data.values): <NEW_LINE> <INDENT> print(i[0]) | This is just a test function to determine how the file data will be manipulated or
if the data was stored correctly
:return: | 625941c323e79379d52ee52d |
@server.route('/smdj') <NEW_LINE> def smdj(): <NEW_LINE> <INDENT> url = bottle.request.query.get('x') <NEW_LINE> urldict = urllib.parse.urlparse(url) <NEW_LINE> netloc = urldict.netloc <NEW_LINE> svrurl = "http://{}:{}/smdj".format(servername, portnum) <NEW_LINE> if url is None: <NEW_LINE> <INDENT> return "Usage: {}?x=... | Use bottle to serve up the modified webpage | 625941c310dbd63aa1bd2b6c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.