code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@given(game=games()) <NEW_LINE> def test_check_inputs_hospital_prefs_all_nonempty(game): <NEW_LINE> <INDENT> hospital = game.hospitals[0] <NEW_LINE> hospital.prefs = [] <NEW_LINE> with warnings.catch_warnings(record=True) as w: <NEW_LINE> <INDENT> game._check_inputs_player_prefs_nonempty("hospitals", "residents") <NEW_...
Test that every hospital has a non-empty preference list. If not, check that a warning is caught and the player has been removed from the game.
625941ef1d351010ab85608b
def batch_pack_op(x, counts, num_rows): <NEW_LINE> <INDENT> outputs = [] <NEW_LINE> for i in range(num_rows): <NEW_LINE> <INDENT> outputs.append(x[i, :counts[i]]) <NEW_LINE> <DEDENT> return tf.concat(outputs, axis=0)
Picks different number of values from each row in x depending on the values in counts.
625941ef44b2445a33932602
def swissPairings(): <NEW_LINE> <INDENT> result = playerStandings() <NEW_LINE> pairs = [] <NEW_LINE> for i in xrange(0, len(result),2): <NEW_LINE> <INDENT> pairs.append((result[i][0], result[i][1], result[i+1][0], result[i+1][1])) <NEW_LINE> <DEDENT> return pairs;
Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standing...
625941ef66673b3332b92601
def filter_words(words, skip_words): <NEW_LINE> <INDENT> for i in skip_words: <NEW_LINE> <INDENT> for j in words: <NEW_LINE> <INDENT> if i == j: <NEW_LINE> <INDENT> words.remove(j) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return words <NEW_LINE> pass
This function takes a list of words and returns a copy of the list from which all words provided in the list skip_words have been removed. For example: >>> filter_words(["help", "me", "please"], ["me", "please"]) ['help'] >>> filter_words(["go", "south"], skip_words) ['go', 'south'] >>> filter_words(['how', 'about',...
625941efbf627c535bc13740
def visit_Name(self, node): <NEW_LINE> <INDENT> is_param = isinstance(node.ctx, ast.Param) <NEW_LINE> if not is_param and (node.variable.is_cellvar or node.variable.is_freevar): <NEW_LINE> <INDENT> logger.debug("Function %s, lookup %s in scope %s: %s", self.ast.name, node.id, self.ast.cur_scope.type, self.ast.cur_scope...
Resolve cellvars and freevars
625941ef6fb2d068a760f617
def test_not_local_not_running_applications_stopped(self): <NEW_LINE> <INDENT> unit = Unit(name=u'mysql-hybridcluster', activation_state=u'inactive') <NEW_LINE> fake_gear = FakeGearClient(units={unit.name: unit}) <NEW_LINE> api = Deployer(create_volume_service(self), gear_client=fake_gear, network=make_memory_network()...
Applications that are not running and are supposed to be on the local node are added to the list of applications to stop.
625941ef8e71fb1e9831dd17
def calc_iwc(W_twc, W_lwc, k, e_liqT=1, e_iceT=1, e_liqL=1, beta_iceL=0): <NEW_LINE> <INDENT> iwc = np.divide( np.asfarray(e_liqL) * W_twc - np.asfarray(e_liqT) * W_lwc, np.asfarray(e_liqL) * k * np.asfarray(e_iceT) - np.asfarray(beta_iceL) * np.asfarray(e_liqT) ) <NEW_LINE> return iwc
Calculate ice water content from the measured LWC and TWC Args: W_twc: array of as-measured total water content from TWC element in g/m**3. W_lwc: array of as-measured total water content from 083 or 021 LWC element in g/m**3. k: Ratio of expended specific energies of water evaporatio...
625941ef8a43f66fc4b545d0
def _eval_(self, n, a, b, x): <NEW_LINE> <INDENT> if SR(a).is_trivial_zero() and SR(b).is_trivial_zero(): <NEW_LINE> <INDENT> return legendre_P(n, x) <NEW_LINE> <DEDENT> if SR(n).is_numeric() and not (n > -1): <NEW_LINE> <INDENT> raise ValueError("n must be greater than -1, got n = {0}".format(n)) <NEW_LINE> <DEDENT> i...
EXAMPLES:: sage: n,a,b,x = SR.var('n,a,b,x') sage: jacobi_P(1,n,n,n) (n + 1)*n sage: jacobi_P(2,n,n,n) 1/4*(2*n - 1)*(n + 2)*(n + 1)^2 sage: jacobi_P(1,n,n,x) (n + 1)*x sage: jacobi_P(3,2,1,x) 21/2*x^3 + 7/2*x^2 - 7/2*x - 1/2 sage: jacobi_P(1,a,b,x) 1/2*a*x + 1/2*b*x + 1/2*a...
625941efab23a570cc2506f8
def setup(self): <NEW_LINE> <INDENT> self.device = tf.device(TF_DEVICE) <NEW_LINE> self.session = tf.Session(config=tf.ConfigProto(device_count={'GPU':0})) <NEW_LINE> self.file_mgr = FileManager() <NEW_LINE> self.config = self.file_mgr.load_config(MODEL_NAME) <NEW_LINE> self.device.__enter__() <NEW_LINE> self.sess...
Setup.
625941efc432627299f051bb
def getdist(self, first, second): <NEW_LINE> <INDENT> dist = (self.distdict.get((id(first), id(second)), None) or self.distdict.get((id(second), id(first)), None)) if self.cachedist else None <NEW_LINE> if not dist: <NEW_LINE> <INDENT> dist = 0 <NEW_LINE> if first != second: <NEW_LINE> <INDENT> dist = self.distance(fir...
Computes the distance between two points. Parameters ---------- first : Point The first point. second: Point The second point. Returns: ------- float or Decimal The distance between `first` and `second`.
625941efd6c5a102081445c0
def sendBestaetigung(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> if self.threadStop: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if self.received: <NEW_LINE> <INDENT> self.clientSocketSenden.sendto(self.ok, (str(self.udpPort), int(self.udpIP))) <NEW_LINE> self.received = False
Thread der bei eingehender nachricht eine Sende Bestaetigung zurueck sendet
625941ef3d592f4c4ed1d5cf
def __init__(self, device_addr, adapter_addr=None): <NEW_LINE> <INDENT> self._pins_configured = False <NEW_LINE> self.ubit = Microbit(device_addr, adapter_addr)
Initialization of an instance of a remote bit:bot :param name: Will look for a BLE device with this string in its name :param device_addr: Will look for a BLE device with this address
625941ef3539df3088e2e8bc
@app.route('/test') <NEW_LINE> def test(): <NEW_LINE> <INDENT> stops_file = open("static/stops.json", "r") <NEW_LINE> stops = stops_file.readline() <NEW_LINE> stops = json.loads(stops) <NEW_LINE> return render_template("test.html", stops=stops)
l = requests.get('https://api.tfl.gov.uk/line/mode/tube', data={"app_id":app_id, "app_key":app_key}) print l lines_data = l.json() lines = [] for line in lines_data: lines.append(line['id']) stops = {} for line in lines: stopData = {} print 'https://api.tfl.gov.uk/line/'+line+'/route/sequence/inbound' r...
625941ef5f7d997b8717500d
def test_kmp(): <NEW_LINE> <INDENT> assert(kmp('abcabeabcabcabd', 'abcabd') == 9)
Tests
625941ef0a50d4780f667407
def add_connection(self): <NEW_LINE> <INDENT> conn_new = NewConnectionDialog() <NEW_LINE> conn_new.setWindowTitle(self.tr('New Catalogue service')) <NEW_LINE> if conn_new.exec_() == QDialog.Accepted: <NEW_LINE> <INDENT> self.populate_connection_list() <NEW_LINE> <DEDENT> self.textMetadata.clear()
add new service
625941ef57b8e32f52483a0f
def parameterize(self): <NEW_LINE> <INDENT> log.info("Parameterizing the {} Molecules".format(len(self.molecules))) <NEW_LINE> for mol in self.molecules: <NEW_LINE> <INDENT> mol.parameterize() <NEW_LINE> <DEDENT> self._steps["parameterized"] = True
Parameterize all Molecules in this SimpleSimulation :return: None
625941ef66656f66f7cbc71d
def test_bellman_with_empty_graph_raises_error(empty_weight_graph): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> empty_weight_graph.bellman_ford_min(4, 19)
Test that ValueError raised if bellman used on empty graph.
625941ef4f88993c3716c5d2
def __walk_plugins(self, parent_menu, tree, find_object): <NEW_LINE> <INDENT> if len(tree.nodes) > 0: <NEW_LINE> <INDENT> for node in tree.nodes: <NEW_LINE> <INDENT> parent_menu.add_cascade(label=node.name, menu=self.__walk_plugins(Menu(parent_menu, tearoff=0), node, find_object)) <NEW_LINE> <DEDENT> <DEDENT> self.add_...
Walks through the plugin folder and adds the to the path For each folder a cascade is created in the main menue parent_menue: the menue in which to work tree: a tree or subtree as returned by os.walk find_object: The Find Object
625941ef167d2b6e31219105
def save_magnet(self, info_hash): <NEW_LINE> <INDENT> hex_info_hash = codecs.getencoder("hex")(info_hash)[0].decode() <NEW_LINE> magnet = MAGNET_PER.format(hex_info_hash) <NEW_LINE> self.rc.add_magnet(magnet) <NEW_LINE> self.logger.info("pid_{0} - {1}".format(self.process_id, magnet))
将磁力链接保存到数据库 :param info_hash: 磁力链接的 info_hash
625941ef287bf620b61d3fd1
def removeElement(self, nums, val): <NEW_LINE> <INDENT> left = 0 <NEW_LINE> right = len(nums) - 1 <NEW_LINE> while left <= right: <NEW_LINE> <INDENT> if nums[left] == val: <NEW_LINE> <INDENT> while nums[right] == val and right >= left: <NEW_LINE> <INDENT> right = right - 1 <NEW_LINE> <DEDENT> if right > left: <NEW_LINE...
:type nums: List[int] :type val: int :rtype: int
625941ef16aa5153ce3629ea
def get_integ_tests(module_prefix = None): <NEW_LINE> <INDENT> if module_prefix and not module_prefix.startswith('test.integ.'): <NEW_LINE> <INDENT> module_prefix = 'test.integ.' + module_prefix <NEW_LINE> <DEDENT> return _get_tests(CONFIG['test.integ_tests'].splitlines(), module_prefix)
Provides the classes for our integration tests. :param str module_prefix: only provide the test if the module starts with this substring :returns: an **iterator** for our integration tests
625941ef5166f23b2e1a56ca
@pytest.mark.parametrize( 'parent', [ ({"test": "one"}), (MockParentData("one")), ] ) <NEW_LINE> def test_enum_resolver_string(parent): <NEW_LINE> <INDENT> enum = Enum("test", [("one", 1), ("two", 2)]) <NEW_LINE> resolve = get_enum_resolver("test", enum) <NEW_LINE> assert resolve(parent, None) == enum.one
Resolve strings to enum values.
625941efd486a94d0b98e6b7
def toxml(self, element): <NEW_LINE> <INDENT> element = SubElement(element, "And") <NEW_LINE> if self._prefix is not None: <NEW_LINE> <INDENT> SubElement(element, "Prefix", self._prefix) <NEW_LINE> <DEDENT> if self._tags is not None: <NEW_LINE> <INDENT> self._tags.toxml(element) <NEW_LINE> <DEDENT> return element
Convert to XML.
625941ef50812a4eaa59c88c
def _v(self, v): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out = get_cronvalue(v, self.enum) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("Unrecognised '%s'='%s'" % (self.name, v)) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError("No enumeration '%s' got '%s'" % ...
Support wrapper for enumerations and check for range
625941efb7558d58953c5479
def _read_stats(self, name): <NEW_LINE> <INDENT> stats = os.stat(name) <NEW_LINE> mode = oct(stats.st_mode)[-4:] <NEW_LINE> size = stats.st_size <NEW_LINE> atime = int(stats.st_atime) <NEW_LINE> mtime = int(stats.st_mtime) <NEW_LINE> return (mode, size, mtime, atime)
return just the file stats needed for scp
625941ef627d3e7fe0d693c2
def calendar_lines(self): <NEW_LINE> <INDENT> empty_calendar = self._build_calandar().content_lines() <NEW_LINE> cal_head, cal_tail = empty_calendar[:-2], empty_calendar[-2:] <NEW_LINE> assert cal_head[0] == "BEGIN:VCALENDAR" <NEW_LINE> assert len(cal_tail) == 2 <NEW_LINE> assert cal_tail[0] == "END:VCALENDAR" <NEW_LIN...
Iteratively generates the lines that would be produced by calling calendar().to_ical(), or calendar().content_lines(). The difference is that this method does not does not hold all icalendar.Event objects in memory, and doesn't generate a string representing the entire icalendar document as calendar().to_ical() would....
625941ef21bff66bcd684ebe
def validate_battery( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> battery_int = int(re.findall(r'[0-9]+',value)[0]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> battery_int = 500000 <NEW_LINE> <DEDE...
Validate num_people value.
625941ef66673b3332b92602
def scores(self, scaling): <NEW_LINE> <INDENT> if scaling not in {1, 2}: <NEW_LINE> <INDENT> raise NotImplementedError("Only scalings 1, 2 available for RDA.") <NEW_LINE> <DEDENT> eigvals = self.eigenvalues <NEW_LINE> const = np.sum(eigvals**2)**0.25 <NEW_LINE> if scaling == 1: <NEW_LINE> <INDENT> scaling_factor = cons...
Compute site, species and biplot scores for different scalings. Parameters ---------- scaling : int TODO: improve explanation based on p. 403 L&L. Scaling type 1 produces a distance biplot. It focuses on the ordination of rows (sites) because their transformed distances approximate their original euc...
625941ef3eb6a72ae02eca5d
def distance_threshold(threshold, lat1, lon1, lat2, lon2): <NEW_LINE> <INDENT> distance = distance_latlon(lat1, lon1, lat2, lon2) <NEW_LINE> return bool(distance <= threshold)
A simple boolean to tell whether the distance between two points is less than or equal to a provided threshold value (True).
625941ef3eb6a72ae02eca5e
def _parse_bool_string(self, value): <NEW_LINE> <INDENT> value = value.strip().lower() <NEW_LINE> if value in ['true', 'yes', '1']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
if value is either 'True' or 'False' it returns that value as a bool, otherwise it returns the value
625941ef63b5f9789fde7657
def on_turn(self, turn_state): <NEW_LINE> <INDENT> game_state = gamelib.GameState(self.config, turn_state) <NEW_LINE> gamelib.debug_write('Performing turn {} of your custom algo strategy'.format(game_state.turn_number)) <NEW_LINE> self.test_strategy(game_state) <NEW_LINE> game_state.submit_turn()
This function is called every turn with the game state wrapper as an argument. The wrapper stores the state of the arena and has methods for querying its state, allocating your current resources as planned unit deployments, and transmitting your intended deployments to the game engine.
625941ef24f1403a926010d2
def _conv(self, view_name): <NEW_LINE> <INDENT> return self.catalog[view_name]
INPUT: string OUTPUT: view object Converts string to an existant view object
625941efb545ff76a8914387
def main(args=None): <NEW_LINE> <INDENT> cli.main(args, 'monz')
Run monz
625941efcdde0d52a9e535a9
def capture_output(command, env=os.environ): <NEW_LINE> <INDENT> stdoutf = tempfile.TemporaryFile() <NEW_LINE> popen = subprocess.Popen(command, env=env, stdout=stdoutf, stderr=stdoutf) <NEW_LINE> popen.wait() <NEW_LINE> stdoutf.seek(0) <NEW_LINE> stdout = stdoutf.read() <NEW_LINE> stdoutf.close() <NEW_LINE> return s...
runs the specified command, capturing and returning output @param command - array containing executable to run w/ parameters @param env - optional environment to set for command @return - stdout generated by the command, if any
625941ef293b9510aa2c3801
def biosystems(taxon_id=None, databases='all'): <NEW_LINE> <INDENT> if taxon_id is None: <NEW_LINE> <INDENT> raise EnvironmentError('No taxon specified') <NEW_LINE> <DEDENT> def _load_biosystem_geisen_v1_1_upwards(p): <NEW_LINE> <INDENT> df = pd.read_csv(p) <NEW_LINE> return df <NEW_LINE> <DEDENT> if databases == 'all'...
Biosystems databases, which is an aggregation of several pathway databases (of which some may not be defined for every taxon) Source: NIH Input: taxon_id int databases default is 'all', which will load 'biocyc', 'kegg', 'lipid_maps', 'pathway_interaction_database',...
625941ef55399d3f05588c29
def morph(S, B): <NEW_LINE> <INDENT> L=[] <NEW_LINE> mat = rowdict2mat(S) <NEW_LINE> for i,e in enumerate(B): <NEW_LINE> <INDENT> L.append((e,S[i])) <NEW_LINE> <DEDENT> return L
Input: - S: a list of distinct Vec instances - B: a list of linearly independent Vec instances - Span S == Span B Output: a list of pairs of vectors to inject and eject Example: >>> #This is how our morph works. Yours may yield different results. >>> S = [list2vec(v) for v in [[1,0,0],[0,1,0],[0,0,...
625941efd18da76e23532a4e
def _copySessionToForm(self, session, displayName): <NEW_LINE> <INDENT> sf = SessionForm() <NEW_LINE> for field in sf.all_fields(): <NEW_LINE> <INDENT> if hasattr(session, field.name): <NEW_LINE> <INDENT> if field.name in ('date', 'start_time'): <NEW_LINE> <INDENT> setattr(sf, field.name, str(getattr(session, field.nam...
Copy relevant fields from Session to SessionForm.
625941eff548e778e58cdaf1
def merge(phone_id, card_id): <NEW_LINE> <INDENT> record_table = 'record' <NEW_LINE> t = db.transaction() <NEW_LINE> phone_id, card_id = int(phone_id), int(card_id) <NEW_LINE> try: <NEW_LINE> <INDENT> db.update(record_table, where="lost_id=%i" % phone_id, lost_id=card_id) <NEW_LINE> db.update(record_table, where="find_...
手机临时账号和校园卡账号合并
625941ef627d3e7fe0d693c3
@app.route("/send_mail", methods=['GET']) <NEW_LINE> def send_mail(): <NEW_LINE> <INDENT> msg = Message("flask欢迎消息", sender="zxqfengdi@163.com", recipients=["zxqfengdi@163.com"]) <NEW_LINE> msg.html = "'<h3>欢迎您成为天天生鲜注册会员!</h3>请点击以下链接激活账户:<a href='#'>激活</a>" <NEW_LINE> mail.send(msg) <NEW_LINE> return redirect(url_for("...
邮件发送
625941ef56b00c62f0f14bce
def ctrl_click(event, points, MenuBar): <NEW_LINE> <INDENT> Canv = event.widget <NEW_LINE> X = event.x <NEW_LINE> Y = event.y <NEW_LINE> if len(points) == 0: <NEW_LINE> <INDENT> droite = Canv.create_line(X, Y, X, Y) <NEW_LINE> points.append(X) <NEW_LINE> points.append(Y) <NEW_LINE> libere_sauv(MenuBar) <NEW_LINE> Canv....
ajoute un point a droite en cours de creation si on a pas de trait en cours on en cree un
625941ef435de62698dfe1be
def submit_button(*args): <NEW_LINE> <INDENT> v1 = parameter_1_entry.get() <NEW_LINE> v2 = parameter_2_entry.get() <NEW_LINE> p1 = p1_var.get() <NEW_LINE> p2 = p2_var.get() <NEW_LINE> des = des_var.get() <NEW_LINE> var1 = str(prop(helper[des], helper[p1], float(v1), helper[p2], float(v2))) <NEW_LINE> answer = des + " =...
Calculates values, erases old data, updates text with new data. Removes text from old data
625941ef8e71fb1e9831dd18
def forward(self, *input): <NEW_LINE> <INDENT> raise NotImplementedError('Subclass must implement this method')
Defines the computation performed at every call. Should be overriden by all subclasses.
625941efd99f1b3c44c67af6
def get_supported_models(type: ModelType): <NEW_LINE> <INDENT> import pkgutil <NEW_LINE> if type == ModelType.SEGMENTATION: <NEW_LINE> <INDENT> excludes = [] <NEW_LINE> for importer, modname, ispkg in pkgutil.walk_packages(path=segmentation.__path__, prefix=segmentation.__name__+".", onerror=lambda x: None): <NEW_LINE>...
:param type: (ModelType): classification or segmentation :return: list (strings) of supported models
625941ef8a349b6b435e86e4
@sb.request_handler(can_handle_func=lambda input: is_intent_name("TriviaAnswerIntent")(input)) <NEW_LINE> def trivia_answer_handler(handler_input): <NEW_LINE> <INDENT> session_attr = handler_input.attributes_manager.session_attributes <NEW_LINE> if 'game_state' not in session_attr or session_attr['game_state'] != "STAR...
Handler for processing guess with target.
625941ef94891a1f4081c01d
def handle_exception(self, exception, debug_mode): <NEW_LINE> <INDENT> error_message = traceback.format_exc() <NEW_LINE> _log.critical(error_message) <NEW_LINE> if isinstance(exception, CapabilityDisabledError): <NEW_LINE> <INDENT> error_code = 503 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_code = 500 <NEW_LIN...
Houston, we have a problem... Handle an uncaught exception. This method overrides the webapp.RequestHandler class's handle_exception method. This method gets called whenever there's an uncaught exception anywhere in the Play By Play code.
625941ef460517430c3946e7
def test_valid_move(self): <NEW_LINE> <INDENT> with self.login(username=self.user1.username): <NEW_LINE> <INDENT> self.post(self.view_string, **self.valid_url_kwargs) <NEW_LINE> self.response_200() <NEW_LINE> assert StoryElementNode.objects.get(pk=self.o1_valid_storynode.pk).path != self.o1_valid_storynode.path
Test that authorized user can make a valid move.
625941ef4c3428357757c895
def proj(self, *attributes, **named_attributes): <NEW_LINE> <INDENT> return Projection.create(self, attributes, named_attributes)
Projection operator. :param attributes: attributes to be included in the result. (The primary key is already included). :param named_attributes: new attributes computed or renamed from existing attributes. :return: the projected expression. Primary key attributes cannot be excluded but may be renamed. Thus self.proj()...
625941efbe8e80087fb211ab
def test(self,e=1e-8): <NEW_LINE> <INDENT> predict = self.predict(self.data['X_test']) <NEW_LINE> res = self.show_metrics(self.data['Y_test'],predict,e) <NEW_LINE> return res
show model metrics
625941ef3317a56b8693a1bc
def _to_dict(self): <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'id') and self.id is not None: <NEW_LINE> <INDENT> _dict['id'] = self.id <NEW_LINE> <DEDENT> if hasattr(self, 'score') and self.score is not None: <NEW_LINE> <INDENT> _dict['score'] = self.score <NEW_LINE> <DEDENT> if hasattr(self, 'metadata...
Return a json dictionary representing this model.
625941ef293b9510aa2c3802
def on_booting(cassettiera): <NEW_LINE> <INDENT> if not cassettiera: <NEW_LINE> <INDENT> log.bug("cassettiera non è un parametro valido: %r" % cassettiera) <NEW_LINE> return <NEW_LINE> <DEDENT> if "next_cassetto" in cassettiera.specials and cassettiera.specials["next_cassetto"]: <NEW_LINE> <INDENT> code = cassettiera.s...
Poiché lo special next_cassetto al caricamento è una stringa, e nel gamescript invece viene utilizzato, per comodità, come riferimento lo deve cercare nel database e reinizializzarlo.
625941ef4e4d5625662d4941
def set_sort_callback(self, callback): <NEW_LINE> <INDENT> self.sort_callback = callback
Callback for sorting action :param callback: The callback method that is used for delegation of sorting action
625941efd7e4931a7ee9e491
def testBz2Read(self): <NEW_LINE> <INDENT> fname=tempfile.mktemp(prefix='fitsio-BZ2TableWrite-',suffix='.fits') <NEW_LINE> bzfname = fname + '.bz2' <NEW_LINE> try: <NEW_LINE> <INDENT> fits = fitsio.FITS(fname,'rw',clobber=True) <NEW_LINE> fits.write_table(self.data, header=self.keys, extname='mytable') <NEW_LINE> fits....
Write a normal .fits file, run bzip2 on it, then read the bz2 file and verify that it's the same as what we put in; we don't [currently support or] test *writing* bzip2.
625941ef7cff6e4e81117ef7
def add_sample(self, *args, **kwargs): <NEW_LINE> <INDENT> return _algorithms.svm_dense_add_sample(self, *args, **kwargs)
add_sample(self, y_val, x_vector)
625941efbde94217f368335d
def is_enum(cls): <NEW_LINE> <INDENT> return cls == enum.Enum or cls == enum.EnumMeta
True if cls is a enumerator class
625941ef7c178a314d6ef9da
def get_symmetry_operation_ranges(self): <NEW_LINE> <INDENT> M = np.Inf <NEW_LINE> ranges = np.array([[-M,M],[-M,M],[0,0]]) <NEW_LINE> return ranges
Return ranges for symmetry operations.
625941ef2c8b7c6e89b35d2d
def broadcast_transfer(self, msg: binance_chain.messages.TransferMsg, wallet_name: str): <NEW_LINE> <INDENT> data = { 'msg': msg.to_sign_dict(), 'wallet_name': wallet_name } <NEW_LINE> return self._post('transfer/broadcast', json=data)
Sign and broadcast a message using a signing service :param msg: Type of TransferMsg :param wallet_name: Name of the wallet .. code:: python transfer_msg = TransferMsg( symbol='BNB', amount=1, to_address='<to address>' ) res = client.sign_transfer(transfer_msg, wallet_name='mywall...
625941ef925a0f43d254a3ee
def test_product_installed(self): <NEW_LINE> <INDENT> self.assertTrue(self.installer.is_product_installed( 'nva.inwimandant'))
Test if nva.inwimandant is installed.
625941ef1f037a2d8b94676e
def close(self): <NEW_LINE> <INDENT> if self._is_connected: <NEW_LINE> <INDENT> self._client[0].close() <NEW_LINE> self._client = None <NEW_LINE> self._is_connected = False <NEW_LINE> if self._logging: <NEW_LINE> <INDENT> _internals.active_exp._event_file_log( "TcpServer,closed")
Close the connection to the client.
625941ef1b99ca400220b025
def print_h1(log, end='\n'): <NEW_LINE> <INDENT> print(color.GREEN + '\n' + '*' * 10 + ' ' + log + ' ' + '*' * 10 + '\n' + color.END, end=end)
:param log: :param end: :return:
625941efdc8b845886cb5aa8
def _lock_or_fail(self): <NEW_LINE> <INDENT> if not self._create_lock_dir(): <NEW_LINE> <INDENT> raise ClaimLockError("Failed to claim lock (the lock directory exists at {})".format(self.lock_dir))
Raise ClaimLockError if claiming lock failed
625941efd18da76e23532a4f
def __init__(self, training_text, multiplicity, keys, message): <NEW_LINE> <INDENT> self.trainingText = training_text <NEW_LINE> self.codedMessage = message <NEW_LINE> self.multiplicity = multiplicity <NEW_LINE> self.keys = keys.split(", ") <NEW_LINE> self.message = "" <NEW_LINE> self.ngramms = [] <NEW_LINE> self.marko...
Базовый конструктор класса
625941ef56b00c62f0f14bcf
def __init__(self, parent): <NEW_LINE> <INDENT> QTableView.__init__(self, parent) <NEW_LINE> self.parent = parent <NEW_LINE> self.setModel(parent.model()) <NEW_LINE> self.setFocusPolicy(Qt.NoFocus) <NEW_LINE> self.verticalHeader().hide() <NEW_LINE> try: <NEW_LINE> <INDENT> self.horizontalHeader().setSectionResizeMode(Q...
Constructor.
625941ef0383005118ecfb52
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('path', help="Base path to the venv.") <NEW_LINE> parser.add_argument('--tox', help="Add when called via tox.", action='store_true') <NEW_LINE> args = parser.parse_args() <NEW_LINE> if args.tox: <NEW_LINE> <INDENT> executa...
Main entry point.
625941ef4f6381625f114fad
def dump(self): <NEW_LINE> <INDENT> d = deepcopy(self.__dict__) <NEW_LINE> try: <NEW_LINE> <INDENT> del d["_sa_instance_state"] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return d
Dump all attributes to a dictionnary
625941ef009cb60464c6391f
def _validate_estimator(self, default=AdaBoostClassifier()): <NEW_LINE> <INDENT> if not isinstance(self.n_estimators, (numbers.Integral, np.integer)): <NEW_LINE> <INDENT> raise ValueError("n_estimators must be an integer, " "got {0}.".format(type(self.n_estimators))) <NEW_LINE> <DEDENT> if self.n_estimators <= 0: <NEW_...
Check the estimator and the n_estimator attribute, set the `base_estimator_` attribute.
625941efd164cc61757832c1
def _Get_gpio(self): <NEW_LINE> <INDENT> self._logger.debug('') <NEW_LINE> return self._create_logical_value(self._read_control_reg())
Get pca9500 GPIO value and return. Returns: integer value from gpio
625941ef6e29344779a62b82
def temporary_unavailable(request, template_name=MAINTENANCE_503_TEMPLATE): <NEW_LINE> <INDENT> if request.META.get("CONTENT_TYPE") == "application/json": <NEW_LINE> <INDENT> content = json.dumps({ "code": 503, "error": "temporarily_unavailable", "reason": "maintenance", "error_description": "Sorry, the service is temp...
Default 503 handler
625941ef3cc13d1c6d3c78e9
def get_tripadvisor_hotels_urls(self, input_file): <NEW_LINE> <INDENT> tripadvisor = pd.read_csv(input_file, encoding='utf-8-sig') <NEW_LINE> return tripadvisor['link-href'].values.tolist()
:param input_file: :return:
625941ef10dbd63aa1bd3114
def GrotzschGraph(): <NEW_LINE> <INDENT> g = Graph() <NEW_LINE> g.add_vertices(range(11)) <NEW_LINE> edges = []; <NEW_LINE> for u in range(1,6): <NEW_LINE> <INDENT> edges.append( (0,u) ) <NEW_LINE> <DEDENT> edges.append( (10,6) ) <NEW_LINE> for u in range(6,10): <NEW_LINE> <INDENT> edges.append( (u,u+1) ) <NEW_LINE> ed...
Returns the Grötzsch graph. The Grötzsch graph is an example of a triangle-free graph with chromatic number equal to 4. For more information, see this `Wikipedia article on Grötzsch graph <http://en.wikipedia.org/wiki/Gr%C3%B6tzsch_graph>`_. REFERENCE: - [1] Weisstein, Eric W. "Grotzsch Graph." From MathWorld--A W...
625941ef656771135c3ebde7
def readMessage(self): <NEW_LINE> <INDENT> while len(self.buf) < _msg_size: <NEW_LINE> <INDENT> self.buf.extend(self.socket.recv(4096)) <NEW_LINE> <DEDENT> msg_dict = MessageStrategy.parse(self.buf[0:_msg_size],self.stream,self.hmacf) <NEW_LINE> self.buf = self.buf[_msg_size:] <NEW_LINE> return msg_dict
Perform a buffered read from the socket
625941ef9f2886367277adfa
def matching_KMP(t, p, pnext): <NEW_LINE> <INDENT> j, i = 0, 0 <NEW_LINE> n, m = len(t), len(p) <NEW_LINE> while j < n and i < m: <NEW_LINE> <INDENT> if p[i] == t[j] or i == -1: <NEW_LINE> <INDENT> i, j = i+1, j+1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = pnext[i] <NEW_LINE> <DEDENT> <DEDENT> if i == m: <NEW_LI...
KMP串匹配,主函数
625941efb830903b967e9e76
def calculate_level(score): <NEW_LINE> <INDENT> if not score or score < 0: <NEW_LINE> <INDENT> level = 1 <NEW_LINE> score_next = 1 <NEW_LINE> score_left = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> to_next = lambda l: int(ceil(LEVEL_A * l ** 3 + LEVEL_B * l ** 2 + ...
Takes player's score and returns calcualted current level, total score needed to reach the next level, and the number of points the player still has to gather before reaching the next level.
625941ef046cf37aa974d2b4
def find_blade_root_dir(working_dir=None): <NEW_LINE> <INDENT> blade_root = find_file_bottom_up('BLADE_ROOT', from_dir=working_dir) <NEW_LINE> if not blade_root: <NEW_LINE> <INDENT> console.fatal( "Can't find the file 'BLADE_ROOT' in this or any upper directory.\n" "Blade need this file as a placeholder to locate the r...
find_blade_root_dir to find the dir holds the BLADE_ROOT file. The blade_root_dir is the directory which is the closest upper level directory of the current working directory, and containing a file named BLADE_ROOT.
625941efb830903b967e9e77
def sumSeries(requestContext, *seriesLists): <NEW_LINE> <INDENT> return aggregate(requestContext, seriesLists, 'sum')
Short form: sum() This will add metrics together and return the sum at each datapoint. (See integral for a sum over time) Example: .. code-block:: none &target=sum(company.server.application*.requestsHandled) This would show the sum of all requests handled per minute (provided requestsHandled are collected once ...
625941efa219f33f34628ed3
def unlink_ignore(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(path) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno != errno.ENOENT: <NEW_LINE> <INDENT> raise
Unlinks the given path, but succeeds if it doesn't exist.
625941ef6fb2d068a760f618
def transient_auc(x): <NEW_LINE> <INDENT> period = x.trial.parent.frame_period() <NEW_LINE> y = np.zeros(x.im_data.shape) <NEW_LINE> y[x.start_frame:x.stop_frame] = 1 <NEW_LINE> y *= x.im_data <NEW_LINE> return nantrapz_1d(y, dx=period)
Return the AUC for the transient.
625941ef283ffb24f3c55e6d
@pytest.fixture <NEW_LINE> def hide(pootle_content_type): <NEW_LINE> <INDENT> return _require_permission("hide", "Cannot access a project", pootle_content_type)
Require the `hide` permission.
625941ef1b99ca400220b026
def __eq__(self, other): <NEW_LINE> <INDENT> return (not self and not other) or (self and other and self._quality == other._quality)
Check whether two matches have the same quality.
625941ef462c4b4f79d1dc41
def is_parallel(l1, l2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a1, b1, c1 = l1.coefficients <NEW_LINE> a2, b2, c2 = l2.coefficients <NEW_LINE> return bool(simplify(a1*b2 - b1*a2) == 0) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return False
Are two linear entities parallel? Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= True if l1 and l2 are parallel, False otherwise. See Also ======== coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> p3, p4 = Point(3, 4), Point(6,...
625941efcc0a2c11143dd404
@api.route('/new_photo', methods=['POST']) <NEW_LINE> @login_required <NEW_LINE> def new_photo(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file = request.files['file'] <NEW_LINE> if file and allowed_file(file.filename): <NEW_LINE> <INDENT> filename = secure_filename(file.filename) <NEW_LINE> url = os.path.join(curr...
功能: 添加新的商品图片 参数类型: json 参数: 图片(二进制信息) 返回类型: json 参数: status(1为成功, 0为json参数不对, -1为文件夹没创建或路径不对, -2为未知错误, -3为文件为空, -4为文件名后缀不符合), data(商品列表数据)
625941ef287bf620b61d3fd2
def Cel2Gal(ra, dec): <NEW_LINE> <INDENT> deg = np.pi/180 <NEW_LINE> Ag = np.array([[-0.0548755604162154, -0.8734370902348850, -0.4838350155487132], [0.4941094278755837, -0.4448296299600112, 0.7469822444972189], [-0.8676661490190047, -0.1980763734312015, 0.4559837761750669]]) <NEW_LI...
Transform Ra and Dec to galactic coordinates from celestial.
625941ef6fece00bbac2dcb8
def test_propertySetter(self): <NEW_LINE> <INDENT> newValue = object() <NEW_LINE> obj = ClassWithDeprecatedProperty() <NEW_LINE> obj.someProperty = newValue <NEW_LINE> self.assertIs(newValue, obj._someProtectedValue) <NEW_LINE> message = ( 'twisted.python.test.test_deprecate.ClassWithDeprecatedProperty.' 'someProperty ...
When L{deprecatedProperty} is used on a C{property}, setter accesses raise a L{DeprecationWarning}.
625941ef99cbb53fe6793157
def null_decrypt(ciphertext, _): <NEW_LINE> <INDENT> return ciphertext
A function for not decrypting at all.
625941eff548e778e58cdaf2
def raw_x_batch(self, coeff_count=13): <NEW_LINE> <INDENT> mfccs, mfcc_sr = self.mfcc(coeff_count) <NEW_LINE> delta1, delta2 = self.delta_coeffs(mfccs) <NEW_LINE> batch_x = np.concatenate((mfccs, delta1, delta2), axis=0).transpose() <NEW_LINE> return batch_x
Retrieve only the Neural Network input batch data. No Annotations.
625941efbe8e80087fb211ac
def getGitVersionDate(versionIn=None): <NEW_LINE> <INDENT> if not versionIn: <NEW_LINE> <INDENT> version = getGitVersion() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> version = versionIn <NEW_LINE> <DEDENT> cwd = os.getcwd() <NEW_LINE> dn = os.path.dirname(__file__) <NEW_LINE> if dn: <NEW_LINE> <INDENT> os.chdir(dn) ...
Attempt to determine the date of the version from git
625941efac7a0e7691ed4633
def __init__( self, *, scope_map_id: Optional[str] = None, credentials: Optional["TokenCredentialsProperties"] = None, status: Optional[Union[str, "TokenStatus"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(Token, self).__init__(**kwargs) <NEW_LINE> self.creation_date = None <NEW_LINE> self.provisioning_state = None ...
:keyword scope_map_id: The resource ID of the scope map to which the token will be associated with. :paramtype scope_map_id: str :keyword credentials: The credentials that can be used for authenticating the token. :paramtype credentials: ~azure.mgmt.containerregistry.v2019_05_01_preview.models.TokenCredentialsPropert...
625941efb7558d58953c547a
def Compute_Sat(KB, facts, print_info): <NEW_LINE> <INDENT> new_KB = KB[:] <NEW_LINE> for fact in facts: <NEW_LINE> <INDENT> if fact not in KB: <NEW_LINE> <INDENT> new_KB.append(fact) <NEW_LINE> <DEDENT> <DEDENT> symbols = find_symbols(new_KB) <NEW_LINE> model = {} <NEW_LINE> for symbol in symbols: <NEW_LINE> <INDENT> ...
Prints symbols, propositions, and additional information from a knowledge base, then runs a DPLL satisfiability search and prints the result
625941ef7b180e01f3dc4d63
@login_required <NEW_LINE> def topics(request): <NEW_LINE> <INDENT> topics = Topic.objects.filter(owner=request.user).order_by('date_added') <NEW_LINE> context = {'topics': topics} <NEW_LINE> return render(request, 'learning_logs/topics.html', context)
显示所有主题的网页
625941efd268445f265b53e1
def test_fail_delete_file(self): <NEW_LINE> <INDENT> materials_queue = ["foo"] <NEW_LINE> products_queue = ["foo"] <NEW_LINE> rule = ["DELETE", "foo"] <NEW_LINE> with self.assertRaises(RuleVerficationError): <NEW_LINE> <INDENT> verify_delete_rule(rule, materials_queue, products_queue)
["DELETE", "foo"], foo still in products (not deleted), fails.
625941ef73bcbd0ca4b2c5e8
def close(self): <NEW_LINE> <INDENT> return self.__connection.close()
Permanently remove all messages that have the \Deleted flag set from the currently selected mailbox, and returns to the authenticated state from the selected state
625941ef1d351010ab85608d
def cross_edge(A,B,pt,no): <NEW_LINE> <INDENT> ret_val = [None]*3 <NEW_LINE> V = B - A <NEW_LINE> proj = V.project(no).length <NEW_LINE> if proj == 0: <NEW_LINE> <INDENT> p_to_A = A - pt <NEW_LINE> a_proj = p_to_A.project(no).length <NEW_LINE> if a_proj == 0: <NEW_LINE> <INDENT> print('special case co planar edge') <NE...
wrapper of intersect_line_plane that limits intersection to within the line segment. args: A - Vector endpoint of line segment B - Vector enpoint of line segment pt - pt on plane to intersect no - normal of plane to intersect return: list [Intersection Type, Intersection Point, Intersection Po...
625941ef4e4d5625662d4942
def full_dump(self): <NEW_LINE> <INDENT> return self.game_object.to_dict()
Return full dump of running game with seed.
625941ef498bea3a759ba020
def message_ports_out(self): <NEW_LINE> <INDENT> return _PHY_swig.conv_decode_tag_sptr_message_ports_out(self)
message_ports_out(conv_decode_tag_sptr self) -> swig_int_ptr
625941efeab8aa0e5d26e0cc
def groups(self): <NEW_LINE> <INDENT> return list(self.grpimg.keys())
Get list of available image groups. Returns ------- grp : list A list of names of available image groups
625941efe5267d203edce208
def _find_det_type(self, start, sent): <NEW_LINE> <INDENT> word = sent[start]['word'].lower() <NEW_LINE> pos = sent[start]['pos'] <NEW_LINE> if pos == 'DT': <NEW_LINE> <INDENT> if word in ('a', 'an'): <NEW_LINE> <INDENT> return 'indefinite' <NEW_LINE> <DEDENT> elif word == 'the': <NEW_LINE> <INDENT> return 'definite' <...
Finds the type of the determiner of the mention, if it exists. Possible values are 'indefinite', 'definite', 'demonstrative', 'unk', and 'none'. Args: start: the starting index of the mention. sent: the sentence the mention occurs in. Returns: The determiner type.
625941efd53ae8145f87a7d7
def setUp(self): <NEW_LINE> <INDENT> query = os.path.join(DATA_DIR,"query_notpresent.fastq") <NEW_LINE> self.query_fid1 = "@COOPER:74:HFTH3BBXX:3:1101:29833:1033 1:N:0:NAGATTCC+NAGCTATA" <NEW_LINE> self.query_rid1 = "@COOPER:74:HFTH3BBXX:3:1101:29833:1033 2:N:0:NAGATTCC+NAGCTATA" <NEW_LINE> self.fout_name = os.path.joi...
Here, one of the queries is present in the parent FASTQ files, and one of them isn't. The query file has the record below from the reads2.fastq file: 1) @COOPER:74:HFTH3BBXX:3:1101:29833:1033 2:N:0:NAGATTCC+NAGCTATA And the non-existant record: 2) @not_present_ Need to make sure that the output files co...
625941ef4527f215b584c9c4
def growN(self, N): <NEW_LINE> <INDENT> for n in range(0,N): <NEW_LINE> <INDENT> self.grow() <NEW_LINE> print(str(n+1) + ' of ' + str(N) + ' generated') <NEW_LINE> <DEDENT> return
Grow the causal set N times
625941ef99fddb7c1c9de900
def checkRocketPosition(obs, agent_host): <NEW_LINE> <INDENT> for i in range(1,39): <NEW_LINE> <INDENT> key = 'InventorySlot_'+str(i)+'_item' <NEW_LINE> if key in obs: <NEW_LINE> <INDENT> item = obs[key] <NEW_LINE> if item == 'fireworks': <NEW_LINE> <INDENT> agent_host.sendCommand("swapInventoryItems 0 " + str(i)) <NEW...
Make sure our rockets, if we have any, is in slot 0.
625941ef71ff763f4b549c08
def natural_key(string_): <NEW_LINE> <INDENT> return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]
Define sort key that is integer-aware
625941efe8904600ed9f24a9
def update_from_database(self, data_path): <NEW_LINE> <INDENT> if data_path: <NEW_LINE> <INDENT> self.data_path = data_path <NEW_LINE> self.data = dict() <NEW_LINE> self.button.props.sensitive = True <NEW_LINE> with open(data_path) as csv_file: <NEW_LINE> <INDENT> csv_reader = csv.DictReader(csv_file, delimiter=';') <N...
Display dialog box and get selected item Returns: Selected row on Ok None on Cancel
625941ef8e71fb1e9831dd19