code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def append_word_explain(word, phonetics, explains): <NEW_LINE> <INDENT> ps = "\t".join(phonetics) <NEW_LINE> with open("./record/words.txt", "a", encoding="utf-8") as f: <NEW_LINE> <INDENT> f.write(word + ": " + ps) <NEW_LINE> f.write("\n") <NEW_LINE> for explain in explains: <NEW_LINE> <INDENT> f.write("\t" + explain ...
向文件中添加单词解释 :param word: 要解释的单词 :param phonetics: 发音(英、美) :param explains: 单词中文解释 :return:
625941cdf9cc0f698b1406f9
def iterator(self, callback, thread_id): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.running_thread_num += 1 <NEW_LINE> element = self.q.get(block=True, timeout=1) <NEW_LINE> self.element_index += 1 <NEW_LINE> if self.print_before_task: <NEW_LINE> <INDENT> print('线程 %d 开始执行第 %d 个任务...
在线程中迭代,直到出错
625941cdde87d2750b85fe90
def checktype(value,type_): <NEW_LINE> <INDENT> if type_ is True: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if type(type_)==type: <NEW_LINE> <INDENT> if not isinstance(value,type_): <NEW_LINE> <INDENT> raise CheckError("isinstance failed",value,"of type",type(value),"is not of type",type_) <NEW_LINE> <DEDENT...
Check value against the type spec. If everything is OK, this just returns the value itself. If the types don't check out, an exception is thrown.
625941cd01c39578d7e74f38
def GetInput2(self): <NEW_LINE> <INDENT> return _itkContourDirectedMeanDistanceImageFilterPython.itkContourDirectedMeanDistanceImageFilterIUS3IUS3_GetInput2(self)
GetInput2(self) -> itkImageUS3
625941cd379a373c97cfac42
def list_obs_screen(header): <NEW_LINE> <INDENT> ready_screen("list_obs_screen") <NEW_LINE> screen.addstr(1, 1, header + " > List Observation ") <NEW_LINE> screen.addstr(6, 6, "List of observation(s): ") <NEW_LINE> for i, obs_info in enumerate(observations_info): <NEW_LINE> <INDENT> screen.addstr(8 + i, 10, " [" + str(...
Generates screen to list observations. :param header: Header of page :type header: string
625941cd293b9510aa2c3394
def __init__(self, video_path, sample_interval=1): <NEW_LINE> <INDENT> if not os.path.exists(video_path): <NEW_LINE> <INDENT> raise IOError("Video not exist: " + video_path) <NEW_LINE> <DEDENT> assert isinstance(sample_interval, int) and sample_interval >= 1 <NEW_LINE> self.cnt_imgs = 0 <NEW_LINE> self.is_stoped = Fals...
A video reader class for reading video frames from video. Arguments: video_path sample_interval {int}: sample every kth image.
625941cd82261d6c526ab59c
def calc_hessian(self, t, x, p): <NEW_LINE> <INDENT> return self.hessian
Return Hessian.
625941cd8a349b6b435e8270
def get_spatial_edge_feature(xyz, features, k=20, idx=None): <NEW_LINE> <INDENT> if idx is None: <NEW_LINE> <INDENT> _, idx = knn_point(k+1, xyz, xyz, unique=True, sort=True) <NEW_LINE> idx = idx[:, :, 1:, :] <NEW_LINE> <DEDENT> point_cloud_neighbors = tf.gather_nd(features, idx) <NEW_LINE> point_cloud_central = tf.exp...
Construct edge feature for each point Args: point_cloud: (batch_size, num_points, 1, num_dims) nn_idx: (batch_size, num_points, k) k: int Returns: edge features: (batch_size, num_points, k, num_dims)
625941cd4527f215b584c554
def set_CreatedTime(self, value): <NEW_LINE> <INDENT> super(CreateReadingInputSet, self)._set_input('CreatedTime', value)
Set the value of the CreatedTime input for this Choreo. ((optional, date) The time that the action was created (e.g. 2013-06-24T18:53:35+0000).)
625941cd9c8ee82313fbb873
def get_size(self): <NEW_LINE> <INDENT> return self.__size
:return: the size of the asteroid
625941cdd8ef3951e324363b
def gifsplit(gif,outfolder): <NEW_LINE> <INDENT> images = imageio.mimread(gif) <NEW_LINE> for x, img in enumerate(images): <NEW_LINE> <INDENT> img = np.asarray(img) <NEW_LINE> imageio.imwrite(os.path.join(outfolder,"%d.png" % x), img)
Split GIF to PNG
625941cde1aae11d1e749db4
def run(): <NEW_LINE> <INDENT> file_name = get_file_name() <NEW_LINE> frontier = select_frontier() <NEW_LINE> maze = Maze(file_name, frontier) <NEW_LINE> maze.go()
Runs the program for the user
625941cd0383005118ecf6e0
@server.route('/check-loggers', methods=['GET']) <NEW_LINE> def check_loggers(): <NEW_LINE> <INDENT> raise Exception("Test exception")
Logging check endpoint. This endpoint errors so as to verify that loggers are working.
625941cd23849d37ff7b318d
@click.command(help=__doc__) <NEW_LINE> @click.option( "--namespaces", default="namespaces.yaml", type=click.File(), help="Path to a yaml namespaces file", ) <NEW_LINE> @click.option( "--app-listings-uri", default="https://probeinfo.telemetry.mozilla.org/v2/glean/app-listings", help="URI for probeinfo service v2 glean ...
Generate lookml from namespaces.
625941cd7b180e01f3dc48fa
def move(self): <NEW_LINE> <INDENT> self.vy -= self.a <NEW_LINE> self.x += self.vx <NEW_LINE> self.y -= self.vy <NEW_LINE> self.check_walls() <NEW_LINE> self.set_coord()
Переместить мяч по прошествии единицы времени. Метод описывает перемещение мяча за один кадр перерисовки. То есть, обновляет значения self.x и self.y с учетом скоростей self.vx и self.vy, силы гравитации, действующей на мяч, и стен по краям окна (размер окна 800х600).
625941cd3346ee7daa2b2e69
def get_center_points(self, session, is_train=True): <NEW_LINE> <INDENT> self.melody_profile.get_cluster_center_points(session, is_train)
计算音符平均音高的中心点,这些中心点对
625941cd090684286d50ede3
def texture_pie(ax): <NEW_LINE> <INDENT> tf = {} <NEW_LINE> tf['Fine Noise'] = Texture(style='noise', block=2) <NEW_LINE> tf['Coarse Noise'] = Texture(style='noise', block=8) <NEW_LINE> tf['Shaded Noise'] = Texture(style='noise', light=True, block=2) <NEW_LINE> tf['Shaded\nCoarse Noise'] = Texture(style='noise', light=...
Demonstration routine showing multiple examples of textures and how to make them. If you only want one texture, you can just use ``agg_filter=my_texture`` when drawing the first time.
625941cd2c8b7c6e89b358be
def closeEvent(self, event): <NEW_LINE> <INDENT> event.ignore() <NEW_LINE> self._hideMainWindow()
Prevent main window from closing by clicking on close button @param event: the event, which controls the operation @type event: QCloseEvent
625941cd6e29344779a6270f
@log_help.log2screen(LG) <NEW_LINE> def xyz(archivo): <NEW_LINE> <INDENT> lines = open(archivo,"r").readlines() <NEW_LINE> nat = int(lines[0]) <NEW_LINE> LG.debug('Expecting %s atoms'%(nat)) <NEW_LINE> try: <NEW_LINE> <INDENT> lines[1] = lines[1].split('#')[0] <NEW_LINE> vecs = lines[1].replace(' ','').lstrip().rstrip(...
Reads the lattice information from an extended xyz file. The file is assumed to have the following structure: N atoms [latt vec 1][latt vec 2]... # eg: [1,0,0][0,1,0] C 0 0 0 1/-1 # atom X Y Z sublattice If the lattice vectors are not specified it will return an empty list, so the prog...
625941cd4f88993c3716c165
def prepare_Cps(self, Cp): <NEW_LINE> <INDENT> assert isinstance(Cp, ndarray) <NEW_LINE> CpDict = {} <NEW_LINE> for eid, element in enumerate(self.elements): <NEW_LINE> <INDENT> eidi = eid + 1 <NEW_LINE> (n1, n2, n3) = element <NEW_LINE> cp = Cp[element-1].sum() / 3. <NEW_LINE> CpDict[eidi] = cp <NEW_LINE> <DEDENT> sel...
converts Cp applied to the node -> Cp applied on the element centroid
625941cdb57a9660fec33982
def intToRomanNum(i): <NEW_LINE> <INDENT> if i >= len(_romanNumbers): <NEW_LINE> <INDENT> raise IndexError(u'Roman value %i is not defined' % i) <NEW_LINE> <DEDENT> return _romanNumbers[i]
Convert integer to roman numeral.
625941cda4f1c619b28b0137
def _get_attribute(self, attribute, level): <NEW_LINE> <INDENT> if 0 <= level < self.num_levels: <NEW_LINE> <INDENT> return attribute[level] <NEW_LINE> <DEDENT> raise ValueError('Invalid pyramid level: '+str(level))
Return an attribute from the Scale Space at a given level. Returns the level-th element of attribute if level is a valid level of this scale space. Otherwise, returns None. Parameters ---------- attribute : list the attribute to retrieve the level-th element from level : int, the index of the required element...
625941cd5f7d997b87174b96
def test_pop_empty(self): <NEW_LINE> <INDENT> with self.assertRaises(AttributeError): <NEW_LINE> <INDENT> self.stack.pop()
popping an empty linked list give a none type error
625941cd91f36d47f21ac5f1
def add_ip(self, name, ip, array='py_api'): <NEW_LINE> <INDENT> request = ModifySecurityIpsRequest.ModifySecurityIpsRequest() <NEW_LINE> db_list = self.get_db_instance(name) <NEW_LINE> if not db_list: <NEW_LINE> <INDENT> raise AttributeError('the db instance is not exist') <NEW_LINE> <DEDENT> print(db_list[0].id) <NEW_...
添加白名单 :name: rds实例别名 :param ip: 要添加的ip :param array: 分组 :return:
625941cd26238365f5f0ef6c
def list_check(lst): <NEW_LINE> <INDENT> return all([True if item == list(item) else False for item in lst])
Are all items in lst a list? >>> list_check([[1], [2, 3]]) True >>> list_check([[1], "nope"]) False
625941cd96565a6dacc8f7c9
def add(a, b): <NEW_LINE> <INDENT> return a + b
returns the sum of a and b
625941cdcdde0d52a9e53131
def _create_plt_obj(self, idx): <NEW_LINE> <INDENT> raise NotImplementedError
Sets 'self.plt_obj' to an instance of a matplotlib.artist.Artist object (or derived classes) created by using 'self.ax' which can later be updated by feeding new data into it. Only called on the first call for visualization.
625941cdbe7bc26dc91cd6fe
def DeepMobileNetV3PlusD_HANet(args, num_classes, criterion, criterion_aux): <NEW_LINE> <INDENT> print("Model : DeepLabv3+, Backbone : mobilenetv2") <NEW_LINE> return DeepV3PlusHANet(num_classes, trunk='mobilenetv2', criterion=criterion, criterion_aux=criterion_aux, variant='D16', skip='m1', args=args)
ShuffleNet Based Network
625941cd94891a1f4081bba7
def log(msg): <NEW_LINE> <INDENT> global logfile <NEW_LINE> if not renpy.config.log: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if msg is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> msg = unicode(msg) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT...
:doc: debug If :var:`config.log` is not set, this does nothing. Otherwise, it opens the logfile (if not already open), formats the message to :var:`config.log_width` columns, and prints it to the logfile.
625941cd3539df3088e2e449
def translated(self, value, resolved): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> return resolved.translate(value, False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
translate using the schema type
625941cd283ffb24f3c559ff
def to_dict(self) -> Dict: <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'restart') and self.restart is not None: <NEW_LINE> <INDENT> _dict['restart'] = self.restart <NEW_LINE> <DEDENT> if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: <NEW_LINE> <INDENT> _dict['alternate_intent...
Return a json dictionary representing this model.
625941cd21bff66bcd684a51
def visitInterface(self, node): <NEW_LINE> <INDENT> if node.hasAttribute(self.mark.getName()): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> node.addAttribute(self.mark) <NEW_LINE> for parent in node.getParents(): <NEW_LINE> <INDENT> parent.accept(self.__IORself) <NEW_LINE> <DEDENT> node.addDependencies(node.getP...
Record dependence on methods
625941cdf8510a7c17cf97fb
def process(tree, processes=["sub", "toc", "xref"], **kwargs): <NEW_LINE> <INDENT> for process in processes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process_module = getattr(__import__('processes', globals(), locals(), [str(process)], -1), process) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pro...
Process the given tree.
625941cd3c8af77a43ae389e
def jquery_update_text(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): <NEW_LINE> <INDENT> self.jquery_update_text_value( selector, new_value, by=by, timeout=timeout)
The shorter version of jquery_update_text_value() (The longer version remains for backwards compatibility.)
625941cd71ff763f4b549789
def confirmDownloadGameImages(): <NEW_LINE> <INDENT> return Yes == QMessageBox.question(_parent(), my.tr("Save game images"), my.tr("Do you want to save all images to your Desktop?"), Yes|No, No)
@return bool
625941cd460517430c394283
def relativeSource(self, other): <NEW_LINE> <INDENT> return os.path.relpath(self.local, os.path.dirname(other.local))
Location of this page related to the other page.
625941cd0a50d4780f666f90
@fixture <NEW_LINE> def user(app): <NEW_LINE> <INDENT> user = add_user(app.db, app, name=new_username()) <NEW_LINE> yield user
Fixture for creating a temporary user Each time the fixture is used, a new user is created
625941cd5166f23b2e1a5257
def minMeetingRooms2(self, intervals): <NEW_LINE> <INDENT> if len(intervals) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> intervals.sort(key=lambda x: x.start) <NEW_LINE> pq = [(intervals[0].end, intervals[0].start)] <NEW_LINE> n_parallels = 1 <NEW_LINE> for itvl in intervals[1:]: <NEW_LINE> <INDENT> while le...
:type intervals: List[Interval] :rtype: bool
625941cde8904600ed9f202b
def validate_query_params(self, request): <NEW_LINE> <INDENT> for qp in request.query_params.keys(): <NEW_LINE> <INDENT> if not self.query_regex.match(qp): <NEW_LINE> <INDENT> raise ValidationError('invalid query parameter: {}'.format(qp)) <NEW_LINE> <DEDENT> if len(request.query_params.getlist(qp)) > 1: <NEW_LINE> <IN...
Validate that query params are in the list of valid query keywords in :py:attr:`query_regex` :raises ValidationError: if not.
625941cdd99f1b3c44c6768c
def softmaxesToWords(self, softmaxes, dictionary, no_unk=True): <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> for sm in softmaxes: <NEW_LINE> <INDENT> token = sm.argmax() + 1 <NEW_LINE> tokens.append(token) <NEW_LINE> <DEDENT> return self.tokensToWords(tokens, dictionary, no_unk=no_unk)
Expects softmaxes to be a numpy array with normalized rows. This will take the argmax of each row, translate that into a token, and convert the accumulated tokens to a series of words.
625941cd99fddb7c1c9de48f
def calculate_send_write_CMD( parameterGroup=None, parameterNumber=None, inputValue=None ): <NEW_LINE> <INDENT> assert parameterGroup is not None, ValueError( 'Parameter Group is not defined') <NEW_LINE> assert parameterNumber is not None, ValueError( 'Parameter Number is not defined') <NEW_LINE> assert inputValue is n...
Calculating from parameter group, parameter number and input value to write command to be sent to GRAPHIX and make full string command
625941cd7cff6e4e81117a84
def __init__(self, name, input_objs, parent_name, level=0): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> assert type(input_objs) == list, 'shiftAdd - expecting input_obj to be a list' <NEW_LINE> self.inputObjs = input_objs <NEW_LINE> self.outputs = [] <NEW_LINE> self.shiftAddLevel = level <NEW_LINE> self.fuName = pa...
Constructor to initialize the shiftAmts and inputs
625941cd3cc13d1c6d3c7478
@marsloader(query_api_support=True) <NEW_LINE> def _immunization_list(request, group_by, date_group, aggregate_by, limit, offset, order_by, status, date_range, filters, record=None, carenet=None): <NEW_LINE> <INDENT> q = FactQuery(Immunization, IMMUNIZATION_FILTERS, group_by, date_group, aggregate_by, limit, offset, or...
List the immunization objects matching the passed query parameters. See :doc:`/query-api` for a listing of valid parameters. Will return :http:statuscode:`200` with a list of immunizations on success, :http:statuscode:`400` if any invalid query parameters were passed.
625941cd7b25080760e39557
def get_mongodb_collection(): <NEW_LINE> <INDENT> client = pymongo.MongoClient(host='localhost', port=27017) <NEW_LINE> db = client.fastfishdata <NEW_LINE> collection = db.yp_russia <NEW_LINE> return collection
获取MongoDB :return:
625941cd3c8af77a43ae389f
def invoke_lambda(batches, m_id): <NEW_LINE> <INDENT> batch = [k.key for k in batches[m_id-1]] <NEW_LINE> resp = lambda_client.invoke( FunctionName = mapper_lambda_name, InvocationType = 'RequestResponse', Payload = json.dumps({ "bucket": bucket, "keys": batch, "jobBucket": job_bucket, "jobId": job_id, "mapperId": m_i...
lambda invoke function
625941cdfff4ab517eb2f53b
def export_subs(self): <NEW_LINE> <INDENT> fh = open(self._filename, 'w') <NEW_LINE> subs = sorted(self.get_subs(), key=str.lower) <NEW_LINE> json.dump(subs, fh, indent=2) <NEW_LINE> fh.close()
Saves the user's subreddits to file.
625941cd91af0d3eaac9bb17
def rws(self, size, fitness): <NEW_LINE> <INDENT> if self.maximum: <NEW_LINE> <INDENT> fitness_ = fitness <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fitness_ = 1.0 / fitness <NEW_LINE> <DEDENT> idx = np.random.choice(np.arange(len(fitness_)), size=size, replace=True, p=fitness_/fitness_.sum()) <NEW_LINE> return idx
Roulette Wheel Selection. Args: size: the size of individuals you want to select according to their fitness. fitness: the fitness of population you want to apply rws to.
625941cd76d4e153a657ec2f
def report_cpu_for_vserver(vs_host, vs_directory): <NEW_LINE> <INDENT> total = {'user': 0, 'system': 0, 'onhold': 0} <NEW_LINE> sched_path = os.path.join(vs_directory, 'sched') <NEW_LINE> with open(sched_path, 'r') as sched: <NEW_LINE> <INDENT> sched.readline() <NEW_LINE> for line in sched: <NEW_LINE> <INDENT> if line....
Reports cpu usage for vs_host. Args: vs_host: str, hostname of vserver context. vs_directory: str, path to vserver directory containing 'sched' stats.
625941cd7047854f462a1508
def test_get_col(self): <NEW_LINE> <INDENT> expected = [6,0,1,0,3,2,0,8,4] <NEW_LINE> actual = self.sudoku.get_col(0) <NEW_LINE> self.assertEqual(actual, expected) <NEW_LINE> expected = [2,1,0,7,4,0,6,0,8] <NEW_LINE> actual = self.sudoku.get_col(8) <NEW_LINE> self.assertEqual(actual, expected)
Test that specific column can be retrieved
625941cdb7558d58953c5013
def updateInstancePassword(**kargs): <NEW_LINE> <INDENT> my_apikey, my_secretkey = c.read_config() <NEW_LINE> if not 'instanceid' in kargs: <NEW_LINE> <INDENT> return '[ktcloud] Not required argument \'instanceid\' ' <NEW_LINE> <DEDENT> if not 'dbmasterpassword' in kargs: <NEW_LINE> <INDENT> return '[ktcloud] Not requi...
Update Database dbmasterpassword * Args : - instanceid(String, Required) : instanceid - dbmasterpassword(String, Required) : dbmasterpassword * Examples : print(db.updateInstancePassword(zone='KR-M', instanceid='94699dfe-f3f9-4867-8fe7-14b5298792ce', dbmasterpassword='abcd1357')) * Ref : https://cloud.kt.com/p...
625941cd56b00c62f0f14758
def test_doc_usage_expressions_1(): <NEW_LINE> <INDENT> from mini_lambda import x <NEW_LINE> print(type(x)) <NEW_LINE> assert type(x) == LambdaExpression <NEW_LINE> print(x.evaluate(1234)) <NEW_LINE> assert x.evaluate(1234) == 1234 <NEW_LINE> print(x.to_string()) <NEW_LINE> assert x.to_string() == 'x'
Tests that the first example in doc/usage in the expressions section works
625941cdd10714528d5ffde2
def independent_act(): <NEW_LINE> <INDENT> return self.global_timestep
Does not store state, action, internal in buffer. Hence, does not have any influence on learning. Does not increase timesteps.
625941cd4e696a04525c954a
def make_maximal_planar(g, unfilter=False): <NEW_LINE> <INDENT> g = GraphView(g, directed=False) <NEW_LINE> libgraph_tool_topology.maximal_planar(g._Graph__graph)
Add edges to the graph to make it maximally planar. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be used. It must be a biconnected planar graph with at least 3 vertices. Notes ----- A graph is maximal planar if no additional edges can be added to it without creating a non-planar graph. By Eu...
625941cda05bb46b383ec920
def make_directory(inputDir): <NEW_LINE> <INDENT> if not os.path.exists(inputDir): <NEW_LINE> <INDENT> os.makedirs(inputDir)
make input directory if it does not exist.
625941cd379a373c97cfac43
def isa(self,variant_idx,expr): <NEW_LINE> <INDENT> return '(' + expr + ').tag == {}'.format(variant_idx)
return a test indicating whether expr is of the variant type with index variant_idx
625941cd8da39b475bd65072
def index(request): <NEW_LINE> <INDENT> context = { 'questions': Question.objects.all(), } <NEW_LINE> return render(request, 'polls/index.html', context)
1. 모든 Question을 출력하는 View(Controller)구현 context dict객체를 생성, 'questions'키에 모든 Question객체를 DB에서 가져온 QuerySet을 할당 render함수를 사용해서 'polls/index.html'을 context와 함께 rendering한 결과를 리턴 2. 템플릿 파일들이 있는 디렉토리를 settings.py에 설정 settings.py에 TEMPLATE_DIR를 지정 TEMPLATE = ...설정의 'DIRS'키를 갖는 리스트에 TEMPLATE_DIR추가 3. 템플릿 파...
625941cd1f5feb6acb0c4c4f
def initialize_random(self): <NEW_LINE> <INDENT> self.deck = copy.deepcopy(self.base_deck) <NEW_LINE> self.player_hands = [] <NEW_LINE> for player_num in range(self.num_players): <NEW_LINE> <INDENT> hand = [] <NEW_LINE> for i in range(self.cards_per_player): <NEW_LINE> <INDENT> hand.append(HintedCard(self.deck.draw(), ...
Initialize a random starting hand for all players.
625941cd8da39b475bd65073
def import_module(self, module, names=None, start=0): <NEW_LINE> <INDENT> self.import_arguments(module.pipe, names) <NEW_LINE> self.import_stages(module.pipe, start)
Imports another pipeline, adding all of its arguments, or only the sublist from `names`, and all of its stages, or only those starting from number `start`.
625941cdfbf16365ca6f62c3
def _astype(self, dtype, **kwargs): <NEW_LINE> <INDENT> if com.is_datetime64tz_dtype(dtype): <NEW_LINE> <INDENT> dtype = DatetimeTZDtype(dtype) <NEW_LINE> values = self.values <NEW_LINE> if getattr(values,'tz',None) is None: <NEW_LINE> <INDENT> values = DatetimeIndex(values).tz_localize('UTC') <NEW_LINE> <DEDENT> value...
these automatically copy, so copy=True has no effect raise on an except if raise == True
625941cdb830903b967e9a0a
def simplify_gene_expressions(self): <NEW_LINE> <INDENT> gene_ui = UnitOfInformation("ct", "gene") <NEW_LINE> mrna_ui = UnitOfInformation("ct", "mRNA") <NEW_LINE> es = EmptySet() <NEW_LINE> for p in self.processes: <NEW_LINE> <INDENT> if isinstance(p, StoichiometricProcess) and isinstance(p.reactants[0], EmptySet): <NE...
Simplifies transcription and translation processes into generic processes a la CellDesigner
625941cda4f1c619b28b0138
@report <NEW_LINE> def testIntegerDataArray(): <NEW_LINE> <INDENT> da = pyopenms.IntegerDataArray() <NEW_LINE> assert da.size() == 0 <NEW_LINE> da.push_back(1) <NEW_LINE> da.push_back(4) <NEW_LINE> assert da.size() == 2 <NEW_LINE> assert da[0] == 1 <NEW_LINE> assert da[1] == 4 <NEW_LINE> da[1] = 7 <NEW_LINE> assert da[...
@tests: IntegerDataArray
625941cd460517430c394284
def nanoi(n, pillar_src="A", pillar_bridge="B", pillar_tar="C"): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> print("%s -> %s" % (pillar_src, pillar_tar)) <NEW_LINE> return <NEW_LINE> <DEDENT> nanoi(n - 1, pillar_src, pillar_tar, pillar_bridge) <NEW_LINE> print("%s -> %s" % (pillar_src, pillar_tar)) <NEW_LINE> na...
:param n: :param pillar_src: :param pillar_bridge: :param pillar_tar: :return:
625941cd656771135c3eb96d
def _set_display_name(ctx): <NEW_LINE> <INDENT> pass
Sets document display name.
625941cdbde94217f3682ef0
def check_all_equal(iter_val, iter_ref, msg=None, any_order=False, diff=False): <NEW_LINE> <INDENT> r_val = repr(iter_val) <NEW_LINE> r_ref = repr(iter_ref) <NEW_LINE> assert all_equal(iter_val, iter_ref, any_order), format_test_val_ref(r_val, r_ref, pre="All Equal Fail", msg=msg, diff=diff)
:param iter_val: tested values. :param iter_ref: reference values. :param msg: override message to display if failing test. :param any_order: allow equal values to be provided in any order, otherwise order must match as well as values. :param diff: generate a detailed diff result within indications of different fields ...
625941cd07d97122c417898a
def _assert_output(self, output, *args, **kwargs): <NEW_LINE> <INDENT> assert len(output) == (len(args) + 1) <NEW_LINE> assert {'user_id': 'user_id', 'username': 'username', 'email': 'email', 'full_name': 'full_name', 'course_id': 'course_id', 'is_opted_in_for_email': 'is_opted_in_for_email', 'preference_set_datetime':...
Check the output of the report. Arguments: output (list): List of rows in the output CSV file. *args: Tuples of (user, course_id, opt_in_pref) Keyword Arguments: expect_pref_datetime (bool): If false, expect the default datetime. Returns: None Raises: AssertionError
625941cd7d847024c06be3ba
def test_save_as_duplication(self): <NEW_LINE> <INDENT> post_data = {'_saveasnew': '', 'name': 'John M', 'gender': 1, 'age': 42} <NEW_LINE> response = self.client.post('/test_admin/admin/admin_views/person/1/', post_data) <NEW_LINE> self.assertEqual(len(Person.objects.filter(name='John M')), 1) <NEW_LINE> self.assertEq...
Ensure save as actually creates a new person
625941cd7c178a314d6ef55f
def get_requested_participation(self): <NEW_LINE> <INDENT> participations = participation.Participation.objects.filter(requested=True, started=False, finished=False, author=self, trip__active=True, requested_deleted=False) <NEW_LINE> if not participations: return None <NEW_LINE> if len(participations) > 1: return None ...
Returns the currently Participation of the Person in a Trip.
625941cdcc40096d61595a50
def pipeline_get_metadata(metadata): <NEW_LINE> <INDENT> found_metadata = None <NEW_LINE> if not metadata: <NEW_LINE> <INDENT> return found_metadata <NEW_LINE> <DEDENT> json_len = len(metadata) <NEW_LINE> if json_len <= 0: <NEW_LINE> <INDENT> return found_metadata <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if isinsta...
Look through the metadata looking for pipeline configuration Args: metadata(JSON): the JSON object, or list of JSON objects, to search Returns: The found JSON is returned, otherwise None is returned. None is also returned if the passed in JSON is invalid or is empty. Notes: If the metadata parameter is ...
625941cd009cb60464c634b1
def delete_instance_groups(self, instance_groups, **ignore): <NEW_LINE> <INDENT> action = const.ACTION_DELETE_INSTANCE_GROUPS <NEW_LINE> valid_keys = ['instance_groups'] <NEW_LINE> body = filter_out_none(locals(), valid_keys) <NEW_LINE> if not self.conn.req_checker.check_params(body, required_params=['instance_groups']...
Delete the specific instance group. @param instance_groups: An id list contains the group(s) id which will be deleted.
625941cdadb09d7d5db6c88f
@app.get('/users') <NEW_LINE> def get_users(): <NEW_LINE> <INDENT> users = db.query(User).order_by(User.email).all() <NEW_LINE> return users
Return users.
625941cd596a897236089bc0
def ALMAUVFITSTab(inUV, filename, outDisk, err, exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], include=[], logfile=""): <NEW_LINE> <INDENT> mess = "Write Tables to FITS UV data "+filename+" on disk "+str(outDisk) <NEW_LINE> printMess(mess, logfile) <NEW_LINE> if not UV.P...
Write Tables on UV data as FITS file Write Tables from a UV data set (but no data) as a FITAB format file History written to header * inUV = UV data to copy * filename = name of FITS file, any whitespace characters replaced with underscore * outDisk = FITS directory number * err = Python Obit Error...
625941cd44b2445a33932195
def winning_move(self): <NEW_LINE> <INDENT> return self._end_game(self.mark, self.opponent_mark)
If the bot has two in a row, it can place a third to get three in a row.
625941cd82261d6c526ab59e
def load_extracted_glossary(glossary_file, locale): <NEW_LINE> <INDENT> result = defaultdict(GlossaryEntry) <NEW_LINE> counter = 0 <NEW_LINE> term_index = 0 <NEW_LINE> for row in read_csv_file(glossary_file): <NEW_LINE> <INDENT> if counter == 0: <NEW_LINE> <INDENT> colum_counter = 0 <NEW_LINE> for header in row: <NEW_L...
Build a defaultdict(GlossaryEntry) glossary from the given extracted glossary csv file for the given locale, raising an error for entries that have no translation.
625941cd63b5f9789fde71e5
def ir_fuel(self): <NEW_LINE> <INDENT> return self.iFuel
Outer radius of fuel material. :returns: A radial index
625941cdeab8aa0e5d26dc57
def setup(): <NEW_LINE> <INDENT> base.features = base.FeatureBroker()
set up test fixtures
625941cd4a966d76dd55110f
def table_must_exist(self,tableName): <NEW_LINE> <INDENT> if self.db_api_module_name in ["cx_Oracle"]: <NEW_LINE> <INDENT> selectStatement = ("SELECT * FROM all_objects WHERE object_type IN ('TABLE','VIEW') AND owner = SYS_CONTEXT('USERENV', 'SESSION_USER') AND object_name = UPPER('%s')" % tableName) <NEW_LINE> <DEDENT...
Check if the table given exists in the database. For example, given we have a table `person` in a database When you do the following: | Table Must Exist | person | Then you will get the following: | Table Must Exist | person | # PASS | | Table Must Exist | first_name | # FAIL |
625941cd7d43ff24873a2d9f
def get_from_cache(unique_identifier): <NEW_LINE> <INDENT> ensure_context() <NEW_LINE> context = get_context() <NEW_LINE> if not CACHE_ENABLED: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ret = None <NEW_LINE> if context.context_enabled: <NEW_LINE> <INDENT> ret = context.stack.top.get_entity(unique_identifier) ...
Return an entity from the context cache, falling back to memcache when possible
625941cd7d847024c06be3bb
def _ends_with_vowel(self, letter_group: str) -> bool: <NEW_LINE> <INDENT> if len(letter_group) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._contains_vowels(letter_group[-1])
Check if a string ends with a vowel.
625941cda17c0f6771cbe150
def cmd_clone(self, selector): <NEW_LINE> <INDENT> if len(selector) == 0: <NEW_LINE> <INDENT> selector = ["all"] <NEW_LINE> <DEDENT> repos = self._select(selector[0]) <NEW_LINE> for repo in repos: <NEW_LINE> <INDENT> directory = os.path.dirname(repo.local_url) <NEW_LINE> if not os.path.exists(directory): <NEW_LINE> <IN...
[selector] - clones all matching repos
625941cd796e427e537b06c5
def create_export(self, vid, name=None, passwd=None, squota="", hquota=""): <NEW_LINE> <INDENT> enode = self._get_exportd_node() <NEW_LINE> econfig = enode.get_configurations(Role.EXPORTD) <NEW_LINE> if econfig is None: <NEW_LINE> <INDENT> raise Exception("%s is not reachable" % enode._host) <NEW_LINE> <DEDENT> if vid ...
Export a new file system Args: vid: the volume id to use the file system relies on
625941cdd7e4931a7ee9e01d
def get_tbl_data(filename,comment='|'): <NEW_LINE> <INDENT> f = open(filename) <NEW_LINE> lines = f.readlines() <NEW_LINE> tbl = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if line[0] != comment: <NEW_LINE> <INDENT> strarr = str.split(line) <NEW_LINE> if len(strarr) > 0: <NEW_LINE> <INDENT> tbl.append(strarr) ...
Reads data from a table into a numpy array.
625941cdcb5e8a47e48b7baa
def get_dates(self): <NEW_LINE> <INDENT> return list(set(self.get_person_dates() + self.get_text_dates()))
Returns a list of all sort dates associated with this Text.
625941cd26238365f5f0ef6d
def test_sport_type_value(self): <NEW_LINE> <INDENT> buffer = copy(self.entity1) <NEW_LINE> buffer.sport_type = "9" <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> buffer.save() <NEW_LINE> <DEDENT> transaction.rollback()
Tests CHECK constraint of sport_type.
625941cd7b180e01f3dc48fc
def _continue_topic(self, from_node=None): <NEW_LINE> <INDENT> messages = [] <NEW_LINE> if from_node is not None: <NEW_LINE> <INDENT> self.conversation.set_current_node(from_node) <NEW_LINE> <DEDENT> node = from_node or self.conversation.current_node() <NEW_LINE> while node is not None: <NEW_LINE> <INDENT> if isinstanc...
Iterate the piece of conversation under the same label. Return the list of messages found during iteration. If specified, iteration starts from the from_node Node.
625941cda219f33f34628a69
def datespan(start_date, end_date, delta=timedelta(days=1)): <NEW_LINE> <INDENT> current_date = start_date <NEW_LINE> while current_date < end_date: <NEW_LINE> <INDENT> yield current_date <NEW_LINE> current_date += delta
Iterates over each day comprised in the datespan. Parameters ---------- start_date: date The first day to be returned. end_date: date The day after the last one that should be returned. delta: timedelta The step of the generator. Returns ------- date The currently yelded date.
625941cdcc0a2c11143dcf90
def select_action(self, legal_action_arr, qs, train_mode): <NEW_LINE> <INDENT> if train_mode: <NEW_LINE> <INDENT> self.epsilon = self.epsilon <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.epsilon = 0 <NEW_LINE> <DEDENT> legal_action_list = list(evolution.all_legal_actions) <NEW_LINE> qs_list = qs.tolist() <NEW_LI...
Args: legal_action_arr which is a list Returns: action in the form of a str
625941cd4e696a04525c954b
def pre_optim_step(self, optim_data: OptimData, frame_indexes): <NEW_LINE> <INDENT> self.prev_latitude = optim_data.bboxes[frame_indexes[0]].z <NEW_LINE> cur_bbox = optim_data.bboxes[frame_indexes[1]] <NEW_LINE> terrain = optim_data.terrain <NEW_LINE> self.cur_ground_latitude = utils.get_latitude(cur_bbox, terrain, sel...
set the newest previous latitude, so that we can compute the loss w.r.t motion
625941cde5267d203edcdd9d
def getEditChoices(self, currentText=''): <NEW_LINE> <INDENT> format = globalref.options.strData('EditTimeFormat', True) <NEW_LINE> now = GenTime().timeStr(format) <NEW_LINE> choices = [(now, '(%s)' % _('now'))] <NEW_LINE> for hr in (6, 9, 12, 15, 18, 21, 0): <NEW_LINE> <INDENT> time = GenTime((hr, 0)).timeStr(format) ...
Return list of choices for combo box, each a tuple of edit text and annotated text
625941cd56ac1b37e62642cf
def plot_influence_components(influences, labels, plot_pdf): <NEW_LINE> <INDENT> classes = np.sort(np.unique(labels)) <NEW_LINE> if len(classes) > 10: <NEW_LINE> <INDENT> raise Exception("Not more than 10 distinct classes allowed for influence components " "plot, but given %d." % len(classes)) <NEW_LINE> <DEDENT> def_c...
Generates three scatter plots, comparing influence values of modified versions of IF I_{up,loss}. :param influences: Contains four vectors of influence values: - influence values with train loss & Hessian - influence values without Hessian - # influence values without train loss - # influence values without train ...
625941cd26068e7796caedde
def plot_bz2d (ax, bz, repeat=(1, 1), kvec=None, rotation=0, labels=None, color=(.2, .7, .7, .7)): <NEW_LINE> <INDENT> kspace = [] <NEW_LINE> if not hasattr (repeat, "__len__"): <NEW_LINE> <INDENT> repeat = (int(repeat), int(repeat)) <NEW_LINE> <DEDENT> if kvec is None: <NEW_LINE> <INDENT> kvec = [(0,0), (0,0)] <NEW_LI...
Plots the Brollouin Zone (BZ) projection specified by points *bz* as a line onto axis *ax*, rotated by *rotation* degrees. If *kvec* is not None, it is expected to be a list of (x,y) tuples representing the projections of the *kvec* vectors by which to repeat the BZ *repeat* times in each direction.
625941cd5f7d997b87174b97
def wait_job_done(): <NEW_LINE> <INDENT> if utils_misc.wait_for(lambda: not vm.monitor.query_block_job(device_id), timeout=int(params.get("job_timeout", 3600)), text="Wait for canceling block job") is None: <NEW_LINE> <INDENT> raise error.TestFail("Wait job finish timeout")
Wait for job on the device done, raise TestFail exception if timeout;
625941cd4f88993c3716c167
def failoversources(sources): <NEW_LINE> <INDENT> for source in sources: <NEW_LINE> <INDENT> if source is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if source.startswith("ftp:") or (source.startswith("http") and ":" in source): <NEW_LINE> <INDENT> stat, stdout, stderr = mycmd("curl -i -I --keepalive-time 5 ...
try a list of locations where a file could be, one after the other
625941cd91f36d47f21ac5f2
def test_freq_choices(self): <NEW_LINE> <INDENT> bc = BaseClient() <NEW_LINE> self.assertEqual('1hr', bc.FREQUENCY_CHOICES.hourly) <NEW_LINE> self.assertEqual('5m', bc.FREQUENCY_CHOICES.fivemin) <NEW_LINE> self.assertEqual('10m', bc.FREQUENCY_CHOICES.tenmin) <NEW_LINE> self.assertEqual('n/a', bc.FREQUENCY_CHOICES.na)
Frequency choices have expected values.
625941cd0fa83653e46570bb
def base64(self, image): <NEW_LINE> <INDENT> req_url = '/vision/predict' <NEW_LINE> fields = { 'modelId': st.EINSTEIN_VISION_MODELID, 'sampleBase64Content': image, } <NEW_LINE> return self.post_requests(req_url, fields)
Prediction with Image Base64 String
625941cd63f4b57ef0001219
def remaining_active_supporters_with_capacity(self): <NEW_LINE> <INDENT> return len(self._active_supporters) != 0 and self._active_supporters[0].available_slots() > 0
@return: Boolean value, indicating whether we have at least one active supporter that still has available slots
625941cd26238365f5f0ef6e
def permute(self, nums): <NEW_LINE> <INDENT> def permute_iter(n): <NEW_LINE> <INDENT> if n: <NEW_LINE> <INDENT> last = permute_iter(n-1) <NEW_LINE> p = nums[n] <NEW_LINE> new = [] <NEW_LINE> for item in last: <NEW_LINE> <INDENT> for i in range(n+1): <NEW_LINE> <INDENT> d = deepcopy(item) <NEW_LINE> d.insert(i, p) <NEW_...
:type nums: List[int] :rtype: List[List[int]]
625941cdbe7bc26dc91cd700
def test_xpub_to_addresses(): <NEW_LINE> <INDENT> xpub = 'xpub68V4ZQQ62mea7ZUKn2urQu47Bdn2Wr7SxrBxBDDwE3kjytj361YBGSKDT4WoBrE5htrSB8eAMe59NPnKrcAbiv2veN5GQUmfdjRddD1Hxrk' <NEW_LINE> root = HDKey.from_xpub(xpub=xpub, path='m') <NEW_LINE> expected_addresses = [ '1LZypJUwJJRdfdndwvDmtAjrVYaHko136r', '1MKSdDCtBSXiE49vik8xU...
Test vectors from here: https://iancoleman.io/bip39/
625941cd167d2b6e31218c96
def __plotMelodicICsChanged(self, *a): <NEW_LINE> <INDENT> self.refreshDataSeriesWidgets()
Called when the :attr:`.TimeSeriesPanel.plotMelodicICs` property changes. If the current overlay is a :class:`.MelodicImage`, re-generates the widgets in the *current time course* section, as the :class:`.DataSeries` instance associated with the overlay may have been re-created.
625941cd1d351010ab855c1b
def is_degree_of_collaboration_shared(): <NEW_LINE> <INDENT> return
In Shared ID, Boden designates, different aspects of a complex problem are tackled by different groups. They possess complementary skills, communicate results, and monitor overall progress. Yet, daily cooperation does not necessarily occur
625941cd099cdd3c635f0d5b
def sysctl(name, is_string=True): <NEW_LINE> <INDENT> size = c_uint(0) <NEW_LINE> libc = CDLL(find_library('c')) <NEW_LINE> libc.sysctlbyname(name, None, byref(size), None, 0) <NEW_LINE> buf = create_string_buffer(size.value) <NEW_LINE> libc.sysctlbyname(name, buf, byref(size), None, 0) <NEW_LINE> if is_string: <NEW_LI...
Wrapper for sysctl so we don't have to use subprocess
625941cd30bbd722463cbec6