code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def getTreeFromPhyloxml(xml, saveToFile="default.xml", delFile=True): <NEW_LINE> <INDENT> project = Phyloxml() <NEW_LINE> fo = open(saveToFile, "w+") <NEW_LINE> fo.write(xml) <NEW_LINE> fo.close() <NEW_LINE> project.build_from_file(saveToFile) <NEW_LINE> treeList = [] <NEW_LINE> for tree in project.get_phylogeny(): <NE...
Read a phylogeny tree from a phyloxml string and return a TreeClass object or a list of TreeClass object
625941eb15baa723493c446e
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, WebCredentials): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941eb96565a6dacc8fbbf
def char_data(self,data): <NEW_LINE> <INDENT> curdict = self.content <NEW_LINE> for ie in self.elem[:-1]: <NEW_LINE> <INDENT> curdict = curdict[ie] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> data = float(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if curdict[self.elem[-1]] and not i...
Add the value of an element to the dictionary with its designation. @parameter data: value of the element @type data: string
625941eb8c3a8732951588b6
def make_linkedin_blueprint( client_id=None, client_secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): <NEW_LINE> <INDENT> linkedin_bp = OAuth2ConsumerBlueprint( "linkedin", __name__, client_id=client_id, client_secret=client_secret, s...
Make a blueprint for authenticating with LinkedIn using OAuth 2. This requires a client ID and client secret from LinkedIn. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`LINKEDIN_OAUTH_CLIENT_ID` and :envvar:`LINKEDIN_OAUTH_CL...
625941eba4f1c619b28b0522
def remove_node(self, node_name): <NEW_LINE> <INDENT> node = self.__env.get_node(name=node_name) <NEW_LINE> node.remove()
Remove node
625941eb099cdd3c635f114e
def test_jlink_hardware_breakpoint_set(self): <NEW_LINE> <INDENT> addr = 0x1337 <NEW_LINE> self.dll.JLINKARM_SetBPEx.return_value = 0 <NEW_LINE> with self.assertRaises(JLinkException): <NEW_LINE> <INDENT> self.jlink.hardware_breakpoint_set(addr) <NEW_LINE> <DEDENT> self.dll.JLINKARM_SetBPEx.return_value = 1 <NEW_LINE> ...
Tests setting a hardware breakpoint. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None``
625941ebd6c5a10208144544
def test_found(self): <NEW_LINE> <INDENT> self.mock_cache.get.return_value = "x" <NEW_LINE> assert "x" == self.get_or_add() <NEW_LINE> self.mock_cache.get.assert_called_once_with("key", "ns") <NEW_LINE> assert not self.mock_create_factory.called
An item found in cache.
625941eb15fb5d323cde100c
def _status(ui, repo, wctx, kwt, *pats, **opts): <NEW_LINE> <INDENT> if kwt: <NEW_LINE> <INDENT> return repo.status(match=scmutil.match(wctx, pats, opts), clean=True, unknown=opts.get('unknown') or opts.get('all')) <NEW_LINE> <DEDENT> if ui.configitems('keyword'): <NEW_LINE> <INDENT> raise error.Abort(_('[keyword] patt...
Bails out if [keyword] configuration is not active. Returns status of working directory.
625941eb004d5f362079a825
def retrieve_business_cat(business_cat_search, user_location_coordinates): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> business_cat_search = business_cat_search.title() <NEW_LINE> db = getdb() <NEW_LINE> c = db[0] <NEW_LINE> c.execute("SELECT * FROM business INNER JOIN coordinates ON (business.postcode = coordinates....
input: user coorindates output:
625941eb5fc7496912cc3e73
@pytest.fixture() <NEW_LINE> def dummy_request(new_session): <NEW_LINE> <INDENT> return testing.DummyRequest(dbsession=new_session)
Call a dummy request.
625941eb73bcbd0ca4b2c56b
def test_by_org(self): <NEW_LINE> <INDENT> boundary1 = factories.Boundary() <NEW_LINE> boundary2 = factories.Boundary() <NEW_LINE> self.assertEqual( list(models.Boundary.objects.by_org(boundary1.org)), [boundary1]) <NEW_LINE> self.assertEqual( list(models.Boundary.objects.by_org(boundary2.org)), [boundary2])
Test by_org filter.
625941eb4e4d5625662d48c6
def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self._logger.debug("waiting execution queue") <NEW_LINE> container = self._containers_stats_queue.get() <NEW_LINE> if container is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self._logger.info("querying statistics metrics for container %s" % con...
Execute the thread
625941eb30c21e258bdfa998
def remove_embargo_countries(apps, schema_editor): <NEW_LINE> <INDENT> country_model = apps.get_model("embargo", "Country") <NEW_LINE> db_alias = schema_editor.connection.alias <NEW_LINE> country_model.objects.using(db_alias).all().delete()
Clear all available countries.
625941eb91af0d3eaac9bf13
def getJHU(country,start=None,end=None,thresh= None): <NEW_LINE> <INDENT> dfr = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv") <NEW_LINE> dfd = pd.read_csv("https://raw.githubusercontent.com/CSSEGISand...
return Pandas Dataframe with columns 'date','confirmed','recovered','dead','new_cases','active' Function to Get Data from JHU Database on GitHub url://https://github.com/CSSEGISandData/COVID-19 country: str; Country/Region in JHU Database (see above) start: str; Start Date (MM/DD/YYYY) end: str; End Date (MM/DD/YYYY)
625941ebcc40096d61595e44
def get_config_filename_from_os_env() -> str: <NEW_LINE> <INDENT> config_filename = os.environ.get(ENVVAR_CONFIG_FILE) <NEW_LINE> if not config_filename: <NEW_LINE> <INDENT> raise AssertionError( f"OS environment did not provide the required " f"environment variable {ENVVAR_CONFIG_FILE}") <NEW_LINE> <DEDENT> return con...
Returns the config filename to use, from our operating system environment variable. (We do NOT trust the WSGI environment for this.)
625941eb56b00c62f0f14b52
def transform(self, K, copy=True): <NEW_LINE> <INDENT> check_is_fitted(self) <NEW_LINE> K = check_array(K, copy=copy, dtype=FLOAT_DTYPES) <NEW_LINE> K_pred_cols = (np.sum(K, axis=1) / self.K_fit_rows_.shape[0])[:, np.newaxis] <NEW_LINE> K -= self.K_fit_rows_ <NEW_LINE> K -= K_pred_cols <NEW_LINE> K += self.K_fit_all_ <...
Center kernel matrix. Parameters ---------- K : numpy array of shape [n_samples1, n_samples2] Kernel matrix. copy : boolean, optional, default True Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. Returns ------- K_new : numpy array of shape [n_samples1, ...
625941eb97e22403b379d491
def test_workerresource(n=100): <NEW_LINE> <INDENT> worker = doctable.WorkerResource(start=False, verbose=True) <NEW_LINE> assert(not worker.is_alive()) <NEW_LINE> worker.start() <NEW_LINE> assert(worker.is_alive()) <NEW_LINE> with pytest.raises(doctable.WorkerHasNoUserFunctionError): <NEW_LINE> <INDENT> worker.execute...
Tests ability to solve tasks when tasks take an unequal ammount of time to execute.
625941eb4f88993c3716c558
def mysql_execute(con: pymysql.connect, query: str) -> List: <NEW_LINE> <INDENT> with closing(con) as connection: <NEW_LINE> <INDENT> with connection.cursor() as cursor: <NEW_LINE> <INDENT> cursor.execute(query) <NEW_LINE> result = cursor.fetchall() <NEW_LINE> result = [x[0] for x in result] <NEW_LINE> <DEDENT> return ...
Returns the result for a query in mysql.
625941ebeab8aa0e5d26e04f
def __init__(self, cred, debug): <NEW_LINE> <INDENT> self.logger = logger.SecureTeaLogger( self.modulename, debug ) <NEW_LINE> self.enabled = common.check_config(cred) <NEW_LINE> if not self.enabled: <NEW_LINE> <INDENT> self.logger.log( "Credentials not present, please set Slack config at ~/.securetea/securetea.conf ",...
Init logger params. Args: modulename (str): Script module name cred (dict): Slack user_id, token
625941eb24f1403a92601057
def distributeCoins(self, root): <NEW_LINE> <INDENT> def dfs(root, result): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> left, right = dfs(root.left, result), dfs(root.right, result) <NEW_LINE> result[0] += abs(left) + abs(right) <NEW_LINE> return root.val + left + right - 1 <NEW_LI...
:type root: TreeNode :rtype: int
625941ebac7a0e7691ed45b8
def meta_load_omoccurrences_provinces(states_array_file): <NEW_LINE> <INDENT> with open(states_array_file, "rb") as f: <NEW_LINE> <INDENT> return pkl.load(f)
:param states_array_file: Pickle file containing a list of stateProvinces used to filter the omoccurrences table :return: str[] of states
625941ebeab8aa0e5d26e050
def get_algorithm(): <NEW_LINE> <INDENT> from Utils.UTILS_TL_drawing_default import DefaultDrawingAlgorithm <NEW_LINE> return DefaultDrawingAlgorithm()
Factory method. Return the drawing algorithm that should be used by the application.
625941eb3cc13d1c6d3c786d
@need_singularity <NEW_LINE> def test_singularity_3_singuflag(plugin, tmpdir): <NEW_LINE> <INDENT> tmpdir.mkdir("new_dir") <NEW_LINE> cmd = ["ls", "/tmp_dir"] <NEW_LINE> image = "library://sylabsed/linux/alpine" <NEW_LINE> shingu = SingularityTask( name="singu", executable=cmd, container_info=("singularity", image), ca...
a simple command in container with bindings, creating directory in tmp dir and checking if it is in the container using ShellComandTask with container_info=("singularity", image)
625941eb07d97122c4178d8d
def _finish_init(self, client, entities, input_chat): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._sender = entities.get(self._sender_id) <NEW_LINE> if self._sender: <NEW_LINE> <INDENT> self._input_sender = utils.get_input_peer(self._sender) <NEW_LINE> if not getattr(self._input_sender, 'access_hash', Tru...
Finishes the initialization of this message by setting the client that sent the message and making use of the known entities.
625941eb26238365f5f0f36b
def _try_run_command(self, *cmd): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process = self._run(*cmd) <NEW_LINE> <DEDENT> except (PermissionError, FileNotFoundError) as e: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return process.returncode == 0
Tries to run a command to completion: if no exception happens and the return code is zero, returns True. Otherwise, False.
625941eb24f1403a92601058
def test_wpa2_ocv_ap_override_eapol_m3_post_enable(dev, apdev): <NEW_LINE> <INDENT> run_wpa2_ocv_ap_override_eapol_m3(dev, apdev, True)
OCV on 2.4 GHz and AP override EAPOL-Key msg 3/4 (post enable)
625941eb656771135c3ebd6b
def get_first_found(file_list): <NEW_LINE> <INDENT> for f in file_list: <NEW_LINE> <INDENT> if os.path.exists(f): <NEW_LINE> <INDENT> return f <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return find_file(file_list[1:])
Find a list of files, given in the order of descending priorities, until one is found. Parameters ---------- file_list : list of str List of files given in descending order. Returns ------- f : str or `None` First file found in the given list. Returns `None` if none found.
625941ebfbf16365ca6f66c4
def generate_db_string(db_config): <NEW_LINE> <INDENT> user = db_config.get("user") <NEW_LINE> if db_config.get("password"): <NEW_LINE> <INDENT> user = user + ":" + config.get("password") <NEW_LINE> <DEDENT> db_string = "postgresql://{}@{}:{}/{}".format( user, db_config.get("host"), db_config.get("port"), db_config.get...
Build a database connection string starting from a config file Parameters ---------- db_config : dict Database connexion parameters Returns ------- str Database connexion string
625941eb5e10d32532c5f41b
def test_required(self): <NEW_LINE> <INDENT> schema = DjangoConfigurationSchema() <NEW_LINE> raw_settings = {} <NEW_LINE> with self.assertRaises(colander.Invalid): <NEW_LINE> <INDENT> schema.deserialize(raw_settings) <NEW_LINE> <DEDENT> raw_settings = { 'DATABASES': {}, 'INSTALLED_APPS': [], 'ROOT_URLCONF': 'fake.urls'...
Minimal settings for Django 1.5.
625941ebd18da76e235329d2
def cluster_ensembles_MCLAONLY(cluster_runs, hdf5_file_name=None, verbose=False, N_clusters_max=None, weighted=False, clustering_weights=None, cluster_level_weights=None, alpha=1): <NEW_LINE> <INDENT> if hdf5_file_name is None: <NEW_LINE> <INDENT> hdf5_file_name = './Cluster_Ensembles.h5' <NEW_LINE> <DEDENT> fileh = ta...
Call up to three different functions for heuristic ensemble clustering (namely CSPA, HGPA and MCLA) then select as the definitive consensus clustering the one with the highest average mutual information score between its vector of consensus labels and the vectors of labels associated to each partition from ...
625941eb097d151d1a22334d
def saveresults(good_proxies): <NEW_LINE> <INDENT> with open("elite_result.csv", 'w') as result_file: <NEW_LINE> <INDENT> result_file.write('PROXY,LEVEL,TIME,HEADERS\n') <NEW_LINE> for aproxy in good_proxies: <NEW_LINE> <INDENT> if aproxy.level == "Elite": <NEW_LINE> <INDENT> result_file.write(aproxy.ip_port + "," + ap...
save results to file
625941eb9c8ee82313fbbc6d
def invert_dict(d): <NEW_LINE> <INDENT> return dict((v,k) for k,v in d.items())
invert a dict key -> value, value -> key
625941eb1d351010ab856011
def test_backfilling_failling_midway(self): <NEW_LINE> <INDENT> config_manager, json_file = self._setup_config_manager( 'socorro.unittest.cron.test_crontabber' '.CertainDayHaterBackfillJob|1d' ) <NEW_LINE> with config_manager.context() as config: <NEW_LINE> <INDENT> tab = crontabber.CronTabber(config) <NEW_LINE> tab.ru...
this test simulates when you have something like this: Monday: Success Tuesday: Failure Wednesday: Failure Thursday: today! When encountering this on the Thursday it will run (in order): Tuesday, Wednesday, Thursday Suppose then that something goes wrong on the Wednesday. Then, if so, we don't w...
625941ebf9cc0f698b140aed
def get_path(ref_node): <NEW_LINE> <INDENT> return cmds.referenceQuery(ref_node, filename=True)
Get a reference nodes path
625941ebdc8b845886cb5a2d
def preprocess_reminder(text): <NEW_LINE> <INDENT> return _reminder_text.sub(_reminder_chop, text).strip()
Chop out reminder text during the preprocessing step. While this isn't strictly necessary because we can ignore reminder text via an ignore token, it is useful to do during preprocessing so that searching cards for text won't match reminder text.
625941ebd486a94d0b98e63d
def post_async_relative_retry_invalid_json_polling( self, product=None, custom_headers={}, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/lro/error/postasync/retry/invalidjsonpolling' <NEW_LINE> query_parameters = {} <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Content-Type'] = 'applicat...
Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status :param product: Product to put :type product: :class:`Product <fixtures.acceptancetestslro.models.Prod...
625941eb0a366e3fb873ed15
def cell_is_game_over(self, y, x): <NEW_LINE> <INDENT> if self.grid_data[y][x] == self.WATER_SYMBOL: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for i in range(y, -1, -1): <NEW_LINE> <INDENT> if self.grid_data[i][x] == self.ANTI_TANK_DOWN_SYMBOL: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.cell_...
Check if the cell with the given coordinates will result in game over. :param y: y coord :param x: x coord :return: True if blocked, False otherwise
625941ebe1aae11d1e74a1b2
def increase_speed(self): <NEW_LINE> <INDENT> self.ship_speed_factor *= self.speedup_scale <NEW_LINE> self.bullet_speed_factor *= self.speedup_scale <NEW_LINE> self.alien_speed_factor *= self.speedup_scale <NEW_LINE> self.alien_points = int(self.alien_points * self.score_scale)
"Increase speed settings and alien point values.
625941eb566aa707497f4a58
def FocalMechanismReference_ConstCast(*args): <NEW_LINE> <INDENT> return _DataModel.FocalMechanismReference_ConstCast(*args)
ConstCast(BaseObject o) -> FocalMechanismReference FocalMechanismReference_ConstCast(Seiscomp::Core::BaseObjectCPtr o) -> FocalMechanismReference
625941eb55399d3f05588bae
def make_declarative_base(self, metadata=None): <NEW_LINE> <INDENT> base = declarative_base(cls=Model, name='Model', metadata=metadata, metaclass=_BoundDeclarativeMeta) <NEW_LINE> base.query = _QueryProperty(self) <NEW_LINE> return base
Creates the declarative base.
625941eb3539df3088e2e842
def getImplementationType(self): <NEW_LINE> <INDENT> return self._get_impl_type()
@rtype: ErtImplType
625941eb1b99ca400220afaa
def on_connect(client, userdata, flags, rc): <NEW_LINE> <INDENT> del userdata, flags <NEW_LINE> if rc == 0: <NEW_LINE> <INDENT> client.is_connected = True <NEW_LINE> client.subscribe("hermes/asr/stopListening") <NEW_LINE> client.subscribe("hermes/asr/startListening")
MQTT Client connect callback. This is invoked when the MQTT client connects to the server. It then subscribes to the interesting intents
625941eb8e05c05ec3eea86f
def search_plan(sym, ntrial=6, type_dict=None, **kwargs): <NEW_LINE> <INDENT> history = [] <NEW_LINE> threshold = 0 <NEW_LINE> min_threshold = None <NEW_LINE> min_cost = None <NEW_LINE> nbegin = 3 <NEW_LINE> for k in range(nbegin): <NEW_LINE> <INDENT> info = {} <NEW_LINE> sym = make_mirror_plan(sym, threshold=threshold...
Quickly heurestic search over possible plans to find good memory plan. Parameters ---------- sym : symbolic Symbolic configurations ntrial: integer Additional grid search steps
625941eb38b623060ff0b2e3
def parse_arguments(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Repair a TSV file') <NEW_LINE> parser.add_argument('--input-filename', type=str, required=True, help='input TSV file to repair') <NEW_LINE> parser.add_argument('--output-filename', type=str, required=True, help='output file where t...
Parse script input arguments
625941eb925a0f43d254a372
def setKeyringCredential(service_name, user, passwd): <NEW_LINE> <INDENT> logging.info("Set credentials in service %s for %s", service_name, user) <NEW_LINE> keyring.set_password(service_name,"ID", user) <NEW_LINE> keyring.set_password(service_name, user, passwd)
Set username and password under well-known entry in keyring Set username and password in well-known location that is user independent. service_name: ID = user service_name: user = passwd In this way the username to use for the service can always be retrieved, otherwise it would be necessary to always request...
625941ebf7d966606f6aa500
def refresh(self): <NEW_LINE> <INDENT> self.varsVar.set('') <NEW_LINE> self.cBoxVars['menu'].delete(0, 'end') <NEW_LINE> new_choices = self.parent.getCustomvarsString() <NEW_LINE> for choice in new_choices: <NEW_LINE> <INDENT> self.cBoxVars['menu'].add_command(label=choice, command=tk._setit(self.varsVar, choice))
Refesh some controls Don't invoke this method manually
625941ebd8ef3951e3243a34
def string(self): <NEW_LINE> <INDENT> return utils.lib.zdigest_string(self._p)
Return digest as printable hex string; caller should not modify nor free this string. After calling this, you may not use zdigest_update() on the same digest. If built without crypto support, returns NULL.
625941eb4e4d5625662d48c7
def calculateHandlen(hand): <NEW_LINE> <INDENT> sumValue = 0 <NEW_LINE> for value in hand.values(): <NEW_LINE> <INDENT> sumValue += value <NEW_LINE> <DEDENT> return sumValue
Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer
625941ebb545ff76a891430c
def __init__( self, *, vm_agent_version: Optional[str] = None, extension_handlers: Optional[List["VirtualMachineExtensionHandlerInstanceView"]] = None, statuses: Optional[List["InstanceViewStatus"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(VirtualMachineAgentInstanceView, self).__init__(**kwargs) <NEW_LINE> self.v...
:keyword vm_agent_version: The VM Agent full version. :paramtype vm_agent_version: str :keyword extension_handlers: The virtual machine extension handler instance view. :paramtype extension_handlers: list[~azure.mgmt.compute.v2019_12_01.models.VirtualMachineExtensionHandlerInstanceView] :keyword statuses: The resource...
625941eb31939e2706e4d359
def set_ClientSecret(self, value): <NEW_LINE> <INDENT> super(AddListRowsInputSet, self)._set_input('ClientSecret', value)
Set the value of the ClientSecret input for this Choreo. ((optional, string) The Client Secret provided by Google. Required when authenticating with OAuth unless providing a valid AccessToken.)
625941ebad47b63b2c50a475
def install_apache_config(self): <NEW_LINE> <INDENT> confdir = join(self.apache_base_path, 'conf.d') <NEW_LINE> if not exists(confdir): <NEW_LINE> <INDENT> os.mkdir(confdir) <NEW_LINE> default_httpd_conf_path = join(self.apache_base_path, 'conf', 'httpd.conf') <NEW_LINE> with open(default_httpd_conf_path, 'a') as fh: <...
Create and install an Apache HTTPD configuration stub file. This tells the web server how to run the web apps.
625941ebd10714528d6001df
def skip_format_url(format, url): <NEW_LINE> <INDENT> if '' == format: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if ('mailto:' in url) and ('@' in url): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if RE_VALID_FORMATS.match(format): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if RE_NON_SIMPLE_...
Checks whether a give format/url should be skipped and not downloaded. @param format: Filename format (extension). @type format: str (e.g. html, txt, zip, pdf) @param url: URL. @type url: str @return: True if format/url should be skipped, False otherwise. @rtype bool
625941eb498bea3a759b9fa4
def __init__(self, suit: Suit, number: Number): <NEW_LINE> <INDENT> self.suit = suit <NEW_LINE> self.number = number <NEW_LINE> if self.suit in Simples: <NEW_LINE> <INDENT> self.number = int(number) <NEW_LINE> <DEDENT> elif self.suit == Honors.FENG: <NEW_LINE> <INDENT> self.number = Wind(number) <NEW_LINE> <DEDENT> eli...
Initialize Tile.
625941eb99fddb7c1c9de885
def parseargs(p): <NEW_LINE> <INDENT> p.set_defaults(func=func) <NEW_LINE> p.description = "Print newline, word, and byte counts for each file" <NEW_LINE> p.epilog = ( "If the FILE ends with '.bz2' or '.gz', the file will be " + "decompressed automatically." ) <NEW_LINE> p.add_argument('FILE', nargs='*') <NEW_LINE> p.a...
Add arguments and `func` to `p`. :param p: ArgumentParser :return: ArgumentParser
625941eb2ae34c7f2600d627
def to_categorical(y, num_classes): <NEW_LINE> <INDENT> y = np.array(y, dtype="int") <NEW_LINE> n = y.shape[0] <NEW_LINE> categorical = np.zeros((n, num_classes)) <NEW_LINE> categorical[np.arange(n), y] = 1 <NEW_LINE> categorical = categorical.astype(np.float32) <NEW_LINE> return categorical
Converts a class vector (integers) to binary class matrix. Args y: class vector to be converted into a matrix (integers from 0 to num_classes). num_classes: total number of classes. Return A binary matrix representation of the input.
625941ebe8904600ed9f242c
def SetMaxSize(size: int) -> None: <NEW_LINE> <INDENT> MAX_SIZE = size
Set the maximum size a sentence can be before becoming a blob
625941eb3317a56b8693a142
def run(self): <NEW_LINE> <INDENT> self._list_flavors() <NEW_LINE> self._list_flavors_as_admin()
List flavors.
625941ebadb09d7d5db6cc83
def __init__(self, name): <NEW_LINE> <INDENT> global level <NEW_LINE> logging.Logger.__init__(self, name, level) <NEW_LINE> color_formatter = ColoredFormatter(self.COLOR_FORMAT) <NEW_LINE> console = logging.StreamHandler() <NEW_LINE> console.setFormatter(color_formatter) <NEW_LINE> self.addHandler(console) <NEW_LINE> f...
Constructor for the ColoredLogger class. @param name: name of the Logger. @type name: str
625941ebb830903b967e9dfc
def __init__( self, initial_learning_rate, first_decay_steps, t_mul=2.0, m_mul=1.0, alpha=0.0, name=None): <NEW_LINE> <INDENT> super(CosineDecayRestarts, self).__init__() <NEW_LINE> self.initial_learning_rate = initial_learning_rate <NEW_LINE> self.first_decay_steps = first_decay_steps <NEW_LINE> self._t_mul = t_mul <N...
Applies cosine decay with restarts to the learning rate. Args: initial_learning_rate: A scalar `float32` or `float64` Tensor or a Python number. The initial learning rate. first_decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. Number of steps to decay over. t_mul: A scalar `float32` ...
625941eb0a50d4780f66738d
def isValid(self, s): <NEW_LINE> <INDENT> corr = {')':'(','}':'{',']':'['} <NEW_LINE> que = list() <NEW_LINE> for c in s: <NEW_LINE> <INDENT> if c in corr.keys() and len(que)>0 and que[-1] == corr[c]: <NEW_LINE> <INDENT> que.pop() <NEW_LINE> <DEDENT> elif c in corr.keys(): <NEW_LINE> <INDENT> return False <NEW_LINE> <D...
:type s: str :rtype: bool
625941eb460517430c39466e
def jac_weight_b_j(self, j): <NEW_LINE> <INDENT> if isinstance(j, int) or isinstance(j, np.int32) or isinstance(j, np.int64): <NEW_LINE> <INDENT> j = [j] <NEW_LINE> <DEDENT> scale = self.scale_j(j=j) <NEW_LINE> loc = self.location_j(j=j) <NEW_LINE> if isinstance(self.x, scipy.sparse.csr_matrix): <NEW_LINE> <INDENT> sca...
:return: observations x features
625941eb099cdd3c635f114f
def set_image(self, image): <NEW_LINE> <INDENT> super().set_image(image) <NEW_LINE> self._reset_catalogs() <NEW_LINE> self._file_name = None <NEW_LINE> if self._tmp_file is not None: <NEW_LINE> <INDENT> self._tmp_file.close() <NEW_LINE> <DEDENT> if image is None: <NEW_LINE> <INDENT> self._tmp_file = None <NEW_LINE> ret...
Set image to be used for source finding. Parameters ---------- image: numpy.ndarray, str When setting an image either a `numpy.ndarray` of image data or a string file name is acceptable. Image file name may be followed by an extension specification such as ``'file1.fits[1]'`` or ``'file1.fits[(sci,1)]'...
625941ebac7a0e7691ed45b9
def get_dev_uuid(dev, peer=None): <NEW_LINE> <INDENT> out = get_dev_info(dev, "UUID", peer=peer).splitlines() <NEW_LINE> return out[0] if out else get_dev_uuid_2(dev, peer)
Get UUID of device on local or peer node
625941eb596a897236089fb0
def get_M(self): <NEW_LINE> <INDENT> return self.get_par('MORB')
Get number of orbitals.
625941eb507cdc57c63071dd
def get_previous( all_decks: Iterable, current: DeckId, constraint_check: Callable ) -> Optional[DeckTreeNode]: <NEW_LINE> <INDENT> last = None <NEW_LINE> for deck in all_decks: <NEW_LINE> <INDENT> if deck.id == current: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if constraint_check(deck.id, current) and visible(dec...
Get the last element before `current` that fulfills the constraint.
625941eba79ad161976cc63c
def daemonize(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pid = os.fork() <NEW_LINE> if pid > 0: <NEW_LINE> <INDENT> sys.exit(0) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> print("First fork failed: %d (%s)\n" % (e.errno, e.strerror), file=sys.stderr) <NEW_LINE> sys.exit(1) <NEW_LINE> <DED...
Do the UNIX double-fork magic for properly detaching process
625941ebbaa26c4b54cb1611
def pairwise_comparison_winner(election): <NEW_LINE> <INDENT> data = [(candidate, pairwise_score(candidate, election)) for candidate in candidates(election)] <NEW_LINE> return determine_winner(data)
Give the winner of the election using pairwise comparisons.
625941ebf8510a7c17cf9bf7
def _expire_url_caches(self): <NEW_LINE> <INDENT> cachekeys = [ 'fluent_pages.instance_of.{0}.{1}'.format(self.__class__.__name__, self.parent_site_id), ] <NEW_LINE> for cachekey in cachekeys: <NEW_LINE> <INDENT> cache.delete(cachekey)
Reset all cache keys related to this model.
625941eb4428ac0f6e5bacee
def filter_list_query(self, query): <NEW_LINE> <INDENT> if not self.filtering: <NEW_LINE> <INDENT> return query <NEW_LINE> <DEDENT> return self.filtering.filter_query(query, self)
Apply filtering as specified to the provided `query`. :param: A SQL query :type: :py:class:`sqlalchemy.orm.query.Query` :return: The filtered query :rtype: :py:class:`sqlalchemy.orm.query.Query`
625941eb8e05c05ec3eea870
def __reduce__(self): <NEW_LINE> <INDENT> return self._factory_data[0].reduce_data(self)
For pickling. EXAMPLES:: sage: k.<b> = FiniteField(5^20, impl='pari_ffelt') sage: type(k) <class 'sage.rings.finite_rings.finite_field_pari_ffelt.FiniteField_pari_ffelt_with_category'> sage: k is loads(dumps(k)) True
625941eb30bbd722463cc2c0
def get_paths(self): <NEW_LINE> <INDENT> if self.dataset == 'training': <NEW_LINE> <INDENT> file = 'trainset.txt' <NEW_LINE> <DEDENT> elif self.dataset == 'validation': <NEW_LINE> <INDENT> file = 'valset.txt' <NEW_LINE> <DEDENT> elif self.dataset == 'test': <NEW_LINE> <INDENT> file = 'testset.txt' <NEW_LINE> <DEDENT> e...
Load the absolute paths to the files that are in the dataset. Returns: list of tuples of str: Each tuple containing the class' name, the path to the image and the path to its bounding boxes. Example: ('google', '/datasets/flickr32/classes/jpg/google/2240784196.jpg', '/data...
625941eb7047854f462a18fb
def sequence_capture(self): <NEW_LINE> <INDENT> self.sequence_order() <NEW_LINE> server = "http://grch37.rest.ensembl.org" <NEW_LINE> ext = "/sequence/region/human/" + str(self.chr) + ":" + str(self.start) + ".." + str(self.end) + ":1?" <NEW_LINE> r = requests.get(server+ext, headers={ "Content-Type" : "text/plain"}) <...
Capture sequences from Ensembl between two bases (the start and end positions of the cDNA, inclusive)
625941eb8a43f66fc4b54557
def build_string_list_from_fields(record, tag, subfields, punctuation=',', spaced_punctuation=':;/-', tag_grouping=[]): <NEW_LINE> <INDENT> fields = record.get_fields(tag) <NEW_LINE> field_string_list = [] <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> grouping_data = [] <NEW_LINE> grouping_code = [] <NEW_LINE> fo...
Build a list of strings (one per field). from the given field tag and given subfields. the given separator is used as subfields delimiter.
625941eb15baa723493c4470
def test_get_main_page_without_logged_in_user(self): <NEW_LINE> <INDENT> response = self.testapp.get('/') <NEW_LINE> self.assertEqual(response.status_int, 200)
Test a GET / and check a 200 status
625941ebcc40096d61595e45
def it_can_disable_coloring(self): <NEW_LINE> <INDENT> pass
Users should be able to turn off colored output. V3
625941eb7c178a314d6ef95f
def get_available_actions(node: extensive_game.ExtensiveGameNode): <NEW_LINE> <INDENT> return [a for a in node.children.keys()]
Returns the actions available to the player to play.
625941eb293b9510aa2c3788
def tearDown(self): <NEW_LINE> <INDENT> self.delete_project_folders()
Reset the database when test is done.
625941ebdc8b845886cb5a2e
def update_linear_regression(self, linear_regression, changes): <NEW_LINE> <INDENT> check_resource_type(linear_regression, LINEAR_REGRESSION_PATH, message="A linear regression id is needed.") <NEW_LINE> linear_regression_id = get_linear_regression_id( linear_regression) <NEW_LINE> if linear_regression_id: <NEW_LINE> <I...
Updates a linear regression.
625941eb29b78933be1e5b9d
def check_state(self, state): <NEW_LINE> <INDENT> if isinstance(state, collections.Iterable) and len(state) == 2: <NEW_LINE> <INDENT> if state[0] < 0 or state[1] < 0 or state[0] >= self._size[0] or state[1] >= self._size[1]: <NEW_LINE> <INDENT> return 'N' <NEW_LINE> <DEDENT> return self._map[tuple(state)] <NEW_LINE> <D...
检查状态是否符合规范,如果当前state超出了范围就不行,如果可以就取出当前状态对应的标记 N表示未知的state,表明超出了范围,F表示错误的state
625941ebe76e3b2f99f3acfa
def boxFilter(im, radius): <NEW_LINE> <INDENT> height, width = len(im), len(im[0]) <NEW_LINE> imDst = [] <NEW_LINE> imCum = [] <NEW_LINE> for x in range(height): <NEW_LINE> <INDENT> imDst.append([0.0] * width) <NEW_LINE> imCum.append([0.0] * width) <NEW_LINE> <DEDENT> for i in range(width): <NEW_LINE> <INDENT> for j in...
box filter for the image of the radius
625941eb91f36d47f21ac9ef
def _declare(self): <NEW_LINE> <INDENT> self._declare_variable('h_i') <NEW_LINE> self._declare_argument('h', indices=[0])
owned variable: h_i (initial altitude point) dependencies: h (altitude points)
625941eb15baa723493c4471
def load_data(city, month, day): <NEW_LINE> <INDENT> df = pd.read_csv(CITY_DATA[city]) <NEW_LINE> df['Start Time'] = pd.to_datetime(df['Start Time']) <NEW_LINE> df['month'] = df['Start Time'].dt.month_name() <NEW_LINE> df['day_of_week'] = df['Start Time'].dt.weekday_name <NEW_LINE> if month != 'all': <NEW_LINE> <INDENT...
Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pa...
625941eb596a897236089fb1
def kill_other_or_sys_exit(xpid, hname=r'hubble', ksig=signal.SIGTERM, kill_other=True, no_pgrp=True): <NEW_LINE> <INDENT> if no_pgrp is True: <NEW_LINE> <INDENT> no_pgrp = os.getpgrp() <NEW_LINE> <DEDENT> if isinstance(no_pgrp, int): <NEW_LINE> <INDENT> no_pgrp = str(no_pgrp) <NEW_LINE> <DEDENT> if os.path.isdir("/pro...
Attempt to locate other hubbles using a cmdline regular expression and kill them when found. If killing the other processes fails (or kill_other is False), sys.exit instead. params: hname :- the regular expression pattern to use to locate hubble (default: hubble) ksig :- the signal to use to kill the ot...
625941eb50812a4eaa59c814
def on_display_signatures(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(self, view, *args, **kwargs): <NEW_LINE> <INDENT> if get_settings(view, 'display_signatures', False): <NEW_LINE> <INDENT> return func(self, view, *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return wrapper
Execute the given function if display signatures is enabled
625941eb956e5f7376d71363
def playWave(sound='horse', pitch=1, amplitude=1, loop=False, duration=1, starttime=0, pitch_envelope='default', amplitude_envelope='default'): <NEW_LINE> <INDENT> if '/' in sound: <NEW_LINE> <INDENT> fullname = sound <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fullname = finddir() + str(sound) <NEW_LINE> <DEDENT> if...
Play a wave file (sound = ['horse'], pitch = [1], amplitude = [1], loop = [False], duration = [1], starttime = [0], pitch_envelope=['default'], amplitude_envelope=['default'])
625941eb99cbb53fe67930dc
def encodePayload(self): <NEW_LINE> <INDENT> output = b'' <NEW_LINE> for val in self.payload: <NEW_LINE> <INDENT> output += pack('>B',val) <NEW_LINE> <DEDENT> return output
output the payload, encoded in NBT format
625941eb8e71fb1e9831dc9e
def isLongPressedName(self, name, typed): <NEW_LINE> <INDENT> if name[0] != typed[0]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> t_l = len(typed) <NEW_LINE> t_j = 0 <NEW_LINE> t_p = name[0] <NEW_LINE> for i in name: <NEW_LINE> <INDENT> if t_j >= t_l: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if i =...
:type name: str :type typed: str :rtype: bool
625941eb167d2b6e3121908c
def tag_id(self): <NEW_LINE> <INDENT> return _gnsdk.GnAlbum_tag_id(self)
tag_id(GnAlbum self) -> gnsdk_cstr_t
625941eb8a349b6b435e866a
def test_conditional_1bit(self): <NEW_LINE> <INDENT> shots = 100 <NEW_LINE> circuits = ref_conditionals.conditional_circuits_1bit(final_measure=True) <NEW_LINE> qobj = qiskit_compile(circuits, QasmSimulator(), shots=shots) <NEW_LINE> targets = ref_conditionals.conditional_counts_1bit(shots) <NEW_LINE> job = QasmSimulat...
Test conditional operations on 1-bit conditional register.
625941eb8c0ade5d55d3eeb7
def update_movie(self, param_num: str, new_param_val: Union[str, int]) -> None: <NEW_LINE> <INDENT> if param_num == 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if param_num == '1': <NEW_LINE> <INDENT> self.movie.title = new_param_val <NEW_LINE> self._options[param_num] = 'Title: ' + new_param_val <NEW_LINE> <DEDENT...
Update LibraryDB_Movie parameter. :param str param_num: Number of parameter to be updated :param Union[str, int] new_param_val: New value of the parameter :return None: Nothing
625941eb0c0af96317bb86df
def getClosestSubValue(self, itemList): <NEW_LINE> <INDENT> return None
Get the closest relevant subvalue through a list of subitems, itemList = the path of the value to get the closest value for
625941ebc4546d3d9de72f30
def generate_sparse_spd_matrix(dim=1, alpha=0.95, prng=np.random): <NEW_LINE> <INDENT> chol = -np.eye(dim) <NEW_LINE> aux = prng.rand(dim, dim) <NEW_LINE> aux[aux<alpha] = 0 <NEW_LINE> aux[aux>alpha] = .9*prng.rand(np.sum(aux>alpha)) <NEW_LINE> aux = np.tril(aux, k=-1) <NEW_LINE> permutation = prng.permutation(dim) <NE...
generate a sparse symetric definite positive matrix with the given dimension Returns ------- prec: array of shape(dim,dim)
625941eb4a966d76dd55150c
def get(self): <NEW_LINE> <INDENT> pushes = query.open_pushes() <NEW_LINE> response = {'pushes': [push.json for push in pushes]} <NEW_LINE> self.response.out.write(json.dumps(response))
List pushes
625941eb6fece00bbac2dc3c
def rsa_signer(message): <NEW_LINE> <INDENT> with open(KEY_FILE, "rb") as key_file: <NEW_LINE> <INDENT> private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend() ) <NEW_LINE> return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1())
Signs a message with the key file. :param message: The message to be signed.
625941ebde87d2750b860290
def test_no_match(self): <NEW_LINE> <INDENT> user = UserFactory() <NEW_LINE> course = CourseFactory() <NEW_LINE> GeneratedCertificate( user=user, course_id=course.location.course_key, status=CertificateStatuses.downloadable ).save() <NEW_LINE> self.assertFalse(user.badgeassertion_set.all())
Make sure a badge isn't created before a user's completed any course groups.
625941eb26068e7796caf1de
def _ServerIsRunning( self ): <NEW_LINE> <INDENT> return ( self._omnisharp_port != None and self._GetResponse( '/checkalivestatus', silent=True ) != None )
Check if our OmniSharp server is running
625941eba17c0f6771cbe547
def ratio(matrix, objectives, weights): <NEW_LINE> <INDENT> objective_x_weights = weights * objectives <NEW_LINE> rank_mtx = np.inner(matrix, objective_x_weights) <NEW_LINE> score = np.squeeze(np.asarray(rank_mtx)) <NEW_LINE> return rank.rank_values(score, reverse=True), score
Execute ratio MOORA without any validation.
625941eb7b25080760e3994d
def to_array(self, prefer_original=False): <NEW_LINE> <INDENT> if prefer_original and self._raw: <NEW_LINE> <INDENT> return self._raw <NEW_LINE> <DEDENT> from ..receivable.media import MessageEntity <NEW_LINE> from .reply_markup import InlineKeyboardMarkup <NEW_LINE> array = super(InlineQueryResultCachedVoice, self).to...
Serializes this InlineQueryResultCachedVoice to a dictionary. :param prefer_original: If we should return the data this was constructed with if available. If it's not available, it will be constructed normally from the data of the object. :type prefer_original: bool :return: dictionary representation of this object....
625941eb6aa9bd52df03729f
def get(self): <NEW_LINE> <INDENT> xmpp_configured = True <NEW_LINE> values = { 'xmpp_configured': xmpp_configured, 'request': self.request } <NEW_LINE> self.generate('xmpp.html', values)
Shows template displaying the XMPP.
625941ebbaa26c4b54cb1612
def get_result_darray(self, model_run_name, model_name, output_name, timesteps=None, decision_iterations=None, time_decision_tuples=None): <NEW_LINE> <INDENT> available = self.available_results(model_run_name) <NEW_LINE> if not timesteps and not decision_iterations and not time_decision_tuples: <NEW_LINE> <INDENT> list...
Return data for multiple timesteps and decision iterations for a given output from a given sector model in a specific model run. You can specify either: a list of (timestep, decision) tuples in which case data for all of those tuples matching the available results will be returned or: a list of...
625941eb26068e7796caf1df