code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def plot(self, skyimage, **kwargs): <NEW_LINE> <INDENT> p = self.parameters <NEW_LINE> axes = [] <NEW_LINE> for panel in range(p['npanels']): <NEW_LINE> <INDENT> ax = self.plot_panel(skyimage, panel=panel, **kwargs) <NEW_LINE> axes.append(ax) <NEW_LINE> <DEDENT> return axes
Plot sky image on all panels. Parameters ---------- skyimage : `~gammapy.image.SkyImage` Sky image to plot.
625941ebd268445f265b5357
@api.route('/tables/<int:id>', methods = ['GET']) <NEW_LINE> def tables_show(id = None): <NEW_LINE> <INDENT> mytable = db.session.query(HiveTbls).filter(HiveTbls.id == id).first() <NEW_LINE> if mytable is None: <NEW_LINE> <INDENT> data = { 'code' : 201, 'msg': 'table not exist' } <NEW_LINE> return jsonify(data), 201 <N...
展示一个表的详情 :param id: :return:
625941eb5166f23b2e1a5641
def get_path_kwargs(path): <NEW_LINE> <INDENT> l = path.split('/') <NEW_LINE> kwargs = {} <NEW_LINE> for i,k in enumerate(l[:-2]): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> arg = pathKwargs[k] <NEW_LINE> kwargs[arg] = int(l[i + 1]) <NEW_LINE> <DEDENT> except (KeyError,ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE>...
extract dict of kwargs from path, suitable for reverse()
625941eb656771135c3ebd5d
def getConfig(self): <NEW_LINE> <INDENT> return {key:value[0] for key, value in self.__config.iteritems()}
Return a dict() of the key-value pairs for the supplied configuration objects, this method removes the description.
625941eb3539df3088e2e833
def __init__(self, version, response, solution): <NEW_LINE> <INDENT> super(KeyPage, self).__init__(version, response) <NEW_LINE> self._solution = solution
Initialize the KeyPage :param Version version: Version that contains the resource :param Response response: Response from the API :param account_sid: A 34 character string that uniquely identifies this resource. :returns: twilio_code.rest.api.v2010.account.key.KeyPage :rtype: twilio.rest.api.v2010.account.key.KeyPage
625941eb99fddb7c1c9de876
def get_picture(self, name: str, level: int) -> ImageSendMessage: <NEW_LINE> <INDENT> self.verify_input(name, level, level) <NEW_LINE> data = self.item_data[name] <NEW_LINE> if data['type'] == 'node': <NEW_LINE> <INDENT> if level == 0: <NEW_LINE> <INDENT> raise ValueError('Database::get_picture error!') <NEW_LINE> <DED...
取得程式或節點的圖片 Args: name: 欲查詢的東西的名稱 level: 欲查詢的等級
625941eb097d151d1a22333f
def sign(data, apikey): <NEW_LINE> <INDENT> keys = sorted(data.keys()) <NEW_LINE> query_string = '&'.join(['%s=%s' % (k, data[k]) for k in keys]) <NEW_LINE> signature = hmac.new(apikey, query_string.encode(), hashlib.sha1).digest() <NEW_LINE> signature = base64.b64encode(signature).decode() <NEW_LINE> logger.debug('Sig...
Sign a http query string in the array of key-value pairs return b64 encoded hmac hash https://github.com/Yubico/yubikey-val/blob/master/doc/Validation_Protocol_V2.0.adoc#generating-signatures
625941eb1d351010ab856003
def test_group_messages_by_category(self): <NEW_LINE> <INDENT> messages = pfif_diff.pfif_file_diff( StringIO(PfifXml.XML_ADDED_DELETED_CHANGED_1), StringIO(PfifXml.XML_ADDED_DELETED_CHANGED_2)) <NEW_LINE> grouped_messages = utils.MessagesOutput.group_messages_by_category(messages) <NEW_LINE> self.assertTrue(utils.Categ...
group_messages_by_category should return a map from category to message.
625941eb76d4e153a657f01b
def countPlayers(): <NEW_LINE> <INDENT> conn=connect() <NEW_LINE> curs=conn.cursor() <NEW_LINE> curs.execute("SELECT count(*) as num from player") <NEW_LINE> num=curs.fetchone()[0] <NEW_LINE> conn.close() <NEW_LINE> return num
Returns the number of players currently registered.
625941ebfb3f5b602dac3b80
def get_distance_meters(location_a, location_b): <NEW_LINE> <INDENT> distance_seconds = get_distance_seconds(location_a, location_b) <NEW_LINE> distance_meters = int(distance_seconds * 1.7) <NEW_LINE> return distance_meters
Return distance in meters between given points. location_a - coordinates set location_b - coordinates set
625941ebd4950a0f3b08c830
def roll_forward(self, branch_name: str) -> bool: <NEW_LINE> <INDENT> if not self.can_roll_forward(branch_name): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> prev = self.get_active_branch() <NEW_LINE> self.switch_branch(branch_name) <NEW_LINE> self.repo.git.checkout(self.redo_stack[branch_name].pop()) <NEW_LINE...
Moves the head of this branch forward one commit (effective "re-do" button) :param branch_name: The name of the branch to modify :return: True if the roll is successful, False otherwise
625941eb1f5feb6acb0c5031
def get_profit_for_pair(exchange, pair): <NEW_LINE> <INDENT> profit = 0 <NEW_LINE> counter = 0 <NEW_LINE> s = select([database.TradingPositions]).where(and_(database.TradingPositions.c.Exchange == exchange, database.TradingPositions.c.Pair == pair)) <NEW_LINE> result = conn.execute(s) <NEW_LINE> for row in result: <NEW...
Iterates through all trades for given exchange pair over the course of trading. Starts by subtracting the long positions (the buys) and adding the short positions (the sells) to arrive at the difference (profit
625941eb1b99ca400220af9c
def get_bibtex_string(self): <NEW_LINE> <INDENT> bibtex_keys = {'author': ('_publ_author_name', '_citation_author_name'), 'title': ('_publ_section_title', '_citation_title'), 'journal': ('_journal_name_full', '_journal_name_abbrev', '_citation_journal_full', '_citation_journal_abbrev'), 'volume': ('_journal_volume', '_...
Get BibTeX reference from CIF file. :param data: :return: BibTeX string
625941eb167d2b6e3121907d
def __init__(self, x, y, text="hallo", color=(255, 0, 0), dx=0, dy=-50, duration=2, acceleration_factor = 1.0, delay = 0, fontsize=22): <NEW_LINE> <INDENT> self._layer = 7 <NEW_LINE> pygame.sprite.Sprite.__init__(self, self.groups) <NEW_LINE> self.text = text <NEW_LINE> self.r, self.g, self.b = color[0], color[1], colo...
a text flying upward and for a short time and disappearing
625941ebd486a94d0b98e62f
def g(x, n, c): <NEW_LINE> <INDENT> return (x ** 2 + c) % n
polynomial function for semi-randomness
625941eb31939e2706e4d34b
def gcd(self, x, y): <NEW_LINE> <INDENT> return x if y == 0 else self.gcd(y, x % y)
get greatest common divisor of x and y famous Euclidean algorithm
625941ebd7e4931a7ee9e407
def _get_content(self): <NEW_LINE> <INDENT> class MultiEncoder(WebAPIEncoder): <NEW_LINE> <INDENT> def __init__(self, encoders): <NEW_LINE> <INDENT> self.encoders = encoders <NEW_LINE> <DEDENT> def encode(self, *args, **kwargs): <NEW_LINE> <INDENT> for encoder in self.encoders: <NEW_LINE> <INDENT> result = encoder.enco...
Returns the API response content in the appropriate format. This is an overridden version of HttpResponse._get_content that generates the resulting content when requested, rather than generating it up-front in the constructor. This is used so that the @webapi decorator can set the appropriate API format before the con...
625941eb23849d37ff7b3573
def get_model_upload_path(instance, filename): <NEW_LINE> <INDENT> return join(MODELS_TMP_DIR, instance.name, filename)
This method must stay outside of the class definition because django cannot serialize unbound methods in Python 2: https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing
625941ebe5267d203edce17f
def find_bounds(packages): <NEW_LINE> <INDENT> if not packages: <NEW_LINE> <INDENT> return json.dumps([[-90.0, 90.0], [-180.0, 180.0]]) <NEW_LINE> <DEDENT> max_lat = NMEA_to_dd(max([pkg['latitude'] for pkg in packages])) <NEW_LINE> min_lat = NMEA_to_dd(min([pkg['latitude'] for pkg in packages])) <NEW_LINE> max_lon = NM...
Function for finding coordinates bounds for all points contained in list. Args: pkg_list: list of packages with points. See self.get_packages. Returns: List with two lists first one is latitude range [min, max] and second one longitude range [min, max].
625941ebf7d966606f6aa4f2
def get_valid_root(self, ev, ds): <NEW_LINE> <INDENT> if ev.DefaultFitVertexExists() and ev.GetDefaultFitVertex().ContainsPosition() and ev.GetDefaultFitVertex().ValidPosition(): <NEW_LINE> <INDENT> if self._fv_radius: <NEW_LINE> <INDENT> return self.fv_cut_root(ev, ds) <NEW_LINE> <DEDENT>...
Check whether radius of a DS::EV is valid Args: ev (:class:`RAT.DS.EV`): event ds (:class:`RAT.DS`): Data Structure entry Returns: bool: Validity boolean
625941ebd8ef3951e3243a26
def MakeMd5(filename, md5filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename, 'r') as read_file: <NEW_LINE> <INDENT> with open(md5filename, 'w') as hash_file: <NEW_LINE> <INDENT> hasher = hashlib.md5() <NEW_LINE> for chunk in iter(lambda: read_file.read(128*hasher.block_size), ''): <NEW_LINE> <IN...
Creates an MD5 checksum file from a provided file. Assuming directory of destination file is writable. Args: filename: absolute path name of file to hash md5filename: absolute path name of MD5 file to create Returns: a boolean, True when md5checksum file is successfully created
625941eb71ff763f4b549b7d
def add_children(G, parent, level, n=2): <NEW_LINE> <INDENT> if level == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for i in range(n): <NEW_LINE> <INDENT> child = parent+str(i) <NEW_LINE> G.add_node(child) <NEW_LINE> G.add_edge(parent,child) <NEW_LINE> add_children(G, child, level-1, n)
Add children recursively to a binary tree.
625941ebe1aae11d1e74a1a5
def most_connected(edges_table): <NEW_LINE> <INDENT> num_connections = [] <NEW_LINE> counties = [] <NEW_LINE> for countie, borders in edges_table.items(): <NEW_LINE> <INDENT> num_connections.append(len(borders)) <NEW_LINE> counties.append(countie) <NEW_LINE> <DEDENT> data = pd.DataFrame({'Length': num_connections, 'Cou...
returns the most connected countie as starting point based on an edgestable
625941eb97e22403b379d484
def fusePostProcess(y_f, y_hat, img1, img2, single = True): <NEW_LINE> <INDENT> with torch.no_grad(): <NEW_LINE> <INDENT> y_f = (y_f + 1) * 127.5 <NEW_LINE> y_hat = (y_hat + 1) * 127.5 <NEW_LINE> img1 = (img1 + 1) * 127.5 <NEW_LINE> img2 = (img2 + 1) * 127.5 <NEW_LINE> cr_fuse, cb_fuse = weightedFusion( cr1 = i...
Perform the post fusion process toward the both image with generated luminance slice Arg: y_f (torch.Tensor) - The generated luminance slice y_hat (torch.Tensor) - The ground truth luminance slice which is computed by MEF-SSIM formula img1 (torch.Tensor) - The 1st image tensor (in YCrCb ...
625941eb99fddb7c1c9de877
@njit(cache=False) <NEW_LINE> def chromosphere_z_v(zs, k): <NEW_LINE> <INDENT> nz = len(zs) <NEW_LINE> flux = ones_like(zs) <NEW_LINE> for i in range(nz): <NEW_LINE> <INDENT> z = zs[i] <NEW_LINE> if (z > 0.0) and (z - k < 1.0): <NEW_LINE> <INDENT> zmk2 = (z - k) ** 2 <NEW_LINE> if z + k < 1.0: <NEW_LINE> <INDENT> t = s...
Optically thin chromosphere model presented in Schlawin, Agol, Walkowicz, Covey & Lloyd (2010)
625941eb2ae34c7f2600d619
def add_api_key_authorization(self, request): <NEW_LINE> <INDENT> request.params.update({'api_key': self.api_key, 'user_key': self.user_key} )
Pardot uses for basic authorization email, password and user_key.
625941eb287bf620b61d3f49
def __or__(self, f): <NEW_LINE> <INDENT> return Qt.ItemFlags()
Qt.ItemFlags Qt.ItemFlags.__or__(Qt.ItemFlags f)
625941eb293b9510aa2c3779
def list_tags(request): <NEW_LINE> <INDENT> query = request.GET.get('q', '') <NEW_LINE> limit = request.GET.get('limit', MAX_SUGGESTIONS) <NEW_LINE> try: <NEW_LINE> <INDENT> request.GET.get('limit', MAX_SUGGESTIONS) <NEW_LINE> limit = min(int(limit), MAX_SUGGESTIONS) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <I...
Returns a list of JSON objects with a `name` and a `value` property that all start like your query string `q` (not case sensitive).
625941ebcb5e8a47e48b7f8b
def plot_knee_normalized(self, ): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> plt.figure(figsize=(8, 8)) <NEW_LINE> plt.plot(self.xsn, self.ysn) <NEW_LINE> plt.plot(self.xd, self.yd, 'r') <NEW_LINE> plt.xticks(np.arange(min(self.xsn), max(self.xsn) + 0.1, 0.1)) <NEW_LINE> plt.yticks(np.arange(min(sel...
Plot the normalized curve, the distance curve (xd, ysn) and the knee, if it exists.
625941eb56ac1b37e62646ae
@pytest.fixture <NEW_LINE> def adapters_2() -> List[int]: <NEW_LINE> <INDENT> dir_path = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> cm: ContextManager[IO] = file_read(dir_path + "/testinputs/day10_2") <NEW_LINE> with cm as input_file: <NEW_LINE> <INDENT> adapters: List[int] = [int(line) for line in input_fi...
Returns the test input 2.
625941eb91af0d3eaac9bf06
def variance_gcv(log10lmbd, data, matrices): <NEW_LINE> <INDENT> lmbd = 10**np.asscalar(log10lmbd) <NEW_LINE> A, b = matrices.build_linear_system(lmbd, data) <NEW_LINE> yhat = solve(A, b) <NEW_LINE> M = matrices.M <NEW_LINE> y = matrices.as_column_vector(data.y) <NEW_LINE> H = M * solve(A, M.T * matrices.W) <NEW_LINE> ...
Return squared variance from generalized cross-validation. Solve for optimal lambda by using this function with fmin.
625941eb4527f215b584c93b
def increamentstat(self,key): <NEW_LINE> <INDENT> oldstat = dict(self.loginstat) if self.loginstat else {} <NEW_LINE> oldval = oldstat.get(key) <NEW_LINE> if oldval: <NEW_LINE> <INDENT> oldstat[key] = oldval + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> oldstat[key] = 1 <NEW_LINE> <DEDENT> self.loginstat = oldstat...
method to increament value of stat for a particular key
625941eb956e5f7376d71354
def decrypt(self, node, *nodes): <NEW_LINE> <INDENT> signature = (node, nodes) <NEW_LINE> if signature in self._decryptable_nodes: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._decryptable_nodes.append(signature) <NEW_LINE> if self.is_encrypted(): <NEW_LINE> <INDENT> self._decrypt(node, nodes)
Decrypt an object in our config tree. :py:attr:`_decryption_cipher` is used as our key, retrieved using :py:func:`~getpass.getpass` in :py:meth:`load` if it wasn't already specified. If this is called when passwords are not encrypted (check with :py:meth:`is_encrypted`), nothing will happen. We'll also keep track of t...
625941eb6fb2d068a760f58e
def launch_with_missing_parameter(self, missing_param): <NEW_LINE> <INDENT> request = build_launch_request() <NEW_LINE> del request.POST[missing_param] <NEW_LINE> return views.lti_launch(request, None, None)
Helper method to remove a parameter from the LTI launch and call the view
625941eb6e29344779a62af9
def get_string(self): <NEW_LINE> <INDENT> return self.__string
Returns the string component.
625941eba8370b7717052d86
def backup_old(self): <NEW_LINE> <INDENT> import tarfile <NEW_LINE> print('Backing up old scripts, logs and properties directories.') <NEW_LINE> lggr.debug( 'Taking a backup of old scripts, logs and properties folders.') <NEW_LINE> dirs_to_backup = ['scripts', 'logs', 'properties'] <NEW_LINE> with tarfile.open( os.path...
Take a backup of old scripts, logs and properties directories.
625941eb2eb69b55b151cd9f
def get_field_value(data, field, default=None): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if '.' in field: <NEW_LINE> <INDENT> current, rest = field.split('.', 1) <NEW_LINE> if isinstance(data, list) and current.isdigit(): <NEW_LINE> <INDENT> return...
Will return the field value out of data. Field can contain '.', which will be followed. :param field: the field name, can contain '.' :param data: the data as a dict, can contain sub-dicts :param default: the default value to return if field can't be found :return: the field value, or default.
625941eb94891a1f4081bf94
def test_user(self): <NEW_LINE> <INDENT> test_dict = { "path_to_dict": "dict1.json", "path_to_stat": "statistic1.json", "words_per_lesson": 6, "CntStudyWords": 60, "MinPercent": 98.0, "MinSuccessCnt": 11, "retry_time": 1801, "hide_transcription": "yes", "start_time_delay": 2, "stat_count_row": 300, "right_answer_percen...
Тестирование загрузки пользовательского файла с конфигурацией
625941eb9b70327d1c4e12c0
def transform_data(self, data=None): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> transformed_data = self.data[ self.independent + [self.weight] + [self.dependent] ] <NEW_LINE> transformed_data = copy.deepcopy(transformed_data) <NEW_LINE> transformed_data["_response"] = ( transformed_data[self.dependent] / ...
Method to add any customs, variates, interactions, and offsets to a generic dataset so that it can be used in the GLM object
625941eb8e05c05ec3eea862
def suppress_setattr(obj, attr, value, filter_none=False): <NEW_LINE> <INDENT> if filter_none and value is None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> setattr(obj, attr, value) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass
Set an attribute, suppressing any exceptions and skipping the attempt on failure. :param Any obj: Object to set the attribute on :param str attr: The attribute name to set :param Any value: The value to set the attribute to :param bool filter_none: [description], defaults to False :return: Nothing :rtype: None :Examp...
625941eb7c178a314d6ef950
def insert_data(self, table_name, data): <NEW_LINE> <INDENT> _table = self._meta.tables[table_name] <NEW_LINE> self._conn.execute(_table.insert_child(), data)
往指定表插入数据 当表不存在时, self.tables[table_name] 会报 KeyError 错误, 其中 KeyError.message 为表名字, 可以捕捉这个错误来动态创建需要的表 :param table_name: :param data: data 为数组形式的字典 :return:
625941eb26238365f5f0f35e
def df_kde_scores2(n, idxs, scores): <NEW_LINE> <INDENT> results = {'Score':[], 'Data index':[]} <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> results['Score'].append(scores[i]) <NEW_LINE> results['Data index'].append(idxs[i]) <NEW_LINE> <DEDENT> df = pd.DataFrame.from_dict(results) <NEW_LINE> return df
One density per data object
625941ebbe7bc26dc91cdadf
def __init__(self, autoRegisterStandardEditors=False): <NEW_LINE> <INDENT> self.editorsForValueType = dict() <NEW_LINE> self.registeredEditorTypes = set() <NEW_LINE> if autoRegisterStandardEditors: <NEW_LINE> <INDENT> self.registerStardardEditors()
Initialise an empty instance by default. If "autoRegisterStandardsEditors" is True, automatically register the standard editors.
625941eb596a897236089fa3
def set_params(self, **params): <NEW_LINE> <INDENT> params_for_clf = {} <NEW_LINE> for name, value in params.items(): <NEW_LINE> <INDENT> if name == 'features': <NEW_LINE> <INDENT> self.features = value <NEW_LINE> <DEDENT> elif name == 'clf': <NEW_LINE> <INDENT> self.clf = value <NEW_LINE> <DEDENT> elif name.startswith...
Set the parameters of this estimator. :param dict params: parameters to set in model .. note:: parameters of base estimator can be accessed (for example param `depth`) by both *depth* and *clf__depth*.
625941eb956e5f7376d71355
def set_image_tensor_batch_dim(tensor, batch_dim): <NEW_LINE> <INDENT> shape = tensor.get_shape() <NEW_LINE> tensor.set_shape([batch_dim, shape[1], shape[2], shape[3]]) <NEW_LINE> return tensor
Sets the batch dimension on an image tensor.
625941eb82261d6c526ab990
def limited_shell_exec(command, nlines=0): <NEW_LINE> <INDENT> st, so, se = BASE.shell_exec2(command, capture=1) <NEW_LINE> if nlines > 0: <NEW_LINE> <INDENT> so = so[0:nlines] <NEW_LINE> se = se[0:nlines] <NEW_LINE> <DEDENT> return st, so, se
run a simple shell command, returning the top nlines
625941eb50812a4eaa59c806
def get_color_XKCD(rgb_values, typed='LAB'): <NEW_LINE> <INDENT> overlap = {name for name in mcolors.CSS4_COLORS if "xkcd:" + name in mcolors.XKCD_COLORS} <NEW_LINE> rgb_names = sorted(overlap, reverse=True) <NEW_LINE> rgb_vals = [] <NEW_LINE> for j, n in enumerate(rgb_names): <NEW_LINE> <INDENT> rgb_vals.append(mcolor...
Get the color info of an RGB value in the corresponding XKCD colors :param rgb_values: ndarray with 3 numbers RGB from 0 to 255 :param typed: distance to be used, 'EUCRGB' for euclidean distance between rgb values or 'LAB' for delta_e_cie1976 distance between lab values or 'EUCLAB' for euclidean distance between lab va...
625941ebd4950a0f3b08c831
def ThreeSum(int_list): <NEW_LINE> <INDENT> triples = (t for t in combinations(int_list, 3) if sum(t) == 0) <NEW_LINE> count = 0 <NEW_LINE> for t in triples: <NEW_LINE> <INDENT> count += 1
given n distinct ints, how many sum to 0?
625941eb090684286d50f1d6
def clear_rows(cursor): <NEW_LINE> <INDENT> cursor.execute("""DELETE FROM infoarret""")
Docstring of the function clear_rows : This function allows to delete the table which is present in the main table 'infoarret' cursor : comande SQL with the library sqlite 3 of python allows to place in the table 'infoarret'
625941eb99cbb53fe67930ce
def _bed_iter(bed): <NEW_LINE> <INDENT> records = (line.split()[:3] for line in bed if not (line.startswith('browser') or line.startswith('track'))) <NEW_LINE> for chrom, chrom_iter in itertools.groupby(records, lambda x: x[0]): <NEW_LINE> <INDENT> yield chrom, ((int(start), int(stop)) for _, start, stop in chrom_iter)
Given an open BED file, yield tuples of (`chrom`, `chrom_iter`) where `chrom_iter` yields tuples of (`start`, `stop`).
625941eb5fc7496912cc3e67
def top(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.data[self.size - 1]
Returns the top item from the stack, None if the stack is empty. Does NOT remove the top item.
625941eb9c8ee82313fbbc60
def to_dict(self): <NEW_LINE> <INDENT> return dict(self._json_data)
Convert the Webex Teams object data to a dictionary.
625941ebcc40096d61595e38
def set_cover_position(hass, position, entity_id=None): <NEW_LINE> <INDENT> data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} <NEW_LINE> data[ATTR_POSITION] = position <NEW_LINE> hass.services.call(DOMAIN, SERVICE_SET_COVER_POSITION, data)
Move to specific position all or specified cover.
625941ebf9cc0f698b140ae0
def __init__(self, input_shape, n_output_classes, conv1_channels, conv2_channels): <NEW_LINE> <INDENT> self.layer_1 = ConvolutionalLayer(input_shape[2], conv1_channels, 3, 1) <NEW_LINE> self.layer_2 = ReLULayer() <NEW_LINE> self.layer_3 = MaxPoolingLayer(4, 4) <NEW_LINE> self.layer_4 = ConvolutionalLayer(conv1_channels...
Initializes the neural network Arguments: input_shape, tuple of 3 ints - image_width, image_height, n_channels Will be equal to (32, 32, 3) n_output_classes, int - number of classes to predict conv1_channels, int - number of filters in the 1st conv layer conv2_channels, int - number of...
625941ebec188e330fd5ac7e
def current_to_pbest_mutation(population: np.ndarray, population_fitness: np.ndarray, f: List[float], p: Union[float, np.ndarray, int], bounds: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> if len(population) < 4: <NEW_LINE> <INDENT> return population <NEW_LINE> <DEDENT> p_best = [] <NEW_LINE> for p_i in p: <NEW_LINE>...
Calculates the mutation of the entire population based on the "current to p-best" mutation. This is V_{i, G} = X_{i, G} + F * (X_{p_best, G} - X_{i, G} + F * (X_{r1. G} - X_{r2, G} :param population: Population to apply the mutation :type population: np.ndarray :param population_fitness: Fitness of the given population...
625941eb004d5f362079a819
def put(self, site_name): <NEW_LINE> <INDENT> args = self.reqparse.parse_args() <NEW_LINE> config = args['config'] <NEW_LINE> enable = args['enable'] <NEW_LINE> if enable is not None: <NEW_LINE> <INDENT> enable = enable.lower() == "true" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enable = False <NEW_LINE> <DEDENT> r...
@api {put} /config/site/:site_name Update a configuration. @apiName UpdateSiteConfig @apiDescription Replace a configuration for a site. @apiGroup Configuration @apiParam {String} site_name Name of the site. @apiParam {String} config Configuration of the site. @apiParam {String} enable Activate the configur...
625941eb07f4c71912b1196e
def test_delete_version_followed_by_archive(self): <NEW_LINE> <INDENT> log = logging.getLogger("test_delete_version_followed_by_archive") <NEW_LINE> key_names = ["test-key1", ] <NEW_LINE> iteration_count = 10 <NEW_LINE> bucket = self._s3_connection.create_unique_bucket() <NEW_LINE> bucket.configure_versioning(True) <NE...
test this sequence * create a bucket with versioning * archive a key to the bucket * delete the version that was just archived * archive a new version * verify that the new version is accessible
625941eb4e696a04525c9937
def rollback_iteration( self, project_id, iteration_id, training_key=None, training_key1=None, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/{projectId}/iterations/current/{iterationId}' <NEW_LINE> path_format_arguments = { 'projectId': self._serialize.url("project_id", project_id, 's...
:param project_id: Format - uuid. :type project_id: str :param iteration_id: Format - uuid. :type iteration_id: str :param training_key: subscription key in url :type training_key: str :param training_key1: subscription key in header :type training_key1: str :param dict custom_headers: headers that will be added to the...
625941eb167d2b6e3121907e
def contextMenuData(self): <NEW_LINE> <INDENT> return QWebEngineContextMenuData
contextMenuData(self) -> QWebEngineContextMenuData
625941ebab23a570cc250670
def lamda_func(): <NEW_LINE> <INDENT> def make_incrementor(n): <NEW_LINE> <INDENT> return lambda x: x + n <NEW_LINE> <DEDENT> f = make_incrementor(42) <NEW_LINE> f(0) <NEW_LINE> f(1)
小匿名函数可以利用lamda创建,且被限制为单个表达式; lamda表达式具有闭包特性,可索引局部变量
625941ebcb5e8a47e48b7f8c
def len2(x): <NEW_LINE> <INDENT> if hasattr(x, '__len__'): <NEW_LINE> <INDENT> length = len(x) <NEW_LINE> <DEDENT> elif isinstance(x, (int,float,long,complex)): <NEW_LINE> <INDENT> length = 1 <NEW_LINE> <DEDENT> return length
A modified version of len() to work with numbers. Numbers have a length of 1
625941ebd8ef3951e3243a27
def users_post(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.users_post_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.users_post_with_http_info(**kwargs) <NEW_LINE> return data
This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.users_post(callback=callback_function) :param callback functio...
625941eb566aa707497f4a4b
def setConvertObj(self, convertObj): <NEW_LINE> <INDENT> self.convertObj = convertObj <NEW_LINE> self.editWidget.setConvertObj(self.convertObj)
Sets the object that is used for the conversion between scene position and timestamp or price. Arguments: convertObj - PriceBarChartGraphicsScene object that is used for scene position conversions of X point to timestamp and Y point to price.
625941eb5e10d32532c5f40e
def remove_number(self, num): <NEW_LINE> <INDENT> self.pile -= num <NEW_LINE> self.last_player = 1 - self.last_player
removes the top checker from column col of the called Board object. If the column is empty, then the method should do nothing
625941eb24f1403a9260104b
def __rmul__(self, other): <NEW_LINE> <INDENT> if isinstance(other, numbers.Number): <NEW_LINE> <INDENT> pass <NEW_LINE> rmulti = [] <NEW_LINE> for r in range(self.h): <NEW_LINE> <INDENT> row = [] <NEW_LINE> for c in range(self.w): <NEW_LINE> <INDENT> row.append(other*self[r][c]) <NEW_LINE> <DEDENT> rmulti.append(row) ...
Called when the thing on the left of the * is not a matrix. Example: > identity = Matrix([ [1,0], [0,1] ]) > doubled = 2 * identity > print(doubled) 2.0 0.0 0.0 2.0
625941ebbf627c535bc136b9
def __init__(self, page_id: str, har_parser=None, har_data: dict = None): <NEW_LINE> <INDENT> self.page_id = page_id <NEW_LINE> self._index = 0 <NEW_LINE> if har_parser is None and har_data is None: <NEW_LINE> <INDENT> raise ValueError("Either parser or har_data is required") <NEW_LINE> <DEDENT> if har_parser: <NEW_LIN...
:param page_id: ``str`` of the page ID :param har_parser: a HarParser object :param har_data: ``dict`` of a file HAR file
625941eb4f88993c3716c54c
def __init__(self): <NEW_LINE> <INDENT> super(QtGui.QDockWidget, self).__init__() <NEW_LINE> self.setWindowTitle('Selected songs') <NEW_LINE> container = self.init_layout() <NEW_LINE> self.setWidget(container)
Handles DockWidget containing selected songs
625941eb5fcc89381b1e1bac
def test_iso8859_meta_tag(self): <NEW_LINE> <INDENT> self._test_charset_in_meta_tag('iso-8859-1')
https://github.com/snarfed/bridgy/issues/385
625941eb6fece00bbac2dc2e
def create_lexicon(pos_file, neg_file): <NEW_LINE> <INDENT> pos_words = process_file(pos_file) <NEW_LINE> neg_words = process_file(neg_file) <NEW_LINE> lex = pos_words + neg_words <NEW_LINE> word_count = Counter(lex) <NEW_LINE> low_limit = 0.94 <NEW_LINE> high_limit = 0.9991 <NEW_LINE> words = [_[0] for _ in sorted(wor...
创建词汇表 :param str pos_file: 正面评论文件名 :param str neg_file: 负面评论文件名 :return dict: 可用用的单词字典{word: position}
625941ebc4546d3d9de72f22
def get_score(store, phone, email, birthday=None, gender=None, first_name=None, last_name=None): <NEW_LINE> <INDENT> key_parts = [ first_name or "", last_name or "", str(phone) or "", birthday if birthday else "", ] <NEW_LINE> key = "uid:" + hashlib.md5("".join(key_parts).encode('utf-8')).hexdigest() <NEW_LINE> score =...
Get user's score based on given user fields
625941eb56b00c62f0f14b46
def calibrate_camera(): <NEW_LINE> <INDENT> import pickle <NEW_LINE> import os <NEW_LINE> import glob <NEW_LINE> import cv2 <NEW_LINE> from create_chess_grid import create_chess_grid <NEW_LINE> import numpy as np <NEW_LINE> workdir = os.getcwd() <NEW_LINE> os.chdir("/calibrationphotos") <NEW_LINE> grid = (7, 8) <NEW_LI...
Find the camera matrix and distortion coefficients for the camera. The directory should contain approx 20 photos of the chessboard from different angles. Returns the camera matrix and distortion coefficients. Also saves a file containing the coefficients to the same directory as the program.
625941eb5510c4643540f8c1
def test_runs_by_project_w_created_before_exc(client): <NEW_LINE> <INDENT> with pytest.raises(TypeError) as exc: <NEW_LINE> <INDENT> list(client.runs( models.Project(client, {'id': 1234}), created_before='asdf')) <NEW_LINE> <DEDENT> assert 'created/updated after/before' in str(exc) <NEW_LINE> assert 'asdf' in str(exc) ...
Verify calling ``client.runs(Project)`` with created_before exception
625941eb76d4e153a657f01c
def __init__(self): <NEW_LINE> <INDENT> self.__name = self.__read('name') <NEW_LINE> self.__vendor = self.__read('vendor') <NEW_LINE> self.__product = self.__read('product') <NEW_LINE> self.__product_id = self.__read('product_id') <NEW_LINE> self.__product_ver = self.__read('product_ver') <NEW_LINE> self.__uuid = self....
Constructor
625941eb1d351010ab856004
def conditional_depth(self, call): <NEW_LINE> <INDENT> ret = self.db.scalar("select max(depth) from conditionals where " + "call_id = %s;", (call['id'],)) <NEW_LINE> return -1 if ret is None else ret
Get current depth of the conditional stack.
625941ebcc0a2c11143dd37b
def _handleOnlyStateTransition(self, workload, req_status, dn): <NEW_LINE> <INDENT> if req_status == "aborted" or req_status == "force-complete": <NEW_LINE> <INDENT> self.gq_service.cancelWorkflow(workload.name()) <NEW_LINE> <DEDENT> report = self.reqmgr_db_service.updateRequestStatus(workload.name(), req_status, dn) <...
only handles state transition, when aborted and force completed. GQ elements need to be cancelled. Allows assigned and assigned approved transition without args update
625941eb656771135c3ebd5e
def inorderSuccessor(self, root, p): <NEW_LINE> <INDENT> while root is not None and root.val <= p.val: <NEW_LINE> <INDENT> root = root.right <NEW_LINE> <DEDENT> if root is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> left_node = self.inorderSuccessor(root.left, p) <NEW_LINE> return left_node if (left_node ...
:type root: TreeNode :type p: TreeNode :rtype: TreeNode
625941ebadb09d7d5db6cc76
def file_content_signature(fname): <NEW_LINE> <INDENT> sign = "" <NEW_LINE> if not osp.isfile(fname): <NEW_LINE> <INDENT> return sign <NEW_LINE> <DEDENT> txt = open(fname, "rb").read() <NEW_LINE> sign = sha1(fname+txt).hexdigest() <NEW_LINE> return sign
Return the signature of the File
625941ebd268445f265b5359
def get_image_size(img): <NEW_LINE> <INDENT> h, w = img.shape <NEW_LINE> return (w, h)
Retuns image size in pixels as a tuple with width and height length
625941eba4f1c619b28b0517
def compute_outlier_scores(self, frequencies): <NEW_LINE> <INDENT> if (len(frequencies.keys()) < 2): <NEW_LINE> <INDENT> raise Exception("There must be at least 2 aggregation units.") <NEW_LINE> <DEDENT> outlier_values = {} <NEW_LINE> rng = list(frequencies[list(frequencies.keys())[0]].keys()) <NEW_LINE> normalized_fre...
Computes the SVA outlier scores fo the given frequencies dictionary. Args: frequencies: dictionary of dictionaries, mapping (aggregation unit) -> (value) -> (number of times aggregation unit reported value). Returns: dictionary mapping (aggregation unit) -> (SVA outlier score for aggregation unit)...
625941eb56ac1b37e62646af
@chain.command('run') <NEW_LINE> @click.argument('name', nargs=1, default="default") <NEW_LINE> @click.option('--mine/--no-mine', default=True) <NEW_LINE> def chain_run(name, mine): <NEW_LINE> <INDENT> data_dir = get_geth_data_dir(os.getcwd(), name) <NEW_LINE> logfile_path = get_geth_logfile_path(data_dir) <NEW_LINE> e...
Run a geth node.
625941ebff9c53063f47c6db
def doNotBuy(): <NEW_LINE> <INDENT> notBuyList = [] <NEW_LINE> print('As the Designated Shopper you can choose to not buy certain items.' '\nWhen you are done inputting type done.') <NEW_LINE> notBuyItem = raw_input('Enter the food items you will NOT buy: ').lower() <NEW_LINE> while notBuyItem != 'done': <NEW_...
creates a do not buy list
625941eb287bf620b61d3f4a
def test_four_stations(): <NEW_LINE> <INDENT> game = Game() <NEW_LINE> player = game.add_player(DefaultPlayerAI()) <NEW_LINE> owner = game.add_player(DefaultPlayerAI()) <NEW_LINE> game.give_property_to_player(owner, Square.Name.LIVERPOOL_STREET_STATION) <NEW_LINE> game.give_property_to_player(owner, Square.Name.MARYLEB...
Tests that rent of £200 is taken when the owner owns four stations.
625941eb99fddb7c1c9de878
def rndb64(size): <NEW_LINE> <INDENT> rnd = base64.b64encode(rndbin(int(size * 0.75 + 1))).decode() <NEW_LINE> return rnd[0:size]
Returns a random text string of the given size (Base64 characters).
625941eb097d151d1a223341
def project_vectors_full(self, vectors, kpoint): <NEW_LINE> <INDENT> ncells = self._ncells <NEW_LINE> ndim = self._ndim <NEW_LINE> expanded_mappings = self._expanded_mappings <NEW_LINE> projected_vectors = np.zeros_like(vectors) <NEW_LINE> for expanded_mapping in expanded_mappings: <NEW_LINE> <INDENT> projected_vectors...
Project vectors onto kpoint Parameters ---------- vectors : (..., natoms * ndim, nbands) array Vectors for SC at kpoint. Each "column" vector is an eigenvector. kpoint : (ndim) array Reciprocal space point in fractional coordinates for SC. Returns ------- projected_vectors : (..., natoms * ndim, nbands) arra...
625941eb796e427e537b0ab4
def login_for_angular(request): <NEW_LINE> <INDENT> env = json.loads(request.body) <NEW_LINE> email = env['email'] <NEW_LINE> password = env['password'] <NEW_LINE> if request.user.is_authenticated: <NEW_LINE> <INDENT> return JsonResponse({"auth": "true", "message": "User was already logged in!", "messageCode": LOGIN_RE...
The login view. The code is self explanatory.
625941eb8e7ae83300e4b4b8
def score(self, strategy='max', crossing=True): <NEW_LINE> <INDENT> stadion = self.stadion_paths <NEW_LINE> if isinstance(crossing, bool) and crossing: <NEW_LINE> <INDENT> crossing = StadionEstimator._find_crossing(stadion, self.param_values, self.y_ref) <NEW_LINE> <DEDENT> elif isinstance(crossing, bool): <NEW_LINE> <...
Aggregate stadion path using specified strategy, until crossing with K=1 solution (optional). Parameters ---------- strategy : string or callable (default = 'max') stadion path aggregation strategy ('max', 'mean' or callable). crossing : bool (default = True aggregate only until all paths are under the path wi...
625941eb32920d7e50b286be
def JointTrajectory(thetastart, thetaend, Tf, N, method): <NEW_LINE> <INDENT> N = int(N) <NEW_LINE> timegap = Tf / (N - 1.0) <NEW_LINE> traj = np.zeros((len(thetastart), N)) <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> if method == 3: <NEW_LINE> <INDENT> s = CubicTimeScaling(Tf, timegap * i) <NEW_LINE> <DEDENT> el...
Example Input: thetastart = [1, 0, 0, 1, 1, 0.2, 0,1] thetaend = [1.2, 0.5, 0.6, 1.1, 2, 2, 0.9, 1] Tf = 4 N = 6 method = 3 Output: [[ 1. 0. 0. 1. 1. 0.2 0. 1. ] [ 1.0208 0.052 0.0624 1.0104 1.104 0.3872 0.0936 1. ] [ 1.0704 0.176 0.2112 1.0352 1.352 0.8336 0....
625941eb55399d3f05588ba1
def test_list_relationship_entity(self): <NEW_LINE> <INDENT> class Resource(ResourceBase): <NEW_LINE> <INDENT> _pks = ['id'] <NEW_LINE> _relationships = [ ListRelationship('related', relation='Resource') ] <NEW_LINE> <DEDENT> props = dict(id=1, related=[dict(id=2), dict(id=3)]) <NEW_LINE> res = Resource(properties=prop...
Tests a List entity entity
625941eb44b2445a3393257c
def botShot(ship_plr, ship_plr_shot, fleet_plr): <NEW_LINE> <INDENT> global prev_shot <NEW_LINE> shooted = 0 <NEW_LINE> dead = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> end = False <NEW_LINE> if prev_shot: <NEW_LINE> <INDENT> print('предыдущие выстрелы =>', prev_shot) <NEW_LINE> x, y = aptShot(prev_shot, fleet_plr) ...
print('заходит в >>>>>>>>>> bot_shot') for i in fleet_plr: print(i) print('<'*30)
625941eb0383005118ecfacb
def count_congruence_solutions__good_type(self, p, k, m, zvec, nzvec): <NEW_LINE> <INDENT> return CountAllLocalTypesNaive(self, p, k, m, zvec, nzvec)[1]
Counts the good-type solutions of Q(x) = m (mod p^k) satisfying the additional congruence conditions described in QuadraticForm.count_congruence_solutions_as_vector(). INPUT: `p` -- prime number > 0 `k` -- an integer > 0 `m` -- an integer (depending only on mod `p^k`) zvec, nzvec -- a list of integ...
625941ebd7e4931a7ee9e409
def decode_onestep(self, sess, feed): <NEW_LINE> <INDENT> to_return = { "ids": self._topk_ids, "probs": self._topk_log_probs, "states": self.state, "attn_dists": self.attn_dists} <NEW_LINE> if self.use_coverage: <NEW_LINE> <INDENT> to_return['coverage'] = self.coverage <NEW_LINE> <DEDENT> results = sess.run(to_return, ...
For beam search decoding. Run the decoder for one step. Args: sess: Tensorflow session. batch: Batch object containing single example repeated across the batch latest_tokens: Tokens to be fed as input into the decoder for this timestep enc_states: The encoder states. dec_init_states: List of beam_size LSTMSt...
625941eb7047854f462a18ee
def index(request): <NEW_LINE> <INDENT> return render(request, 'learning_blogs/index.html')
首页
625941eb462c4b4f79d1dbba
def cmp(self, a, b): <NEW_LINE> <INDENT> return cmp(self.getValue(a), self.getValue(b))
This column's comparison function, used for sorting a table by this column. By default this does an ascending sort using getValue.
625941ebf7d966606f6aa4f4
def format_call_str(*args: Any, **kwargs: Mapping[Any, Any]): <NEW_LINE> <INDENT> use_func_name = None <NEW_LINE> with suppress(KeyError): <NEW_LINE> <INDENT> use_func = kwargs.pop('_call_func') <NEW_LINE> if use_func is not None: <NEW_LINE> <INDENT> use_func_name = use_func.__qualname__ <NEW_LINE> <DEDENT> else: <NEW_...
Build a formatted string for a function signature.
625941eb63b5f9789fde75d0
@api_view(['POST', ]) <NEW_LINE> def index(request): <NEW_LINE> <INDENT> print("Hit API") <NEW_LINE> r = get_redis() <NEW_LINE> print("API POST") <NEW_LINE> r.incr('clicks') <NEW_LINE> return Response()
Test index page for clicks app.
625941eb71ff763f4b549b7f
def testFakeDataSet2(self): <NEW_LINE> <INDENT> string_db = StringDB('rdf_graph', True) <NEW_LINE> string_db.graph = RDFGraph() <NEW_LINE> self.assertEqual(len(string_db.graph), 0) <NEW_LINE> dataframe = pd.DataFrame(data=self.test_set_2, columns=self.columns) <NEW_LINE> string_db._process_protein_links(dataframe, self...
Dataset contains a deprecated protein ID that we expect if filtered out by ensembl biomart We test that this returns an empty graph :return:
625941ebd8ef3951e3243a28
def get_rnn_params(self): <NEW_LINE> <INDENT> n_hidden = self.n_hidden <NEW_LINE> sparsity = self.sparsity <NEW_LINE> rec_spec_rad = self.recurrence_spectral_radius <NEW_LINE> input_rad = self.recurrence_input_scale <NEW_LINE> depth = self.depth <NEW_LINE> if self.rnn_layer == sru_tip_layer: <NEW_LINE> <INDENT> rnn_par...
uhs = operators[0] w0s = operators[1] uzs = operators[2] wzs = operators[3] urs = operators[4] wrs = operators[5] :return:
625941ebe1aae11d1e74a1a7
def to_ss(self): <NEW_LINE> <INDENT> return StateSpace(*tf2ss(self.num, self.den))
Convert system representation to `StateSpace`. Returns ------- sys : instance of `StateSpace` State space model of the current system
625941eb925a0f43d254a366
def test_topic(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> driver.find_element(*test_page.topic_loc).click() <NEW_LINE> select = driver.find_element(*test_page.select_loc) <NEW_LINE> Select(select).select_by_value('share') <NEW_LINE> driver.find_element(*test_page.title_loc).send_keys('这个select框是By_Valu...
发布话题
625941ebd99f1b3c44c67a70
def __init__(self, iface, parent=None): <NEW_LINE> <INDENT> super(RasterDestripeDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.iface = iface <NEW_LINE> self.populateProc() <NEW_LINE> self.ButtonBrowseRaster.clicked.connect(self.outFileBrowse) <NEW_LINE> self.runButton.clicked.connect(self....
Constructor.
625941ebd18da76e235329c7