code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_images_in_use(ec2): <NEW_LINE> <INDENT> amis = set() <NEW_LINE> for instance in ec2.instances.all(): <NEW_LINE> <INDENT> amis.add(instance.image_id) <NEW_LINE> <DEDENT> return amis
Returns a list of image IDs in use by any EC2 instance.
625941f0e76e3b2f99f3ad8b
def test_meap01(): <NEW_LINE> <INDENT> test_path = tempfile.mkdtemp() <NEW_LINE> x_train, metadata = meap01(test_path) <NEW_LINE> try: <NEW_LINE> <INDENT> assert x_train.shape == (1823, 11) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> shutil.rmtree(test_path) <NEW_LINE> raise()
Test module meap01.py by downloading meap01.csv and testing shape of extracted data has 1823 rows and 11 columns
625941f0442bda511e8be999
def decToHex(string_num): <NEW_LINE> <INDENT> num = int(string_num) <NEW_LINE> mid = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> if num == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> num, rem = divmod(num, 16) <NEW_LINE> mid.append(base[rem]) <NEW_LINE> <DEDENT> return ''.join([str(x) for x in mid[::-1]])
将十进制转换为十六进制
625941f0d58c6744b42581e7
def at_object_creation(self): <NEW_LINE> <INDENT> self.db.role = " the Citizen" <NEW_LINE> self.db.potassium = 0 <NEW_LINE> self.db.carbs = 0 <NEW_LINE> self.db.magnesium = 0 <NEW_LINE> self.db.iron = 0 <NEW_LINE> self.db.disorders = None <NEW_LINE> self.cmdset.add_default(CmdSetTest, permanent=True)
This is called when object is first created, only.
625941f071ff763f4b549c1f
def format_profile(self, userid: UserID, profile: ValidatedDict) -> Node: <NEW_LINE> <INDENT> return Node.void('gametop')
Base handler for a profile. Given a userid and a profile dictionary, return a Node representing a profile. Should be overridden.
625941f024f1403a926010ea
def add_func(self, func): <NEW_LINE> <INDENT> self.syncTasks.append(func) <NEW_LINE> self.logger.info("[ParallelQt] New task added")
Add function as next background task. :param func: The function to be added :return: None
625941f09b70327d1c4e1361
def arg_max(t): <NEW_LINE> <INDENT> m = max(t) <NEW_LINE> for i in range(len(t)): <NEW_LINE> <INDENT> if t[i] == m: <NEW_LINE> <INDENT> return i
Retourne l'indice du maximum de t.
625941f07b180e01f3dc4d7a
def calculate_probabilities(inputs, means, stds): <NEW_LINE> <INDENT> likelihood = [] <NEW_LINE> for input, mean, std in zip(inputs, means, stds): <NEW_LINE> <INDENT> exp_part = -(((input - mean) * (input - mean))/(2 * std * std)) <NEW_LINE> mult_part = 1/(math.sqrt(2 * 3.142) * std) <NEW_LINE> answer = mult_part * mat...
:param inputs: features of a single input from test data :param means: means of features :param stds: standard deviation of features :return: likelihood probabilities for a class
625941f07c178a314d6ef9f2
def generate(self, capture_api_file): <NEW_LINE> <INDENT> logger.info("[Initial]:开始通过Postman集合转换生成Excel接口抓包文档......") <NEW_LINE> file_extend = str(os.path.splitext(capture_api_file)[-1]).lower() <NEW_LINE> try: <NEW_LINE> <INDENT> postman_collection_df = self.load_collection <NEW_LINE> if file_extend not in [".xls", "....
生成接口抓包文档(当前支持Excel文件[xls/xlsx]) :param capture_api_file: 接口抓包文档路径 :return:
625941f050485f2cf553d325
def main(): <NEW_LINE> <INDENT> coloredlogs.install(level='DEBUG', fmt='%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s') <NEW_LINE> logger.setLevel(logging.DEBUG) <NEW_LINE> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--gym-env', type=str, default='PongNoFrameskip-v4', help='OpenAi Gy...
Run main program. Requirements: sudo apt-get install python3-tk Usage: python3 get_demo.py --gym-env=PongNoFrameskip-v4 --num-episodes=5 --demo-time-limit=20 --hz=60.0 --create-movie
625941f07cff6e4e81117f0f
def lock_check(USERNAME): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> outputs = check_output("grep %s: /etc/shadow" % USERNAME, shell=True) <NEW_LINE> outputs = outputs.split("\n") <NEW_LINE> for output in outputs: <NEW_LINE> <INDENT> if output.startswith("%s:" % USERNAME): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT...
Checking user lock status Input: USERNAME -- username. Output: True -- user lock, False -- user unlock, None -- lock_check() error.
625941f04428ac0f6e5bad81
def delete_with_regexp(self, regexp, root=None): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> root = self.folder <NEW_LINE> <DEDENT> if regexp is not None: <NEW_LINE> <INDENT> file_names = find_with_regexp(regexp, root) <NEW_LINE> if file_names: <NEW_LINE> <INDENT> self.log.debug( "From regexp %r in folder ...
Deletes all files compatible with the given `regexp`. If `regexp` is `None` and `root` is defined, deletes the `root` folder.
625941f023849d37ff7b3614
def MessageBox(*args, **kwargs): <NEW_LINE> <INDENT> result = Tester.dialogTester.runNext(None) <NEW_LINE> if result is not None: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> wx.GetApp().unbindActivateApp() <NEW_LINE> result = wx.MessageBox(*args, **kwargs) <NEW_LINE> wx.GetApp().bindActivateApp() <NEW_LINE> r...
Замена стандартного MessageBox. Перед показом диалога отключает приложение от события EVT_ACTIVATE_APP.
625941f0cb5e8a47e48b802a
def fix_patches(series, fnames): <NEW_LINE> <INDENT> backup_dir = None <NEW_LINE> count = 0 <NEW_LINE> for fname in fnames: <NEW_LINE> <INDENT> cmt = series.commits[count] <NEW_LINE> cmt.patch = fname <NEW_LINE> cmt.count = count <NEW_LINE> result = fix_patch(backup_dir, fname, series, cmt) <NEW_LINE> if result: <NEW_L...
Fix up a list of patches identified by filenames The patch files are processed in place, and overwritten. Args: series (Series): The Series object fnames (:type: list of str): List of patch files to process
625941f08a349b6b435e86fc
def __setitem__(self, key, color): <NEW_LINE> <INDENT> cmd = bytearray(2 + self._bpp) <NEW_LINE> struct.pack_into(">H", cmd, 0, key * self._bpp) <NEW_LINE> if isinstance(color, int): <NEW_LINE> <INDENT> w = color >> 24 <NEW_LINE> r = (color >> 16) & 0xFF <NEW_LINE> g = (color >> 8) & 0xFF <NEW_LINE> b = color & 0xFF <N...
Set one pixel to a new value
625941f0b57a9660fec33e16
def rubberBandStartEvent(self, event): <NEW_LINE> <INDENT> self._rubberBandStartPos = event.pos() <NEW_LINE> rect = QtCore.QRect(self._rubberBandStartPos, QtCore.QSize()) <NEW_LINE> rubberBand = self.rubberBand() <NEW_LINE> rubberBand.setGeometry(rect) <NEW_LINE> rubberBand.show()
Triggered when the user presses an empty area. :type event: QtWidgets.QMouseEvent :rtype: None
625941f00c0af96317bb8770
def to_gro(self, fpath): <NEW_LINE> <INDENT> raise NotImplementedError('Writing to GRO format file not supported.')
Write data to GRO format file
625941f091af0d3eaac9bfa7
def find_time_to_escape(cow_speed, cow_distance): <NEW_LINE> <INDENT> if cow_speed == 0: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return round(cow_distance/cow_speed,2)
Type contract: (float, float) -> float Description: returns the time needed for the cow to escape given a speed and distance Example: >>> find_time_to_escape(2.0, 8.0) 4.0
625941f0d6c5a102081445d9
def get_value(self): <NEW_LINE> <INDENT> return u"\n".join( u"{} {}".format(document.link, document.title) for document in self.row_converter.obj.documents )
Generate a new line separated string for all document links. Returns: string containing all evidence URLs and titles.
625941f092d797404e304716
def testCastFromExtMDerived1ToMDerived1Bases(self): <NEW_LINE> <INDENT> a = ExtMDerived1() <NEW_LINE> refcnt = sys.getrefcount(a) <NEW_LINE> b1 = a.castToBase1() <NEW_LINE> self.assert_(isinstance(b1, MDerived1)) <NEW_LINE> self.assert_(isinstance(b1, ExtMDerived1)) <NEW_LINE> b2 = a.castToBase2() <NEW_LINE> self.asser...
Python defined class ExtMDerived1 is casted by C++ to MDerived1 parents and the binding must return the correct ExtMDerived1 instance.
625941f0435de62698dfe1d6
def fitExponentialToChunk(fitType,xdata,Y,chunkIdx): <NEW_LINE> <INDENT> fits = [] <NEW_LINE> if fitType == "decrease": <NEW_LINE> <INDENT> for ydata in Y: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fitResult = curve_fit(expDecrease,xdata[~np.isnan(ydata)],ydata[~np.isnan(ydata)], bounds=(0, [1., 1., 0.01])) <NEW_LIN...
To Do: get is nan for complete Y and index by row.
625941f0d99f1b3c44c67b0d
def backpropagation(self, final_outputs, hidden_outputs, X, y, delta_weights_i_h, delta_weights_h_o): <NEW_LINE> <INDENT> error = y-final_outputs <NEW_LINE> output_error_term = error <NEW_LINE> hidden_error = np.dot(output_error_term, self.weights_hidden_to_output.T) <NEW_LINE> hidden_error_term = hidden_error * (hidde...
Implement backpropagation Arguments --------- final_outputs: output from forward pass y: target (i.e. label) batch delta_weights_i_h: change in weights from input to hidden layers delta_weights_h_o: change in weights from hidden to output layers
625941f09c8ee82313fbbd01
@cython.locals(start=int, q=int, single_q=int, double_q=int, hash_mark=int, end=int, k=int, counter=int, quote_len=int) <NEW_LINE> def strip_string_literals(code, prefix='__Pyx_L'): <NEW_LINE> <INDENT> new_code = [] <NEW_LINE> literals = {} <NEW_LINE> counter = 0 <NEW_LINE> start = q = 0 <NEW_LINE> in_quote = False <NE...
Normalizes every string literal to be of the form '__Pyx_Lxxx', returning the normalized code and a mapping of labels to string literals.
625941f0090684286d50f279
def watch(cams, path=None, delay=10): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> for c in cams: <NEW_LINE> <INDENT> c.snap(path) <NEW_LINE> <DEDENT> time.sleep(delay)
Get screenshots from all cams at defined intervall.
625941f0236d856c2ad44d6c
def setSecond( self, value ): <NEW_LINE> <INDENT> if 0 <= value < 60: <NEW_LINE> <INDENT> self.__second = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("second (%d) must be in range 0-59, inclusive" % value)
Set method for second attribute
625941f08e71fb1e9831dd30
def TL_im_detect_end(scores, bbox_pred, rois,im): <NEW_LINE> <INDENT> blobs, im_scales = _get_blobs(im) <NEW_LINE> assert len(im_scales) == 1, "Only single-image batch implemented" <NEW_LINE> boxes = rois[:, 1:5] / im_scales[0] <NEW_LINE> scores = np.reshape(scores, [scores.shape[0], -1]) <NEW_LINE> bbox_pred = np.resh...
To get the box Need to provide cls_prob, bbox_pred, rois provide by the function TL_im_detect
625941f0379a373c97cfb0d0
def random_name(gender): <NEW_LINE> <INDENT> last_name = random.choice(last_names) <NEW_LINE> first_name = random.choice(first_names[gender]) <NEW_LINE> return last_name + first_name
随机产生一个名字
625941f056ac1b37e626474e
def unpack_bytes_from_file(compressed_file): <NEW_LINE> <INDENT> sio = StringIO() <NEW_LINE> sink = PlainFPSink(sio) <NEW_LINE> with open(compressed_file, 'rb') as fp: <NEW_LINE> <INDENT> source = CompressedFPSource(fp) <NEW_LINE> unpack(source, sink) <NEW_LINE> return sio.getvalue(), source.metadata
Uncompress bytes from a file. Parameters ---------- compressed_file : str the name of the input file Returns ------- bytes_ : bytes_ the decompressed bytes metadata : bytes the metadata contained in the file if present Raises ------ FormatVersionMismatch if the file has an unmatching format version ...
625941f024f1403a926010eb
@mod_catalog.route('/index/') <NEW_LINE> @mod_catalog.route('/') <NEW_LINE> def catalog(): <NEW_LINE> <INDENT> categories = Category.get_categories() <NEW_LINE> latest_items = Item.query.join(Category) .add_columns(Category.name, Item.title, Item.date_created, Item.id) ...
Handle requests to the /category/ and /catalog/index/ route List latest items and all categories
625941f04e696a04525c99d7
def prepare_manager(): <NEW_LINE> <INDENT> class MyManager(BaseManager): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create_setter_getters(cls): <NEW_LINE> <INDENT> def set_attr(self, attr, val): <NEW_LINE> <INDENT> setattr(self, attr, val) <NEW_LINE> <DEDENT> def get_attr(self, attr): <NEW_LINE> <INDENT> return g...
Configures a multiprocessing manager by registering the classes of this module, along with adding the required setters and getters for it in order to easily access the attributes of a given class attributes. Also configures a manager for shared objects between all proxy-managed instances. Used for queues. The 1st re...
625941f08e05c05ec3eea903
def effect_condition_to_pddl(self, condition_sting, class_name, operator_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.parse_conditional_statement(condition_sting = condition_sting, class_name = class_name, context = self.classes[class_name]['operators'][operator_name]['parameters']) <N...
This procedure translates operator's effect condition into PDDL
625941f094891a1f4081c036
def register_pack(self, pack_name, pack_dir): <NEW_LINE> <INDENT> if self._use_pack_cache and pack_name in REGISTERED_PACKS_CACHE: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> LOG.debug("Registering pack: %s" % (pack_name)) <NEW_LINE> REGISTERED_PACKS_CACHE[pack_name] = True <NEW_LINE> try: <NEW_LINE> <INDENT> pack_d...
Register pack in the provided directory.
625941f0dc8b845886cb5ac1
def discovery(*listeners: Listener, session: ClientSession = None) -> DiscoveryService: <NEW_LINE> <INDENT> service = _DiscoveryServiceImpl(session=session) <NEW_LINE> for listener in listeners: <NEW_LINE> <INDENT> service.add_listener(listener) <NEW_LINE> <DEDENT> return service
Create discovery service. Returned object is a asynchronous context manager so can be used with 'async with' statement. Alternately call start_discovery or start_discovery_async to commence the discovery process.
625941f030bbd722463cc353
def test04a_int(self): <NEW_LINE> <INDENT> root = self.rootgroup <NEW_LINE> if common.verbose: <NEW_LINE> <INDENT> print('\n', '-=' * 30) <NEW_LINE> print("Running %s.test04a_int..." % self.__class__.__name__) <NEW_LINE> <DEDENT> byteorder = {'little': 'big', 'big': 'little'}[sys.byteorder] <NEW_LINE> earray = self.h5f...
Checking earray with byteswapped appends (2, ints)
625941f00c0af96317bb8771
def is_break_stmt(self): <NEW_LINE> <INDENT> return True
Returns ``True``.
625941f021a7993f00bc8284
def __init__(self, key): <NEW_LINE> <INDENT> super(RedlinkData, self).__init__(key)
@type key: str @param key: api key
625941f060cbc95b062c6acd
def main(argv=None, directory=None): <NEW_LINE> <INDENT> logging.basicConfig(format='%(message)s') <NEW_LINE> argv = argv or sys.argv <NEW_LINE> arg_dict = parse_coverage_args(argv[1:]) <NEW_LINE> GitPathTool.set_cwd(directory) <NEW_LINE> fail_under = arg_dict.get('fail_under') <NEW_LINE> percent_covered = generate_cov...
Main entry point for the tool, used by setup.py Returns a value that can be passed into exit() specifying the exit code. 1 is an error 0 is successful run
625941f0cc40096d61595ed8
def wait_completion_timeout(self, iterations): <NEW_LINE> <INDENT> iters = ( shared_utils.THREAD_MTURK_POLLING_SLEEP / shared_utils.THREAD_MEDIUM_SLEEP ) <NEW_LINE> i = 0 <NEW_LINE> while not self.hit_is_complete and i < iters * iterations: <NEW_LINE> <INDENT> time.sleep(shared_utils.THREAD_SHORT_SLEEP) <NEW_LINE> i +=...
Suspends the thread waiting for hit completion for some number of iterations on the THREAD_MTURK_POLLING_SLEEP time
625941f0cc0a2c11143dd41c
def _sort_test_list(self, test_list): <NEW_LINE> <INDENT> return sorted(test_list, key=self._get_test_number)
Try to sort a list of test runned by numbers if have.
625941f073bcbd0ca4b2c5ff
def get_config(): <NEW_LINE> <INDENT> username = getpass.getuser() <NEW_LINE> if platform.system() == "Windows": <NEW_LINE> <INDENT> config_dir = f"C:\\Users\\{username}\\AppData\\Roaming\\mpddrp\\" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config_dir = f"/home/{username}/.config/mpddrp/" <NEW_LINE> <DEDENT> defaul...
reads the config file and returns it as an object
625941f05166f23b2e1a56e3
def get_uuid(input_str): <NEW_LINE> <INDENT> temp_md5 = md5(NAMESPACE_DNS.bytes + input_str.encode('utf-8')).digest() <NEW_LINE> return str(UUID(bytes=temp_md5[:16], version=3)).upper()
Convert a string to a UUID. Given a project name string, create a 128 bit unique hash for Visual Studio. Args: input_str: Unicode string of the filename to convert into a hash Returns: A string in the format of CF994A05-58B3-3EF5-8539-E7753D89E84F
625941f05fdd1c0f98dc07bf
def pyramidnet164_a270_bn_svhn(num_classes=10, **kwargs): <NEW_LINE> <INDENT> return get_pyramidnet_cifar( num_classes=num_classes, blocks=164, alpha=270, bottleneck=True, model_name="pyramidnet164_a270_bn_svhn", **kwargs)
PyramidNet-164 (a=270, bn) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- num_classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/....
625941f06fece00bbac2dcd0
@hook.command <NEW_LINE> def cdecl(inp): <NEW_LINE> <INDENT> return http.get("http://cdecl.org/query.php", q=inp)
.cdecl <expr> -- translate between C declarations and English, using cdecl.org
625941f0f548e778e58cdb0a
def oxygen_mobility(T): <NEW_LINE> <INDENT> return 1.0e4/T*np.exp(-0.86/(k*T))
Mobility of oxygen vacancy at given temperature
625941f04527f215b584c9dc
def json_to_kml(): <NEW_LINE> <INDENT> pass
Converts a JSON file created using the water_stn_downloader module to KML
625941f026068e7796caf272
def filter(self, qs, value): <NEW_LINE> <INDENT> raise NotImplementedError()
Args: qs (django.db.models.query.QuerySet): The Content Queryset value (string): The RepositoryVersion href to filter by
625941f08e71fb1e9831dd31
def load_args_from_snapshot(args, path_vars=PATH_VARS): <NEW_LINE> <INDENT> if not args.snapshot.exists(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif len(args.snapshot.name) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> snapshot, logfile = args.snapshot, args.logfile <NEW_LINE> with open(args...
Update arguments with those from snapshot JSON
625941f0adb09d7d5db6cd16
def Parse(self, pentest, file_opened, **_kwargs): <NEW_LINE> <INDENT> tags = ["todo"] <NEW_LINE> data = file_opened.read().decode("utf-8") <NEW_LINE> notes = "" <NEW_LINE> if data.strip() == "": <NEW_LINE> <INDENT> return None, None, None, None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hosts = parse_dirsearch_file(...
Parse a opened file to extract information Args: file_opened: the open file _kwargs: not used Returns: a tuple with 4 values (All set to None if Parsing wrong file): 0. notes: notes to be inserted in tool giving direct info to pentester 1. tags: a list of tags to be added to tool 2...
625941f0925a0f43d254a407
def _load_embed_txt(embed_file): <NEW_LINE> <INDENT> emb_dict = dict() <NEW_LINE> with codecs.getreader("utf-8")(tf.gfile.GFile(embed_file, 'rb')) as f: <NEW_LINE> <INDENT> emb_num, emb_size = f.readline().strip().split() <NEW_LINE> emb_num = int(emb_num) <NEW_LINE> emb_size = int(emb_size) <NEW_LINE> for line in f: <N...
Load embed_file into a python dictionary. Note: the embed_file should be a Glove formated txt file. Assuming embed_size=5, for example: the -0.071549 0.093459 0.023738 -0.090339 0.056123 to 0.57346 0.5417 -0.23477 -0.3624 0.4037 and 0.20327 0.47348 0.050877 0.002103 0.060547 Note: The first line stores the informati...
625941f0d10714528d600275
def build_laplacian_pyramid(im, max_levels, filter_size): <NEW_LINE> <INDENT> gaussian_pyr, filter_vec = build_gaussian_pyramid(im, max_levels, filter_size) <NEW_LINE> pyr = [] <NEW_LINE> max_levels = len(gaussian_pyr) <NEW_LINE> for i in range(max_levels - 1): <NEW_LINE> <INDENT> pyr.append(gaussian_pyr[i] - expand_im...
this function creates a laplacian image pyramid :param im: the image to create the pyramid from :param max_levels: number of max levels in the pyramid :param filter_size: the size of the filter used to blur the image :return: tuple of the pyramid, and the filter used to create it
625941f0eab8aa0e5d26e0e5
def convert_listDict2DictColumn(self,rows_I,column_I): <NEW_LINE> <INDENT> rows_O = {}; <NEW_LINE> try: <NEW_LINE> <INDENT> if rows_I: <NEW_LINE> <INDENT> for d in rows_I: <NEW_LINE> <INDENT> if d[column_I] in rows_O.keys(): <NEW_LINE> <INDENT> rows_O[d[column_I]].append(d); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
convert a [{},...] to {:[{},...],...} INPUT: rows_I = list of dictionaries column_I = name of the column OUTPUT: rows_O = dict of lists of dictionaries
625941f0e64d504609d74dca
def jj(*args, **kw): <NEW_LINE> <INDENT> delim = kw.get('delim', ' ') <NEW_LINE> try: <NEW_LINE> <INDENT> return delim.join(str(x) for x in args) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return delim.join(six.text_type(x) for x in args)
jj is a more flexible join(), handy for debug output >>> jj(330,'info',None) '330 info None'
625941f03346ee7daa2b32fc
def _history_lookup(self): <NEW_LINE> <INDENT> to_return = (None, None, [], None, None) <NEW_LINE> if not self.nzb_name and not self.folder_name: <NEW_LINE> <INDENT> self.in_history = False <NEW_LINE> return to_return <NEW_LINE> <DEDENT> names = [] <NEW_LINE> if self.nzb_name: <NEW_LINE> <INDENT> names.append(self.nzb_...
Look up the NZB name in the history and see if it contains a record for self.nzb_name :return: A (indexer_id, season, [], quality, version) tuple. The first two may be None if none were found.
625941f0d4950a0f3b08c8d1
def possible_mu0s(SUK, v): <NEW_LINE> <INDENT> beta_and_ns = [[beta,beta.valuation(v)] for beta in SUK.fundamental_units()] <NEW_LINE> betak, nk = beta_k(beta_and_ns) <NEW_LINE> ns = [beta[1] for beta in beta_and_ns if beta[0] != betak] <NEW_LINE> betas = [beta[0] for beta in beta_and_ns if beta[0] != betak] <NEW_LINE>...
Return a list `[\mu_0]` of all possible `\mu_0` values defined in [AKMRVW]_. INPUT: - ``SUK`` -- a group of `S`-units - ``v`` -- a finite place of ``K`` OUTPUT: A list ``[mu0s]`` where each ``mu0`` is an element of ``K`` EXAMPLES:: sage: from sage.rings.number_field.S_unit_solver import possible_mu0s sage...
625941f0ac7a0e7691ed464c
def __init__(self, name=None, slug=None, site=None): <NEW_LINE> <INDENT> self.swagger_types = { 'name': 'str', 'slug': 'str', 'site': 'SiteNestedSerializer' } <NEW_LINE> self.attribute_map = { 'name': 'name', 'slug': 'slug', 'site': 'site' } <NEW_LINE> self._name = name <NEW_LINE> self._slug = slug <NEW_LINE> self._sit...
WriteRackGroupSerializer - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941f0bf627c535bc1375a
def get_snps(x: str) -> tuple: <NEW_LINE> <INDENT> snp, loc = x.split(' ') <NEW_LINE> chrom, position = loc.strip('()').split(':') <NEW_LINE> return snp, chrom, int(position)
Parse a SNP line and return name, chromsome, position.
625941f0460517430c394700
@pytest.mark.parametrize( "plaintext, row_key, col_key, ciphertext", [ ("hello world!", (2, 1, 0), (3, 2, 1, 0), "!dlrow olleh"), ("Luther College", (1, 0), (5, 4, 6, 0, 1, 3, 2), "geeCollre Luht"), ( "Information Assurance and Security.", (5, 3, 1, 6, 4, 0, 2), (3, 1, 0, 4, 2), "cS uenrucaiamotyir.tn edaonIrfs nsA", )...
Testing phrase encryption
625941f00a50d4780f667422
def initialize_chain(test_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join("cache", "node0")): <NEW_LINE> <INDENT> devnull = open("/dev/null", "w+") <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> datadir=initialize_datadir("cache", i) <NEW_LINE> args = [ os.getenv("BITCOIND", "sendd"), "-keypool=1", "-dat...
Create (or copy from cache) a 200-block-long chain and 4 wallets. sendd and send-cli must be in search path.
625941f0aad79263cf390fd4
def getCurrencyExchangeRate(fromCurrency, toCurrency): <NEW_LINE> <INDENT> url = f"https://api.ratesapi.io/api/latest?" f"base={fromCurrency}&" f"symbols={toCurrency}" <NEW_LINE> response = requests.get(url, verify=False) <NEW_LINE> exchangeRateDict = json.loads(response.text) <NEW_LINE> exchangeRate = ex...
Parameters are acronyms. Currency acronyms can be found on the following link: https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html
625941f03539df3088e2e8d6
def _discover_all(self): <NEW_LINE> <INDENT> if self._discovered: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._log.debug("Discovering all on %s", self._name) <NEW_LINE> for thing in self._handle.iterate(simulator.OBJECTS): <NEW_LINE> <INDENT> name = thing.get_name_string() <NEW_LINE> path = self._child_path(nam...
When iterating or performing IPython tab completion, we run through ahead of time and discover all possible children, populating the :any:`_sub_handles` mapping. Hierarchy can't change after elaboration so we only have to do this once.
625941f007f4c71912b11a10
def process(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hsv = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV) <NEW_LINE> self.__mask = cv2.inRange(hsv, self.__colorThresholds[0], self.__colorThresholds[1]) <NEW_LINE> <DEDENT> except cv2.error: <NEW_LINE> <INDENT> print("process: image not found!!!")
Start processing
625941f07d847024c06be84c
def moving_eddies_example(grid, npart=2, mode='jit', verbose=False, method=AdvectionRK4): <NEW_LINE> <INDENT> ParticleClass = JITParticle if mode == 'jit' else Particle <NEW_LINE> pset = grid.ParticleSet(size=npart, pclass=ParticleClass, start=(3.3, 46.), finish=(3.3, 47.8)) <NEW_LINE> if verbose: <NEW_LINE> <INDENT> p...
Configuration of a particle set that follows two moving eddies :arg grid: :class Grid: that defines the flow field :arg npart: Number of particles to intialise
625941f08c3a87329515894c
def addAccount(self, accountNumber): <NEW_LINE> <INDENT> pass
Parameters: - accountNumber
625941f0287bf620b61d3feb
def delSeenByFor( self, ob, uname=None ): <NEW_LINE> <INDENT> uid = self.__uid(ob) <NEW_LINE> values = self._values.get( ID=uid ) <NEW_LINE> if not values: return <NEW_LINE> if uname: <NEW_LINE> <INDENT> members = [ member for ID, seen_time, member in values ] <NEW_LINE> IsChanged = 0 <NEW_LINE> if uname not in ( ListT...
Removes seen by entry for the given user. Arguments: 'ob' -- Task item. 'uname' -- User id string/list.
625941f00fa83653e4657542
def send_message(self, message, candidate): <NEW_LINE> <INDENT> assert isinstance(message, Message.Implementation), message <NEW_LINE> assert isinstance(candidate, Candidate) <NEW_LINE> logger.debug("%s to %s", message.name, candidate) <NEW_LINE> self.encode_message(message) <NEW_LINE> return self.send_packet(message.p...
Sends MESSAGE to ADDRESS using the nodes' socket after it is encoded. Returns MESSAGE
625941f0be383301e01b5a05
def __init__(self, p_pyhouse_obj): <NEW_LINE> <INDENT> self.m_headers = Headers({'User-Agent': ['AutoUpdate Web Client']}) <NEW_LINE> if p_pyhouse_obj != None: <NEW_LINE> <INDENT> self.m_pyhouse_obj = p_pyhouse_obj <NEW_LINE> self.m_hue_agent = Agent(p_pyhouse_obj._Twisted.Reactor) <NEW_LINE> LOG.info('Initialized') <N...
Agent is a very basic HTTP client. It supports I{HTTP} and I{HTTPS} scheme URIs.
625941f0711fe17d825428e9
@register.function <NEW_LINE> def field_errors(field): <NEW_LINE> <INDENT> return Markup(render_to_string('form-error.html', {'field': field}))
Return string with rendered template with field errors.
625941f0627d3e7fe0d693dd
def hangman(secret_word): <NEW_LINE> <INDENT> secret_word = "apple" <NEW_LINE> letters_guessed = [] <NEW_LINE> warnings_and_guesses_left = (3,6) <NEW_LINE> won_game = False <NEW_LINE> print("Welcome to the game Hangman!") <NEW_LINE> print("I am thinking of a word that is", len(secret_word), "letters long.") <NEW_LINE> ...
secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before each round, you should display to the user how ...
625941f0fff4ab517eb2f9cb
def handle_show_recipes(self, message): <NEW_LINE> <INDENT> foodTitle = message.data["recipe"].lower() <NEW_LINE> for x in globalObject['hits']: <NEW_LINE> <INDENT> mapLabel = x['recipe']['label'].replace("-", "").replace(" ", "").lower() <NEW_LINE> if mapLabel == foodTitle: <NEW_LINE> <INDENT> recipeTitle = x['recipe'...
Show Recipes By Keywords
625941f030dc7b7665901eeb
def sit(self): <NEW_LINE> <INDENT> print(self.name.title() + " is now sitting.")
模拟小狗被命令是蹲下
625941f0187af65679ca56ab
def test_naive_bayes(object_dict): <NEW_LINE> <INDENT> lines = read_data('test') <NEW_LINE> acc_count =0 <NEW_LINE> line_count = 0 <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line_count +=1 <NEW_LINE> sum_dict = collections.defaultdict(lambda:0) <NEW_LINE> sum = 0 <NEW_LINE> class_name, sentence_list = data_proc...
Take test data and finding accuracy
625941f030c21e258bdfaa2f
def __unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix): <NEW_LINE> <INDENT> validPayload = None <NEW_LINE> vector = None <NEW_LINE> if conf.uColsStop == conf.uColsStart: <NEW_LINE> <INDENT> count = conf.uColsStart <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = __findUnionCharCount(comm...
This method tests if the target url is affected by an inband SQL injection vulnerability. The test is done up to 50 columns on the target database table
625941f0d8ef3951e3243ac9
def test_type(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.temp_b, City) <NEW_LINE> self.assertEqual(type(self.temp_b), City) <NEW_LINE> self.assertEqual(issubclass(self.temp_b.__class__, BaseModel), True) <NEW_LINE> self.assertEqual(isinstance(self.temp_b, BaseModel), True)
test method for type testing of city model
625941f08e7ae83300e4b55a
def id2name(self, unimod_id): <NEW_LINE> <INDENT> return self._map_key_2_index_2_value(unimod_id, "unimodname")
Converts unimod ID to unimod name Args: unimod_id (int): identifier of modification Returns: str: Unimod name
625941f03cc13d1c6d3c7902
def show_result(self): <NEW_LINE> <INDENT> answer = self.question.text() <NEW_LINE> if answer == '': <NEW_LINE> <INDENT> self.result.setText('Hum... Did you click by mistake ?') <NEW_LINE> self.result_image.hide() <NEW_LINE> self.button_retry.hide() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT>...
Apply logic and show results
625941f07b25080760e399e0
def pop(self, idx=-1): <NEW_LINE> <INDENT> temp = self[idx] <NEW_LINE> del self[idx] <NEW_LINE> return temp
Deletes and returns the element at idx (which is the last element, by default).
625941f063d6d428bbe44a7c
def test_harm_without_consent_is_unethical(self): <NEW_LINE> <INDENT> assailant = Person('Assailant') <NEW_LINE> victim = Person('Victim') <NEW_LINE> assailant.do('Victim', 'harm') <NEW_LINE> self.assertFalse(is_ethical_action(assailant, victim, 'harm'), "Harm without consent is unethical")
Harm without consent is unethical
625941f032920d7e50b28760
def main(): <NEW_LINE> <INDENT> bucketname = "static.ucldc.cdlib.org" <NEW_LINE> prefix = "media_json_2" <NEW_LINE> client = boto3.client("s3") <NEW_LINE> for key in get_matching_s3_keys(bucket=bucketname, prefix=prefix, suffix='-media.json'): <NEW_LINE> <INDENT> transform_json(bucketname, key)
iterate over the media.json files in given s3 bucket probably want to create a separate process for getting a list of media.json files that are current and that we want to process. there is likely a lot of crud on s3
625941f0e76e3b2f99f3ad8d
def setUp(self): <NEW_LINE> <INDENT> self.core_controller.start() <NEW_LINE> self.session = self.core_controller.sessions_controller.create_session(request='fake-request') <NEW_LINE> self.session.root_object = tstdk.GAUser(id='user') <NEW_LINE> self.session_event_queue_key = 'eventqueue:%s' % self.session.redis_key
Initialize context
625941f015baa723493c4505
def check_meta(meta): <NEW_LINE> <INDENT> required = ("database", "db_table", "managed") <NEW_LINE> for k in required: <NEW_LINE> <INDENT> if not getattr(meta, k, None): <NEW_LINE> <INDENT> raise ImproperlyConfig(u"%s is need to be configured", k) <NEW_LINE> <DEDENT> <DEDENT> return True
Args: meta(Meta):
625941f0099cdd3c635f11e3
def encircle(x,y, ax=None, **kw): <NEW_LINE> <INDENT> if not ax: ax=plt.gca() <NEW_LINE> p = np.c_[x,y] <NEW_LINE> hull = ConvexHull(p) <NEW_LINE> poly = plt.Polygon(p[hull.vertices,:], **kw) <NEW_LINE> ax.add_patch(poly)
from: https://stackoverflow.com/questions/44575681/how-do-i-encircle-different-data-sets-in-scatter-plot
625941f050812a4eaa59c8a7
def updatelinenumbers(self): <NEW_LINE> <INDENT> self.verticalScrollBar(). setSliderPosition(self.verticalScrollBar().sliderPosition()) <NEW_LINE> self.update_viewport() <NEW_LINE> self.line_number_area.update(0, 0, self.line_number_area.width(), self.height())
Update the line numbers after any change in the viewport.
625941f02eb69b55b151ce43
def check_all(): <NEW_LINE> <INDENT> if not NODE_ROLE.is_fuel(): <NEW_LINE> <INDENT> check_all_profile() <NEW_LINE> check_all_service() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for role in all_roles: <NEW_LINE> <INDENT> check_nodes(role, 'all')
Check All OpenStack Component
625941f07cff6e4e81117f11
def write_dict_to_mongo(data_dict, db, collection, host='localhost', port=27017, username=None, password=None): <NEW_LINE> <INDENT> db = _connect_mongo(host=host, port=port, username=username, password=password, db=db) <NEW_LINE> cursor = db[collection] <NEW_LINE> cursor.insert_one(data_dict)
Write python dictionary to MongoDb document. Args: data_dict: Dictionary to be stored in MongoDb. db: Name of Mongo database. collection: Name of collection in which dictionary will be inserted. host: Mongo server host. port: Port on which Mongo server is listening. username: Username for Mongo...
625941f04428ac0f6e5bad83
def rmswidth(self, floor=0): <NEW_LINE> <INDENT> mywaveunits = self.waveunits.name <NEW_LINE> self.convert('angstroms') <NEW_LINE> wave = self.wave <NEW_LINE> thru = self.throughput <NEW_LINE> self.convert(mywaveunits) <NEW_LINE> if floor != 0: <NEW_LINE> <INDENT> idx = N.where(thru >= floor) <NEW_LINE> wave = wave[idx...
Calculate :ref:`pysynphot-formula-rmswidth`. Parameters ---------- floor : float Throughput values equal or below this threshold are not included in the calculation. By default (0), all points are included. Returns ------- ans : float RMS band width.
625941f0009cb60464c63938
def _dExpForPiecewiselambda(self,rates, tenors): <NEW_LINE> <INDENT> x = np.linspace(0, max(tenors), 100) <NEW_LINE> def rate(s): <NEW_LINE> <INDENT> k = 1 <NEW_LINE> while k <= max(tenors): <NEW_LINE> <INDENT> if s <= tenors[k]: <NEW_LINE> <INDENT> return rates[k-1] <NEW_LINE> <DEDENT> k += 1 <NEW_LINE> <DEDENT> retur...
Probability density function of an Exponential random variable x using piecewise constant lambda to display varying rates. Parameters ========== rates : array(float) piecewise rates of exponential distn ======= pdf : float value of probability density function
625941f03539df3088e2e8d7
def task(ctx, config): <NEW_LINE> <INDENT> assert isinstance(config, dict) <NEW_LINE> config = teuthology.replace_all_with_clients(ctx.cluster, config) <NEW_LINE> log.info('Setting up autotest...') <NEW_LINE> testdir = teuthology.get_testdir(ctx) <NEW_LINE> with parallel() as p: <NEW_LINE> <INDENT> for role in config.k...
Run an autotest test on the ceph cluster. Only autotest client tests are supported. The config is a mapping from role name to list of tests to run on that client. For example:: tasks: - ceph: - ceph-fuse: [client.0, client.1] - autotest: client.0: [dbench] client.1: [bonnie] You can...
625941f08a349b6b435e86fe
def do_attack_all(self, args): <NEW_LINE> <INDENT> self.armada.attack_all() <NEW_LINE> print("[+] All ships in attack range ordered to attack")
Order all ships in range of enemy ships to attack
625941f0de87d2750b860324
def predict(self, item_id, num, data_source): <NEW_LINE> <INDENT> results = self._r.zrange(self.SIMKEY % item_id, 0, num-1, withscores=True, desc=True) <NEW_LINE> ds = pd.read_csv(data_source) <NEW_LINE> for indx, row in ds.iterrows(): <NEW_LINE> <INDENT> if str(row['id']) == item_id: <NEW_LINE> <INDENT> info("Matching...
Couldn't be simpler! Just retrieves the similar items and their 'score' from redis. :param item_id: string, if id == -1, meaning predict for the last one!! :param num: number of similar items to return :return: A list of lists like: [["19", 0.2203], ["494", 0.1693], ...]. The first item in each sub-list is the item ID...
625941f0bd1bec0571d90bba
def update(self, pot, inc_mat, inc_transpose, inv_len_mat): <NEW_LINE> <INDENT> grad = inv_len_mat * inc_transpose * pot <NEW_LINE> if self.coupling == "l2": <NEW_LINE> <INDENT> rhs_ode = (self.tdens ** self.pflux) * ((grad ** 2).sum(axis=1)) - self.tdens <NEW_LINE> <DEDENT> if self.coupling == "l1": <NEW_LINE> <INDENT...
One step update Parameters: pot: np.array, potential matrix on nodes inc_mat: sparse.matrix, oriented incidence matrix inc_transpose: sparse.matrix, oriented incidence matrix transposed inv_len_mat: sparse.matrix, diagonal matrix 1/l_e Returns: tdens: np.array, updated conductivities pot: np.a...
625941f06aa9bd52df037333
def _get_indentation_level(self, docstring_lines, default_existing_docstring=4, default_no_existing_docstring=0): <NEW_LINE> <INDENT> if len(docstring_lines) == 0: <NEW_LINE> <INDENT> return default_no_existing_docstring <NEW_LINE> <DEDENT> if len(docstring_lines) == 1: <NEW_LINE> <INDENT> return default_existing_docst...
Determine the level of indentation of the docstring to match it. The indented content after the first line of a docstring can differ based on the nesting of the functionality being documented. For example, a top-level function may have its "Parameters" section indented four-spaces, but a method nested under a class may...
625941f03617ad0b5ed68482
def collect_time_stats(key): <NEW_LINE> <INDENT> path = os.path.join(_cfg.OUTPUT_PATH, key) <NEW_LINE> if os.path.exists(os.path.join(path, 'time_stats.pkl')): <NEW_LINE> <INDENT> with open(os.path.join(path, 'time_stats.pkl'), 'rb') as f: <NEW_LINE> <INDENT> time_stats = pickle.load(f) <NEW_LINE> <DEDENT> return time_...
Collect time statistics for a learned and cached solver.
625941f056ac1b37e626474f
def greed_alg(input_data): <NEW_LINE> <INDENT> (caches, endpoints) = get_endpoints(input_data) <NEW_LINE> fill_caches_from_endpoints(endpoints) <NEW_LINE> return caches_to_output_data(caches)
Greedy Alg
625941f01b99ca400220b03f
def render(self, latent_color, latent, R, T, clamp_dist=0.1, profile=False, no_grad=False, lighting_locations=None, lighting_energies=None): <NEW_LINE> <INDENT> profiler = Profiler(silent = not profile) <NEW_LINE> profiler.report_process('\nprepare camera time') <NEW_LINE> Zdepth, valid_mask, min_sdf_sample = self.rend...
differentiable rendering. Input: - latent_color type torch.Tensor (1, latent_size) - latent type torch.Tensor (1, latent_size) - R type torch.Tensor (3,3) - T type torch.Tensor (3) Return: - color type torch.Tensor (H, W, 3) - rendered rgb image - Z...
625941f0d99f1b3c44c67b10
def __init__(self, *args, **kw): <NEW_LINE> <INDENT> super(TaskSpec, self).__init__(*args, **kw) <NEW_LINE> self._input_data = {} <NEW_LINE> self._output_data = {} <NEW_LINE> self._dirty = True
Initialize the spec and add private attributes.
625941f010dbd63aa1bd312d
def get_status_inv_base(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = current_app.config['UFRAME_STATUS_INV'] <NEW_LINE> return result <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> message = 'Unable to locate UFRAME_STATUS_INV in config file.' <NEW_LINE> current_app.logger.info(message) <NEW_LINE> raise Ex...
Returns configuration file value for UFRAME_STATUS_INV. ('query') If error, raise exception. Used in 'status/query'
625941f06e29344779a62b9c
def get_organisation_by_orgnumber_or_brreg_number(data, auth_token_username): <NEW_LINE> <INDENT> organisation_entity = {} <NEW_LINE> org_id = data.get("id", None) <NEW_LINE> brreg_number = data.get("org_number", None) <NEW_LINE> if org_id: <NEW_LINE> <INDENT> organisation_entity = get_organisation(org_id, auth_token_u...
If the data dict contains "id", the organisation lookup is done with that, otherwise it will do lookup with "org_number". The JSON representation of the object/dict is returned. If none are specfied, {} is returned. If more than one organisation is found (...) {} is returned.
625941f04527f215b584c9dd
def match_row(self, row): <NEW_LINE> <INDENT> return self.extract_value(row).has_path(self._leaf_tag, self._leaf_value)
called to determine if this row matches. Returns True if it matches; False otherwise Overrides baseclass method.
625941f04e4d5625662d495b
def alltags(self, tagname=None, **attrs): <NEW_LINE> <INDENT> tags = [] <NEW_LINE> for i in range(self.tagmin, self.tagmax + 1): <NEW_LINE> <INDENT> if self.matchtag(i, tagname, attrs): <NEW_LINE> <INDENT> tags.append(Region(self, 0, 0, i)) <NEW_LINE> <DEDENT> <DEDENT> return tags
Return a list of Regions for all the tags entirely within this Region with the given tag name and attributes.
625941f0d18da76e23532a69
def client_disconnect(self, index): <NEW_LINE> <INDENT> if index in self: <NEW_LINE> <INDENT> del self[index]
Remove the player from the cache.
625941f02ae34c7f2600d6bc