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(... | 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_a... | 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 <... | 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.un... | 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
... | 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.ur... | 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 == r... | 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 immut... | 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'] = n... | 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, ... | 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 dicti... | 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... | 事件向量化接口,从前端接收事件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>... | 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 ... | 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 sel... | 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,... | 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] != ... | 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 spec... | 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' <NE... | 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> <IND... | 展示回滚的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 UiS... | 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, " ... | 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>... | 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.
Retur... | 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, catal... | 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> <INDEN... | 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 ... | 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_... | 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(), wavefunctio... | 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/... | 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.adm... | 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... | 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 = servi... | 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... | 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: ... | 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 pNod... | 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... | 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_L... | 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
:par... | 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 = [] ... | 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, c... | 创建数据库表: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... | 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> r... | 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.upd... | :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.posi... | 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 == '... | 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_LI... | :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)... | 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 bran... | 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.InvalidRe... | 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 t... | 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-tupl... | 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... | 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_sta... | 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_LI... | 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... | 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
... | 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> <DEDEN... | 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>... | 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, web... | 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... | 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.ass... | 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> se... | 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) an... | 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)... | 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 <... | 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 ... | 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 <NE... | 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> <INDE... | 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.