code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_command_line_interface(tmpdir): <NEW_LINE> <INDENT> folder = str(tmpdir.mkdir("html")) <NEW_LINE> db_path = str(tmpdir.mkdir("db").join('test.db')) <NEW_LINE> engine = create_engine('sqlite:///' + db_path) <NEW_LINE> init_db(engine) <NEW_LINE> runner = CliRunner() <NEW_LINE> result = runner.invoke(cli, [db_pat... | Test the CLI. | 625941c9004d5f362079a3b5 |
def forward(self, x_emb, x_m, utterance, size=FLAGS.batch_size): <NEW_LINE> <INDENT> x_emb_ta = tensor_array_ops.TensorArray(dtype=tf.float32, size=0, dynamic_size=True).unstack(x_emb) <NEW_LINE> x_m_ta = tensor_array_ops.TensorArray(dtype=tf.float32, size=0, dynamic_size=True).unstack(x_m) <NEW_LINE> prob_ta = tensor_... | forward with golden including start and end token
:param x_emb: max_len * size * e_dim
:param x_m: max_len * size * 1
:param utterance: size * hred_h_dim
:return: max_len * size * vocab_size(with start_token pre written) | 625941c910dbd63aa1bd2c25 |
def is_time_axis_dynamic(self): <NEW_LINE> <INDENT> assert self.time_dim_axis is not None <NEW_LINE> if self.time_dim_axis_excluding_batch in self.size_placeholder: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> assert isinstance(self.shape[self.time_dim_axis_excluding_batch], int), ( "%s: dynamic time axis dim (N... | :return: whether there are different seq-lens for the time, or all the same (static)
:rtype: bool | 625941c9c432627299f04cc7 |
def isPalindrome(self, x): <NEW_LINE> <INDENT> if (str(x)[::-1] == str(x))!=True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if str(x)[::-1] == str(x): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> False | :type x: int
:rtype: bool | 625941c9925a0f43d2549ef8 |
def isToeplitzMatrix(self, matrix): <NEW_LINE> <INDENT> times = len(matrix)+len(matrix[0]) <NEW_LINE> for i in range(1, len(matrix)): <NEW_LINE> <INDENT> for j in range(1,len(matrix[0])): <NEW_LINE> <INDENT> if matrix[i-1][j-1] != matrix[i][j]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> retu... | :type matrix: list[list[int]]
:rtype: bool | 625941c9cc0a2c11143dcf12 |
def find_place(me): <NEW_LINE> <INDENT> loc = me.entity.location.copy() <NEW_LINE> loc.pos = Vector3D([c + uniform(-50, 50) for c in loc.pos]) <NEW_LINE> ent = Entity(me, location=loc) <NEW_LINE> return Operation("move", ent) | find place for home: wander randomly | 625941c963d6d428bbe44571 |
def unions(): <NEW_LINE> <INDENT> global out <NEW_LINE> global indent <NEW_LINE> for union in soup.find_all("compounddef", kind="union"): <NEW_LINE> <INDENT> name = str(union.compoundname.string) <NEW_LINE> if name in blacklist: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> out.append("") <NEW_LINE> describe(union) ... | Converts C unions to Go types with access methods. | 625941c9167d2b6e31218c17 |
@bottle.get('/recent') <NEW_LINE> def recent(db): <NEW_LINE> <INDENT> pastes = db.query( model.Paste.id, model.Paste.filename, model.Paste.mimetype, model.Paste.created, model.Paste.password ).order_by(model.Paste.id.desc()).limit(20).all() <NEW_LINE> ul = u'<ul>%s</ul>' <NEW_LINE> li = [] <NEW_LINE> for paste in paste... | Shows an unordered list of most recent pasted items | 625941c93cc13d1c6d3c73fc |
def generate(self, numRows): <NEW_LINE> <INDENT> matrix = [[1]*(i+1) for i in range(numRows)] <NEW_LINE> for i in range(numRows): <NEW_LINE> <INDENT> for j in range(1, i): <NEW_LINE> <INDENT> matrix[i][j] = matrix[i-1][j-1] + matrix[i-1][j] <NEW_LINE> <DEDENT> <DEDENT> return matrix | :type numRows: int
:rtype: List[List[int]] | 625941c9d53ae8145f87a2f3 |
def add_note(self,note,replace=False): <NEW_LINE> <INDENT> if self.data is None: <NEW_LINE> <INDENT> raise ValueError('Cannot edit empty data. Use read() or set data attribute') <NEW_LINE> <DEDENT> if note is None: <NEW_LINE> <INDENT> note = '' <NEW_LINE> <DEDENT> if replace: <NEW_LINE> <INDENT> self.data[self.note_fie... | Add (or replace) a note. Does *NOT* write() | 625941c98a43f66fc4b540e7 |
def __init__(self, size): <NEW_LINE> <INDENT> self.integer_validator("size", size) <NEW_LINE> self.__size = size <NEW_LINE> super().__init__(size, size) | Init with super function to use all attributes from parent class | 625941c9e76e3b2f99f3a88e |
def test_in_date_5(self): <NEW_LINE> <INDENT> stock_location = self.env.ref('stock.stock_location_stock') <NEW_LINE> product1 = self.env['product.product'].create({ 'name': 'Product A', 'type': 'product', 'tracking': 'lot', }) <NEW_LINE> lot1 = self.env['stock.production.lot'].create({ 'name': 'lot1', 'product_id': pro... | Receive the same lot at different times, once they're in the same location, the quants
are merged and only the earliest incoming date is kept. | 625941c9f7d966606f6aa085 |
def images_at(self, rects, colorkey=None, x_transform=False): <NEW_LINE> <INDENT> return [self.image_at(rect, colorkey, x_transform) for rect in rects] | Loads multiple images, supply a list of coordinates | 625941c9377c676e9127222b |
def clear(self) -> None: <NEW_LINE> <INDENT> for i in range(0, self._max_displayed_items): <NEW_LINE> <INDENT> self._window.addstr(self._display_start_y + i, 0, self._pad_item_str("")) | Clears the menu.
Clears by writing blank lines the width of the entire menu. Very
inefficient, and should not be used frequently. | 625941c966673b3332b92112 |
def get_api_keys_details(self, *, iam_api_key: str = None, include_history: bool = None, **kwargs ) -> DetailedResponse: <NEW_LINE> <INDENT> headers = { 'IAM-ApiKey': iam_api_key } <NEW_LINE> sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='get_api_keys_details')... | Get details of an API key by its value.
Returns the details of an API key by its value. Users can manage user API keys for
themself, or service ID API keys for service IDs that are bound to an entity they
have access to.
:param str iam_api_key: (optional) API key value.
:param bool include_history: (optional) Define... | 625941c9167d2b6e31218c18 |
def clean(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if os.path.isfile(self._private_key_file): <NEW_LINE> <INDENT> os.remove(self._private_key_file) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.warning(e) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if os.path.isfile(self._publi... | Removes the files under the work dir | 625941c9c4546d3d9de72ab5 |
def fetch_arm(user_id, api_key, datastream, variables, start, end): <NEW_LINE> <INDENT> datastream_dfs = [] <NEW_LINE> filenames = list_arm_filenames(user_id, api_key, datastream, start, end) <NEW_LINE> for filename in filenames: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nc_file = retrieve_arm_dataset(user_id, api_k... | Gets data from ARM API and concatenates requested datastreams into
a single Pandas Dataframe.
Parameters
----------
user_id: string
ARM user id.
api_key: string
ARM live API access token.
datastream: string
The datastream to request.
variables
List of variables to parse from the datastream.
start: date... | 625941c956ac1b37e6264252 |
def set_port_profile_created(self, vlan_id, profile_name): <NEW_LINE> <INDENT> with self.session.begin(subtransactions=True): <NEW_LINE> <INDENT> port_profile = self.session.query( ucsm_model.PortProfile).filter_by( vlan_id=vlan_id, profile_id=profile_name).first() <NEW_LINE> if port_profile: <NEW_LINE> <INDENT> port_p... | Sets created_on_ucs flag to True. | 625941c930dc7b76659019e9 |
def test_post_create_uri_in_location_hdr(sut: SystemUnderTest): <NEW_LINE> <INDENT> response = sut.get_response('POST', sut.sessions_uri) <NEW_LINE> if response is None or not response.ok: <NEW_LINE> <INDENT> msg = ('No successful response found for POST to Sessions URI; ' 'unable to test this assertion') <NEW_LINE> st... | Perform tests for Assertion.REQ_POST_CREATE_URI_IN_LOCATION_HDR. | 625941c9e5267d203edcdd20 |
def f_instable(z: typing.Tuple[float, float], _: float) -> typing.Tuple[float, float]: <NEW_LINE> <INDENT> y, dy = z <NEW_LINE> return dy, 6 * y - dy | Equation différentielle instable. | 625941c93d592f4c4ed1d0f1 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(axis_recordResponse, self).__init__(*args, **kwds) <NEW_LINE> if self.ret is None: <NEW_LINE> <INDENT> self.ret = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.ret = False | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
ret
:param args: complete set of ... | 625941c929b78933be1e572f |
def create_route(self, route_table_id, destination_cidr_block, gateway_id=None, instance_id=None, interface_id=None, dry_run=False): <NEW_LINE> <INDENT> params = { 'RouteTableId': route_table_id, 'DestinationCidrBlock': destination_cidr_block } <NEW_LINE> if gateway_id is not None: <NEW_LINE> <INDENT> params['GatewayId... | Creates a new route in the route table within a VPC. The route's target
can be either a gateway attached to the VPC or a NAT instance in the
VPC.
:type route_table_id: str
:param route_table_id: The ID of the route table for the route.
:type destination_cidr_block: str
:param destination_cidr_block: The CIDR address ... | 625941c91b99ca400220ab33 |
def set_state(self, state): <NEW_LINE> <INDENT> self._state = state | Set the state of the translator. | 625941c97c178a314d6ef4e0 |
def draw_environment(particles): <NEW_LINE> <INDENT> momentum_gas = momentum(particles) <NEW_LINE> print("U: {} | P: {} | P_wall: {}".format(energy(particles), momentum_gas, momentum_ini - momentum_gas)) <NEW_LINE> game_display.fill(WHITE) <NEW_LINE> for particle_pair in combinations(particles, 2): <NEW_LINE> <INDENT> ... | the drawing of the frame | 625941c9f548e778e58cd5ff |
def recv(self): <NEW_LINE> <INDENT> buf=self.sock.recv(1024,0) <NEW_LINE> if len(buf) < 12: <NEW_LINE> <INDENT> if len(buf) <=0: <NEW_LINE> <INDENT> print ("socket disconnect") <NEW_LINE> sys.exit(-1) <NEW_LINE> <DEDENT> print ("the receved buf is small") <NEW_LINE> return "" <NEW_LINE> <DEDENT> mark,slen,crc32,json=st... | get pack from socket | 625941c9009cb60464c63434 |
def _time2sec(time): <NEW_LINE> <INDENT> if not isinstance(time, numbers.Number): <NEW_LINE> <INDENT> time, unit = float(time[:-1]), time[-1] <NEW_LINE> assert unit in 'dh' <NEW_LINE> time *= 24 * 3600 if unit == 'd' else 3600 <NEW_LINE> <DEDENT> return time | Convert string (e.g. 1d or 0.5h) to seconds | 625941c92ae34c7f2600d1b3 |
def save_draft(db_session, log, account_id, draftmsg): <NEW_LINE> <INDENT> register_backends() <NEW_LINE> account = db_session.query(Account).get(account_id) <NEW_LINE> local_save_draft = ACTION_MODULES[account.provider].local_save_draft <NEW_LINE> imapuid = local_save_draft(db_session, log, account.id, account.drafts_... | Save draft locally and also sync back to the backend. | 625941c91f037a2d8b946280 |
def read_role(self, name, mount_point=DEFAULT_MOUNT_POINT): <NEW_LINE> <INDENT> api_path = utils.format_url( '/v1/{mount_point}/roles/{name}', mount_point=mount_point, name=name, ) <NEW_LINE> return self._adapter.get( url=api_path, ) | Read Role.
Queries the role definition.
Supported methods:
GET: /{mount_point}/roles/{name}. Produces: 200 application/json
:param name: The name of the role to read.
:type name: str | unicode
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON res... | 625941c9287bf620b61d3ae6 |
def blank_spaces_ratio(game): <NEW_LINE> <INDENT> blank_spaces = len(game.get_blank_spaces()) <NEW_LINE> dim = game.width * game.height <NEW_LINE> return blank_spaces / dim | " The Ratio of empty fields and dimension of the board | 625941c95fcc89381b1e1740 |
def _configure(self, engine): <NEW_LINE> <INDENT> CONF.set_override('connection', str(engine.url), group='database') | Repo and database configuration
For each type of repository we should do some configuration steps.
For migrate_repo we should set our database under version control.
For alembic we should configure database settings. For this goal we
should use oslo.config and openstack.commom.db.sqlalchemy.session with
database funct... | 625941c923849d37ff7b3112 |
def write_32_va(self, vaddr, pid, value): <NEW_LINE> <INDENT> msgtype = "WRITE_32_VA" <NEW_LINE> self.tprint(DEBUG, msgtype) <NEW_LINE> submsg = self.vmmsg_helper(msgtype) <NEW_LINE> submsg.vaddr = int(vaddr) <NEW_LINE> submsg.value = int(value) <NEW_LINE> submsg.pid = int(pid) <NEW_LINE> self.send_default_reply() <NEW... | Supported API call.
Matches LibVMI behavior. | 625941c98c0ade5d55d3ea3c |
def test_wrapper_class_has_groovy_classmethods(self): <NEW_LINE> <INDENT> element_proxy = Person._GRAPH.person <NEW_LINE> obj = element_proxy.create(name='test', age=32) <NEW_LINE> self.assertTrue(hasattr(Person, 'get_older_30')) <NEW_LINE> self.assertEqual(Person.__dict__['get_older_30'].__class__.__name__, 'classmeth... | Make sure private groovy methods are applied as classmethods to the wrapper class.
These custom groovy functions are useful for optimized common queries that can be performed on the database
side. | 625941c9236d856c2ad4485b |
def setUserCategory(self, uid, userCategory): <NEW_LINE> <INDENT> pass | Parameters:
- uid
- userCategory | 625941c94c3428357757c3aa |
def GetPayOff(tree,attribute): <NEW_LINE> <INDENT> node = tree.get_node(attribute) <NEW_LINE> level_all = tree.depth() + 1 <NEW_LINE> level_site = tree.depth() + 1 - tree.depth(node) <NEW_LINE> return float(level_site/level_all) | 获取非数字型的PayOff
:param tree: 属性的树
:param attribute: 属性值
:return: PayOff | 625941c98e7ae83300e4b04e |
def MakeConfigDir(name): <NEW_LINE> <INDENT> config_dir = wx.GetHomeDir() + GetPathChar() + u"." + ed_glob.PROG_NAME <NEW_LINE> try: <NEW_LINE> <INDENT> os.mkdir(config_dir + GetPathChar() + name) <NEW_LINE> <DEDENT> except (OSError, IOError): <NEW_LINE> <INDENT> pass | Makes a user config direcotry
@param name: name of config directory to make in user config dir | 625941c9adb09d7d5db6c812 |
def BeforeSetupRound( self ): <NEW_LINE> <INDENT> self.itemTracker.Clear() | Called right before the round is set up on the map (before weapons/armor is placed) | 625941c9aad79263cf390ac2 |
@main.command() <NEW_LINE> def balance(): <NEW_LINE> <INDENT> dump(api.balance) | Show account balance | 625941c98c3a87329515843c |
def _db_load_items_all(self): <NEW_LINE> <INDENT> for modname, plugin in self.plugins.items(): <NEW_LINE> <INDENT> self._db_load_item(modname, plugin) | Load all internal+plugin data from persistent DB for every initialized plugin | 625941c9851cf427c661a592 |
def size(self, size): <NEW_LINE> <INDENT> self.structure['size'] = size <NEW_LINE> return self | Limit the number of query results. | 625941c9f9cc0f698b14067e |
def generate_news_section(): <NEW_LINE> <INDENT> news = None <NEW_LINE> common.setup_gettext() <NEW_LINE> if file_current_enough(DB_PICKLED): <NEW_LINE> <INDENT> with open('databags/news.pickle', 'rb') as goodname: <NEW_LINE> <INDENT> news = pickle.load(goodname) <NEW_LINE> <DEDENT> <DEDENT> elif 'DEBUG' in os.environ:... | Retrieve news from multiple sources and generate a news section. If the
environment variable DEBUG, databags/news.pickle is loaded, if it exists.
Otherwise the file is retrieved and stored for subsequent debugging. If no
internet access is present and no databags/news.pickle file exists, the news
section will be empty. | 625941c95166f23b2e1a51db |
def test_invalid_court_order_courtname(): <NEW_LINE> <INDENT> co_info = copy.deepcopy(COURT_ORDER) <NEW_LINE> co_info['courtName'] = 'xx' <NEW_LINE> is_valid, errors = validate(co_info, 'courtOrder', 'ppr') <NEW_LINE> if errors: <NEW_LINE> <INDENT> for err in errors: <NEW_LINE> <INDENT> print(err.message) <NEW_LINE> <D... | Assert that an invalid court order fails - court name is too short. | 625941c9236d856c2ad4485c |
def filter_reads_by_length(fq1, fq2, quality_format, min_length=20): <NEW_LINE> <INDENT> logger.info("Removing reads in %s and %s that " "are less than %d bases." % (fq1, fq2, min_length)) <NEW_LINE> fq1_out = utils.append_stem(fq1, ".fixed") <NEW_LINE> fq2_out = utils.append_stem(fq2, ".fixed") <NEW_LINE> fq1_single =... | removes reads from a pair of fastq files that are shorter than
a minimum length. removes both ends of a read if one end falls
below the threshold while maintaining the order of the reads | 625941c9283ffb24f3c55984 |
def recommend(self, user): <NEW_LINE> <INDENT> K = self.n_sim_movie <NEW_LINE> N = self.n_rec_movie <NEW_LINE> rank = {} <NEW_LINE> watched_movies = self.trainset[user] <NEW_LINE> print("=========itemsim_mat==========:",self.movie_sim_mat) <NEW_LINE> for movie, rating in watched_movies.iteritems(): <NEW_LINE> <INDENT> ... | Find K similar movies and recommend N movies. | 625941c9a8ecb033257d3150 |
def rename_seqs_to_asvs(otu_table, otu_table_renamed_loc, asvs_fasta_loc): <NEW_LINE> <INDENT> asv_sequences = list(otu_table.index) <NEW_LINE> seq_to_asv_name = {} <NEW_LINE> for i, asv_seq in enumerate(asv_sequences): <NEW_LINE> <INDENT> seq_to_asv_name.update({asv_seq: 'ASV'+str(i)}) <NEW_LINE> <DEDENT> otu_table_re... | Because by default from dada2 we have indexes as full sequences we need to give them new human-readable names,
and save this mapping to fasta file. | 625941c9fff4ab517eb2f4be |
def from_periodogram(Sx, fs): <NEW_LINE> <INDENT> sh = Sx.shape <NEW_LINE> if (len(sh) == 1): <NEW_LINE> <INDENT> Sx = np.reshape(Sx,(1,sh[0])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (sh[0] > sh[1]): <NEW_LINE> <INDENT> Sx = Sx.T <NEW_LINE> <DEDENT> <DEDENT> sh = Sx.shape <NEW_LINE> NX = sh[0] <NEW_LINE... | Simulate RPs from given spectral densities.
Parameters: Sx: spectral densities as ndarray (must have odd
length, otherwise it will be truncated by 1 and
the length of simulation will not be as expected!)
The largest dimension of Sx is assumed to be the
... | 625941c9091ae35668666fe2 |
def train_gan(gan, dataset, epochs): <NEW_LINE> <INDENT> generator, discriminator = gan.layers <NEW_LINE> coding_size = generator.coding_size <NEW_LINE> discriminator_loss = [] <NEW_LINE> generator_loss = [] <NEW_LINE> for epoch in range(epochs): <NEW_LINE> <INDENT> batch = 1 <NEW_LINE> for X_batch in dataset: <NEW_LIN... | Train a Generative Adversarial Network and return batch losses
Arguments:
gan (tf.keras.Model) - Complete GAN model, consisting of a Generator and Discriminator
stacked as a Sequential model
dataset (tf.Dataset) - Batched and preprocessed set of images to train on
epochs (int) - Number of times to ... | 625941c9f9cc0f698b14067f |
def renderFromTemplate(directory, template_name, **kwargs): <NEW_LINE> <INDENT> loader = FileSystemLoader(directory) <NEW_LINE> env = Environment(loader=loader, trim_blocks=True, lstrip_blocks=True) <NEW_LINE> template = env.get_template(template_name) <NEW_LINE> return template.render(**kwargs) | Render the html
| 625941c9e8904600ed9f1fae |
def write(self, atoms=None, **kwargs): <NEW_LINE> <INDENT> if atoms is None: <NEW_LINE> <INDENT> atoms = self.atoms <NEW_LINE> <DEDENT> for image in atoms.iterimages(): <NEW_LINE> <INDENT> self._write_atoms(image, **kwargs) | Write the atoms to the file.
If the atoms argument is not given, the atoms object specified
when creating the trajectory object is used.
Use keyword arguments to add extra properties::
writer.write(atoms, energy=117, dipole=[0, 0, 1.0]) | 625941c9fb3f5b602dac3715 |
@_inherit_docstrings(pandas.merge, apilink="pandas.merge") <NEW_LINE> def merge( left, right, how: str = "inner", on=None, left_on=None, right_on=None, left_index: bool = False, right_index: bool = False, sort: bool = False, suffixes=("_x", "_y"), copy: bool = True, indicator: bool = False, validate=None, ): <NEW_LINE>... | Merge DataFrame or named Series objects with a database-style join. | 625941c9442bda511e8be49c |
def queue_processor(queue, handler, kwargs=None): <NEW_LINE> <INDENT> kwargs = kwargs or {} <NEW_LINE> while True: <NEW_LINE> <INDENT> item = queue.get(block=True) <NEW_LINE> try: <NEW_LINE> <INDENT> handler(item, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> item_str = 'unknown' <NEW_LINE> t... | Get all message from sink, run them though handler
:param sink: a Queue object where messages can be taken from
:param handler: a function that takes a single argument, a message
:param kwargs: extra kwargs that are passed to the handler with each call | 625941c9656771135c3eb8f0 |
def save(self): <NEW_LINE> <INDENT> with self.open(self.filename, 'wt') as fd: <NEW_LINE> <INDENT> for node in self.elements: <NEW_LINE> <INDENT> fd.write(node.text) | Re-writes the current raw file, saving all changes. | 625941c9046cf37aa974cdcb |
def semcor2run(args): <NEW_LINE> <INDENT> input_files = list_files(*args.input_files) <NEW_LINE> output_dir = Path(args.output_dir) <NEW_LINE> if not output_dir.is_dir(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output_dir.mkdir() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('Invalid output directory name.... | Generate a file with running text (and wordform/pos format) to be read with
corpus analysis tools. | 625941c92ae34c7f2600d1b4 |
def recorrido_bfs(grafo, origen, visitados, orden, padre, visitar, extra): <NEW_LINE> <INDENT> cola = Cola() <NEW_LINE> cola.encolar(origen) <NEW_LINE> visitados.append(origen) <NEW_LINE> while not cola.esta_vacia(): <NEW_LINE> <INDENT> actual = cola.desencolar() <NEW_LINE> continuar = visitar(actual, padre, orden, ext... | Recorrido BFS para un grafo, se aplicara la funcion
visitar a cada vertice y se finalizara el recorrido
si la funcion devuelve False, extra es un parametro para
la funcion visitar, si es necesario | 625941c9e8904600ed9f1faf |
def _arome_download(arome_parameters, time_frame='00H06H'): <NEW_LINE> <INDENT> _logger.debug('Begin - getArome') <NEW_LINE> web_parameters = {'fond': 'donnee_libre', 'token': _AROME_DOWNLOAD_TOKEN} <NEW_LINE> arome_parameters['time'] = time_frame <NEW_LINE> arome_parameters.update(web_parameters) <NEW_LINE> enc... | Download one Arome grib2 file from MeteoFrance
| 625941c921bff66bcd6849d6 |
def __expr_stmt(self): <NEW_LINE> <INDENT> expr = self.__expression() <NEW_LINE> self.__consume(expected=TokenType.SEMICOLON, err_msg="Expect ';' after statement.") <NEW_LINE> return Expression(expr) | exprStmt → expression ";" ; | 625941c9a05bb46b383ec8a4 |
def get_keys(self): <NEW_LINE> <INDENT> key, pri, pub = self.read_keys() <NEW_LINE> if not all([key, pri, pub]): <NEW_LINE> <INDENT> key, pri, pub = self.generate_keys() <NEW_LINE> self.cache_keys(pri, pub) <NEW_LINE> <DEDENT> return key, pub, pri | If a cached keypair is available, return it; otherwise, generate, cache and
return a new keypair. | 625941c957b8e32f5248351d |
def temparature(update, context): <NEW_LINE> <INDENT> query = update.callback_query <NEW_LINE> query.answer() <NEW_LINE> keyboard = [ [ InlineKeyboardButton("🚰 Pump Status", callback_data=str(MOTOR)) ], [ InlineKeyboardButton("⬅️ Back", callback_data=str(BACK)) ] ] <NEW_LINE> reply_markup = InlineKeyboardMarkup(keyboa... | Show new choice of buttons | 625941c90a50d4780f666f14 |
def sum13(nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> for i in range(0, len(nums)): <NEW_LINE> <INDENT> if nums[i] == 13: <NEW_LINE> <INDENT> nums[i] = 0 <NEW_LINE> if i+1 < len(nums): <NEW_LINE> <INDENT> nums[i+1] = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return sum(n... | Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very
unlucky, so it does not count and numbers that come immediately after a 13 also do not count. | 625941c907d97122c417890c |
def request(self, path, request, body=None, **kwargs): <NEW_LINE> <INDENT> out_hdrs = dict.copy(self.headers) <NEW_LINE> if kwargs.get("accept"): <NEW_LINE> <INDENT> out_hdrs['accept'] = kwargs.get("accept") <NEW_LINE> <DEDENT> if body: <NEW_LINE> <INDENT> if isinstance(body, dict): <NEW_LINE> <INDENT> body = six.text_... | Make an HTTP request and return the results.
:param path: Path used with the initialized URL to make a request.
:param request: HTTP request type (GET, POST, PUT, DELETE).
:param body: HTTP body of request.
:key accept: Set HTTP 'Accept' header with this value.
:key base_path: Override the base_path for this request.
... | 625941c9cc40096d615959d3 |
def matches(self, string): <NEW_LINE> <INDENT> result = self.__matches(string) <NEW_LINE> return not result if self.invert else result | Try to match a candidate string and return a Boolean | 625941c90383005118ecf665 |
def gcp_histone_normalize(data_df, gcp_normalization_peptide_id): <NEW_LINE> <INDENT> assert gcp_normalization_peptide_id in data_df.index, ( ("The normalization peptide is not in this dataset. " + "gcp_normalization_peptide_id: {}".format(gcp_normalization_peptide_id))) <NEW_LINE> norm_values = data_df.loc[gcp_normali... | Subtract values of gcp_normalization_peptide_id from all the other probes.
Remove the row of data corresponding to the normalization histone.
Assumes that all probes should be normalized to the same peptide id.
Args:
data_df (pandas df)
gcp_normalization_peptide_id (string): id
Returns:
out_df (pandas df... | 625941c9ac7a0e7691ed4150 |
def vo_storage_graph_cmd(level, vose_dict, attribute, start_time, site_name='', small=False): <NEW_LINE> <INDENT> if vose_dict == {}: <NEW_LINE> <INDENT> return 'N/A' <NEW_LINE> <DEDENT> rrd_dir = '/var/cache/gstat/rrd/VO' <NEW_LINE> if level == 'vose': <NEW_LINE> <INDENT> title="%s Storage Space (GlueSE: %s, VO: %s)" ... | Compose RRD graph command for Storage space for VO | 625941c963f4b57ef000119e |
def exactly_one_link_per_end(graph, segment): <NEW_LINE> <INDENT> num = segment.number <NEW_LINE> if num in graph.forward_links and len(graph.forward_links[num]) != 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if num in graph.reverse_links and len(graph.reverse_links[num]) != 1: <NEW_LINE> <INDENT> return Fa... | Returns True if the given segment has exactly one link on either end. | 625941c982261d6c526ab521 |
def _get_open_file_names(self_, msg, start_dir, filter_str): <NEW_LINE> <INDENT> return [returned_files] | Return filenames like a open file dialog. | 625941c95e10d32532c5efaa |
def get_folder_path(self, filename: str = None) -> str: <NEW_LINE> <INDENT> if not filename and not self.filename: <NEW_LINE> <INDENT> raise FileNotFoundError("No file provided.") <NEW_LINE> <DEDENT> if not filename: <NEW_LINE> <INDENT> filename = self.filename <NEW_LINE> <DEDENT> current_directory = os.getcwd() <NEW_L... | Gets file path without file from project root directory.
Args:
filename: Name of the file
Returns:
str: Folder path of the file | 625941c950812a4eaa59c3a5 |
def store_results(results, imdbid, backlog=False): <NEW_LINE> <INDENT> today = datetime.date.today() <NEW_LINE> logging.info('{} results found for {}. Storing results.'.format(len(results), imdbid)) <NEW_LINE> BATCH_DB_STRING = [] <NEW_LINE> for result in results: <NEW_LINE> <INDENT> if 'date_found' not in result: <NEW... | Stores search results in database.
results (list): of dicts of search results
imdbid (str): imdb identification number
backlog (bool): if this call is from a backlog search <optional -
default False>
Writes batch of search results to table.
If storing backlog search results, will purge exist... | 625941c9be383301e01b550a |
def setdefault(pb_or_dict, key, value): <NEW_LINE> <INDENT> if not get(pb_or_dict, key, default=None): <NEW_LINE> <INDENT> set(pb_or_dict, key, value) | Set the key on the object to the value if the current value is falsy.
Because protobuf Messages do not distinguish between unset values and
falsy ones particularly well, this method treats any falsy value
(e.g. 0, empty list) as a target to be overwritten, on both Messages
and dictionaries.
Args:
pb_or_dict (Unio... | 625941c9b7558d58953c4f98 |
@pytest.fixture <NEW_LINE> def vulns_filtering(host, vuln_factory): <NEW_LINE> <INDENT> yield [ vuln_factory.create(host=host, name='vuln 1', xtype='test.123', severity=SeverityEnum.info, tags=None), vuln_factory.create(host=host, name='vuln 2', xtype='test.123', severity=SeverityEnum.info, tags=['tagx']), vuln_factory... | prepare set of vulns needed for basic filtering tests | 625941c9bde94217f3682e74 |
def __init__(self, connection_class=Connection, max_connections=None, **connection_kwargs): <NEW_LINE> <INDENT> self.pid = os.getpid() <NEW_LINE> self.connection_class = connection_class <NEW_LINE> self.connection_kwargs = connection_kwargs <NEW_LINE> self.max_connections = max_connections or 2 ** 31 <NEW_LINE> self._c... | Create a connection pool. If max_connections is set, then this object
raises ssdb.ConnectionError when the pool's limit is reached. By
default, TCP connections are created connection_class is specified. Any
additionan keyword arguments are passed to the constructor of
connection_class. | 625941c9a05bb46b383ec8a5 |
def featureNormalize(X): <NEW_LINE> <INDENT> X_norm = X.copy() <NEW_LINE> mu = np.zeros(X.shape[1]) <NEW_LINE> sigma = np.zeros(X.shape[1]) <NEW_LINE> mu[0]=np.mean(X[:,0]) <NEW_LINE> mu[1]=np.mean(X[:,1]) <NEW_LINE> sigma[0]=np.std(X[:,0]) <NEW_LINE> sigma[1]=np.std(X[:,1]) <NEW_LINE> X_norm[:,0]=(X[:,0]-mu[0])/sigma... | Normalizes the features in X. returns a normalized version of X where
the mean value of each feature is 0 and the standard deviation
is 1. This is often a good preprocessing step to do when working with
learning algorithms.
Parameters
----------
X : array_like
The dataset of shape (m x n).
Returns
-------
X_norm ... | 625941c9bf627c535bc13251 |
def exec_sub_success_arg(self): <NEW_LINE> <INDENT> return self.exec_sub_store_arg(store_type="success") | exec_sub_success_arg ::= exec_sub_store_arg | 625941c99f2886367277a910 |
def solution(n): <NEW_LINE> <INDENT> return bin(n).count("1") | ans = 0
while n != 0:
n, r = divmod(n, 2)
ans += r
return ans | 625941c9b5575c28eb68e083 |
def meets_forcecli_version(self, minversion): <NEW_LINE> <INDENT> version = Helper.get_forcecli_version(self) <NEW_LINE> print("Version: " + version + ", min: " + minversion) <NEW_LINE> if version == "dev": <NEW_LINE> <INDENT> return version == "dev" <NEW_LINE> <DEDENT> return semver.match(version, ">=" + minversion) | Sample doc string. | 625941c991af0d3eaac9ba9b |
def getActivePlayerAndID(): <NEW_LINE> <INDENT> return gc.getGame().getActivePlayer(), gc.getActivePlayer() | Returns the Player ID and CyPlayer for the active player. | 625941c950485f2cf553ce1c |
def coverage_callback(files): <NEW_LINE> <INDENT> display.info('Including %d exported coverage file(s) in payload.' % len(pairs), verbosity=1) <NEW_LINE> files.extend(pairs) | Add the coverage files to the payload file list. | 625941c99f2886367277a911 |
@pytest.mark.parametrize('user', ['visitor', 'editor', 'archivist']) <NEW_LINE> def test_principals__AddForm__6(address_book, browser, user): <NEW_LINE> <INDENT> browser.login(user) <NEW_LINE> browser.assert_forbidden(browser.PRINCIPAL_ADD_URL) | It cannot be accessed by a non-admin users. | 625941c9bf627c535bc13252 |
def train_dataloader(self, dataset_index=None): <NEW_LINE> <INDENT> return self._build_dataloader( dataset_index=dataset_index, indices=self.datasets[dataset_index].indices["train"], ) | WIP | 625941c9283ffb24f3c55985 |
def handle_data(self, data, cdata=False): <NEW_LINE> <INDENT> if data and self.element: <NEW_LINE> <INDENT> if self.check_validity and self.elementType: <NEW_LINE> <INDENT> check_standalone = ( self.declared_standalone() and self.elementType.entity is not self.docEntity) <NEW_LINE> if (check_standalone and self.element... | [43] content
data
A string of data to be handled
cdata
If True *data* is treated as character data (even if it
matches the production for S).
Data is handled by calling
:py:meth:`~pyslet.xml.structures.Element.add_data`
even if the data is optional white space. | 625941c997e22403b379d01c |
def soft_update(local_model, target_model, tau): <NEW_LINE> <INDENT> for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): <NEW_LINE> <INDENT> target_param.data.copy_(tau*local_param.data + (1.0 - tau) * target_param.data) | Soft update model parameters.
target parameters = tau * local parameters + (1 - tau) * target parameters | 625941c945492302aab5e346 |
def get_songs(test=True): <NEW_LINE> <INDENT> if _Constants._TEST or test: <NEW_LINE> <INDENT> rows = _Constants._DATABASE.execute("SELECT data FROM music LIMIT {hardware}".format( hardware=_Constants._HARDWARE)) <NEW_LINE> data = [r[0] for r in rows] <NEW_LINE> data = [_Auxiliary._byteify(_json.loads(r)) for r in data... | Gets a list of all the songs in the database. | 625941c966656f66f7cbc22e |
def polygon_inside_polygon(P, Q): <NEW_LINE> <INDENT> r = simple_polygon_intersection(P, Q) <NEW_LINE> if len(r) == 0 or len(r) > 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return polygon_equality(P, r[0]) | Test whether a polygon (P) is completely inside a second polygon (Q).
Args:
P (numpy.array): (n x 2) The vertex coordinates for the first polygon
((x, y) by rows).
Q (numpy.array): (m x 2) The vertex coordinates for the second polygon
((x, y) by rows).
Returns:
bool | 625941c901c39578d7e74ebe |
def __init__(self): <NEW_LINE> <INDENT> super(XacmlContextBase, self).__init__() <NEW_LINE> if self.__class__.ELEMENT_LOCAL_NAME is None: <NEW_LINE> <INDENT> raise NotImplementedError('Set "ELEMENT_LOCAL_NAME" in a derived ' 'type') | ELEMENT_LOCAL_NAME check makes this class virtual - derived classes
must override this method and set ELEMENT_LOCAL_NAME to the appropriate
string | 625941c9d4950a0f3b08c3d3 |
def canFinish(self, numCourses, prerequisites): <NEW_LINE> <INDENT> d = dict() <NEW_LINE> for p in prerequisites: <NEW_LINE> <INDENT> if p[0] in d: <NEW_LINE> <INDENT> d[p[0]].append(p[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d[p[0]] = [p[1]] <NEW_LINE> <DEDENT> <DEDENT> if len(d) == 0: return True <NEW_LINE> ... | :type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool | 625941c95fc7496912cc3a01 |
def get_horizontal_vertical(self, image_folder, degrees=True): <NEW_LINE> <INDENT> splitted = key.replace('(', ')').split(')') <NEW_LINE> if len(splitted) == 3: <NEW_LINE> <INDENT> horizontal, vertical = splitted[1].replace(' ', '').split(',') <NEW_LINE> horizontal = int(horizontal) <NEW_LINE> vertical = int(vertical) ... | Tries to return the horizontal and vertical for an image folder.
image_folder
degrees If true, return in degrees | 625941c907f4c71912b11505 |
def report(*packages): <NEW_LINE> <INDENT> accepted_commands = ['python','conda'] <NEW_LINE> for package in packages: <NEW_LINE> <INDENT> loc = "not installed in this environment" <NEW_LINE> ver = "unknown" <NEW_LINE> try: <NEW_LINE> <INDENT> module = importlib.import_module(package) <NEW_LINE> loc = os.path.dirname(m... | Import and print location and version information for specified Python packages | 625941c9e1aae11d1e749d39 |
def clear_text(self, _): <NEW_LINE> <INDENT> assert self.textarea is not None, 'textarea not set before use' <NEW_LINE> self.textarea.delete("1.0", END) | Clear all the text from the text widget | 625941c9f8510a7c17cf977f |
def create_configuration(self): <NEW_LINE> <INDENT> configuration = {'instance' : 'http://ci.debian.net', 'packages' : ''} <NEW_LINE> with open(self.CONFIG_PATH, 'w') as conf: <NEW_LINE> <INDENT> json.dump(configuration, conf) | Creates the default configuration file.
Parameters: none
Returns: nothing | 625941c9e64d504609d748c3 |
def put(self): <NEW_LINE> <INDENT> groups = Group.query.filter_by(service=True).all() <NEW_LINE> for item in groups: <NEW_LINE> <INDENT> item.score = 0 <NEW_LINE> <DEDENT> db.session.commit() <NEW_LINE> return api_abort(200) | 使所有队伍的分数清零
:return: | 625941c96aa9bd52df036e27 |
def newPageSaveWarning(self, file_list): <NEW_LINE> <INDENT> msg = QMessageBox() <NEW_LINE> f_list = '\n'.join(file_list) <NEW_LINE> msg.setWindowTitle("Unsaved File(s)") <NEW_LINE> msg.setIcon(msg.Warning) <NEW_LINE> msg.setText('One or more files have been modified, would you like to save?') <NEW_LINE> msg.setDetaile... | Warning message that pops up when the user has unsaved documents when attempting to click "New". | 625941c944b2445a33932119 |
def __old_state_paths( self, cjs ): <NEW_LINE> <INDENT> if cjs.job_wrapper is not None: <NEW_LINE> <INDENT> user_log = "%s/%s.condor.log" % (self.app.config.cluster_files_directory, cjs.job_wrapper.job_id) <NEW_LINE> if not os.path.exists( cjs.user_log ) and os.path.exists( user_log ): <NEW_LINE> <INDENT> cjs.output_fi... | For recovery of jobs started prior to standardizing the naming of
files in the AsychronousJobState object | 625941c98e05c05ec3eea3f7 |
def inFunction(self): <NEW_LINE> <INDENT> function = self.finder.findFunction(TEST_METHOD, 3, 0) <NEW_LINE> self.assertIsNot(None, function, 'The function should not be None when within a function body') <NEW_LINE> self.assertEquals((1,7), function, 'The function should contain the proper lines') | Test that it returns the proper lines when in a function | 625941c9eab8aa0e5d26dbdb |
def write_package_info(self, info): <NEW_LINE> <INDENT> path = wayround_i2p.utils.path.abspath(self.path) <NEW_LINE> ret = 0 <NEW_LINE> package_information_filename = wayround_i2p.utils.path.join( path, 'package_info.json') <NEW_LINE> f = None <NEW_LINE> try: <NEW_LINE> <INDENT> f = open(package_information_filename, '... | Writes given info to given building site
Raises exceptions in case of errors | 625941c9dc8b845886cb55b8 |
def draw_boxes(im, bboxes,i, is_display=True, color=None, caption="Image", wait=True): <NEW_LINE> <INDENT> im=im.copy() <NEW_LINE> bbox_list = [] <NEW_LINE> for box in bboxes: <NEW_LINE> <INDENT> if color==None: <NEW_LINE> <INDENT> if len(box)==5 or len(box)==9: <NEW_LINE> <INDENT> c=tuple(cm.jet([box[-1]])[0, 2::-1]*2... | boxes: bounding boxes | 625941c9d486a94d0b98e1c9 |
def __init__(self): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.setDaemon(True) <NEW_LINE> name = "Network" + self.getName() <NEW_LINE> self.setName(name) <NEW_LINE> self.initComplete = False <NEW_LINE> self.registered = False <NEW_LINE> self.dispersy = None <NEW_LINE> self.database_thread = None <NEW_LIN... | Called only once (unless we have multiple Sessions) by MainThread | 625941c9bde94217f3682e75 |
def city_from_id(city_id): <NEW_LINE> <INDENT> return df_city.loc[city_id] | Returns a Pandas series containing the city information for the City
identified by 'city_id'. | 625941c991f36d47f21ac575 |
def test_index_crash(self): <NEW_LINE> <INDENT> es_storage = ESCrashStorage(config=self.config) <NEW_LINE> es_storage.save_raw_and_processed( raw_crash=a_raw_crash, dumps=None, processed_crash=a_processed_crash, crash_id=a_processed_crash['uuid'] ) <NEW_LINE> ok_( self.es_client.get( index=self.config.elasticsearch.ela... | Test indexing a crash document.
| 625941c956b00c62f0f146dc |
def read_file_xml(self, filename=None): <NEW_LINE> <INDENT> if filename: <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> if self.filename == '' or not os.path.isfile(self.filename): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> self.clear_list() <NEW_LINE> count = 0 <NEW_LINE> jf_xml = etree.parse(s... | Open and read the header stuff into _header and the entries
into the entry list. If filename is not given, we use
the value set in BookFile.set_file_name() if valid. Note that we
do not care if the entries or header have been modified; that is
the job of the calling routine.
Return value is the number of record entrie... | 625941c9097d151d1a222ede |
def test_milestone_remove_error_bad_milestone(self): <NEW_LINE> <INDENT> rv, output = self.execute('milestone remove bad_milestone') <NEW_LINE> self.assertEqual(2, rv, output) <NEW_LINE> self.assertExpectedResult(output) | Tests the 'milestone remove' command in trac-admin. This particular
test tries to remove a milestone that does not exist. | 625941c93eb6a72ae02ec55f |
def has_proper_image_plot_for_filter(self, fltr): <NEW_LINE> <INDENT> return fs.is_file(self.get_proper_image_plot_filepath_for_filter(fltr)) | This function ...
:param fltr:
:return: | 625941c9a219f33f346289ee |
def prepare_base_config(host, ip_address): <NEW_LINE> <INDENT> print('Preparing base config') <NEW_LINE> work_dir = os.getcwd() <NEW_LINE> base_template = work_dir+'/templates/base_template' <NEW_LINE> tmp_file = '/tmp/' + host + '.base' <NEW_LINE> shutil.copyfile(base_template, tmp_file) <NEW_LINE> for line in fileinp... | Creates base device config from base template.
Replaces the IP_ADDR in the template with the device's IP address
:param ip_address: device management IP address
:return: base config file name | 625941c930c21e258bdfa520 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.