code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def prediction_error(self, X, y): <NEW_LINE> <INDENT> y_predicted = self.predict_classes(X) <NEW_LINE> if y_predicted is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> error = len([i for i in range(len(y)) if y_predicted[i] != y[i]]) <NEW_LINE> return error
Returns prediciton error given data. Args: X (numpy array): Data y (numpy array): True outputs
625941da8c0ade5d55d3ec76
def protocol_spanning_tree_rstp_hello_time(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> protocol = ET.SubElement(config, "protocol", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete_protocol', False) is True: <NEW_LINE> <INDENT> delete_protocol = config.find('....
Auto Generated Code
625941da67a9b606de4a8171
def strong_foot_flag(df): <NEW_LINE> <INDENT> tags = df['tags'] <NEW_LINE> foot = df['foot'] <NEW_LINE> if 401 in tags: <NEW_LINE> <INDENT> passFoot = 'L' <NEW_LINE> <DEDENT> elif 402 in tags: <NEW_LINE> <INDENT> passFoot = 'R' <NEW_LINE> <DEDENT> elif 403 in tags: <NEW_LINE> <INDENT> passFoot = 'H' <NEW_LINE> <DEDENT>...
Compare foot of pass with footedness of player Provides flag = 1 if pass played with strong foot of the player
625941dafbf16365ca6f6481
def __init__(self, G: nx.Graph) -> None: <NEW_LINE> <INDENT> self.G = G <NEW_LINE> self.directed = G.is_directed()
:param G: Networkx Graph
625941da656771135c3ebb2b
def add_extra_layer_warning(crypto_message): <NEW_LINE> <INDENT> tag = EXTRA_LAYER_WARNING <NEW_LINE> if tag in crypto_message.get_email_message().get_content(): <NEW_LINE> <INDENT> log_message('not adding tag because it is already in crypto message content: {}'.format(tag)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Add a warning that there's still a layer of encryption.
625941dad99f1b3c44c67844
def fixpointmethod(self, cfg_node): <NEW_LINE> <INDENT> if cfg_node.ast_type == Compare.__name__ or cfg_node.ast_type == Call.__name__: <NEW_LINE> <INDENT> JOIN = self.join(cfg_node) <NEW_LINE> JOIN.update(self.annotated_cfg_nodes[cfg_node]) <NEW_LINE> cfg_node.new_constraint = JOIN <NEW_LINE> <DEDENT> elif isinstance(...
Setting the constraints of the given cfg node obeying the liveness analysis rules.
625941dafff4ab517eb2f6f7
def setCompositeMode(self, mode): <NEW_LINE> <INDENT> self.setCompositeEx(mode, None, None, useTransitions=False)
legacy command
625941da56b00c62f0f14914
def curvature_optimisation_func_lensmaker(curv_1 = 0.002, focal_length = 100., diameter = 5., thickness = 5., ref_index = 1.5): <NEW_LINE> <INDENT> curv_2 = lensmaker_equation(curv_1, focal_length, thickness, ref_index) <NEW_LINE> if curv_2 == 0: <NEW_LINE> <INDENT> curv_2 -= 1e-13 <NEW_LINE> <DEDENT> if curv_1 == 0: <...
This function is used to minimise the RMS spread of a beam of given diameter, propagated through a lens of given thickness, by changing the curvatures of the two sides of the lens. It is meant to be used in conjunction with an optimisation function. This function is bounded by the lensmaker equation, so it only requir...
625941dacdde0d52a9e532ef
def get_host_tags(self): <NEW_LINE> <INDENT> r = [] <NEW_LINE> names = self.rg.tags.keys() <NEW_LINE> names.sort() <NEW_LINE> for name in names: <NEW_LINE> <INDENT> r.append((name, self.rg.tags[name])) <NEW_LINE> <DEDENT> return r
Get the hosts tags sorted by names.
625941daa934411ee375194e
def colors(self): <NEW_LINE> <INDENT> c = self.colors_ <NEW_LINE> if callable(c): <NEW_LINE> <INDENT> self.warning('Callable Parameter value returned, ', callable(c)) <NEW_LINE> c = c() <NEW_LINE> <DEDENT> return c
Return the complete list of palette colors in tuple form
625941da9b70327d1c4e1090
def average_qp_to_vertices(self, data_qp, integral): <NEW_LINE> <INDENT> region = self.region <NEW_LINE> n_cells = region.get_n_cells(True) <NEW_LINE> if n_cells != data_qp.shape[0]: <NEW_LINE> <INDENT> msg = 'incomatible shape! (%d == %d)' % (n_cells, data_qp.shape[0]) <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDE...
Average data given in quadrature points in region elements into region vertices. .. math:: u_n = \sum_e (u_{e,avg} * area_e) / \sum_e area_e = \sum_e \int_{area_e} u / \sum area_e
625941da8a43f66fc4b5431c
def summary_DAG(G): <NEW_LINE> <INDENT> num_nodes = G.number_of_nodes() <NEW_LINE> num_edges = G.number_of_edges() <NEW_LINE> num_real_nodes = G.graph['n'] <NEW_LINE> average_clustering = nx.average_clustering(nx.to_undirected(G)) <NEW_LINE> transitivity = nx.transitivity(nx.to_undirected(G)) <NEW_LINE> transitivity_di...
Summary information of a DAG. The information reflect structural features of a DAG that may influence on the performance of corresponding neural network. Returns: -------- num_nodes : number of nodes num_edges : number of edges num_real_nodes : number of real nodes, except the unique input and output nodes. average ...
625941dad99f1b3c44c67845
def test(self): <NEW_LINE> <INDENT> os.chdir(self.teststmpdir) <NEW_LINE> status = process.system('./mem_integrity_test -s %s' % self.scenario_arg, shell=True, ignore_status=True) <NEW_LINE> if status != 0: <NEW_LINE> <INDENT> if status == 201: <NEW_LINE> <INDENT> self.cancel("System does not have numa/memory to run th...
Execute Integrity tests
625941da8e05c05ec3eea630
def test_0015_create_tool_repository( self ): <NEW_LINE> <INDENT> category = self.create_category( name='Test 0120', description='Description of test 0120' ) <NEW_LINE> self.logout() <NEW_LINE> self.login( email=common.test_user_1_email, username=common.test_user_1_name ) <NEW_LINE> strings_displayed = [ 'Repository %s...
Create and populate the blastxml_to_top_descr_0120 repository
625941da7d43ff24873a2f5b
def postcmd(self, stop, line): <NEW_LINE> <INDENT> if self.p.online and self.dynamic_temp: <NEW_LINE> <INDENT> self.p.send_now("M105") <NEW_LINE> <DEDENT> self.prompt = self.promptf() <NEW_LINE> return stop
A hook we override to generate prompts after each command is executed, for the next prompt. We also use it to send M105 commands so that temp info gets updated for the prompt.
625941da4e4d5625662d468f
def pathSum(self, root, path_sum): <NEW_LINE> <INDENT> self.num_of_sum = 0 <NEW_LINE> self.dfs(root, path_sum) <NEW_LINE> return self.num_of_sum
:type root: TreeNode :type sum: int :rtype: int
625941da796e427e537b0881
def get_unique_periods(filelist, frequency): <NEW_LINE> <INDENT> if frequency == 'monthly': <NEW_LINE> <INDENT> months = set(get_month_label(filelist)) <NEW_LINE> return list(months) <NEW_LINE> <DEDENT> elif frequency == 'daily': <NEW_LINE> <INDENT> days = set(get_day_label(filelist)) <NEW_LINE> return list(days) <NEW_...
Extract all unique values in the filelist (do this using set )
625941da30c21e258bdfa758
def _update_changelist_description(ctx, change_num, description): <NEW_LINE> <INDENT> fmt = '@{change_num:<5} {msg}' <NEW_LINE> change = p4gf_util.first_dict_with_key( ctx.p4run('change', '-o', str(change_num)) , 'Description') <NEW_LINE> old_desc = change['Description'] <NEW_LINE> if not old_desc: <NEW_LINE> <INDENT> ...
Set on echangelist's description.
625941da3d592f4c4ed1d322
def calculate(self, atoms=None, properties=None, system_changes=None): <NEW_LINE> <INDENT> if system_changes is None: <NEW_LINE> <INDENT> system_changes = ['positions', 'numbers', 'cell', 'pbc', 'charges', 'magmoms'] <NEW_LINE> <DEDENT> if properties is None: <NEW_LINE> <INDENT> properties = ['energy'] <NEW_LINE> <DEDE...
PDF Calculator Parameters ---------- atoms: Atoms object Contains positions, unit-cell, ... properties: list of str List of what needs to be calculated. Can be any combination of 'energy', 'forces' system_changes: list of str List of what has changed since last calculation. Can be any combination...
625941dabd1bec0571d908e9
def process_response(self, request, response, spider): <NEW_LINE> <INDENT> is_ban = getattr(spider, 'response_is_ban') <NEW_LINE> ban = is_ban(request, response) <NEW_LINE> if ban: <NEW_LINE> <INDENT> url = request.meta.get('redirect_urls', [request.url])[0] if request.meta else request.url <NEW_LINE> self.set_proxy(re...
Interesting to check cached page
625941da50485f2cf553d055
def countNumbersWithUniqueDigits(self, n): <NEW_LINE> <INDENT> if n==0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> res = 9 <NEW_LINE> for i in range(n-1): <NEW_LINE> <INDENT> res *= 9-i <NEW_LINE> <DEDENT> return res + self.countNumbersWithUniqueDigits(n-1)
:type n: int :rtype: int
625941da3539df3088e2e605
def __init__ (self, request_cfg=None, topology_cfg=None, **kwargs): <NEW_LINE> <INDENT> super(DynamicallyGeneratedTestCase, self).__init__(**kwargs) <NEW_LINE> self.request_cfg = request_cfg <NEW_LINE> self.new_req = False <NEW_LINE> self.topology_cfg = topology_cfg <NEW_LINE> self.new_topo = False <NEW_LINE> log.debug...
:type request_cfg: dict :type topology_cfg: dict :type kwargs: dict
625941da63b5f9789fde73a0
def getScriptExecutable(self): <NEW_LINE> <INDENT> return self.__strScriptExecutable
Returns the executable path
625941da167d2b6e31218e4f
def SetStatusText(self, text): <NEW_LINE> <INDENT> class event: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> event.text = text <NEW_LINE> self.status_text(event)
SetStatusText(self, text) --> None Sets the status text of the frame
625941daf7d966606f6aa2c1
def __ScanTSP(self): <NEW_LINE> <INDENT> fn = os.path.join(self.workdir,self.__filename) <NEW_LINE> if not os.path.isfile(fn): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> line = b'' <NEW_LINE> try: <NEW_LINE> <INDENT> fh = open(fn,'rb') <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> temp = fh...
this function is to scan the tsp file, and returns the string of data where the lib information locates.
625941daf9cc0f698b1408b3
def repl_absolute(m, base_path): <NEW_LINE> <INDENT> link = m.group(0) <NEW_LINE> try: <NEW_LINE> <INDENT> scheme, netloc, path, params, query, fragment, is_url, is_absolute = util.parse_url(m.group('path')[1:-1]) <NEW_LINE> if (not is_absolute and not is_url): <NEW_LINE> <INDENT> path = util.url2path(path) <NEW_LINE> ...
Replace path with absolute path.
625941da01c39578d7e750f6
def export(self, checkpoint_path=None, export_dir_base=None): <NEW_LINE> <INDENT> estimator = self._make_estimator() <NEW_LINE> if checkpoint_path is not None and tf.gfile.IsDirectory(checkpoint_path): <NEW_LINE> <INDENT> checkpoint_path = tf.train.latest_checkpoint(checkpoint_path) <NEW_LINE> <DEDENT> if export_dir_ba...
Exports a model. Args: checkpoint_path: The checkpoint path to export. If ``None``, the latest is used. export_dir_base: The base directory in which a timestamped subdirectory containing the exported model will be created. Defaults to ``$MODEL_DIR/export/manual``. Returns: The string path to the exporte...
625941da76d4e153a657edec
def test_returns_json(self): <NEW_LINE> <INDENT> response = gateway_languages_autocomplete(self.request) <NEW_LINE> self.assertIsInstance(response, JsonResponse) <NEW_LINE> self.assertIn("results", response.content) <NEW_LINE> self.assertIn("count", response.content) <NEW_LINE> self.assertIn("term", response.content)
Must return JsonResponse with results, count, and term
625941dadd821e528d63b462
def test_on_batch( self, x_batch: torch.Tensor, y_batch: torch.Tensor, weight_map_batch: Optional[torch.Tensor] = None, ) -> float: <NEW_LINE> <INDENT> y_hat_batch = self.predict_on_batch(x_batch) <NEW_LINE> args = [y_hat_batch, y_batch] <NEW_LINE> if weight_map_batch is not None: <NEW_LINE> <INDENT> args.append(weight...
Test model on a batch of inputs and targets. Parameters ---------- x_batch Batched input. y_batch Batched target. weight_map_batch Optional batched weight map. Returns ------- float Loss as evaluated by self.criterion.
625941da4428ac0f6e5baaae
def pre_order(self): <NEW_LINE> <INDENT> yield self <NEW_LINE> for child in self.children: <NEW_LINE> <INDENT> for node in child.post_order(): <NEW_LINE> <INDENT> yield node
Returns a pre-order iterator for the tree.
625941dac432627299f04f02
def setLandscapeOrientation(self): <NEW_LINE> <INDENT> pass
setLandscapeOrientation(self)
625941dab5575c28eb68e2bc
def message(self): <NEW_LINE> <INDENT> raise NotImplementedError
Returns a string describing the failure in more detail.
625941da23e79379d52ee81b
def p_float(self, p): <NEW_LINE> <INDENT> if '.' in p[1]: <NEW_LINE> <INDENT> p[0] = FloatConstant(p[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = IntConstant(p[1])
constant : NUMBER
625941daf8510a7c17cf99b8
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineObject2): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941da460517430c39443a
def heap_sort(values): <NEW_LINE> <INDENT> heapsort = HeapSort(values) <NEW_LINE> return heapsort.heap_sort()
堆排序
625941da26238365f5f0f12c
def move_and_score(self, direction): <NEW_LINE> <INDENT> score = 0 <NEW_LINE> board_to_left = np.rot90(self.board, -direction) <NEW_LINE> for row in range(self.size): <NEW_LINE> <INDENT> core, score_row = _merge_and_score(board_to_left[row]) <NEW_LINE> score += score_row <NEW_LINE> board_to_left[row, :len(core)] = core...
direction: 0: left 1: down 2: right 3: up
625941da8e05c05ec3eea631
def parse_json(self, page, exactly_one=True, output='latlon'): <NEW_LINE> <INDENT> if not isinstance(page, basestring): <NEW_LINE> <INDENT> page = util.decode_page(page) <NEW_LINE> <DEDENT> self.doc = json.loads(page) <NEW_LINE> places = self.doc.get('results', []) <NEW_LINE> if not places: <NEW_LINE> <INDENT> check_st...
Parse returned json feed of geocoded results Returns various forms of the geocoded 'location' from the JSON feed. Type of locations include latitude and longitude, address, bounding box (viewport), geometry information, or the entire JSON feed.
625941da9f2886367277ab46
def train(self): <NEW_LINE> <INDENT> pass
Update model parameters :return:
625941dae5267d203edcdf54
def complete_batch(self): <NEW_LINE> <INDENT> if not hasattr(self, 'batchrequest'): <NEW_LINE> <INDENT> raise BatchError("There's no open batch request to complete") <NEW_LINE> <DEDENT> if self.endpoint is None: <NEW_LINE> <INDENT> raise BatchError("There's no batch processor endpoint to which to send a batch request")...
Closes a batch request, submitting it and dispatching the subresponses. If no batch request is open, a `BatchError` is raised.
625941da090684286d50efa2
def csv_to_tuples(path, out_path=None, force=False): <NEW_LINE> <INDENT> ENTITY_ID_FILE = "entity2id.txt" <NEW_LINE> RELATION_ID_FILE = "relation2id.txt" <NEW_LINE> TUPLE_FILE = "train2id.txt" <NEW_LINE> CONCEPNET_SIZE = 32755210 <NEW_LINE> def is_english(entity): <NEW_LINE> <INDENT> return entity[:6] == b"/c/en/" <NEW...
@brief Transform the ConceptNet csv files to the toples format that OpenKE takes as input @param path the path of the file @param out_path the path to store the tuples. If None, then the tuples will be stored in the same directory as the csv file @param force if True, ignore existing file and re-...
625941da4c3428357757c5e1
def atanh(x, context=None): <NEW_LINE> <INDENT> return _apply_function_in_current_context( BigFloat, mpfr.mpfr_atanh, (BigFloat._implicit_convert(x),), context, )
Return the inverse hyperbolic tangent of x.
625941da07d97122c4178b4b
def mouth_display(self, img_code="", x=0, y=0, refresh=True): <NEW_LINE> <INDENT> self.display_manager.set_active(self.name) <NEW_LINE> self.bus.emit(Message('enclosure.mouth.display', {'img_code': img_code, 'xOffset': x, 'yOffset': y, 'clearPrev': refresh}))
Display images on faceplate. Currently supports images up to 16x8, or half the face. You can use the 'x' parameter to cover the other half of the faceplate. Args: img_code (str): text string that encodes a black and white image x (int): x offset for image y (int): y offset for image refresh (bool)...
625941daac7a0e7691ed4382
def destroy(self, instance): <NEW_LINE> <INDENT> instance.is_active = False <NEW_LINE> instance.save()
Disable trip.
625941da377c676e91272463
def __init__(self, subcpath: Union[List[str], Tuple[str, ...]] = ()) -> None: <NEW_LINE> <INDENT> self.subcpath: List[str] = list(subcpath) <NEW_LINE> self._cache: Dict[Tuple[str, str, Optional[str]], AbstractKCorpus] = {}
Args: subcpath: a list of paths where user corpora are located
625941da956e5f7376d71127
def get_short_refs(self, product): <NEW_LINE> <INDENT> rv = {} <NEW_LINE> for commit, ref in self.get_full_refs(product): <NEW_LINE> <INDENT> ref_name = None <NEW_LINE> if self.is_ref_remote(ref): <NEW_LINE> <INDENT> ref_name = ref[len('refs/remotes/'):] <NEW_LINE> <DEDENT> elif self.is_ref_branch(ref): <NEW_LINE> <IND...
Return map of named refs (branches or tags) to commit hashes.
625941da60cbc95b062c67fe
def test_index_view_with_no_tracks(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('session:tracks')) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, "No tracks are available") <NEW_LINE> self.assertQuerysetEqual(response.context['track_list'], [])
If no tracks exist, an appropriate message should be displayed.
625941da32920d7e50b2848d
def is_valid_port_name(name): <NEW_LINE> <INDENT> if future.utils.isidentifier(name) and not keyword.iskeyword(name): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Validate port name
625941dacad5886f8bd27294
def encode(self, src_sents_var, src_sents_len): <NEW_LINE> <INDENT> src_token_embed = self.src_embed(src_sents_var) <NEW_LINE> packed_src_token_embed = pack_padded_sequence(src_token_embed, src_sents_len) <NEW_LINE> src_encodings, (last_state, last_cell) = self.encoder_lstm(packed_src_token_embed) <NEW_LINE> src_encodi...
encode the source sequence :return: src_encodings: Variable(batch_size, src_sent_len, hidden_size * 2) last_state, last_cell: Variable(batch_size, hidden_size)
625941dad10714528d5fffa1
def add_type_and_hosting_device_info(self, context, router, binding_info_db=None, schedule=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if binding_info_db is None: <NEW_LINE> <INDENT> binding_info_db = self._get_router_binding_info(context, router['id']) <NEW_LINE> <DEDENT> <DEDENT> except RouterBindingInfoError...
Adds type and hosting device information to a router.
625941daa8ecb033257d3387
def arraysize(self, q_class): <NEW_LINE> <INDENT> return self._config["queryClasses"][q_class].get("arraysize")
Return array size for fetchmany(). Parameters ---------- q_class : `str` Query class name. Returns ------- arraysize : `int` Array size to use.
625941dade87d2750b86004f
def _create_alien(self, alien_number, row_number): <NEW_LINE> <INDENT> alien = Alien(self) <NEW_LINE> alien_width, alien_height = alien.rect.size <NEW_LINE> alien.x = alien_width + 2 * alien_width * alien_number <NEW_LINE> alien.rect.x = alien.x <NEW_LINE> alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_...
Create an alien and place it in the row. :meta public:
625941da5fcc89381b1e197c
def assignTotalRevenue(): <NEW_LINE> <INDENT> productionDictionary=populate() <NEW_LINE> count=0 <NEW_LINE> for film in dataset: <NEW_LINE> <INDENT> if (film['Production'] in productionDictionary): <NEW_LINE> <INDENT> productionDictionary[film['Production']]+=float(film['BoxOffice']) <NEW_LINE> <DEDENT> <DEDENT> return...
The function returns a dictionary in which the keys - the names of the produciton houses(that appear in the dataset) the values - the total revenue generrated by the films produced by them (only the films present in the dataset are considered here
625941da23e79379d52ee81c
def delete(self, key): <NEW_LINE> <INDENT> i = self.quadratic_probe(key) <NEW_LINE> if self.table[i] is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.table[i] = None <NEW_LINE> self.size -= 1
Deletes the key in the hash table by setting self.table[i] to None :param key: the key of the node to remove from the hash table :return: None
625941daaad79263cf390d00
def remove_event_handler(name, func): <NEW_LINE> <INDENT> for e in list(_events.get(name, [])): <NEW_LINE> <INDENT> if e.func is func: <NEW_LINE> <INDENT> _events[name].remove(e)
Remove `func` from the handlers for event `name`.
625941da3eb6a72ae02ec79e
def guess_type(value): <NEW_LINE> <INDENT> for name in _INFER_TYPE_ORDER: <NEW_LINE> <INDENT> cast = getattr(types, 'cast_%s' % name) <NEW_LINE> result = cast('default', value) <NEW_LINE> if result != config.ERROR: <NEW_LINE> <INDENT> return name
Guess the type for a value
625941daec188e330fd5aa55
def atmosphere_geo(altg,disa): <NEW_LINE> <INDENT> g = gravity() <NEW_LINE> R,gam,Cp,Cv = gas_data() <NEW_LINE> Zi = numpy.array([0., 11000., 20000.,32000., 47000., 50000.]) <NEW_LINE> dtodzi = numpy.array([-0.0065, 0., 0.0010, 0.0028, 0.]) <NEW_LINE> Z = numpy.zeros_like(Zi) <NEW_LINE> dtodz = numpy.zeros_like(dtodzi)...
Pressure from pressure altitude from ground to 50 km
625941da8e71fb1e9831da63
def status(word, strikes, letters): <NEW_LINE> <INDENT> spaced_word = ' '.join(word) <NEW_LINE> print(str((6 - strikes)) + ' Strikes remaining!') <NEW_LINE> print('Guessed letters: ' + letters) <NEW_LINE> print(spaced_word) <NEW_LINE> print('\n')
:param word: List, The word that the user has guessed so far :param strikes: Int, The numbers of strikes the user has used so far :param letters: String, The letters the user has already guessed
625941da009cb60464c6366b
def __init__(self, wrappedFactory): <NEW_LINE> <INDENT> self._wrappedFactory = wrappedFactory <NEW_LINE> self._onConnection = defer.Deferred(canceller=self._canceller)
@param wrappedFactory: A provider of I{IProtocolFactory} whose buildProtocol method will be called and whose resulting protocol will be wrapped.
625941da85dfad0860c3b117
def rsm_func(ref, gamma_diff_cal): <NEW_LINE> <INDENT> return -20 * np.log10(ref[0]) - ref[1] * ref[0] - ref[2] - gamma_diff_cal
RSM structure with correction param gamma_diff_cal.
625941da6e29344779a628cb
@effect() <NEW_LINE> def outline(tensor, shape, sobel_metric=1, invert=False, time=0.0, speed=1.0): <NEW_LINE> <INDENT> height, width, channels = shape <NEW_LINE> value_shape = value.value_shape(shape) <NEW_LINE> values = value.value_map(tensor, shape, keepdims=True) <NEW_LINE> edges = sobel_operator(values, value_shap...
Superimpose sobel operator results (cartoon edges) :param Tensor tensor: :param list[int] shape: :param DistanceMetric|int sobel_metric: Sobel distance metric
625941da711fe17d82542621
def import_stopwords(filename, hashtable): <NEW_LINE> <INDENT> file_object = open(filename, 'r') <NEW_LINE> for line in file_object: <NEW_LINE> <INDENT> listWords = line.split(" ") <NEW_LINE> <DEDENT> for word in listWords: <NEW_LINE> <INDENT> hashtable.put(word, word) <NEW_LINE> <DEDENT> print(len(listWords)) <NEW_LIN...
Returns a hashtable object of either seperate chaining, linear probing, or quadratic probing :param filename: the name of the file hashtable: (Hashtable) object which is either 3 of the implementations defined above :return:
625941da187af65679ca53da
def value(self): <NEW_LINE> <INDENT> min = int(float(self._minwidget.text() or "0")) <NEW_LINE> max = int(float(self._maxwidget.text() or "0")) <NEW_LINE> return min, max
Get the current range. :rtype: list[int]
625941daf548e778e58cd83a
def xtal_get_local_rot(symbols, scaled_positions, cell, iat, dist_cut_, equivalent_indices=[], locrot=None, fm_direction=None, Nmax=4, tol=1.e-5, log=sys.stdout): <NEW_LINE> <INDENT> mol = xtal_extract_mol(symbols, scaled_positions, cell, iat, dist_cut_, equivalent_indices=equivalent_indices, locrot=locrot, fm_directio...
Get rotation operations of center atom iat in crystal.
625941dad18da76e23532793
def input(self, pin): <NEW_LINE> <INDENT> return self.input_pins([pin])[0]
Get the input value on a pin. This method returns the state of the input on a given pin of the MCP23008 device. :param pin: pin to read :return bool state of pin
625941da1f5feb6acb0c4e07
def __init__(self,fp): <NEW_LINE> <INDENT> self.rules = list() <NEW_LINE> seen, self.variables = set(), list() <NEW_LINE> for rule in fp.get_rules(): <NEW_LINE> <INDENT> r = Rule(rule) <NEW_LINE> if r.head is None: continue <NEW_LINE> self.rules.append(r) <NEW_LINE> for x in r.variables: <NEW_LINE> <INDENT> if x.hash()...
builds the program control flow graph (CFG)
625941dab7558d58953c51cb
def test_ordinal_scale(self): <NEW_LINE> <INDENT> choices = [("last", 3), ("middle", 2), ("first", 1)] <NEW_LINE> for choice in choices: <NEW_LINE> <INDENT> self._ordinal_choice(label=choice[0], score=choice[1]) <NEW_LINE> <DEDENT> expected = "{} [first (1), middle (2), last (3)]".format(self.scale.name) <NEW_LINE> sel...
Ensure proper string representation
625941dabe7bc26dc91cd8b6
def prepareForTransfer(self): <NEW_LINE> <INDENT> lst={} <NEW_LINE> for i,p in iteritems(self.plots): <NEW_LINE> <INDENT> lst[str(i)]={ "nr" : i, "spec" : p.spec.getDict(), "id" : p.spec.id, "data" : p.data.lineNr } <NEW_LINE> <DEDENT> return lst
Makes sure that the data about the plots is to be transfered via XMLRPC
625941daa934411ee375194f
@portal.route('/initial-queries', methods=['GET', 'POST']) <NEW_LINE> def initial_queries(): <NEW_LINE> <INDENT> if not current_user(): <NEW_LINE> <INDENT> current_app.logger.debug("initial_queries (no user!) -> landing") <NEW_LINE> return redirect('/') <NEW_LINE> <DEDENT> user = get_user(current_user().id, 'edit') <NE...
Initial consent terms, initial queries view function
625941da66656f66f7cbc467
@exporter.export <NEW_LINE> @preprocess_and_wrap() <NEW_LINE> def lat_lon_grid_deltas(longitude, latitude, x_dim=-1, y_dim=-2, geod=None): <NEW_LINE> <INDENT> if latitude.ndim != longitude.ndim: <NEW_LINE> <INDENT> raise ValueError('Latitude and longitude must have the same number of dimensions.') <NEW_LINE> <DEDENT> i...
Calculate the actual delta between grid points that are in latitude/longitude format. Parameters ---------- longitude : array_like Array of longitudes defining the grid. If not a `pint.Quantity`, assumed to be in degrees. latitude : array_like Array of latitudes defining the grid. If not a `pint.Quantity`...
625941da30dc7b7665901c1f
def add_list_function(self, list_name, list_func): <NEW_LINE> <INDENT> if self.get_list_function(list_name) is not None: <NEW_LINE> <INDENT> msg = ('A list with name {0} already exists in this design doc' .format(list_name)) <NEW_LINE> raise CloudantArgumentError(msg) <NEW_LINE> <DEDENT> self.lists.__setitem__(list_nam...
Appends a list function to the locally cached DesignDocument indexes dictionary. :param str list_name: Name used to identify the list function. :param str list_func: Javascript list function.
625941daec188e330fd5aa56
def _get_buy_amount_by_cash_limit(self, trade_price, cash, cost_ratio): <NEW_LINE> <INDENT> max_trade_amount = 0 <NEW_LINE> if cash >= self.min_cost: <NEW_LINE> <INDENT> critical_price = self.min_cost / cost_ratio + self.min_cost <NEW_LINE> if cash >= critical_price: <NEW_LINE> <INDENT> max_trade_amount = cash / (1 + c...
return the real order amount after cash limit for buying. Parameters ---------- trade_price : float position : cash cost_ratio : float Return ---------- float the real order amount after cash limit for buying.
625941da5e10d32532c5f1e2
def queryString(key, subKey, name): <NEW_LINE> <INDENT> for sam in _readAccessModes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> keyHandle = winreg.OpenKey(key, subKey, 0, sam) <NEW_LINE> try: <NEW_LINE> <INDENT> return str(winreg.QueryValueEx(keyHandle, name)[0]) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> winre...
Queries a string value from the Windows registry. On 64-bit Windows this function will first try to query the value from the 64-bit registry. If the value doesn't exist there it will then try to find the value in the 32-bit registry. @param key: The key to query, eg: winreg.HKEY_LOCAL_MACHINE @type key: string @para...
625941da3346ee7daa2b3029
def passPower(stateFoot, dest, maxPower, thetaPass): <NEW_LINE> <INDENT> dist = stateFoot.distance_ball(dest) <NEW_LINE> return maxPower*(1.-exp(-(thetaPass*dist)))
Renvoie la force avec laquelle on va faire une passer selon la distance entre la balle et le recepteur
625941da66656f66f7cbc468
def detect_faces(bucket, key, attributes=['ALL'], region='us-west-2'): <NEW_LINE> <INDENT> rekognition = boto3.client('rekognition', region) <NEW_LINE> response = rekognition.detect_faces( Image = { "S3Object": { "Bucket": bucket, "Name": key, } }, Attributes = attributes, ) <NEW_LINE> return response['FaceDetails']
Returns the AWS Rekognition detect_faces() response on an image stored in an S3 bucket.
625941dabaa26c4b54cb13d8
def numJewelsInStones(self, J, S): <NEW_LINE> <INDENT> c = 0 <NEW_LINE> for el in J: <NEW_LINE> <INDENT> if el in S: <NEW_LINE> <INDENT> c += S.count(el) <NEW_LINE> <DEDENT> <DEDENT> return c
:type J: str :type S: str :rtype: int
625941da7b25080760e39714
def check_if_user_exists_return_id(username, array_of_all_in_thread): <NEW_LINE> <INDENT> for user in array_of_all_in_thread: <NEW_LINE> <INDENT> if user.name == username: <NEW_LINE> <INDENT> return user.db_id <NEW_LINE> <DEDENT> <DEDENT> in_db = ds.createUser(username)[0] <NEW_LINE> array_of_all_in_thread.append(User_...
Check if name of user exsits in database, adds user to db if necessary Arguments: username {string} -- name of user array_of_all_in_thread {List[User_with_db_id]} -- list of object of type User_with_db_id
625941da8c0ade5d55d3ec78
def FormatLines(lines): <NEW_LINE> <INDENT> new_lines = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if len(line) <= 100: <NEW_LINE> <INDENT> new_lines.append(line) <NEW_LINE> continue <NEW_LINE> <DEDENT> padding = 0 <NEW_LINE> for c in line: <NEW_LINE> <INDENT> if c != ' ': break <NEW_LINE> padding += 1 <NEW_L...
Reformat lines by splitting long lines.
625941da29b78933be1e5963
@actions('ZG-F-07-04') <NEW_LINE> def department_user_add(ret, content, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> User_list = views.action_get(ret, 'User_Con_Department', content)['content']['value'] <NEW_LINE> objs = [] <NEW_LINE> for row in list(User_list): <NEW_LINE> <INDENT> temp = org_models.U...
获取某部门账户 :param ret: :param content: :param args: :param kwargs: :return:
625941da67a9b606de4a8173
def transform_color(original_im, source_mean, source_std): <NEW_LINE> <INDENT> target_im = original_im.copy() <NEW_LINE> target_im_mean = np.mean(target_im, axis = (0, 1)) <NEW_LINE> target_im_std = np.std(target_im, axis = (0, 1)) <NEW_LINE> target_im[:,:,0] -= target_im_mean[0] <NEW_LINE> target_im[:,:,1] -= target_i...
Works better on lad color space
625941da76e4537e8c351930
def commit_all(): <NEW_LINE> <INDENT> from solar.system_log.operations import move_to_commited <NEW_LINE> for item in data.SL(): <NEW_LINE> <INDENT> move_to_commited(item.log_action)
Helper mainly for ease of testing
625941da8e71fb1e9831da64
def test_schemaless_param_success(self): <NEW_LINE> <INDENT> body = {'type': 'CandyItem'} <NEW_LINE> query = {'woot': 'woot'} <NEW_LINE> path = '/null/' <NEW_LINE> headers = {'Whatever': 'woot'} <NEW_LINE> operation = Operation.from_schema(Schema(SPEC), 'Null') <NEW_LINE> self.assertEqual(True, operation.validate_reque...
Validates that we allow arbitrary bodies when a body parameter hasn't been specified.
625941da3eb6a72ae02ec79f
def generate_captain() -> Tuple[Captain, OurShip, str, float, str, str]: <NEW_LINE> <INDENT> captain = Captain() <NEW_LINE> ship = OurShip(captain=captain) <NEW_LINE> location: str = random.choice(data.place_names) <NEW_LINE> destination, distance = navigation.choose_destination( location, data.place_coords, set() ) <N...
This function initialises a new captain, ship and location
625941da71ff763f4b54994b
def check_date(data): <NEW_LINE> <INDENT> global db <NEW_LINE> c = db.cursor() <NEW_LINE> datefmt = "%a, %d %b %Y %X %z" <NEW_LINE> date = datetime.datetime.strptime(data['published'], datefmt).isoformat()[:19] <NEW_LINE> c.execute("SELECT * FROM torrents WHERE datetime(date)<=datetime(?)", (date,)) <NEW_LINE> lc = len...
Check if we already have a a newer dat in out database
625941dae1aae11d1e749f75
def load_cache_from_dict(self, app_data): <NEW_LINE> <INDENT> assert app_data["players"] <NEW_LINE> assert app_data["team_players"] <NEW_LINE> assert app_data["owners"] <NEW_LINE> if not app_data.get("redraft"): <NEW_LINE> <INDENT> app_data["redraft"] = [] <NEW_LINE> <DEDENT> for player in app_data["players"]: <NEW_LIN...
Kind of confusing how this has to be done because of the crazy indexing thing i set up. Essentially your app_data dict should look like: { "players": [{ "name": <str>, "position": <str>, "value": <int> }, ...], "team_players": [{ "owner_name": <str>, "player": <name>,...
625941da0c0af96317bb84a3
def generator(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self.work_queue.get() <NEW_LINE> self.status = 'processing' <NEW_LINE> for request_id in self.request: <NEW_LINE> <INDENT> self.processed_request[request_id] = {} <NEW_LINE> self.processed_request[request_id]['request'] = self.request[request_id] ...
Each time someone decides to put some work in queue, we yield all collected requests.
625941dad486a94d0b98e402
def recv(self, size): <NEW_LINE> <INDENT> if self._closed: <NEW_LINE> <INDENT> raise SocketClosedError() <NEW_LINE> <DEDENT> if self._buf: <NEW_LINE> <INDENT> out = self._buf[:size] <NEW_LINE> self._buf = self._buf[size:] <NEW_LINE> return ValueEvent(out) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ReceiveEven...
Read at most size bytes of data from the socket.
625941daad47b63b2c50a23a
def post_source(self, source): <NEW_LINE> <INDENT> self.logger.debug('Posting source for manufacturer_id: %s', source.get('manufacturer_id')) <NEW_LINE> return self._post('sources', payload=source)
Post a source payload to create a new source. :param source: :return:
625941da3c8af77a43ae3a5e
@register.simple_tag <NEW_LINE> def oauthio_install_javascript(): <NEW_LINE> <INDENT> tpl = '<script type="text/javascript" src="{0}"></script>' <NEW_LINE> return '{0}\n{1}'.format(tpl.format( getattr( settings, "OAUTHIO_JAVASCRIPT_SRC", "https://cdn.rawgit.com/oauth-io/oauth-js/master/dist/oauth.js" ) ), tpl.format(se...
Get the javascript file for Oauth.io :return: A script tag :rtype: str
625941da236d856c2ad44a99
def Update_Sample(self,sql,params): <NEW_LINE> <INDENT> conn = MySQLdb.connect(**self.conn_dict) <NEW_LINE> cur = conn.cursor() <NEW_LINE> count=cur.execute(sql,params) <NEW_LINE> conn.commit() <NEW_LINE> cur.close() <NEW_LINE> conn.close() <NEW_LINE> return count
修改单行数据 @return: 受影响的条数
625941da01c39578d7e750f7
def close(self): <NEW_LINE> <INDENT> os.close(self.ind) <NEW_LINE> os.close(self.outd) <NEW_LINE> self.ind, self.outd = (None, None)
Close the port. Once close, the only logical next is to shutdown the port process.
625941da7d847024c06be57a
def flattendeep(*seqs): <NEW_LINE> <INDENT> for item in itertools.chain.from_iterable(seqs): <NEW_LINE> <INDENT> if iscollection(item): <NEW_LINE> <INDENT> yield from flattendeep(item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield item
Recursively flatten iterables. Examples: >>> list(flattendeep([[1], [2, [3]], [[4]]])) [1, 2, 3, 4] >>> list(flattendeep([[1], [2, [3]], [[4]]], [5, [6, 7]])) [1, 2, 3, 4, 5, 6, 7] >>> list(flattendeep([[1], [2, [3]], [[4]]], [5, [[[[6, [[[7]]]]]]]])) [1, 2, 3, 4, 5, 6, 7] Args: *seqs (Ite...
625941da9b70327d1c4e1092
def test_account_integration_router_disable_glockapps_ip_monitoring(self): <NEW_LINE> <INDENT> pass
Test case for account_integration_router_disable_glockapps_ip_monitoring
625941da8a43f66fc4b5431e
def __str__(self): <NEW_LINE> <INDENT> return str(vars(self))
Returns string representation of this object.
625941da21bff66bcd684c0c
def _interval_in_bb(interval_left_coord, interval_width, bbox): <NEW_LINE> <INDENT> assert len(bbox) == 2 <NEW_LINE> bbox_lo, bbox_hi = bbox <NEW_LINE> interval_right_coord = interval_left_coord + interval_width <NEW_LINE> if bbox_lo < interval_left_coord < bbox_hi: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> e...
1D chunk_in_bb
625941da71ff763f4b54994c
def test_report_sanitize_url(self): <NEW_LINE> <INDENT> report = self.new_report() <NEW_LINE> report.add('feed.url', URL_UNSANE) <NEW_LINE> self.assertEqual(URL_SANE, report['feed.url'])
Test if report sanitizes an URL.
625941da187af65679ca53db
def list_security_groups(self, **params): <NEW_LINE> <INDENT> url = 'os-security-groups' <NEW_LINE> if params: <NEW_LINE> <INDENT> url += '?%s' % urllib.urlencode(params) <NEW_LINE> <DEDENT> resp, body = self.get(url) <NEW_LINE> body = json.loads(body) <NEW_LINE> self.validate_response(schema.list_security_groups, resp...
List all security groups for a user. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-security-groups
625941da9c8ee82313fbba31
def getHelpAsString(fulldoc=True): <NEW_LINE> <INDENT> return wavecal.__doc__
Return documentation on the wavecal function.
625941da30c21e258bdfa75a
def _filter(t_center, window, spiketrain): <NEW_LINE> <INDENT> u = 1 * pq.s <NEW_LINE> try: <NEW_LINE> <INDENT> t_sec = t_center.rescale(u).magnitude <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError("t must be a quantities object") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> h_sec = wind...
This function calculates the difference of spike counts in the left and right side of a window of size h centered in t and normalized by its variance. The variance of this count can be expressed as a combination of mean and var of the I.S.I. lying inside the window. Parameters ---------- t_center : quantity time o...
625941da293b9510aa2c354f
def __init__(self, tp, trail_dict=None): <NEW_LINE> <INDENT> if not trail_dict: <NEW_LINE> <INDENT> trail_dict ={} <NEW_LINE> <DEDENT> self.trail_length = trail_dict.get('length', tdc_TP_Plotter.__trail_length) <NEW_LINE> self.marker_style = trail_dict.get('marker', 'symbols') <NEW_LINE> self.markersize = trail_dict....
Arguments: ---------- tp tdc_TP_Data instance, if None <default> self.TP will be initialized by an empty dictionary trail_dict dictionary with trail plot properties dict( length=3, style='color', marker='symbols', markersize=10 ) Entries: ------- trail Length of the particle trail -1 -...
625941da30dc7b7665901c20
def __init__(self, config): <NEW_LINE> <INDENT> BaseWorkerThread.__init__(self) <NEW_LINE> self.dbsUrl = config.DBSInterface.globalDBSUrl <NEW_LINE> self.pollCounter = 0 <NEW_LINE> self.subFrequency = None <NEW_LINE> if getattr(config.PhEDExInjector, "subscribeDatasets", False): <NEW_LINE> <INDENT> pollInterval = confi...
___init___ Initialise class members
625941da30bbd722463cc084