code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def proof_of_work(self, last_proof): <NEW_LINE> <INDENT> proof = 0 <NEW_LINE> while self.valid_proof(last_proof, proof) is False: <NEW_LINE> <INDENT> proof += 1 <NEW_LINE> <DEDENT> return proof | Simple Proof of Work Algorithm:
- Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p'
- p is the previous proof, and p' is the new proof
:param last_proof: <int>
:return: <int> | 625941dd7d43ff24873a2fca |
def behead(self): <NEW_LINE> <INDENT> split = self.data.find(' ') <NEW_LINE> if split == -1: <NEW_LINE> <INDENT> return (self.data,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> word = self.data[:split] <NEW_LINE> rest = StaticSentence(self.data[split + 1:]) <NEW_LINE> return (word, rest) | Returns a tuple consisting of the first word and a sentence
with the of the sentence after the first word. | 625941dd63d6d428bbe44818 |
@pytest.mark.system <NEW_LINE> @pytest.mark.slow <NEW_LINE> def test_sklearn_tensor(tmpdir): <NEW_LINE> <INDENT> modelDirectory = str(tmpdir.mkdir("model")) <NEW_LINE> K, M_train, M_test = 3, [500, 100, 50], [500, 100, 50] <NEW_LINE> lrData = LowRank(rank=K, M_train=M_train, M_test=M_test) <NEW_LINE> priors, K, dtype =... | Tests the sk-learn interface of the tensor factorisation estimator.
The test creates a `DECOMPOSE` object and applies its `fit_transform`
method to some low rank training data. The learned filter banks have
to reconstruct the data very well. Then unseen test data is transformed
into the learned basis. The test data ha... | 625941dd3346ee7daa2b3095 |
@click.group() <NEW_LINE> @click.option("-l", "--log-level", default="info", type=click.Choice(LOG_LEVEL_CODES.keys()), help="Logging level") <NEW_LINE> @click.pass_context <NEW_LINE> def cli(ctx, log_level): <NEW_LINE> <INDENT> ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} | Run kibitzr COMMAND --help for detailed descriptions | 625941dd23e79379d52ee888 |
def great_circle(self, lon1, lat1, lon2, lat2, arc='full'): <NEW_LINE> <INDENT> x1, y1, z1 = self.cartesian(np.radians(lon1), np.radians(lat1)) <NEW_LINE> x2, y2, z2 = self.cartesian(np.radians(lon2), np.radians(lat2)) <NEW_LINE> u = np.array([x1, y1, z1]) <NEW_LINE> v = np.array([x2, y2, z2]) <NEW_LINE> w = np.cross(n... | Create a great circle between two points.
Parameters:
-----------
lon1, lat1 : The longitude/latitude of first point
lon2, lat2 : The longitude/latitude of second point
arc : ['full','long','short'] which arc segment to draw
Returns:
--------
matplotlib.plot | 625941dda05bb46b383ecb47 |
def rzz(self, theta, qubit1, qubit2): <NEW_LINE> <INDENT> return self.append(RZZGate(theta), [qubit1, qubit2], []) | Apply :class:`~qiskit.extensions.standard.RZZGate`. | 625941dd566aa707497f488d |
def transfer(system, image_path, metadata_path=None, logger=None): <NEW_LINE> <INDENT> if metadata_path is not None: <NEW_LINE> <INDENT> copy_file(metadata_path, system, logger) <NEW_LINE> <DEDENT> if copy_file(image_path, system, logger): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if logger is not None: <NEW_... | transfer an image and its metadata to the system | 625941dd55399d3f055889dd |
def update_subtasks(self, total=0, on=0): <NEW_LINE> <INDENT> if total != 0: <NEW_LINE> <INDENT> percent = (on * 100) / total <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> percent = 0 <NEW_LINE> <DEDENT> count = "%d/%d" % (on, total) <NEW_LINE> self.title = REGEX_SUBTASK.sub("[%s]" % (count), self.title) <NEW_LINE> sel... | Update subtask information for current heading
:total: total # of top level checkboxes
:on: # of top level checkboxes which are on | 625941dd32920d7e50b284fb |
def inorderTraversal(self, root): <NEW_LINE> <INDENT> res = [] <NEW_LINE> self.in_order_traverse(root, res) <NEW_LINE> return res | :type root: TreeNode
:rtype: List[int] | 625941dd3c8af77a43ae3acb |
def set_virt_auto_boot(self, num): <NEW_LINE> <INDENT> if num == "<<inherit>>": <NEW_LINE> <INDENT> self.virt_auto_boot = "<<inherit>>" <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> inum = int(num) <NEW_LINE> if (inum == 0) or (inum == 1): <NEW_LINE> <INDENT> self.virt_auto_boot = inum <NEW_LINE> retur... | For Virt only.
Specifies whether the VM should automatically boot upon host reboot 0 tells Koan not to auto_boot virtuals.
:param self: The object where the virt auto boot should be set for.
:param num: May be "0" (disabled) or "1" (enabled)
:type num: int | 625941dd8da39b475bd6529f |
def delay(self, delay_time): <NEW_LINE> <INDENT> self.start(delay_time, 1) | Start the timer with a delay. | 625941dd44b2445a339323bc |
def expand(self, names=None, rank_method=None, thresholds=None): <NEW_LINE> <INDENT> conf = ResourceLocator.default().get_conf() <NEW_LINE> if not names: <NEW_LINE> <INDENT> node = conf.get(["rose-host-select", "default"], no_ignore=True) <NEW_LINE> if node: <NEW_LINE> <INDENT> names = [node.value] <NEW_LINE> <DEDENT> ... | Expand each name in names, and look up rank method for each name.
names, if specified, should be a list of host names or known groups in
the site / user configuration file. Otherwise, the default setting in
the site / user configuration file will be used.
rank_method, if specified, should be the name of a supported r... | 625941dd21a7993f00bc801d |
def zip(path_input, path_output, pw=''): <NEW_LINE> <INDENT> path_7z = r'C:\Program Files\7-Zip\7z.exe' <NEW_LINE> path_7z = str(Path(path_7z)) <NEW_LINE> command = [path_7z, 'a', path_output, path_input, '-mx0', '-p' + pw, '-mhe' ] <NEW_LINE> sp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STD... | Creates a 7z container for path_input in path_output with password pw.
:return: True, when zip operation ended without any warnings and errors, else False. | 625941dd91f36d47f21ac81d |
def supports_maybe(self, capabilities): <NEW_LINE> <INDENT> return javabridge.call(self.jobject, "supportsMaybe", "(Lweka/core/Capabilities;)Z", capabilities.jobject) | Returns true if the currently set capabilities support (or have a dependency) at least all of the
capabilities of the given Capabilities object (checks only the enum!)
:param capabilities: the capabilities to check
:type capabilities: Capabilities
:return: whether the current capabilities (potentially) support the spec... | 625941dd7cff6e4e81117cad |
@check_login_required <NEW_LINE> @check_local_site_access <NEW_LINE> def bug_url(request, review_request_id, bug_id, local_site=None): <NEW_LINE> <INDENT> review_request, response = _find_review_request(request, review_request_id, local_site) <NEW_LINE> if not review_request: <NEW_LINE> <INDENT> return response ... | Redirects user to bug tracker issue page. | 625941dd8c0ade5d55d3ece5 |
def parse_date(raw_date): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return email.utils.parsedate_to_datetime(raw_date) <NEW_LINE> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> log.exception(f'error in parsing date: "{raw_date}" {str(e)}') <NEW_LINE> return None | Parse the date format inside emails, returning `None` if failed. | 625941dd76e4537e8c35199d |
@Issue(2517) <NEW_LINE> def revert_after_manual_conflict_resolution__text(sbox): <NEW_LINE> <INDENT> sbox.build() <NEW_LINE> wc_dir_1 = sbox.wc_dir <NEW_LINE> wc_dir_2 = sbox.add_wc_path('other') <NEW_LINE> svntest.actions.duplicate_dir(wc_dir_1, wc_dir_2) <NEW_LINE> iota_path_1 = os.path.join(wc_dir_1, 'iota') <NEW_LI... | revert after manual text-conflict resolution | 625941ddad47b63b2c50a2a6 |
@with_connection <NEW_LINE> def apply_async(task, args=None, kwargs=None, countdown=None, eta=None, task_id=None, publisher=None, connection=None, connect_timeout=None, **options): <NEW_LINE> <INDENT> if conf.ALWAYS_EAGER: <NEW_LINE> <INDENT> return apply(task, args, kwargs, task_id=task_id) <NEW_LINE> <DEDENT> task = ... | Run a task asynchronously by the celery daemon(s).
:param task: The task to run (a callable object, or a :class:`Task`
instance
:keyword args: The positional arguments to pass on to the
task (a ``list``).
:keyword kwargs: The keyword arguments to pass on to the task (a ``dict``)
:keyword countdown: Number o... | 625941dde76e3b2f99f3ab2f |
def find_file(self, filename, readonly=False, other=False, force=False): <NEW_LINE> <INDENT> if filename not in self.filenames() or force: <NEW_LINE> <INDENT> self._open_file(filename, new=other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> found = False <NEW_LINE> for tab in vim.tabpages: <NEW_LINE> <INDENT> for win ... | Originally coming from Emacs, so the definition is the same as
the Emacs Lisp function find-file ... "
(find-file FILENAME &optional WILDCARDS)
Edit file FILENAME.
Switch to a buffer visiting file FILENAME,
creating one if none already exists. | 625941dda4f1c619b28b035a |
def _compare_image_pairs(self, pair1, pair2): <NEW_LINE> <INDENT> sumD1 = pair1[1].D + pair1[0].D <NEW_LINE> sumD2 = pair2[1].D + pair2[0].D <NEW_LINE> cond_H = (abs((pair1[0].H - pair2[0].H)/pair1[0].H) < self.tol and abs((pair1[1].H - pair2[1].H)/pair1[1].H) < self.tol) <NEW_LINE> cond_sumD = abs((sumD1 - sumD2)/(sum... | Compare two pairs of boreholes or segments and return True if the two
pairs have the same FLS solution for mirror sources.
Parameters
----------
pair1 : Tuple of Borehole objects
First pair of boreholes or segments.
pair2 : Tuple of Borehole objects
Second pair of boreholes or segments.
Returns
-------
simila... | 625941dd6aa9bd52df0370cd |
def _format_tree(self: "Task", depth: int = 0) -> Iterator[str]: <NEW_LINE> <INDENT> indent = " " * depth <NEW_LINE> bullet = "- " if depth != 0 else "" <NEW_LINE> suffix = ":" if self.subtasks else "" <NEW_LINE> line = "{indent}{bullet}{self.name}{suffix}".format(**locals()) <NEW_LINE> yield line <NEW_LINE> for n i... | Generates task and subtasks into a string formatted tree | 625941ddc4546d3d9de72d5f |
def face_urls(self, urls, local_ids=None, meta=None): <NEW_LINE> <INDENT> return self._multi_dataurl_op(urls, ['facedet'], model=None, local_ids=local_ids, meta=meta, select_classes=None, language=None) | Get face detections from a url or list of urls.
Args:
urls: a single url for the input data to be processed or a list of urls
for a set of data to be processed. Note: all urls must be publically
accessible.
model: specifies the desired model to use for processing of the data.
local_ids: a single string identifie... | 625941ddc432627299f04f70 |
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> curr=head <NEW_LINE> while curr and curr.next: <NEW_LINE> <INDENT> if curr.val==curr.next.val: <NEW_LINE> <INDENT> curr.next=curr.necx.next <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> curr=curr.next <NEW_LINE> <DEDENT> <DEDENT> return head | :type head: ListNode
:rtype: ListNode | 625941ddbf627c535bc134f8 |
def compress_whitespaces(some_string): <NEW_LINE> <INDENT> return compress_whitespace_regex.sub(' ', some_string) | Compresses whitespaces within a given string | 625941dde8904600ed9f2259 |
def test_account_info_not_allowed_account(app, example_cern_openid): <NEW_LINE> <INDENT> client = app.test_client() <NEW_LINE> app.config['OAUTHCLIENT_CERN_OPENID_ALLOWED_ROLES'] = [ 'another cern role' ] <NEW_LINE> ioc = app.extensions['oauthlib.client'] <NEW_LINE> client.get(url_for('invenio_oauthclient.login', remot... | Test account info extraction. | 625941dda8ecb033257d33f4 |
def stepwiseRadon2D(self, angleIndex): <NEW_LINE> <INDENT> CT = CTScan(self.inputImage) <NEW_LINE> angle = self.radon_angles_array[angleIndex] <NEW_LINE> values = CT.onePassRadon(angle) <NEW_LINE> valueIndex = 0 <NEW_LINE> valueCount = len(values) <NEW_LINE> for value in values: <NEW_LINE> <INDENT> self.radonOutput[val... | Do one pass of radon , return list of 1D values | 625941ddbaa26c4b54cb1445 |
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.internal is None: <NEW_LINE> <INDENT> self.internal = custom_msgs.msg.Internal() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE... | unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str`` | 625941dd55399d3f055889de |
def _replace_expand(self, m, repl): <NEW_LINE> <INDENT> if self.engine.isre(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> new = m.expand(repl) <NEW_LINE> <DEDENT> except re.error: <NEW_LINE> <INDENT> self.engine.report_error(repl, 'Invalid Replace Expression') <NEW_LINE> new = None <NEW_LINE> <DEDENT> <DEDENT> else: ... | Expand replacement text if regular expression. | 625941dd2c8b7c6e89b35ae7 |
def append_list(self, list1, list2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lst = list1.extend(list2) <NEW_LINE> return lst <NEW_LINE> <DEDENT> except (AttributeError, TypeError): <NEW_LINE> <INDENT> raise AssertionError('Input variables should be lists') | Appends a whole list to another one
Appends list2 to list1.
:param list1: The list to which we are going to append the other one
:param list2: The list to be append
:type list1: List
:type list2: List
:returns: A new list comprising the two previous ones.
:rtype: List
:raises: AssertionError | 625941dd4e4d5625662d46fc |
def desti_path_table(source_table, desti_dir): <NEW_LINE> <INDENT> desti_dir = resolve(desti_dir) <NEW_LINE> if desti_dir.exists() and (not desti_dir.is_dir()): <NEW_LINE> <INDENT> msg = "destination path exists but is NOT a directory." <NEW_LINE> raise e.ValidationError(msg) <NEW_LINE> <DEDENT> desti_table = source_ta... | Return a dataframe representing information for the destination paths.
Args:
source_table (DataFrame): Table containing info about the source paths.
desti_dir (Path): Path object representing the directory where we should
copy the paths represented in ``source_table``.
Returns:
DataFrame | 625941dd30dc7b7665901c8c |
def immediateFinishPractice(dynamicId,characterId,payType,payNum): <NEW_LINE> <INDENT> player = PlayersManager().getPlayerByID(characterId) <NEW_LINE> if not player or not player.CheckClient(dynamicId): <NEW_LINE> <INDENT> return {'result':False,'message':Lg().g(18)} <NEW_LINE> <DEDENT> data = player.practice.immediate... | 立即完成修炼
@param dynamicId: int 客户端的动态id
@param characterId: int 角色的id
@param payType: int 支付类型
@param payNum: int 支付的数量 | 625941ddcad5886f8bd27301 |
def GetNumberOfIterations(self): <NEW_LINE> <INDENT> return _itkConfidenceConnectedImageFilterPython.itkConfidenceConnectedImageFilterIF3IUL3_GetNumberOfIterations(self) | GetNumberOfIterations(self) -> unsigned int | 625941dd4f6381625f114d64 |
def __getFilterOptionsFromCFG(self, logFilter): <NEW_LINE> <INDENT> from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFilterConfig <NEW_LINE> retDictRessources = getFilterConfig(logFilter) <NEW_LINE> if retDictRessources["OK"]: <NEW_LINE> <INDENT> return retDictRessources["Value"] <NEW_LINE> <DEDENT> re... | Get filter options from the configuration..
:param logFilter: filter identifier: stdout, file, f04 | 625941ddaad79263cf390d6e |
def sbcAC(self): <NEW_LINE> <INDENT> self._sbcAR(self.c) | Subtracts C + Carry from A and stores the result in A. | 625941dd3cc13d1c6d3c76a1 |
def get_plugin(guid: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPluginResult: <NEW_LINE> <INDENT> __args__ = dict() <NEW_LINE> __args__['guid'] = guid <NEW_LINE> if opts is None: <NEW_LINE> <INDENT> opts = pulumi.InvokeOptions() <NEW_LINE> <DEDENT> if opts.version is None: <NEW_LI... | New Relic Plugins reached end of life Wednesday June 16, 2021.
**This data source has been removed.**
For more information, [click here](https://discuss.newrelic.com/t/new-relic-plugin-eol-wednesday-june-16th-2021/127267) | 625941dd7d847024c06be5e7 |
def oops(arg_string): <NEW_LINE> <INDENT> parms.logger.critical("OOPS, " + arg_string) <NEW_LINE> sys.exit(86) | Log an error-string.
Make an orderly exit to the O.S. | 625941dd4428ac0f6e5bab1d |
def __uiPoseSelectObjects(self, *args): <NEW_LINE> <INDENT> rootNode = cmds.textFieldButtonGrp(self.uitfgPoseRootNode, q=True, text=True) <NEW_LINE> if rootNode and cmds.objExists(rootNode): <NEW_LINE> <INDENT> self.__uiPresetFillFilter() <NEW_LINE> pose = r9Pose.PoseData(self.filterSettings) <NEW_LINE> pose.matchMetho... | Select matching internal nodes | 625941dd596a897236089de6 |
def build(self, buildOrders): <NEW_LINE> <INDENT> for buildOrder in buildOrders: <NEW_LINE> <INDENT> self.buildOneAgent(buildOrder) | generated source for method build | 625941dd6aa9bd52df0370ce |
def testConstructor_006(self): <NEW_LINE> <INDENT> config = Config() <NEW_LINE> config.reference = None <NEW_LINE> self.assertEqual(None, config.reference) | Test assignment of reference attribute, None value. | 625941dd76d4e153a657ee5b |
def connection_state_changed(self, new_state): <NEW_LINE> <INDENT> if new_state in ['closed', 'error', 'timed_out'] and not self.is_closed(): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> self.notify_controller('connection_state', self._connection_state) <NEW_LINE> self.notify_controller('connection_health', sel... | Called from parent Connection class whenever state changes. | 625941dd6fb2d068a760f3ca |
def read_text(self, mypath="InspiringSet/"): <NEW_LINE> <INDENT> text_files = [f for f in listdir(mypath) if isfile(join(mypath, f)) and str(f).endswith(".txt")] <NEW_LINE> return text_files | Reads the contents of the Inspiring Set folder to find TXT files.
:returns:
a list of TXT file names of files contained in the path | 625941dd9f2886367277abb4 |
def markov_blanket_sample(self, e): <NEW_LINE> <INDENT> ex = dict(e) <NEW_LINE> ex[self] = False <NEW_LINE> fp = self.p(False, e) * product(child.p(ex[child], ex) for child in self.children) <NEW_LINE> ex[self] = True <NEW_LINE> tp = self.p(True, e) * product(child.p(ex[child], ex) for child in self.children) <NEW_LIN... | Return a random sample from P(self | others) where 'others' denotes
that all other variables take their values from event e. | 625941ddab23a570cc2504ad |
def test_cannot_create_user_with_numeric_password(self): <NEW_LINE> <INDENT> url = reverse('create-user') <NEW_LINE> data = { "username": "createduser", "first_name": "Created", "last_name": "User", "email": "created@example.com", "password": "1234567890" } <NEW_LINE> response = self.client.post(url, data, format='json... | Confirm that a user cannot be created with an entirely numeric password | 625941ddfb3f5b602dac39bf |
def func3(_book): <NEW_LINE> <INDENT> global rdm_data, end_month <NEW_LINE> _l = 1 <NEW_LINE> for _pj_name in sorted(rdm_data["test_task"]): <NEW_LINE> <INDENT> _book.write((_l, 0, _pj_name)) <NEW_LINE> for _idx in range(1, end_month): <NEW_LINE> <INDENT> _book.write((_l, _idx, float(rdm_data["test_task"][_pj_name][_id... | 测试资源投入
:param _book: 文档
:return: | 625941dd187af65679ca5448 |
def setEndTime(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.MEDCouplingFieldDouble_setEndTime(self, *args) | setEndTime(self, double val, int iteration, int order)
1 | 625941ddbd1bec0571d90957 |
def test_load_from_v24(self): <NEW_LINE> <INDENT> exploration = exp_domain.Exploration.from_yaml( 'eid', self.YAML_CONTENT_V24) <NEW_LINE> self.assertEqual(exploration.to_yaml(), self._LATEST_YAML_CONTENT) | Test direct loading from a v24 yaml file. | 625941dd5e10d32532c5f24f |
def GetFieldNumber(field_tuple): <NEW_LINE> <INDENT> return field_tuple[0].number | Get the field number from the tuple returned by `Message.ListFields`. | 625941dd7d847024c06be5e8 |
def percent_cover(poly, bufPoly, units = "SQUAREMETERS"): <NEW_LINE> <INDENT> arcpy.MakeFeatureLayer_management(poly, "poly") <NEW_LINE> lst=[] <NEW_LINE> orderLst=[] <NEW_LINE> with arcpy.da.SearchCursor(bufPoly, ["SHAPE@", "OID@"]) as cursor: <NEW_LINE> <INDENT> for row in cursor: <NEW_LINE> <INDENT> totalArea = dec(... | Percent Cover
Purpose: | 625941dd63b5f9789fde740f |
def _element_constructor_(self, *v, **kwds): <NEW_LINE> <INDENT> if len(v) == 1: <NEW_LINE> <INDENT> v = v[0] <NEW_LINE> <DEDENT> return self.codomain()._point(self, v, **kwds) | The element contstructor.
INPUT:
- ``v`` -- anything that determines a scheme morphism in the
Hom-set.
OUTPUT:
The scheme morphism determined by ``v``.
EXAMPLES::
sage: A2 = AffineSpace(ZZ,2)
sage: F = GF(3)
sage: F_points = A2(F); type(F_points)
<class 'sage.schemes.affine.affine_homset.Scheme... | 625941dd9c8ee82313fbba9f |
@click.command( context_settings={'ignore_unknown_options': True, 'allow_extra_args': True} ) <NEW_LINE> @click.argument('classifier', type=click.Choice(constants.CLASSIFIERS)) <NEW_LINE> @click.argument('catalog', type=click.Choice(target_database.supported_targets())) <NEW_LINE> @click.argument('entity', type=click.C... | Evaluate the performance of a supervised linker.
By default, run 5-fold cross-validation and
return averaged performance scores. | 625941ddfff4ab517eb2f766 |
def fromFile(self, fp): <NEW_LINE> <INDENT> ti = self(fp.readline()) <NEW_LINE> return ti | Return the first line of the file.
| 625941ddd99f1b3c44c678b3 |
def get_layer(self, instance_id, layer_id, load_url=False): <NEW_LINE> <INDENT> conf_index = self.get_configuration_index(instance_id) <NEW_LINE> layer_index = self.get_layer_index(instance_id, layer_id) <NEW_LINE> layer = self._configurations[conf_index].layers[layer_index] <NEW_LINE> data_source = layer.data_source <... | Provides a single layer object, optionally it loads additional info about it's data source and service URL
:param instance_id: A configuration instance ID
:type instance_id: str
:param layer_id: A layer ID
:type layer_id: str
:param load_url: If True it will make an additional request to find out which at which servic... | 625941dd99cbb53fe6792f0f |
def getLedge(self): <NEW_LINE> <INDENT> return max(self.lx,self.ly) | return the maximum length of half an umbrella edge | 625941dd26238365f5f0f19b |
def main(): <NEW_LINE> <INDENT> argument_spec = vmware_argument_spec() <NEW_LINE> argument_spec.update( state=dict(default='enabled', choices=['enabled', 'disabled']), esxi_hostname=dict(type='str', required=False), cluster_name=dict(type='str', required=False), ) <NEW_LINE> module = AnsibleModule(argument_spec=argumen... | Main | 625941dd435de62698dfdf76 |
def detect_api_mismatch(ref_api, other_api, *, ignore=()): <NEW_LINE> <INDENT> missing_items = set(dir(ref_api)) - set(dir(other_api)) <NEW_LINE> if ignore: <NEW_LINE> <INDENT> missing_items -= set(ignore) <NEW_LINE> <DEDENT> missing_items = set(m for m in missing_items if not m.startswith('_') or m.endswith('__')) <NE... | Returns the set of items in ref_api not in other_api, except for a
defined list of items to be ignored in this check.
By default this skips private attributes beginning with '_' but
includes all magic methods, i.e. those starting and ending in '__'. | 625941dd2ae34c7f2600d45a |
def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None | CreateDeviceResponse - a model defined in Swagger | 625941dd7b25080760e39781 |
def load_data(mode="train"): <NEW_LINE> <INDENT> char2idx, idx2char = load_vocab() <NEW_LINE> if mode=="train": <NEW_LINE> <INDENT> fpaths, text_lengths, texts = [], [], [] <NEW_LINE> transcript = os.path.join(hp.data, 'transcript.txt') <NEW_LINE> lines = codecs.open(transcript, 'r', 'utf-8').readlines() <NEW_LINE> for... | Loads data
Args:
mode: "train" or "synthesize". | 625941ddcad5886f8bd27302 |
def looks_like_weight(name): <NEW_LINE> <INDENT> if name.endswith("_weight"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if name.endswith("_bias"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Internal helper to figure out if node should be hidden with ``hide_weights``.
| 625941dd7c178a314d6ef78d |
def hydrafy_properties(properties, semantic_ref_name=None): <NEW_LINE> <INDENT> hydra_props = list() <NEW_LINE> for prop in properties: <NEW_LINE> <INDENT> domains = [None] <NEW_LINE> ranges = [None] <NEW_LINE> if "rdf:domain" in prop: <NEW_LINE> <INDENT> domains = [fix_keyword(x["@id"]) for x in prop["rdf:domain"]] <N... | Return list of Hydrafied properties along with the classes they are supported in. | 625941dd91af0d3eaac9bd45 |
def raise_window(figname=None): <NEW_LINE> <INDENT> if figname: <NEW_LINE> <INDENT> plt.figure(figname) <NEW_LINE> <DEDENT> cfm = plt.get_current_fig_manager() <NEW_LINE> cfm.window.attributes('-topmost', True) <NEW_LINE> cfm.window.attributes('-topmost', False) <NEW_LINE> cfm.window.focus() <NEW_LINE> return cfm | Raise the plot window for Figure figname to the foreground. If no argument
is given, raise the current figure.
This function will only work with a Tk graphics backend. It assumes you
have already executed the command 'import matplotlib.pyplot as plt'. | 625941ddb545ff76a891413e |
def mobilenet_wd2(**kwargs): <NEW_LINE> <INDENT> return get_mobilenet(version="orig", width_scale=0.5, model_name="mobilenet_wd2", **kwargs) | 0.5 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Location for ... | 625941dda79ad161976cc46e |
def MergeTablesData(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("MergeTablesData", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.MergeTablesDataResponse() <NE... | 合并指定表格
:param request: Request instance for MergeTablesData.
:type request: :class:`tencentcloud.tcaplusdb.v20190823.models.MergeTablesDataRequest`
:rtype: :class:`tencentcloud.tcaplusdb.v20190823.models.MergeTablesDataResponse` | 625941dda79ad161976cc46f |
def pytest_addoption(parser): <NEW_LINE> <INDENT> parser.addoption( "--validate", action="store_true", default=False, help="Enable long running validation tests.", ) | Add GSD specific options to the pytest command line.
* validate - run validation tests | 625941dde76e3b2f99f3ab30 |
def set_state_sequence(self, sequence): <NEW_LINE> <INDENT> self.X = sequence | Sets the state sequence | 625941dd507cdc57c630700b |
def pytest_funcarg__plrdm(request): <NEW_LINE> <INDENT> from datazilla.model.refdata import PushLogRefDataModel <NEW_LINE> plrdm = PushLogRefDataModel( request._pyfuncitem.session.pushlog_name) <NEW_LINE> request.addfinalizer(partial(truncate, plrdm, ["branches", "branch_map"])) <NEW_LINE> return plrdm | Give a test access to a PushLogStatsModel instance.
Truncate all project tables between tests in order to provide isolation. | 625941ddcb5e8a47e48b7dcf |
def create_assessment(self, people=None): <NEW_LINE> <INDENT> assessment = factories.AssessmentFactory() <NEW_LINE> if not people: <NEW_LINE> <INDENT> people = [ ("creator@example.com", "Creator"), ("assessor_1@example.com", "Assessor"), ("assessor_2@example.com", "Assessor"), ("verifier_1@example.com", "Verifier"), ("... | Create default assessment with some default assignees in all roles.
Args:
people: List of tuples with email address and their assignee roles for
Assessments.
Returns:
Assessment object. | 625941dd0383005118ecf90b |
def update_databags(self, vars_dict): <NEW_LINE> <INDENT> databag_names = self.config_manager.get_chef_databag_names() <NEW_LINE> if not databag_names: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> import chef <NEW_LINE> databags_dir = os.path.join(self.tmpl_dir, self.DATABAG_TMPL_DIR) <NEW_LINE> for databag_name in d... | Update datbag item attributes.
:param dict vars_dict: The dictionary used to get attributes from
templates. | 625941dd7047854f462a172f |
def get(self, url, *, allow_redirects=True, **kwargs): <NEW_LINE> <INDENT> return _RequestContextManager( self._request(hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs)) | Perform HTTP GET request. | 625941ddbe8e80087fb20f68 |
def test_harvester_new_file_exception_tel(self): <NEW_LINE> <INDENT> log.debug('===== START QUAL TEST HARVESTER EXCEPTION TEL =====') <NEW_LINE> self.create_sample_data_set_dir(FILE4, TEL_DIR, mode=000) <NEW_LINE> self.assert_initialize(final_state=ResourceAgentState.COMMAND) <NEW_LINE> self.event_subscribers.clear_eve... | Test an exception raised after the driver is started during
the file read.
exception callback called. | 625941dd60cbc95b062c686d |
def addHiddenWallFormworkQuant(self,price): <NEW_LINE> <INDENT> if self.LhiddFormwork>0.0: <NEW_LINE> <INDENT> price.quantities.append(MeasurementRecord(self.textComment,self.nUnits,self.LdeckUnifSect,self.LhiddFormwork,None)) <NEW_LINE> <DEDENT> if self.nLateralFormwork>0: <NEW_LINE> <INDENT> price.quantities.append(M... | Add hidden-wall formwork quantities to the price defined as parameter
:price: instance of object UnitPriceQuantities | 625941dd92d797404e3044b4 |
def hugetlb_test(self): <NEW_LINE> <INDENT> print("\nHugetlb testing...") <NEW_LINE> self.get_memory() <NEW_LINE> print("HugePages Total: %u" % self.hugepage_total) <NEW_LINE> print("HugePages Free: %u" % self.hugepage_free) <NEW_LINE> print("HugePages Size: %uMB" % self.hugepage_size) <NEW_LINE> update_hugepage = 1 <N... | hugetlb test
:return: | 625941dd7d43ff24873a2fcb |
@mod.route('/') <NEW_LINE> @mod.route('/home') <NEW_LINE> @if_logged_in() <NEW_LINE> def home(): <NEW_LINE> <INDENT> listx = lxc.listx() <NEW_LINE> containers_all = [] <NEW_LINE> for status in ('RUNNING', 'FROZEN', 'STOPPED'): <NEW_LINE> <INDENT> containers_by_status = [] <NEW_LINE> for container in listx[status]: <NEW... | home page function | 625941dd29b78933be1e59d1 |
def h_decrement_offset(self, *args, **keywords): <NEW_LINE> <INDENT> pass | Method used by forms that manipulate API data, to fetch the previous values | 625941dd21bff66bcd684c79 |
def __init__(self, turn_limit=200, custom_start_positions=None, default_logging=False): <NEW_LINE> <INDENT> start_pos = custom_start_positions or deepcopy(DEFAULT_START_POSITIONS) <NEW_LINE> self.logging = default_logging if default_logging else LOGGING <NEW_LINE> self.board = Board(start_pos) <NEW_LINE> self.pieces = ... | Initialise game object and create required member objects | 625941dda8370b7717052bc7 |
def __init__(self, settings: Settings): <NEW_LINE> <INDENT> self._upload_directory = settings.upload_directory <NEW_LINE> if not os.path.isdir(self._upload_directory): <NEW_LINE> <INDENT> os.makedirs(self._upload_directory) | Construct the file service
:param settings: the settings object needed to get the upload_directory path | 625941dd63f4b57ef000143b |
def is_subsequence_of(needle, haystack): <NEW_LINE> <INDENT> if len(needle) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for offset in (i for i, x in enumerate(haystack) if x == needle[0]): <NEW_LINE> <INDENT> if offset + len(needle) > len(haystack): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> ma... | Returns True if needle occurs as a consecutive subsequence in haystack.
Both needle and haystack must be ordered containers. The values in
needle must appear in haystack in the order they appear in needle
and must be consecutive in haystack.
For example, with needle=[1,2,3] and haystack=[1,1,2,3,4], the
function ret... | 625941ddcc0a2c11143dd1ba |
def flatten(deep_array): <NEW_LINE> <INDENT> response = [] <NEW_LINE> for item in deep_array: <NEW_LINE> <INDENT> if isinstance(item, list): <NEW_LINE> <INDENT> response.extend(flatten(item)) <NEW_LINE> <DEDENT> elif isinstance(item, (str, int)): <NEW_LINE> <INDENT> response.append(item) <NEW_LINE> <DEDENT> <DEDENT> re... | Returns flatten array. | 625941dd8a43f66fc4b5438b |
def setup_llc_allocation(self): <NEW_LINE> <INDENT> cpumap = defaultdict(list) <NEW_LINE> vswitchmask = S.getValue('VSWITCHD_DPDK_CONFIG')['dpdk-lcore-mask'] <NEW_LINE> vnfcores = list(itertools.chain.from_iterable( S.getValue('GUEST_CORE_BINDING'))) <NEW_LINE> if not guest_vm_settings_expanded(vnfcores): <NEW_LINE> <I... | Wrapper for settingup cacheways | 625941dd92d797404e3044b5 |
def l2_loss_old(y_true, y_pred): <NEW_LINE> <INDENT> diff = (y_true - y_pred)**2 <NEW_LINE> loss = K.mean(diff, axis=0) <NEW_LINE> loss = K.sum(diff) <NEW_LINE> return loss / 2. / 255. | Implements Smooth-L1 loss.
y_true and y_pred are typicallly: [N, 4], but could be any shape. | 625941dd236d856c2ad44b08 |
def stop_msg_confirm_create(pid: int, leader_id: int, ts: float) -> message.Message: <NEW_LINE> <INDENT> return message.Message(pid, mt.MsgType.STOP_CONFIRM, leader_id, ts) | create to confirm stop
:param pid: agent pid
:type pid: int
:param leader_id: leader pid
:type leader_id: int
:param ts: time stamp
:type ts: float
:return: stop message confirmation create
:rtype: Message | 625941dd566aa707497f488e |
def test_remove_member(self): <NEW_LINE> <INDENT> app = self._get_test_app() <NEW_LINE> user_one = factories.User(fullname='User One', name='user-one') <NEW_LINE> user_two = factories.User(fullname='User Two') <NEW_LINE> other_users = [ {'name': user_two['id'], 'capacity': 'member'} ] <NEW_LINE> group = self._create_gr... | Member can be removed from group | 625941dd63d6d428bbe44819 |
def test_symlinks_in_path_get_resolved(self): <NEW_LINE> <INDENT> if platform.system() == "Windows": <NEW_LINE> <INDENT> self.skipTest("symlinks not supported on Windows") <NEW_LINE> <DEDENT> with testutil.in_tempdir(os.getcwd(), "executable_path") as temp_dir: <NEW_LINE> <INDENT> link = os.path.join(temp_dir, "link") ... | Returned executable path has symlinks resolved. | 625941dd8c3a8732951586e7 |
def get_median(number_list): <NEW_LINE> <INDENT> sorted_list = number_list[:] <NEW_LINE> sorted_list.sort() <NEW_LINE> median = sorted_list[int(len(sorted_list) / 2)] if len(sorted_list) % 2 else (sorted_list[int(len(sorted_list) / 2) - 1] + sorted_list[int(len(sorted_list) / 2)]) / 2 <NEW_LINE> return median | 주어진 리스트 숫자들의 중간값을 구함.
Parameters:
number_list (list): integer로 값으로만 구성된 list
ex - [10, 33, 22, 99, 33]
Returns:
median (int): parameter number_list 숫자들의 중간값
Examples:
>>> number_list = [39, 54, 32, 11, 99]
>>> import basic_math as bm
>>> bm.get_median(numbe... | 625941dd5166f23b2e1a5483 |
@tf_export('image.rot90') <NEW_LINE> @dispatch.add_dispatch_support <NEW_LINE> def rot90(image, k=1, name=None): <NEW_LINE> <INDENT> with ops.name_scope(name, 'rot90', [image, k]) as scope: <NEW_LINE> <INDENT> image = ops.convert_to_tensor(image, name='image') <NEW_LINE> image = _AssertAtLeast3DImage(image) <NEW_LINE> ... | Rotate image(s) counter-clockwise by 90 degrees.
For example:
>>> a=tf.constant([[[1],[2]],
... [[3],[4]]])
>>> # rotating `a` counter clockwise by 90 degrees
>>> a_rot=tf.image.rot90(a)
>>> print(a_rot[...,0].numpy())
[[2 4]
[1 3]]
>>> # rotating `a` counter clockwise by 270 degrees
>>> a_rot=tf.ima... | 625941dd460517430c3944a8 |
def get_usersproject(self): <NEW_LINE> <INDENT> if not self.request.user: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> up = UsersProject.objects.filter(user=self.request.user, project=self.object).first() <NEW_LINE> return up | Return userproject object for current user | 625941ddff9c53063f47c51c |
def authenticate(self): <NEW_LINE> <INDENT> user = get_config().get('hpss', 'user') <NEW_LINE> auth = get_config().get('hpss', 'auth') <NEW_LINE> rcode = self._hpsslib.hpss_SetLoginCred( user.encode('utf8'), HPSS_AUTHN_MECH_UNIX, HPSS_RPC_CRED_CLIENT, HPSS_RPC_AUTH_TYPE_KEYTAB, auth.encode('utf8') ) <NEW_LINE> self._ch... | Authenticate the user with the hpss system. | 625941dd32920d7e50b284fc |
def filter_queryset( self, queryset: QuerySet, feature_type: FeatureType ) -> QuerySet: <NEW_LINE> <INDENT> if self.is_empty: <NEW_LINE> <INDENT> return queryset.none() <NEW_LINE> <DEDENT> if self.extra_lookups: <NEW_LINE> <INDENT> raise RuntimeError("apply_extra_lookups() was not called") <NEW_LINE> <DEDENT> if self.a... | Apply the filters and lookups to the queryset.
:param queryset: The queryset to filter.
:param feature_type: The feature type that the queryset originated from. | 625941dd1d351010ab855e45 |
def now_utc_time(): <NEW_LINE> <INDENT> return datetime.utcnow().strftime(GMT_FORMAT) | 获取GTM时间, 格式为: Wed, 09-Aug-2017 19:55:25 GMT | 625941ddd164cc6175783078 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DeploymentPolicy): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941dd7d43ff24873a2fcc |
def is_curious_fraction(numenator, denominator): <NEW_LINE> <INDENT> snum = str(numenator) <NEW_LINE> sden = str(denominator) <NEW_LINE> for i in xrange(len(snum)): <NEW_LINE> <INDENT> for j in xrange(len(sden)): <NEW_LINE> <INDENT> if snum[i] != sden[j] or not int(snum[i]) or not int(sden[j]): <NEW_LINE> <INDENT> cont... | The fraction 49/98 is a curious fraction, as an inexperienced mathematician
in attempting to simplify it may incorrectly believe that 49/98 = 4/8,
which is correct, is obtained by cancelling the 9s. | 625941dd379a373c97cfae70 |
def invoke(self, method, relpath=None, params=None, data=None, headers=None, allow_redirects=False, clear_cookies=False): <NEW_LINE> <INDENT> path = self._join_uri(relpath) <NEW_LINE> resp = self._client.execute(method, path, params=params, data=data, headers=headers, allow_redirects=allow_redirects) <NEW_LINE> if resp... | Invoke an API method.
Look for sqoop-error-code and sqoop-error-message.
@return: Raw body or JSON dictionary (if response content type is JSON). | 625941dd9f2886367277abb5 |
def read_pio_result_files(self): <NEW_LINE> <INDENT> p_strd_pattern = re.compile('\w*straddles') <NEW_LINE> for path_strd in os.listdir(self.pio_result_path): <NEW_LINE> <INDENT> full_path_strd = os.path.join(self.pio_result_path,path_strd) <NEW_LINE> if not(os.path.isdir(full_path_strd) & bool(re.match(p_strd_pattern,... | read all file names of PioSOLVER's result files in self.strategy_files
the output should be {strd_limit: {user_position: [file_names]}.
if there are any duplicated files, raise an exception. | 625941ddd18da76e23532803 |
def get_queryset(self): <NEW_LINE> <INDENT> return Category.objects.all() | Handle incoming GET requests and enumerate objects that get returned by
the API. | 625941dd711fe17d8254268e |
def Get_frequecy_feature(wav_Signal, fs): <NEW_LINE> <INDENT> time_Window = 25 <NEW_LINE> window_Length = fs / 1000 * time_Window <NEW_LINE> wav_Array = np.array(wav_Signal) <NEW_LINE> wav_Length = wav_Array.shape[1] <NEW_LINE> range_End = int(len(wav_Signal[0]) / fs * 1000 - time_Window) // 10 <NEW_LINE> if range_End ... | 对输入数据进行处理,加窗?????? | 625941dd498bea3a759b9dd8 |
def validateQemuReadable(targetPath): <NEW_LINE> <INDENT> gids = (grp.getgrnam(constants.DISKIMAGE_GROUP).gr_gid, grp.getgrnam(constants.METADATA_GROUP).gr_gid) <NEW_LINE> st = os.stat(targetPath) <NEW_LINE> if not (st.st_gid in gids and st.st_mode & stat.S_IRGRP or st.st_mode & stat.S_IROTH): <NEW_LINE> <INDENT> raise... | Validate that qemu process can read file | 625941dd4f88993c3716c38f |
def __match_td_vals(self): <NEW_LINE> <INDENT> pairs = self.__get_pairs() <NEW_LINE> vals = [] <NEW_LINE> for pair in pairs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> vals.append(self.TD_VALS[pair]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return vals | Matches input pairs with their thermodynamic values
and returns them as a list of tuples - (dH, dS, dG) | 625941dd3346ee7daa2b3098 |
def InterfaceStateEvent_registerIDL(self, sessionHandle, xosHandle, interfaceType, stateEventType, maxrun_sec, maxrun_msec): <NEW_LINE> <INDENT> pass | ---------------------------------------
NetworkInterface Event Registration API
---------------------------------------
Parameters:
- sessionHandle
- xosHandle
- interfaceType
- stateEventType
- maxrun_sec
- maxrun_msec | 625941dd76d4e153a657ee5c |
def _save_local(self, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> import errno <NEW_LINE> if e.errno == errno.EEXIST and os.path.isdir(path): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DE... | Save current query object to local path
| 625941dddc8b845886cb5860 |
def showThemesMenu(parent=None, themes=None): <NEW_LINE> <INDENT> theme = Theme() <NEW_LINE> menu = ThemesMenu(parent=parent, theme=theme, themes=themes) <NEW_LINE> position = QtWidgets.QCursor().pos() <NEW_LINE> action = menu.exec_(position) <NEW_LINE> return theme | Show a menu with the given themes.
:type themes: list[Theme]
:type parent: QtWidgets.QWidget
:rtype: QtWidgets.QAction | 625941ddcdde0d52a9e5335f |
def OnHddSelectorOk(self, event): <NEW_LINE> <INDENT> self.__hddList.SaveToConfig() <NEW_LINE> event.Skip() | Saves changes made | 625941dd30dc7b7665901c8d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.