code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def secondary_structure_pairs(self): <NEW_LINE> <INDENT> self.H1 = [i for i in itertools.combinations(self.alpha1, 2)] <NEW_LINE> self.H2 = [i for i in itertools.combinations(self.alpha2, 2)] <NEW_LINE> self.B = [i for i in itertools.combinations(self.beta, 2)]
defines the sequence pairs for R/L Alpha Helix and Beta Sheet
625941c182261d6c526ab426
@pytest.fixture <NEW_LINE> def p_chris(): <NEW_LINE> <INDENT> chris = BasicGame.Player(20, "chris", "blue") <NEW_LINE> return chris
This is BOB. He is a player of the game. Does THIS docstring get shown? YES yes it does!
625941c13cc13d1c6d3c7305
def get_cached_bottlenecks_and_converted_labels(sess, image_path_list, batch_size, bottleneck_dir, converted_label_dir, jpeg_data_placeholder, decoded_image_tensor, resized_image_placeholder, bottleneck_tensor, architecture): <NEW_LINE> <INDENT> bottlenecks = [] <NEW_LINE> loss_feed_vals = {} <NEW_LINE> NUM_IMAGES = len(image_path_list) <NEW_LINE> if batch_size >= 0: <NEW_LINE> <INDENT> for unused_i in range(batch_size): <NEW_LINE> <INDENT> image_index = random.randint(0, NUM_IMAGES - 1) <NEW_LINE> image_path = image_path_list[image_index] <NEW_LINE> bottleneck = get_or_create_bottleneck( sess, image_path, bottleneck_dir, jpeg_data_placeholder, decoded_image_tensor, resized_image_placeholder, bottleneck_tensor, architecture) <NEW_LINE> label_path = get_label_path_by_image_path(image_path) <NEW_LINE> loss_feed_val = get_or_create_converted_label(sess, label_path, converted_label_dir, architecture) <NEW_LINE> bottlenecks.append(bottleneck) <NEW_LINE> for k,v in loss_feed_val.items(): <NEW_LINE> <INDENT> if k not in loss_feed_vals: <NEW_LINE> <INDENT> loss_feed_vals[k] = [] <NEW_LINE> <DEDENT> loss_feed_vals[k].append(v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for image_index in range(NUM_IMAGES): <NEW_LINE> <INDENT> image_path = image_path_list[image_index] <NEW_LINE> bottleneck = get_or_create_bottleneck( sess, image_path, bottleneck_dir, jpeg_data_placeholder, decoded_image_tensor, resized_image_placeholder, bottleneck_tensor, architecture) <NEW_LINE> label_path = get_label_path_by_image_path(image_path) <NEW_LINE> loss_feed_val = get_or_create_converted_label(sess, label_path, converted_label_dir, architecture) <NEW_LINE> bottlenecks.append(bottleneck) <NEW_LINE> for k,v in loss_feed_val.items(): <NEW_LINE> <INDENT> if k not in loss_feed_vals: <NEW_LINE> <INDENT> loss_feed_vals[k] = [] <NEW_LINE> <DEDENT> loss_feed_vals[k].append(v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return bottlenecks, loss_feed_vals
Retrieves bottleneck values for cached images. If no distortions are being applied, this function can retrieve the cached bottleneck values directly from disk for images. It picks a random set of images from the specified category. Args: sess: Current TensorFlow Session. image_lists: Dictionary of training images for each label. how_many: If positive, a random sample of this size will be chosen. If negative, all bottlenecks will be retrieved. category: Name string of which set to pull from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. image_dir: Root folder string of the subfolders containing the training images. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. architecture: The name of the model architecture. Returns: List of bottleneck arrays, their corresponding ground truths, and the relevant filenames.
625941c1a219f33f346288f6
def load_user_file(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> json_file = open(self.user_file) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> print('User configuration file not found. Creating default.') <NEW_LINE> self.create_default_json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> json_obj = json.load(json_file) <NEW_LINE> json_file.close() <NEW_LINE> return json_obj
does a quick test to see if we have a user file. if not, we create one. this should use an if not a try though...
625941c1d164cc6175782cd7
def __init__(self, master, controller): <NEW_LINE> <INDENT> ttk.Frame.__init__(self, master) <NEW_LINE> self.logger = logging.getLogger(__name__) <NEW_LINE> self.master = master <NEW_LINE> self.controller = controller <NEW_LINE> self.master_frame = ttk.Frame(self.master) <NEW_LINE> self.top_frame = ttk.Frame(self.master_frame) <NEW_LINE> self.mid_frame = ttk.Frame(self.master_frame) <NEW_LINE> self.view_label_frame = ttk.LabelFrame(self.mid_frame, text='Home Page') <NEW_LINE> self.content_frame = ttk.Frame(self.view_label_frame, width=800, height=600) <NEW_LINE> self.bottom_frame = ttk.Frame(self.master_frame) <NEW_LINE> self.master_frame.pack(side=tk.TOP, fill=tk.BOTH) <NEW_LINE> self.top_frame.pack(side=tk.TOP) <NEW_LINE> self.mid_frame.pack(side=tk.TOP, fill=tk.BOTH) <NEW_LINE> self.view_label_frame.pack(padx=75, pady=10) <NEW_LINE> self.content_frame.pack(side=tk.TOP, fill=tk.BOTH) <NEW_LINE> self.bottom_frame.pack(side=tk.BOTTOM) <NEW_LINE> img1 = ImageTk.PhotoImage(Image.open("src/assets/Logo.png").resize((80, 100), Image.ANTIALIAS)) <NEW_LINE> img_panel1 = ttk.Label(self.top_frame, image=img1) <NEW_LINE> img_panel1.image = img1 <NEW_LINE> self.welcome_label = ttk.Label(self.top_frame) <NEW_LINE> self.home_button = ttk.Button(self.top_frame, text='Home') <NEW_LINE> self.logout_button = ttk.Button(self.bottom_frame, text='Logout') <NEW_LINE> img_panel1.pack(side=tk.LEFT, padx=25, pady=25) <NEW_LINE> self.welcome_label.pack(side=tk.LEFT, padx=25, pady=10) <NEW_LINE> self.home_button.pack(padx=25, pady=25) <NEW_LINE> self.logout_button.pack(padx=25, pady=25)
Initialize Main page
625941c1a79ad161976cc0cf
def __ne__(self, other): <NEW_LINE> <INDENT> return bool()
bool KFileItem.__ne__(KFileItem other)
625941c145492302aab5e24b
def shapefile_to_geodataframe(infile): <NEW_LINE> <INDENT> gpd_data = gpd.GeoDataFrame.from_file(infile) <NEW_LINE> return gpd_data
Convert shapefile into geopandas dataframe
625941c185dfad0860c3ade3
def dispatch(self, mode, queries): <NEW_LINE> <INDENT> if mode not in self.func_registry: <NEW_LINE> <INDENT> message = 'Error: Attempt to invoke unregistered mode |%s|' % (mode) <NEW_LINE> raise Exception(message) <NEW_LINE> <DEDENT> args = [] <NEW_LINE> kwargs = {} <NEW_LINE> unused_args = queries.copy() <NEW_LINE> if self.args_registry[mode]: <NEW_LINE> <INDENT> for arg in self.args_registry[mode]: <NEW_LINE> <INDENT> arg = arg.strip() <NEW_LINE> if arg in queries: <NEW_LINE> <INDENT> args.append(self.__coerce(queries[arg])) <NEW_LINE> del unused_args[arg] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = 'Error: mode |%s| requested argument |%s| but it was not provided.' % (mode, arg) <NEW_LINE> raise Exception(message) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.kwargs_registry[mode]: <NEW_LINE> <INDENT> for arg in self.kwargs_registry[mode]: <NEW_LINE> <INDENT> arg = arg.strip() <NEW_LINE> if arg in queries: <NEW_LINE> <INDENT> kwargs[arg] = self.__coerce(queries[arg]) <NEW_LINE> del unused_args[arg] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if 'mode' in unused_args: del unused_args['mode'] <NEW_LINE> if unused_args: pass <NEW_LINE> self.func_registry[mode](*args, **kwargs)
Dispatch function to execute function registered for the provided mode mode: the string that the function was associated with queries: a dictionary of the parameters to be passed to the called function
625941c17c178a314d6ef3e6
def create_area(self): <NEW_LINE> <INDENT> data = AREADATA[self.__id] <NEW_LINE> i = 0 <NEW_LINE> tileinfo = {} <NEW_LINE> while data[i] != "MAP" and i <= len(data): <NEW_LINE> <INDENT> row = data[i].split("=") <NEW_LINE> tileinfo[row[0]] = row[1].split(",") <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> while i < len(data): <NEW_LINE> <INDENT> row = [] <NEW_LINE> for char in data[i]: <NEW_LINE> <INDENT> if char in tileinfo: <NEW_LINE> <INDENT> tile = Tile(*tileinfo[char]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tile = Tile(*tileinfo["neutral"]) <NEW_LINE> <DEDENT> row.append(tile) <NEW_LINE> <DEDENT> self.__map.append(row) <NEW_LINE> i += 1
The function creates the area from the data previously read from input files. :return: None
625941c18a349b6b435e80fd
def destroy_unit(self, unit): <NEW_LINE> <INDENT> if isinstance(unit, Unit): <NEW_LINE> <INDENT> unit = unit.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unit = str(unit) <NEW_LINE> <DEDENT> self._single_request('Units.Delete', unitName=unit) <NEW_LINE> return True
Delete a unit from the cluster Args: unit (str, Unit): The Unit, or name of the unit to delete Returns: True: The unit was deleted Raises: fleet.v1.errors.APIError: Fleet returned a response code >= 400
625941c1656771135c3eb7f6
@api_1.route('/auth/register/', methods=['POST']) <NEW_LINE> def new_user(): <NEW_LINE> <INDENT> username = request.json.get('username') <NEW_LINE> password = request.json.get('password') <NEW_LINE> if username is None or password is None: <NEW_LINE> <INDENT> return errors.bad_request(400) <NEW_LINE> <DEDENT> if User.query.filter_by(username=username).first() is not None: <NEW_LINE> <INDENT> return errors.bad_request(400) <NEW_LINE> <DEDENT> user = User(username=username) <NEW_LINE> user.hash_password(password) <NEW_LINE> user.date_created = datetime.now() <NEW_LINE> user.save() <NEW_LINE> return jsonify({ 'username': user.username, 'user_url': url_for('api_1.get_user', username=user.username, _external=True) })
Register a new user
625941c1e8904600ed9f1eb4
def masked_cross_entropy(logits, target, length, is_logit=True): <NEW_LINE> <INDENT> logits_flat = logits.view(-1, logits.size(-1)) <NEW_LINE> if is_logit: <NEW_LINE> <INDENT> log_probs_flat = functional.log_softmax(logits_flat, dim=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_probs_flat = torch.log(logits_flat + 1e-10) <NEW_LINE> <DEDENT> target_flat = target.view(-1, 1) <NEW_LINE> losses_flat = -torch.gather(log_probs_flat, dim=1, index=target_flat) <NEW_LINE> losses = losses_flat.view(*target.size()) <NEW_LINE> mask = sequence_mask(sequence_length=length, max_len=target.size(1)) <NEW_LINE> losses = losses * mask.float() <NEW_LINE> loss = losses.sum() / length.float().sum() <NEW_LINE> return loss
Args: logits: A Variable containing a FloatTensor of size (batch, max_len, num_classes) which contains the unnormalized probability for each class. target: A Variable containing a LongTensor of size (batch, max_len) which contains the index of the true class for each corresponding step. length: A Variable containing a LongTensor of size (batch,) which contains the length of each data in a batch. Returns: loss: An average loss value masked by the length.
625941c130c21e258bdfa426
def test_simple(self): <NEW_LINE> <INDENT> m=IMP.Model() <NEW_LINE> p1=IMP.Particle(m) <NEW_LINE> d1=IMP.core.XYZR.setup_particle(p1) <NEW_LINE> d1.set_coordinates((0,0,0)) <NEW_LINE> d1.set_radius(1.0) <NEW_LINE> p2=IMP.Particle(m) <NEW_LINE> d2=IMP.core.XYZR.setup_particle(p2) <NEW_LINE> d2.set_coordinates((10,0,0)) <NEW_LINE> d2.set_radius(2.0) <NEW_LINE> dist=IMP.pmi.get_bipartite_minimum_sphere_distance([d1],[d2]) <NEW_LINE> self.assertEqual(dist,7.0)
simple test
625941c167a9b606de4a7e45
def hint_desc(self, qfield): <NEW_LINE> <INDENT> return self.__hint(qfield, DESCENDING)
Applies a hint for the query that it should use a (``qfield``, DESCENDING) index when performing the query. :param qfield: the instance of :class:`mongoalchemy.QueryField` to use as the key.
625941c19c8ee82313fbb6fe
def getSum(self, a: int, b: int) -> int: <NEW_LINE> <INDENT> pass
put solution here
625941c1507cdc57c6306c60
def options(self, context, module_options): <NEW_LINE> <INDENT> self.met_payload = 'reverse_https' <NEW_LINE> self.procid = None <NEW_LINE> if not 'LHOST' in module_options or not 'LPORT' in module_options: <NEW_LINE> <INDENT> context.log.error('LHOST and LPORT options are required!') <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> if 'PAYLOAD' in module_options: <NEW_LINE> <INDENT> self.met_payload = module_options['PAYLOAD'] <NEW_LINE> <DEDENT> if 'PROCID' in module_options: <NEW_LINE> <INDENT> self.procid = module_options['PROCID'] <NEW_LINE> <DEDENT> self.lhost = module_options['LHOST'] <NEW_LINE> self.lport = module_options['LPORT'] <NEW_LINE> self.ps_script = obfs_ps_script('powersploit/CodeExecution/Invoke-Shellcode.ps1')
LHOST IP hosting the handler LPORT Handler port PAYLOAD Payload to inject: reverse_http or reverse_https (default: reverse_https) PROCID Process ID to inject into (default: current powershell process)
625941c12c8b7c6e89b3574c
@event.listens_for(Index.thumbnail, 'set') <NEW_LINE> @event.listens_for(CommonName.thumbnail, 'set') <NEW_LINE> @event.listens_for(Section.thumbnail, 'set') <NEW_LINE> @event.listens_for(Cultivar.thumbnail, 'set') <NEW_LINE> @event.listens_for(BulkSeries.thumbnail, 'set') <NEW_LINE> @event.listens_for(BulkItem.thumbnail, 'set') <NEW_LINE> def add_thumbnail_to_images(target, value, oldvalue, initiator): <NEW_LINE> <INDENT> if value and value not in target.images: <NEW_LINE> <INDENT> target.images.append(value)
Add `thumbnail` to `images` when setting it.
625941c126238365f5f0edf5
def event_m10_18_x90(z17=10181301, z18=10181300, z19=900000): <NEW_LINE> <INDENT> call = event_m10_18_x66(z17=z17, z18=z18, z19=z19) <NEW_LINE> if call.Get() == 1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif call.Get() == 0: <NEW_LINE> <INDENT> assert event_m10_18_x67(z18=z18) <NEW_LINE> assert event_m10_18_x68(z18=z18, z17=z17, z19=z19) <NEW_LINE> <DEDENT> """State 5: End state""" <NEW_LINE> return 0
[Preset] Iron fence opened with lever z17: Instance ID of iron fence OBJ z18: Lever OBJ instance ID z19: Point ID for Navimesh change
625941c15fc7496912cc3908
def build_mlp(f_input_layer, hidden_units_per_layer): <NEW_LINE> <INDENT> num_f_inputs = f_input_layer.get_shape().as_list()[1] <NEW_LINE> mlp_weights = { 'h1': tf.Variable(tf.random_uniform([num_f_inputs, hidden_units_per_layer], **_weight_init_range(num_f_inputs, hidden_units_per_layer))), 'b1': tf.Variable(tf.zeros([hidden_units_per_layer])), 'h2': tf.Variable(tf.random_uniform([hidden_units_per_layer, hidden_units_per_layer], **_weight_init_range(hidden_units_per_layer, hidden_units_per_layer))), 'b2': tf.Variable(tf.zeros([hidden_units_per_layer])), 'h3': tf.Variable(tf.random_uniform([hidden_units_per_layer, hidden_units_per_layer], **_weight_init_range(hidden_units_per_layer, hidden_units_per_layer))), 'b3': tf.Variable(tf.zeros([hidden_units_per_layer])), 'out': tf.Variable(tf.random_uniform([hidden_units_per_layer, 1], **_weight_init_range(hidden_units_per_layer, 1))), 'b_out': tf.Variable(tf.zeros([1])), } <NEW_LINE> mlp_layer_1 = tf.nn.sigmoid(tf.matmul(f_input_layer, mlp_weights['h1']) + mlp_weights['b1']) <NEW_LINE> mlp_layer_2 = tf.nn.sigmoid(tf.matmul(mlp_layer_1, mlp_weights['h2']) + mlp_weights['b2']) <NEW_LINE> mlp_layer_3 = tf.nn.sigmoid(tf.matmul(mlp_layer_2, mlp_weights['h3']) + mlp_weights['b3']) <NEW_LINE> out = tf.matmul(mlp_layer_3, mlp_weights['out']) + mlp_weights['b_out'] <NEW_LINE> return out, mlp_weights
Builds a feed-forward NN (MLP) with 3 hidden layers.
625941c1baa26c4b54cb10ac
def parse_args() -> Union[argparse.Namespace, int]: <NEW_LINE> <INDENT> parser = init_parser() <NEW_LINE> args = parser.parse_args() <NEW_LINE> global VERBOSE <NEW_LINE> VERBOSE = args.verbose or 0 <NEW_LINE> if args.quiet: <NEW_LINE> <INDENT> VERBOSE = -1 <NEW_LINE> <DEDENT> tiles = args.tiles.lower().split('x') <NEW_LINE> try: <NEW_LINE> <INDENT> args.tiles_width = int(tiles[0]) <NEW_LINE> args.tiles_height = int(tiles[1]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> log(ERR, 'Invalid tiles argument \'{tiles}\'. Should be of the form' ' "WxH" where W and H are ints.', tiles=args.tiles) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> if args.quality <= 0 or 100 < args.quality: <NEW_LINE> <INDENT> args.quality = 92 <NEW_LINE> <DEDENT> if args.watermark: <NEW_LINE> <INDENT> args.watermark = sanitize_path(args.watermark) <NEW_LINE> log(0, 'Watermarking screenshots with \'{0}\'', args.watermark) <NEW_LINE> <DEDENT> video = [] <NEW_LINE> for v in args.video: <NEW_LINE> <INDENT> orig_path = Path(v) <NEW_LINE> video += get_videos(orig_path) <NEW_LINE> if len(video) == 0: <NEW_LINE> <INDENT> log(ERR, 'No videos found from \'{0}\'', orig_path) <NEW_LINE> <DEDENT> <DEDENT> args.video = video <NEW_LINE> if len(args.video) == 0: <NEW_LINE> <INDENT> log(ERR, '\nNo videos found!') <NEW_LINE> return 0 <NEW_LINE> <DEDENT> orig_out = None <NEW_LINE> if args.output is None: <NEW_LINE> <INDENT> args.output = format_outpaths(args.video) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> orig_out = Path(args.output) <NEW_LINE> if orig_out.exists(): <NEW_LINE> <INDENT> if orig_out.is_dir(): <NEW_LINE> <INDENT> args.output = format_outpaths(args.video, orig_out) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args.output = format_outpaths(args.video, orig_out.parent, orig_out.name) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if orig_out.suffix: <NEW_LINE> <INDENT> args.output = format_outpaths(args.video, orig_out.parent, orig_out.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args.output = format_outpaths(args.video, orig_out) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if VERBOSE >= 2: <NEW_LINE> <INDENT> import os <NEW_LINE> log(2, 'Video -> Output: {0}', '-'*10) <NEW_LINE> for i, v in enumerate(args.video): <NEW_LINE> <INDENT> pre = ''.format(os.sep) <NEW_LINE> out = args.output[i] <NEW_LINE> try: <NEW_LINE> <INDENT> out = out.relative_to(v.parent) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pre = '...' + os.sep <NEW_LINE> <DEDENT> log(2, '{input}\n\t-> {pre}{output}', input=v, output=out, pre=pre, print_kwargs={'end': '\n\n'}) <NEW_LINE> <DEDENT> log(2, '-'*72, print_kwargs={'end': '\n\n'}) <NEW_LINE> <DEDENT> return args
Returns: argparse.Namespace: The parsed cli arguments. int: The exit code if the script should exit.
625941c1004d5f362079a2bf
def _maybe_extract_attached_key(self, attachments, address): <NEW_LINE> <INDENT> MIME_KEY = "application/pgp-keys" <NEW_LINE> def log_key_added(ignored): <NEW_LINE> <INDENT> logger.debug('Added key found in attachment for %s' % address) <NEW_LINE> return True <NEW_LINE> <DEDENT> def failed_put_key(failure): <NEW_LINE> <INDENT> logger.info("An error has ocurred adding attached key for %s: %s" % (address, failure.getErrorMessage())) <NEW_LINE> return False <NEW_LINE> <DEDENT> deferreds = [] <NEW_LINE> for attachment in attachments: <NEW_LINE> <INDENT> if MIME_KEY == attachment.get_content_type(): <NEW_LINE> <INDENT> d = self._keymanager.put_raw_key( attachment.get_payload(decode=True), address=address) <NEW_LINE> d.addCallbacks(log_key_added, failed_put_key) <NEW_LINE> deferreds.append(d) <NEW_LINE> <DEDENT> <DEDENT> d = defer.gatherResults(deferreds) <NEW_LINE> d.addCallback(lambda result: any(result)) <NEW_LINE> return d
Import keys from the attachments :param attachments: email attachment list :type attachments: list(email.Message) :param address: email address in the from header :type address: str :return: A Deferred that will be fired when all the keys are stored with a boolean: True if there was a valid key attached, or False otherwise. :rtype: Deferred
625941c1d7e4931a7ee9dea7
def create_db_file(filename="CDPO.sqlite"): <NEW_LINE> <INDENT> conn = sqlite3.connect(filename) <NEW_LINE> c = conn.cursor() <NEW_LINE> c.execute("CREATE TABLE metadata (collection_name VARCHAR(40),brand_stats VARCHAR(100),track_stats VARCHAR(40)," "exp_date_stats VARCHAR(40),pan_stats VARCHAR(100),collection_type VARCHAR(40),components VARCHAR(100)," "primary key(collection_name))") <NEW_LINE> passwords_match = False <NEW_LINE> while not passwords_match: <NEW_LINE> <INDENT> new_password = getpass.getpass("\n\tEncryption password (masked): ") <NEW_LINE> confirm_password = getpass.getpass("\tConfirm password (masked): ") <NEW_LINE> if len(new_password) == 0: <NEW_LINE> <INDENT> print("\n\n !!!!Password cannot be blank. Please use a long and complex password." " Neither CDPO nor its creators are responsible if your database password is cracked.\n") <NEW_LINE> <DEDENT> elif new_password == confirm_password: <NEW_LINE> <INDENT> passwords_match = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("\n\n !!!!Passwords did not match. Please try again.\n") <NEW_LINE> <DEDENT> <DEDENT> skrtkey = new_password <NEW_LINE> md5_password_digest = hashlib.md5() <NEW_LINE> md5_password_digest.update(skrtkey) <NEW_LINE> password_md5_hex = md5_password_digest.hexdigest() <NEW_LINE> c.execute("CREATE TABLE password_hash_table (password_hash VARCHAR(40),primary key(password_hash))") <NEW_LINE> c.execute("INSERT INTO password_hash_table (password_hash) VALUES (?)", (str(password_md5_hex),)) <NEW_LINE> conn.commit() <NEW_LINE> conn.close() <NEW_LINE> return skrtkey
Creates database file
625941c124f1403a92600af2
def read_input(self, inputs): <NEW_LINE> <INDENT> delta = inputs.findFirst('delta') <NEW_LINE> if delta: <NEW_LINE> <INDENT> self._allowable = delta.value <NEW_LINE> <DEDENT> tol = inputs.findFirst('tolerance') <NEW_LINE> if tol: <NEW_LINE> <INDENT> self._tolerance = tol.value
Loads settings based on provided inputs @ In, inputs, InputData.InputSpecs, input specifications @ Out, None
625941c1cb5e8a47e48b7a37
def train(q, graph, train_data, test_data, trainer_args, metric, loss, verbose, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> model = graph.produce_model() <NEW_LINE> loss, metric_value = ModelTrainer(model=model, path=path, train_data=train_data, test_data=test_data, metric=metric, loss_function=loss, verbose=verbose).train_model(**trainer_args) <NEW_LINE> model.set_weight_to_graph() <NEW_LINE> if q: <NEW_LINE> <INDENT> q.put((metric_value, loss, model.graph)) <NEW_LINE> <DEDENT> return metric_value, loss, model.graph <NEW_LINE> <DEDENT> except RuntimeError as e: <NEW_LINE> <INDENT> if not re.search('out of memory', str(e)): <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> if verbose: <NEW_LINE> <INDENT> print('\nCurrent model size is too big. Discontinuing training this model to search for other models.') <NEW_LINE> <DEDENT> Constant.MAX_MODEL_SIZE = graph.size() - 1 <NEW_LINE> if q: <NEW_LINE> <INDENT> q.put((None, None, None)) <NEW_LINE> <DEDENT> return None, None, None <NEW_LINE> <DEDENT> except TimeoutError as exp: <NEW_LINE> <INDENT> logging.warning("TimeoutError occurred at train() : {0}".format(str(exp))) <NEW_LINE> if q: <NEW_LINE> <INDENT> q.put((None, None, None)) <NEW_LINE> <DEDENT> return None, None, None <NEW_LINE> <DEDENT> except Exception as exp: <NEW_LINE> <INDENT> logging.warning("Exception occurred at train() : {0}".format(str(exp))) <NEW_LINE> if verbose: <NEW_LINE> <INDENT> print("Exception occurred at train() : {0}".format(str(exp))) <NEW_LINE> <DEDENT> if q: <NEW_LINE> <INDENT> q.put((None, None, None)) <NEW_LINE> <DEDENT> return None, None, None
Train the neural architecture.
625941c18a43f66fc4b53ff1
def width(dct): <NEW_LINE> <INDENT> values = [ value for value in dct.itervalues() if isinstance(value, dict) ] <NEW_LINE> return sum(width(value) for value in values) + len(dct) - len(values)
Width of a dictionary. :param dct: dictionary :type dct: dict :rtype: int
625941c1dc8b845886cb54be
def isHomogeneous(self): <NEW_LINE> <INDENT> m,n = self.size() <NEW_LINE> if m != 4 or n != 4: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> test = self[0:3,0:3]; <NEW_LINE> test = test*test.tr() <NEW_LINE> test[0,0] = test[0,0] - 1.0 <NEW_LINE> test[1,1] = test[1,1] - 1.0 <NEW_LINE> test[2,2] = test[2,2] - 1.0 <NEW_LINE> zero = 0.0 <NEW_LINE> for x in range(3): <NEW_LINE> <INDENT> for y in range(3): <NEW_LINE> <INDENT> zero = zero + abs(test[x,y]) <NEW_LINE> <DEDENT> <DEDENT> if zero > 1e-4: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
returns 1 if it is a Homogeneous matrix
625941c199cbb53fe6792b71
def _try_dump(cnf, outpath, otype, fmsg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> API.dump(cnf, outpath, otype) <NEW_LINE> <DEDENT> except API.UnknownFileTypeError: <NEW_LINE> <INDENT> _exit_with_output(fmsg % outpath, 1) <NEW_LINE> <DEDENT> except API.UnknownParserTypeError: <NEW_LINE> <INDENT> _exit_with_output("Invalid output type '%s'" % otype, 1)
:param cnf: Configuration object to print out :param outpath: Output file path or None :param otype: Output type or None :param fmsg: message if it cannot detect otype by `inpath`
625941c1442bda511e8be3a5
def test_sequential_writer(tmp_path): <NEW_LINE> <INDENT> bag_path = str(tmp_path / 'tmp_write_test') <NEW_LINE> storage_options, converter_options = get_rosbag_options(bag_path) <NEW_LINE> writer = rosbag2_py.SequentialWriter() <NEW_LINE> writer.open(storage_options, converter_options) <NEW_LINE> topic_name = '/chatter' <NEW_LINE> create_topic(writer, topic_name, 'std_msgs/msg/String') <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> msg = String() <NEW_LINE> msg.data = f'Hello, world! {str(i)}' <NEW_LINE> time_stamp = i * 100 <NEW_LINE> writer.write(topic_name, serialize_message(msg), time_stamp) <NEW_LINE> <DEDENT> del writer <NEW_LINE> storage_options, converter_options = get_rosbag_options(bag_path) <NEW_LINE> reader = rosbag2_py.SequentialReader() <NEW_LINE> reader.open(storage_options, converter_options) <NEW_LINE> topic_types = reader.get_all_topics_and_types() <NEW_LINE> type_map = {topic_types[i].name: topic_types[i].type for i in range(len(topic_types))} <NEW_LINE> msg_counter = 0 <NEW_LINE> while reader.has_next(): <NEW_LINE> <INDENT> topic, data, t = reader.read_next() <NEW_LINE> msg_type = get_message(type_map[topic]) <NEW_LINE> msg_deserialized = deserialize_message(data, msg_type) <NEW_LINE> assert isinstance(msg_deserialized, String) <NEW_LINE> assert msg_deserialized.data == f'Hello, world! {msg_counter}' <NEW_LINE> assert t == msg_counter * 100 <NEW_LINE> msg_counter += 1
Test for sequential writer. :return:
625941c19b70327d1c4e0d5e
def Reroll(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
625941c19f2886367277a819
def backward_D(self): <NEW_LINE> <INDENT> if self.args.cgan==False: <NEW_LINE> <INDENT> pred_fake=self.netD(self.fake_B.detach()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fake_AB=torch.cat((self.real_A, self.fake_B), 1) <NEW_LINE> pred_fake=self.netD(fake_AB.detach()) <NEW_LINE> <DEDENT> self.loss_D_fake = self.criterionGAN(pred_fake, False) <NEW_LINE> if self.args.cgan==False: <NEW_LINE> <INDENT> pred_real = self.netD(self.real_B) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> real_AB=torch.cat((self.real_A, self.real_B), 1) <NEW_LINE> pred_real = self.netD(real_AB) <NEW_LINE> <DEDENT> self.loss_D_real = self.criterionGAN(pred_real, True) <NEW_LINE> self.loss_D = self.loss_D_fake*self.args.loss_weight['D_fake'] + self.loss_D_real * self.args.loss_weight['D_real'] <NEW_LINE> self.loss_D.backward()
Calculate GAN loss for the discriminator
625941c1b830903b967e9897
def palette(self, alpha='natural'): <NEW_LINE> <INDENT> if not self.plte: <NEW_LINE> <INDENT> raise FormatError( "Required PLTE chunk is missing in colour type 3 image.") <NEW_LINE> <DEDENT> plte = group(array('B', self.plte), 3) <NEW_LINE> if self.trns or alpha == 'force': <NEW_LINE> <INDENT> trns = array('B', self.trns or []) <NEW_LINE> trns.extend([255]*(len(plte)-len(trns))) <NEW_LINE> plte = list(map(operator.add, plte, group(trns, 1))) <NEW_LINE> <DEDENT> return plte
Returns a palette that is a sequence of 3-tuples or 4-tuples, synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These chunks should have already been processed (for example, by calling the :meth:`preamble` method). All the tuples are the same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when there is a ``tRNS`` chunk. Assumes that the image is colour type 3 and therefore a ``PLTE`` chunk is required. If the `alpha` argument is ``'force'`` then an alpha channel is always added, forcing the result to be a sequence of 4-tuples.
625941c10a366e3fb873e7a3
def test_get(self): <NEW_LINE> <INDENT> response = self.client.get( reverse("wagtailimages:generate_url", args=(self.image.id, "fill-800x600")) ) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response["Content-Type"], "application/json") <NEW_LINE> content_json = json.loads(response.content.decode()) <NEW_LINE> self.assertEqual(set(content_json.keys()), {"url", "preview_url"}) <NEW_LINE> expected_url = ( "http://localhost/images/%(signature)s/%(image_id)d/fill-800x600/" % { "signature": urllib.parse.quote( generate_signature(self.image.id, "fill-800x600"), safe=urlquote_safechars, ), "image_id": self.image.id, } ) <NEW_LINE> self.assertEqual(content_json["url"], expected_url) <NEW_LINE> expected_preview_url = reverse( "wagtailimages:preview", args=(self.image.id, "fill-800x600") ) <NEW_LINE> self.assertEqual(content_json["preview_url"], expected_preview_url)
This tests that the view responds correctly for a user with edit permissions on this image
625941c107d97122c4178812
def validate_self(self): <NEW_LINE> <INDENT> self._validate_input_symbol_subset() <NEW_LINE> self._validate_transitions() <NEW_LINE> self._validate_initial_state() <NEW_LINE> self._validate_initial_state_transitions() <NEW_LINE> self._validate_nonfinal_initial_state() <NEW_LINE> self._validate_final_states() <NEW_LINE> self._validate_final_state_transitions() <NEW_LINE> return True
Return True if this DTM is internally consistent.
625941c1851cf427c661a49c
def subfields_to_dict(self, subfields): <NEW_LINE> <INDENT> subfields_list = [] <NEW_LINE> for idx in range(0, len(subfields), 2): <NEW_LINE> <INDENT> if idx + 1 < len(subfields): <NEW_LINE> <INDENT> subfields_list.append({"code": subfields[idx], "value": subfields[idx+1]}) <NEW_LINE> <DEDENT> <DEDENT> return subfields_list
muuntaa pymarc-kirjaston käyttämän osakenttälistan, jossa joka toinen alkio on osakenttäkoodi ja joka toinen osakenttä, konversio-ohjelmalle helpommin käsiteltävään muotoon listaksi, jossa on avainarvopareja {osakenttäkoodi, osakenttä}
625941c1a17c0f6771cbdfdd
def reindex(self): <NEW_LINE> <INDENT> call_command('rebuild_index', interactive=False)
Re-index the search database for the unit tests.
625941c11b99ca400220aa3b
def mouse_click(self, event): <NEW_LINE> <INDENT> if event.button == 1: <NEW_LINE> <INDENT> self.left_click(event) <NEW_LINE> <DEDENT> elif event.button == 3: <NEW_LINE> <INDENT> self.right_click(event)
deal with mouse input :param event: :return:
625941c1187af65679ca50a9
def copyRandomList(self, head): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self.hashmap.has_key(head.label): <NEW_LINE> <INDENT> return self.hashmap[head.label] <NEW_LINE> <DEDENT> copyhead = RandomListNode(head.label) <NEW_LINE> self.hashmap[head.label] = copyhead <NEW_LINE> copyhead.next = self.copyRandomList(head.next) <NEW_LINE> copyhead.random = self.copyRandomList(head.random) <NEW_LINE> return copyhead
:type head: RandomListNode :rtype: RandomListNode
625941c13eb6a72ae02ec462
def check_uniqueness(keys=UNIQUES, data=None, *, ignore_self=False): <NEW_LINE> <INDENT> user_files = fetch_user_files() <NEW_LINE> if ignore_self: <NEW_LINE> <INDENT> user_files.remove('{}.txt'.format(data['id'])) <NEW_LINE> <DEDENT> for user_file in user_files: <NEW_LINE> <INDENT> with open(user_file, 'r') as f: <NEW_LINE> <INDENT> file_data = json.load(f) <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> if data[key] == file_data[key]: <NEW_LINE> <INDENT> return {'status': 409, 'error': "{} already in use!".format(key)} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return {'status': 200}
Check if the given data is unique in the DB for the provided keys.
625941c18a43f66fc4b53ff2
def fake_decimal(self, digits, right_digits, flag=None, min_value=None, max_value=None): <NEW_LINE> <INDENT> if flag is None: <NEW_LINE> <INDENT> flag = random.randint(0, 1) <NEW_LINE> <DEDENT> number = self.faker.pyfloat(left_digits=(digits - right_digits), right_digits=right_digits, positive=True, min_value=min_value, max_value=max_value) <NEW_LINE> return number if flag == 1 else -number
mysql中DECIMAL(6,2); 最多可以存储6位数字,小数位数为2位; 因此范围是从-9999.99到9999.99 而pyfloat left_digits, right_digits 表示小数点左右数字位数 :param args: :return:
625941c121a7993f00bc7c77
def __delattr__(self, k): <NEW_LINE> <INDENT> del self[k]
Remove attribute.
625941c1379a373c97cfaace
@experimental(as_of="0.4.0") <NEW_LINE> def esty_ci(counts): <NEW_LINE> <INDENT> counts = _validate_counts_vector(counts) <NEW_LINE> f1 = singles(counts) <NEW_LINE> f2 = doubles(counts) <NEW_LINE> n = counts.sum() <NEW_LINE> z = 1.959963985 <NEW_LINE> W = (f1 * (n - f1) + 2 * n * f2) / (n ** 3) <NEW_LINE> return f1 / n - z * np.sqrt(W), f1 / n + z * np.sqrt(W)
Calculate Esty's CI. Esty's CI is defined as .. math:: F_1/N \pm z\sqrt{W} where :math:`F_1` is the number of singleton OTUs, :math:`N` is the total number of individuals (sum of abundances for all OTUs), and :math:`z` is a constant that depends on the targeted confidence and based on the normal distribution. :math:`W` is defined as .. math:: \frac{F_1(N-F_1)+2NF_2}{N^3} where :math:`F_2` is the number of doubleton OTUs. Parameters ---------- counts : 1-D array_like, int Vector of counts. Returns ------- tuple Esty's confidence interval as ``(lower_bound, upper_bound)``. Notes ----- Esty's CI is defined in [1]_. :math:`z` is hardcoded for a 95% confidence interval. References ---------- .. [1] Esty, W. W. (1983). "A normal limit law for a nonparametric estimator of the coverage of a random sample". Ann Statist 11: 905-912.
625941c1091ae35668666eed
def test_util(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = parse_qs_dict("http://example.org/?foo=1&bar=2") <NEW_LINE> assert res['foo'] == '1' <NEW_LINE> assert res['bar'] == '2' <NEW_LINE> parse_qs_dict("http://example.org/?foo=1&foo=2") <NEW_LINE> assert False <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> assert True
Test the utility function for dictionaries.
625941c15e10d32532c5eeb2
def do_datamodel(self, arg): <NEW_LINE> <INDENT> self.__checkConnection() <NEW_LINE> parser = self.parser_datamodel() <NEW_LINE> options, args = parser.parse_args(arg) <NEW_LINE> pysqlgraphics.datamodel(self.db, options.user.upper(), tableFilter=" ".join(args), withColumns=options.columns)
Exports a datamodel as a picture
625941c176e4537e8c3515fb
def format_player_scores(self, player_scores): <NEW_LINE> <INDENT> player_score_list = player_scores.split(',') <NEW_LINE> for i in range(len(player_score_list)): <NEW_LINE> <INDENT> player_score_list[i] = player_score_list[i].split(':') <NEW_LINE> player_score_list[i][0] = int(player_score_list[i][0]) <NEW_LINE> player_score_list[i][1] = int(player_score_list[i][1]) <NEW_LINE> <DEDENT> return player_score_list
take player scores from state string and reformat to be used
625941c163d6d428bbe4447a
def get_logger(): <NEW_LINE> <INDENT> logger = logging.getLogger('parky_bot') <NEW_LINE> return logger
This function returns a single logging object. Returns: Logger: logger object.
625941c17b25080760e393e5
def __init__(self, storage: Storage, read_handle: ReadHandle, config: dict): <NEW_LINE> <INDENT> async def run(): <NEW_LINE> <INDENT> self.server = await aio.start_server(self.startReceive, server_addr, server_port) <NEW_LINE> addr = self.server.sockets[0].getsockname() <NEW_LINE> logging.info(f'TCP insertion handle serving on {addr}') <NEW_LINE> async with self.server: <NEW_LINE> <INDENT> await self.server.serve_forever() <NEW_LINE> <DEDENT> <DEDENT> self.storage = storage <NEW_LINE> self.read_handle = read_handle <NEW_LINE> server_addr = config['tcp_bulk_insert']['addr'] <NEW_LINE> server_port = config['tcp_bulk_insert']['port'] <NEW_LINE> event_loop = aio.get_event_loop() <NEW_LINE> if sys.version_info.minor >= 7: <NEW_LINE> <INDENT> event_loop.create_task(run()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> coro = aio.start_server(self.startReceive, server_addr, server_port, loop=event_loop) <NEW_LINE> server = event_loop.run_until_complete(coro) <NEW_LINE> logging.info('TCP insertion handle serving on {}'.format(server.sockets[0].getsockname()))
TCP bulk insertion handle need to keep a reference to ReadHandle to register new prefixes.
625941c155399d3f0558863e
def removeProperty(self, object, name): <NEW_LINE> <INDENT> raise NotImplementedError
Remove the property 'name' from an object.
625941c1442bda511e8be3a6
def __init__(self, spatial_size=50 * 8 + 8, dimension=3, num_input_features=1, block_reps=1, m=32, num_planes_coeffs=[1, 2, 3, 4, 5], num_planes=None, residual_blocks=False, downsample=[2, 2], bias=False, mode=3, num_classes=50, ): <NEW_LINE> <INDENT> self.spatial_size = spatial_size <NEW_LINE> self.dimension = dimension <NEW_LINE> self.block_reps = block_reps <NEW_LINE> self.m = m <NEW_LINE> self.num_planes_coeffs = num_planes_coeffs <NEW_LINE> self.num_planes = num_planes <NEW_LINE> self.residual_blocks = residual_blocks <NEW_LINE> self.num_classes = num_classes <NEW_LINE> self.num_input_features = num_input_features <NEW_LINE> self.downsample = downsample <NEW_LINE> self.bias = bias <NEW_LINE> self.mode = mode <NEW_LINE> if self.num_planes is None: <NEW_LINE> <INDENT> self.num_planes = [self.m * i for i in num_planes_coeffs]
Parameters ---------- dimension: int reps: int Conv block repetition factor m: int Unet number of features num_planes_coeffs: array of int num_planes=None: array of int UNet number of features per level residual_blocks: bool mode: int mode == 0 if the input is guaranteed to have no duplicates mode == 1 to use the last item at each spatial location mode == 2 to keep the first item at each spatial location mode == 3 to sum feature vectors sharing one spatial location mode == 4 to average feature vectors at each spatial location num_input_features: int downsample: list [filter_size, filter_stride] bias: bool num_classes_total: int
625941c1a219f33f346288f7
def _write_nlu_to_file( export_nlu_path: Text, evts: List[Dict[Text, Any]] ) -> None: <NEW_LINE> <INDENT> msgs = _collect_messages(evts) <NEW_LINE> try: <NEW_LINE> <INDENT> previous_examples = load_data(export_nlu_path) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.exception("An exception occurred while trying to load the " "NLU data.") <NEW_LINE> export_nlu_path = questionary.text( message="Could not load existing NLU data, please " "specify where to store NLU data learned in " "this session (this will overwrite any " "existing file). {}".format(str(e)), default=PATHS["backup"]).ask() <NEW_LINE> if export_nlu_path is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> previous_examples = TrainingData() <NEW_LINE> <DEDENT> nlu_data = previous_examples.merge(TrainingData(msgs)) <NEW_LINE> with io.open(export_nlu_path, 'w', encoding="utf-8") as f: <NEW_LINE> <INDENT> if _guess_format(export_nlu_path) in {"md", "unk"}: <NEW_LINE> <INDENT> f.write(nlu_data.as_markdown()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f.write(nlu_data.as_json())
Write the nlu data of the sender_id to the file paths.
625941c116aa5153ce362403
def __GetExtensionSettings(self, project_path): <NEW_LINE> <INDENT> for folderName, subfoldersName, fileNames in os.walk(project_path): <NEW_LINE> <INDENT> for fileName in fileNames: <NEW_LINE> <INDENT> ind = 0 <NEW_LINE> for item in self.__ExtensionList: <NEW_LINE> <INDENT> if self.__MarkerName.find("*") == 0: <NEW_LINE> <INDENT> if (fileName.lower()).endswith(self.__MarkerName + item): <NEW_LINE> <INDENT> self.__CurrentExtension = item <NEW_LINE> self.__NewExtension = self.__ExtensionList[(ind + 1) % len(self.__ExtensionList)] <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if fileName.lower() == (self.__MarkerName + item): <NEW_LINE> <INDENT> self.__CurrentExtension = item <NEW_LINE> self.__NewExtension = self.__ExtensionList[(ind + 1) % len(self.__ExtensionList)] <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> ind = ind + 1
Метод автоматического определения настроек конвертации
625941c1377c676e91272134
def _Create(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Create an Apache Spark cluster.
625941c166673b3332b9201c
def __init__(self, learning_rate=0.001, discount=0.99, batch_size=64, state_size=4, action_size=2, use_huber_loss=False, state_process_fn=None, action_process_fn=None, action_post_process_fn=None, model_dir=None): <NEW_LINE> <INDENT> self.learning_rate = learning_rate <NEW_LINE> self.gamma = discount <NEW_LINE> self.online_model = mlp_policy(state_size, action_size) <NEW_LINE> self.target_model = mlp_policy(state_size, action_size) <NEW_LINE> self.online_model.build() <NEW_LINE> self.target_model.build() <NEW_LINE> self.optimizer = tf.keras.optimizers.Adam(lr=self.learning_rate,) <NEW_LINE> self.loss = tf.keras.losses.Huber() <NEW_LINE> self.global_step = tf.Variable(1, name='global_step') <NEW_LINE> self.learn_step = tf.Variable(1, name='learn_step') <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.state_size = state_size <NEW_LINE> self.action_size = action_size <NEW_LINE> self._use_huber_loss = use_huber_loss <NEW_LINE> self._state_process_fn = state_process_fn <NEW_LINE> self._action_process_fn = action_process_fn <NEW_LINE> self._action_post_process_fn = action_post_process_fn <NEW_LINE> if model_dir: <NEW_LINE> <INDENT> self.saver = tf.train.Checkpoint( optimizer=self.optimizer, online_model=self.online_model, target_model=self.target_model, step=self.global_step) <NEW_LINE> self.manager = tf.train.CheckpointManager( self.saver, model_dir, max_to_keep=5, checkpoint_name='model')
Initialize the double dqn agent. Args: learning_rate: learning rate of the optimizer discount: future discount of the agent batch_size: size of the batch state_size: size of the observation action_size: size of the action use_huber_loss: whether to use huber loss or l2 loss state_process_fn: function that process state before compute action_process_fn: function that process action before compute action_post_process_fn: function that process state after compute model_dir: optional directory for saving weights
625941c182261d6c526ab427
def generic_compare(self, builder, key, argtypes, args): <NEW_LINE> <INDENT> at, bt = argtypes <NEW_LINE> av, bv = args <NEW_LINE> ty = self.typing_context.unify_types(at, bt) <NEW_LINE> assert ty is not None <NEW_LINE> cav = self.cast(builder, av, at, ty) <NEW_LINE> cbv = self.cast(builder, bv, bt, ty) <NEW_LINE> fnty = self.typing_context.resolve_value_type(key) <NEW_LINE> cmpsig = fnty.get_call_type(self.typing_context, (ty, ty), {}) <NEW_LINE> cmpfunc = self.get_function(fnty, cmpsig) <NEW_LINE> self.add_linking_libs(getattr(cmpfunc, 'libs', ())) <NEW_LINE> return cmpfunc(builder, (cav, cbv))
Compare the given LLVM values of the given Numba types using the comparison *key* (e.g. '=='). The values are first cast to a common safe conversion type.
625941c17d43ff24873a2c2a
def _validate_callbacks(self, a, b, anum, bnum): <NEW_LINE> <INDENT> f_a, f_b = self._get_method(a), self._get_method(b) <NEW_LINE> has_a, has_b = f_a != None, f_b != None <NEW_LINE> if has_a and has_b: <NEW_LINE> <INDENT> raise AssertionError("Cannot define both " + a + " and " + b + ".") <NEW_LINE> <DEDENT> elif has_a: <NEW_LINE> <INDENT> fargs, _, _, _ = inspect.getargspec(f_a) <NEW_LINE> if len(fargs) != anum: <NEW_LINE> <INDENT> raise AssertionError(a + " must take exactly " + str(anum) + " args.") <NEW_LINE> <DEDENT> <DEDENT> elif has_b: <NEW_LINE> <INDENT> fargs, _, _, _ = inspect.getargspec(f_b) <NEW_LINE> if len(fargs) != bnum: <NEW_LINE> <INDENT> raise AssertionError(b + " must take exactly " + str(bnum) + " args.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise AssertionError("Must define one of " + a + " or " + b + ".")
Makes sure that only one of methods a and b are defined. Makes sure that the method defined has the correct number of arguments (anum, bnum).
625941c1d18da76e2353245f
def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch()
Fetch the MemberInstance :returns: The fetched MemberInstance :rtype: twilio.rest.ip_messaging.v1.service.channel.member.MemberInstance
625941c1d6c5a10208143fd4
def build(self) -> 'TableSchema': <NEW_LINE> <INDENT> return TableSchema(self._field_names, self._field_data_types)
Returns a :class:`TableSchema` instance. :return: The :class:`TableSchema` instance.
625941c163f4b57ef00010a9
def to_dict(self): <NEW_LINE> <INDENT> d = {'filename': self.filename, 'sections': self.sections} <NEW_LINE> for section in self.sections: <NEW_LINE> <INDENT> d[section] = copy.deepcopy(getattr(self, section)) <NEW_LINE> <DEDENT> return d
Serializes the instance as dict.
625941c18da39b475bd64efc
def test_get_comment(self): <NEW_LINE> <INDENT> pass
Test case for get_comment Gets a Comment of a Defect
625941c1925a0f43d2549e00
def time_to_td(ti): <NEW_LINE> <INDENT> return datetime.timedelta(hours=ti.hour, minutes=ti.minute, seconds=ti.second)
Convert from datetime.time object to timedelta object
625941c18e71fb1e9831d735
def CreateUpload(self, archive=None, manifest=None, **kwargs): <NEW_LINE> <INDENT> if archive is not None: <NEW_LINE> <INDENT> url = archive.upload <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = self._top_resource_url('uploads') <NEW_LINE> <DEDENT> kwargs['data'] = model_to_json(manifest) <NEW_LINE> body, headers = json_response(self.post)(url, **kwargs) <NEW_LINE> return models.Upload(meta=headers, **body)
Create a new upload for an archive :param archive: the archive model instance :param manifest: the upload manifest
625941c1099cdd3c635f0be7
def load_data(): <NEW_LINE> <INDENT> wiki_data = read_from_wiki(topics) <NEW_LINE> write_to_json(wiki_data)
Loads data from Wikipedia
625941c1eab8aa0e5d26dae3
def get(self, uuid): <NEW_LINE> <INDENT> if uuid in model.AccessPoints: <NEW_LINE> <INDENT> return model.AccessPoints[uuid].marshal() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ResourceNotFoundError
Return details of access point taken from configuration file.
625941c1004d5f362079a2c0
def calculate_metrics(self, metric_df, dose): <NEW_LINE> <INDENT> roi_exists = self.roi_mask.max(axis=(0, 1, 2)) <NEW_LINE> voxels_in_tenth_of_cc = np.maximum(1, np.round(100/self.voxel_size)) <NEW_LINE> for roi_idx, roi in enumerate(self.data_loader.dataset.defdataset.full_roi_list): <NEW_LINE> <INDENT> if roi_exists[roi_idx]: <NEW_LINE> <INDENT> roi_mask = self.roi_mask[:, :, :, roi_idx].flatten() <NEW_LINE> roi_dose = dose[roi_mask] <NEW_LINE> roi_size = len(roi_dose) <NEW_LINE> if roi in self.data_loader.dataset.defdataset.rois['oars']: <NEW_LINE> <INDENT> if 'D_0.1_cc' in self.oar_eval_metrics: <NEW_LINE> <INDENT> fractional_volume_to_evaluate = 100 - voxels_in_tenth_of_cc/roi_size * 100 <NEW_LINE> metric_eval = np.percentile(roi_dose, fractional_volume_to_evaluate) <NEW_LINE> metric_df.at[self.patient_list[0], ('D_0.1_cc', roi)] = metric_eval <NEW_LINE> <DEDENT> if 'mean' in self.oar_eval_metrics: <NEW_LINE> <INDENT> metric_eval = roi_dose.mean() <NEW_LINE> metric_df.at[self.patient_list[0], ('mean', roi)] = metric_eval <NEW_LINE> <DEDENT> <DEDENT> elif roi in self.data_loader.dataset.defdataset.rois['targets']: <NEW_LINE> <INDENT> if 'D_99' in self.tar_eval_metrics: <NEW_LINE> <INDENT> metric_eval = np.percentile(roi_dose, 1) <NEW_LINE> metric_df.at[self.patient_list[0], ('D_99', roi)] = metric_eval <NEW_LINE> <DEDENT> if 'D_95' in self.tar_eval_metrics: <NEW_LINE> <INDENT> metric_eval = np.percentile(roi_dose, 5) <NEW_LINE> metric_df.at[self.patient_list[0], ('D_95', roi)] = metric_eval <NEW_LINE> <DEDENT> if 'D_1' in self.tar_eval_metrics: <NEW_LINE> <INDENT> metric_eval = np.percentile(roi_dose, 99) <NEW_LINE> metric_df.at[self.patient_list[0], ('D_1', roi)] = metric_eval <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return metric_df
Calculate the competition metrics :param metric_df: A DataFrame with columns indexed by the metric name and the structure name :param dose: the dose to be evaluated :return: the same metric_df that is input, but now with the metrics for the provided dose
625941c1d10714528d5ffc6c
def bool_to_string(bool): <NEW_LINE> <INDENT> string = str(bool) <NEW_LINE> string = string.lower() <NEW_LINE> return string
Convert a boolean to a string :param bool: provide boolean to be converted
625941c1d7e4931a7ee9dea8
def friend_by_public_key(self, public_key): <NEW_LINE> <INDENT> tox_err_friend_by_public_key = c_int() <NEW_LINE> result = Tox.libtoxcore.tox_friend_by_public_key(self._tox_pointer, string_to_bin(public_key), byref(tox_err_friend_by_public_key)) <NEW_LINE> tox_err_friend_by_public_key = tox_err_friend_by_public_key.value <NEW_LINE> if tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['OK']: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> elif tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['NULL']: <NEW_LINE> <INDENT> raise ArgumentError('One of the arguments to the function was NULL when it was not expected.') <NEW_LINE> <DEDENT> elif tox_err_friend_by_public_key == TOX_ERR_FRIEND_BY_PUBLIC_KEY['NOT_FOUND']: <NEW_LINE> <INDENT> raise ArgumentError('No friend with the given Public Key exists on the friend list.')
Return the friend number associated with that Public Key. :param public_key: A byte array containing the Public Key. :return: friend number
625941c1a8ecb033257d3059
def tostr(self): <NEW_LINE> <INDENT> if len(self.items) != 2: <NEW_LINE> <INDENT> raise InternalError( "Cray_Pointer_Decl.tostr(). 'Items' should be of size 2 but " "found '{0}'.".format(len(self.items))) <NEW_LINE> <DEDENT> if not self.items[0]: <NEW_LINE> <INDENT> raise InternalError("Cray_Pointer_Decl_Stmt.tostr(). 'Items' " "entry 0 should be a pointer name but it is " "empty") <NEW_LINE> <DEDENT> if not self.items[1]: <NEW_LINE> <INDENT> raise InternalError("Cray_Pointer_Decl_Stmt.tostr(). 'Items' " "entry 1 should be a pointee name or pointee " "declaration but it is empty") <NEW_LINE> <DEDENT> return "({0}, {1})".format(self.items[0], self.items[1])
:return: this Cray-pointee declaration as a string :rtype: str :raises InternalError: if the internal items list variable is not the expected size. :raises InternalError: if the first element of the internal items list is None or is empty. :raises InternalError: if the second element of the internal items list is None or is empty.
625941c126068e7796caec67
def print_page_cb(self, print_op, print_context, page_nb, keep_refs={}): <NEW_LINE> <INDENT> raise NotImplementedError()
Arguments: keep_refs --- Workaround ugly as fuck to keep some object alive (--> non-garbage-collected) during the whole printing process
625941c199fddb7c1c9de31d
def get_performance_logs(self): <NEW_LINE> <INDENT> files = os.listdir(self.performance_logs_dir) <NEW_LINE> for i, f in enumerate(files): <NEW_LINE> <INDENT> files[i] = 'file://{0}/{1}'.format(self.performance_logs_dir, f) <NEW_LINE> <DEDENT> return files
Returns a list of full paths to performance log files
625941c115baa723493c3eff
def dumps(self, objects): <NEW_LINE> <INDENT> if len(objects) == 0: <NEW_LINE> <INDENT> objects = list(self._models.values()) <NEW_LINE> <DEDENT> if len(objects) == 1 and isinstance(objects[0], Plot): <NEW_LINE> <INDENT> the_plot = objects[0] <NEW_LINE> objects = list(self._models.values()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> the_plot = [m for m in objects if isinstance(m, Plot)][0] <NEW_LINE> <DEDENT> plot_ref = self.get_ref(the_plot) <NEW_LINE> elementid = str(uuid.uuid4()) <NEW_LINE> models = [] <NEW_LINE> for m in objects: <NEW_LINE> <INDENT> ref = self.get_ref(m) <NEW_LINE> ref["attributes"] = m.vm_serialize() <NEW_LINE> ref["attributes"].update({"id": ref["id"], "doc": None}) <NEW_LINE> models.append(ref) <NEW_LINE> <DEDENT> js = self._load_template(self.js_template).render( elementid = elementid, modelid = plot_ref["id"], modeltype = plot_ref["type"], all_models = self.serialize(models), ) <NEW_LINE> plot_div = self._load_template(self.div_template).render( elementid=elementid ) <NEW_LINE> html = self._load_template(self.html_template).render( html_snippets=[plot_div], elementid = elementid, js_snippets = [js], ) <NEW_LINE> return html.encode("utf-8") <NEW_LINE> plot_ref = self.get_ref(the_plot) <NEW_LINE> elementid = str(uuid.uuid4()) <NEW_LINE> models = [] <NEW_LINE> for m in objects: <NEW_LINE> <INDENT> ref = self.get_ref(m) <NEW_LINE> ref["attributes"] = m.vm_serialize() <NEW_LINE> ref["attributes"].update({"id": ref["id"], "doc": None}) <NEW_LINE> models.append(ref) <NEW_LINE> <DEDENT> js = self._load_template(self.js_template).render( elementid = elementid, modelid = plot_ref["id"], modeltype = plot_ref["type"], all_models = self.serialize(models), ) <NEW_LINE> plot_div = self._load_template(self.div_template).render( elementid=elementid ) <NEW_LINE> html = self._load_template(self.html_template).render( html_snippets=[plot_div], elementid = elementid, js_snippets = [js], ) <NEW_LINE> return html.encode("utf-8")
Returns the HTML contents as a string FIXME : signature different than other dumps FIXME: should consolidate code between this one and that one.
625941c1ff9c53063f47c180
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, LbClientCertificateSubjectDnCondition): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c110dbd63aa1bd2b30
def train(self, env_name): <NEW_LINE> <INDENT> timestr = time.strftime("%Y%m%d-%H%M%S") + "_" + str(env_name) <NEW_LINE> tensorboard = TensorBoard(log_dir='./Graph/{}'.format(timestr), histogram_freq=0, write_graph=True, write_images=False) <NEW_LINE> self.dqn.fit(self.env, nb_max_start_steps=nb_max_start_steps, nb_steps=nb_steps, visualize=False, verbose=2, start_step_policy=self.start_step_policy, callbacks=[tensorboard]) <NEW_LINE> dqn_json = self.model.to_json() <NEW_LINE> with open("dqn_{}_json.json".format(env_name), "w") as json_file: <NEW_LINE> <INDENT> json.dump(dqn_json, json_file) <NEW_LINE> <DEDENT> self.dqn.save_weights('dqn_{}_weights.h5'.format(env_name), overwrite=True) <NEW_LINE> self.dqn.test(self.env, nb_episodes=5, visualize=False)
Train a model
625941c1b7558d58953c4ea4
def clean(self, value): <NEW_LINE> <INDENT> value = super(ModelNameFormField, self).clean(value) <NEW_LINE> if value == u'': <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if not ModelNameFormField.get_model_from_string(value): <NEW_LINE> <INDENT> raise forms.ValidationError(self.error_messages['invalid']) <NEW_LINE> <DEDENT> return value
Validates that the input matches the regular expression. Returns a Unicode object.
625941c157b8e32f52483425
def __init__(self, segments, linewidths = None, colors = None, antialiaseds = None, linestyles = 'solid', offsets = None, transOffset = None, norm = None, cmap = None, pickradius = 5, **kwargs ): <NEW_LINE> <INDENT> if colors is None: colors = mpl.rcParams['lines.color'] <NEW_LINE> if linewidths is None: linewidths = (mpl.rcParams['lines.linewidth'],) <NEW_LINE> if antialiaseds is None: antialiaseds = (mpl.rcParams['lines.antialiased'],) <NEW_LINE> self.set_linestyles(linestyles) <NEW_LINE> colors = mcolors.colorConverter.to_rgba_array(colors) <NEW_LINE> Collection.__init__( self, edgecolors=colors, facecolors='none', linewidths=linewidths, linestyles=linestyles, antialiaseds=antialiaseds, offsets=offsets, transOffset=transOffset, norm=norm, cmap=cmap, pickradius=pickradius, **kwargs) <NEW_LINE> self.set_segments(segments)
*segments* a sequence of (*line0*, *line1*, *line2*), where:: linen = (x0, y0), (x1, y1), ... (xm, ym) or the equivalent numpy array with two columns. Each line can be a different length. *colors* must be a sequence of RGBA tuples (eg arbitrary color strings, etc, not allowed). *antialiaseds* must be a sequence of ones or zeros *linestyles* [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ] a string or dash tuple. The dash tuple is:: (offset, onoffseq), where *onoffseq* is an even length tuple of on and off ink in points. If *linewidths*, *colors*, or *antialiaseds* is None, they default to their rcParams setting, in sequence form. If *offsets* and *transOffset* are not None, then *offsets* are transformed by *transOffset* and applied after the segments have been transformed to display coordinates. If *offsets* is not None but *transOffset* is None, then the *offsets* are added to the segments before any transformation. In this case, a single offset can be specified as:: offsets=(xo,yo) and this value will be added cumulatively to each successive segment, so as to produce a set of successively offset curves. *norm* None (optional for :class:`matplotlib.cm.ScalarMappable`) *cmap* None (optional for :class:`matplotlib.cm.ScalarMappable`) *pickradius* is the tolerance for mouse clicks picking a line. The default is 5 pt. The use of :class:`~matplotlib.cm.ScalarMappable` is optional. If the :class:`~matplotlib.cm.ScalarMappable` array :attr:`~matplotlib.cm.ScalarMappable._A` is not None (ie a call to :meth:`~matplotlib.cm.ScalarMappable.set_array` has been made), at draw time a call to scalar mappable will be made to set the colors.
625941c1009cb60464c6333f
def propose_beta(self, beta_prev, beta_jump_length): <NEW_LINE> <INDENT> sigma_prop = np.eye(self.beta_dim) * beta_jump_length <NEW_LINE> return multivariate_normal(mean=beta_prev, cov=sigma_prop).rvs()
Proposes a perturbed beta based on a jump length hyperparameter. Args: beta_prev: beta_jump_length: Returns:
625941c1460517430c394116
def affine_forward(x, w, b): <NEW_LINE> <INDENT> out = None <NEW_LINE> N = x.shape[0] <NEW_LINE> D = w.shape[0] <NEW_LINE> out = np.dot(np.reshape(x, [N, D]), w) + b <NEW_LINE> cache = (x, w, b) <NEW_LINE> return out, cache
Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has shape (d_1, ..., d_k). We will reshape each input into a vector of dimension D = d_1 * ... * d_k, and then transform it to an output vector of dimension M. Inputs: - x: A numpy array containing input data, of shape (N, d_1, ..., d_k) - w: A numpy array of weights, of shape (D, M) - b: A numpy array of biases, of shape (M,) Returns a tuple of: - out: output, of shape (N, M) - cache: (x, w, b)
625941c1293b9510aa2c3224
def _dataframe_to_db(self): <NEW_LINE> <INDENT> self._dataframe = pickle.dumps(self.dataframe, protocol=pickle.HIGHEST_PROTOCOL)
This is basically the same code from pandas 0.18 pandas.io.pickle.to_pickle but keeping the bytes in memory. Since that method does not allow passing the pickle in memory (only via file on file system) the logic is duplicated.
625941c15166f23b2e1a50e5
def do_scheme(self, out=sys.stdout): <NEW_LINE> <INDENT> self.logger.info("Modular input: scheme requested") <NEW_LINE> out.write(self.get_scheme()) <NEW_LINE> return True
Get the scheme and write it out to standard output. Arguments: out -- The stream to write the message to (defaults to standard output)
625941c171ff763f4b549613
def _Populate(self, info: Dict[str, Any], warnings: Dict[str, Any]) -> None: <NEW_LINE> <INDENT> info.update({ 'Name': self._object.Name(), 'Image': self._object.Image(), 'Mounts': self._object.VolumeMounts(), }) <NEW_LINE> (warnings if self._object.IsPrivileged() else info)['Privileged'] = self._object.IsPrivileged() <NEW_LINE> warnings['DeclaredPorts'] = self._object.ContainerPorts()
Method override.
625941c14f6381625f1149c7
def image_scaner(): <NEW_LINE> <INDENT> print(f'正在扫描 {base_img_dir} 文件夹下的图片') <NEW_LINE> print('*' * 50) <NEW_LINE> for root, dirs, files in os.walk(base_img_dir): <NEW_LINE> <INDENT> for file in files: <NEW_LINE> <INDENT> file_path = os.path.join(root, file) <NEW_LINE> for dimension in dimensions: <NEW_LINE> <INDENT> x = int(dimension.split(',')[0].strip()) <NEW_LINE> y = int(dimension.split(',')[1].strip()) <NEW_LINE> change_image_size(file_path, x, y)
扫描图片路径
625941c185dfad0860c3ade5
def reload(plugin): <NEW_LINE> <INDENT> unload(plugin) <NEW_LINE> load(plugin)
Reload plugin
625941c166656f66f7cbc136
def testYAMLErrorParser(self): <NEW_LINE> <INDENT> document = ('item1: string1\n' '- item2\n') <NEW_LINE> expected_event_list = [ (yaml.events.StreamStartEvent,), (yaml.events.DocumentStartEvent,), (yaml.events.MappingStartEvent,), (yaml.events.ScalarEvent, 'item1'), (yaml.events.ScalarEvent, 'string1'), ] <NEW_LINE> handler = yaml_test_util.FakeEventHandler(self) <NEW_LINE> listener = yaml_listener.EventListener(handler) <NEW_LINE> with self.assertRaises(yaml_errors.EventListenerYAMLError) as e: <NEW_LINE> <INDENT> listener.Parse(document) <NEW_LINE> self.fail('No parser error raised') <NEW_LINE> <DEDENT> self.assertTrue(str(e.exception).startswith('while parsing a block')) <NEW_LINE> self.assertIsInstance(e.exception.cause, yaml.parser.ParserError) <NEW_LINE> self.assertEqual(len(expected_event_list), len(handler.events)) <NEW_LINE> for expected_event, event in zip(expected_event_list, handler.events): <NEW_LINE> <INDENT> self._AssertEventClass(event, *expected_event)
Test handling of YAML error from Parser.
625941c191af0d3eaac9b9a2
def _create_fluents(self): <NEW_LINE> <INDENT> self.fluents = set([]) <NEW_LINE> for p in self.predicates: <NEW_LINE> <INDENT> var_names, val_generator = self._create_valuations(p.args) <NEW_LINE> for valuation in val_generator: <NEW_LINE> <INDENT> assignment = {var_name: val for var_name, val in zip(var_names, valuation)} <NEW_LINE> self.fluents.add(self._predicate_to_fluent(p, assignment))
Create the set of fluents by grounding the predicates.
625941c156ac1b37e626415f
def concat_tparams(self, tparams): <NEW_LINE> <INDENT> types = [", ".join(p) for p in tparams] <NEW_LINE> return "[{}]".format(types)
Return a valid signature from a list of type parameters.
625941c1e1aae11d1e749c41
def is_import(line): <NEW_LINE> <INDENT> return js_module_re.search(line) is not None
Determines if a selected line contains an import statement.
625941c1e8904600ed9f1eb7
def set(self, attrname, value): <NEW_LINE> <INDENT> if attrname in self.attributes: <NEW_LINE> <INDENT> self.attributes[attrname].value = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.attributes[attrname] = AlarmAttribute(attrname, value)
Setter for attributes :param attrname: attribute name :param value: value
625941c1f8510a7c17cf9687
def step(self, action): <NEW_LINE> <INDENT> self.shapely_obj = None <NEW_LINE> if action is None: <NEW_LINE> <INDENT> action = [0, 0] <NEW_LINE> <DEDENT> delta_f, a = action <NEW_LINE> delta_f, rad_angle = np.radians(10*delta_f), np.radians(self.angle) <NEW_LINE> if a > self.max_vel - self.vel: <NEW_LINE> <INDENT> a = self.max_vel - self.vel <NEW_LINE> <DEDENT> elif a < -self.max_vel - self.vel: <NEW_LINE> <INDENT> a = - self.max_vel - self.vel <NEW_LINE> <DEDENT> ode_state = [self.x, self.y, self.vel, rad_angle] <NEW_LINE> aux_state = (a, delta_f) <NEW_LINE> t = np.arange(0.0, 1.0, 0.1) <NEW_LINE> delta_ode_state = odeint(self.integrator, ode_state, t, args=aux_state) <NEW_LINE> x, y, vel, angle = delta_ode_state[-1] <NEW_LINE> self.x, self.y, self.vel, self.angle = x, y, vel, np.rad2deg(angle) <NEW_LINE> self.angle %= 360.0
Updates the car for one timestep. Args: action: 1x2 array, steering / acceleration action. info_dict: dict, contains information about the environment.
625941c17047854f462a1398
def set_password(self, data: dict) -> dict: <NEW_LINE> <INDENT> if data is None or 'username' not in data or not isinstance(data['username'], str) or 'password' not in data or not isinstance(data['password'], str): <NEW_LINE> <INDENT> return {'error': {'code': -10001, 'message': 'invalid_data'}} <NEW_LINE> <DEDENT> username = data['username'] <NEW_LINE> if not RULE_USERNAME.match(username): <NEW_LINE> <INDENT> return {'error': {'code': -10002, 'message': 'invalid_username'}} <NEW_LINE> <DEDENT> password = data['password'] <NEW_LINE> if not RULE_PASSWORD.match(password): <NEW_LINE> <INDENT> return {'error': {'code': -10003, 'message': 'invalid_password'}} <NEW_LINE> <DEDENT> user = self.__user_db.collection.find_one({'username': username}) <NEW_LINE> if user is None: <NEW_LINE> <INDENT> return {'error': {'code': -10004, 'message': 'user_not_found'}} <NEW_LINE> <DEDENT> new_salt = create_salt_as_base64_string() <NEW_LINE> user['salt'] = new_salt <NEW_LINE> user['password'] = hash_password_with_base64_salt_as_base64_string(password, new_salt) <NEW_LINE> self.__user_db.collection.save(user) <NEW_LINE> return {'success': {'message': 'User password changed'}}
Set the password for a user :param dict data: The data from the call :return: Response dictionary :rtype: dict
625941c185dfad0860c3ade6
def test_filter_input_subsample_vocab(self): <NEW_LINE> <INDENT> random_seed.set_random_seed(42) <NEW_LINE> input_tensor = constant_op.constant([ b"the", b"answer", b"to", b"life", b"and", b"universe" ]) <NEW_LINE> keys = constant_op.constant([b"and", b"life", b"the", b"to", b"universe"]) <NEW_LINE> values = constant_op.constant([40, 8, 30, 20, 2], dtypes.int64) <NEW_LINE> vocab_freq_table = lookup.HashTable( lookup.KeyValueTensorInitializer(keys, values), -1) <NEW_LINE> with self.test_session(): <NEW_LINE> <INDENT> vocab_freq_table.init.run() <NEW_LINE> output = skip_gram_ops._filter_input( input_tensor=input_tensor, vocab_freq_table=vocab_freq_table, vocab_min_count=3, vocab_subsampling=0.05, corpus_size=math_ops.reduce_sum(values), seed=9) <NEW_LINE> self.assertAllEqual([b"the", b"to", b"life", b"and"], output.eval())
Tests input filtering based on vocab subsampling.
625941c1a4f1c619b28affca
def expectation( p: ProbabilityDistributionLike, obj1: PackedExpectationObject, obj2: PackedExpectationObject = None, nghp: Optional[int] = None, ) -> tf.Tensor: <NEW_LINE> <INDENT> p, obj1, feat1, obj2, feat2 = _init_expectation(p, obj1, obj2) <NEW_LINE> try: <NEW_LINE> <INDENT> return dispatch.expectation(p, obj1, feat1, obj2, feat2, nghp=nghp) <NEW_LINE> <DEDENT> except NotImplementedError as error: <NEW_LINE> <INDENT> return dispatch.quadrature_expectation(p, obj1, feat1, obj2, feat2, nghp=nghp)
Compute the expectation <obj1(x) obj2(x)>_p(x) Uses multiple-dispatch to select an analytical implementation, if one is available. If not, it falls back to quadrature. :type p: (mu, cov) tuple or a `ProbabilityDistribution` object :type obj1: kernel, mean function, (kernel, inducing_variable), or None :type obj2: kernel, mean function, (kernel, inducing_variable), or None :param int nghp: passed to `_quadrature_expectation` to set the number of Gauss-Hermite points used: `num_gauss_hermite_points` :return: a 1-D, 2-D, or 3-D tensor containing the expectation Allowed combinations - Psi statistics: >>> eKdiag = expectation(p, kernel) (N) # Psi0 >>> eKxz = expectation(p, (kernel, inducing_variable)) (NxM) # Psi1 >>> exKxz = expectation(p, identity_mean, (kernel, inducing_variable)) (NxDxM) >>> eKzxKxz = expectation(p, (kernel, inducing_variable), (kernel, inducing_variable)) (NxMxM) # Psi2 - kernels and mean functions: >>> eKzxMx = expectation(p, (kernel, inducing_variable), mean) (NxMxQ) >>> eMxKxz = expectation(p, mean, (kernel, inducing_variable)) (NxQxM) - only mean functions: >>> eMx = expectation(p, mean) (NxQ) >>> eM1x_M2x = expectation(p, mean1, mean2) (NxQ1xQ2) .. note:: mean(x) is 1xQ (row vector) - different kernels. This occurs, for instance, when we are calculating Psi2 for Sum kernels: >>> eK1zxK2xz = expectation(p, (kern1, inducing_variable), (kern2, inducing_variable)) (NxMxM)
625941c11f5feb6acb0c4adf
def toml_url(url): <NEW_LINE> <INDENT> response = requests.get(url) <NEW_LINE> return tomlkit.parse(response.text)
Grab a TOML file from URL and return the parsed object
625941c1c432627299f04bd0
def deserialize(self, data): <NEW_LINE> <INDENT> return self._level_deserial(data)
Decodes your encoded data to tree. :type data: str :rtype: TreeNode
625941c130dc7b76659018f4
def onHdenChange(self,value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> self.lineEditHden.setStyleSheet("QLineEdit { background-color: rgb(255, 170, 170) }") <NEW_LINE> self._set_expression_error('H[Den](s)', True, '[{}] is not a valid expression'.format(value)) <NEW_LINE> return <NEW_LINE> <DEDENT> Hden = self.checkTFinput(value) <NEW_LINE> if (Hden == 0): <NEW_LINE> <INDENT> self.lineEditHden.setStyleSheet("QLineEdit { background-color: rgb(255, 170, 170) }") <NEW_LINE> self._set_expression_error('H[Den](s)', True, '[{}] is not a valid expression'.format(value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.lineEditHden.setStyleSheet("QLineEdit { background-color: rgb(95, 211, 141) }") <NEW_LINE> self._set_expression_error('H[Den](s)', False) <NEW_LINE> self.sys.HdenStr = str(value) <NEW_LINE> self.sys.Hden = Hden <NEW_LINE> self.sys.Atualiza()
When user enters a character.
625941c191af0d3eaac9b9a3
def buble_sort(arr): <NEW_LINE> <INDENT> print("Пузырьковая сортировка:") <NEW_LINE> swap = 0 <NEW_LINE> for i in range(len(arr), -1, -1): <NEW_LINE> <INDENT> for j in range(0, i-1): <NEW_LINE> <INDENT> if arr[j] > arr[j+1]: <NEW_LINE> <INDENT> arr[j], arr[j+1] = arr[j+1], arr[j] <NEW_LINE> swap += 1 <NEW_LINE> print("---------swap-----------") <NEW_LINE> <DEDENT> print(arr) <NEW_LINE> <DEDENT> <DEDENT> print(swap) <NEW_LINE> return arr
функция сортировки методов "Пузырька"
625941c1d7e4931a7ee9dea9
def json_load_bean_list(s, t, l=None): <NEW_LINE> <INDENT> j = json.loads(s) <NEW_LINE> if j is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif not isinstance(j, list): <NEW_LINE> <INDENT> logging.error("s: (%s) is not list", s) <NEW_LINE> raise ValueError("not list") <NEW_LINE> <DEDENT> if l is None: <NEW_LINE> <INDENT> l = [] <NEW_LINE> <DEDENT> for ji in j: <NEW_LINE> <INDENT> l.append(t().from_dict(ji)) <NEW_LINE> <DEDENT> return l
@:param t type, should be subclass of BaseBean
625941c1498bea3a759b9a3c
def set_signature(self, signature: str): <NEW_LINE> <INDENT> if (signature is not None) & (len(signature) > 0): <NEW_LINE> <INDENT> self.signature = True <NEW_LINE> self.email.attach(MIMEText(signature, 'plain'))
In this method we add the clients signature to the email @signature: Email signature
625941c123e79379d52ee4f2
def set_connects(self, _workspace): <NEW_LINE> <INDENT> self.proj_combo_box.currentIndexChanged.connect(self.proj_combo_box_changed) <NEW_LINE> self.proj_spin_box.valueChanged.connect(self.proj_spin_box_changed) <NEW_LINE> self.field_combo_box.currentIndexChanged.connect(self.field_type_changed) <NEW_LINE> self.screenshot_act.triggered.connect(self.add_screenshot_conf)
connects signals and slots :param _workspace: :return:
625941c107f4c71912b1140d
def make_marshal_error(marshal_result): <NEW_LINE> <INDENT> error = None <NEW_LINE> if marshal_result[1]: <NEW_LINE> <INDENT> message = None <NEW_LINE> source = marshal_result[1] <NEW_LINE> error = make_error(common.errors.MissingParameterError(message, source)) <NEW_LINE> <DEDENT> return error
Creates a JSON response if the provided marshal_result contains an error message by creating a MissingParameterError with that message. If no error message is present, then None is returned to the caller :marshal_result the tuple returned by marshal_request
625941c1be8e80087fb20bd2
def defineVirtualDevice(parent="string", clear=bool, axis=int, undefine=bool, device="string", usage="string", channel="string", create=bool): <NEW_LINE> <INDENT> pass
defineVirtualDevice is undoable, queryable, and NOT editable. This command defines a virtual device. Virtual devices act like real devices and are useful to manipulate/playback data when an command device is not connected to the computer.
625941c17d43ff24873a2c2b
def backtrack(board, i, j, trie, pre, used, result): <NEW_LINE> <INDENT> if '#' in trie: <NEW_LINE> <INDENT> result.add(pre) <NEW_LINE> <DEDENT> if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not used[i][j] and board[i][j] in trie: <NEW_LINE> <INDENT> used[i][j] = True <NEW_LINE> backtrack(board, i+1, j, trie[board[i][j]], pre+board[i][j], used, result) <NEW_LINE> backtrack(board, i, j+1, trie[board[i][j]], pre+board[i][j], used, result) <NEW_LINE> backtrack(board, i-1, j, trie[board[i][j]], pre+board[i][j], used, result) <NEW_LINE> backtrack(board, i, j-1, trie[board[i][j]], pre+board[i][j], used, result) <NEW_LINE> used[i][j] = False
backtrack tries to build each words from the board and return all words found @param: board, the passed in board of characters @param: i, the row index @param: j, the column index @param: trie, a trie of the passed in words @param: pre, a buffer of currently build string that differs by recursion stack @param: used, a replica of the board except in booleans to state whether a character has been used @param: result, the resulting set that contains all words found @return: list of words found
625941c166673b3332b9201d
def navigate(self, name): <NEW_LINE> <INDENT> return self.getDeclaration(name)
Same as self.getDeclaration
625941c130dc7b76659018f5