code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self,dir1,dir2,dir3,dir4,systemcommand): <NEW_LINE> <INDENT> self.main_dir = dir1 <NEW_LINE> self.cif_dir = dir2 <NEW_LINE> self.temp_dir = dir3 <NEW_LINE> self.pot_dir = dir4 <NEW_LINE> self.systemcommand = systemcommand <NEW_LINE> self.keyphrase = ' reached required accuracy - stopping structural energy ...
Initialize local variables : @self.main_dir (parent directory from which all jobs are executed), @self.cif_dir (location of all the cif files), and @self.temp_dir and @self.pot_dir which should be set on MARCC. The system command is sbatch marcc.job, and the keyphrase which is the last line of the std out file.
625941e7ff9c53063f47c65c
def _set_reported_flags(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass( v, base=RestrictedClassType( base_type=int, restriction_dict={"range": ["0..255"]}, int_size=8 ), is_leaf=True, yang_name="reporte...
Setter method for reported_flags, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/rsvp_te/sessions/session/record_route_objects/record_route_object/state/reported_flags (uint8) If this variable is read-only (config: false) in the source YANG file, then _set_reported_flags is consi...
625941e72eb69b55b151cd20
def get_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('host', metavar='IP', type=str, help='server') <NEW_LINE> parser.add_argument('interval', metavar='INTERVAL', type=int, help='(s)') <NEW_LINE> parser.add_argument('-p', '--port') <NEW_LINE> parser.add_argument('-v', '-...
Parse arguments and return dictionary.
625941e799fddb7c1c9de7fa
def p_expression_ne_number(t): <NEW_LINE> <INDENT> t[0] = f"({t[1]} != {t[3]})"
expression : PARAM NE NUMBER
625941e7d6c5a102081444b9
def get_similar_syllables(self): <NEW_LINE> <INDENT> req = requests.get(self.all_syllables_route) <NEW_LINE> dico = json.loads(req.content) <NEW_LINE> language_syllables = dico['result'] <NEW_LINE> for language in self.other_languages: <NEW_LINE> <INDENT> other_language_syllables_routes = self.url + "/" + language + "_...
/!\ this also patches, not just gets :return:
625941e7925a0f43d254a2e6
def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> import matplotlib as mlib <NEW_LINE> from matplotlib import rc <NEW_LINE> import matplotlib.pyplot as plt <NEW_LINE> rc('text', usetex=True) <NEW_LINE> mlib.rcParams['text.latex.preamble'].append(r'\usepackage{amsmath}') <NEW_LINE> mlib.rcParams['text.late...
since this class is not made for exception handling, but for plotting, we do not use the arguments to the method.
625941e74c3428357757c790
def deletePage(self, fireEvent=True): <NEW_LINE> <INDENT> with self.textOperationLock: <NEW_LINE> <INDENT> if self.isReadOnlyEffect(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.isDefined(): <NEW_LINE> <INDENT> self.getWikiData().deleteWord(self.getWikiWord()) <NEW_LINE> <DEDENT> vo = self.getExistingVersio...
Deletes the page from database
625941e7a79ad161976cc5b0
def __init__(self, session, user_id, channel_id, auth_str, base_url, store): <NEW_LINE> <INDENT> super(UserMemory, self).__init__(session, channel_id, auth_str, base_url, store) <NEW_LINE> self.user_id = user_id <NEW_LINE> self.get_data()
Data can be any format for how you want to save. Lists or dictionaries are recommended so you can save multiple items for each conversation.
625941e7be7bc26dc91cda63
def takecycle(elements, n): <NEW_LINE> <INDENT> return thread_first(elements, cycle, (islice, n), list)
Return first n elements of infinite cycle given by elements.
625941e7c432627299f050b4
def glsl_parse_precision(source): <NEW_LINE> <INDENT> (typeid, remaining) = extract_tokens(source, ("precision", "?t", ";")) <NEW_LINE> if typeid: <NEW_LINE> <INDENT> return (GlslBlockPrecision(typeid), remaining) <NEW_LINE> <DEDENT> return (None, source)
Parse precision block.
625941e76fb2d068a760f50f
def _removeItem(self, item): <NEW_LINE> <INDENT> raise NotImplementedError('Base class')
Remove table items corresponding to given plot item from the table. :param item: The plot item
625941e74e4d5625662d483d
def heap_sort(unsorted): <NEW_LINE> <INDENT> sort_heap = BinaryMinHeap() <NEW_LINE> for i in range(0, len(unsorted)): <NEW_LINE> <INDENT> sort_heap.heap_push(unsorted.pop()) <NEW_LINE> <DEDENT> for i in range(0, len(sort_heap.table)): <NEW_LINE> <INDENT> unsorted.append(sort_heap.pop_min()) <NEW_LINE> <DEDENT> return u...
Sorts a list by using a heap :param unsorted: unsorted list :return: the sorted list.
625941e78da39b475bd653e4
def assign_ladder_peaks( self, peaks, method='allele-autoladder' ): <NEW_LINE> <INDENT> self.reset_peaks() <NEW_LINE> method_id = EK._id(method) <NEW_LINE> ladder_peaks = [ (v, s, p, h, a, 'peak-ladder', 'undefined', method) for v, s, p, h, a in peaks ] <NEW_LINE> self.assign_complete_peaks( ladder_peaks, method )
reset the peaks for this channel, create a new alleleset and populate with the peaks
625941e72eb69b55b151cd21
def test_parser_deserialize(self): <NEW_LINE> <INDENT> obj = self.parser.deserialize(darknet_string) <NEW_LINE> self.assertEqual(type(obj), list) <NEW_LINE> self.assertEqual(len(obj), 3) <NEW_LINE> self.assertEqual(obj[0].class_label, '') <NEW_LINE> self.assertEqual(obj[2].class_label, 'person')
test basic deserialization with parser
625941e7d7e4931a7ee9e38a
def _call(self, options, parsed_globals): <NEW_LINE> <INDENT> gse = options.include_global_service_events <NEW_LINE> if gse: <NEW_LINE> <INDENT> if gse.lower() == 'true': <NEW_LINE> <INDENT> gse = True <NEW_LINE> <DEDENT> elif gse.lower() == 'false': <NEW_LINE> <INDENT> gse = False <NEW_LINE> <DEDENT> else: <NEW_LINE> ...
Run the command. Calls various services based on input options and outputs the final CloudTrail configuration.
625941e7b57a9660fec33cf5
def onPVSMessageReceived(self, jsonString): <NEW_LINE> <INDENT> logging.debug("Received: %s", jsonString) <NEW_LINE> try: <NEW_LINE> <INDENT> message = json.loads(jsonString) <NEW_LINE> self._validateJSON(message) <NEW_LINE> lg = PVSCommunicationLogger() <NEW_LINE> lg.log(constants.JSONLOG, "<= %s\n"%(message,)) <NEW_L...
Process a request from PVS An XML-RPC request presumably from PVS - typically a JSON-RPC message without id. This always returns a value at the XML-RPC level. If the JSON-RPC message cannot be parsed, or some other problem happens at the XML-RPC level, then it returns an error string. If the JSON-RPC message is par...
625941e744b2445a339324fe
def delta_ts(self): <NEW_LINE> <INDENT> return self.ts - self.last_ts
Return the interval between two (same) events.
625941e755399d3f05588b22
def __call__(self, theta): <NEW_LINE> <INDENT> p1_num_params = len(self.p1.bounds) <NEW_LINE> return self.p1(theta[:p1_num_params]) + self.p2(theta[p1_num_params:])
Evaluate the prior log-PDF at the given values of the hyperparameters, theta. The log-PDFs of the two priors are summed. Parameters ---------- theta : array-like, (`num_params`,) The hyperparameters to evaluate the log-PDF at.
625941e7d99f1b3c44c679f2
def gzip(response, level=4, mime_types=['text/html', 'text/plain']): <NEW_LINE> <INDENT> if not response.body: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> if getattr(response.request, "cached", False): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> acceptable = response.request.headers.elements('Ac...
Try to gzip the response body if Content-Type in mime_types. response.headers['Content-Type'] must be set to one of the values in the mime_types arg before calling this function. No compression is performed if any of the following hold: * The client sends no Accept-Encoding request header * No 'gzip' or 'x-gz...
625941e75166f23b2e1a55c4
def fitFun(self,par): <NEW_LINE> <INDENT> nw = int(np.sum(np.ones(7)[self.which])) <NEW_LINE> p = np.copy(self.param) <NEW_LINE> p[0:7][self.which] = np.array(par)[0:nw] <NEW_LINE> p[7:14][vecAnd([self.which,vecNot(self.doubled)])]=np.array(par)[nw:] <NEW_LINE> p[7:14][vecAnd([self.which,self.doubled])]=p[0:7][vecAnd([...
Function which is being fit to data. Calls two vibronic progressions 'lineshape.absFitMu' which takes the functional form explained in "derivation.pdf" Note that fitFun respects both 'which' and 'doubled' Input par: 1d numpy array holding FREE parameters to be modified during fitting (meaning neith...
625941e71d351010ab855f86
def test_delete_storage_accounts(self): <NEW_LINE> <INDENT> pass
Test case for delete_storage_accounts Deletes (hides) a multiple storage accounts and all their buckets/containers # noqa: E501
625941e7be8e80087fb210a7
def PrintMatch(s, d, start, end, isdir=False): <NEW_LINE> <INDENT> if isdir: <NEW_LINE> <INDENT> c.fg(c_dir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c.fg(c_plain) <NEW_LINE> <DEDENT> out(s[:start]) <NEW_LINE> c.fg(c_match) <NEW_LINE> out(s[start:end]) <NEW_LINE> if isdir: <NEW_LINE> <INDENT> c.fg(c_dir) <NEW_LINE...
For the match in s, print things out in the appropriate colors.
625941e756b00c62f0f14ac7
def is_compatible_with(self, other): <NEW_LINE> <INDENT> other = as_dtype(other) <NEW_LINE> return self._type_enum in (other.as_datatype_enum, other.base_dtype.as_datatype_enum)
Returns True if the `other` DType will be converted to this DType. The conversion rules are as follows: ```python DType(T) .is_compatible_with(DType(T)) == True DType(T) .is_compatible_with(DType(T).as_ref) == True DType(T).as_ref.is_compatible_with(DType(T)) == False DType(T).as_ref.is_comp...
625941e7a219f33f34628dcf
def axisEqual3D(ax): <NEW_LINE> <INDENT> extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) <NEW_LINE> sz = extents[:,1] - extents[:,0] <NEW_LINE> centers = np.mean(extents, axis=1) <NEW_LINE> maxsize = max(abs(sz)) <NEW_LINE> r = maxsize/2 <NEW_LINE> for ctr, dim in zip(centers, 'xyz'): <NEW...
http://stackoverflow.com/a/9349255
625941e7091ae356686673c2
def update_to_status(self, to_status): <NEW_LINE> <INDENT> data = dict(to_status=to_status) <NEW_LINE> response = self._api_client.api_request(self.url, "put", data=data) <NEW_LINE> self._update_entity_data(response)
Update the desired alert level of the given alert type. :param to_status: The name of the new 'to_status' of the policy.
625941e7462c4b4f79d1db3b
def websize(W): <NEW_LINE> <INDENT> return np.prod(np.shape(W))
Return the size of a matrix
625941e715fb5d323cde0f81
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> self.publish_date = datetime.today() <NEW_LINE> self.slug = slugify(self.title) <NEW_LINE> <DEDENT> self.modify_date = datetime.now() <NEW_LINE> super(PartnersPublication, self).save(*args, **kwargs)
On save, update timestamps
625941e763d6d428bbe4495c
def load_file(self, filename, encoding='utf8', **kwargs): <NEW_LINE> <INDENT> filename = resource_find(filename) or filename <NEW_LINE> if __debug__: <NEW_LINE> <INDENT> trace('Lang: load file %s, using %s encoding', filename, encoding) <NEW_LINE> <DEDENT> kwargs['filename'] = filename <NEW_LINE> with open(filename, 'r...
Insert a file into the language builder and return the root widget (if defined) of the kv file. :parameters: `rulesonly`: bool, defaults to False If True, the Builder will raise an exception if you have a root widget inside the definition. `encoding`: File character encoding. Defaults to utf-8...
625941e74527f215b584c8be
def most_constrained_cell_num(self) : <NEW_LINE> <INDENT> default_answer = 0 <NEW_LINE> if self.is_solved() : <NEW_LINE> <INDENT> return default_answer <NEW_LINE> <DEDENT> unsolved_cells = list(self.unsolved_cells) <NEW_LINE> def by_cell_num(cell) : <NEW_LINE> <INDENT> return cell.cell_num <NEW_LINE> <DEDENT> def by_nu...
Returns the unsolved cell_num with the fewest choices. The algorithm: pick unsolved cell with fewest possibles if more than one break tie with lowest total unsolved in RCB if still more than one pick the first
625941e710dbd63aa1bd300d
def subsets( nums): <NEW_LINE> <INDENT> output = [[]] <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> for j in range(len(output)): <NEW_LINE> <INDENT> output.append(sorted(output[j] + [nums[i]])) <NEW_LINE> <DEDENT> <DEDENT> return output
:type nums: List[int] :rtype: List[List[int]]
625941e75fcc89381b1e1b2e
def initialsToFront(entries): <NEW_LINE> <INDENT> for entry_type, entry_key, entry_fields in entries: <NEW_LINE> <INDENT> if 'author' in entry_fields: <NEW_LINE> <INDENT> authors = entry_fields['author'].split(' and ') <NEW_LINE> new_authors = [] <NEW_LINE> for author in authors: <NEW_LINE> <INDENT> surname, names = au...
AIP style authors: A. B. Smith
625941e796565a6dacc8fb35
def word_count(self, word, vertex=None): <NEW_LINE> <INDENT> if not vertex: <NEW_LINE> <INDENT> vertex = self._root <NEW_LINE> <DEDENT> if word: <NEW_LINE> <INDENT> key = word[0] <NEW_LINE> if key in vertex.edges: <NEW_LINE> <INDENT> next_vertex = vertex.edges[key] <NEW_LINE> if len(word) == 1: <NEW_LINE> <INDENT> retu...
Return the frequency of the word in the trie.
625941e7aad79263cf390eb3
def is_winner(self, player): <NEW_LINE> <INDENT> return any([ any([ all(self.board[row,:]==player) for row in self.vals ]), any([ all(self.board[:,col]==player) for col in self.vals ]), all([ self.board[i,i]==player for i in self.vals ]), all([ self.board[self.N-1-i,i]==player for i in self.vals ]) ])
Return True if player is the winner player: int Player to check for victory
625941e7a4f1c619b28b049a
def weighting_select(attr, old, new): <NEW_LINE> <INDENT> set_weighting_in(gui_weighting, weighting_plus, weighting_minus, weighting_step_size, gui_weighting_nu) <NEW_LINE> if gui_weighting.value in ['Target Slope']: <NEW_LINE> <INDENT> start_calc(True) <NEW_LINE> Opt_w.init = True <NEW_LINE> SPLove...
Arranges the GUI depending on chosen weighting approach. Runs init PALC calculation by triggering :any:`start_calc`, if 'Target Slope' is chosen. Triggered by :any:`gui_weighting`. Parameters ---------- attr : str Changed attribute (value). old : str Old weighting approach. new : str New weighting approach...
625941e756ac1b37e6264632
def test_help(self): <NEW_LINE> <INDENT> run_nbgrader(["export", "--help-all"])
Does the help display without error?
625941e77b180e01f3dc4c60
def _run_length_encode(serial_list): <NEW_LINE> <INDENT> serial_index = 0 <NEW_LINE> run_length = [] <NEW_LINE> while serial_index < 64: <NEW_LINE> <INDENT> if serial_index == 0: <NEW_LINE> <INDENT> value = serial_list[serial_index] <NEW_LINE> run_length.append((get_magnitude_dc(value), get_ones_complement_bit_string(v...
Perform run length encoding on a serialized block.
625941e7a934411ee3751b00
def pin_memory(self): <NEW_LINE> <INDENT> if self.is_cuda: <NEW_LINE> <INDENT> raise TypeError("cannot pin '{0}' only CPU memory can be pinned" .format(self.type())) <NEW_LINE> <DEDENT> storage = self.contiguous().storage() <NEW_LINE> if storage is None: <NEW_LINE> <INDENT> storage = (self.storage_type())() <NEW_LINE> ...
如果 tensor 尚未固定, 则将 tensor 复制到固定内存.
625941e77d43ff24873a310f
def point_mutation(self, random_state): <NEW_LINE> <INDENT> program = deepcopy(self.program) <NEW_LINE> mutate = np.where([True if (random_state.uniform() < self.p_point_replace) else False for _ in range(len(program))])[0] <NEW_LINE> for node in mutate: <NEW_LINE> <INDENT> if isinstance(program[node], six.string_types...
Perform the point mutation operation on the program. Point mutation selects random nodes from the embedded program to be replaced. Terminals are replaced by other terminals and functions are replaced by other functions that require the same number of arguments as the original node. The resulting tree forms an offsprin...
625941e7925a0f43d254a2e7
def truncate(text, limit, ellipsis='...'): <NEW_LINE> <INDENT> return text[:limit] + (text[limit:] and ellipsis)
Generic function that truncates long text by a specified limit
625941e757b8e32f5248390a
def wordPattern(self, pattern, str): <NEW_LINE> <INDENT> patternDict = {} <NEW_LINE> strDict = {} <NEW_LINE> length = len(pattern) <NEW_LINE> strList = str.split(" ") <NEW_LINE> if length != len(strList): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for index in xrange(length): <NEW_LINE> <INDENT> if pattern[in...
:type pattern: str :type str: str :rtype: bool
625941e7be8e80087fb210a8
def test_given_namespaces_with_exclusion(self): <NEW_LINE> <INDENT> gf = pagegenerators.GeneratorFactory(site=self.get_site()) <NEW_LINE> gf.handleArg('-ns:1,2,3,4,5') <NEW_LINE> gf.handleArg('-ns:not:User') <NEW_LINE> self.assertEqual(gf.namespaces, set([1, 3, 4, 5]))
Test mixed namespaces with exclusion.
625941e715fb5d323cde0f82
def SetStillHeater(self,xx): <NEW_LINE> <INDENT> mystr = 'SET:DEV:H2:HTR:SIG:POWR:%f' % xx <NEW_LINE> reply = self.query(mystr) <NEW_LINE> print(reply[reply.rfind(":")+1:]) <NEW_LINE> return
Set still heater power Set the still heater power (in uW?) to given value Parameters ---------- xx : float Desired heater power
625941e7d4950a0f3b08c7b5
def test_add(self): <NEW_LINE> <INDENT> f0 = Fraction(5) <NEW_LINE> f1 = Fraction(6) <NEW_LINE> self.assertEqual(f0+f1, 11) <NEW_LINE> f2 = Fraction(7, 12) + f0 <NEW_LINE> self.assertEqual(f2, Fraction("5 7/12")) <NEW_LINE> self.assertEqual(f2, Fraction(67, 12))
Try adding Fractions together.
625941e7d7e4931a7ee9e38b
def check_minimizer_bounds(self, minimizer): <NEW_LINE> <INDENT> if self.support_for_bounds is False or minimizer in self.no_bounds_minimizers: <NEW_LINE> <INDENT> message = 'The selected minimizer does not currently support ' 'problems with parameter bounds' <NEW_LINE> raise Incompa...
Helper function which checks whether the selected minimizer from the options (options.minimizer) supports problems with parameter bounds :param minimizer: string of minimizers selected from the options :type minimizer: str
625941e72ae34c7f2600d59c
@app.template_filter('get_tweet') <NEW_LINE> def get_tweet(status): <NEW_LINE> <INDENT> retweeted_status = False <NEW_LINE> if status.get("retweeted_status"): <NEW_LINE> <INDENT> retweeted_status = True <NEW_LINE> status = status["retweeted_status"] <NEW_LINE> <DEDENT> tweet = status['text'] <NEW_LINE> entities = [] <N...
Projdu si vsechny znaky, najdu hashtagy, nahradim je a vratim cely tweet vcetne html.
625941e7796e427e537b0a36
def dijkstra(self, start, maxD=1e309): <NEW_LINE> <INDENT> tdist = defaultdict(lambda: 1e309) <NEW_LINE> tdist[start] = 0 <NEW_LINE> preceding_node = {} <NEW_LINE> unvisited = copy.copy(self.nodes) <NEW_LINE> while unvisited: <NEW_LINE> <INDENT> current = unvisited.intersection(tdist.keys()) <NEW_LINE> if not current: ...
Returns a map of nodes to distance from start and a map of nodes to the neighbouring node that is closest to start.
625941e7cdde0d52a9e534a2
def set_transition_matrices(self, priorActPairs=None, reward=None, probability=None, just_return=False): <NEW_LINE> <INDENT> if reward is None: <NEW_LINE> <INDENT> nU, nS, nP = self.nU, self.nS, self.nP <NEW_LINE> pL, pH, rL, rH = self.pL, self.pH, self.rL, self.rH <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nU = 2 <...
Defines the transition matrices (actions) for the task, using the input priorActPairs as priors over the probability of transitioning to a new action pair. The input priorActPairs must be a vector of size nP, normalized, whose elements represent the biases towards each of the action pairs.
625941e7046cf37aa974d1af
def compute_ap(self): <NEW_LINE> <INDENT> aps = {} <NEW_LINE> for cid in range(1, self.loader.num_classes): <NEW_LINE> <INDENT> cat_name = self.loader.ids_to_cats[cid] <NEW_LINE> rec, prec = self.eval_category(cid) <NEW_LINE> ap = voc_ap(rec, prec, self.loader.year == '07') <NEW_LINE> aps[self.loader.ids_to_cats[cid]] ...
computes average precision for all categories
625941e70383005118ecfa4d
def Main(self): <NEW_LINE> <INDENT> self.dr.implicitly_wait(1) <NEW_LINE> blog_urls = open(self.path + '/blog_url.txt').readlines() <NEW_LINE> for url in blog_urls: <NEW_LINE> <INDENT> num = 1 <NEW_LINE> print(f'即将对其发起 {num} 次访问请求:{url}') <NEW_LINE> for T in range(num): <NEW_LINE> <INDENT> self.dr.get(url) <NEW_LINE> t...
点击链接进行访问
625941e755399d3f05588b23
def apply_inputs(self, attrs_dict): <NEW_LINE> <INDENT> for lbl, w in self._colors.items(): <NEW_LINE> <INDENT> default = self.COLORS.get(lbl, [0, 0, 0]) <NEW_LINE> value = attrs_dict.get(lbl, default) <NEW_LINE> w.color = value <NEW_LINE> <DEDENT> override = attrs_dict.get('override_display', False) <NEW_LINE> self.ov...
Overrides base ArtellaPlayblastPlugin apply_inputs function Applies the given dict of attributes to the widget :param attrs_dict: dict
625941e74a966d76dd551480
def transformFromAxis(self, v): <NEW_LINE> <INDENT> x = v/self.settings.datascale <NEW_LINE> return N.exp(x) if self.settings.log else x
Convert transformed values back.
625941e7bf627c535bc1363b
def simulate(self, steps, time = None, solution = solve_type.RK4, collect_dynamic = False): <NEW_LINE> <INDENT> return self.simulate_static(steps, time, solution, collect_dynamic);
! @brief Performs static simulation of pulse coupled neural network. @param[in] steps (uint): Number steps of simulations during simulation. @param[in] time (double): Can be ingored - steps are used instead of time of simulation. @param[in] solution (solve_type): Type of solution (solving). @param[in] collect_dynamic ...
625941e76fece00bbac2dbb0
def _handleCarriageReturnOnList(self, texts): <NEW_LINE> <INDENT> for i in range(len(texts)-1): <NEW_LINE> <INDENT> if texts[i].endswith('\r') and not texts[i+1].startswith('\n'): <NEW_LINE> <INDENT> texts[i] = '' <NEW_LINE> <DEDENT> <DEDENT> return [t for t in texts if t]
Discard messages that end with CR and that are not followed with LF. Assumes that each message is one line.
625941e7236d856c2ad44c4c
def match(self, dict_object): <NEW_LINE> <INDENT> se_stack = [] <NEW_LINE> for i in range(0, len(self.expr_list)): <NEW_LINE> <INDENT> if self.expr_list[i] in self.search_logical_operators.LOGIC_DICT: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> search_exp1_truth = se_stack.pop() <NEW_LINE> search_exp2_truth = se_stack...
Method to match the Search to evaluate postfix expression Algorithm: Initialize a stack Until end of expression list do if token in list is a logical operator pop 2 expressions and evaluate truth based on the logical operator else if token in list is an expression ...
625941e7fff4ab517eb2f8ab
def export_pages(output_dir, prefix='', width=600, supersample=2, yvar=None, cvar=None, rescale=False, num_contour=21): <NEW_LINE> <INDENT> import tecplot as tp <NEW_LINE> import tecplot.constant as tpc <NEW_LINE> os.makedirs(output_dir, exist_ok=True) <NEW_LINE> for page in tp.pages(): <NEW_LINE> <INDENT> page.activat...
Export all pages in the current layout to <page_name>.png
625941e79b70327d1c4e1243
def get( self, resource_group_name, network_profile_name, expand=None, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_ver...
Gets the specified network profile in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_profile_name: The name of the public IP prefix. :type network_profile_name: str :param expand: Expands referenced resources. :type expand: str :key...
625941e7a8ecb033257d3538
def _top_level_key(data): <NEW_LINE> <INDENT> msg = ('cannot find top level attribute "spack" or "env"' 'in the environment') <NEW_LINE> assert any(x in data for x in ('spack', 'env')), msg <NEW_LINE> if 'spack' in data: <NEW_LINE> <INDENT> return 'spack' <NEW_LINE> <DEDENT> return 'env'
Return the top level key used in this environment Args: data (dict): raw yaml data of the environment Returns: Either 'spack' or 'env'
625941e799cbb53fe6793051
def _MirrorNeighbors(self): <NEW_LINE> <INDENT> fd = self.neighbors.copy() <NEW_LINE> fd.loc[:, 'target'] = self.neighbors.loc[:, 'neighbor'] <NEW_LINE> fd.loc[:, 'neighbor'] = self.neighbors.loc[:, 'target'] <NEW_LINE> result = pd.concat([self.neighbors, fd]) <NEW_LINE> result = result.sort_values(by=['target', 'neigh...
Mirrors a neighbors DataFrame from MinimalPairND Mirror the neighbors DataFrame such that every A-B pair appears as both A(target)-B(neighbor) and B(target)-A(neighbor) Args: df (pandas.DataFrame): a neighbors DataFrame from MinimalPairND() Returns: A pandas.DataFrame with twice as many rows as the input df,...
625941e73346ee7daa2b31dc
def __init__(self, **args_model): <NEW_LINE> <INDENT> self._ss = None <NEW_LINE> self._H = None <NEW_LINE> self._rdmgen = None <NEW_LINE> self._fom_func = {} <NEW_LINE> self._t_array = None <NEW_LINE> self.pop_t = None <NEW_LINE> self.t_simul = None <NEW_LINE> self.T = None <NEW_LINE> self._ensemble_simulation = False ...
Intializes the `model` object. States: state_init, state_tgt, state self.pop: population i.e. the probability of a state (given in the reference basis) Notes ----- * DIMENSIONALITY: States which don't depend on time are of dim d while states over time have dim d x t * ENSEMBLE BEHAVIOR: self._ensemble_simulation ...
625941e7c4546d3d9de72ea4
@pytest.fixture(scope='module') <NEW_LINE> def pediatric_liposarcoma(): <NEW_LINE> <INDENT> return Disease(**{ "concept_id": "DOID:5695", "label": "childhood liposarcoma", "xrefs": ["ncit:C8091"], "associated_with": ["umls:C0279984"], "aliases": ["pediatric liposarcoma"] })
Create test fixture for pediatric liposarcoma.
625941e7507cdc57c6307152
def autodetect(): <NEW_LINE> <INDENT> logging.getLogger(__name__).debug('auto-detecting QT_API') <NEW_LINE> for API in QT_API_ORDER: <NEW_LINE> <INDENT> if API in QT_API_LOADER: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> QT_API_LOADER[API]() <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> continue <NEW_LI...
Auto-detects and use the first available QT_API by importing them in order defined in QT_API_ORDER
625941e77cff6e4e81117df2
def adapt(self, words): <NEW_LINE> <INDENT> pass
changes the stored list of words so that subsequent correction boxes can display the corrected list, and informs the speech engine of the corrected list of words, so it can adapt. **INPUTS** *[(STR, STR)]* -- corrected list of words (as (spoken, written) 2-tuples) **OUTPUTS** *BOOL* -- true if the adaption was a...
625941e7090684286d50f159
def __call__(self, x: str) -> List[str]: <NEW_LINE> <INDENT> if self.lower: <NEW_LINE> <INDENT> x = x.lower() <NEW_LINE> <DEDENT> out: List[str] = ( self.pre_id + [y.text for y in self.nlp.tokenizer(x)] + self.post_id ) <NEW_LINE> return out
Call to tokenize function Args: x (str): Input string Returns: List[str]: List of tokens
625941e74428ac0f6e5bac62
def test_getitem(): <NEW_LINE> <INDENT> nums = WordList(WORDS_DIR + "/integers.txt") <NEW_LINE> assert nums['1'] == "one" <NEW_LINE> assert nums['2'] == "two"
Testing getitem method
625941e7cdde0d52a9e534a3
def _genRouterKey(self): <NEW_LINE> <INDENT> datadir = self._env['dir'] <NEW_LINE> tor = self._env['tor'] <NEW_LINE> torrc = self._getTorrcFname() <NEW_LINE> cmdline = [ tor, "--ignore-missing-torrc", "-f", torrc, "--orport", "1", "--datadirectory", datadir, "--list-fingerprint", ] <NEW_LINE> stdouterr = run_tor(cmdlin...
Generate an identity key for this router, unless we already have, and set up the 'fingerprint' entry in the Environ.
625941e76aa9bd52df037214
def getXMLText(nodelist): <NEW_LINE> <INDENT> alltext = "" <NEW_LINE> for node in nodelist: <NEW_LINE> <INDENT> if node.nodeType == node.TEXT_NODE: <NEW_LINE> <INDENT> alltext += node.data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> alltext += getXMLText(node.childNodes) <NEW_LINE> <DEDENT> <DEDENT> return purifyText...
Provides a concatenated string version of the content of all subordinate text nodes in the passed node list.
625941e74e696a04525c98ba
def load_test_images(in_dir): <NEW_LINE> <INDENT> with gzip.open(path.realpath(path.join(in_dir, "t10k-images-idx3-ubyte.gz")), "rb") as f_in: <NEW_LINE> <INDENT> magic_num = unpack(">I", f_in.read(4))[0] <NEW_LINE> num_items = unpack(">I", f_in.read(4))[0] <NEW_LINE> img_height = unpack(">I", f_in.read(4))[0] <NEW_LIN...
Loads all testing images and returns a tuple of numpy arrays containing images and labels.
625941e7cad5886f8bd27445
def drawSquare(self, c1, c2, col): <NEW_LINE> <INDENT> c1 = self.displace[0] + np.int32(c1 * self.frameside) <NEW_LINE> c2 = self.displace[1] + np.int32(c2 * self.frameside) <NEW_LINE> p0 = np.int32([c1[0], c1[1]]) <NEW_LINE> p1 = np.int32([c1[0], c2[1]]) <NEW_LINE> p2 = np.int32([c2[0], c1[1]]) <NEW_LINE> p3 = np.int3...
Draws a square :param c1: Corner 1 :param c2: Corner 2 :param col: Color :return:
625941e75fc7496912cc3dea
def predict(self, state, action, deterministic=False): <NEW_LINE> <INDENT> inputs = self._prepare_input(state, action) <NEW_LINE> raise NotImplementedError <NEW_LINE> return samples
Predicts next states, rewards and not_done using the probabilistic ensemble For each (state, action) pair, pick a elite model uniformly at random, then use that elite model to predict next state, reward and not_done. The model can de different for each sample in the batch. If deterministic=True, then the prediction sho...
625941e78e05c05ec3eea7e5
def __init__(self): <NEW_LINE> <INDENT> self.error_state = False <NEW_LINE> self.errors = []
initilzes the error log to be free of errors
625941e7498bea3a759b9f1a
def _verifyOpenRegistration(): <NEW_LINE> <INDENT> policy = model_importer.ModelImporter().model('setting').get( SettingKey.REGISTRATION_POLICY, default='open') <NEW_LINE> if policy != 'open': <NEW_LINE> <INDENT> raise RestException( 'Registration on this instance is closed. Contact an administrator ' 'to create an acc...
Raises a REST exception if registration policy on the server is not set to 'open'. This should be called by the provider-specific code in the case when a user logs in with an email that is not already tied to an existing user.
625941e745492302aab5e735
def break_currtime_mt19937(rand_num: int, eps: int = 1200) -> int: <NEW_LINE> <INDENT> curr_time = int(time.time()) <NEW_LINE> for t in range(curr_time-eps, curr_time+1): <NEW_LINE> <INDENT> mt = MT19937() <NEW_LINE> mt.seed_mt(t) <NEW_LINE> if mt.extract_number() == rand_num: <NEW_LINE> <INDENT> return t <NEW_LINE> <D...
params: rand_num: first number generated by MT19937 using current UNIX time as seed eps: number of seconds in the past to look back through returns: seed used by MT19937 to generate `rand_num` None if seed not found
625941e7c4546d3d9de72ea5
def use_ansi_escape_colorbold_composites(): <NEW_LINE> <INDENT> color_codes = {} <NEW_LINE> for color_name, color_escape in list(colors.items()): <NEW_LINE> <INDENT> color_code = color_escape.replace("\x1b[", "").replace("m", "") <NEW_LINE> color_codes[color_name] = color_code <NEW_LINE> <DEDENT> for alias in aliases: ...
Patch for "sphinxcontrib-ansi" to process the following ANSI escapes correctly (set-color set-bold sequences): ESC[{color}mESC[1m => ESC[{color};1m Reapply aliases to ANSI escapes mapping.
625941e7d58c6744b42580cb
def send_to_client(self, message, client): <NEW_LINE> <INDENT> assert isinstance(message, LeapP2PMessage) <NEW_LINE> assert client in list(self.factory.clients.keys()) <NEW_LINE> message = jsonpickle.encode(message) <NEW_LINE> nline = "<{}@{}> {}".format( self.factory.clients[client], client.transport.getPeer().host, m...
Send a message to a specific client.
625941e7377c676e91272613
def rayleigh_pdf(x, loc=0, scale=1, if_CI=True, probs=(0.6827, 0.9545, 0.9973, 0.99994), xlabel='x', title='x ~ RA(gamma) CDF', colors=('k', 'r', 'orange', 'm'), fontsize=15, figsize=(15,12), rotation=0, filename='theo_rayleigh_cdf.png', usetex=False, sns_style=False, show=False): <NEW_LINE> <INDENT> fig = plt.figure(f...
Plots the probability distribution of Rayleigh distributed data, with given confidence interval.
625941e738b623060ff0b25a
def get_child_page_model_choices(): <NEW_LINE> <INDENT> _models = get_child_page_models() <NEW_LINE> names = [m._meta.db_table for m in _models] <NEW_LINE> labels = [m._meta.verbose_name_plural for m in _models] <NEW_LINE> return zip(names, labels)
Return choices for all models that are derived from ChildPage.
625941e721bff66bcd684dbb
def do_inference(hostport, work_dir, concurrency, num_tests): <NEW_LINE> <INDENT> test_data_set = mnist_input_data.read_data_sets(work_dir).test
Tests PredictionService with concurrent requests. Args: hostport: Host:port address of the PredictionService. work_dir: The full path of working directory for test data set. concurrency: Maximum number of concurrent requests. num_tests: Number of test images to use. Returns: The classification error rate. ...
625941e77c178a314d6ef8d3
def get(self, request, uuid): <NEW_LINE> <INDENT> text, image = captcha.generate_captcha() <NEW_LINE> redis_conn = get_redis_connection('verify_code') <NEW_LINE> try: <NEW_LINE> <INDENT> redis_conn.setex('img_%s' % uuid, 300, text) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> logge...
生成图形验证码, 保存到redis中, 另外返回图片 :param request:请求对象 :param uuid:浏览器端生成的唯一id :return:一个图片
625941e74f6381625f114ea9
def _cache_recent(f): <NEW_LINE> <INDENT> data = { 'args': None, 'result': None, } <NEW_LINE> @functools.wraps(f) <NEW_LINE> def wrapped(*args): <NEW_LINE> <INDENT> if data.get('args') != args: <NEW_LINE> <INDENT> data['args'] = args <NEW_LINE> data['result'] = f(*args) <NEW_LINE> <DEDENT> return data['result'] <NEW_LI...
Cache the most recent argument/result
625941e7bde94217f3683259
def __init__(self, provider_transaction_cost_b, provider_transaction_cost_s, provider_fixed_cost_pb, provider_fixed_cost_ps): <NEW_LINE> <INDENT> print("Initialize RO class...") <NEW_LINE> self.provider_transaction_cost_b = provider_transaction_cost_b <NEW_LINE> self.provider_transaction_cost_s = provider_transaction_c...
For initialization. The following values are needed for the calculations: 1. The current transactions costs for buyer 2. The current transactions costs for seller 3. The fixed costs incurred to the provider for each buyer 4. The fixed costs incurred to the provider for each seller
625941e7004d5f362079a79d
def enable_client_auth(self, cert_file, key_file): <NEW_LINE> <INDENT> self.tls_client_auth_enabled = True <NEW_LINE> self.tls_client_cert = cert_file <NEW_LINE> self.tls_client_key = key_file
Enable TLS client authentication Args: cert_file (str): Path of a PEM file containing client cert key_file (str): Path of a PEM file containing the client key
625941e776e4537e8c351ae3
def OnAbout(self, evt): <NEW_LINE> <INDENT> self.sb.SetStatusText(u'关于', 1)
关于
625941e7d6c5a102081444bb
def plot_predictions_experiments_comparison(M_pred, S_pred, exps, name='', filename=None): <NEW_LINE> <INDENT> assert type(M_pred) == list, 'Input should be list object' <NEW_LINE> assert type(S_pred) == list, 'Input should be list object' <NEW_LINE> assert type(exps) == list, 'Input should be list object' <NEW_LINE> a...
Plot visualization of predicted and ground-truth data Individual visualizations are plotted for each element of the lists of predicted and ground-truth experimental data. A figurename prefix can be given. If a filename-prefix is given, the individual plots are saved to disc. args: M_pred: list of predicted mean ...
625941e750812a4eaa59c78a
def testInitialize(self): <NEW_LINE> <INDENT> data_type_map_context = data_maps.DataTypeMapContext() <NEW_LINE> self.assertIsNotNone(data_type_map_context)
Tests the __init__ function.
625941e7dc8b845886cb59a4
def usage(): <NEW_LINE> <INDENT> pass
python replace_rare.py [input_file] > [output_file] Read in a gene tagged training input file and output its content with rare words replaced with _RARE_.
625941e707d97122c4178d02
def update_image_pool(self, pool, images, pool_size=50): <NEW_LINE> <INDENT> selected = [] <NEW_LINE> for image in images: <NEW_LINE> <INDENT> if len(pool) < pool_size: <NEW_LINE> <INDENT> pool.append(image) <NEW_LINE> selected.append(image) <NEW_LINE> <DEDENT> elif np.random.random() > 0.5: <NEW_LINE> <INDENT> selecte...
Filling the image pool to update discriminators, returns a list of images selected from the pool
625941e76fb2d068a760f511
def DescribeInvocationMetricDataPoint(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribeInvocationMetricDataPoint", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = ...
查询单值指标维度 :param request: Request instance for DescribeInvocationMetricDataPoint. :type request: :class:`tencentcloud.tsf.v20180326.models.DescribeInvocationMetricDataPointRequest` :rtype: :class:`tencentcloud.tsf.v20180326.models.DescribeInvocationMetricDataPointResponse`
625941e74f88993c3716c4d0
def tokenize(sa, to_lower=False, delimiters=["\r", "\v", "\n", "\f", "\t", " "]): <NEW_LINE> <INDENT> _raise_error_if_not_sarray(sa, "sa") <NEW_LINE> sf = _turicreate.SFrame({'docs': sa}) <NEW_LINE> fe = _feature_engineering.Tokenizer(features='docs', to_lower=to_lower, delimiters=delimiters, output_column_prefix=None)...
tokenize(sa, to_lower=False, delimiters=["\\r", "\\v", "\\n", "\\f", "\\t", " "]) Tokenize the input SArray of text strings and return the list of tokens. Parameters ---------- sa : SArray[str] Input data of strings representing English text. This tokenizer is not intended to process XML, HTML, or other struc...
625941e78da39b475bd653e6
def set_buttons(self, new, tick, back): <NEW_LINE> <INDENT> self.new_button = new <NEW_LINE> self.tick_button = tick <NEW_LINE> self.back_button = back
Sugar toolbar buttons
625941e74e4d5625662d483f
def kappainfresonances(chieff, q, chi1, chi2): <NEW_LINE> <INDENT> chieff = np.atleast_1d(chieff) <NEW_LINE> q = np.atleast_1d(q) <NEW_LINE> S1, S2 = spinmags(q, chi1, chi2) <NEW_LINE> kappainfmin = np.maximum((chieff - (q**-1-q)*S2)/(1+q), (chieff - (q**-1-q)*S1)/(1+q**-1)) <NEW_LINE> kappainfmax = np.minimum((chieff ...
Regularized angular momentum of the two spin-orbit resonances. The resonances minimizes and maximizes kappa for a given value of chieff. The minimum corresponds to deltaphi=pi and the maximum corresponds to deltaphi=0. Call ---- kappainfmin,kappainfmax = kappainfresonances(chieff,q,chi1,chi2) Parameters ---------- ch...
625941e7b57a9660fec33cf7
def get_vs_qos_vnetports(vsname, datacenter_uuid = None): <NEW_LINE> <INDENT> if global_params.vserverflag: <NEW_LINE> <INDENT> portgroup_objs = dbmodule.db_op.db_values('vm_portgroup',{"vswitch__name":vsname}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> portgroup_objs = dbmodule.db_op.db_values('vm_portgroup',{"vswi...
获取所有使用虚拟交换机默认qos配置的虚拟网卡端口
625941e78e71fb1e9831dc15
def test_filter_recipes_by_tags(self): <NEW_LINE> <INDENT> recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry') <NEW_LINE> recipe2 = sample_recipe(user=self.user, title='Beijing Roasted Duck') <NEW_LINE> tag1 = sample_tag(user=self.user, name='Vegetarian') <NEW_LINE> tag2 = sample_tag(user=self.user, n...
Test returning recipes with specific tags.
625941e7e8904600ed9f23a1
def __del__(self): <NEW_LINE> <INDENT> self.connexion.close()
Se déconnecter
625941e755399d3f05588b24
def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> command = self.commands.get(True) <NEW_LINE> if command == "Start": <NEW_LINE> <INDENT> self.interrupted = False <NEW_LINE> if self.vars_are_changed: <NEW_LINE> <INDENT> if self.detectors is not None: <NEW_LINE> <INDENT> self.de...
Runs in separate thread - waits on command to either run detectors or terminate thread from commands queue
625941e7cb5e8a47e48b7f11
def execute(self, index): <NEW_LINE> <INDENT> function = self._function <NEW_LINE> self.size_var = [] <NEW_LINE> self.domains = function.get_domain_restrictions <NEW_LINE> for i in range(function.nr_args): <NEW_LINE> <INDENT> size = utils.get_nr_bits(self.domains[i], self.precision) <NEW_LINE> self.size_var.append(size...
The algorithm implementation.
625941e7d99f1b3c44c679f4
def test_inheritence(self): <NEW_LINE> <INDENT> self.assertTrue(issubclass(City, BaseModel))
Test if the class inherit from BaseModel
625941e732920d7e50b28641
def testLinkOnDeletedTicket(self): <NEW_LINE> <INDENT> self.assert_true(self.t1.link_to(self.t2)) <NEW_LINE> self.assert_true(self.t2.is_linked_from(self.t1)) <NEW_LINE> self.assert_true(self.t1.is_linked_to(self.t2)) <NEW_LINE> self.t1.delete() <NEW_LINE> self.assert_false(self.t2.is_linked_from(self.t1))
Tests the deletion of a link after a deleted ticket
625941e7004d5f362079a79e
def get_mesh_symmetry_factor(simtype,top,w3d): <NEW_LINE> <INDENT> if simtype == "w3d": <NEW_LINE> <INDENT> if w3d.l4symtry: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> <DEDENT> elif simtype in ["wrz","em2d","em3d"]: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DE...
Gets the symmetry factor based on the simulation type and the parameters stored in the w3d object. Args: simtype: The type of simulation. Supports "w3d" and "wrz" currently. top: The top object from warp. w3d: The w3d object from warp. Return value: symmetry_factor: either 1 or 2.
625941e7956e5f7376d712d9
def _output_ret(self, ret, out): <NEW_LINE> <INDENT> import salt.output <NEW_LINE> if self.config['fun'] == 'sys.doc' and not isinstance(ret, Exception): <NEW_LINE> <INDENT> self._print_docs(ret) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> salt.output.display_output(ret, out, self.config) <NEW_LINE> <DEDENT> if not r...
Print the output from a single return to the terminal
625941e7d53ae8145f87a6d4
def _not_equal_nodes_build_tree(nodes_xyz, xyz_compare, tol, neq_max=4, msg=''): <NEW_LINE> <INDENT> assert isinstance(xyz_compare, np.ndarray), type(xyz_compare) <NEW_LINE> if nodes_xyz.shape[1] != xyz_compare.shape[1]: <NEW_LINE> <INDENT> msgi = 'nodes_xyz.shape=%s xyz_compare.shape=%s%s' % ( str(nodes_xyz.shape), st...
helper function for `bdf_equivalence_nodes` Parameters ---------- nodes_xyz : (Nnodes, 3) float ndarray the source points xyz_compare : (Ncompare, 3) float ndarray the xyz points to compare to tol : float the max spherical tolerance neq_max : int; default=4 the number of close nodes msg : str; defaul...
625941e74e696a04525c98bb