code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_formatted_name(first_name, last_name, middle_name="",): <NEW_LINE> <INDENT> if middle_name: <NEW_LINE> <INDENT> full_name = f"{first_name} {middle_name} {last_name}" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> full_name = f"{first_name} {last_name}" <NEW_LINE> <DEDENT> return full_name.title()
Return a fullname, neatly formatted.
625941ef3539df3088e2e8b9
def test_setKeysCiphers(self): <NEW_LINE> <INDENT> key = b'\x00' * 64 <NEW_LINE> for cipName in transport.SSHTransportBase.supportedCiphers: <NEW_LINE> <INDENT> modName, keySize, counter = transport.SSHCiphers.cipherMap[cipName] <NEW_LINE> encCipher = transport.SSHCiphers(cipName, b'none', b'none', b'none') <NEW_LINE> ...
Test that setKeys sets up the ciphers.
625941efa79ad161976cc6b3
def Get_contract_price(currency_type, contract_type): <NEW_LINE> <INDENT> for i in range(2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp = api.get_contract_price(currency_type, contract_type) <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> print(resp) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("resp"...
@output: {"symbol":"BTC","contract_code":"BTC190705","contract_type":"next_week","high_limit":11101.490000000000000000000000000000000000,"low_limit":10440.870000000000000000000000000000000000}
625941ef7c178a314d6ef9d6
def convert_2d_to_3d( contnrs, max_variants_per_compound, thoroughness, num_procs, job_manager, parallelizer_obj, ): <NEW_LINE> <INDENT> Utils.log("Converting all molecules to 3D structures.") <NEW_LINE> params = [] <NEW_LINE> for contnr in contnrs: <NEW_LINE> <INDENT> for mol in contnr.mols: <NEW_LINE> <INDENT> params...
Converts the 1D smiles strings into 3D small-molecule models. :param contnrs: A list of containers (MolContainer.MolContainer). :type contnrs: list :param max_variants_per_compound: To control the combinatorial explosion, only this number of variants (molecules) will be advanced to the next step. :type max_varia...
625941ef4f6381625f114fa8
def delete_extra(self, session, _id, db_content, not_send_msg=None): <NEW_LINE> <INDENT> self.fs.file_delete(_id, ignore_non_exist=True) <NEW_LINE> self.db.del_list("nslcmops", {"nsInstanceId": _id}) <NEW_LINE> self.db.del_list("vnfrs", {"nsr-id-ref": _id}) <NEW_LINE> self.db.set_list("pdus", {"_admin.usage.nsr_id": _i...
Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem. Set usageState of pdu, vnfd, nsd :param session: contains "username", "admin", "force", "public", "project_id", "set_project" :param _id: server internal id :param db_content: The database content of the descriptor :param not_send_msg:...
625941ef2c8b7c6e89b35d2a
def delete_docs(self, ids, step=None): <NEW_LINE> <INDENT> index_name = self._index <NEW_LINE> doc_type = self._doc_type <NEW_LINE> step = step or self.step <NEW_LINE> def _get_bulk(_id): <NEW_LINE> <INDENT> doc = { '_op_type': 'delete', "_index": index_name, "_type": doc_type, "_id": _id } <NEW_LINE> return doc <NEW_L...
delete a list of docs in bulk.
625941ef1f037a2d8b94676a
def Go(self): <NEW_LINE> <INDENT> self.startCallFunction() <NEW_LINE> self.display.Running() <NEW_LINE> while(self.isGameTerminated == False): <NEW_LINE> <INDENT> self.display.TurnStarted(turn = self.turn, time = self.time) <NEW_LINE> result = None <NEW_LINE> action = None <NEW_LINE> top = None <NEW_LINE> if(self.turn ...
Indicates the start of the gameplay. If this function is executed, the program falls in to this loop of gameplay, which sides of board taking actions one by one.
625941ef236d856c2ad44d50
def alter(self, name: Optional[str] = None, description: Optional[str] = None, device_properties: Optional[Union[Dictable, dict]] = None): <NEW_LINE> <INDENT> device_properties = self.device_properties if not device_properties else device_properties <NEW_LINE> device_properties = device_properties.to_dict() if isinstan...
Alter the device object properties. Args: name: device object name description: device object description device_properties: properties of the device, specific for each device type
625941ef3617ad0b5ed68464
def test_hand_value_should_correctly_identify_straight(): <NEW_LINE> <INDENT> straight = PokerHand('TD 8S 9C JD QH') <NEW_LINE> assert cph.hand_value(straight) == HandValue.STRAIGHT
GIVEN: A straight flush poker hand. WHEN: We identify its hand value. THEN: It should be correctly classified as a straight flush.
625941ef92d797404e3046fa
def merge(s1, s2): <NEW_LINE> <INDENT> if len(s1)==0: <NEW_LINE> <INDENT> return s2 <NEW_LINE> <DEDENT> elif len(s2)==0: <NEW_LINE> <INDENT> return s1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if s1[0]<s2[0]: <NEW_LINE> <INDENT> return [s1[0]]+merge(s1[1:],s2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [s...
Merges two sorted lists >>> merge([1, 3], [2, 4]) [1, 2, 3, 4] >>> merge([1, 2], []) [1, 2]
625941efdc8b845886cb5aa4
def onFoeMaybeTrapPokemon (pokemon, source): <NEW_LINE> <INDENT> pass
function (pokemon, source) { if (!source) source = this.effectState.target; if (!source || !pokemon.isAdjacent(source)) return; if (pokemon.isGrounded(!pokemon.knownType)) { // Negate immunity if the type is unknown pokemon.maybeTrapped = True; ...
625941eff9cc0f698b140b64
def index_vnf(fields, filename, final_path, new_version): <NEW_LINE> <INDENT> user = get_user() <NEW_LINE> fields['user'] = user <NEW_LINE> fields['visibility'] = str_to_bool(request.form.get('visibility', 1)) <NEW_LINE> data_ind = {'name': fields['name'], 'description': fields['description'], 'vendor': fields['vendor'...
Indexing function for VNFs
625941ef4a966d76dd551583
def test_registers_as_task(self): <NEW_LINE> <INDENT> l = lambda x: x <NEW_LINE> l.__name__ = 'test' <NEW_LINE> self.router.node(['test'], celery_task=self.celery.task)(l) <NEW_LINE> self.assertTrue( isinstance(self.router.functions[prefix('test')], Task) )
registers the function as a task
625941ef090684286d50f25c
def add_bCs(self): <NEW_LINE> <INDENT> bCs = OxmlElement('w:bCs') <NEW_LINE> self.insert(0, bCs) <NEW_LINE> return bCs
Return a newly added <w:bCs/> child element.
625941ef046cf37aa974d2af
def get_turbine_types(print_out=True, **kwargs): <NEW_LINE> <INDENT> df = read_turbine_data(**kwargs) <NEW_LINE> if print_out: <NEW_LINE> <INDENT> pd.set_option('display.max_rows', len(df)) <NEW_LINE> print(df[['turbine_id', 'p_nom']]) <NEW_LINE> pd.reset_option('display.max_rows') <NEW_LINE> <DEDENT> return df[['turbi...
Get the names of all possible wind turbine types for which the power coefficient curve or power curve is provided in the data files in the directory windpowerlib/data. Parameters ---------- print_out : boolean Directly prints the list of types if set to True. Default: True. Other Parameters ---------------- datap...
625941ef4e696a04525c99bb
def print_jobs(job_list): <NEW_LINE> <INDENT> name_len = 10 <NEW_LINE> for k, v in job_list.items(): <NEW_LINE> <INDENT> name_len = max([name_len, len(v['job_name'])]) <NEW_LINE> <DEDENT> name_len = name_len + 2 <NEW_LINE> print("Job_ID".ljust(8) + "Job_Name".ljust(name_len) + "Job_Type".ljust(10) + "Queue".ljust(13) +...
Pretty print a list of running interactive jobs from create_queue
625941ef6e29344779a62b7e
def create_user(first_name, last_name, password): <NEW_LINE> <INDENT> new_user = User(first_name, last_name, password) <NEW_LINE> return new_user
Function to create a new user_list
625941ef1d351010ab856088
def ndb(self, fi_ndx): <NEW_LINE> <INDENT> if fi_ndx >= len(self.__dct_ndb): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__dct_ndb[fi_ndx]
return a pointer to the NDB with specified index
625941ef091ae356686674c3
def crossOver(self): <NEW_LINE> <INDENT> while len(self.getPopulation()) < self.getPopulationSize(): <NEW_LINE> <INDENT> [positionA, positionB] = self.randomSelectedPos() <NEW_LINE> nodeA = self.getPopulation()[positionA][0] <NEW_LINE> nodeB = self.getPopulation()[positionB][0] <NEW_LINE> child = self.crossOverWeights(...
Creates new neural networks offspring members for the population by mixing random features of two random neural networks from the selected population.
625941efbaa26c4b54cb1687
def make_the_path(): <NEW_LINE> <INDENT> global history, join_path <NEW_LINE> history = [] <NEW_LINE> join_path = [] <NEW_LINE> the_path = the_path_list() <NEW_LINE> current_position = (-90, 190) <NEW_LINE> history.append(current_position) <NEW_LINE> the_path.remove(current_position) <NEW_LINE> while len(the_path) != 0...
-> this function creates the path by joining the point that is goes to and stores the joined points in a list and a point in the history list
625941ef15baa723493c44e8
def replace_child(old_child: LN, new_child: LN) -> None: <NEW_LINE> <INDENT> parent = old_child.parent <NEW_LINE> if not parent: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> child_idx = old_child.remove() <NEW_LINE> if child_idx is not None: <NEW_LINE> <INDENT> parent.insert_child(child_idx, new_child)
Side Effects: * If @old_child.parent is set, replace @old_child with @new_child in @old_child's underlying Node structure. OR * Otherwise, this function does nothing.
625941ef462c4b4f79d1dc3d
def check_status(i_warning, i_critical, value): <NEW_LINE> <INDENT> test_int(i_warning, i_critical) <NEW_LINE> test_int_or_float(value) <NEW_LINE> if value > i_critical: <NEW_LINE> <INDENT> return 'CRITICAL' <NEW_LINE> <DEDENT> elif value > i_warning: <NEW_LINE> <INDENT> return 'WARNING' <NEW_LINE> <DEDENT> elif value ...
Checks if status is OK, WARNING or CRITICAL Gets: i_warning: Warning Threshold i_critical: Critical Threshold value: value to check against Returns: 'OK'|'WARNING'|'CRITICAL'|'UNKNOWN'
625941ef287bf620b61d3fce
def _weighted_loss(loss, weight): <NEW_LINE> <INDENT> with ops.name_scope(None, "weighted_loss", (loss, weight)) as name: <NEW_LINE> <INDENT> return math_ops.multiply( array_ops.reshape(loss, shape=(-1,)), array_ops.reshape(weight, shape=(-1,)), name=name)
Returns cumulative weighted loss as 1d `Tensor`.
625941efcc0a2c11143dd400
def write(self, headers, key_values): <NEW_LINE> <INDENT> if self.file == None: <NEW_LINE> <INDENT> self.openFile() <NEW_LINE> <DEDENT> f_csv = csv.DictWriter(self.file, headers) <NEW_LINE> f_csv.writeheader() <NEW_LINE> for data in key_values: <NEW_LINE> <INDENT> if self.encoding != "utf-8": <NEW_LINE> <INDENT> for k,...
输出字典 :param headers: :param key_values: :return:
625941ef26068e7796caf255
def get_data_recurrent(n, time_steps, input_dim, attention_column=10): <NEW_LINE> <INDENT> x = np.random.standard_normal(size=(n, time_steps, input_dim)) <NEW_LINE> y = np.random.randint(low=0, high=2, size=(n, 1)) <NEW_LINE> x[:, attention_column, :] = np.tile(y[:], (1, input_dim)) <NEW_LINE> return x, y
Data generation. x is purely random except that it's first value equals the target y. In practice, the network should learn that the target = x[attention_column]. Therefore, most of its attention should be focused on the value addressed by attention_column. :param n: the number of samples to retrieve. :param time_steps...
625941ef7d43ff24873a3213
def loadHiddenTemplates(self): <NEW_LINE> <INDENT> for langK in pywikibot.Family(u'wikipedia').langs.keys(): <NEW_LINE> <INDENT> self.hiddentemplates.append(pywikibot.Page(self.site, u'Template:%s' % langK)) <NEW_LINE> <DEDENT> if self.pageHidden: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pageHiddenText = pywikibot....
Function to load the white templates
625941ef3c8af77a43ae3d15
def p_InitialiserNoIn(self, p): <NEW_LINE> <INDENT> p[0] = p[2]
InitialiserNoIn : EQUALS AssignmentExpressionNoIn
625941ef5fcc89381b1e1c32
def base_dictionary(): <NEW_LINE> <INDENT> return {"chef_type": "environment", "default_attributes": {}, "cookbook_versions": {}, "override_attributes": {}, "json_class": "Chef::Environment", "description": "Environment for Openstack Private Cloud"}
Return Base JSON environment.
625941ef4f88993c3716c5cf
def _load_cls(self, cls_): <NEW_LINE> <INDENT> if isinstance(cls_, tuple): <NEW_LINE> <INDENT> mod = importlib.import_module(cls_[0]) <NEW_LINE> return getattr(mod, cls_[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cls_
Wrapper function to either return cls_ if it is a class or load the class if it is a tuple of the form (package, class_name)
625941efb7558d58953c5476
def paint(self, painter, style_options, model_index): <NEW_LINE> <INDENT> if model_index == self.__current_editor_index: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> WidgetDelegate.paint(self, painter, style_options, model_index)
Paint method to handle all cells that are not being currently edited. :param painter: The painter instance to use when painting :param style_options: The style options to use when painting :type style_options: :class:`~PySide.QtGui.QStyleOptionViewItem` :param model_index: The index in the data mode...
625941ef377c676e91272715
@dajaxice_register <NEW_LINE> def get_filters_for(request): <NEW_LINE> <INDENT> dajax = Dajax() <NEW_LINE> apis = Api.objects.filter(user=User.objects.get(username=request.user)) <NEW_LINE> api_objects = [] <NEW_LINE> plugindir = os.listdir(preferences.BASE_DIR + "/datavis/plugins") <NEW_LINE> for api in apis: <NEW_LIN...
Get filters for a certain location.
625941ef32920d7e50b28743
def get_problem_list(self, course_id, grader_id): <NEW_LINE> <INDENT> params = {'course_id': course_id, 'grader_id': grader_id} <NEW_LINE> result = self.get(self.get_problem_list_url, params) <NEW_LINE> tags = [u'course_id:{}'.format(course_id)] <NEW_LINE> self._record_result('get_problem_list', result, tags) <NEW_LINE...
Get the list of problems for a given course. Args: course_id: course id that we want the problems of grader_id: who is grading this? The anonymous user_id of the grader. Returns: dict with the response from the service. (Deliberately not writing out the fields here--see the docs on the staff_grading...
625941ef1f5feb6acb0c50b8
def set_node_list(self, node_ids: Tuple['NodeId', ...]) -> None: <NEW_LINE> <INDENT> self._nodes = node_ids
set the node list using a tuple contains all the nodes :param node_ids:
625941efa8370b7717052e0c
def read_requirements(filename='requirements.txt'): <NEW_LINE> <INDENT> if not filename.startswith('requirements'): <NEW_LINE> <INDENT> filename = 'requirements-' + filename <NEW_LINE> <DEDENT> if not os.path.splitext(filename)[1]: <NEW_LINE> <INDENT> filename += '.txt' <NEW_LINE> <DEDENT> def valid_line(line): <NEW_LI...
Reads the list of requirements from given file. :param filename: Filename to read the requirements from. Uses ``'requirements.txt'`` by default. :return: Requirments as list of strings.
625941ef73bcbd0ca4b2c5e4
def detect_encoding(filename): <NEW_LINE> <INDENT> detector = UniversalDetector() <NEW_LINE> with open(filename, 'rb') as unknown_file: <NEW_LINE> <INDENT> for line in unknown_file: <NEW_LINE> <INDENT> detector.feed(line) <NEW_LINE> if detector.done: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> detec...
Takes a filename and attempts to detect the character encoding of the file using `chardet`. :param filename: Name of the file to process :type filename: string :returns: encoding : string
625941efeab8aa0e5d26e0c8
def __init__(self, items): <NEW_LINE> <INDENT> if len(items) == 0: <NEW_LINE> <INDENT> self._first = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._first = _Node(items[0]) <NEW_LINE> current_node = self._first <NEW_LINE> for item in items[1:]: <NEW_LINE> <INDENT> current_node.next = _Node(item) <NEW_LINE> cur...
Initialize a new linked list containing the given items. The first node in the linked list contains the first item in <items>. @type self: LinkedList @type items: list @rtype: None
625941ef99fddb7c1c9de8fc
def __make_list_flat(self, l) : <NEW_LINE> <INDENT> ans = [] <NEW_LINE> for i in l: <NEW_LINE> <INDENT> if type(i) is list: <NEW_LINE> <INDENT> ans = self.__make_list_flat(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ans.append(i) <NEW_LINE> <DEDENT> <DEDENT> return ans
@brief sometimes an element of the list might be a list too, so we need to flat the list given in the argument and return the oblate list
625941ef44b2445a33932600
def _show_last(self): <NEW_LINE> <INDENT> def show_state_or_inputs(item, prev = None): <NEW_LINE> <INDENT> values = item.get_str_values() <NEW_LINE> for var in values: <NEW_LINE> <INDENT> if (prev is not None and prev.get_str_values()[var] != values[var] or prev is None) : <NEW_LINE> <INDENT> print(var, "=", values[var...
Show the last BDD. If the size of the last BDD is greater than self.bound, show only a message asking for constraints (and the size of the BDD in terms of states).
625941ef76d4e153a657f0a0
def getUpdateMode(self): <NEW_LINE> <INDENT> if self._manualRB.isChecked(): <NEW_LINE> <INDENT> return UpdateMode.MANUAL <NEW_LINE> <DEDENT> elif self._autoRB.isChecked(): <NEW_LINE> <INDENT> return UpdateMode.AUTO <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError("No mode selected")
Returns update mode (See :meth:`setUpdateMode`). :return: the active update mode :rtype: UpdateMode
625941ef4527f215b584c9c0
def main(): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> screen = pygame.display.set_mode(settings.DISPLAY_SIZE) <NEW_LINE> while 1: <NEW_LINE> <INDENT> level1 = level.Level(screen) <NEW_LINE> level1.run()
your app starts here
625941ef67a9b606de4a8425
def test_args_order_by(testapp): <NEW_LINE> <INDENT> stream = chain.process( testapp, [ holocron.Item({"title": "The Dark Side", "content": "Vader", "id": 3}), holocron.Item({"title": "The Force", "content": "Obi-Wan", "id": 1}), holocron.Item({"title": "Force, The", "content": "Yoda", "id": 2}), ], order_by="id", ) <N...
Chain processor has to respect 'order_by' argument.
625941ef8a43f66fc4b545cd
def __init__(self, filename, logger, ignoreIniHeader=False): <NEW_LINE> <INDENT> self._ignoreIniHeader = ignoreIniHeader <NEW_LINE> self._vars = dict() <NEW_LINE> self._logger = logger <NEW_LINE> if filename is not None: <NEW_LINE> <INDENT> self.readConfig(filename)
Constructor. @param filename: None: the instance remain "empty" otherwise: the filename with path @param logger: the logger @param ignoreIniHeader: True: '[<section>]' will be ignored
625941ef6fb2d068a760f615
def get_pkg_rpm_names(self, pkg, arch=None): <NEW_LINE> <INDENT> if arch is None: <NEW_LINE> <INDENT> arch = utils.get_arch() <NEW_LINE> <DEDENT> rpms = self.get_pkg_rpm_info(pkg, arch) <NEW_LINE> return [rpm['name'] for rpm in rpms]
Gets the names for the RPM packages specified in pkg :type pkg: KojiPkgSpec :param pkg: a package specification :type arch: string :param arch: packages built for this architecture, but also including architecture independent (noarch) packages
625941ef3d592f4c4ed1d5cd
def get_plugin_arguments(plugin_name): <NEW_LINE> <INDENT> plugin = plugins_base.PLUGINS.get_plugin(plugin_name) <NEW_LINE> versions = plugin.get_versions() <NEW_LINE> return {version: plugin.get_image_arguments(version) for version in versions}
Gets plugin arguments, as a dict of version to argument list.
625941ef925a0f43d254a3eb
def handle_biology(self, resp): <NEW_LINE> <INDENT> self.say_text('Handling Biology (in {language})'.format(language=self.get_user_language()))
Handles Biology
625941efd4950a0f3b08c8b5
def test_pass_none(self): <NEW_LINE> <INDENT> self.assertFilterPasses(None)
``None`` always passes this filter. Use ``Required | NodeUri`` to reject null values.
625941efd6c5a102081445be
def test_check_X_categorical_prediction_exceeds_training(wage, wage_gam): <NEW_LINE> <INDENT> X, y = wage <NEW_LINE> gam = wage_gam <NEW_LINE> eks = gam._edge_knots[-1] <NEW_LINE> X[:,-1] = eks[-1] + 1 <NEW_LINE> try: <NEW_LINE> <INDENT> gam.predict(X) <NEW_LINE> assert False <NEW_LINE> <DEDENT> except ValueError: <NEW...
if our categorical variable is outside the training range we should get an error
625941ef4f88993c3716c5d0
def openmooc_settings(request): <NEW_LINE> <INDENT> copy_attrs = ('COURSE_URL', 'COURSE_TITLE', 'COURSE_NAME', 'FULL_ASKBOT_URL', ) <NEW_LINE> custom_settings = {} <NEW_LINE> for key in copy_attrs: <NEW_LINE> <INDENT> custom_settings[key] = getattr(settings, key, '') <NEW_LINE> <DEDENT> if getattr(settings, 'FOOTER_LIN...
The context processor function
625941ef66656f66f7cbc71b
def __init__(self, city, auction_type, payment_rule, drivers_schedule, init_pos, bidding_strategy, driving_velocity=30, payment_ratio=0.3, charge_rate_per_kilometer=60, gas_cost_per_kilometer=4, waiting_time_threshold=15): <NEW_LINE> <INDENT> self.driving_velocity = driving_velocity <NEW_LINE> self.payment_ratio = paym...
city: where the taxi coordinator works on auction_type: auction mechanism drivers_schedule: determine how many drivers in a period. init_pos: initial pos of all drivers
625941efa4f1c619b28b059a
@task <NEW_LINE> def tweet_preprocessing(tweet_data): <NEW_LINE> <INDENT> if tweet_data["lang"] == "en": <NEW_LINE> <INDENT> if tweet_data["text"].startswith("RT"): <NEW_LINE> <INDENT> if tweet_data["retweeted_status"].get("extended_tweet"): <NEW_LINE> <INDENT> tweet_text = tweet_data["retweeted_status"]["extended_twee...
The tweet data will be preprocesed and its relevant fields will be extracted here. :param tweet_data: line returned by twitter streaming API :return:
625941ef16aa5153ce3629e8
def getMaximum(self, arguments, maximun): <NEW_LINE> <INDENT> self.sequence.append({ "type" : "findingMaximum" , "coords" : arguments }) <NEW_LINE> self.sequence.append({ "type" : "foundMaximum" , "coord" : maximun })
A function for recording the fact that the getMaximum function of some subproblem has been called. RUNTIME: O(1)
625941ef442bda511e8be97f
def is_integer(value, min=None, max=None): <NEW_LINE> <INDENT> (min_val, max_val) = _is_num_param(('min', 'max'), (min, max)) <NEW_LINE> if not isinstance(value, int_or_string_types): <NEW_LINE> <INDENT> raise VdtTypeError(value) <NEW_LINE> <DEDENT> if isinstance(value, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT...
A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. >>> vtor = Validator() >>> vtor.check('integer', '-1') -1 >>> v...
625941efd486a94d0b98e6b5
def call_openeye( oe_callable: Callable[[T], bool], *args: T, exception_type: Type[RechargeException] = RuntimeError, exception_kwargs: Dict[str, Any] = None, ): <NEW_LINE> <INDENT> from openeye import oechem <NEW_LINE> if exception_kwargs is None: <NEW_LINE> <INDENT> exception_kwargs = {} <NEW_LINE> <DEDENT> output_st...
Wraps a call to an OpenEye function, either capturing the output in an exception if the function does not complete successfully, or redirecting it to the logger. Parameters ---------- oe_callable The OpenEye function to call. args The arguments to pass to the OpenEye function. exception_type: The type of ex...
625941ef45492302aab5e838
def __init__(self, cursor=None, sort_ascending=None, sort_by=None, result_count=None, results=None, *args, **kwargs): <NEW_LINE> <INDENT> self._cursor = None <NEW_LINE> self._sort_ascending = None <NEW_LINE> self._sort_by = None <NEW_LINE> self._result_count = None <NEW_LINE> self._results = None <NEW_LINE> self.discri...
NSProfileListResult - a model defined in Swagger
625941ef627d3e7fe0d693c0
@algo("Another divide & conquer algorithm") <NEW_LINE> def alternative_dc(words, width): <NEW_LINE> <INDENT> lines, lastline, _ = alternate_dc_helper(list(words), width) <NEW_LINE> lines.append(lastline) <NEW_LINE> return lines
This algorithm recursively splits the list into two parts until having only one word in each one. It then reduces the number of parts by concatenating them until each one reaches the maximum line width.
625941ef8e7ae83300e4b53d
def compat(self): <NEW_LINE> <INDENT> COMPAT_QUEUE = 'dpq:queue:_compat' <NEW_LINE> self.connection.rename(self.key, COMPAT_QUEUE) <NEW_LINE> while True: <NEW_LINE> <INDENT> job_id = self.connection.lpop(COMPAT_QUEUE) <NEW_LINE> if job_id is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if Job.exists(job_id): <NE...
Remove all dead jobs from queue by cycling through it, while guarantueeing FIFO semamtics.
625941ef66673b3332b92600
def _remove_stage(self,stage): <NEW_LINE> <INDENT> s = len(self) <NEW_LINE> A=np.delete(np.delete(self.A,stage,1),stage,0) <NEW_LINE> b=np.delete(self.b,stage) <NEW_LINE> c=np.delete(self.c,stage) <NEW_LINE> self.A=A <NEW_LINE> self.b=b <NEW_LINE> self.c=c <NEW_LINE> if hasattr(self,'bhat'): <NEW_LINE> <INDENT> bhat=np...
Eliminate a stage of a DJ-reducible Runge-Kutta method. Typically used to reduce reducible methods. Note that stages in the NumPy arrays are indexed from zero, so to remove stage j use _remove_stage(j-1).
625941ef3eb6a72ae02eca5c
def _replace_admin_for_model(modeladmin, admin_site): <NEW_LINE> <INDENT> if isinstance(modeladmin, VersionLockAdminMixin): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> new_admin_class = version_lock_admin_factory(modeladmin.__class__) <NEW_LINE> admin_site.unregister(modeladmin.model) <NEW_LINE> admin_site.register(...
Replaces existing admin class registered for `modeladmin.model` with a subclass that includes version locking functionality. Doesn't do anything if `modeladmin` is already an instance of `VersionLockAdminMixin`. :param model: ModelAdmin instance :param admin_site: AdminSite instance
625941ef293b9510aa2c37ff
def magnetic_field(self, fourier=False, cartesian=None, coord=None): <NEW_LINE> <INDENT> if coord is None: <NEW_LINE> <INDENT> raise NotImplementedError("Need a coord for LayeredMode") <NEW_LINE> <DEDENT> H, E=self._construct_fields_(coord, he=True) <NEW_LINE> return self._convert_polar_vector(H, coord, cartesian=carte...
The three component magnetic field (h_r,h_ϕ,h_z) or (hx,hy,hz)
625941ef7d847024c06be830
def write_version_file(package: str, version: str): <NEW_LINE> <INDENT> with open(os.path.join(package, VERSION_FILENAME), 'w') as version_file: <NEW_LINE> <INDENT> version_file.write(version)
Write the version to a file :param package: Name of the package (usually its subdirectory in *src/*) :param version: Version to write
625941ef57b8e32f52483a0e
def execute(self): <NEW_LINE> <INDENT> rows = [] <NEW_LINE> for c in self.config['status-errors']: <NEW_LINE> <INDENT> errors = StatusErrorsParser(c['source'], c['descriptions'], self.config['serverPath'], self.config['restPath']) <NEW_LINE> rows.extend(errors.parse()) <NEW_LINE> <DEDENT> note = 'List of status errors ...
Contains all the logic to execute a command.
625941ef07d97122c4178e08
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_4f7B2f.pack(_x.Curvature, _x.Heading, _x.Left_Dist, _x.Right_Dist, _x.Left_Type, _x.Right_Type, _x.Left_Conf, _x.Right_Conf, _x.Left_LDW_avai, _x.Right_LDW_avai, _x.Constr_Area, _x.YawAngle, _x.PitchAngle)) <...
serialize message into buffer :param buff: buffer, ``StringIO``
625941ef8c3a873295158931
def copyItemById(self, item_id, parent_id, new_name=None): <NEW_LINE> <INDENT> data = { "parentReference": {"id": parent_id}, } <NEW_LINE> if new_name: <NEW_LINE> <INDENT> data["name"] = str(new_name) <NEW_LINE> <DEDENT> url = "%s/drive/items/%s/action.copy" % (self.api_root_uri, item_id) <NEW_LINE> headers = {'Content...
copy item by id
625941ef627d3e7fe0d693c1
def get_class_logger(obj): <NEW_LINE> <INDENT> class_name = obj.__class__.__name__ <NEW_LINE> if hasattr(obj, 'name'): <NEW_LINE> <INDENT> logger_name = '{}({})'.format(class_name, obj.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger_name = class_name <NEW_LINE> <DEDENT> return logging.getLogger(logger_name)
Returns a new logging instance for an class object instance. If the obj instance has a name attribute, it will be included in the logger name. This is useful for using %(name)s in logging your formatter. :param obj an instance of any class
625941ef796e427e537b0b3a
def gcd_ext(a, b): <NEW_LINE> <INDENT> if b == 0: <NEW_LINE> <INDENT> return 1, 0, a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x, y, gcd = gcd_ext(b, a % b) <NEW_LINE> return y, x - y * (a // b), gcd
Extended GCD
625941ef30c21e258bdfaa13
def pop_last(self): <NEW_LINE> <INDENT> if self.Empty(): <NEW_LINE> <INDENT> print('链表为空') <NEW_LINE> return <NEW_LINE> <DEDENT> current = self.head <NEW_LINE> if current.next is None: <NEW_LINE> <INDENT> e = current.val <NEW_LINE> self.head = None <NEW_LINE> return e <NEW_LINE> <DEDENT> while current.next.next != None...
删除链表尾部的元素
625941ef99fddb7c1c9de8fd
def clean(self,positive=True): <NEW_LINE> <INDENT> if 'mask' in list(self.__dict__.keys()): mask = copy.deepcopy(self.mask) <NEW_LINE> else: mask = numpy.zeros(len(self.wave)) <NEW_LINE> mask[numpy.isnan(self.flux.value)==True] = 1 <NEW_LINE> mask[numpy.isnan(self.noise.value)==True] = 1 <NEW_LINE> if postive==True: ma...
Clean spectrum of nan, zero flux, and mask
625941efa8ecb033257d363a
def send_message(self, buddy, message): <NEW_LINE> <INDENT> recipient = buddy <NEW_LINE> if isinstance(buddy, Buddy): <NEW_LINE> <INDENT> recipient = buddy.jid <NEW_LINE> <DEDENT> if not self.is_connected(): <NEW_LINE> <INDENT> weechat.prnt(self.buffer, "%swhatsapp: unable to send message, connection is down" % weechat...
Send a message to buddy. The buddy argument can be either a jid string, eg username@domain.tld/resource or a Buddy object instance.
625941efd99f1b3c44c67af4
def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> order_data = self.order_queue.get() <NEW_LINE> self.order.emit(order_data)
쓰레드에서 order를 받자마자 메인 쓰레드로 보내주기
625941ef004d5f362079a89e
@fn.curry(2) <NEW_LINE> def remainder(denom, number): <NEW_LINE> <INDENT> return _math.remainder(number, denom)
IEEE 754-style remainder of number with respect to denom. (Signal is chosen so remainder has the smaller absolute value). Similar to math.remainder, but curried and with the order of arguments flipped.
625941ef94891a1f4081c01b
def __init__(self, **kwargs): <NEW_LINE> <INDENT> BiasRunTableAnalysisTask.__init__(self, **kwargs)
C'tor Parameters ---------- kwargs Used to override configruation
625941ef56ac1b37e6264734
def positive_elements(self, iterable): <NEW_LINE> <INDENT> if iterable: <NEW_LINE> <INDENT> return all( map(lambda x: isinstance(x, int) and self.positive_num(x), iterable) ) <NEW_LINE> <DEDENT> return False
Checks if the ``iterable`` contains positive ints. :: # valid values [1, 2, 3] [1, 2] (1, ) # invalid values [0, 1] ['a', 'h'] [-5, 10] :param iterable: an iterable of positive ints :return: boolean
625941efcc40096d61595ebd
def internal_convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None, as_ref=False): <NEW_LINE> <INDENT> if not isinstance(values, collections_abc.Iterable): <NEW_LINE> <INDENT> raise TypeError("values must be iterable.") <NEW_LINE> <DEDENT> ret = [] <NEW_LINE> for i, value in enumerate(values): <NEW_LINE> ...
Converts `values` to a list of `Tensor` or `IndexedSlices` objects. Any `IndexedSlices` or `SparseTensor` objects in `values` are returned unmodified. Args: values: An iterable of `None`, `IndexedSlices`, `SparseTensor`, or objects that can be consumed by `convert_to_tensor()`. dtype: (Optional.) The required...
625941ef507cdc57c6307258
def extract_chunk_from_buffer(self, size): <NEW_LINE> <INDENT> data = self.extract_size_from_buffer(size) <NEW_LINE> data = data + self.parse_line_from_buffer() <NEW_LINE> return data
Extract given bytes from the internal buffer and move the read index. returned data may be shorter if EOS is reached. Note that the chunk really ends at the next EOL after this size. So we extract some more bytes.
625941efd53ae8145f87a7d4
def assert_in(x, thing, msg=''): <NEW_LINE> <INDENT> if x not in thing: <NEW_LINE> <INDENT> assert False, msg or '%r is not in %r' % (x, thing)
**DEPRECATED**: use assert instead.
625941ef31939e2706e4d3d1
def history(): <NEW_LINE> <INDENT> global current_account <NEW_LINE> if current_account is None: <NEW_LINE> <INDENT> print('Authorization is required.') <NEW_LINE> return <NEW_LINE> <DEDENT> histories = api.get_transaction_histories(current_account.account_id) <NEW_LINE> if len(histories) < 1: <NEW_LINE> <INDENT> print...
Prints all transaction histories of currently authorized account :return:
625941ef3539df3088e2e8bb
def test_get_metrics_type_choices(self): <NEW_LINE> <INDENT> job_test_utils.create_seed_job_type() <NEW_LINE> metrics_type = MetricsJobType.objects.get_metrics_type(include_choices=True) <NEW_LINE> self.assertEqual(metrics_type.name, 'job-types') <NEW_LINE> self.assertEqual(len(metrics_type.filters), 2) <NEW_LINE> self...
Tests getting the metrics type with choices.
625941ef0c0af96317bb8756
def get_queryset(self, *args, **kwargs): <NEW_LINE> <INDENT> select_sql = {} <NEW_LINE> encrypted_fields = [] <NEW_LINE> for f in self.model._meta.get_fields_with_model(): <NEW_LINE> <INDENT> field = f[0] <NEW_LINE> if isinstance(field, PGPMixin): <NEW_LINE> <INDENT> select_sql[field.name] = self.get_decrypt_sql(field)...
Django queryset.extra() is used here to add decryption sql to query.
625941ef236d856c2ad44d52
def fetch_user_details(token): <NEW_LINE> <INDENT> ret_value = {} <NEW_LINE> try: <NEW_LINE> <INDENT> headers = { "Authorization": "Bearer {}".format(token) } <NEW_LINE> mail_request = requests.get(config.USER_INFO_ENDPOINT, headers=headers) <NEW_LINE> ret_value = json.loads(mail_request.text) <NEW_LINE> <DEDENT> excep...
Function to fetch mail from outlook with ID and token @Param id: message ID @Param token: message token
625941ef99cbb53fe6793154
def __init__(self, mu): <NEW_LINE> <INDENT> object.__init__(self) <NEW_LINE> self.mu = mu
mu is a scalar: the coefficient of kinetic friction. To take energy from the particle, use a negative mu.
625941ef2ae34c7f2600d6a0
def p_ConditionalAndExpression(p): <NEW_LINE> <INDENT> if(len(p)==2): <NEW_LINE> <INDENT> p[0] = p[1] <NEW_LINE> return <NEW_LINE> <DEDENT> tempvar = ST.getTemp() <NEW_LINE> p[0] = { 'place' : tempvar, 'type' : 'UNDEFINED_TYPE' } <NEW_LINE> if p[1]['type']=='UNDEFINED_TYPE' or p[3]['type']=='UNDEFINED_TYPE': <NEW_LINE>...
ConditionalAndExpression : InclusiveOrExpression | ConditionalAndExpression OPAND InclusiveOrExpression
625941ef6e29344779a62b80
def get_module_info(name): <NEW_LINE> <INDENT> module_config = ConfigParser.ConfigParser() <NEW_LINE> with tools.file_open(os.path.join(name, 'tryton.cfg')) as fp: <NEW_LINE> <INDENT> module_config.readfp(fp) <NEW_LINE> directory = os.path.dirname(fp.name) <NEW_LINE> <DEDENT> info = dict(module_config.items('tryton')) ...
Return the content of the tryton.cfg
625941ef01c39578d7e753ab
def profile(clock_type="cpu", profile_builtins=False, return_callback=None): <NEW_LINE> <INDENT> def _profile_dec(func): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> if func._rec_level == 0: <NEW_LINE> <INDENT> clear_stats() <NEW_LINE> set_clock_type(clock_type) <NEW_LINE> start(profile_builtin...
A profile decorator that can be used to profile a single call. We need to clear_stats() on entry/exit of the function unfortunately. As yappi is a per-interpreter resource, we cannot simply resume profiling session upon exit of the function, that is because we _may_ simply change start() params which may differ from t...
625941ef379a373c97cfb0b7
def GetTransfer(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Get information about one transfer. https://developer.token.io/sdk/#get-transfers
625941efdc8b845886cb5aa7
def redirect(path='/', body=None, delay=0): <NEW_LINE> <INDENT> s = '<HTML><HEAD>\n' <NEW_LINE> s += '<meta http-equiv="Refresh" content="%d; url=%s">\n' % (delay, path) <NEW_LINE> s += '</HEAD>\n' <NEW_LINE> if body: <NEW_LINE> <INDENT> s += '<BODY>%s</BODY>\n' % body <NEW_LINE> <DEDENT> s += '</HTML>\n' <NEW_LINE> re...
redirect browser, if desired after showing a message
625941efa219f33f34628ed1
def machine3(self) -> str or float or int: <NEW_LINE> <INDENT> a = self.__selectfrom(dist_table['Taldefax']['GenerationOfElectricity']['machine 3']) <NEW_LINE> return _check_the_data_single(a)
Возвращает последнее значение мощности машины 3
625941ef004d5f362079a89f
def endRendering(self): <NEW_LINE> <INDENT> glFlush()
Leképezés lezárása
625941efa05bb46b383ecd8c
def setfile(self, h5path =defaultFilePath, h5name = defaultFileName, resetFilenum = True): <NEW_LINE> <INDENT> self.h5.FilePath = h5path <NEW_LINE> self.h5.FileName = h5name <NEW_LINE> if resetFilenum == True: <NEW_LINE> <INDENT> self.setfilenum(1)
set the path and file name' keyword: resetFilenum(default=True): reset the file number to 1 when changing the file name
625941ef091ae356686674c5
def spawn_queue_feeder(self, hit_map, hit_to_scan, scan_hit_type_map, hit_to_group=None): <NEW_LINE> <INDENT> feeder_thread = Thread( target=self.feeder, args=(hit_map, hit_to_scan, scan_hit_type_map, hit_to_group)) <NEW_LINE> feeder_thread.daemon = True <NEW_LINE> feeder_thread.start() <NEW_LINE> return feeder_thread
Create a thread to run :meth:`feeder` with the provided arguments so that work can be sent in tandem with waiting for results Parameters ---------- hit_map : dict Maps hit id to structure hit_to_scan : dict Maps hit id to list of scan ids scan_hit_type_map : dict Maps (hit id, scan id) to the type of mass ...
625941ef9b70327d1c4e1348
def authenticate_service(service_name, api_version): <NEW_LINE> <INDENT> credentials = ServiceAccountCredentials.from_json_keyfile_name( filename=KEY_FILE, scopes=SCOPES ) <NEW_LINE> service = build( ANALYTICS_SERVICE, ANALYTICS_SERVICE_VERSION, credentials=credentials ) <NEW_LINE> return service
authenticate google analytics service using service account
625941ef15baa723493c44ea
def add_labels_stellar_components(self): <NEW_LINE> <INDENT> log.info("Adding parameter labels for stellar component properties ...") <NEW_LINE> for parameter_name in self.config.free_parameters: <NEW_LINE> <INDENT> if parameter_name not in free_parameters_relative_stellar_component_paths: continue <NEW_LINE> path, com...
This function ... :return:
625941ef21a7993f00bc826a
def main(args): <NEW_LINE> <INDENT> args.builddir = expand_path(args.builddir) <NEW_LINE> args.workdir = expand_path(args.workdir) <NEW_LINE> args.output = expand_path(args.output) <NEW_LINE> with open(os.path.join(args.builddir, "meson-info", "intro-installed.json")) as ifd: <NEW_LINE> <INDENT> install = json.load(ifd...
Produce library bundle
625941ef462c4b4f79d1dc3f
def get_comments(submission): <NEW_LINE> <INDENT> submission.comments.replace_more(limit=0) <NEW_LINE> comment_data = [comment.body for comment in submission.comments.list()] <NEW_LINE> return comment_data
get comments from submission :param submission: Submission object (sqlite3) :return: comments (string) in list
625941ef442bda511e8be980
def getSelectedTrackway(self): <NEW_LINE> <INDENT> tracks = list() <NEW_LINE> trav = self.getFirstTrack() <NEW_LINE> while trav != None: <NEW_LINE> <INDENT> tracks.append(trav) <NEW_LINE> trav = self.getNextTrack(trav) <NEW_LINE> <DEDENT> return tracks
:return: A list of tracks denoting the selected trackway.
625941ef50485f2cf553d30c
def __init__(self, settings, screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = settings <NEW_LINE> self.image = pygame.image.load('images/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y =...
initialize the alien
625941efab23a570cc2506f7
def map_to_dict_with_lists(lambda_call, list): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for item in list: <NEW_LINE> <INDENT> key, val = lambda_call(item) <NEW_LINE> if result.get(key): <NEW_LINE> <INDENT> result[key].append(val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[key] = [val] <NEW_LINE> <DEDENT> <D...
Maps a list of items to a two item array [item1, item2]. item1s are used as keys of the result dict and item2 are used as array values of the result dict. Thus key item1 has a value of one or more corresponding item2s :param lambda_call: lambda that expects and item and returns a two-item array :param list:...
625941efa8370b7717052e0d
def process(self, gstream): <NEW_LINE> <INDENT> gstream.redistribute("freq") <NEW_LINE> gsv = gstream.vis[:] <NEW_LINE> gsw = gstream.weight[:] <NEW_LINE> gsr = gstream.redundancy[:] <NEW_LINE> el = self.span * np.linspace(-1.0, 1.0, self.npix) <NEW_LINE> hv = containers.HybridVisStream(el=el, axes_from=gstream, attrs_...
Computes the ringmap. Parameters ---------- sstream : VisGridStream The input stream. Returns ------- bf : HybridVisStream
625941ef7b180e01f3dc4d61
def _m_caller(self, method_name, what='value', changed=None, callback=None): <NEW_LINE> <INDENT> function = getattr(self, method_name) <NEW_LINE> if iscoroutinefunction(function): <NEW_LINE> <INDENT> import asyncio <NEW_LINE> @asyncio.coroutine <NEW_LINE> def caller(*events): <NEW_LINE> <INDENT> if callback: callback(*...
Wraps a method call adding support for scheduling a callback before it is executed and skipping events if a subobject has changed but its values have not.
625941efa8370b7717052e0e
def back(self): <NEW_LINE> <INDENT> return _pypl.FloatVectorVector_back(self)
back(FloatVectorVector self) -> FloatVector
625941ef498bea3a759ba01e
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DateHistogramPoint): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941efc432627299f051ba