code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_rfid(port): <NEW_LINE> <INDENT> sleep(0.05) <NEW_LINE> while True: <NEW_LINE> <INDENT> line = port.readline() <NEW_LINE> if port.inWaiting() < 16: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if not line: <NEW_LINE> <INDENT> raise ValueError("RFID could not be read.") <NEW_LINE> <DEDENT> rfid = '' <NE...
Reads the most recently detected 12 character RFID input from the serial port and ignores all others in the buffer. Args: port is a serial.Serial() object. Returns: A string containing the RFID. Raises: ValueError: No RFID could be read despite TIR pin going High.
625941e1d10714528d60008d
def get_raw_score(self, string1, string2, force_ascii=True, full_process=True): <NEW_LINE> <INDENT> utils.sim_check_for_none(string1, string2) <NEW_LINE> utils.sim_check_for_string_inputs(string1, string2) <NEW_LINE> if utils.sim_check_for_empty(string1, string2): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> sorted...
Computes the Fuzzy Wuzzy token sort measure raw score between two strings. This score is in the range [0,100]. Args: string1,string2 (str), : Input strings force_ascii (boolean) : Flag to remove non-ascii characters or not full_process (boolean) : Flag to process the string or not. Processing includes r...
625941e1be7bc26dc91cd9a0
def __init__(self, renaming, next=None, name=None): <NEW_LINE> <INDENT> Step.__init__(self, worker=None, next=next, name=name) <NEW_LINE> self.renaming = renaming
Arguments: - name: A name for the Step instance. This is used when another Step (implicitly or explicitly) passes on rows. If two instanes have the same name, the name is mapped to the instance that was created the latest. Default: None - renaming: A dict with pairs (oldname, newname) which will by used by pyg...
625941e1d58c6744b4258004
def summaryRanges(self, nums): <NEW_LINE> <INDENT> start , end = 0, 0 <NEW_LINE> res = [] <NEW_LINE> n = len(nums) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> end = i <NEW_LINE> if (i < n-1 and nums[i]+1 != nums[i+1]) or i == n-1: <NEW_LINE> <INDENT> if end > start: <NEW_LINE> <INDENT> res.append(str(nums[start])...
:type nums: List[int] :rtype: List[str]
625941e1b57a9660fec33c2f
def read_file(filename): <NEW_LINE> <INDENT> _file = unidecode.unidecode(open(filename).read()) <NEW_LINE> return _file, len(_file)
Read file name Args: filename: String, path to file Returns: _file, len(file)
625941e13346ee7daa2b3114
def reset(self): <NEW_LINE> <INDENT> for player_results in self.results: <NEW_LINE> <INDENT> player_results.clear()
Clear the previous results, keep the players.
625941e115baa723493c431e
def _load(self): <NEW_LINE> <INDENT> reader = csv.reader(self.data_file) <NEW_LINE> header = reader.next() <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> code, description, explanatory_note, change_date = [unicode(x, 'UTF-8') for x in row] <NEW_LINE> self.data[code] = { 'code': code, 'description': description, 'exp...
Do initial load of COFOG csv file into internal data structure.
625941e19f2886367277ac31
def readChainFromFile(filename): <NEW_LINE> <INDENT> chainList = [] <NEW_LINE> probsList = [] <NEW_LINE> indexList = [] <NEW_LINE> maxIndex = 0 <NEW_LINE> with open(filename,'r') as f: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> if len(line) == 0: <NEW_LINE> <INDENT> keepReading = False <NEW_LINE> <DEDENT> keepR...
Reads chain (samples and ln prob) from specified file Should handle things (variation in number of parameters, walkers, steps) pretty robustly
625941e1bd1bec0571d909d5
def format_dataframe(self, _): <NEW_LINE> <INDENT> return ':py:class:`pandas.DataFrame`'
Format dataframe.
625941e196565a6dacc8fa71
def get_base64_diff_value(s1, s2): <NEW_LINE> <INDENT> base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' <NEW_LINE> for i in range(len(s2)): <NEW_LINE> <INDENT> if s1[i] != s2[i]: <NEW_LINE> <INDENT> return abs(base64chars.index(s1[i]) - base64chars.index(s2[i])) <NEW_LINE> <DEDENT> <DEDE...
get base64 diff value
625941e194891a1f4081be51
def _download_response(self): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for name in self.params.keys(): <NEW_LINE> <INDENT> data.append('='.join((name, urllib.quote_plus(_string(self.params[name]))))) <NEW_LINE> <DEDENT> data = '&'.join(data) <NEW_LINE> headers = { "Content-type": "application/x-www-form-urlencoded", 'A...
Returns a response body string from the server.
625941e18c0ade5d55d3ed64
def get_token(self, clear_load): <NEW_LINE> <INDENT> if "token" not in clear_load: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.loadauth.get_tok(clear_load["token"])
Return the name associated with a token or False if the token is invalid
625941e150485f2cf553d142
def espnetv2_w5d4(**kwargs): <NEW_LINE> <INDENT> return get_espnetv2(width_scale=1.25, model_name="espnetv2_w5d4", **kwargs)
ESPNetv2 x1.25 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural Network,' https://arxiv.org/abs/1811.11431. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for...
625941e11b99ca400220ae59
def antisymmetric_part(self): <NEW_LINE> <INDENT> return list(self[0])
The antisymmetric part as a list of strictly decreasing integers. OUTPUT: - a list EXAMPLES:: sage: SuperPartition([[3,1],[2,2,1]]).antisymmetric_part() [3, 1] sage: SuperPartition([[2,1,0],[3,3]]).antisymmetric_part() [2, 1, 0]
625941e13346ee7daa2b3115
def __updateGradeMenu(self): <NEW_LINE> <INDENT> id=UI.readPositiveInteger("Please enter the ID(Positive number)") <NEW_LINE> discipline=self.readDiscipline("Please enter the discipline") <NEW_LINE> teacher=input("Please enter the teacher") <NEW_LINE> grade=UI.readPositiveInteger("Please enter the grade") <NEW_LINE> tr...
Updates a grade from the registers. Input:- Output: the grade is updated if it exists
625941e18a349b6b435e8519
def append_to_matrix(m, v, axis=COLUMN): <NEW_LINE> <INDENT> if type(m) == type(None): <NEW_LINE> <INDENT> return np.copy(v) <NEW_LINE> <DEDENT> if axis == ROW: <NEW_LINE> <INDENT> if len(v.shape) == 1: <NEW_LINE> <INDENT> tmp_v = v.reshape(1, v.shape[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tmp_v = v <NEW_LIN...
if m(matrix) is none, then assing v(vector) to m o.w according to given axis, append v to m :param m: base matrix :param v: given vector :param axis: row base or column base append
625941e18da39b475bd6531e
def __init__(self, version_str=None): <NEW_LINE> <INDENT> self.ver_major = 0 <NEW_LINE> self.ver_minor = 0 <NEW_LINE> if version_str is not None: <NEW_LINE> <INDENT> match = re.match(r"^([1-9]\d*)\.([1-9]\d*|0|latest)$", version_str) <NEW_LINE> if match: <NEW_LINE> <INDENT> self.ver_major = int(match.group(1)) <NEW_LIN...
Create an API version object. :param version_str: String representation of APIVersionRequest. Correct format is 'X.Y', where 'X' and 'Y' are int values. None value should be used to create Null APIVersionRequest, which is equal to 0.0
625941e1e1aae11d1e74a061
def getDiagramm(): <NEW_LINE> <INDENT> CSVImport.getdiagram(csvfile, columnname_entry.get())
Calls the CSVIm :return:
625941e1e5267d203edce03f
def bprop(self, t, y): <NEW_LINE> <INDENT> return y - t
Creates deltas for bprop Uses shortcut, assumes previous layer has softmax activation :param t: network targets :type t: np.ndarray :param y: network outputs :type y: np.ndarray
625941e14f6381625f114de2
def sec_to_public_pair(sec): <NEW_LINE> <INDENT> x = from_bytes_32(sec[1:33]) <NEW_LINE> sec0 = sec[:1] <NEW_LINE> if sec0 == b'\4': <NEW_LINE> <INDENT> y = from_bytes_32(sec[33:65]) <NEW_LINE> from .ecdsa import generator_secp256k1, is_public_pair_valid <NEW_LINE> public_pair = (x, y) <NEW_LINE> if not is_public_pair_...
Convert a public key in sec binary format to a public pair.
625941e110dbd63aa1bd2f49
def test(model, device, dataloader, evaluator): <NEW_LINE> <INDENT> model = model.to(device) <NEW_LINE> model.eval() <NEW_LINE> pbar = tqdm(dataloader) <NEW_LINE> for (data, targets) in pbar: <NEW_LINE> <INDENT> data = data.to(device) <NEW_LINE> targets = targets.to(device) <NEW_LINE> results = model(data) <NEW_LINE> e...
Test engine. :param model: model(data, targets) -> results :param dataloader: next(iter(dataloader)) -> data, targets :param evaluator: evaluator.evaluate(data, targets, results), evaluator.clear() evaluator.get_results() -> results :return: the results returned by evaluator
625941e14428ac0f6e5bab9b
def api_manage(*args, **kwargs): <NEW_LINE> <INDENT> ctx = context.RequestContext('admin', 'fake', True) <NEW_LINE> vol = { 'status': 'creating', 'display_name': 'fake_name', 'availability_zone': 'nova', 'tenant_id': 'fake', 'id': 'ffffffff-0000-ffff-0000-ffffffffffff', 'volume_type': None, 'snapshot_id': None, 'user_i...
Replacement for cinder.volume.api.API.manage_existing. Overrides cinder.volume.api.API.manage_existing to return some fake volume data structure, rather than initiating a real volume managing. Note that we don't try to replicate any passed-in information (e.g. name, volume type) in the returned structure.
625941e1d8ef3951e32438e4
@task <NEW_LINE> def build_static(): <NEW_LINE> <INDENT> with cd(env.directory): <NEW_LINE> <INDENT> run(env.python + " manage.py collectstatic --noinput")
Copy the static files (images,css,js) to site_media
625941e121a7993f00bc809d
def check_enrollment(self): <NEW_LINE> <INDENT> payload = { 'action': 'checkEnrollment', 'email': self.profile['primary_email'], 'cid': self.data['cid'] } <NEW_LINE> response = requests.post(self.url, json=payload, headers=self.auth_header) <NEW_LINE> return response.json()
Checks if passed profile is enrolled in the passed course. returns true or false
625941e1cc40096d61595cf6
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure it's...
Run administrative tasks.
625941e194891a1f4081be52
def nc_copy(nc_source, nc_destination, timely=None, spatially=None, history_log=''): <NEW_LINE> <INDENT> bounds_dict = nc.nc_subdomain_bounds(nc_source, spatially) <NEW_LINE> excludes = [] <NEW_LINE> for k, v in iteritems(bounds_dict): <NEW_LINE> <INDENT> nc1.createDimension(k, v.stop - v.start) <NEW_LINE> excludes.app...
Copy a NetCDF file. Parameters ---------- nc_source - netCDF4.Dataset nc_destination - netCDF4.Dataset timely - timely spatially - spatially history_log - str Notes ----- This is completely out of date.
625941e15e10d32532c5f2cc
def __sigmoid(self, x): <NEW_LINE> <INDENT> return 1 / (1 + np.exp(-x))
The Sigmoid function, which describes an S shaped curve.
625941e185dfad0860c3b203
def _importBody(self, body): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dom = parseString(body) <NEW_LINE> <DEDENT> except ExpatError as e: <NEW_LINE> <INDENT> filename = (self.filename or '/'.join(self.context.getPhysicalPath())) <NEW_LINE> raise ExpatError('%s: %s' % (filename, e)) <NEW_LINE> <DEDENT> self._encodin...
Import the object from the file body.
625941e121bff66bcd684cf6
def _query(self, ResponseGroup="Large", **kwargs): <NEW_LINE> <INDENT> response = self.api.ItemSearch(ResponseGroup=ResponseGroup, **kwargs) <NEW_LINE> root = objectify.fromstring(response) <NEW_LINE> if (hasattr(root.Items.Request, 'Errors') and not hasattr(root.Items, 'Item')): <NEW_LINE> <INDENT> code = root.Items.R...
Query. Query Amazon search and check for errors. :return: An lxml root element.
625941e19f2886367277ac32
def find_in_list(x, l): <NEW_LINE> <INDENT> assert isinstance(l, list), "The argument l has to be a list, got '{}'.".format(type(l)) <NEW_LINE> return [index for index, value in enumerate(l) if value == x]
Get indices of the element x in list l :param x: element to find :param list l: list to be inspected :return list: indices of the element
625941e13617ad0b5ed6829d
def has_mandatory_placeholder(default_code, product_id): <NEW_LINE> <INDENT> if not product_id.bom_placeholder: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if product_id.bom_placeholder_rule: <NEW_LINE> <INDENT> return eval(product_id.bom_placeholder_rule) <NEW_LINE> <DEDENT> return True
Check if the product: default_code has a component that is mandatory (placeholder set and rule if present)
625941e15fdd1c0f98dc05dc
def filter ( self, object ): <NEW_LINE> <INDENT> pass
Returns True if object is accepted by the filter, and False if it is not.
625941e1004d5f362079a6d8
def set(self, name, value, obj_id=""): <NEW_LINE> <INDENT> if self.wec.getStatus() == 'Created': <NEW_LINE> <INDENT> restApiControl.setExecutionInputValue(self.weid, name, value, obj_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("Inputs cannot be changed as workflow execution status is not Created")
Sets the value of output parameter identified by name to given value @param: name parameter name @param: value associated value @throws: KeyError if input parameter name not found
625941e1d8ef3951e32438e5
def pyfunc(): <NEW_LINE> <INDENT> pass
Some pure python tests... >>> import os >>> 2+3 5 >>> for i in range(3): ... print i, ... print i+1, ... 0 1 1 2 2 3
625941e1cc0a2c11143dd238
def list(self, params=None): <NEW_LINE> <INDENT> return Connector(self.token, model_type="videos", path="videos/closed_questions/").send( method='GET', data=params)
Retrieve list of video closed question Args: page (int): Page of data per_page (int): Limit of date per page Returns: dict: The value containt in Response class as dict
625941e14527f215b584c7fa
def getArea(self): <NEW_LINE> <INDENT> return self.area
Returns area or community the property is located in.
625941e1236d856c2ad44b86
def assert_state(hass, entity_id, state, unit_of_measurement): <NEW_LINE> <INDENT> hass_state = hass.states.get(entity_id) <NEW_LINE> assert hass_state.state == state <NEW_LINE> assert hass_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == unit_of_measurement
Check that the state is what is expected. This is used to ensure that the logic in each sensor class handled the attribute report it received correctly.
625941e1925a0f43d254a221
def get_smoothing_and_feature_data(state_obs_dict, tag, word, state_observation_summary_counts, state_observation_counts, pattern_tag_dict): <NEW_LINE> <INDENT> tag_count_dict = {} <NEW_LINE> for pattern in PATTERNS: <NEW_LINE> <INDENT> _patt = pattern[0] <NEW_LINE> result = re.search(pattern[0], word) <NEW_LINE> if re...
Additional data for Good-Turing smoothing and feature engineering. scan each word and tag to accumulate tag, word counting information.
625941e16fece00bbac2daea
def __init__(self, name, instance_id, current_value, pending_value, read_only, fqdd, lower_bound, upper_bound): <NEW_LINE> <INDENT> super(RAIDIntegerAttribute, self).__init__(name, instance_id, current_value, pending_value, read_only, fqdd) <NEW_LINE> self.lower_bound = lower_bound <NEW_LINE> self.upper_bound = upper_b...
Creates RAIDIntegerAttribute object :param name: name of the RAID attribute :param instance_id: InstanceID of the RAID attribute :param current_value: list containing the current value of the RAID attribute :param pending_value: pending value of the RAID attribute, reflecting an unprocessed change ...
625941e1fbf16365ca6f6572
def __init__ (self, var, saxis, kernel, fft): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> assert len(kernel) <= var.shape[saxis], 'Kernel must not be longer than dimension being smoothed.' <NEW_LINE> self.saxis = saxis <NEW_LINE> self.var = var <NEW_LINE> self.kernel = kernel <NEW_LINE> self.fft = fft <NEW_LINE> ...
__init__()
625941e1ad47b63b2c50a325
def tools(self): <NEW_LINE> <INDENT> tool = tools.Tool() <NEW_LINE> start = tool.run()
Show all tools added in Lab
625941e1dc8b845886cb58de
def train(self, transition): <NEW_LINE> <INDENT> (s0, a, r, s1, done) = transition <NEW_LINE> self._process_rewards(r, done) <NEW_LINE> self._memory.append(transition) <NEW_LINE> if len(self._memory) > self._MEMORY_CAPACITY: <NEW_LINE> <INDENT> self._memory.popleft() <NEW_LINE> <DEDENT> if self.experience_count % self....
Process rewards, and prepares memory, then trains by calling replay method. Args: transition: a tuple of variables for one iteration.
625941e1187af65679ca54c7
def check_fit_config(self, spectra): <NEW_LINE> <INDENT> if not spectra.get_fit_config(): <NEW_LINE> <INDENT> raise CompatibilityError("%s has no fit config" % spectra._name) <NEW_LINE> <DEDENT> for par in spectra.get_fit_config().get_pars(): <NEW_LINE> <INDENT> parameter = spectra.get_fit_config().get_par(par) <NEW_LI...
Checks that a spectra has a fit config. Args: spectra (:class:`echidna.core.spectra.Spectra`): Spectra you want to check. Raises: CompatibilityError: If spectra has no fit config
625941e1bd1bec0571d909d6
def parse_timedelta( delta, min=None, max=None, min_included=True, max_included=True, ): <NEW_LINE> <INDENT> if isinstance(delta, str) and len(delta) > 0: <NEW_LINE> <INDENT> unit = delta[-1] <NEW_LINE> if unit in '0123456789': <NEW_LINE> <INDENT> unit = 's' <NEW_LINE> value = delta <NEW_LINE> <DEDENT> else: <NEW_LINE>...
Parse time delta
625941e126238365f5f0f21a
def is_numeric_dtype(obj): <NEW_LINE> <INDENT> if isclass(obj): <NEW_LINE> <INDENT> if issubclass(obj, cudf.core.dtypes.DecimalDtype): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if issubclass(obj, _BaseDtype): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance...
Check whether the provided array or dtype is of a numeric dtype. Parameters ---------- obj : array-like or dtype The array or dtype to check. Returns ------- bool Whether or not the array or dtype is of a numeric dtype.
625941e1293b9510aa2c3639
def overlay_box(img: np.ndarray, box: list, color: List[int], stroke: int=1) -> np.ndarray: <NEW_LINE> <INDENT> box = [int(b) for b in box] <NEW_LINE> y1, x1, height, width = box <NEW_LINE> y2 = y1 + height <NEW_LINE> x2 = x1 + width <NEW_LINE> img[y1 : y1 + stroke, x1:x2] = color <NEW_LINE> img[y2 : y2 + stroke, x1:x2...
Helper to overlay single box on image
625941e10fa83653e4657360
def rsnippet(s,n=8): <NEW_LINE> <INDENT> s = str(s) <NEW_LINE> start = max(0,len(s)-n) <NEW_LINE> return s[start:]
last N (clipped) chars of string
625941e126238365f5f0f21b
def _author_line(self): <NEW_LINE> <INDENT> if self.author and self.institution: <NEW_LINE> <INDENT> return self.author + ";" + self.institution <NEW_LINE> <DEDENT> elif self.author: <NEW_LINE> <INDENT> return self.author <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.institution
Helper method to concatenate author and institution values, if necessary :return: string
625941e1d268445f265b5216
def learn(self, obs, next_obs, actions, target_actions, predicted_actions, rewards, dones): <NEW_LINE> <INDENT> log_probs = self.critic(obs, actions, log=True) <NEW_LINE> target_probs = self.critic_target(next_obs, target_actions).detach() <NEW_LINE> target_dist = self._categorical(rewards, target_probs, dones) <NEW_LI...
Performs a distributional Actor/Critic calculation and update. Actor πθ and πθ' Critic Zw and Zw' (categorical distribution)
625941e173bcbd0ca4b2c41d
def __init__(self, caption="", fixed=False, modal=True, x=0, y=0, width=175, height=250, **kwargs): <NEW_LINE> <INDENT> Control.__init__(self, x=x, y=y, width=max(width,60), height=max(height,60), **kwargs) <NEW_LINE> img, w = Image(theme["panel"]), 30 <NEW_LINE> self.src = { "cap1" : crop(img, 0, img.height-w, w, w), ...
A panel containing other controls that can be dragged when Panel.fixed=False. Controls or (Layout groups) can be added with Panel.append().
625941e1956e5f7376d71213
def test_db_type_cached(self): <NEW_LINE> <INDENT> assert UselessEnum._db_type is UselessEnum.db_type()
Test that the result of cls.db_type() is cached and reused.
625941e192d797404e304533
def __call__(self, url, auth=None): <NEW_LINE> <INDENT> return requests.Request(self.method, pathjoin(self.path, url=url), auth=auth, headers=self.headers, data=self.data).prepare()
return a prepared request to be sent
625941e10383005118ecf989
def _coalesce_statements(self, statements): <NEW_LINE> <INDENT> if len(statements) == 0: <NEW_LINE> <INDENT> return self._node('ExpressionStatement', expression=None) <NEW_LINE> <DEDENT> elif len(statements) == 1: <NEW_LINE> <INDENT> return statements[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._node('...
Accept a sequence of zero or more statements and return an AST node which is one of a statement, null statement or multipart statement as appropriate.
625941e1baa26c4b54cb14c4
def get_input_data(bill): <NEW_LINE> <INDENT> for x in _split(expand(bill)): <NEW_LINE> <INDENT> yield data_util.extract_infer_features(x, features.FEATURES)
Returns inputs for the vote_prediction model given the bill JSON returned by ProPublica /recent_bills endpoint.
625941e156b00c62f0f14a03
def get_config(manifest,spec="Entrypoint"): <NEW_LINE> <INDENT> cmd = None <NEW_LINE> if "history" in manifest: <NEW_LINE> <INDENT> for entry in manifest['history']: <NEW_LINE> <INDENT> if 'v1Compatibility' in entry: <NEW_LINE> <INDENT> entry = json.loads(entry['v1Compatibility']) <NEW_LINE> if "config" in entry: <NEW_...
get_config returns a particular spec (default is Entrypoint) from a manifest obtained with get_manifest. :param manifest: the manifest obtained from get_manifest :param spec: the key of the spec to return, default is "Entrypoint"
625941e1442bda511e8be7bb
def _update_aliens(self): <NEW_LINE> <INDENT> self._check_fleet_edges() <NEW_LINE> self.aliens.update() <NEW_LINE> """Look for alien-ship collisions.""" <NEW_LINE> if pygame.sprite.spritecollideany(self.ship, self.aliens): <NEW_LINE> <INDENT> self._ship_hit() <NEW_LINE> <DEDENT> """Look for aliens hitting the bottom of...
Check if the fleet hits an edge then update all positions.
625941e166673b3332b92439
def coco_evaluate(references, hypothesis): <NEW_LINE> <INDENT> hyp_words = hypothesis.split(' ') <NEW_LINE> ref_words_list = [ref.split(' ') for ref in references] <NEW_LINE> rouge_scores = _rouge_scores(references, hypothesis) <NEW_LINE> scores = { 'BLEU-1': _bleu_n(1, ref_words_list, hyp_words), 'BLEU-2': _bleu_n(2, ...
Evaluate the hypothesis against the references for COCO scores. Args: references: A list of reference string. hypothesis: A hypothesis string. Returns: A dict containing COCO scores.
625941e1046cf37aa974d0ec
def onChangeComboBox(self, combo): <NEW_LINE> <INDENT> self.logger.debug( "This should show up each time the combobox is changed") <NEW_LINE> tree_iter = combo.get_active_iter() <NEW_LINE> if tree_iter != None: <NEW_LINE> <INDENT> model = combo.get_model() <NEW_LINE> value = model[tree_iter][0] <NEW_LINE> self.lastComb...
This should show up each time the combobox is changed
625941e1293b9510aa2c363a
def select_desc(self, desc): <NEW_LINE> <INDENT> records = self.buffer.linear_search_record(1, desc, 'description') <NEW_LINE> print(records) <NEW_LINE> pass
Finds record by description Can't use btree
625941e13317a56b86939ff8
def pixel2xyz(num, detdim=[195,487]): <NEW_LINE> <INDENT> UB = np.eye(3)/(2*np.pi) <NEW_LINE> XXX,YYY,ZZZ = pixel2hkl(num,detdim,UB) <NEW_LINE> return XXX,YYY,ZZZ
Generate cartesian coordinates of detector pixel positions, in A-1 XXX,YYY,ZZZ = pixel2xyz(#/d, detdim) detdim = detector dimesions def=[195,487] (Pilatus 100K) Uses the pilatus parameters local:"pilpara" to define detector distance, centre etc. pilpara=[119.536,1904.17,44.4698,0.106948,-0.738038,412.19,-0....
625941e167a9b606de4a825f
@tf_export('tile') <NEW_LINE> def tile(input, multiples, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> _, _, _op = _op_def_lib._apply_op_helper( "Tile", input=input, multiples=multiples, name=name) <NEW_LINE> _result = _op.ou...
Constructs a tensor by tiling a given tensor. This operation creates a new tensor by replicating `input` `multiples` times. The output tensor's i'th dimension has `input.dims(i) * multiples[i]` elements, and the values of `input` are replicated `multiples[i]` times along the 'i'th dimension. For example, tiling `[a...
625941e14e696a04525c97f5
def generate_monomorphic(self, literals): <NEW_LINE> <INDENT> c, m = self.make_class_function() <NEW_LINE> self.make_fill(m) <NEW_LINE> result = [] <NEW_LINE> class_var = self.next_variable() <NEW_LINE> result.append(Assignment(class_var, '=', [CallStatement(c, [])])) <NEW_LINE> l = self.make_loop(literals, class_var, ...
Generates a monomorphic callsite.
625941e121bff66bcd684cf7
def add_interface_properties(switchinfo): <NEW_LINE> <INDENT> for port, portitems in switchinfo['portinfo'].items(): <NEW_LINE> <INDENT> if 'switchport access vlan' in portitems.keys(): <NEW_LINE> <INDENT> switchinfo['portinfo'][port]['mode'] = 'access' <NEW_LINE> <DEDENT> elif portitems.get('switchport mode') == 'trun...
Interface properties of switch are inserted in switchinfo object based on configuration of all ports.
625941e1498bea3a759b9e56
def _check_boolean_expressions(self, node): <NEW_LINE> <INDENT> condition = node.test <NEW_LINE> if not isinstance(condition, BoolOp): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> nb_bool_expr = _count_boolean_expressions(condition) <NEW_LINE> if nb_bool_expr > self.config.max_bool_expr: <NEW_LINE> <INDENT> self.add_...
Go through "if" node `node` and counts its boolean expressions if the "if" node test is a BoolOp node
625941e1cc40096d61595cf7
def test_player_123456_with_partial_name(self): <NEW_LINE> <INDENT> self.assertEqual([self.p123456], self.parser.clients.getByMagic('345'))
This test will fail if the b3.clients.Clients.getByMagic method was not patched
625941e163f4b57ef00014b7
def parseArgs(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description='convert2ReadTo4Read, a python script for back converting 2 Illumina sequence reads that have been processed for their barcodes back to a four read set to be reprocessed using dbcAmplicons', epilog='For questions or comments, please cont...
generate main parser
625941e121a7993f00bc809e
def is_too_small_amounts(self, amount_quote, amount_base): <NEW_LINE> <INDENT> if ( amount_quote < Decimal(10) ** -self.market['quote']['precision'] or amount_base < Decimal(10) ** -self.market['base']['precision'] ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Check whether amounts are within asset precision limits :param Decimal amount_quote: QUOTE asset amount :param Decimal amount_base: BASE asset amount :return: bool True = amounts are too small False = amounts are within limits
625941e1656771135c3ebc1b
@verdi_data.group("gaussian.basisset") <NEW_LINE> def cli(): <NEW_LINE> <INDENT> pass
Manage basis sets for GTO-based codes
625941e1a05bb46b383ecbc7
def click_price_policy_grid_first_row_inline_action_button(self): <NEW_LINE> <INDENT> is_clicked = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.logger.info('Start: click price policy grid inline action button') <NEW_LINE> self._price_page.click_price_policy_grid_first_row_inline_action_button() <NEW_LINE> is_clicked =...
Returning click price policy grid inline action button Implementing logging for click price policy grid inline action button functionality :return: True/False
625941e176d4e153a657eeda
def merge_lists(list1, list2): <NEW_LINE> <INDENT> index1 = index2 = 0 <NEW_LINE> sorted_list = [] <NEW_LINE> while index1 < len(list1) and index2 < len(list2): <NEW_LINE> <INDENT> if list1[index1] > list2[index2]: <NEW_LINE> <INDENT> sorted_list.append(list2[index2]) <NEW_LINE> index2 += 1 <NEW_LINE> <DEDENT> elif lis...
Merges two sorted lists.
625941e1c4546d3d9de72ddf
def aggregate_state_estimates_by_county(self, parent): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for division in tqdm( Division.objects.filter(level=self.COUNTY_LEVEL, parent=parent) ): <NEW_LINE> <INDENT> fips = division.code <NEW_LINE> id = division.id <NEW_LINE> aggregated_labels = [] <NEW_LINE> for estimate in divis...
Aggregates county-level estimates for each table within a given state. Creates data structure designed for an export in this format: ...{series}/{year}/{table}/{state_fips}/counties.json
625941e1a219f33f34628d0d
def intersect(segment1, segment2): <NEW_LINE> <INDENT> (x00, y00), (x01, y01) = segment1 <NEW_LINE> R = (x01 - x00, y01 - y00) <NEW_LINE> if R == (0, 0): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> (x10, y10), (x11, y11) = segment2 <NEW_LINE> S = (x11 - x10, y11 - y10) <NEW_LINE> if S == (0, 0): <NEW_LINE> <IN...
If |segment1| or |segment2| has 0 length, returns False. If |segment1| and |segment2| intersect and are colliniar, returns 'collinear'. Otherwise, if |segment1| and |segment2| intersect at exactly one point, returns that point. Otherwise, returns False. Segments should be given in the form ((x0, y0), (x1, y1)).
625941e132920d7e50b2857b
def center_mesh (mesh) : <NEW_LINE> <INDENT> pos = tuple(mesh.position(did) for did in mesh.darts(0) ) <NEW_LINE> if len(pos) == 0 : <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if None in pos : <NEW_LINE> <INDENT> raise UserWarning("One position is not defined") <NEW_LINE> <DEDENT> bary = reduce(lambda x, y: x + y, ...
modify all position in the mesh to center it around its barycenter
625941e1d10714528d60008f
def umfpack_zl_report_numeric(*args): <NEW_LINE> <INDENT> return __umfpack.umfpack_zl_report_numeric(*args)
umfpack_zl_report_numeric(void Numeric, double Control) -> UF_long
625941e123e79379d52ee907
def test_debian_import(self): <NEW_LINE> <INDENT> def _dsc(version): <NEW_LINE> <INDENT> return os.path.join(DEB_TEST_DATA_DIR, 'dsc-native', 'git-buildpackage_%s.dsc' % version) <NEW_LINE> <DEDENT> dsc = _dsc('0.4.14') <NEW_LINE> assert import_dsc(['arg0', dsc]) == 0 <NEW_LINE> repo = ComponentTestGitRepository('git-b...
Test that importing of debian native packages works
625941e1cdde0d52a9e533de
def dump_to(method, raw_data, fields, **kwargs): <NEW_LINE> <INDENT> if method == 'csv': <NEW_LINE> <INDENT> with CsvDumper(kwargs['output_file'], fields) as f: <NEW_LINE> <INDENT> f.dump(raw_data) <NEW_LINE> <DEDENT> <DEDENT> elif method == 'stdout': <NEW_LINE> <INDENT> table_to_stdout(raw_data, fields)
Dumps the data to an appropriate medium. :param method: either 'csv' or 'stdout' :param raw_data: list of dicts containing data from Uber's API :param fields: list of field names of the data to dump :param output_file: (optional) filename of the output when method: 'csv'
625941e1d18da76e23532882
def run_sync(self, fn, *args): <NEW_LINE> <INDENT> return self._do_it(self._run_sync_cb, fn, *args)
Run the given synchronous function in the trio thread, blocking until it is complete. Returns or raises whatever the given function returns or raises. It can also exceptions of its own: Raises: RunFinishedError: if the corresponding call to :func:`trio.run` has already completed. RuntimeError: if you try ca...
625941e13d592f4c4ed1d40c
def __repr__(self): <NEW_LINE> <INDENT> return self.toString(self.alias)
String representation
625941e1d53ae8145f87a611
def scrape_inputs(html): <NEW_LINE> <INDENT> soup = BeautifulSoup(html, 'html.parser') <NEW_LINE> return {inp['name']: inp['value'] for inp in soup.find_all('input') if inp['name'] in ['wpAutoSummary', 'wpEditToken', 'wpEdittime', 'wpWatchthis', 'wpIgnoreWarning', 'wpUpload']}
Function to scrape input data needed to submit. The values input tags wpAutoSummary, wpEditToken and wpEdittime are needed to submit the edit text. wpEditToken, wpWatchthis, wpIgnoreWarning and wpUpload are needed to upload a file
625941e130bbd722463cc170
def __init__(self, name="redis-server", **params): <NEW_LINE> <INDENT> serviceCheck('redis-server', moduleName='redis') <NEW_LINE> Service.__init__(self, name=name, **params) <NEW_LINE> self.getDefaultGlobalMounts()
Initializes a RedisService instance with a set of global parameters Args: name (str): Service name (derived class may wish to override) params: Arbitrary length list of global properties for this service
625941e196565a6dacc8fa73
def visit_token(self, level: int, w: Node) -> Any: <NEW_LINE> <INDENT> assert w.token is not None <NEW_LINE> t = cast(BIN_Terminal, w.terminal) <NEW_LINE> meaning = w.token.match_with_meaning(t) <NEW_LINE> token_index = (w.token.index or 0) - self._first_token_index <NEW_LINE> d = describe_token( token_index, self._tok...
At terminal node, matching a token
625941e1d53ae8145f87a612
def p_expression_hospital(p): <NEW_LINE> <INDENT> if len(p) == 2: <NEW_LINE> <INDENT> p[0] = gisclass.Hospital() <NEW_LINE> <DEDENT> elif len(p) == 3: <NEW_LINE> <INDENT> p[0] = gisclass.Hospital(p[2])
expression : HOSPITAL | HOSPITAL POINT | HOSPITAL LPAREN NAME RPAREN
625941e1377c676e91272550
def get_similarity(self): <NEW_LINE> <INDENT> params = self.similarity_params <NEW_LINE> similarity = params['mode'] <NEW_LINE> axis = lambda a: len(a._keras_shape) - 1 <NEW_LINE> dot = lambda a, b: K.batch_dot(a, b, axes=axis(a)) <NEW_LINE> l2_norm = lambda a, b: K.sqrt(K.sum((a - b) ** 2, axis=axis(a), keepdims=True)...
Specify similarity in configuration under 'similarity_params' -> 'mode' If a parameter is needed for the model, specify it in 'similarity_params' Example configuration: config = { ... other parameters ... 'similarity_params': { 'mode': 'gesd', 'gamma': 1, 'c': 1, } } cosine: dot(a, b...
625941e144b2445a3393243c
def test_parameter_space_order(): <NEW_LINE> <INDENT> class MyTest(rfm.RegressionTest): <NEW_LINE> <INDENT> p0 = parameter([0]) <NEW_LINE> p1 = parameter([0]) <NEW_LINE> p2 = parameter([0]) <NEW_LINE> <DEDENT> assert ['p0', 'p1', 'p2'] == [p for p in MyTest.param_space.params]
FIXME: This can be removed when the old naming scheme is dropped. The order of the parameters is only relevant for the old naming scheme. This test simply ensures that these legacy options are not broken.
625941e1b57a9660fec33c32
def kpi_insert_into_database(): <NEW_LINE> <INDENT> connection.setup(['127.0.0.1'], "pb2") <NEW_LINE> kpi_dict = kpi_get_collection_dictionary() <NEW_LINE> print(kpi_dict) <NEW_LINE> for key in kpi_dict: <NEW_LINE> <INDENT> min_val = kpi_dict[key][2] <NEW_LINE> max_val = kpi_dict[key][3] <NEW_LINE> if not min_val: <NEW...
Put kpi dict into db TODO: change session execute to batch statement for performance
625941e17047854f462a17ae
def run_buildout(prod_user=None, production_cfg=None): <NEW_LINE> <INDENT> opts = dict( prod_user=prod_user or env.get('prod_user'), production_cfg=production_cfg or env.get('production_cfg') or 'production.cfg', ) <NEW_LINE> with cd('/home/%(prod_user)s/niteoweb.%(shortname)s' % opts): <NEW_LINE> <INDENT> sudo('bin/bu...
Run ``bin/buildout -c production.cfg`` in production user's home folder on the production server.
625941e1d58c6744b4258007
def calc_x_woe(data_x, y, range_list): <NEW_LINE> <INDENT> train_woe = [] <NEW_LINE> start = -1 <NEW_LINE> end = -1 <NEW_LINE> woe = calc_woe(y) <NEW_LINE> for value in range_list[1:]: <NEW_LINE> <INDENT> start = end <NEW_LINE> end = value <NEW_LINE> woe_value = woe(data_x, start, end) <NEW_LINE> train_woe.append([woe_...
计算特征分箱的WOE 参数 ------------------------- data_x : 一维numpy数组 y : 一维numpy数组 range_list : list 特征取值范围 返回值 ------------------------- train_woe : list 特征取值范围对应WOE
625941e1f7d966606f6aa3b1
def GetZoomFactor(self): <NEW_LINE> <INDENT> return self._zoomfactor
Returns The Zoom Factor.
625941e1b830903b967e9cb0
def Times(self, lambda_): <NEW_LINE> <INDENT> result = PVectorMatrix(self.v.dim) <NEW_LINE> result.v = self.v.Times(lambda_) <NEW_LINE> result.M = (self.M).Times(lambda_) <NEW_LINE> return result
generated source for method Times
625941e10383005118ecf98a
def calc_Eauxf_fw(Vfw_m3h, deltaP_kPa, b): <NEW_LINE> <INDENT> Cpump = 0.97 <NEW_LINE> if Vfw_m3h > 0.0: <NEW_LINE> <INDENT> Phydr_kW = deltaP_kPa * Vfw_m3h * 1 / 3600 <NEW_LINE> feff = (1.5 * b) / (0.015 * (Phydr_kW) ** 0.74 + 0.4) <NEW_LINE> epmp_eff = feff * Cpump * 1 ** -0.94 <NEW_LINE> Eaux_fw = epmp_eff * Phydr_k...
#Following EN 15316-3-2:2007 Annex F :param Vfw_m3h: :param nf: :return:
625941e132920d7e50b2857c
def print_site_indel_snp(mt): <NEW_LINE> <INDENT> site_ids = ['MOP', 'MAP', 'KWP', 'AAP', 'CTP'] <NEW_LINE> for i in site_ids: <NEW_LINE> <INDENT> site_mt = mt.filter_cols(mt.siteID == i) <NEW_LINE> del_avg = site_mt.aggregate_cols(hl.agg.sum(site_mt.sample_qc.n_deletion)) / site_mt.count_cols() <NEW_LINE> ins_avg = si...
Prints out the average indel and SNP counts for each site :param mt: NGAP hail matrix table with info from 5 pilot data sites and hl.sample_qc() run :return: print statement with average indel and SNP counts for each site
625941e1596a897236089e65
def test_check_required_field(self): <NEW_LINE> <INDENT> self.go_to_submenu('Applications') <NEW_LINE> self.select_and_click_action_for_app('quick-add', self.mockapp_id) <NEW_LINE> self.driver.find_element_by_xpath(c.ButtonSubmit).click() <NEW_LINE> self.check_error_message_is_present('This field is required.') <NEW_LI...
Test required fields Test checks that fields with parameter 'required=True' in yaml form are truly required and can't be omitted Scenario: 1. Navigate to Application Catalog > Applications 2. Start to create MockApp 3. Don't type app name in the 'Application Name' field that is required and click 'Nex...
625941e15fdd1c0f98dc05dd
def getRoleInfoDevices(self, role): <NEW_LINE> <INDENT> roleInfo = self.getRoleInfo(role) <NEW_LINE> if roleInfo is None: <NEW_LINE> <INDENT> self.log.error("could not get device list because role '%s' does not exist", role) <NEW_LINE> return {} <NEW_LINE> <DEDENT> return roleInfo.devices
Get role information for the specified role :param role: role :type role: :class:`Roles` :returns: device infos :rtype: dict
625941e182261d6c526ab84d
def destroy_channels(self): <NEW_LINE> <INDENT> for v in self.__dict__.values(): <NEW_LINE> <INDENT> if isinstance(v, PyDMChannel): <NEW_LINE> <INDENT> v.disconnect()
Method invoked when the channels associated with the widget must be destroyed.
625941e14f6381625f114de4
@view_config(renderer='json', request_method='GET', route_name='pet') <NEW_LINE> def get_pet(context, request): <NEW_LINE> <INDENT> return {}
Get a single pet request.matchdict: * 'pet_id' Pet's Unique identifier `{"type": "string", "required": true, "pattern": "^[a-zA-Z0-9-]+$"}`
625941e16e29344779a629b9
def __exit__(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.graph_type == "dense": <NEW_LINE> <INDENT> identify_dense_edges(self.trace) <NEW_LINE> self.trace.graph["vectorized_map_data_info"] = get_vectorized_map_data_info(self.trace) <NEW_LINE> <DEDENT> return super(TraceMessenger, self).__exit__(*...
Adds appropriate edges based on cond_indep_stack information upon exiting the context.
625941e1fff4ab517eb2f7e6
def add_media(self, media, **kwargs): <NEW_LINE> <INDENT> self._parse_args_from_dict(media, **kwargs) <NEW_LINE> logging.debug("Media: %s", self.media) <NEW_LINE> if path.exists(self.media): <NEW_LINE> <INDENT> new_files = self._file_handler(self.media) <NEW_LINE> if new_files is None: <NEW_LINE> <INDENT> self.push.fai...
Entry point function for adding media via the MHandler object. Required argument: - media valid path to a file or a folder of media to be added. Assumes structure: :: /path/to/<media type>/<media> Other valid arguments: - type Int in range [1, 2, 3, 4]. Declare a specific ...
625941e14428ac0f6e5bab9d
def test_months_not_capitalized(): <NEW_LINE> <INDENT> for item in MONTHS_WITH_30: <NEW_LINE> <INDENT> assert days_in_month(item.lower()) == 30 <NEW_LINE> <DEDENT> for item in MONTHS_WITH_28_or_29: <NEW_LINE> <INDENT> assert days_in_month(item.lower()) == 28 or 29 <NEW_LINE> <DEDENT> for item in MONTHS_WITH_31: <NEW_LI...
Test months not capitalized properly
625941e1eab8aa0e5d26df02
def test_POST_page_data_for_confirmation(self): <NEW_LINE> <INDENT> post_request = DummyRequest(route='/create') <NEW_LINE> post_request.POST["create_page"] = "confirmation" <NEW_LINE> post_request.POST["viewing_date"] = datetime.datetime.today().strftime("%d/%m/%Y") <NEW_LINE> post_request.POST["viewing_hour"] = datet...
This method will test the ability of the create view to access the correct page data from POST. The expected result of this test is for the correct page data to be available for the 'confirmation' page.
625941e14c3428357757c6cf
def test_Cases_prop_LMs1(): <NEW_LINE> <INDENT> actual1 = cases1a.LMs <NEW_LINE> load_params['p'] = 2 <NEW_LINE> cases1c2 = la.distributions.Case(load_params, dft.mat_props) <NEW_LINE> cases1c2.apply(dft.geo_inputs['5-ply']) <NEW_LINE> load_params['p'] = 3 <NEW_LINE> cases1c3 = la.distributions.Case(load_params, dft.ma...
Check viewing inside cases gives correct list.
625941e15510c4643540f784