code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def trigram_printer(filename): <NEW_LINE> <INDENT> file = open(filename) <NEW_LINE> contents = file.read() <NEW_LINE> while len(contents) != 0: <NEW_LINE> <INDENT> print(contents[0:3]) <NEW_LINE> contents = contents[3:] <NEW_LINE> <DEDENT> file.close | takes a string containing a filename.
The function should open the file with the given name
display its contents on the screen, three characters at a time
and then close the file.
str -> str | 625941c03eb6a72ae02ec42b |
def get_configdrive_image(node): <NEW_LINE> <INDENT> configdrive = node.instance_info.get('configdrive') <NEW_LINE> if isinstance(configdrive, dict): <NEW_LINE> <INDENT> configdrive = build_configdrive(node, configdrive) <NEW_LINE> <DEDENT> return configdrive | Get configdrive as an ISO image or a URL.
Converts the JSON representation into an image. URLs and raw contents
are returned unchanged.
:param node: an Ironic node object.
:returns: A gzipped and base64 encoded configdrive as a string. | 625941c0dd821e528d63b0ff |
@pytest.mark.skipif(sys.version_info.major > 2, reason="not relevant for python 3") <NEW_LINE> def test_unicode_segment(): <NEW_LINE> <INDENT> segment = HL7Segment("FOO|Baababamm") <NEW_LINE> str(segment) <NEW_LINE> six.text_type(segment) | unicode segment can be cast to unicode and bytestring | 625941c0046cf37aa974cc9e |
def getDictionaryContents(self,directory,name): <NEW_LINE> <INDENT> return self._master.getSolutionDirectory().getDictionaryContents(directory,name) | @param directory: Sub-directory of the case
@param name: name of the dictionary file
@return: the contents of the file as a python data-structure | 625941c056ac1b37e6264128 |
def isOrphan(self, item): <NEW_LINE> <INDENT> return not self.model('folder').load( item.get('folderId'), force=True) | Returns True if this item is orphaned (its folder is missing).
:param item: The item to check.
:type item: dict | 625941c02c8b7c6e89b35717 |
def index(request): <NEW_LINE> <INDENT> articles = models.Article.objects.all() <NEW_LINE> return render(request, 'blog/index.html', {"articles": articles}) | main use interface
:param request:
:return: all article objects. | 625941c0e1aae11d1e749c0a |
def selected_item(self, num): <NEW_LINE> <INDENT> if num == -1: <NEW_LINE> <INDENT> self.search(s=self.res, link=self.search_links) <NEW_LINE> <DEDENT> if num == 0: <NEW_LINE> <INDENT> self.doc_check(parse_doc(self.search_links[self.num])) <NEW_LINE> <DEDENT> if num == 1: <NEW_LINE> <INDENT> self.doc_view(parse_source(self.search_links[self.num])) <NEW_LINE> <DEDENT> if num == 2: <NEW_LINE> <INDENT> self.doc_view(parse_example(self.search_links[self.num])) <NEW_LINE> <DEDENT> if num == 3: <NEW_LINE> <INDENT> self.see_also, self.see_also_links = seealso_search(self.search_links[self.num]) <NEW_LINE> self.search(s=self.see_also, link=self.see_also_links) <NEW_LINE> <DEDENT> if num == 4: <NEW_LINE> <INDENT> webbrowser.open(self.search_links[self.num]) <NEW_LINE> <DEDENT> if num == 5: <NEW_LINE> <INDENT> self.search() | 1st menu. Directing the options to the main menu. | 625941c0adb09d7d5db6c6e6 |
def init_beat(beat, celery_app): <NEW_LINE> <INDENT> celery_app.loader.import_default_modules() | Configure the passed in celery beat app, usually stored in
:data:`ichnaea.taskapp.app.celery_app`. | 625941c0377c676e912720fe |
def is_active(self, auth_id): <NEW_LINE> <INDENT> return True | Override this method if the categorizer will be active at some time only
(i.e. the garbage collector which analyses the first n points only).
If False is returned, the categorizer will just call its children. | 625941c0dc8b845886cb5488 |
def make_world(self, args=None): <NEW_LINE> <INDENT> world = World() <NEW_LINE> world.dimension_communication = 2 <NEW_LINE> world.log_headers = ["Agent_Type", "Fixed", "Perturbed", "X", "Y", "dX", "dY", "fX", "fY", "Collision"] <NEW_LINE> num_good_agents = 1 <NEW_LINE> num_adversaries = 3 <NEW_LINE> num_agents = num_adversaries + num_good_agents <NEW_LINE> num_landmarks = 2 <NEW_LINE> world.agents = [Agent() for i in range(num_agents)] <NEW_LINE> for i, agent in enumerate(world.agents): <NEW_LINE> <INDENT> agent.name = 'agent {}'.format(i) <NEW_LINE> agent.adversary = True if i < num_adversaries else False <NEW_LINE> agent.accel = 3.0 if agent.adversary else 4.0 <NEW_LINE> agent.collide = True <NEW_LINE> agent.silent = True <NEW_LINE> agent.size = 0.075 if agent.adversary else 0.05 <NEW_LINE> agent.max_speed = 1.0 if agent.adversary else 1.3 <NEW_LINE> <DEDENT> world.landmarks = [Landmark() for i in range(num_landmarks)] <NEW_LINE> for i, landmark in enumerate(world.landmarks): <NEW_LINE> <INDENT> landmark.name = 'landmark {}'.format(i) <NEW_LINE> landmark.boundary = False <NEW_LINE> landmark.collide = True <NEW_LINE> landmark.movable = False <NEW_LINE> landmark.size = 0.2 <NEW_LINE> <DEDENT> boundaries = [Landmark() for i in range(42)] <NEW_LINE> for i, bound in enumerate(boundaries): <NEW_LINE> <INDENT> bound.name = 'boundary {}'.format(i) <NEW_LINE> bound.boundary = True <NEW_LINE> bound.collide = True <NEW_LINE> bound.movable = False <NEW_LINE> bound.size = 0.12 <NEW_LINE> <DEDENT> world.landmarks = world.landmarks + boundaries <NEW_LINE> self.reset_world(world) <NEW_LINE> return world | Construct the world
Returns:
world (multiagent_particle_env.core.World): World object with agents and landmarks | 625941c099fddb7c1c9de2e7 |
def interp_na( self, dim: Hashable = None, use_coordinate: Union[bool, str] = True, method: str = "linear", limit: int = None, max_gap: Union[int, float, str, pd.Timedelta, np.timedelta64, dt.timedelta] = None, keep_attrs: bool = None, **kwargs, ): <NEW_LINE> <INDENT> from xarray.coding.cftimeindex import CFTimeIndex <NEW_LINE> if dim is None: <NEW_LINE> <INDENT> raise NotImplementedError("dim is a required argument") <NEW_LINE> <DEDENT> if limit is not None: <NEW_LINE> <INDENT> valids = _get_valid_fill_mask(self, dim, limit) <NEW_LINE> <DEDENT> if max_gap is not None: <NEW_LINE> <INDENT> max_type = type(max_gap).__name__ <NEW_LINE> if not is_scalar(max_gap): <NEW_LINE> <INDENT> raise ValueError("max_gap must be a scalar.") <NEW_LINE> <DEDENT> if ( dim in self._indexes and isinstance( self._indexes[dim].to_pandas_index(), (pd.DatetimeIndex, CFTimeIndex) ) and use_coordinate ): <NEW_LINE> <INDENT> max_gap = timedelta_to_numeric(max_gap) <NEW_LINE> <DEDENT> if not use_coordinate: <NEW_LINE> <INDENT> if not isinstance(max_gap, (Number, np.number)): <NEW_LINE> <INDENT> raise TypeError( f"Expected integer or floating point max_gap since use_coordinate=False. Received {max_type}." ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> index = get_clean_interp_index(self, dim, use_coordinate=use_coordinate) <NEW_LINE> interp_class, kwargs = _get_interpolator(method, **kwargs) <NEW_LINE> interpolator = partial(func_interpolate_na, interp_class, **kwargs) <NEW_LINE> if keep_attrs is None: <NEW_LINE> <INDENT> keep_attrs = _get_keep_attrs(default=True) <NEW_LINE> <DEDENT> with warnings.catch_warnings(): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", "overflow", RuntimeWarning) <NEW_LINE> warnings.filterwarnings("ignore", "invalid value", RuntimeWarning) <NEW_LINE> arr = apply_ufunc( interpolator, self, index, input_core_dims=[[dim], [dim]], output_core_dims=[[dim]], output_dtypes=[self.dtype], dask="parallelized", vectorize=True, keep_attrs=keep_attrs, ).transpose(*self.dims) <NEW_LINE> <DEDENT> if limit is not None: <NEW_LINE> <INDENT> arr = arr.where(valids) <NEW_LINE> <DEDENT> if max_gap is not None: <NEW_LINE> <INDENT> if dim not in self.coords: <NEW_LINE> <INDENT> raise NotImplementedError( "max_gap not implemented for unlabeled coordinates yet." ) <NEW_LINE> <DEDENT> nan_block_lengths = _get_nan_block_lengths(self, dim, index) <NEW_LINE> arr = arr.where(nan_block_lengths <= max_gap) <NEW_LINE> <DEDENT> return arr | Interpolate values according to different methods. | 625941c0b7558d58953c4e6d |
def is_float(s): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> float(s) <NEW_LINE> return True <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False | Determins if a number is a float or not
Paramaters
s(string)- value to be evaluated
returns
True or False | 625941c00fa83653e4656f11 |
def _sample_pose_circ(rng, params, constraints): <NEW_LINE> <INDENT> for _ in range(1000): <NEW_LINE> <INDENT> r = (params.inner_w + params.inner_h) / 4. + params.mid_margin <NEW_LINE> r = min(r, params.lim_euc_dist) <NEW_LINE> phi = rng.uniform(0, 2 * np.pi) <NEW_LINE> x, y = pol2cart(r, phi) <NEW_LINE> theta = rng.uniform(0, 2 * np.pi) <NEW_LINE> start_pt = OrientedPoint(x, y, theta) <NEW_LINE> end_pt = OrientedPoint(-x, -y, theta) <NEW_LINE> y_off = end_pt.y - start_pt.y <NEW_LINE> x_off = end_pt.x - start_pt.x <NEW_LINE> new_theta = np.arctan2(y_off, x_off) <NEW_LINE> start_pt = OrientedPoint(x, y, new_theta) <NEW_LINE> end_pt = OrientedPoint(-x, -y, new_theta) <NEW_LINE> if _satisfies_constraints(start_pt, constraints) and _satisfies_constraints(end_pt, constraints): <NEW_LINE> <INDENT> return start_pt, end_pt <NEW_LINE> <DEDENT> <DEDENT> raise SpaceSeemsEmptyError( "Something went wrong, the sampling space looks empty.") | Sample the ending and starting pose from the circle,
such that they are on the exactly opposite sides of the circle.
:param rng np.random.RandomState: independent random state
:param params RandomMiniEnvParams: the params, as described above
:param constraints List[Function(Point) -> bool]: Constraints that the points
have to satisfy
:return Tuple(OrientedPoint, OrientedPoint): starting pose and ending pose | 625941c0d99f1b3c44c674e9 |
def finish(self, status=None): <NEW_LINE> <INDENT> if status: <NEW_LINE> <INDENT> self._status = status <NEW_LINE> <DEDENT> self.update(True) | Close the status bar (on error / successful finish).
Args:
status(str, optional): the finish status message (None by default) | 625941c024f1403a92600abd |
def _delete(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._client.delete(self._session_path) <NEW_LINE> <DEDENT> except etcd.EtcdKeyNotFound: <NEW_LINE> <INDENT> pass | Deletes and invalidates the current session. | 625941c03346ee7daa2b2cbf |
def relu(z): <NEW_LINE> <INDENT> if(z < 0): <NEW_LINE> <INDENT> z = 0 <NEW_LINE> <DEDENT> return z | standard ReLu transfer/activation function
returns z or 0 if z < 0
included for testing | 625941c0004d5f362079a28a |
def _get_resources(raml): <NEW_LINE> <INDENT> usable_methods = ["get", "post"] <NEW_LINE> usable_rs = [ r for r in raml.resources if r.method in usable_methods ] <NEW_LINE> rs_without_resource_id = [ r for r in usable_rs if not r.uri_params and not r.body ] <NEW_LINE> rs_with_resource_id = [r for r in usable_rs if r.uri_params] <NEW_LINE> rs_file_upload = [ r for r in usable_rs if r.body and r.body[0].mime_type == "multipart/form-data" ] <NEW_LINE> if ( len(usable_rs) == 0 or len(usable_rs) > 3 or len(rs_without_resource_id) > 1 or len(rs_with_resource_id) > 1 or len(rs_file_upload) > 1 ): <NEW_LINE> <INDENT> raise ValueError( ( "RAML must contain one to three resources with a method of '{}'. " "At most one resource each with and without uri parameter (resource id) " "or one file upload resource.\n" "There are {} resources with matching methods. Resources in RAML: {}" ).format(usable_methods, len(usable_rs), raml.resources) ) <NEW_LINE> <DEDENT> res_normal = rs_without_resource_id[0] if rs_without_resource_id else None <NEW_LINE> res_with_id = rs_with_resource_id[0] if rs_with_resource_id else None <NEW_LINE> res_file = rs_file_upload[0] if rs_file_upload else None <NEW_LINE> return res_normal, res_with_id, res_file | Gets relevant resources from RAML
| 625941c03539df3088e2e2a0 |
def get_permission_links( self, account: str, block_num: int = 0 ) -> PermissionLinkType: <NEW_LINE> <INDENT> headers: dict = {"Authorization": f"Bearer {self.token}"} <NEW_LINE> r = requests.get( f"{self.permission_links_url}?account={account}&block_num={block_num}", headers=headers, ) <NEW_LINE> if r.status_code == requests.codes.ok: <NEW_LINE> <INDENT> response = PermissionLinkType(**r.json()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = DfuseError(**r.json()) <NEW_LINE> <DEDENT> return response | Fetches the accounts controlled by the given public key, at any block height.
GET /v0/state/permission_links
The `block_num` parameter determines for which block you want a linked authorizations snapshot. This can be anywhere in the chain’s history.
If the requested `block_num` is irreversible, you will get an immutable snapshot. If the `block_num` is still in a reversible chain,
you will get a full consistent snapshot, but it is not guaranteed to be the view that will pass irreversibility.
Inspect the returned `up_to_block_id` parameter to understand from which longest chain the returned value is a snapshot of.
https://mainnet.eos.dfuse.io/v0/state/permission_links?account=eoscanadacom&block_num=10000000 | 625941c066673b3332b91fe6 |
def validate_connectors(self, validate_outputs): <NEW_LINE> <INDENT> for runner in self._input_runners: <NEW_LINE> <INDENT> runner.validate_receive() <NEW_LINE> <DEDENT> if validate_outputs: <NEW_LINE> <INDENT> for runner in self._output_runners: <NEW_LINE> <INDENT> runner.validate_send() | Validates connectors.
:param validate_outputs: If True, output runners are validated | 625941c05fdd1c0f98dc0187 |
def convert_currency(value: float, old_currency: str, new_currency: str) -> float: <NEW_LINE> <INDENT> rates = get_currency_rates(new_currency) <NEW_LINE> return float(value) / rates.get(old_currency) | Convert `value` from old_currency to new_currency
Args:
value: the value in the old currency
old_currency: the existing currency
new_currency: the currency to convert to
Returns: value in the new currency. | 625941c0eab8aa0e5d26daac |
def gettest(gtdf, stationin, stationout, passenger, year): <NEW_LINE> <INDENT> rows = len(gtdf) <NEW_LINE> gtdf['yy_mm'] = pd.DataFrame(gtdf.Date.astype(str).str[0:7]) <NEW_LINE> gtdf['TrainPeriod'] = np.repeat(year, rows) <NEW_LINE> gtdf['StationKeyIn'] = np.repeat(stationin, rows) <NEW_LINE> gtdf['StationKeyOut'] = np.repeat(stationout, rows) <NEW_LINE> gtdf['ConcessionTypeName'] = np.repeat(passenger, rows) <NEW_LINE> col_idx = ['Date', 'Year', 'yy_mm', 'TrainPeriod', 'StationKeyIn', 'StationKeyOut', 'ConcessionTypeName'] <NEW_LINE> X_test = dummies(gtdf, col_idx) <NEW_LINE> X_test = pd.concat([X_test, gtdf[col_idx].reset_index()], axis=1) <NEW_LINE> X_test = X_test.set_index(col_idx, append=True) <NEW_LINE> X_test = X_test.drop('index', axis=1) <NEW_LINE> return X_test | A function used to generate independent test dataframe for prediction.
Parameters
----------
df : dataframe
Independent input dataframe for prediction.
year : int
Training period.
crossline : str
FactTrip Direction, e.g. IBL->IBL
media : str
Media Type, CSC or CST
concession : str
Concession Type, e.g. Adult
Returns
-------
X_test : dataframe
Return independent dataframe with combination. | 625941c0287bf620b61d39ba |
def create(self, posting): <NEW_LINE> <INDENT> response = self.createMany([posting]) <NEW_LINE> if response != None: <NEW_LINE> <INDENT> return response[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Create a new posting in the 3taps system.
'posting' should be a Posting object representing the posting to
create. Note that the posting should not include a 'postKey'
entry, as this will be allocated by the 3taps system.
We attempt to insert the new posting into the 3taps system. Upon
completion, we return a dictionary with the following entries:
'postKey'
The newly-allocated posting key for this posting.
'error'
If a problem occurred with the posting, this will be a
dictionary with 'code' and 'message' entries describing the
error that occurred. If there was no error, there won't be
an "error" entry in the response dictionary.
Note that if the 3taps server cannot be contacted for some reason,
we return None. | 625941c063d6d428bbe44444 |
def case(self): <NEW_LINE> <INDENT> if self.family.name == 'wiktionary': <NEW_LINE> <INDENT> return 'case-sensitive' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'first-letter' | Return case-sensitive if wiktionary. | 625941c01f037a2d8b946153 |
@app.route("/vec_delete", methods=["GET", "POST"]) <NEW_LINE> def vev_delete(): <NEW_LINE> <INDENT> if request.method == "GET": <NEW_LINE> <INDENT> event_id = request.args.get("event_id", type=str, default=None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event_id = request.form.get("event_id", type=str, default=None) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> judge("event_id", event_id) <NEW_LINE> delete_vec.execute_delete(DB, event_id) <NEW_LINE> del VEC_DATA[event_id] <NEW_LINE> for cameo in CAMEO2ID: <NEW_LINE> <INDENT> if event_id in CAMEO2ID[cameo]: <NEW_LINE> <INDENT> CAMEO2ID[cameo].remove(event_id) <NEW_LINE> <DEDENT> <DEDENT> return jsonify(status="success", message="success") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> trace = traceback.format_exc() <NEW_LINE> logger.error(trace) <NEW_LINE> jsonify(status="failed", message=str(trace)) | 事件向量化接口,从前端接收事件id,将事件从事件cameo字典以及npy文件中删除。
:return: 删除状态
:raise:事件id为空--ValueError | 625941c0090684286d50ec38 |
def timestamp_init(monitor_params): <NEW_LINE> <INDENT> del monitor_params <NEW_LINE> return None | Initializes the psana Detector interface for timestamp data at LCLS.
Arguments:
monitor_params (:class:`~onda.utils.parameters.MonitorParams`): an object
storing the OnDA monitor parameters from the configuration file. | 625941c09b70327d1c4e0d29 |
def get_api_group_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_group" % key ) <NEW_LINE> <DEDENT> local_var_params[key] = val <NEW_LINE> <DEDENT> del local_var_params['kwargs'] <NEW_LINE> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) <NEW_LINE> auth_settings = ['BearerToken'] <NEW_LINE> return self.api_client.call_api( '/apis/coordination.k8s.io/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIGroup', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | get_api_group # noqa: E501
get information of a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_group_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1APIGroup, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread. | 625941c0a219f33f346288c2 |
def reset_time(): <NEW_LINE> <INDENT> CEToolkit.second = 0 <NEW_LINE> CEToolkit.minute = 0 <NEW_LINE> CEToolkit.hour = 0 <NEW_LINE> parent.ui.lcdNumber_stopwatch.display("00:00:00") | Reset timer variables, makes lcd display 00:00:00. | 625941c0e76e3b2f99f3a765 |
def show(self, *args, **kwargs): <NEW_LINE> <INDENT> self.patch.set_alpha(0.0) <NEW_LINE> super(Plot, self).show(*args, **kwargs) | Display the current figure
| 625941c0fff4ab517eb2f38f |
def getResourceTemplate(self): <NEW_LINE> <INDENT> return ResourceTemplate(self.__data__, self.__user__) | Returns the metadata template for resources of this category.
Example
-------
::
my_resource_category = user.getResourceCategory(17000)
resourceTemplate = my_resource_category.getResourceTemplate()
resourceTemplate.getMetadata()
resourceTemplate.addMetadata('Vendor') | 625941c0d7e4931a7ee9de72 |
def remote_install_sdist(self, sdist_package_path): <NEW_LINE> <INDENT> if not os.path.exists(sdist_package_path): <NEW_LINE> <INDENT> self.log.exception("path '%s' doesn't exist." % sdist_package_path) <NEW_LINE> raise RuntimeError <NEW_LINE> <DEDENT> filename = os.path.basename(sdist_package_path) <NEW_LINE> with self.remote_connection() as conn: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.remote_stop_axon() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.log.info("copy file to remote machine.") <NEW_LINE> conn.put(sdist_package_path, '/tmp') <NEW_LINE> self.log.info("Copy successful") <NEW_LINE> install_cmd = 'sudo -H pip3 install /tmp/' + filename <NEW_LINE> self.log.info("Install sdist package to remote machine.") <NEW_LINE> conn.run(install_cmd) <NEW_LINE> self.log.info("Installation successful.") | Remotely upload previously created sdist_package from local host
to remote host.
:param sdist_package_path: python sdist tar.gz package
:return: None | 625941c023849d37ff7b2fe5 |
def quad_trapezoid_adapt(a, b, f, tol): <NEW_LINE> <INDENT> I1 = quad_trapezoid(a, b, f, 1) <NEW_LINE> I2 = quad_trapezoid(a, b, f, 2) <NEW_LINE> if (abs(I1-I2)/3 <= tol): <NEW_LINE> <INDENT> I = I2; <NEW_LINE> x = [ a, (a+b)/2, b ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> I1, x1 = quad_trapezoid_adapt(a, (a+b)/2, f, tol/2) <NEW_LINE> I2, x2 = quad_trapezoid_adapt((a+b)/2, b, f, tol/2) <NEW_LINE> I = I1 + I2 <NEW_LINE> x = list(set(x1).union(set(x2))) <NEW_LINE> <DEDENT> return I, x | Composite quadrature using adaptive trapezoid method.
Input
a : integration interval start
b : integration interval end
f : function reference
tol: tolerance
Output
I : integral estimation
x : nodes x-axis list | 625941c056b00c62f0f145ad |
def bcast_send(self, data): <NEW_LINE> <INDENT> for idx in range(0, self.ch.balance, -1): <NEW_LINE> <INDENT> self.sendq(data) | Send `data' to _all_ tasklets that are waiting to receive.
If there are no tasklets, this function will immediately return! | 625941c00383005118ecf539 |
def create_mfdata(file, spin=None, spin_id=None, num_frq=None, frq=None): <NEW_LINE> <INDENT> file.write("\nspin " + spin_id + "\n") <NEW_LINE> written = False <NEW_LINE> for j in range(num_frq): <NEW_LINE> <INDENT> r1, r2, noe = None, None, None <NEW_LINE> for ri_id in cdp.ri_ids: <NEW_LINE> <INDENT> if frq[j] != cdp.spectrometer_frq[ri_id]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if cdp.ri_type[ri_id] == 'R1': <NEW_LINE> <INDENT> r1 = spin.ri_data[ri_id] <NEW_LINE> r1_err = spin.ri_data_err[ri_id] <NEW_LINE> <DEDENT> elif cdp.ri_type[ri_id] == 'R2': <NEW_LINE> <INDENT> r2 = spin.ri_data[ri_id] <NEW_LINE> r2_err = spin.ri_data_err[ri_id] <NEW_LINE> <DEDENT> elif cdp.ri_type[ri_id] == 'NOE': <NEW_LINE> <INDENT> noe = spin.ri_data[ri_id] <NEW_LINE> noe_err = spin.ri_data_err[ri_id] <NEW_LINE> <DEDENT> <DEDENT> if r1: <NEW_LINE> <INDENT> file.write('%-7s%-10.3f%20.15f%20.15f %-3i\n' % ('R1', frq[j]*1e-6, r1, r1_err, 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file.write('%-7s%-10.3f%20.15f%20.15f %-3i\n' % ('R1', frq[j]*1e-6, 0, 0, 0)) <NEW_LINE> <DEDENT> if r2: <NEW_LINE> <INDENT> file.write('%-7s%-10.3f%20.15f%20.15f %-3i\n' % ('R2', frq[j]*1e-6, r2, r2_err, 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file.write('%-7s%-10.3f%20.15f%20.15f %-3i\n' % ('R2', frq[j]*1e-6, 0, 0, 0)) <NEW_LINE> <DEDENT> if noe: <NEW_LINE> <INDENT> file.write('%-7s%-10.3f%20.15f%20.15f %-3i\n' % ('NOE', frq[j]*1e-6, noe, noe_err, 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file.write('%-7s%-10.3f%20.15f%20.15f %-3i\n' % ('NOE', frq[j]*1e-6, 0, 0, 0)) <NEW_LINE> <DEDENT> written = True <NEW_LINE> <DEDENT> return written | Create the Modelfree4 input file 'mfmodel'.
@param file: The writable file object.
@type file: file object
@param spin: The spin container.
@type spin: SpinContainer instance
@param spin_id: The spin identification string.
@type spin_id str
@keyword num_frq: The number of spectrometer frequencies relaxation data was collected at.
@type num_frq: int
@keyword frq: The spectrometer frequencies.
@type frq: list of float
@return: True if file data is written, False otherwise.
@rtype: bool | 625941c0435de62698dfdba1 |
def unpack(self, binaryString): <NEW_LINE> <INDENT> if (len(binaryString) < 64): <NEW_LINE> <INDENT> return binaryString <NEW_LINE> <DEDENT> fmt = '!L' <NEW_LINE> start = 0 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.port_no,) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> fmt = '!BBBB' <NEW_LINE> start = 4 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.pad[0], self.pad[1], self.pad[2], self.pad[3]) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> fmt = '!BBBBBB' <NEW_LINE> start = 8 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.hw_addr[0], self.hw_addr[1], self.hw_addr[2], self.hw_addr[3], self.hw_addr[4], self.hw_addr[5]) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> fmt = '!BB' <NEW_LINE> start = 14 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.pad2[0], self.pad2[1]) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> self.name = binaryString[16:32].replace("\0","") <NEW_LINE> fmt = '!LLLLLLLL' <NEW_LINE> start = 32 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.config, self.state, self.curr, self.advertised, self.supported, self.peer, self.curr_speed, self.max_speed) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> return binaryString[64:] | Unpack message
Do not unpack empty array used as placeholder
since they can contain heterogeneous type | 625941c038b623060ff0ad43 |
def rollback(request): <NEW_LINE> <INDENT> workflow_id = request.GET.get('workflow_id') <NEW_LINE> if not can_rollback(request.user, workflow_id): <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> download = request.GET.get('download') <NEW_LINE> if workflow_id == '' or workflow_id is None: <NEW_LINE> <INDENT> context = {'errMsg': 'workflow_id参数为空.'} <NEW_LINE> return render(request, 'error.html', context) <NEW_LINE> <DEDENT> workflow = SqlWorkflow.objects.get(id=int(workflow_id)) <NEW_LINE> if download: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> query_engine = get_engine(instance=workflow.instance) <NEW_LINE> list_backup_sql = query_engine.get_rollback(workflow=workflow) <NEW_LINE> <DEDENT> except Exception as msg: <NEW_LINE> <INDENT> logger.error(traceback.format_exc()) <NEW_LINE> context = {'errMsg': msg} <NEW_LINE> return render(request, 'error.html', context) <NEW_LINE> <DEDENT> path = os.path.join(settings.BASE_DIR, 'downloads/rollback') <NEW_LINE> os.makedirs(path, exist_ok=True) <NEW_LINE> file_name = f'{path}/rollback_{workflow_id}.sql' <NEW_LINE> with open(file_name, 'w') as f: <NEW_LINE> <INDENT> for sql in list_backup_sql: <NEW_LINE> <INDENT> f.write(f'/*{sql[0]}*/\n{sql[1]}\n') <NEW_LINE> <DEDENT> <DEDENT> response = FileResponse(open(file_name, 'rb')) <NEW_LINE> response['Content-Type'] = 'application/octet-stream' <NEW_LINE> response['Content-Disposition'] = f'attachment;filename="rollback_{workflow_id}.sql"' <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rollback_workflow_name = f"【回滚工单】原工单Id:{workflow_id} ,{workflow.workflow_name}" <NEW_LINE> context = {'workflow_detail': workflow, 'rollback_workflow_name': rollback_workflow_name} <NEW_LINE> return render(request, 'rollback.html', context) | 展示回滚的SQL页面 | 625941c07d43ff24873a2bf4 |
def test_myinfo(self): <NEW_LINE> <INDENT> self.driver.find_element_by_android_uiautomator('new UiSelector().text("我的")').click() <NEW_LINE> sleep(1) <NEW_LINE> self.driver.find_element_by_android_uiautomator('new UiSelector().text("帐号密码登录")').click() <NEW_LINE> self.driver.find_element_by_android_uiautomator( 'new UiSelector().resourceId("com.xueqiu.android:id/login_account")').send_keys("wanghao") <NEW_LINE> self.driver.find_element_by_android_uiautomator( 'new UiSelector().resourceId("com.xueqiu.android:id/login_password")').send_keys("123456") <NEW_LINE> self.driver.find_element_by_android_uiautomator( 'new UiSelector().resourceId("com.xueqiu.android:id/button_next")').click() <NEW_LINE> self.driver.find_element_by_android_uiautomator( 'new UiSelector().resourceId("com.xueqiu.android:id/tab_name").text("我的")') <NEW_LINE> self.driver.find_element_by_android_uiautomator( 'new UiSelector().resourceId("com.xueqiu.android:id/title_container").childSelector(text("股票"))' ) <NEW_LINE> self.driver.find_element_by_android_uiautomator( 'new UiSelector().resourceId("com.xueqiu.android:id/stock_layout")' '.fromParent(resourceId("com.xueqiu.android:id/add_attention"))' ) | 1、点击我的,进入到个人信息页面
2、点击登录,进入到登陆页面
3、输入用户名,输入密码
4、点击登录
:return: | 625941c0d18da76e23532428 |
def __init__( self, *, value: List["SharedGalleryImage"], next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(SharedGalleryImageList, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link | :keyword value: Required. A list of shared gallery images.
:paramtype value: list[~azure.mgmt.compute.v2020_09_30.models.SharedGalleryImage]
:keyword next_link: The uri to fetch the next page of shared gallery images. Call ListNext()
with this to fetch the next page of shared gallery images.
:paramtype next_link: str | 625941c097e22403b379ceee |
def test_07_create_character_with_missing_skills(self): <NEW_LINE> <INDENT> league.start_create("Alpha") <NEW_LINE> self.assertRaises(InvalidInput, league.add_leader("James, d10, 3d8, 3d10, 3d10, " + "2d8, 3d10, 2d10, Sharp")) <NEW_LINE> self.assertRaises(InvalidInput, league.add_leader("James, d10, 3d8, 3d10, 3d10, " + "2d8, 3d10, 2d10, Sharp, Deadeye")) | try to create character with missing skills
error raised Please enter 3 abilities, you entered 1
'Invalid Input: Please Enter a valid input for abilities'
Please enter 3 abilities, you entered 2
'Invalid Input: Please Enter a valid input for abilities' | 625941c01f037a2d8b946154 |
def _root_and_conffile(self, installroot, conffile): <NEW_LINE> <INDENT> if installroot and not conffile: <NEW_LINE> <INDENT> conffile = dnf.const.CONF_FILENAME <NEW_LINE> abs_fn = os.path.join(installroot, conffile[1:]) <NEW_LINE> if os.access(abs_fn, os.R_OK): <NEW_LINE> <INDENT> conffile = abs_fn <NEW_LINE> <DEDENT> <DEDENT> if not installroot: <NEW_LINE> <INDENT> installroot = '/' <NEW_LINE> <DEDENT> if not conffile: <NEW_LINE> <INDENT> conffile = dnf.const.CONF_FILENAME <NEW_LINE> <DEDENT> return installroot, conffile | After the first parse of the cmdline options, find initial values for
installroot and conffile.
:return: installroot and conffile strings | 625941c096565a6dacc8f621 |
def sqnxt23v5_w1(**kwargs): <NEW_LINE> <INDENT> return get_squeezenext(version="23v5", width_scale=1.0, model_name="sqnxt23v5_w1", **kwargs) | 1.0-SqNxt-23v5 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Location for keeping the model parameters.
Returns:
-------
functor
Functor for model graph creation with extra fields. | 625941c03317a56b86939bb3 |
def execute_variation(testcase, variation, xp, catalog, args): <NEW_LINE> <INDENT> logging.info('[%s] Start executing variation', variation['id']) <NEW_LINE> if 'readMeFirst' in variation['data']: <NEW_LINE> <INDENT> readMeFirstURI = variation['data']['readMeFirst'] <NEW_LINE> uri = get_uri_in_zip(readMeFirstURI, catalog) if readMeFirstURI.endswith('.zip') else readMeFirstURI <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Unknown entry point in variation %s' % variation['id']) <NEW_LINE> <DEDENT> logging.info('[%s] Validating instance %s', variation['id'], uri) <NEW_LINE> instance, error_log = xbrl.Instance.create_from_url(uri, error_limit=500, catalog=catalog) <NEW_LINE> error_counts = collections.Counter() <NEW_LINE> for error in error_log: <NEW_LINE> <INDENT> if error.severity == xml.ErrorSeverity.ERROR: <NEW_LINE> <INDENT> error_counts['other'] += 1 <NEW_LINE> <DEDENT> <DEDENT> if instance: <NEW_LINE> <INDENT> for result in xp.execute(instance): <NEW_LINE> <INDENT> if result.severity == xbrl.xule.Severity.ERROR: <NEW_LINE> <INDENT> rule_name = result.effective_rule_name <NEW_LINE> if variation['results']['blockedMessageCodes'] is None or rule_name not in variation['results']['blockedMessageCodes']: <NEW_LINE> <INDENT> error_counts[rule_name] += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> passed = False if len(variation['results']['errors']) == 0 and len(error_counts) > 0 else True <NEW_LINE> for code, error in variation['results']['errors'].items(): <NEW_LINE> <INDENT> if error['count'] != error_counts[code]: <NEW_LINE> <INDENT> passed = False <NEW_LINE> <DEDENT> <DEDENT> logging.info('[%s] Finished executing variation: %s, %s', variation['id'], 'PASS' if passed else 'FAIL', dict(error_counts)) <NEW_LINE> return 'PASS' if passed else 'FAIL', error_counts | Peforms the actual XBRL instance or taxonomy validation and returns 'PASS' if the actual outcome is conformant with the result specified in the variation. | 625941c044b2445a33931fec |
def OverwriteBufferLines(startline, endline, lines): <NEW_LINE> <INDENT> orig_lines = vim.current.buffer[startline-1:endline] <NEW_LINE> sequence = difflib.SequenceMatcher(None, orig_lines, lines) <NEW_LINE> offset = startline - 1 <NEW_LINE> for tag, i1, i2, j1, j2 in reversed(sequence.get_opcodes()): <NEW_LINE> <INDENT> if tag != 'equal': <NEW_LINE> <INDENT> vim.current.buffer[i1+offset:i2+offset] = lines[j1:j2] | Overwrite lines from startline to endline in the current buffer withlines.
Computes a diff and replaces individual chunks to avoid disturbing unchanged
lines. The cursor isn't moved except where appropriate, such as when deleting
a line from above the cursor.
Args:
startline: The 1-based index of the first line to replace.
endline: The 1-based index of the last line to replace.
lines: A list of text lines to replace into the current buffer. | 625941c015baa723493c3ec9 |
def getGatingOverride(self, channel, unitCode=0): <NEW_LINE> <INDENT> resp = self.XAPCommand('GOVER', channel, unitCode=unitCode) <NEW_LINE> return bool(int(resp)) | Request the gating override on the specified channel for the specified XAP800.
unitCode - the unit code of the target XAP800
channel - the target channel (1-8, or * for all) | 625941c0167d2b6e31218aeb |
def get_total_percentage(self): <NEW_LINE> <INDENT> return sum(self._percentage.values()) | (Course) -> float
Return the sum of percentage of all categories in Course | 625941c015fb5d323cde0a62 |
def test_operator_leakage_function(): <NEW_LINE> <INDENT> grid = Grid(shape=(5, 6)) <NEW_LINE> f = Function(name='f', grid=grid) <NEW_LINE> g = TimeFunction(name='g', grid=grid) <NEW_LINE> w_f = weakref.ref(f) <NEW_LINE> w_g = weakref.ref(g) <NEW_LINE> op = Operator(Eq(f, 2 * g)) <NEW_LINE> w_op = weakref.ref(op) <NEW_LINE> del op <NEW_LINE> del f <NEW_LINE> del g <NEW_LINE> clear_cache() <NEW_LINE> assert w_f() is None <NEW_LINE> assert w_g() is None <NEW_LINE> assert w_op() is None | Test to ensure that :class:`Operator` creation does not cause
memory leaks. | 625941c07b180e01f3dc4758 |
def remap_static_url(original_url, course): <NEW_LINE> <INDENT> input_url = "'" + original_url + "'" <NEW_LINE> output_url = replace_static_urls( input_url, getattr(course, 'data_dir', None), course_id=course.location.course_id, ) <NEW_LINE> return output_url[1:-1] | Remap a URL in the ways the course requires. | 625941c0cdde0d52a9e52f86 |
def get_bundle(iss, ver_keys, bundle_file): <NEW_LINE> <INDENT> fp = open(bundle_file, 'r') <NEW_LINE> signed_bundle = fp.read() <NEW_LINE> fp.close() <NEW_LINE> return JWKSBundle(iss, None).upload_signed_bundle(signed_bundle, ver_keys) | Read a signed JWKS bundle from disc, verify the signature and
instantiate a JWKSBundle instance with the information from the file.
:param iss:
:param ver_keys:
:param bundle_file:
:return: | 625941c0956e5f7376d70dc4 |
def test_dagger_simple(): <NEW_LINE> <INDENT> wavefunction = np.array([1j, 0., 0., 0.]) <NEW_LINE> mps = MPS.from_wavefunction(wavefunction, nqudits=2, qudit_dimension=2) <NEW_LINE> assert np.allclose(mps.wavefunction(), wavefunction) <NEW_LINE> mps.dagger() <NEW_LINE> assert np.allclose(mps.wavefunction(), wavefunction.conj().T) | Tests taking the dagger of an MPS. | 625941c0fff4ab517eb2f390 |
def test_asset(self): <NEW_LINE> <INDENT> assert self.instance.asset(0) is None <NEW_LINE> assert self.session.get.call_count == 0 <NEW_LINE> self.instance.asset(1) <NEW_LINE> url = self.example_data['url'] + '/releases/assets/1' <NEW_LINE> self.session.get.assert_called_once_with( url, headers={'Accept': 'application/vnd.github.manifold-preview'} ) | Test retrieving an asset uses the right headers
The Releases section of the API is still in Beta and uses custom
headers | 625941c04c3428357757c27f |
def findSubsequences(self, nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> res = set() <NEW_LINE> self.dfs(nums, 0, [], res) <NEW_LINE> return list(res) | :type nums: List[int]
:rtype: List[List[int]] | 625941c0cc0a2c11143dcde6 |
def setUp(self): <NEW_LINE> <INDENT> self.ps = PastaSauce() <NEW_LINE> self.desired_capabilities['name'] = self.id() <NEW_LINE> if not LOCAL_RUN: <NEW_LINE> <INDENT> self.admin = Admin( use_env_vars=True, pasta_user=self.ps, capabilities=self.desired_capabilities ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.admin = Admin( use_env_vars=True, ) <NEW_LINE> <DEDENT> self.wait = WebDriverWait(self.admin.driver, Assignment.WAIT_TIME) <NEW_LINE> self.admin.login() <NEW_LINE> self.admin.goto_admin_control() | Pretest settings. | 625941c04c3428357757c280 |
def ensure_initialized(self): <NEW_LINE> <INDENT> dictionary = config.val.hints.dictionary <NEW_LINE> if not self.words or self.dictionary != dictionary: <NEW_LINE> <INDENT> self.words.clear() <NEW_LINE> self.dictionary = dictionary <NEW_LINE> try: <NEW_LINE> <INDENT> with open(dictionary, encoding="UTF-8") as wordfile: <NEW_LINE> <INDENT> alphabet = set(ascii_lowercase) <NEW_LINE> hints = set() <NEW_LINE> lines = (line.rstrip().lower() for line in wordfile) <NEW_LINE> for word in lines: <NEW_LINE> <INDENT> if set(word) - alphabet: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if len(word) > 4: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for i in range(len(word)): <NEW_LINE> <INDENT> hints.discard(word[:i + 1]) <NEW_LINE> <DEDENT> hints.add(word) <NEW_LINE> <DEDENT> self.words.update(hints) <NEW_LINE> <DEDENT> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> error = "Word hints requires reading the file at {}: {}" <NEW_LINE> raise HintingError(error.format(dictionary, str(e))) | Generate the used words if yet uninitialized. | 625941c0167d2b6e31218aec |
@blueprint.route('/content/<author_email>/contact', methods=['POST']) <NEW_LINE> @util.require_login() <NEW_LINE> def create(author_email): <NEW_LINE> <INDENT> model = json.loads(flask.request.form.get('model')) <NEW_LINE> contact_type = model.get('type') <NEW_LINE> value = model.get('value') <NEW_LINE> listing = services.listing_service.read_by_email(author_email) <NEW_LINE> if not listing: <NEW_LINE> <INDENT> listing = services.listing_service.create_default_listing_for_user( author_email ) <NEW_LINE> <DEDENT> if not listing.get('contact_infos', None): <NEW_LINE> <INDENT> listing['contact_infos'] = [] <NEW_LINE> listing['contact_id_next'] = 0 <NEW_LINE> <DEDENT> if not listing.get('contact_id_next'): <NEW_LINE> <INDENT> contacts = listing['contact_infos'] <NEW_LINE> if len(contacts) == 0: <NEW_LINE> <INDENT> listing['contact_id_next'] = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> listing['contact_id_next'] = max( map(lambda x: x['_id'], ) ) + 1 <NEW_LINE> <DEDENT> <DEDENT> contact_dict = { 'type': contact_type, 'value': value, '_id': listing['contact_id_next'] } <NEW_LINE> listing['contact_id_next'] = listing['contact_id_next'] + 1 <NEW_LINE> listing['contact_infos'].append(contact_dict) <NEW_LINE> services.listing_service.update(listing) <NEW_LINE> return json.dumps(contact_dict) | Creates a new listing contact through the JSON-REST API.
@param author_email: The email address that the listing belongs to.
@type author_email: str
@return: JSON-encoded document describing the contact just created.
@rtype: str | 625941c06fece00bbac2d693 |
def _copy_base_conf(self): <NEW_LINE> <INDENT> self.temp_conf_dir = tempfile.mkdtemp("", "spark-", "/tmp") <NEW_LINE> if os.path.exists(self.local_base_conf_dir): <NEW_LINE> <INDENT> base_conf_files = [os.path.join(self.local_base_conf_dir, f) for f in os.listdir(self.local_base_conf_dir)] <NEW_LINE> for f in base_conf_files: <NEW_LINE> <INDENT> shutil.copy(f, self.temp_conf_dir) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.warn( "Local conf dir does not exist. Using default configuration") <NEW_LINE> base_conf_files = [] <NEW_LINE> <DEDENT> mandatory_files = [] <NEW_LINE> missing_conf_files = mandatory_files <NEW_LINE> for f in base_conf_files: <NEW_LINE> <INDENT> f_base_name = os.path.basename(f) <NEW_LINE> if f_base_name in missing_conf_files: <NEW_LINE> <INDENT> missing_conf_files.remove(f_base_name) <NEW_LINE> <DEDENT> <DEDENT> logger.info("Copying missing conf files from master: " + str( missing_conf_files)) <NEW_LINE> remote_missing_files = [os.path.join(self.conf_dir, f) for f in missing_conf_files] <NEW_LINE> action = Get([self.master], remote_missing_files, self.temp_conf_dir) <NEW_LINE> action.run() | Copy base configuration files to tmp dir. | 625941c0a79ad161976cc09b |
def add(t1: 'Tensor', t2:'Tensor') -> 'Tensor': <NEW_LINE> <INDENT> value = np.add(t1._value, t2._value, dtype=np.float32) <NEW_LINE> have_grad = t1.have_grad or t2.have_grad <NEW_LINE> ops_name = '_add' <NEW_LINE> depends_on: List[Dependency] = [] <NEW_LINE> if t1.have_grad: <NEW_LINE> <INDENT> def grad_fn_add1(grad: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> ndims_added = grad.ndim - t1._value.ndim <NEW_LINE> for _ in range(ndims_added): <NEW_LINE> <INDENT> grad = grad.sum(axis=0, dtype=np.float32) <NEW_LINE> <DEDENT> for i, dim in enumerate(t1.shape): <NEW_LINE> <INDENT> if dim == 1: <NEW_LINE> <INDENT> grad = grad.sum(axis=i, keepdims=True, dtype=np.float32) <NEW_LINE> <DEDENT> <DEDENT> return grad <NEW_LINE> <DEDENT> ops_name = '_add1' <NEW_LINE> depends_on.append(T.Dependency(t1, grad_fn_add1, ops_name)) <NEW_LINE> <DEDENT> if t2.have_grad: <NEW_LINE> <INDENT> def grad_fn_add2(grad: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> ndims_added = grad.ndim - t2._value.ndim <NEW_LINE> for _ in range(ndims_added): <NEW_LINE> <INDENT> grad = grad.sum(axis=0, dtype=np.float32) <NEW_LINE> <DEDENT> for i, dim in enumerate(t2.shape): <NEW_LINE> <INDENT> if dim == 1: <NEW_LINE> <INDENT> grad = grad.sum(axis=i, keepdims=True, dtype=np.float32) <NEW_LINE> <DEDENT> <DEDENT> return grad <NEW_LINE> <DEDENT> ops_name = '_add2' <NEW_LINE> depends_on.append(T.Dependency(t2, grad_fn_add2, ops_name)) <NEW_LINE> <DEDENT> return T.Tensor(value, have_grad, depends_on) | Addition of two `Tensor`. Also it is calculate its gradient of operation
if one of tensor have_grad = True. | 625941c0e5267d203edcdbf5 |
def onEntry(self,comingFrom,transitionType): <NEW_LINE> <INDENT> super(iGyneSecondRegistrationStep, self).onEntry(comingFrom, transitionType) <NEW_LINE> pNode = self.parameterNode() <NEW_LINE> volumeNode = slicer.app.layoutManager().sliceWidget("Red").sliceLogic().GetBackgroundLayer().GetVolumeNode() <NEW_LINE> if pNode.GetParameter('skip') != '1' and volumeNode != None: <NEW_LINE> <INDENT> lm = slicer.app.layoutManager() <NEW_LINE> lm.setLayout(3) <NEW_LINE> pNode = self.parameterNode() <NEW_LINE> labelsColorNode = slicer.modules.colors.logic().GetColorTableNodeID(10) <NEW_LINE> self.saveInitialRegistration() <NEW_LINE> pNode.SetParameter('currentStep', self.stepid) <NEW_LINE> if pNode.GetParameter('followupTransformID')!=None and slicer.util.getNode('Segmentation Model')==None: <NEW_LINE> <INDENT> self.applyModelMaker() <NEW_LINE> <DEDENT> self.t0 = time.clock() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.workflow().goForward() | Update GUI and visualization | 625941c09c8ee82313fbb6ca |
def get_welcome_response(): <NEW_LINE> <INDENT> session_attributes = {} <NEW_LINE> card_title = "Welcome" <NEW_LINE> speech_output = "Welcome to the Alexa Skills Kit sample. " "I can give you 3 movies that are currently playing in local theatres, " <NEW_LINE> reprompt_text = "Please say give me three movies playing today " <NEW_LINE> should_end_session = False <NEW_LINE> return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session)) | If we wanted to initialize the session to have some attributes we could
add those here | 625941c0d268445f265b4dc4 |
def make_negative_examples_from_searches(json_path, path_to_data): <NEW_LINE> <INDENT> with open(json_path) as ff: <NEW_LINE> <INDENT> data = load(ff) <NEW_LINE> <DEDENT> products = pd.read_csv(path_to_data + '/products.csv') <NEW_LINE> products_categories = pd.read_csv(path_to_data + '/products_categories.csv') <NEW_LINE> def query_function(df): <NEW_LINE> <INDENT> query = [] <NEW_LINE> product_external_id = [] <NEW_LINE> for i in range(len(df)): <NEW_LINE> <INDENT> product_external_id.append(list(df[i]['products'].keys())[0]) <NEW_LINE> query.append(df[i]['query']) <NEW_LINE> i+=1 <NEW_LINE> <DEDENT> data_query = pd.DataFrame({'query': query, 'external_id': product_external_id}) <NEW_LINE> data_query['external_id'] = pd.to_numeric(data_query['external_id']) <NEW_LINE> return data_query <NEW_LINE> <DEDENT> dd = query_function(data) <NEW_LINE> dd = pd.merge(dd, products, on='external_id') <NEW_LINE> dd = dd[['query', 'external_id', 'name']] <NEW_LINE> list_of_query = [] <NEW_LINE> count = 0 <NEW_LINE> for i in range(len(dd)): <NEW_LINE> <INDENT> if (re.sub("[^а-яА-Яa-zA-Z0-9]", "", dd.loc[i, 'query'].lower()) == re.sub("[^а-яА-Яa-zA-Z0-9]", "", dd.loc[i, 'name'].lower())): <NEW_LINE> <INDENT> list_of_query.append(dd.loc[i, 'query']) <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> <DEDENT> dd = dd[dd['query'].isin(list_of_query)] <NEW_LINE> del dd['name'] <NEW_LINE> searches = query_function(data[:1500]) <NEW_LINE> searches = pd.concat([searches, dd]) <NEW_LINE> searches = pd.merge(searches, merge_product_external_id_to_categories(products, products_categories), on='external_id') <NEW_LINE> searches.drop_duplicates(subset=['query'], inplace=True, ignore_index=True) <NEW_LINE> searches['category_id_not_redir'] = searches['category_id'].apply(lambda x: get_cousin_id(x)) <NEW_LINE> return searches | Using file "420_searches.json"
1) Взять для каждого продукта категории и найти дальнюю категорию
2) Для каждого продукта сохранить продукт + неподходящая категория
3) Сформировать DataFrame
:param json_path: list of dicts
:param external_id_to_category: результат работы ф-ии merge_product_external_id_to_categories
:param category_tree: anytree.Node(идея использования дерева - брать не прямого предка/потомка, а "брата-сестру"/"кузенов"/"тетю-дядю")
:return: pd.DataFrame with columns = [query: str, category_id: int]
Example of dict:
{'query': '0 70',
'amount': 1,
'products': {
'89072600018': '1',
'89072600022': '1',
'89072600015': '42',}} | 625941c03cc13d1c6d3c72d1 |
def exchanging_step(self): <NEW_LINE> <INDENT> self.exchanger.set_lymphocytes_to_exchange(self.lymphocytes[:]) <NEW_LINE> others = self.exchanger.get_lymphocytes() <NEW_LINE> self.lymphocytes = self.lymphocytes + others <NEW_LINE> sorted_lymphocytes = self._get_sorted_lymphocytes_index_and_value() <NEW_LINE> best = [] <NEW_LINE> for (i, e) in sorted_lymphocytes[:self.config.number_of_lymphocytes]: <NEW_LINE> <INDENT> best.append(self.lymphocytes[i]) <NEW_LINE> <DEDENT> self.lymphocytes = best | Represents the step when we're getting lymphocytes from the other node.
Take some lymphocytes from the exchanger and merge them with current available.
Also set new lymphocytes to exchange (exactly - copy of them) | 625941c066656f66f7cbc100 |
def _getSubTreeHeight(self, curr): <NEW_LINE> <INDENT> if curr == None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return curr.getHeight() + 1 | given a node, get height of node's subtree | 625941c0287bf620b61d39bb |
def create_table(conn, sql): <NEW_LINE> <INDENT> if sql is not None and sql != '': <NEW_LINE> <INDENT> cu = get_cursor(conn) <NEW_LINE> if SHOW_SQL: <NEW_LINE> <INDENT> print('执行sql:[{}]'.format(sql)) <NEW_LINE> <DEDENT> cu.execute(sql) <NEW_LINE> conn.commit() <NEW_LINE> print('创建数据库表成功!') <NEW_LINE> close_all(conn, cu) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('the [{}] is empty or equal None!'.format(sql)) | 创建数据库表:student | 625941c03346ee7daa2b2cc0 |
def _ImportPythonModule(module_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module_object = list(map(__import__, [module_name]))[0] <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if '.' in module_name: <NEW_LINE> <INDENT> for submodule_name in module_name.split('.')[1:]: <NEW_LINE> <INDENT> module_object = getattr(module_object, submodule_name, None) <NEW_LINE> <DEDENT> <DEDENT> return module_object | Imports a Python module.
Args:
module_name (str): name of the module.
Returns:
module: Python module or None if the module cannot be imported. | 625941c05f7d997b871749eb |
def excerpt(permission): <NEW_LINE> <INDENT> compile_time_path = [os.path.pardir, os.path.pardir, 'example', 'python', 'permissions', '{}.py'.format(permission)] <NEW_LINE> path = os.path.join(*compile_time_path) <NEW_LINE> result = [] <NEW_LINE> if not os.path.isfile(path): <NEW_LINE> <INDENT> print(path) <NEW_LINE> return result <NEW_LINE> <DEDENT> window = excerpt_boundaries(path) <NEW_LINE> result.extend(listing(compile_time_path, lines_range=window)) <NEW_LINE> return result | Renders source file listing
:param permission: name of permission to list, used as a part of filename
:return: rst lines | 625941c0f7d966606f6a9f58 |
def dict_splitter(dict_to_split: dict, sort_function: Callable): <NEW_LINE> <INDENT> dict_a = {} <NEW_LINE> dict_b = {} <NEW_LINE> for item in dict_to_split.items(): <NEW_LINE> <INDENT> if sort_function(item): <NEW_LINE> <INDENT> dict_a.update({item[0]: item[1]}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dict_b.update({item[0]: item[1]}) <NEW_LINE> <DEDENT> <DEDENT> return dict_a, dict_b | :param dict_to_split: what to split
:param sort_function: how to split function
:return: dict_a, dict_b | 625941c026238365f5f0edc1 |
def setFromPlacement(self,pl,rebase=False): <NEW_LINE> <INDENT> rot = FreeCAD.Placement(pl).Rotation <NEW_LINE> self.u = rot.multVec(FreeCAD.Vector(1,0,0)) <NEW_LINE> self.v = rot.multVec(FreeCAD.Vector(0,1,0)) <NEW_LINE> self.axis = rot.multVec(FreeCAD.Vector(0,0,1)) <NEW_LINE> if rebase: <NEW_LINE> <INDENT> self.position = pl.Base | sets the working plane from a placement (rotaton ONLY, unless rebaee=True) | 625941c05166f23b2e1a50af |
def install(self, plugin_id, source_type, value): <NEW_LINE> <INDENT> if source_type not in ('url', 'file'): <NEW_LINE> <INDENT> raise ValueError('Source can be either of "url" or "file" types.') <NEW_LINE> <DEDENT> json_data = {'url': value} if source_type == 'url' else None <NEW_LINE> data = value if source_type == 'file' else None <NEW_LINE> headers = {'Content-Type': 'multipart/form-data'} if data else None <NEW_LINE> request_path = "{api_path}{plugin_id}".format( api_path=self.api_path, plugin_id=plugin_id) <NEW_LINE> return self.connection.put_request(request_path, data=data, json_data=json_data, headers=headers) | Install a new plugin on the Gerrit server.
:param plugin_id: Plugin identifier
:param source_type: Source type: 'file'|'url'
:param value: Data source value based on source_type:
- binary data if 'file' source type
- 'url/path/to/plugin.jar' file as a string if 'url' source type | 625941c055399d3f05588609 |
def test_monopole_set(self): <NEW_LINE> <INDENT> zz = sp.random_coefs(11, 10, coef_type=sp.vector) <NEW_LINE> with self.assertRaises(AttributeError): <NEW_LINE> <INDENT> zz[0, 0] = (1, 2) | ::raise an error if I try to set monopole | 625941c094891a1f4081b9fe |
def plot_decision_boundary(theta, x, y): <NEW_LINE> <INDENT> plot_data(x[:, 1:3], y) <NEW_LINE> if x.shape[1] <= 3: <NEW_LINE> <INDENT> plot_x = x[:, 1] <NEW_LINE> plot_y = -1 / theta[2][0] * (theta[0][0] + theta[1][0] * plot_x) <NEW_LINE> plt.title("decision boundary plot") <NEW_LINE> plt.xlabel("Exam1 score") <NEW_LINE> plt.ylabel("Exam2 score") <NEW_LINE> plt.plot(plot_x, plot_y, label="boundary") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> u = np.linspace(-1, 1.5, 50) <NEW_LINE> v = np.linspace(-1, 1.5, 50) <NEW_LINE> u.shape = u.size,1 <NEW_LINE> v.shape = v.size,1 <NEW_LINE> z = np.zeros((u.shape[0], v.shape[0])) <NEW_LINE> for i in range(u.shape[0]): <NEW_LINE> <INDENT> for j in range(v.shape[0]): <NEW_LINE> <INDENT> z[i][j] = map_feature(u[i][0], v[j][0]) @ theta <NEW_LINE> <DEDENT> <DEDENT> u,v = np.meshgrid(u, v) <NEW_LINE> plt.contour(u, v, z.T, [0], colors = 'k') | :param theta: theta值 3*1
:param x: 包含一列1的输入变量矩阵 m*3
:param y: 输出变量矩阵 m*1 | 625941c03c8af77a43ae36f4 |
def calculateLogJointProbabilities(self, datum): <NEW_LINE> <INDENT> import math <NEW_LINE> logJoint = util.Counter() <NEW_LINE> for item in self.legalLabels: <NEW_LINE> <INDENT> logJoint[item] = math.log(self.py[item]) <NEW_LINE> for feat, val in datum.iteritems(): <NEW_LINE> <INDENT> prod = self.pfy[(feat, val, item)] <NEW_LINE> if prod != 0: <NEW_LINE> <INDENT> logJoint[item] += math.log(prod) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return logJoint | Returns the log-joint distribution over legal labels and the datum.
Each log-probability should be stored in the log-joint counter, e.g.
logJoint[3] = <Estimate of log( P(Label = 3, datum) )>
To get the list of all possible features or labels, use self.features and
self.legalLabels. | 625941c091f36d47f21ac446 |
def _GitVersionNameAndBuildNumber(): <NEW_LINE> <INDENT> releaseTag = _GetCurrentCommitReleaseTag() <NEW_LINE> if releaseTag: <NEW_LINE> <INDENT> splitTag = releaseTag.split('-') <NEW_LINE> return splitTag[0], splitTag[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> branchName = _GitBranchName() <NEW_LINE> if not branchName: <NEW_LINE> <INDENT> return _GetCommitRawDescription().split('-')[0], "{0}.beta-{1}".format(_GitCommitCount(), open_gee_version.get_commit_hash_from_tag('HEAD')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if _IsReleaseBranch(branchName): <NEW_LINE> <INDENT> tailTag = _GetReleaseTailTag(branchName) <NEW_LINE> return _GetReleaseVersionName(branchName), '{0}.{1}'.format(_GitBranchedCommitCount(tailTag), _GitCommitCount('HEAD', tailTag)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _GetCommitRawDescription().split('-')[0], "{0}.beta-{1}".format(_GitCommitCount(), _sanitizeBranchName(branchName)) | Get the version name and build number based on state of git
Use a tag only if HEAD is directly pointing to it and it is a
release build tag (see _GetCommitRawDescription for details)
otherwise use the branch name | 625941c08e71fb1e9831d700 |
def traffic_lights_updated(self, traffic_lights): <NEW_LINE> <INDENT> self._traffic_lights = traffic_lights.traffic_lights | callback on new traffic light list
Only used if risk should be avoided. | 625941c04f88993c3716bfc0 |
def validate_authorization_request(self, request): <NEW_LINE> <INDENT> for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> duplicate_params = request.duplicate_params <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request) <NEW_LINE> <DEDENT> if param in duplicate_params: <NEW_LINE> <INDENT> raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request) <NEW_LINE> <DEDENT> <DEDENT> if not request.client_id: <NEW_LINE> <INDENT> raise errors.MissingClientIdError(request=request) <NEW_LINE> <DEDENT> if not self.request_validator.validate_client_id(request.client_id, request): <NEW_LINE> <INDENT> raise errors.InvalidClientIdError(request=request) <NEW_LINE> <DEDENT> log.debug('Validating redirection uri %s for client %s.', request.redirect_uri, request.client_id) <NEW_LINE> if request.redirect_uri is not None: <NEW_LINE> <INDENT> request.using_default_redirect_uri = False <NEW_LINE> log.debug('Using provided redirect_uri %s', request.redirect_uri) <NEW_LINE> if not is_absolute_uri(request.redirect_uri): <NEW_LINE> <INDENT> raise errors.InvalidRedirectURIError(request=request) <NEW_LINE> <DEDENT> if not self.request_validator.validate_redirect_uri( request.client_id, request.redirect_uri, request): <NEW_LINE> <INDENT> raise errors.MismatchingRedirectURIError(request=request) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> request.redirect_uri = self.request_validator.get_default_redirect_uri( request.client_id, request) <NEW_LINE> request.using_default_redirect_uri = True <NEW_LINE> log.debug('Using default redirect_uri %s.', request.redirect_uri) <NEW_LINE> if not request.redirect_uri: <NEW_LINE> <INDENT> raise errors.MissingRedirectURIError(request=request) <NEW_LINE> <DEDENT> <DEDENT> request_info = {} <NEW_LINE> for validator in self.custom_validators.pre_auth: <NEW_LINE> <INDENT> request_info.update(validator(request)) <NEW_LINE> <DEDENT> if request.response_type is None: <NEW_LINE> <INDENT> raise errors.MissingResponseTypeError(request=request) <NEW_LINE> <DEDENT> elif not 'code' in request.response_type and request.response_type != 'none': <NEW_LINE> <INDENT> raise errors.UnsupportedResponseTypeError(request=request) <NEW_LINE> <DEDENT> if not self.request_validator.validate_response_type(request.client_id, request.response_type, request.client, request): <NEW_LINE> <INDENT> log.debug('Client %s is not authorized to use response_type %s.', request.client_id, request.response_type) <NEW_LINE> raise errors.UnauthorizedClientError(request=request) <NEW_LINE> <DEDENT> self.validate_scopes(request) <NEW_LINE> request_info.update({ 'client_id': request.client_id, 'redirect_uri': request.redirect_uri, 'response_type': request.response_type, 'state': request.state, 'request': request }) <NEW_LINE> for validator in self.custom_validators.post_auth: <NEW_LINE> <INDENT> request_info.update(validator(request)) <NEW_LINE> <DEDENT> return request.scopes, request_info | Check the authorization request for normal and fatal errors.
A normal error could be a missing response_type parameter or the client
attempting to access scope it is not allowed to ask authorization for.
Normal errors can safely be included in the redirection URI and
sent back to the client.
Fatal errors occur when the client_id or redirect_uri is invalid or
missing. These must be caught by the provider and handled, how this
is done is outside of the scope of OAuthLib but showing an error
page describing the issue is a good idea. | 625941c060cbc95b062c6499 |
def show_result(self, result, file): <NEW_LINE> <INDENT> print(Stats.data_format.format( result["time-string"], result["elapsed"], result["inserts"], result["insert-rate"], result["total"], result["total-rate"]), file=file) | show result | 625941c045492302aab5e217 |
def flatten(list_): <NEW_LINE> <INDENT> return [item for sublist in list_ for item in sublist] | Via https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists | 625941c071ff763f4b5495de |
def isNear(self, pPos2, pEpsilon=0.0001): <NEW_LINE> <INDENT> return _almathswig.Pose2D_isNear(self, pPos2, pEpsilon) | isNear(Pose2D self, Pose2D pPos2, float const & pEpsilon=0.0001) -> bool
isNear(Pose2D self, Pose2D pPos2) -> bool | 625941c0a934411ee37515e9 |
def side_effect(*args: str, **_: str) -> Any: <NEW_LINE> <INDENT> if args[0] == "urlfetch:get:json": <NEW_LINE> <INDENT> return [{"ip": "1.1.1.1"}] <NEW_LINE> <DEDENT> return mock.DEFAULT | Side effects local function | 625941c0b545ff76a8913d6c |
def _Krueger6(n, *fs6): <NEW_LINE> <INDENT> ns = [n] <NEW_LINE> for i in range(len(fs6) - 1): <NEW_LINE> <INDENT> ns.append(ns[0] * ns[i]) <NEW_LINE> <DEDENT> k6 = [0] <NEW_LINE> for fs in fs6: <NEW_LINE> <INDENT> i = len(ns) - len(fs) <NEW_LINE> k6.append(fdot(fs, *ns[i:])) <NEW_LINE> <DEDENT> return tuple(k6) | (INTERNAL) Compute the 6th-order Krüger Alpha or Beta
series per Karney 2011, 'Transverse Mercator with an
accuracy of a few nanometers', page 7, equations 35
and 36, see <http://arxiv.org/pdf/1002.1417v3.pdf>.
@param n: 3rd flatting (float).
@param fs6: 6-Tuple of coefficent tuples.
@return: 6th-Order Krüger (7-tuple, 1-origin). | 625941c0462c4b4f79d1d626 |
def __contains__(self, x): <NEW_LINE> <INDENT> return x in self.successors | Return True iff x is a node in our Digraph. | 625941c057b8e32f524833f0 |
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over you application logic', 'Is mapped manually to URLs', ] <NEW_LINE> return Response({'message':'Hello!', 'an_apiview': an_apiview}) | Returns a list of API View features | 625941c021bff66bcd6848ab |
def test_hash_release_date(self): <NEW_LINE> <INDENT> ps1_dt = datetime.datetime(2010, 1, 1, 0, 0, tzinfo=tz.utc).astimezone(pytz.timezone('America/Los_Angeles')) <NEW_LINE> ps1 = PropertyState.objects.create( organization=self.org, address_line_1='123 fake st', extra_data={'a': 'result'}, release_date=ps1_dt, data_state=DATA_STATE_IMPORT, import_file_id=0, ) <NEW_LINE> ps2 = PropertyState.objects.create( organization=self.org, address_line_1='123 fake st', extra_data={'a': 'result'}, release_date=datetime.datetime(2010, 1, 1, 0, 0, tzinfo=tz.utc), data_state=DATA_STATE_IMPORT, import_file_id=0, ) <NEW_LINE> self.assertNotEqual(str(ps1.release_date), str(ps2.release_date)) <NEW_LINE> self.assertEqual(ps1.hash_object, ps2.hash_object) | The hash_state_object method makes the timezones naive, so this should work because
the date times are equivalent, even though the database objects are not | 625941c06fb2d068a760eff1 |
def generate_template(self, cnxt, type_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return resources.global_env().get_class( type_name).resource_to_template(type_name) <NEW_LINE> <DEDENT> except exception.StackValidationFailed: <NEW_LINE> <INDENT> raise exception.ResourceTypeNotFound(type_name=type_name) <NEW_LINE> <DEDENT> except exception.NotFound as ex: <NEW_LINE> <INDENT> raise exception.StackValidationFailed(message=ex.message) | Generate a template based on the specified type.
:param cnxt: RPC context.
:param type_name: Name of the resource type to generate a template for. | 625941c04428ac0f6e5ba747 |
def rank_optimized_method_performance_by_dataset(df, dataset="Dataset", method="Method", params="Parameters", metric="F-measure", level="Level", level_range=range(5, 7), display_fields=["Method", "Parameters", "Precision", "Recall", "F-measure"], ascending=False, paired=True, parametric=True, hue=None, y_min=0.0, y_max=1.0, plotf=violinplot, label_rotation=45, color=None, color_palette=None): <NEW_LINE> <INDENT> box = dict() <NEW_LINE> for d in df[dataset].unique(): <NEW_LINE> <INDENT> for lv in level_range: <NEW_LINE> <INDENT> display(Markdown("## {0} level {1}".format(d, lv))) <NEW_LINE> df_l = df[df[level] == lv] <NEW_LINE> best, param_report = isolate_top_params(df_l[df_l[dataset] == d], method, params, metric, ascending=ascending) <NEW_LINE> method_rank = _show_method_rank( best, method, params, metric, display_fields, ascending=ascending) <NEW_LINE> results = per_method_pairwise_tests(best, group_by=method, metric=metric, paired=paired, parametric=parametric) <NEW_LINE> display(results) <NEW_LINE> box[d] = boxplot_from_data_frame( best, group_by=method, color=color, metric=metric, y_min=y_min, y_max=y_max, label_rotation=label_rotation, hue=hue, plotf=plotf, color_palette=color_palette) <NEW_LINE> box[d] = _add_significance_to_boxplots( results, method_rank, box[d]) <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> <DEDENT> return box | Rank the performance of methods using optimized parameter configuration
within each dataset in dataframe. Optimal methods are computed from the
mean performance of each method/param configuration across all datasets
in df.
df: pandas df
dataset: str
df category to use for grouping samples (by dataset)
method: str
df category to use for grouping samples (by method); these groups are
compared in plots and pairwise statistical testing.
params: str
df category containing parameter configurations for each method. Best
method configurations are computed by grouping method groups on this
category value, then finding the best average metric value.
metric: str
df category containing metric to use for ranking and statistical
comparisons between method groups.
level: str
df category containing taxonomic level information.
level_range: range
Perform plotting and testing at each level in range.
display_fields: list
List of columns in df to display in results.
ascending: bool
Rank methods my metric score in ascending or descending order?
paired: bool
Perform paired statistical test? See per_method_pairwise_tests()
parametric: bool
Perform parametric statistical test? See per_method_pairwise_tests()
To generate boxplots instead of violin plots, pass plotf=seaborn.boxplot
hue, color variables all pass directly to equivalently named variables in
seaborn.violinplot(). See boxplot_from_data_frame() for more
information. | 625941c0187af65679ca5074 |
def create_folder(folder): <NEW_LINE> <INDENT> if os.path.exists(folder): <NEW_LINE> <INDENT> response = input('{0} exists. Would you like to overwrite it? [y/n] '.format(folder)) <NEW_LINE> if response == 'y': <NEW_LINE> <INDENT> rmtree(folder) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> <DEDENT> os.makedirs(folder) <NEW_LINE> return folder | Check out folder exists and create a new one.
| 625941c0d58c6744b4257bb7 |
def blog_key(name='default'): <NEW_LINE> <INDENT> return db.Key.from_path('blogs', name) | Define Blog Key | 625941c0d7e4931a7ee9de73 |
def kb_to_mb(rss): <NEW_LINE> <INDENT> if len(rss) == 0: return rss <NEW_LINE> return [mem/1024 for mem in rss] | Converts `rss` in KB to MB
Arguments:
- `rss`: list of rss values | 625941c0711fe17d825422c6 |
def __init__(self, ln, dz, r_model, porous): <NEW_LINE> <INDENT> ln = int(ln) <NEW_LINE> self.dz = dz <NEW_LINE> self.r_model = r_model <NEW_LINE> self.porous = porous <NEW_LINE> self.max_depth_cm = (ln * dz) <NEW_LINE> n_cells = np.linspace(1, 100, ln) <NEW_LINE> if str.upper(r_model) == "UNIFORM": <NEW_LINE> <INDENT> root_pdf = np.ones(ln)/ln <NEW_LINE> <DEDENT> elif str.upper(r_model) == "NEGATIVE_EXP": <NEW_LINE> <INDENT> mu = 15 <NEW_LINE> kp = n_cells/mu <NEW_LINE> root_pdf = np.exp(-kp)/mu <NEW_LINE> <DEDENT> elif str.upper(r_model) == "GAMMA_PDF": <NEW_LINE> <INDENT> shape = 2.5 <NEW_LINE> scale = 5.0 <NEW_LINE> root_pdf = sc_gamma.pdf(n_cells, a=shape, scale=scale) <NEW_LINE> <DEDENT> elif str.upper(r_model) == "MIXTURE": <NEW_LINE> <INDENT> mu = 15 <NEW_LINE> kp = n_cells/mu <NEW_LINE> root_a = np.exp(-kp)/mu <NEW_LINE> shape = 2.5 <NEW_LINE> scale = 5.0 <NEW_LINE> root_b = sc_gamma.pdf(n_cells, a=shape, scale=scale) <NEW_LINE> w1 = 0.15 <NEW_LINE> w2 = 0.85 <NEW_LINE> root_pdf = (w1 * root_a) + (w2 * root_b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(f" {self.__class__.__name__}:" f" Wrong root density profile type: {r_model}") <NEW_LINE> <DEDENT> root_pdf = np.maximum(root_pdf, 1.0e-8) <NEW_LINE> total_area = np.sum(root_pdf)*dz <NEW_LINE> self.profile = np.atleast_1d(root_pdf/total_area) <NEW_LINE> self.f_interp = interp1d(np.linspace(0.0, ln * dz, ln), self.profile) | Default constructor of the root density object class.
:param ln: number of discrete cells that form the total root zone.
:param dz: space discretization [L: cm].
:param r_model: root density model (type). | 625941c01f5feb6acb0c4aaa |
def d2v_websites(self, weblist, sf, n, only_web=False): <NEW_LINE> <INDENT> d2v_score, d2v_rank = self.integrate.ms_d2v(weblist, n) <NEW_LINE> d2v_dict = dict() <NEW_LINE> w2v_mean, num = mean_w2v(self.db_mean_value, weblist) <NEW_LINE> tfidf_mean, num = mean_tfidf(self.tfidf_web, self.corpus, self.tfidf, self.lsi, weblist) <NEW_LINE> if not only_web: <NEW_LINE> <INDENT> for i in range(0, len(d2v_rank)): <NEW_LINE> <INDENT> item = d2v_rank[i] <NEW_LINE> w2v_s = w2v_distance(self.db_mean_value, w2v_mean, item, self.loss) <NEW_LINE> tfidf_s = tfidf_distance(self.corpus, self.tfidf, self.tfidf_web, tfidf_mean, item, self.loss) <NEW_LINE> metadata = self.inp_web_info(item) <NEW_LINE> d2v_dict[item] = metadata <NEW_LINE> scores = {'w2v': w2v_s, 'd2v': d2v_score[i], 'tfidf': tfidf_s} <NEW_LINE> d2v_dict[item]['scores'] = scores <NEW_LINE> if sf.meta_len: <NEW_LINE> <INDENT> w2v_d = metadata['metadata']['keywords_number'] <NEW_LINE> d2v_d = metadata['metadata']['desc_tokens'] <NEW_LINE> tfidf_d = metadata['metadata']['text_tokens'] <NEW_LINE> total_score = sf.score_func(w2v_score=w2v_s, d2v_score=d2v_score[i], tfidf_score=tfidf_s, key_len_out=w2v_d, des_len_out=d2v_d, txt_len_out=tfidf_d) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> total_score = sf.score_func(w2v_score=w2v_s, d2v_score=d2v_score[i], tfidf_score=tfidf_s) <NEW_LINE> <DEDENT> d2v_dict[item].update({'total_score': total_score}) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(0, len(d2v_rank)): <NEW_LINE> <INDENT> item = d2v_rank[i] <NEW_LINE> d2v_dict[item] = {} <NEW_LINE> w2v_s = w2v_distance(self.db_mean_value, w2v_mean, item, self.loss) <NEW_LINE> tfidf_s = tfidf_distance(self.corpus, self.tfidf, self.tfidf_web, tfidf_mean, item, self.loss) <NEW_LINE> if sf.meta_len: <NEW_LINE> <INDENT> w2v_d, d2v_d, tfidf_d = self.get_weight(item) <NEW_LINE> total_score = sf.score_func(w2v_score=w2v_s, d2v_score=d2v_score[i], tfidf_score=tfidf_s, key_len_out=w2v_d, des_len_out=d2v_d, txt_len_out=tfidf_d) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> total_score = sf.score_func(w2v_score=w2v_s, d2v_score=d2v_score[i], tfidf_score=tfidf_s) <NEW_LINE> <DEDENT> d2v_dict[item]['total_score'] = total_score <NEW_LINE> d2v_dict[item]['link'] = 'http://' + item <NEW_LINE> <DEDENT> <DEDENT> return d2v_dict | compute the n websites most similar according to d2v, and compute their value also in the other models | 625941c0f9cc0f698b140554 |
@pytest.fixture(scope='session') <NEW_LINE> def splinter_session_scoped_browser(): <NEW_LINE> <INDENT> return True | Override to default to test getter twice. | 625941c0cdde0d52a9e52f87 |
def __init__(self, kv, coeffs): <NEW_LINE> <INDENT> coeffs = np.asarray(coeffs) <NEW_LINE> assert coeffs.shape == (kv.numdofs,) <NEW_LINE> self.kv = kv <NEW_LINE> self.coeffs = coeffs | Create a spline function with the given knot vector and coefficients. | 625941c0e1aae11d1e749c0b |
def get_total_ionic_dipole(structure, zval_dict): <NEW_LINE> <INDENT> tot_ionic = [] <NEW_LINE> for site in structure: <NEW_LINE> <INDENT> zval = zval_dict[str(site.specie)] <NEW_LINE> tot_ionic.append(calc_ionic(site, structure, zval)) <NEW_LINE> <DEDENT> return np.sum(tot_ionic, axis=0) | Get the total ionic dipole moment for a structure.
structure: pymatgen Structure
zval_dict: specie, zval dictionary pairs
center (np.array with shape [3,1]) : dipole center used by VASP
tiny (float) : tolerance for determining boundary of calculation. | 625941c066673b3332b91fe7 |
def update_activity(self, handler): <NEW_LINE> <INDENT> now = int(time.time()) <NEW_LINE> if now - handler.last_activity < TIMEOUT_PRECISION: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> handler.last_activity = now <NEW_LINE> index = self._handler_to_timeouts.get(hash(handler), -1) <NEW_LINE> if index >= 0: <NEW_LINE> <INDENT> self._timeouts[index] = None <NEW_LINE> <DEDENT> length = len(self._timeouts) <NEW_LINE> self._timeouts.append(handler) <NEW_LINE> self._handler_to_timeouts[hash(handler)] = length | set handler to active | 625941c0b545ff76a8913d6d |
def test_stats(self): <NEW_LINE> <INDENT> output = execute(["stats", "hello"]) <NEW_LINE> self.assertIn("translated_percent", output) <NEW_LINE> output = execute(["stats", "hello/weblate"]) <NEW_LINE> self.assertIn("failing_percent", output) <NEW_LINE> output = execute(["stats", "hello/weblate/cs"]) <NEW_LINE> self.assertIn("failing_percent", output) | Project stats. | 625941c0377c676e912720ff |
def testUnknownIdentityFormat(self): <NEW_LINE> <INDENT> self.assertRaisesHttpError(400, self._tester.AddFollowers, self._cookie, self._user.private_vp_id, ['Unknown:foo']) <NEW_LINE> self.assertRaisesHttpError(400, self._tester.AddFollowers, self._cookie, self._user.private_vp_id, ['Phone:123-456-7890']) <NEW_LINE> self.assertRaisesHttpError(400, self._tester.AddFollowers, self._cookie, self._user.private_vp_id, ['Phone:123']) | ERROR: Try to add contact with unknown identity format. | 625941c0711fe17d825422c7 |
def flash(temp, press, z, temp_crit, press_crit, w, delta=None, tolerance=1e-10): <NEW_LINE> <INDENT> N = len(temp_crit) <NEW_LINE> if delta is None: <NEW_LINE> <INDENT> delta = list() <NEW_LINE> for i in range(0, N): <NEW_LINE> <INDENT> delta.append(list(np.zeros(N))) <NEW_LINE> <DEDENT> <DEDENT> if len(press_crit) and len(z) and len(w) and len(delta) is not N: <NEW_LINE> <INDENT> raise ValueError('Size of inputs do not agree.') <NEW_LINE> <DEDENT> def error(x1, x2): <NEW_LINE> <INDENT> err = 0 <NEW_LINE> for i in range(0, N): <NEW_LINE> <INDENT> err += (x1[i] - x2[i]) ** 2 / (x1[i] * x2[i]) <NEW_LINE> <DEDENT> return err <NEW_LINE> <DEDENT> K_prev = np.array(np.ones(N) * 0.5) <NEW_LINE> K = np.array(np.ones(N) * 0.1) <NEW_LINE> err = error(K, K_prev) <NEW_LINE> x, y, nL = 0, 0, 0 <NEW_LINE> while np.abs(err) > tolerance: <NEW_LINE> <INDENT> K_prev = copy(K) <NEW_LINE> x, y, nL = RachfordRice(z, K, tolerance) <NEW_LINE> phi_L, phi_G = fugacity(temp, press, temp_crit, press_crit, x, y, z, w, delta) <NEW_LINE> K = np.exp(phi_L - phi_G) <NEW_LINE> err = error(K, K_prev) <NEW_LINE> <DEDENT> return x, y, nL | Multicomponent flash calculation for the Peng-Robinson Equation of State.
:param temp: Current Temperature, T (K)
:type temp: float
:param press: Current Pressure, P (Pa)
:type press: float
:param z: Vector that contains the composition of the mixture (unitless)
:param temp_crit: Vector of Critical Temperature, Tc (K)
:param press_crit: Vector of Critical Pressure, Pc (Pa)
:param w: Vector of Acentric Factor, omega (unitless)
:param delta: Square matrix containing the binary interaction coefficients
:param tolerance: Tolerance control (fraction)
:type tolerance: float
:return: Vector containing the liquid composition by component, x
:return: Vector containing the gas composition by component, y
:return: Molar specific volume of the liquid, VL
:return: Molar specific volume of the gas, VG
:return: Liquid Fraction, nL | 625941c02c8b7c6e89b35719 |
def crc_update(crc, data): <NEW_LINE> <INDENT> if type(data) != array.array or data.itemsize != 1: <NEW_LINE> <INDENT> buf = array.array("B", data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> buf = data <NEW_LINE> <DEDENT> crc = crc ^ _MASK <NEW_LINE> for b in buf: <NEW_LINE> <INDENT> table_index = (crc ^ b) & 0xff <NEW_LINE> crc = (CRC_TABLE[table_index] ^ (crc >> 8)) & _MASK <NEW_LINE> <DEDENT> return crc ^ _MASK | Update CRC-32C checksum with data.
Args:
crc: 32-bit checksum to update as long.
data: byte array, string or iterable over bytes.
Returns:
32-bit updated CRC-32C as long. | 625941c08e71fb1e9831d701 |
def get_survey_code_translation(survey_id, person=None): <NEW_LINE> <INDENT> if not valid_survey_id(survey_id): <NEW_LINE> <INDENT> raise InvalidSurveyID(survey_id) <NEW_LINE> <DEDENT> url = "/rest/webq/v2/survey/{}/code-translation".format(survey_id) <NEW_LINE> headers = {"Accept": "text/csv"} <NEW_LINE> if person is not None: <NEW_LINE> <INDENT> headers["X-UW-Act-as"] = person.uwnetid <NEW_LINE> <DEDENT> return get_resource(url, headers) | Returns the survey code translation table as a .csv file | 625941c0ac7a0e7691ed4027 |
def _start_connection_setup(self): <NEW_LINE> <INDENT> logger.info("We are connected[%s], request connection setup", self.link_uri) <NEW_LINE> self.log.refresh_toc(self._log_toc_updated_cb, self._toc_cache) | Start the connection setup by refreshing the TOCs | 625941c0ec188e330fd5a6fa |
def __init__(self): <NEW_LINE> <INDENT> logging.debug('HtcpGui initialized') <NEW_LINE> self.settings = {} <NEW_LINE> self.acpi_socket = create_acpi_socket() <NEW_LINE> self.screen_mode = current_screen_mode() <NEW_LINE> self.gui_needed = False <NEW_LINE> self.gui_process = None <NEW_LINE> self.stay_running = False <NEW_LINE> self.last_record_check = 0 <NEW_LINE> self.last_screen_check = 0 | initializes a new instance of HtpcGui
:return: HtpcGui | 625941c03c8af77a43ae36f5 |
def apply_movement(self): <NEW_LINE> <INDENT> potential_boxes = 0 <NEW_LINE> potential_boxes_range = 0 <NEW_LINE> potential_boxes_extra = 0 <NEW_LINE> nb_range_collected = 0 <NEW_LINE> nb_bomb_collected = 0 <NEW_LINE> me_x = self.me[0] <NEW_LINE> me_y = self.me[1] <NEW_LINE> if self.action == ACT_BOMB: <NEW_LINE> <INDENT> max_timer = 8 <NEW_LINE> for pos in self.impacted_by_flames_from_me: <NEW_LINE> <INDENT> map_item = pos[2] <NEW_LINE> if 1 < map_item < max_timer: max_timer = map_item <NEW_LINE> elif map_item == INT_BOX: <NEW_LINE> <INDENT> self.score += 30 <NEW_LINE> <DEDENT> elif map_item == INT_BOX_RANGE: <NEW_LINE> <INDENT> self.score += 30 <NEW_LINE> <DEDENT> elif map_item == INT_BOX_EXTRA: <NEW_LINE> <INDENT> self.score += 30 <NEW_LINE> <DEDENT> <DEDENT> self.area[me_y, me_x] = max_timer <NEW_LINE> new_bomb = (me_x, me_y, self.my_id, self.bomb_range, max_timer) <NEW_LINE> self.bombs.append(new_bomb) <NEW_LINE> self.nb_remain_bombs -= 1 <NEW_LINE> <DEDENT> self.me = (self.move[0], self.move[1], self.me[2]) <NEW_LINE> me_x = self.me[0] <NEW_LINE> me_y = self.me[1] <NEW_LINE> map_item = self.area[me_y, me_x] <NEW_LINE> if map_item == INT_ITEM_RANGE: <NEW_LINE> <INDENT> self.bomb_range += 1 <NEW_LINE> self.score += 13 <NEW_LINE> self.area[me_y, me_x] = INT_EMPTY <NEW_LINE> <DEDENT> elif map_item == INT_ITEM_EXTRA: <NEW_LINE> <INDENT> self.nb_remain_bombs += 1 <NEW_LINE> self.max_bombs += 1 <NEW_LINE> self.score += 15 <NEW_LINE> self.area[me_y, me_x] = INT_EMPTY <NEW_LINE> <DEDENT> min_distance = 30 <NEW_LINE> for box in self.boxes: <NEW_LINE> <INDENT> dist = abs(box[0] - me_x) + abs(box[1] - me_y) <NEW_LINE> if dist < min_distance: <NEW_LINE> <INDENT> min_distance = dist <NEW_LINE> <DEDENT> <DEDENT> self.score += int((30 - min_distance)/3) | Apply the movement for the current turn | 625941c0c4546d3d9de72988 |
def moving_average(a, n=15): <NEW_LINE> <INDENT> ret = np.cumsum(a.filled(0)) <NEW_LINE> ret[n:] = ret[n:] - ret[:-n] <NEW_LINE> counts = np.cumsum(~a.mask) <NEW_LINE> counts[n:] = counts[n:] - counts[:-n] <NEW_LINE> ret[~a.mask] /= counts[~a.mask] <NEW_LINE> ret[a.mask] = np.nan <NEW_LINE> return ret | Moving Average | 625941c0f548e778e58cd4d3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.