code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get(model_name, inputs, config, checkpoint_dir, is_training=False): <NEW_LINE> <INDENT> return globals()[model_name](inputs, config, checkpoint_dir, is_training)
Returns a Model instance instance by model name. Args: name: class name of the model to instantiate. samples: samples as returned by a DataPipeline. params: dict of model parameters.
625941d9d486a94d0b98e3e0
def set_mutual_compatibility(self, p_i_side, p_j, p_j_side, compatibility): <NEW_LINE> <INDENT> p_j_side_val = InterPieceDistance.get_p_j_side_index(self._puzzle_type, p_j_side) <NEW_LINE> self._mutual_compatibilities[p_i_side.value, p_j, p_j_side_val] = compatibility <NEW_LINE> self._mutual_compatibility_has_changed =...
Puzzle Piece Mutual Compatibility Setter Sets the mutual compatibility for a piece (p_i) to another piece p_j on their respective sides. Args: p_i_side (PuzzlePieceSide): Side of the primary piece (p_i) where p_j will be placed p_j (int): Secondary piece for the asymmetric distance. p_j_side (PuzzlePieceS...
625941d90383005118ecf87b
def coinChange2(self, coins, amount): <NEW_LINE> <INDENT> import math <NEW_LINE> changeDic = {} <NEW_LINE> changeDic[0] = [[amount,0]] <NEW_LINE> while changeDic: <NEW_LINE> <INDENT> curKey = min(changeDic.keys()) <NEW_LINE> curVal = changeDic[curKey].pop() <NEW_LINE> print(curVal) <NEW_LINE> if not changeDic[curKey]: ...
:type coins: List[int] :type amount: int :rtype: int
625941d93cc13d1c6d3c7613
@login_manager.user_loader <NEW_LINE> def load_user(user_id): <NEW_LINE> <INDENT> return models.User.query.get(int(user_id))
Flask-Login user loader
625941d9656771135c3ebb0b
def pc_nproduced_avg(self): <NEW_LINE> <INDENT> return _howto_swig.sc_fdma_interleaver_sptr_pc_nproduced_avg(self)
pc_nproduced_avg(sc_fdma_interleaver_sptr self) -> float
625941d91b99ca400220ad4c
def validate_access_parameters_for_update(body): <NEW_LINE> <INDENT> protocol_dict = deepcopy(body) <NEW_LINE> if (const.NAME not in protocol_dict.keys() and not len(protocol_dict.keys())): <NEW_LINE> <INDENT> raise webob.exc.HTTPBadRequest( _("Request must have name or one protocol type")) <NEW_LINE> <DEDENT> if const...
Validate if the request body is in proper format.
625941d9851cf427c661a7a7
def rank(self): <NEW_LINE> <INDENT> return self.ngens()-1
Return the rank of the unit group. EXAMPLES:: sage: K.<z> = CyclotomicField(13) sage: UnitGroup(K).rank() 5 sage: SUK = UnitGroup(K,S=2); SUK.rank() 6
625941d98e05c05ec3eea610
def conv_block(input_tensor, nb_filter, stage, block, kernel_size=3, strides=(2, 2, 2)): <NEW_LINE> <INDENT> dim_ordering = K.image_dim_ordering() <NEW_LINE> if dim_ordering == 'tf': <NEW_LINE> <INDENT> bn_axis = 4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bn_axis = 1 <NEW_LINE> <DEDENT> nb_filter1, nb_filter2, nb_...
conv_block indicate the block that has a conv layer at shortcut params: input_tensor: input tensor nb_filter: list of integers, the nb_filters of 3 conv layer at main path stage: integet, current stage number block: str like 'a','b'.., current block kernel_size: defualt 3, the kernel size of middle ...
625941d9d268445f265b5108
def calculate_fid_given_paths(paths, batch_size, cuda, dims): <NEW_LINE> <INDENT> for p in paths: <NEW_LINE> <INDENT> if not os.path.exists(p): <NEW_LINE> <INDENT> raise RuntimeError('Invalid path: %s' % p) <NEW_LINE> <DEDENT> <DEDENT> block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] <NEW_LINE> model = InceptionV3([blo...
Calculates the FID of two paths parser.add_argument('paths', type=str, nargs=2, help=('Path to the generated images or ' 'to .npz statistic files')) parser.add_argument('--batch-size', type=int, default=64, help='Batch size to use') parser.add_argument('--...
625941d957b8e32f52483736
def __init__(self, model, back='tf', sess=None): <NEW_LINE> <INDENT> if not(back == 'tf'): <NEW_LINE> <INDENT> raise ValueError("Backend argument must either be 'tf'.") <NEW_LINE> <DEDENT> if back == 'tf' and sess is None: <NEW_LINE> <INDENT> import tensorflow as tf <NEW_LINE> sess = tf.get_default_session() <NEW_LINE>...
:param model: An instance of the cleverhans.model.Model class. :param back: The backend to use. Currently 'tf' is the only option. :param sess: The tf session to run graphs in
625941d9236d856c2ad44a77
@pytest.fixture(scope='session') <NEW_LINE> def nginx_proxy(nginx_config): <NEW_LINE> <INDENT> import pexpect <NEW_LINE> procs = [] <NEW_LINE> def _nginx_proxy(options): <NEW_LINE> <INDENT> port = available_port() <NEW_LINE> proxy_config = nginx_config(port, options) <NEW_LINE> try: <NEW_LINE> <INDENT> proc = run_pexpe...
Runs an nginx rate liming proxy, limiting download speeds to 70 KB/s. HTTP requests are forwarded to port 8080 (default port of the docker hawkBit instance). Returns the port the proxy is running on. This port can be set in the rauc-hawkbit-updater config to rate limit its HTTP requests.
625941d9bd1bec0571d908c8
def close(self): <NEW_LINE> <INDENT> if self.processes_started: <NEW_LINE> <INDENT> for _ in range(self.num_consumers): <NEW_LINE> <INDENT> self.tasks.put(None) <NEW_LINE> <DEDENT> self.tasks.join() <NEW_LINE> self.processes_started = False
Join and close processes
625941d9cdde0d52a9e532cf
def naked_twins(values): <NEW_LINE> <INDENT> unsolved = [box for box in values.keys() if len(values[box]) == 2] <NEW_LINE> twins = [[twin1, twin2] for twin1 in unsolved for twin2 in peers[twin1] if values[twin1] == values[twin2]] <NEW_LINE> if len(twins) > 0: <NEW_LINE> <INDENT> fo...
Eliminate values using the naked twins strategy. Args: values(dict): a dictionary of the form {'box_name': '123456789', ...} Returns: the values dictionary with the naked twins eliminated from peers.
625941d9627d3e7fe0d690eb
def match(self, cloud, params): <NEW_LINE> <INDENT> dir_path = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> path = Path(dir_path) <NEW_LINE> f = open(str(path.parent) + os.sep + 'Policies/User_Source_IP_Restrictions.json') <NEW_LINE> ref_data = f.read() <NEW_LINE> ref_json = json.loads(ref_data) <NEW_LINE> re...
A function to determine equality between the reference policy and the version in the target. :param cloud: The policy retrieved from the target :param params: The configurable params for the target. :return: A boolean.
625941d901c39578d7e750d5
def update_object(request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', form_class=None): <NEW_LINE> <INDENT> if extra_context is None: extr...
Generic object-update function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object object the original object being edited
625941d9435de62698dfdee7
def test_overlay(dfs_index, how, use_sindex): <NEW_LINE> <INDENT> df1, df2 = dfs_index <NEW_LINE> result = overlay(df1, df2, how=how, use_sindex=use_sindex) <NEW_LINE> def _read(name): <NEW_LINE> <INDENT> expected = read_file( os.path.join(DATA, 'polys', 'df1_df2-{0}.geojson'.format(name))) <NEW_LINE> expected.crs = No...
Basic overlay test with small dummy example dataframes (from docs). Results obtained using QGIS 2.16 (Vector -> Geoprocessing Tools -> Intersection / Union / ...), saved to GeoJSON
625941d955399d3f0558894f
def p_optplacement(p): <NEW_LINE> <INDENT> if not p[1]: <NEW_LINE> <INDENT> p[0]=None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not p[2]: <NEW_LINE> <INDENT> side="" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> side=p[2] <NEW_LINE> <DEDENT> p[0]=lookup("in "+side+p[3])()
optplacement : IN optdir CHIEF | IN optdir BASE | empty
625941d98a43f66fc4b542fd
def dictresult(self): <NEW_LINE> <INDENT> for row in self.values: <NEW_LINE> <INDENT> yield {self._fields_str[i]: value for i, value in enumerate(row)}
Iterator of the result which return row by row in form {'field1_name': field1_value, 'field2_name': field2_value, ...}
625941d9f8510a7c17cf9997
def download_cluster_file(t2_url, t2_token, id, resource_name, destination_path): <NEW_LINE> <INDENT> response = requests.get(f"{t2_url}/api/clusters/{id}/{resource_name}", headers={ "t2-token": t2_token }) <NEW_LINE> if(response.status_code != 200): <NEW_LINE> <INDENT> log(f"API call to get resource '{resource_name}' ...
Downloads the cluster resource file with the given resource name to the given destination.
625941d9a79ad161976cc3e0
def OnStartup(self,application): <NEW_LINE> <INDENT> pass
OnStartup(self: IExternalApplication,application: UIControlledApplication) -> Result Implement this method to execute some tasks when Autodesk Revit starts. application: A handle to the application being started. Returns: Indicates if the external application completes its work successfully.
625941d94d74a7450ccd445e
def conversation(self, scope=None): <NEW_LINE> <INDENT> if scope is None: <NEW_LINE> <INDENT> if self.scope is scopes.UNIT: <NEW_LINE> <INDENT> scope = hookenv.remote_unit() <NEW_LINE> <DEDENT> elif self.scope is scopes.SERVICE: <NEW_LINE> <INDENT> scope = hookenv.remote_service() <NEW_LINE> <DEDENT> else: <NEW_LINE> <...
Get a single conversation, by scope, that this relation is currently handling. If the scope is not given, the correct scope is inferred by the current hook execution context. If there is no current hook execution context, it is assume that there is only a single global conversation scope for this relation. If this r...
625941d95166f23b2e1a53f3
def setup_job_drmaa(job, executable, arguments = [], stdin = [], working_directory = None, ncpu = 1, timeout = None): <NEW_LINE> <INDENT> if working_directory is None: <NEW_LINE> <INDENT> working_directory = os.getcwd() <NEW_LINE> <DEDENT> rs = random_string() <NEW_LINE> script_path = os.path.join(working_directory, 'F...
Generate a script to run a program with some command-line arguments and setup cluster job for submission using DRMAA API.
625941d9187af65679ca53b9
def decrease(self, proxy): <NEW_LINE> <INDENT> score = self.db.zscore(settings.REDIS_KEY, proxy) <NEW_LINE> if score and score > settings.MIN_SCORE: <NEW_LINE> <INDENT> print('代理', proxy, '当前分数', score, '减1') <NEW_LINE> return self.db.zincrby(settings.REDIS_KEY, proxy, -1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ...
代理值减一分,分数小于最小值则代理删除 :param proxy: :return:
625941d9c4546d3d9de72cd0
def generate_3d_pointcloud(left_image_dir, right_image_dir, num_disparities, block_size, calibration_file_dir, result_dir): <NEW_LINE> <INDENT> image1 = cv2.imread(left_image_dir, 0) <NEW_LINE> image2 = cv2.imread(right_image_dir, 0) <NEW_LINE> image1_colored = cv2.imread(left_image_dir, 1) <NEW_LINE> image2_colored = ...
Generates the 3D Point Cloud as .ply object in the results directory Parameters ---------- left_image_dir : string The directory of the left image right_image_dir : string The directory of the right image num_disparities : int Parameter for stereo object block_size : int Parameter for stereo object cal...
625941d95f7d997b87174d34
def analyze_file(filename): <NEW_LINE> <INDENT> img = cv.LoadImage(filename) <NEW_LINE> (S1, S2) = cv.GetSize(img) <NEW_LINE> rf = RubiksFinder(S1, S2) <NEW_LINE> if display_window: <NEW_LINE> <INDENT> cv.NamedWindow("Fig", cv.CV_WINDOW_NORMAL) <NEW_LINE> cv.ResizeWindow("Fig", rf.width, rf.height) <NEW_LINE> <DEDENT> ...
Assuming filename is a png that contains a rubiks cube, return the RGB values for all 9 squares
625941d994891a1f4081bd44
def normalized(self): <NEW_LINE> <INDENT> if self.mode == "t2": <NEW_LINE> <INDENT> time_factor = 1e-12 <NEW_LINE> norm = lambda t, c: float(c)/(t[1]-t[0])*1e12 <NEW_LINE> <DEDENT> elif self.mode == "t3": <NEW_LINE> <INDENT> norm = lambda t, c: float(c)/(t[1]-t[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mode_err...
Return the counts, normalized to pulse or time as necessary.
625941d9c432627299f04ee2
def put(self, url, data=None, **kwargs): <NEW_LINE> <INDENT> return self.request('PUT', url, data=data, **kwargs)
Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or File-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
625941d9b57a9660fec33b22
def testConvertIterable(self): <NEW_LINE> <INDENT> expected = ([651409.804], [313177.45]) <NEW_LINE> result = convert_bng(iter([1.7160739736]), iter([52.658007833])) <NEW_LINE> self.assertEqual(expected, result)
Test lon, lat --> BNG conversion of tuples
625941d91f037a2d8b946498
def canonical_dir(self, f): <NEW_LINE> <INDENT> return os.path.split(self.file_locator.canonical_filename(f))[0]
Return the canonical directory of the file `f`.
625941d9e8904600ed9f21ca
def connect(self): <NEW_LINE> <INDENT> self._dbcon = pymssql.connect( server=self._host, port=self._port, database=self._dbname, user=self._username, password=self._password) <NEW_LINE> self.result_as_dict(self._result_as_dict)
Method connects to database Args: none Returns: void
625941d9f9cc0f698b140894
def _peeloff_pi(arg): <NEW_LINE> <INDENT> for a in Add.make_args(arg): <NEW_LINE> <INDENT> if a is S.Pi: <NEW_LINE> <INDENT> K = S.One <NEW_LINE> break <NEW_LINE> <DEDENT> elif a.is_Mul: <NEW_LINE> <INDENT> K, p = a.as_two_terms() <NEW_LINE> if p is S.Pi and K.is_Rational: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> ...
Split ARG into two parts, a "rest" and a multiple of pi/2. This assumes ARG to be an Add. The multiple of pi returned in the second position is always a Rational. Examples: >>> from sympy.functions.elementary.trigonometric import _peeloff_pi as peel >>> from sympy import pi >>> from sympy.abc import x, y >>> peel(x + ...
625941d96fb2d068a760f33b
def test_flexx_in_thread1(): <NEW_LINE> <INDENT> def main(): <NEW_LINE> <INDENT> asyncio.set_event_loop(loop2) <NEW_LINE> app.create_server() <NEW_LINE> <DEDENT> loop1 = asyncio.new_event_loop() <NEW_LINE> loop2 = asyncio.new_event_loop() <NEW_LINE> loop3 = asyncio.new_event_loop() <NEW_LINE> asyncio.set_event_loop(loo...
Test threading and ioloop selection.
625941d996565a6dacc8f965
def test_child_msg(self): <NEW_LINE> <INDENT> valid_data_parent = {'to': 'john', 'body': 'Body'} <NEW_LINE> form = ComposeForm(data=valid_data_parent) <NEW_LINE> self.failUnless(form.is_valid()) <NEW_LINE> sender = User.objects.get(username='jane') <NEW_LINE> parent_msg = form.save(sender) <NEW_LINE> valid_data = {'to'...
Test a child message
625941d99c8ee82313fbba10
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941d99f2886367277ab26
def run_browser_task(run_task): <NEW_LINE> <INDENT> driver = driver_setup.get_webdriver() <NEW_LINE> try: <NEW_LINE> <INDENT> return run_task(driver) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> driver.quit()
Starts a new browser, runs the given task, and returns the result
625941d98c0ade5d55d3ec57
def crlbUsblOdo(T,x,y,xb,yb,dtUsbl,varr,vara,varv,vel,varhdg): <NEW_LINE> <INDENT> NUsbl = int(floor(T/dtUsbl)) <NEW_LINE> Ns = 2*NUsbl <NEW_LINE> Cr = zeros((NUsbl,Ns)) <NEW_LINE> r = sqrt((x-xb)**2+(y-yb)**2) <NEW_LINE> dy = y-yb <NEW_LINE> dx = x-xb <NEW_LINE> for ii in range(NUsbl): <NEW_LINE> <INDENT> Cr[ii,ii*2] ...
INPUTS T - Duration of observation window. Number of obs. determined by dtUsbl x,y - location of observations xb,yb - location of USBL origin dtUsbl - sampling time of USBL varr - USBL range variance vara - USBL angle variance varv - velocity variance vel - mobile velocity varhdg - heading velocity OUTPUTS: CRLBxy - ...
625941d956ac1b37e6264466
def get_supports_goals(document, supports_section): <NEW_LINE> <INDENT> if supports_section == SupportsType.CORE: <NEW_LINE> <INDENT> regex_strings = ( 'goal/s my core supports', 'core supports' ) <NEW_LINE> <DEDENT> elif supports_section == SupportsType.CAPACITY_BUILDING: <NEW_LINE> <INDENT> regex_strings = ( 'goal/s ...
Extracts supports goals out of a document Args: document (str): The contents of a document supports_section (SupportsType): The supports category to search for goals Returns: tuple(str): The extracted supports goals, or 'TBC' if none could be found
625941d999fddb7c1c9de62b
def struct_to_date(date_struct): <NEW_LINE> <INDENT> return date(date_struct['y'], date_struct['m'], date_struct['d'])
convert a {y: 2013, m: 1, d: 1} struct to a date
625941d9e5267d203edcdf34
def update_single_row(self, tablename, key, **colvals): <NEW_LINE> <INDENT> cursor = self.conn.cursor(buffered=True) <NEW_LINE> primary_key_column = self.get_primary_key(tablename) <NEW_LINE> columns = colvals.get("columns") <NEW_LINE> values = tuple(colvals.get("values")) <NEW_LINE> if isinstance(columns, str): <NEW_L...
insert single row/values into table. requires 'columns' and 'values' as an argument
625941d9bde94217f3683089
def expr(self): <NEW_LINE> <INDENT> result = self.term() <NEW_LINE> while self.current_token.type in (PLUS, MINUS): <NEW_LINE> <INDENT> token = self.current_token <NEW_LINE> if token.type == PLUS: <NEW_LINE> <INDENT> self.eat(PLUS) <NEW_LINE> result = OP_FUNCS[PLUS](result, self.term()) <NEW_LINE> <DEDENT> elif token.t...
Arithmetic exp parser / interpreter expr: term ((PLUS | MINUS) term)* term: factor ((MUL | DIV) factor)* factor: primary (POW primary)* primary: INTEGER | (LPAREN expr RPAREN)
625941d9e76e3b2f99f3aaa2
def getNext(self, ID): <NEW_LINE> <INDENT> d = self._getNext(ID) <NEW_LINE> self.dt.put(d) <NEW_LINE> return d
Gets the next item for the iterator specified by I{ID}, returning a C{Deferred} that fires with a response containing the pickled item and the I{isValid} status indicating if the item is legit (C{False} = L{StopIteration}).
625941d9283ffb24f3c55b99
def modifyMovieTreeStore(method): <NEW_LINE> <INDENT> def wrapper(self, contextId, context, response, treeIndex, originalMovieEntity, originalSeriesIndex, modifiedMovieEntity, modifiedSeriesIndex): <NEW_LINE> <INDENT> if (response == Gtk.ResponseType.OK and ((modifiedMovieEntity != originalMovieEntity if modifiedMovieE...
Decorator for methods to modify a movieTreeStore.
625941d9442bda511e8be6af
def sub_purse(self,item,amount): <NEW_LINE> <INDENT> self.purse=self.purse-self._itemPrice[item]*int(amount)
A function which subtracts the cost of an item from the purse
625941d9099cdd3c635f0ef4
def test_stf_empty(self): <NEW_LINE> <INDENT> Square.save_to_file([]) <NEW_LINE> with open("Square.json", "r") as f: <NEW_LINE> <INDENT> self.assertEqual("[]", f.read())
test save_to_file with empty list
625941d9287bf620b61d3cfd
def filter_by_organization(field, object_type): <NEW_LINE> <INDENT> values = db_util.filter_by_organization(object_type) <NEW_LINE> field.query = values <NEW_LINE> if len(values) == 0: <NEW_LINE> <INDENT> field._object_list = []
Set field query for a edit or create form :param field: field to set the query :param object_type: object type to filter :return: field with query and _object_list set by the values
625941d9f7d966606f6aa2a1
def test_initialization(self): <NEW_LINE> <INDENT> registry_path = os.path.join(self.tmp_path, REGISTRY_NAME) <NEW_LINE> self.assertFalse(os.path.exists(registry_path)) <NEW_LINE> registry = Registry(self.tmp_path) <NEW_LINE> self.assertEqual(registry.path, registry_path) <NEW_LINE> self.assertTrue(os.path.exists(regis...
Test whether attributes are initialized
625941d9b830903b967e9ba3
def make_accepted( self: "SessionAdmin", request: WSGIRequest, queryset: QuerySet ) -> None: <NEW_LINE> <INDENT> queryset.update(status="Accepted")
Custom action that update the status of session to Accepted.
625941d9d7e4931a7ee9e1b8
def __eq__(self, other): <NEW_LINE> <INDENT> return self.board == other.board
Determine if self (board) and other(board) are equal :param other: board data structure we're comparing self.board to :return: true if equal false if not
625941d994891a1f4081bd45
def addBinary(self, a, b): <NEW_LINE> <INDENT> la, lb = len(a), len(b) <NEW_LINE> if la > lb: <NEW_LINE> <INDENT> la, lb, a, b = lb, la, b, a <NEW_LINE> <DEDENT> carry = 0 <NEW_LINE> ans = [] <NEW_LINE> for i in range(la): <NEW_LINE> <INDENT> carry, s = divmod(int(a[~i]) + int(b[~i]) + carry, 2) <NEW_LINE> ans.append(s...
:type a: str :type b: str :rtype: str
625941d9ac7a0e7691ed4363
def _zamanda(): <NEW_LINE> <INDENT> put('%(local_path)s/install/install_zamanda.sh' % env, '/tmp/install_zamanda.sh' % env) <NEW_LINE> sudo('chmod +x /tmp/install_zamanda.sh; /tmp/install_zamanda.sh %(mysql_root_pwd)s %(mysql_user_pwd)s %(type)s' % (env)) <NEW_LINE> sudo('rm /tmp/install_zamanda.sh')
install backup tools
625941d9ec188e330fd5aa35
def split(self, toarray): <NEW_LINE> <INDENT> return train_test_split( self.vectorized.toarray() if toarray else self.vectorized , self.labels , train_size = self.train_size , random_state = random.randint(0,1000) )
Split the data set into test and train data. Args : toarray : Convert to array.
625941d9099cdd3c635f0ef5
def test_get_all_orgs(self): <NEW_LINE> <INDENT> test_orgs = [test_config['course_org_filter']] <NEW_LINE> with with_site_configuration_context(configuration=test_config): <NEW_LINE> <INDENT> self.assertCountEqual( list(configuration_helpers.get_all_orgs()), test_orgs, )
Test that get_all_orgs returns organizations defined in site configuration
625941d9a219f33f34628c01
def plot_flags(self, name: Any = 0) -> None: <NEW_LINE> <INDENT> if name not in self.columns: <NEW_LINE> <INDENT> name = self.columns[name] <NEW_LINE> <DEDENT> col = list(self.columns).index(name) <NEW_LINE> plt.plot(self.index, self.x[:, col], color="lightgrey", marker=".", zorder=1) <NEW_LINE> colors = { "NEGATIVE_OR...
Plot cleaned series and anomalous values colored by flag. Args: name: Series to plot, as either an integer index or name in :attr:`columns`.
625941d910dbd63aa1bd2e3d
def draw_ellipse(position, covariance, ax=None, **kwargs): <NEW_LINE> <INDENT> ax = ax or plt.gca() <NEW_LINE> if covariance.shape == (2, 2): <NEW_LINE> <INDENT> U, s, Vt = np.linalg.svd(covariance) <NEW_LINE> angle = np.degrees(np.arctan2(U[1, 0], U[0, 0])) <NEW_LINE> width, height = 2 * np.sqrt(s) <NEW_LINE> <DEDENT>...
Draw an ellipse with a given position and covariance
625941d95fc7496912cc3c19
def remove_F_score_blast_p_by_ppi_couple(self, FK_id_PPI_couple_PCP_FSB_P): <NEW_LINE> <INDENT> sql_string = "DELETE FROM F_SCORE_BLAST_P WHERE FK_id_protein_phage_PT_FSB_P = %s OR FK_id_PPI_couple_PCP_FSB_P = %s" <NEW_LINE> dalObj = DAL(self.db_name, sql_string) <NEW_LINE> params = [fk_id_protein, fk_id_protein] <NEW_...
remove a FK_score_blast_P by the id of the protein :param FK_id_PPI_couple_PCP_FSB_P: id of the PPI_couple :type FK_id_PPI_couple_PCP_FSB_P: int - required :return: quantity of row deleted row :rtype int
625941d93617ad0b5ed68191
def image_whitening(data): <NEW_LINE> <INDENT> assert len(np.shape(data)) == 4 <NEW_LINE> nb_pixels = np.shape(data)[1] * np.shape(data)[2] * np.shape(data)[3] <NEW_LINE> mean = np.mean(data, axis=(1, 2, 3)) <NEW_LINE> ones = np.ones(np.shape(data)[1:4], dtype=np.float32) <NEW_LINE> for i in xrange(len(data)): <NEW_LIN...
Subtracts mean of image and divides by adjusted standard variance (for stability). Operations are per image but performed for the entire array.
625941d9b5575c28eb68e29d
def walk(handler, path, excludes=None, fs_encoding=LOCAL_FS_ENCODING, recursive=False): <NEW_LINE> <INDENT> if isinstance(path, pathlib.Path): <NEW_LINE> <INDENT> path = str(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = str(path, fs_encoding) if type(path) is not str else path <NEW_LINE> <DEDENT> excludes ...
A wrapper around os.walk which handles exclusion patterns and multiple path types (str, pathlib.Path, bytes).
625941d926238365f5f0f10c
def plot_sigma_g(self,N=0): <NEW_LINE> <INDENT> from matplotlib.pyplot import loglog,title,xlabel,ylabel,ylim <NEW_LINE> if (N+1>self.sigma_g.shape[0]): <NEW_LINE> <INDENT> N=0; <NEW_LINE> <DEDENT> loglog(self.x,self.sigma_g[N],'-') <NEW_LINE> title('Gas surface density') <NEW_LINE> xlabel('r [AU]') <NEW_LINE> ylabel('...
Produces a plot of the gas surface density at snapshot number N. Nothing fancy yet. Arguments: N index of the snapshot, defaults to first snapshot Example: >>> D.plot_sigma_g(133)
625941d9aad79263cf390cdf
def haslayer(self, cls): <NEW_LINE> <INDENT> if self.__class__ == cls or cls in [self.__class__.__name__, self._name]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for f in self.packetfields: <NEW_LINE> <INDENT> fvalue_gen = self.getfieldval(f.name) <NEW_LINE> if fvalue_gen is None: <NEW_LINE> <INDENT> continue ...
true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.
625941d9fbf16365ca6f6462
def info(group_id, artifact_id, version): <NEW_LINE> <INDENT> xml = quick_search(artifact_id) <NEW_LINE> root = ET.fromstring(xml) <NEW_LINE> infos = [] <NEW_LINE> for artifact in root.iter('artifact'): <NEW_LINE> <INDENT> g = artifact.find('groupId').text <NEW_LINE> a = artifact.find('artifactId').text <NEW_LINE> v = ...
Determine the extension and classifier of an artifact in Nexus. Returns: A tuple of (extension, classifier).
625941d9711fe17d82542601
def reset_AScurrent_sum(neuron, AScurrents_t0, r): <NEW_LINE> <INDENT> new_currents=neuron.asc_amp_array * neuron.coeffs['asc_amp_array'] <NEW_LINE> left_over_currents=AScurrents_t0 * r * np.exp(-(neuron.k * neuron.dt * neuron.spike_cut_length)) <NEW_LINE> return new_currents+left_over_currents
Reset afterspike currents by adding summed exponentials. Left over currents from last spikes as well as newly initiated currents from current spike. Currents amplitudes in neuron.asc_amp_array need to be the amplitudes advanced though the spike cutting. I.e. In the preprocessor if the after spike currents are calcu...
625941d98a349b6b435e840e
def get_cert_from_db(self, nickname): <NEW_LINE> <INDENT> return mock_Cert(nickname)
Return the nickname. This will match the value of get_directive
625941d91f5feb6acb0c4de7
def next_move(self): <NEW_LINE> <INDENT> valid_flag = True <NEW_LINE> while valid_flag: <NEW_LINE> <INDENT> x = input('{} [Move] (from to): '.format( g('Player 1') if self.id == 1 else b('Player 2') )).lower().strip().split(' ') <NEW_LINE> if len(x) != 2: <NEW_LINE> <INDENT> print('Invalid Move-Movement....
This function takes two location inputs (s, t) for MOVE-movement. It keeps checking whether it is a legal MOVE-movement until the input is a legal MOVE-movement. After getting the correct input, it then does the movement on the board (by calling board.move_piece()). It returns the position to which the piece moves beca...
625941d93cc13d1c6d3c7614
def fetch(self, retry_counter=0): <NEW_LINE> <INDENT> if not self.options['silent']: <NEW_LINE> <INDENT> print('Fetching', self.data) <NEW_LINE> <DEDENT> time.sleep(self.options['delay']) <NEW_LINE> try: <NEW_LINE> <INDENT> request = requests.get(self.data) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> if n...
Returns http request from URL as a string. Can be called to return HTML data, although not generally meant to be called directly by user. If user calls .fetch(), retry_counter should not be passed so that it will start at 0. This function is intended to be called by .soup() in order to feed its parser. If the request...
625941d923849d37ff7b3328
def test_no_base_no_learning_words( self ): <NEW_LINE> <INDENT> expected_list=[ ['6cb08b08a1b3145f1a7a1de2983daa8f', 'b', ['Def'], 'ddd', ''], ['18223d6b04accdd8ef610ee7a566dd6a', 'b', ['Hjk'], 'www', 'note'] ] <NEW_LINE> myFilteredDictionary=FilteredDictionary(TestWordCycleInit.BASE_NAME, 'hungarian', 'swedish') <NEW_...
The line int the dict file will be avoided which are: -empty -has no base word -has no learning word
625941d921a7993f00bc7f8e
def get_id(self) -> str: <NEW_LINE> <INDENT> return self._card_id
Returns a String with the ID of the Card
625941d9435de62698dfdee8
def write_to_file(path, data): <NEW_LINE> <INDENT> with open(path, 'a') as f: <NEW_LINE> <INDENT> for column in data: <NEW_LINE> <INDENT> f.write("%s " % column) <NEW_LINE> <DEDENT> f.write('\n')
Takes a path to file and data to br written as an array. Appends the file with the given data.
625941d9956e5f7376d71107
def has_encountered_output_source(context): <NEW_LINE> <INDENT> return CONTEXT_OUTPUT_SOURCE in context
Return True if the current context has already encountered an @output_source directive.
625941d94e4d5625662d4670
def app_factory(config_env='PRD', app_name=__name__): <NEW_LINE> <INDENT> app = Flask(app_name, template_folder=_TEMPLATE_FOLDER, instance_path=_INSTANCE_FOLDER, instance_relative_config=True) <NEW_LINE> config_app(app, config_env) <NEW_LINE> config_init(app) <NEW_LINE> config_extensions(app) <NEW_LINE> config_blueprin...
Initialize the application with the specified environment specific configuration. Parameters ---------- config_env: string: The abbreviation of the environment to load the configuration settings for. app_name: string The name of the application. Returns ------- Flask instance: The Flask application instan...
625941d95166f23b2e1a53f4
def subtract_logs(log0_path, log1_path, result_log_path): <NEW_LINE> <INDENT> log0 = file2dict(log0_path, numeric=True) <NEW_LINE> log1 = file2dict(log1_path, numeric=True) <NEW_LINE> result_log = {} <NEW_LINE> for key in log0.keys(): <NEW_LINE> <INDENT> result_log[key] = log0[key] - log1[key] <NEW_LINE> <DEDENT> dict2...
log0 - log1 Args: log0_path, log1_path: the path of logs to be result result_log_path: where the result is saved
625941d9be383301e01b571e
def __init__(self): <NEW_LINE> <INDENT> self.gsheets = self.connect()
Initialize the spreadsheet
625941d91d351010ab855db7
def take_until(source: Observable[_T]) -> Observable[_T]: <NEW_LINE> <INDENT> def subscribe( observer: abc.ObserverBase[_T], scheduler: Optional[abc.SchedulerBase] = None, ) -> abc.DisposableBase: <NEW_LINE> <INDENT> def on_completed(_: _T) -> None: <NEW_LINE> <INDENT> observer.on_completed() <NEW_LINE> <DEDENT> return...
Returns the values from the source observable sequence until the other observable sequence produces a value. Args: source: The source observable sequence. Returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
625941d92eb69b55b151cb4d
def custom_action_response_descriptor_octopus_server_web_api_actions_dashboard_configuration_update_action_spaces_with_http_info(self, base_space_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['base_space_id'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> ...
custom_action_response_descriptor_octopus_server_web_api_actions_dashboard_configuration_update_action_spaces # noqa: E501 NOTE: This definition is not complete. We will be adding more detail in future releases of Octopus. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronou...
625941d966656f66f7cbc447
def parsehelper_634(self, node): <NEW_LINE> <INDENT> oldpos = self.pos <NEW_LINE> childs = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> oldpos2 = self.pos <NEW_LINE> c = self.parsehelper_635(node) <NEW_LINE> if c is None: <NEW_LINE> <INDENT> self.pos = oldpos2 <NEW_LINE> break <NEW_LINE> <DEDENT> childs.extend(c) <NEW...
## subexpr ## GrammarNode('*', GrammarNode('S', [GrammarNode('A', [GrammarNode('S', ["'<<'"]), GrammarNode('S', ["'>>'"])]), 'arith_expr']))
625941d94f88993c3716c301
def __showRules(ircMsg): <NEW_LINE> <INDENT> chan = ircMsg.net.findChannel(ircMsg.dest) <NEW_LINE> if not chan.checkFlag("norules"): <NEW_LINE> <INDENT> ircMsg.net.sendFile("help/rules.txt", "NOTICE", ircMsg.src)
Shows rules from the rules.txt help file.
625941d9aad79263cf390ce0
def total_seconds(td): <NEW_LINE> <INDENT> return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) // 10 ** 6
Compute total seconds for a timedelta. Added for backward compatibility, pre 2.7.
625941d93d592f4c4ed1d304
def _send_client_update(self, client_update: ClientUpdate, client_id: uuid.UUID = None) -> None: <NEW_LINE> <INDENT> assert isinstance(client_update, ClientUpdate) <NEW_LINE> if client_id is None: <NEW_LINE> <INDENT> client_ids = self._authenticated_client_ids <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> client_ids = ...
Send a ClientUpdate to either a specific GradeBook client or to all open, authenticated GradeBook clients. :param client_update: The update to send. :param client_id: The ID of the client to send to. If this is None, then send to all clients.
625941d9be8e80087fb20edb
def interp_to_model_time(time_model, varp, tp): <NEW_LINE> <INDENT> epoc = time_model[0] <NEW_LINE> tp_wrt_epoc = [] <NEW_LINE> for t in tp: <NEW_LINE> <INDENT> tp_wrt_epoc.append((t-epoc).total_seconds()) <NEW_LINE> <DEDENT> varp_interp = [] <NEW_LINE> for t in time_model: <NEW_LINE> <INDENT> mod_wrt_epoc = (t-epoc).t...
Interpolates a variable to model output times. :arg model_time: array of model output times as datetime objects :type model_time: array with datetimes :arg varp: array of variable to be interpolated :type varp: array :arg tp: array of times associated with variable :type tp: array :returns: varp_interp, the variabl...
625941d9bf627c535bc1346a
def closeEvent(self, QCloseEvent): <NEW_LINE> <INDENT> pass
closeEvent(self, QCloseEvent)
625941d966656f66f7cbc448
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BlueCash.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sur...
Run administrative tasks.
625941d9498bea3a759b9d4a
def test_content(response: typing.Any) -> None: <NEW_LINE> <INDENT> pass
Sample pytest test function with the pytest fixture as an argument.
625941d96aa9bd52df037040
@memoize_function <NEW_LINE> def number_of_trees_bin_nont_partial(n, l, N): <NEW_LINE> <INDENT> if (l != n) or (N != 2 * n - 1) or (n < 0): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if n == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return (N - 2) * number_of_trees_bin_nont_partial(n - 1, l - 1, N - 2)
Gives the number of phylogenetic trees on n taxa with l leaves and N nodes. Assume binary trees without nested taxa.
625941d9d99f1b3c44c67826
def teardown(self): <NEW_LINE> <INDENT> del self.inst, self.const, self.ref_time
Clean up after each test
625941d9a8370b7717052b3a
def __init__(self, id, labels): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.labels = labels
Parameters ---------- id : int unique Minion id. labels : array-like, shape (n_labels,) list of valid labels for the classification task. Note ---- The provided labels must be valid for the classification task.
625941d99b70327d1c4e1071
def warn(self, message, *args): <NEW_LINE> <INDENT> self._output(Fore.YELLOW, message, *args)
Prints the given warning message. :return: None
625941d9851cf427c661a7a9
def __contains__(self, key): <NEW_LINE> <INDENT> return ( key in ["country_code", "state", "city", "street_line1", "street_line2", "post_code"] and hasattr(self, key) and bool(getattr(self, key, None)) )
Implements `"key" in shippingaddress_instance`
625941d9bd1bec0571d908ca
def _create_credentials() -> tuple: <NEW_LINE> <INDENT> sa, ep, sakey = os.environ['SHIPYARD_STORAGE_ENV'].split(':') <NEW_LINE> blob_client = azureblob.BlockBlobService( account_name=sa, account_key=sakey, endpoint_suffix=ep) <NEW_LINE> table_client = azuretable.TableService( account_name=sa, account_key=sakey, endpoi...
Create storage credentials :rtype: tuple :return: (blob_client, table_client)
625941d957b8e32f52483738
@solid( description="A solid to invoke dbt test via CLI.", input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)], output_defs=[OutputDefinition(name="dbt_cli_output", dagster_type=DbtCliOutput)], config_schema={ **CLI_CONFIG_SCHEMA, "data": Field( config=bool, description='Run data tests defined in "te...
This solid executes ``dbt test`` via the dbt CLI. See the solid definition for available parameters.
625941d910dbd63aa1bd2e3e
def get_unstructured_grid(self, subset=None): <NEW_LINE> <INDENT> if subset is None: <NEW_LINE> <INDENT> return self.vtk_ugd <NEW_LINE> <DEDENT> vtk_subpts = self.get_points(subset) <NEW_LINE> vtk_subugd = vtkUnstructuredGrid() <NEW_LINE> vtk_subugd.SetWholeBoundingBox(self.cell.get_bounding_box()) <NEW_LINE> vtk_subug...
Return (subset of) an unstructured grid of the atomic positions. subset=None: list of int A list of indices into the atomic positions; ignored if None.
625941d93617ad0b5ed68192
def is_garrison(self, civ_id: int = -1) -> bool: <NEW_LINE> <INDENT> head_unit = self.get_head_unit() <NEW_LINE> if civ_id != -1: <NEW_LINE> <INDENT> head_unit = self.data.civ_groups[civ_id]["units"][self.get_head_unit_id()] <NEW_LINE> <DEDENT> trait = head_unit["trait"].get_value() <NEW_LINE> if trait & 0x01: <NEW_LIN...
Checks whether the group can garrison other entities. This covers all of these garrisons: - Natural garrisons (castle, town center, tower) - Production garrisons (barracks, archery range, stable, etc.) - Unit garrisons (ram, siege tower) - Transport ships This does not include kidnapping units! :param civ_id: Test i...
625941d90c0af96317bb8484
def test_list_updates_by_date_submitted_valid(self): <NEW_LINE> <INDENT> res = self.app.get('/updates/', {"submitted_since": "1984-11-01"}) <NEW_LINE> body = res.json_body <NEW_LINE> self.assertEquals(len(body['updates']), 1) <NEW_LINE> up = body['updates'][0] <NEW_LINE> self.assertEquals(up['title'], u'bodhi-2.0-1.fc1...
test filtering by submitted date with valid data
625941d9cdde0d52a9e532d1
def get_host_by_ipaddr(ipaddr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> socket.inet_aton(ipaddr) <NEW_LINE> return socket.gethostbyaddr(ipaddr)[0] <NEW_LINE> <DEDENT> except socket.herror: <NEW_LINE> <INDENT> return 'no reverse DNS found' <NEW_LINE> <DEDENT> except (socket.error, TypeError): <NEW_LINE> <INDENT> re...
returns a reverse DNS name if available
625941d907f4c71912b11720
def _setup_orbital(uni, verbose, vector, fps, icoefs, log=None, jcoefs=None, irrep=None): <NEW_LINE> <INDENT> log = log or func_log(_setup_orbital) <NEW_LINE> t1 = datetime.now() <NEW_LINE> nbf = len(uni.basis_functions) <NEW_LINE> if irrep is not None: <NEW_LINE> <INDENT> nbf = len(uni.basis_set_order.groupby('irrep')...
Boilerplate for starting the functions in this module.
625941d94527f215b584c6f0
@commandWrap <NEW_LINE> def polyMoveFacet(*args, **kwargs): <NEW_LINE> <INDENT> return cmds.polyMoveFacet(*args, **kwargs)
:rtype: list|str|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941d9293b9510aa2c352f
def dcgain(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.isctime(): <NEW_LINE> <INDENT> gain = np.asarray(self.D - self.C.dot(np.linalg.solve(self.A, self.B))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gain = self.horner(1) <NEW_LINE> <DEDENT> <DEDENT> except LinAlgError: <NEW_LINE> <INDENT> gain = np...
Return the zero-frequency gain The zero-frequency gain of a continuous-time state-space system is given by: .. math: G(0) = - C A^{-1} B + D and of a discrete-time state-space system by: .. math: G(1) = C (I - A)^{-1} B + D Returns ------- gain : ndarray An array of shape (outputs,inputs); the array will eithe...
625941d9435de62698dfdee9
def delete_draft(db_session, account, draft_public_id): <NEW_LINE> <INDENT> draft = db_session.query(Message).filter( Message.public_id == draft_public_id).one() <NEW_LINE> assert draft.is_draft <NEW_LINE> db_session.delete(draft) <NEW_LINE> if not draft.thread.drafts: <NEW_LINE> <INDENT> draft.thread.remove_tag(draft....
Delete the draft with public_id = `draft_public_id`.
625941d93eb6a72ae02ec77f
def getB(self): <NEW_LINE> <INDENT> return self._b
return blue component of this pixel
625941d9fff4ab517eb2f6d9
@time_pass <NEW_LINE> def get_minor_major(data, string, minority_ratio, majority_ratio): <NEW_LINE> <INDENT> by_column = data.apply(sum, axis=0) <NEW_LINE> minority_num = np.percentile(by_column.values, minority_ratio) <NEW_LINE> majority_num = np.percentile(by_column.values, majority_ratio) <NEW_LINE> minority_feature...
data是一个0-1型DataFrame 以用户安装app的数据为例,这个函数计算出了: 1.每个用户安装小众软件的数量 2.每个用户安装大众软件的数量 3.每个用户安装任何软件的数量
625941d9a79ad161976cc3e2
def on_done(self, index): <NEW_LINE> <INDENT> if index == -1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> repository = self.repositories[index] <NEW_LINE> try: <NEW_LINE> <INDENT> self.repositories.remove(repository) <NEW_LINE> self.settings.set('repositories', self.repositories) <NEW_LINE> sublime.save_settings(pc_...
Quick panel handler - removes the repository from settings :param index: The numeric index of the repository in the list of repositories
625941d932920d7e50b2846e
def economic_sensitivity(self, years_arr, inv_rate_arr): <NEW_LINE> <INDENT> ny = len(years_arr) <NEW_LINE> ni = len(inv_rate_arr) <NEW_LINE> values = np.zeros((3, ni, ny)) <NEW_LINE> for i, years in enumerate(years_arr): <NEW_LINE> <INDENT> for j, inv_rate in enumerate(inv_rate_arr): <NEW_LINE> <INDENT> lcoe, income, ...
:param years_arr: :param inv_rate_arr: :return:
625941d97d847024c06be55a