code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def str_param_comp(current, defaults, descriptions={}, prefix=''): <NEW_LINE> <INDENT> s = "" <NEW_LINE> for code, (defval, mand, pref) in defaults.items(): <NEW_LINE> <INDENT> mand = "T" if mand else "F" <NEW_LINE> defval = "[empty default value]" if defval == "" else defval <NEW_LINE> desc = descriptions.get(code) <N...
Illustrate which value would be given for each param
625941e976d4e153a657efdc
def _handle_alarm(self, timestamp: datetime, alarm: str, state: bool): <NEW_LINE> <INDENT> _LOGGER.debug("Handle alarm: %s; State: %s", alarm, state) <NEW_LINE> self.last_activity = timestamp <NEW_LINE> self.alarm_timestamp[alarm] = timestamp <NEW_LINE> self.alarm_state[alarm] = state <NEW_LINE> for handler in self._al...
Handle alarms from Beward device.
625941e97d43ff24873a314e
def _regular_statement_clause_generator(dev_autotap, cap_autotap, par_autotap, comp, val, neg): <NEW_LINE> <INDENT> dev_list_backend = list(m.Device.objects.all().order_by('id')) <NEW_LINE> dev_name_list = [_dev_name_to_autotap(dev.name) for dev in dev_list_backend] <NEW_LINE> device = dev_list_backend[dev_name_list.in...
handle non-special case (not location, not music) :param dev_autotap: :param cap_autotap: :param par_autotap: :param comp: :param val: :param neg: :return: parameters, parameter_vals
625941e955399d3f05588b61
def add(self, software_name, tags, primary_link, one_liner, paid, primary_ref = "N.A", remarks = "N.A", meta = None): <NEW_LINE> <INDENT> if all([ type(software_name) is str, type(tags) is list, type(primary_link) is str, type(one_liner) is str, type(paid) is bool, type(primary_ref) is str, type(remarks) is str, type(m...
Adds the software into the Database. Any additional properties should only be added into `meta`.
625941e9167d2b6e3121903f
def __str__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._data[u'name'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return str(self._data) <NEW_LINE> <DEDENT> <DEDENT> except TypeErro...
a simple to string function: just the name or the full info -- debug only
625941e9283ffb24f3c55da6
def remove_namespace(xml_file): <NEW_LINE> <INDENT> lines = xml_file.read() <NEW_LINE> lines = re.sub(r'<document [^>]+>', '<document>', lines) <NEW_LINE> lines = re.sub(r'\w+:type="[^"]+"', '', lines) <NEW_LINE> return StringIO.StringIO(lines)
SPL files have namespaces that don't play nice with python's libxml. For now we just remove namespaces to work around this.
625941e963b5f9789fde7590
def test_server_configurable_configlet_good(self): <NEW_LINE> <INDENT> module = Mock() <NEW_LINE> module.params = dict(switch_name='eos') <NEW_LINE> configlets = [dict(name='configlet1', info='line'), dict(name='eos-server', info='info')] <NEW_LINE> module.client.api.get_configlets_by_device_id.return_value = configlet...
Test server_configurable_configlet good.
625941e915baa723493c4423
def __init__(self, *values): <NEW_LINE> <INDENT> if not isinstance(values, list) and not isinstance(values, tuple): <NEW_LINE> <INDENT> raise TypeError("Invalid type of value list.") <NEW_LINE> <DEDENT> self._root = None <NEW_LINE> self._size = 0 <NEW_LINE> for val in values: <NEW_LINE> <INDENT> if isinstance(val, list...
Create a complete binary tree.
625941e9a934411ee3751b3f
@do.route("/do/vote/<pid>/<value>", methods=["POST"]) <NEW_LINE> def upvote(pid, value): <NEW_LINE> <INDENT> form = CsrfTokenOnlyForm() <NEW_LINE> if not form.validate(): <NEW_LINE> <INDENT> return json.dumps({"status": "error", "error": get_errors(form)}), 400 <NEW_LINE> <DEDENT> if not current_user.is_authenticated: ...
Logs an upvote to a post.
625941e9f8510a7c17cf9baa
def _find_move_direction(fun,keys:list,params:dict,upper_point:dict,lower_point:dict,move_up:dict)->tuple: <NEW_LINE> <INDENT> best_score = np.Inf <NEW_LINE> move_space = {key: [False, True] for key in params.keys()} <NEW_LINE> for move in grid(move_space): <NEW_LINE> <INDENT> param = {} <NEW_LINE> for key in keys: <NE...
This function is to calculate the best combination of upper_point and lower_point. The best one decide the moving direction for each parameter. The best score should be also stored. :param fun: One callable function to optimize, with inputs as the keys. :param keys: A list of strings, from the keys of params :param par...
625941e932920d7e50b2867e
def SetScale(self, dynamicSymbolType, scaleX, scaleY): <NEW_LINE> <INDENT> return super(IDynamicSymbolProperties2, self).SetScale(dynamicSymbolType, scaleX, scaleY)
Method IDynamicSymbolProperties.SetScale (from IDynamicSymbolProperties) INPUTS dynamicSymbolType : esriDynamicSymbolType scaleX : float scaleY : float
625941e901c39578d7e752e6
def get(self, url, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('allow_redirects', True) <NEW_LINE> self.response = self.request('GET', url, **kwargs) <NEW_LINE> self.response_data = self.response.content <NEW_LINE> self.response_json_to_dict() <NEW_LINE> self.response.raise_for_status() <NEW_LINE> return self.resp...
Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
625941e991f36d47f21ac9a1
def cols(self, ncols): <NEW_LINE> <INDENT> self._max_cols = ncols <NEW_LINE> return self
Sets the maximum number of columns in the NdLayout. Any items beyond the set number of cols will flow onto a new row. The number of columns control the indexing and display semantics of the NdLayout. Args: ncols (int): Number of columns to set on the NdLayout
625941e91f5feb6acb0c4ff4
def from_xml(self, xml_node): <NEW_LINE> <INDENT> self.id = xml_node.attrib['id'] <NEW_LINE> self.start = int(xml_node.find('start').text) <NEW_LINE> self.end = int(xml_node.find('end').text) <NEW_LINE> self.name = xml_node.find('name').text <NEW_LINE> self.enabled = xml_node.find('enabled').text == 'True' <NEW_LINE> s...
Fills attributes with the given XML node :param xml_node: an xml.etree.ElementTree.Element instance
625941e9d8ef3951e32439e8
@APP.route('/document', methods=['POST']) <NEW_LINE> def createDocument(): <NEW_LINE> <INDENT> man = DocumentManager() <NEW_LINE> try: <NEW_LINE> <INDENT> man.setCollection(settings.GetConfigValue("ServiceStockageAnnotations", "documentCollection")) <NEW_LINE> man.connect() <NEW_LINE> if request.method == 'POST': <NEW_...
:route: **/document** :POST creates a new document: :Request: :: Preconditions: Here are the minimum required elements by the document. { @context: context describing the format of the document } All the other parameters will be saved as is. ...
625941e91f5feb6acb0c4ff3
def longestUnivaluePath(self, root): <NEW_LINE> <INDENT> self.res = 0 <NEW_LINE> def length_path(node): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> left_length = length_path(node.left) <NEW_LINE> right_length = length_path(node.right) <NEW_LINE> left_temp = right_temp = 0 <NEW_LINE...
:type root: TreeNode :rtype: int
625941e9c4546d3d9de72ee2
def __init__(self, user, is_board_admin: bool, is_no_comments: bool, is_comment_only: bool): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.is_board_admin = is_board_admin <NEW_LINE> self.is_no_comment = is_no_comments <NEW_LINE> self.is_comment_only = is_comment_only
:param user: A Wekan user. :param is_board_admin: Can view and edit cards, remove members, and change settings for the board. :param is_no_comments: Can not see comments and activities. :param is_comment_only: Can comment on cards only.
625941e9d7e4931a7ee9e3c9
def check_paypal_multiple(ids, limit=None): <NEW_LINE> <INDENT> if limit is None: <NEW_LINE> <INDENT> limit = Sample.objects.get(name='paypal-disabled-limit').percent <NEW_LINE> <DEDENT> log.info('Starting run of paypal addon checks: %s' % len(ids)) <NEW_LINE> cache.set(key, [time.time(), len(ids), float(limit)]) <NEW_...
Setup redis so that we can store the count of addons tested and failed and spot when the test is completed. ids: Is the add-on ids we'll be checking. limit: The percentage of add-ons to change before we assume something has gone wrong. Setting this to zero (not recommended) disables it. If not set, we'll...
625941e9956e5f7376d71316
@blueprint.route("/static/<filename>") <NEW_LINE> def static(filename): <NEW_LINE> <INDENT> dirpath = flask.current_app.config["SITE_STATIC_DIR"] <NEW_LINE> if not dirpath: <NEW_LINE> <INDENT> raise ValueError("misconfiguration: SITE_STATIC_DIR not set") <NEW_LINE> <DEDENT> dirpath = os.path.expandvars(os.path.expandus...
Return the given site-specific static file.
625941e916aa5153ce362922
def doBlast(self, outputDir=Main.workDir): <NEW_LINE> <INDENT> Main.logger.debug("Blast doBlast: o." + outputDir) <NEW_LINE> workline = "blastn -db " + outputDir + "/others -query " + self.query + " -out " + outputDir + "/blastResult"+str(self.y)+".csv -outfmt \"10 std\"" <NEW_LINE> Main.execute(workl...
Runs the blast based on the local database and the query. Before this, a local database should be made named others :param outputDir: location where the blast results are saved :return:
625941e98e71fb1e9831dc52
def reject(self): <NEW_LINE> <INDENT> if self.status != 'P': <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.status = 'R' <NEW_LINE> self.updated = timezone.now() <NEW_LINE> self.save()
Rejects a pending friendship.
625941e923e79379d52eea08
def test_last_publish(self): <NEW_LINE> <INDENT> unpublished = self.conduit.last_publish() <NEW_LINE> self.assertTrue(unpublished is None) <NEW_LINE> last_publish = datetime.datetime.now() <NEW_LINE> repo_dist = RepoDistributor.get_collection().find_one({'repo_id' : 'repo-1'}) <NEW_LINE> repo_dist['last_publish'] = dat...
Tests retrieving the last publish time in both the unpublish and previously published cases.
625941e967a9b606de4a8361
def vis_detections(im, class_name, dets, thresh=0.5): <NEW_LINE> <INDENT> inds = np.where(dets[:, -1] >= thresh)[0] <NEW_LINE> if len(inds) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> im = im[:, :, (2, 1, 0)] <NEW_LINE> fig, ax = plt.subplots(figsize=(12, 12)) <NEW_LINE> ax.imshow(im, aspect='equal') <NEW_LINE...
Draw detected bounding boxes.
625941e92ae34c7f2600d5db
def set_to_tuple(tokens): <NEW_LINE> <INDENT> if len(tokens) != 1: <NEW_LINE> <INDENT> raise CoconutInternalException("invalid set maker tokens", tokens) <NEW_LINE> <DEDENT> elif "comp" in tokens.keys() or "list" in tokens.keys(): <NEW_LINE> <INDENT> return "(" + tokens[0] + ")" <NEW_LINE> <DEDENT> elif "test" in token...
Converts set literal tokens to tuples.
625941e9e5267d203edce141
def Start(self, input_dict, api_type = 'stream_v1', outlet_type = 'local'): <NEW_LINE> <INDENT> if not input_dict or not api_type or not outlet_type: <NEW_LINE> <INDENT> raise ValueError('INPUT_DICT, API_TYPE and ' + 'OUTLET_TYPE are needed.') <NEW_LINE> <DEDENT> self.input_dict = input_dict <NEW_LINE> self.api_type = ...
Start the monitor Parameters: input_dict (dict): dict of input parameters (parameters, start_id, end_id, etc). api_type (str): type of API: stream, REST, lab-covid19 outlet_type (str): type of outlet: local disk, pubsub, kinesis, Oracle stream. Returns: ...
625941e9a8ecb033257d3575
def remove_cobbler_system_interface(self, system_name, if_name): <NEW_LINE> <INDENT> url = "/cm/v1/cobbler/systems/{0}/{1}".format(system_name, if_name) <NEW_LINE> rest_data = self.request_rest_api("delete", url) <NEW_LINE> return rest_data["result"]
remove a specific interface *if_name* from the cobbler system *system_name*. :param string system_name: the name of a cobbler system :param string if_name: the name of an interface on the cobbler system. :return: True means remove an interface operation success, otherwise Failed
625941e9d58c6744b4258108
def pixel_dtype(ds: "Dataset", as_float: bool = False) -> "np.dtype": <NEW_LINE> <INDENT> if not HAVE_NP: <NEW_LINE> <INDENT> raise ImportError("Numpy is required to determine the dtype.") <NEW_LINE> <DEDENT> if ds.is_little_endian is None: <NEW_LINE> <INDENT> ds.is_little_endian = ds.file_meta.TransferSyntaxUID.is_lit...
Return a :class:`numpy.dtype` for the pixel data in `ds`. Suitable for use with IODs containing the Image Pixel module (with ``as_float=False``) and the Floating Point Image Pixel and Double Floating Point Image Pixel modules (with ``as_float=True``). +------------------------------------------+------------------+ | ...
625941e9d268445f265b5319
def plot_er_values(n, p_list): <NEW_LINE> <INDENT> k_list = [] <NEW_LINE> c_list = [] <NEW_LINE> d_list = [] <NEW_LINE> c_list_theory = [] <NEW_LINE> k_list_theory = [] <NEW_LINE> d_list_theory = [] <NEW_LINE> for p in p_list: <NEW_LINE> <INDENT> print("calculating for n=%d p=%f" % (n, p), file=sys.stderr) <NEW_LINE> a...
This function calculates the theoretical clustering coefficient, average degree and diameter for ER network with parameters n and p and plots them against the expected values from an ensemble of 100 realizations. Parameters ---------- n : int Number of nodes p_list : list of floats where each member is the probabi...
625941e95fc7496912cc3e28
def extractTemp(): <NEW_LINE> <INDENT> data = {} <NEW_LINE> print('running query...') <NEW_LINE> data = execQuery(queries.SELECT_ALL, db=constants.DB) <NEW_LINE> print('query ran') <NEW_LINE> for item in data: <NEW_LINE> <INDENT> print(item)
Pulls Data from the Temp database. AKA Staging DB
625941e9adb09d7d5db6cc37
def json(self): <NEW_LINE> <INDENT> def _json_or_none(obj): <NEW_LINE> <INDENT> return None if obj is None else obj.json() <NEW_LINE> <DEDENT> data = { "segment_models": [_json_or_none(m) for m in self.segment_models], "model_lookup": { key: _json_or_none(val) for key, val in self.model_lookup.items() }, "prediction_se...
Return a JSON-serializable representation of this result. The output of this function can be converted to a serialized string with :any:`json.dumps`.
625941e96fb2d068a760f54f
def get_data(get_command): <NEW_LINE> <INDENT> udp.send(get_command) <NEW_LINE> d = udp.receive(1) <NEW_LINE> try: <NEW_LINE> <INDENT> return loads(d[len(Command.VALUE):]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None
Get data from the recording PC get_commands e.g. Command.GET_FZ or Command.GET_VERSION ....
625941e9ad47b63b2c50a429
def _print_latex_(self, n, z): <NEW_LINE> <INDENT> return r"j_{{{}}}\left({}\right)".format(latex(n), latex(z))
TESTS:: sage: latex(spherical_bessel_J(4, x)) j_{4}\left(x\right)
625941e9a219f33f34628e0d
def p_for_loop(p): <NEW_LINE> <INDENT> p[0] = [Node("for_stmt", [Node("var_stmt", p[2], "variable")] + p[3] + [Node("in", None, "IN")] + p[4] + [Node("do_stmt", p[6], "DO")], "FOR")]
for_loop : FOR identifier direction expr DO instr | FOR identifier direction expr DO block
625941e90a50d4780f667340
def _is_nnsa_kb_core(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename, "rb") as fh: <NEW_LINE> <INDENT> lines = fh.readlines() <NEW_LINE> if not lines: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for line in lines: <NEW_LINE> <INDENT> assert(len(line.rstrip(b"\n\r")) == 287) <NEW_LINE...
Checks whether a file is NNSA KB Core waveform data (header) or not. :type filename: str :param filename: NNSA KB Core file to be checked. :rtype: bool :return: ``True`` if a NNSA KB Core waveform header file.
625941e9cc0a2c11143dd33c
def isBalanced(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> stack = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> while root: <NEW_LINE> <INDENT> stack.append(root) <NEW_LINE> root = root.left <NEW_LINE> <DEDENT> if not stack: <NEW_LINE> <INDENT> break <NEW_LINE> <DE...
:type root: TreeNode :rtype: bool
625941e9de87d2750b860242
def lowestCommonAncestor(self, root, p, q): <NEW_LINE> <INDENT> self.targetList = [[], []] <NEW_LINE> self.target = [p, q] <NEW_LINE> self.cur = [] <NEW_LINE> self.dfs(root, 0) <NEW_LINE> self.cur = [] <NEW_LINE> self.dfs(root, 1) <NEW_LINE> for i in self.targetList[0][::-1]: <NEW_LINE> <INDENT> if i in self.targetList...
:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
625941e93539df3088e2e7f6
@app.cli.command() <NEW_LINE> def load(): <NEW_LINE> <INDENT> for country in CountriesEnum: <NEW_LINE> <INDENT> c = Country.query.filter_by(name=country).first() <NEW_LINE> if c is not None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> c = Country(name=country) <NEW_LINE> db.session.add(c) <NEW_LINE> <DEDENT> for s...
Add missing enum data to tables that use these enums i.e contact.countries, contact.subgroups
625941e97b180e01f3dc4c9e
def t_comment(self, t): <NEW_LINE> <INDENT> t.lexer.lineno += t.value.count('\n')
(/\*(.|\n)*?\*/)|(//.*)
625941e923849d37ff7b3536
def _multiplexed_response_stream_helper(self, response): <NEW_LINE> <INDENT> socket = self._get_raw_response_socket(response) <NEW_LINE> if six.PY3: <NEW_LINE> <INDENT> socket._sock.settimeout(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> socket.settimeout(None) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT>...
A generator of multiplexed data blocks coming from a response stream.
625941e98da39b475bd65424
def _do_download(self, env, source, name, forceDownload): <NEW_LINE> <INDENT> srcDirTmp = name <NEW_LINE> if source.attribute('module_directory').value : <NEW_LINE> <INDENT> srcDirTmp = source.attribute('module_directory').value <NEW_LINE> <DEDENT> env.start_source(name, srcDirTmp) <NEW_LINE> rt = source.check_version(...
Recursive download function, do the download for each target module.
625941e95510c4643540f883
def GetTimeWarpCount(self,pTake): <NEW_LINE> <INDENT> pass
Get the count of TimeWarp in a Take. pTake : The Take queried. return : the TimeWarp count.
625941e95f7d997b87174f47
def face_up_dealer_initial(self): <NEW_LINE> <INDENT> self._dealt[0].face_up()
Turn up the first dealt of the dealer's cards
625941e9d10714528d600193
def traversal_tree(root: TreeNode) -> list: <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> answer, queue = [], [root] <NEW_LINE> while queue: <NEW_LINE> <INDENT> tmp = [] <NEW_LINE> for _ in range(len(queue)): <NEW_LINE> <INDENT> node = queue.pop(0) <NEW_LINE> tmp.append(node.val) <N...
traversal tree by width
625941e9d486a94d0b98e5f1
def datasets_for_lddas(trans, lddas): <NEW_LINE> <INDENT> dataset_ids = [x.dataset_id for x in lddas] <NEW_LINE> datasets = trans.sa_session.query(trans.app.model.Dataset) .filter(trans.app.model.Dataset.id.in_(dataset_ids)) .all() <NEW_LINE> return datasets
Given a list of LDDAs, return a list of Datasets for them.
625941e930c21e258bdfa94d
def ismember(a, b): <NEW_LINE> <INDENT> a = np.array(a) <NEW_LINE> b = np.array(b) <NEW_LINE> member_ind = np.zeros_like(a) <NEW_LINE> for element in b: <NEW_LINE> <INDENT> member_ind[a == element] = 1 <NEW_LINE> <DEDENT> return member_ind>0
Return an array with the same size of 'a' that indicates if an element of 'a' is in 'b'. Can be used as an index for slicing since it contains bool elements
625941e94d74a7450ccd4670
def stop_job(self, job_id: str, pipeline_name: str, reason: str = None) -> None: <NEW_LINE> <INDENT> message = pps_pb2.StopJobRequest( job=pps_pb2.Job( id=job_id, pipeline=pps_pb2.Pipeline(name=pipeline_name), ), reason=reason, ) <NEW_LINE> self.__stub.StopJob(message)
Stops a subjob (job at the pipeline-level). Parameters ---------- job_id : str The ID of the job. pipeline_name : str The name of the pipeline. reason : str, optional A reason for stopping the job.
625941e924f1403a9260100d
def __init__(self): <NEW_LINE> <INDENT> self.Namespaces = None <NEW_LINE> self.TotalCount = None <NEW_LINE> self.RequestId = None
:param Namespaces: namespace详情 :type Namespaces: list of Namespace :param TotalCount: 返回的namespace数量 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
625941e907f4c71912b1192f
def p_init_declarator_2(p): <NEW_LINE> <INDENT> pass
init_declarator : declarator ASSIGN initializer
625941e9d58c6744b4258109
def clock_on(event): <NEW_LINE> <INDENT> add_clock_window() <NEW_LINE> clock_indicator['background'] = ON
clock_on docs
625941e9851cf427c661a9b6
def extract_name(name_string): <NEW_LINE> <INDENT> if isinstance(name_string, str): <NEW_LINE> <INDENT> name_string = name_string.split() <NEW_LINE> <DEDENT> full_name = name_string[-1] <NEW_LINE> full_name = full_name.split('_') <NEW_LINE> if len(full_name) > 1: <NEW_LINE> <INDENT> roi_name = full_name[0] <NEW_LINE> s...
A helper method to extract the name of the ROI, and separate it into main name, and part name :param name_string: The full string of the line with the name :type name_string: str | list of [str] :return: the first name of the region, and the sub name of the region
625941e9a05bb46b383eccc8
def get_ordered_argument_string(args): <NEW_LINE> <INDENT> args_copy = dict(args) <NEW_LINE> if 'signature' in args_copy: <NEW_LINE> <INDENT> del args_copy['signature'] <NEW_LINE> <DEDENT> ordered_args = [] <NEW_LINE> for arg in sorted(args_copy): <NEW_LINE> <INDENT> ordered_args.append( (arg, args_copy[arg]) ) <NEW_LI...
Sort and urlencode the given dict
625941e9a79ad161976cc5f0
def homo_lumo_mix(C, nocc, beta): <NEW_LINE> <INDENT> if beta < 0. or beta > 1.: <NEW_LINE> <INDENT> raise Exception("Mixing beta must be in [0, 1]") <NEW_LINE> <DEDENT> Cb = C.copy() <NEW_LINE> homo = C[:, nocc - 1] <NEW_LINE> lumo = C[:, nocc] <NEW_LINE> Cb[:, nocc - 1] = (1. - beta) ** 0.5 * homo + beta ** 0.5 * lum...
Mix a portion of LUMO to HOMO. Used when generating spin-unrestricted guess.
625941e9ff9c53063f47c69c
def get_users( start: datetime, end: datetime, repo: Optional[str] = None, db: Optional[DbEngine] = None, session: Optional[Session] = None, ) -> List[User]: <NEW_LINE> <INDENT> key = get_key(repo, start, end, 'User') <NEW_LINE> cache = loads_item(db, key) <NEW_LINE> if cache is not None: <NEW_LINE> <INDENT> return cac...
getting users committed for given repo in given time period :param start: lower time border :param end: upper time border :param repo: repo name :param db: database instance :param session: Request context
625941e9cad5886f8bd27483
def receive_classical_int_list(self, list_max_length: int): <NEW_LINE> <INDENT> message_max_length = 1 + list_max_length * 2 <NEW_LINE> msg = list(self.recv_msg_my(msg_size=message_max_length)) <NEW_LINE> assert not (msg[0] != 0 and len(msg) % 2 == 0) <NEW_LINE> is_factors_list_needed = msg[0] <NEW_LINE> msg = msg[1:] ...
This function was made to avoid error when receiving empty lists or integers >256. :param list_max_length: The expected maximum length or received list. :return:
625941e915fb5d323cde0fc1
def parse_fastqc_per_seq_gc_content(sample, file): <NEW_LINE> <INDENT> fqc = parse_fastqc(sample, file, field='Per sequence GC content') <NEW_LINE> df = fqc.df <NEW_LINE> df['sample'] = sample <NEW_LINE> return df.set_index(append=True, keys='sample').swaplevel()
Parse fastqc Per Seq GC Content Parameters ---------- sample : str Sample name which will be added as row index. file : str Path to the fastqc zip file.
625941e94f6381625f114ee6
def _phi_recip(zs,rs,R,alpha,kc): <NEW_LINE> <INDENT> from cmath import exp <NEW_LINE> Um = 0 <NEW_LINE> V = np.dot(R[0],np.cross(R[1],R[2])) <NEW_LINE> k1 = 2*np.pi*np.cross(R[1],R[2])/V <NEW_LINE> k2 = 2*np.pi*np.cross(R[2],R[0])/V <NEW_LINE> k3 = 2*np.pi*np.cross(R[0],R[1])/V <NEW_LINE> K = np.array([k1,k2,k3]) <NEW...
Finds the reciprocal space portion of the ewald summation. Args: zs (list of int): The amount of charge on each nucleus. rs (list of list of float): Each entry contains the position of an atom. R (list of list of float): The lattice vectors. alpha (float): The ewald summation parameter. kc (float):...
625941e92eb69b55b151cd61
def name_variable(edge, prefix="x"): <NEW_LINE> <INDENT> return "{}_{},{}".format(prefix, *edge)
Create a variable name
625941e963b5f9789fde7591
def __init__(self, name, inputs=[], outputs=[]): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.inputs = inputs <NEW_LINE> self.outputs = outputs <NEW_LINE> super(FunctionText, self).__init__()
name is the function name (string). inputs is a list of variables. ditto outputs.
625941e98e05c05ec3eea824
def send_review_2(self, reviewer_id, manager_id, review_id): <NEW_LINE> <INDENT> if self._user_manager.has_role(reviewer_id, 'reviewer') and self._user_manager.has_role(manager_id, 'manager'): <NEW_LINE> <INDENT> message = "review2: {} from {} to {}".format(review_id, reviewer_id, manager_id) <NEW_LINE> ...
Response to request 2
625941e97b25080760e39901
def __init__(self, host=None, port=3306, user='root', password='', charset='utf8', database=None, **kw ): <NEW_LINE> <INDENT> self.conn = pymysql.connect( host=host, port=port, user=user, password=password, charset=charset, database=database, **kw ) <NEW_LINE> self.cursor = self.conn.cursor()
初始化数据库
625941e9711fe17d8254280c
def __init__(self, chrom_sizes_dict): <NEW_LINE> <INDENT> self.chrom_sizes_dict = chrom_sizes_dict
Define chromosome sizes. :param chrom_sizes_dict: dictionary with chromosome names as key and chromosome lengths as values. :return: ChromSizes object
625941e9a4f1c619b28b04d9
def rollback_snapshot(vm, name, key='uuid'): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> if key not in ['uuid', 'alias', 'hostname']: <NEW_LINE> <INDENT> ret['Error'] = 'Key must be either uuid, alias or hostname' <NEW_LINE> return ret <NEW_LINE> <DEDENT> vm = lookup('{0}={1}'.format(key, vm), one=True) <NEW_LINE> if 'Erro...
Rollback snapshot of a vm vm : string vm to be targeted name : string snapshot name The snapname must be 64 characters or less and must only contain alphanumeric characters and characters in the set [-_.:%] to comply with ZFS restrictions. key : string [uuid|alias|hostname] value ty...
625941e9cad5886f8bd27484
def get_legal_moves(self, player=None): <NEW_LINE> <INDENT> if player is None: <NEW_LINE> <INDENT> player = self.active_player <NEW_LINE> <DEDENT> return self.__get_moves__(self.get_player_location(player))
Return the list of all legal moves for the specified player. Parameters ---------- player : object (optional) An object registered as a player in the current game. If None, return the legal moves for the active player on the board. Returns ------- list<(int, int)> The list of coordinate pairs (row, column...
625941e9e1aae11d1e74a167
def get_quaternion_product(q1, q2, convention='xyzw'): <NEW_LINE> <INDENT> if type(q1) != type(q2): <NEW_LINE> <INDENT> raise TypeError("Expecting q1 and q2 to be of the same type") <NEW_LINE> <DEDENT> if isinstance(q1, quaternion.quaternion): <NEW_LINE> <INDENT> return q1*q2 <NEW_LINE> <DEDENT> elif isinstance(q1, Ite...
Return the quaternion product between two quaternions. The quaternion corresponding to the product :math:`R_1 R_2` where :math:`R_i` are rotation matrices is given by :math:`q_1 * q_2`. Args: q1 (np.array[float[4]], quaternion.quaternion): first quaternion q2 (np.array[float[4]], quaternion.quaternion): secon...
625941e9cdde0d52a9e534e2
def HostGetShortNameFailedEvent(vim, *args, **kwargs): <NEW_LINE> <INDENT> obj = vim.client.factory.create('{urn:vim25}HostGetShortNameFailedEvent') <NEW_LINE> if (len(args) + len(kwargs)) < 4: <NEW_LINE> <INDENT> raise IndexError('Expected at least 5 arguments got: %d' % len(args)) <NEW_LINE> <DEDENT> required = [ 'ch...
This event records that hostname -s failed or returned a name containing '.'.
625941e996565a6dacc8fb75
def generate_subplot_grid(nparam=2): <NEW_LINE> <INDENT> ns1 = math.ceil(math.sqrt(nparam)) <NEW_LINE> ns2 = round(math.sqrt(nparam)) <NEW_LINE> return ns1, ns2
Generate subplot grid. For example, if `nparam` = 2, then the subplot will have 2 rows and 1 column. Args: * **nparam** (:py:class:`int`): Number of parameters Returns: * **ns1** (:py:class:`int`): Number of rows in subplot * **ns2** (:py:class:`int`): Number of columns in subplot
625941e93eb6a72ae02ec995
@xfail <NEW_LINE> def test_topic(): <NEW_LINE> <INDENT> assert False
Expect to filter results to topics.
625941e97047854f462a18af
def lcm(ipt_a, ipt_b): <NEW_LINE> <INDENT> a = ipt_a <NEW_LINE> b = ipt_b <NEW_LINE> while b != 0: <NEW_LINE> <INDENT> c = a % b <NEW_LINE> a = b <NEW_LINE> b = c <NEW_LINE> <DEDENT> result = int(ipt_a * ipt_b / a) <NEW_LINE> return result
求两个整数的最小公倍数 已验证
625941e960cbc95b062c69ef
def annotate(self, images=None, requests_pb=None): <NEW_LINE> <INDENT> if any([images, requests_pb]) is False: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> requests = [] <NEW_LINE> if requests_pb is None: <NEW_LINE> <INDENT> for image, features in images: <NEW_LINE> <INDENT> requests.append(_make_request(image, fe...
Annotate an image to discover it's attributes. :type images: list of :class:`~google.cloud.vision.image.Image` :param images: A list of ``Image``. :rtype: list :returns: List of :class:`~googe.cloud.vision.annotations.Annotations`. :type requests_pb: list :param requests_pb: List of :class:`google.cloud.vision_v1.pr...
625941e9d10714528d600194
def __init__(self, db_obj, **kwargs): <NEW_LINE> <INDENT> self.db_obj = db_obj <NEW_LINE> super(DbWorkflowEngine, self).__init__()
Instantiate a new BibWorkflowEngine object. :param db_obj: the workflow engine :type db_obj: Workflow This object is needed to run a workflow and control the workflow, like at which step of the workflow execution is currently at, as well as control object manipulation inside the workflow. You can pass several parame...
625941e9f9cc0f698b140aa3
def get_default_prefix() -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> default_prefix = get("ARTHUR_DEFAULT_PREFIX") <NEW_LINE> <DEDENT> except (KeyError, ValueError): <NEW_LINE> <INDENT> default_prefix = os.environ.get("USER", "") <NEW_LINE> if len(default_prefix) == 0: <NEW_LINE> <INDENT> default_prefix = getp...
Return default prefix, gleaned from the environment in ARTHUR_DEFAULT_PREFIX or USER. We have a last resort by checking the user name using the getapass module. >>> os.environ["ARTHUR_DEFAULT_PREFIX"] = "doctest" >>> get_default_prefix() 'doctest'
625941e9b7558d58953c53b5
def compile_code(text_code: typing.Union[types.CodeType, str]) -> types.CodeType: <NEW_LINE> <INDENT> if isinstance(text_code, str): <NEW_LINE> <INDENT> code = compile(text_code, '<stdin>', 'exec') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code = text_code <NEW_LINE> <DEDENT> for const in code.co_consts: <NEW_LINE>...
This is utility function with primary purpose to convert string code to code type. Secondary purpose - print byte code for text_code and all nested text_code :param text_code: text code for compiling :return: compiled code
625941e944b2445a3393253e
def deleteCoupon(self, shop_id, coupon_id): <NEW_LINE> <INDENT> endpoint = '/shops/%s/coupons/%s' % (shop_id, coupon_id) <NEW_LINE> self.params = {} <NEW_LINE> self.params['shop_id'] = shop_id <NEW_LINE> self.params['coupon_id'] = coupon_id <NEW_LINE> response = self.execute(endpoint, 'delete') <NEW_LINE> return json.l...
Deletes a coupon
625941e9a8370b7717052d49
def __str__(self): <NEW_LINE> <INDENT> text = ("EventSynchronizationClimateNetwork:\n%s\n%s\n" "Type of event synchronization to construct the network: %s") <NEW_LINE> return text % (EventSynchronization.__str__(self), ClimateNetwork.__str__(self), self.__eventsynctype)
Return a string representation of TsonisClimateNetwork. **Example:** >>> data = EventSynchronizationClimateNetwork.SmallTestData() >>> print(EventSynchronizationClimateNetwork(data, 0.8, 16)) Extracting network adjacency matrix by thresholding... Setting area weights according to type surface... Setting area weights ...
625941e997e22403b379d447
def TemplateFiles(path): <NEW_LINE> <INDENT> rv = {} <NEW_LINE> includes = [] <NEW_LINE> excludes = [] <NEW_LINE> if os.path.exists(path) == False: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if os.path.isdir(path): <NEW_LINE> <INDENT> base_dir = path <NEW_LINE> cfg_file = path + "/config" <NEW_LINE> <DEDENT> e...
Load a ConfigParser file as a configuration file. Look for a section labeled "Files", "exclude" and "include" otions. Return both in a dictionary; the value is an array of files to include or exclude. (The files may be paths, or shell-style globs.)
625941e95fcc89381b1e1b6e
def __init__(self, benchmark): <NEW_LINE> <INDENT> self.allCreatedFiles = [] <NEW_LINE> self.benchmark = benchmark <NEW_LINE> self.statistics = Statistics() <NEW_LINE> self.runSet = None <NEW_LINE> sysinfo = None <NEW_LINE> if not self.benchmark.config.cloud and not self.benchmark.config.appengine: <NEW_LINE> <INDENT> ...
The constructor of OutputHandler collects information about the benchmark and the computer.
625941e930c21e258bdfa94e
def callback(self, diagnostic_array): <NEW_LINE> <INDENT> warnings, errors, stale = 0, 0, 0 <NEW_LINE> statuses = list() <NEW_LINE> for status in diagnostic_array.status: <NEW_LINE> <INDENT> included = False <NEW_LINE> if self.check_include: <NEW_LINE> <INDENT> for regex in self.include_re: <NEW_LINE> <INDENT> if regex...
Main callback for diagnostic messages. Updates status of warnings/errors
625941e9925a0f43d254a327
def test_event_ok_disables_is_event(self): <NEW_LINE> <INDENT> self.product_new.is_event = True <NEW_LINE> self.product_new._onchange_is_event() <NEW_LINE> self.product_new.event_ok = True <NEW_LINE> self.product_new.update( self.product_new.onchange_event_ok( self.product_new.event_type_id, self.product_new.event_ok)....
Setting ``event_ok`` disables ``is_event``.
625941e926238365f5f0f321
def find_containers(self): <NEW_LINE> <INDENT> notifiers_count = 0 <NEW_LINE> for container in self.client.containers.list(): <NEW_LINE> <INDENT> if fnmatch(container.name, self.container_name_pattern): <NEW_LINE> <INDENT> notifiers = self.watch_container(container.name) <NEW_LINE> logging.info( 'Container %s has %i wa...
Traverse running containers and spawn notifiers for mounts matching patterns.
625941e992d797404e304638
def test_user_data_form_no_last_name(self): <NEW_LINE> <INDENT> form = UserDataForm({ 'first_name': 'Joe', 'last_name': '', 'email': 'test@hotmail.co.uk' }) <NEW_LINE> self.assertFalse(form.is_valid())
Test UserDataForm without last name
625941e98a349b6b435e861e
@login_required <NEW_LINE> def download_vcard(request, vcard=VCard): <NEW_LINE> <INDENT> pk = request.GET.get('id'); <NEW_LINE> contact = Contact.objects.get(pk=pk) <NEW_LINE> output = vcard(contact).output_string() <NEW_LINE> filename = "contact_%s%s.vcf" % (contact.first_name, contact.last_name) <NEW_LINE> response =...
View function for returning single vcard
625941e9507cdc57c6307191
def pytest_configure(): <NEW_LINE> <INDENT> from django.conf import settings <NEW_LINE> MIDDLEWARE = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', )...
Configure pytest.
625941e9460517430c394624
def export_data( self, name, output_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): <NEW_LINE> <INDENT> if "export_data" not in self._inner_api_calls: <NEW_LINE> <INDENT> self._inner_api_calls[ "export_data" ] = google.api_core.gapic_v1.method.wr...
Exports dataset's data to the provided output location. Returns an empty response in the ``response`` field when it completes. Example: >>> from google.cloud import automl_v1 >>> >>> client = automl_v1.AutoMlClient() >>> >>> name = client.dataset_path('[PROJECT]', '[LOCATION]', '[DATASET]') >>>...
625941e93617ad0b5ed683a2
def inspect_disks(self, instance_name): <NEW_LINE> <INDENT> raise NotImplementedError()
Inspect the disk statistics for an instance. :param instance_name: the name of the target instance :return: for each disk, the number of bytes & operations read and written, and the error count
625941e97d43ff24873a3150
def key(): <NEW_LINE> <INDENT> user_key = int(input("what should the rotation of the alphabet be (0-25) ")) <NEW_LINE> return user_key
this gets the key from the user :return: this returns the function
625941e93cc13d1c6d3c7824
def prep_msg(self, msg): <NEW_LINE> <INDENT> self.msg_image = self.font.render(msg, True, self.text_color) <NEW_LINE> self.msg_image_rect = self.msg_image.get_rect() <NEW_LINE> self.msg_image_rect.centerx = self.rect.centerx + 6 <NEW_LINE> self.msg_image_rect.centery = self.rect.centery
Turn msg into a rendered image and center text on the button
625941e9ec188e330fd5ac41
def test_text(self): <NEW_LINE> <INDENT> self.answer = main.translate_it(config.output_file)['text'] <NEW_LINE> self.equal_data = ['Hi'] <NEW_LINE> self.assertEqual(self.answer, self.equal_data, 'проблемы с переводом') <NEW_LINE> self.assertIsNot(self.answer, self.equal_data, 'один и тот же объект')
тест правильности перевода слова 'привет'
625941e9fb3f5b602dac3b44
def __init__(self, n=30): <NEW_LINE> <INDENT> Problem.__init__(self) <NEW_LINE> self.name = PPS2.__name__ <NEW_LINE> self.decisions = [Decision("x1",0,1)] + [Decision("x"+str(index+1),-1,1) for index in xrange(1, n)] <NEW_LINE> self.objectives = [Objective("f1", True, 0, 1000), Objective("f2", True, 0, 1000)]
Initialize the problem :param n: Number of decisions :return:
625941e9d18da76e23532988
@spice_error_check <NEW_LINE> def dskrb2( vrtces: ndarray, plates: ndarray, corsys: int, corpar: ndarray ) -> Tuple[float, float]: <NEW_LINE> <INDENT> nv = ctypes.c_int(len(vrtces)) <NEW_LINE> vrtces = stypes.to_double_matrix(vrtces) <NEW_LINE> np = ctypes.c_int(len(plates)) <NEW_LINE> plates = stypes.to_int_matrix(pla...
Determine range bounds for a set of triangular plates to be stored in a type 2 DSK segment. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskrb2_c.html :param vrtces: Vertices :param plates: Plates :param corsys: DSK coordinate system code :param corpar: DSK coordinate system parameters :return: Lower and ...
625941e915baa723493c4425
def get_client(hostname=None, username=None, password=None, key_filename=None, timeout=None): <NEW_LINE> <INDENT> if hostname is None: <NEW_LINE> <INDENT> hostname = settings.server.hostname <NEW_LINE> <DEDENT> if username is None: <NEW_LINE> <INDENT> username = settings.server.ssh_username <NEW_LINE> <DEDENT> if key_f...
Returns a SSH client connected to given hostname
625941e97c178a314d6ef913
def compressWithGZIP(self, fullPath): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(fullPath, 'rb') as f_in: <NEW_LINE> <INDENT> with gzip.open(fullPath + '.gz', 'wb') as f_out: <NEW_LINE> <INDENT> shutil.copyfileobj(f_in, f_out) <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> except IOError as e:...
Ha a hiba tortent: return False, vagyis a tomoritendo fajlt nem engedje torolni a muvelet vegen.
625941e9fff4ab517eb2f8eb
def decrypt(self, key_password): <NEW_LINE> <INDENT> pass
Does nothing for this entry type; these entries stored arbitrary user-supplied data, unclear how to decrypt (may not be encrypted at all).
625941e9d4950a0f3b08c7f4
def shortestBridge(self, A: List[List[int]]) -> int: <NEW_LINE> <INDENT> m, n = len(A), len(A[0]) <NEW_LINE> queue, visited, marked = deque(), set(), False <NEW_LINE> def dfs(A, i, j, q, visited): <NEW_LINE> <INDENT> if(i<0 or j < 0 or i>=len(A) or j >= len(A[0]) or (i,j) in visited or A[i][j] == 0): <NEW_LINE> <INDENT...
Since there are only two islands, we can firstly use dfs to find one, and push these points into queue , and then use bfs to find the remaining one
625941e9004d5f362079a7dc
def validate(self): <NEW_LINE> <INDENT> pass
Abstract function that will validate the parameters of the command. It will be implemented in every command
625941e93eb6a72ae02ec996
def train(self, X, y, iteration=1000): <NEW_LINE> <INDENT> data_num = X.shape[0] <NEW_LINE> feature_size = X.shape[1] <NEW_LINE> it = 0 <NEW_LINE> if self.is_dual: <NEW_LINE> <INDENT> gram_matrix = np.matmul(X, np.transpose(X)) <NEW_LINE> self.a = np.zeros(data_num) <NEW_LINE> self.b = np.zeros(1) <NEW_LINE> while it <...
param X: numpy.array, [None, size of feature vector], batches of feature vectors params y: numpy.array, [None, 1], batches of labels return trained parameters
625941e901c39578d7e752e7
def get_host_architecture(): <NEW_LINE> <INDENT> machine = os.uname()[-1] <NEW_LINE> table = { 'x86_64': 'x86_64', 'i386': 'x86_32', 'i486': 'x86_32', 'i586': 'x86_32', 'i686': 'x86_32', 'armv7l': 'armv7l', 'armv7b': 'armv7b', 'armv8l': 'armv8l', 'armv8b': 'armv8b', 'aarch64': 'armv8l64', 'aarch64b': 'armv8b64', 'ppc64...
Get the canonical Morph name for the host's architecture.
625941e910dbd63aa1bd304e
def single_acc(id_to_emd_1, id_to_emd_2): <NEW_LINE> <INDENT> similarity, label_to_id_1, label_to_id_2 = get_similarity(id_to_emd_1, id_to_emd_2) <NEW_LINE> acc = [] <NEW_LINE> res = {} <NEW_LINE> for k in [1, 3, 5, 10, 50]: <NEW_LINE> <INDENT> tmp_search_rc = [] <NEW_LINE> true_num = 0 <NEW_LINE> _, indices = similari...
id_to_emd_1: 被查询的emb id_to_emd_2: 查询emb
625941e92eb69b55b151cd62
def format_print(s, length): <NEW_LINE> <INDENT> if re.match('[\u4e00-\u9fa5]+', s): <NEW_LINE> <INDENT> return s.ljust(length, chr(12288)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s.ljust(length, ' ')
格式化输出, 区分出汉字和ascii的填充字符
625941e9287bf620b61d3f0d
def __str__(self) -> str: <NEW_LINE> <INDENT> return "MovableSegment[low=" + str(self.low) + ", high=" + str(self.high) + ", speed=" + str(self.speed) + "]"
Returns a description string of the object. Returns ------- string: str The string object description.
625941e98a349b6b435e861f
def load_app(self): <NEW_LINE> <INDENT> __traceback_hide__ = True <NEW_LINE> if self._loaded_app is not None: <NEW_LINE> <INDENT> return self._loaded_app <NEW_LINE> <DEDENT> app = None <NEW_LINE> if self.create_app is not None: <NEW_LINE> <INDENT> app = call_factory(self, self.create_app) <NEW_LINE> <DEDENT> else: <NEW...
Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.
625941e9a8ecb033257d3577