code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@register.inclusion_tag("admin/change_list_results.html") <NEW_LINE> def folderless_result_list(cl): <NEW_LINE> <INDENT> context = result_list(cl) <NEW_LINE> for row_no, row in enumerate(context['results']): <NEW_LINE> <INDENT> for cell_no, cell in enumerate(row): <NEW_LINE> <INDENT> context['results'][row_no][cell_no]... | Displays the headers and data list together | 625941f63346ee7daa2b33cc |
def cast(*args): <NEW_LINE> <INDENT> return _itkRescaleIntensityImageFilterPython.itkRescaleIntensityImageFilterID2IUL2_cast(*args) | cast(itkLightObject obj) -> itkRescaleIntensityImageFilterID2IUL2 | 625941f6099cdd3c635f12b1 |
def get_last(self, key): <NEW_LINE> <INDENT> return self[key].last | Will return the last EclSumNode corresponding to @key.
If you are only interested in the final value, you can use the
last_value() method. | 625941f6b545ff76a891446f |
def generate(self): <NEW_LINE> <INDENT> grid = np.empty((self.H, self.W), dtype=np.int8) <NEW_LINE> grid.fill(1) <NEW_LINE> if self.maze_type == SERPENTINE: <NEW_LINE> <INDENT> return self._generate_serpentine_maze(grid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._generate_spiral_maze(grid) | highest-level method that implements the maze-generating algorithm
Returns:
np.array: returned matrix | 625941f64d74a7450ccd4820 |
def set_predec_weightmat(self, weightmat): <NEW_LINE> <INDENT> wmflat = weightmat.flat <NEW_LINE> pdflat = self.pre_dec.flat <NEW_LINE> for i,w in enumerate(wmflat): <NEW_LINE> <INDENT> if numpy.isnan(w): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pdflat[i].setWeights(w) | set the weights in the predec connections according to the weightmat. | 625941f676d4e153a657f18c |
def command_ingest(self,command_str): <NEW_LINE> <INDENT> command = EmulatorCommand(command_str) <NEW_LINE> if re.search('^renumb.',command.command): <NEW_LINE> <INDENT> command_new = list(command.command) <NEW_LINE> char_new = ord(command_new[7]) <NEW_LINE> char_new = 0x80 if char_new == 0x72 ... | We've received a command. We'll forward all commands except
for the renumber command where we'll do something tricky. | 625941f60383005118ecfc3a |
def propose_item_budget(self, auction_item: str, auction_round: int) -> float: <NEW_LINE> <INDENT> raise NotImplementedError("Must be implemented by student") | Function called during the auction phase, when the owner agent has to announce a new price for a new
auction round.
:param auction_item:
:param auction_round:
:return: | 625941f6566aa707497f4bb9 |
def nearest_neighbor_tour(tsp): <NEW_LINE> <INDENT> nearest_neighbor_path = [1] <NEW_LINE> current_city = 1 <NEW_LINE> cities_to_travel = set(range(2, tsp["DIMENSION"] + 1)) <NEW_LINE> while cities_to_travel: <NEW_LINE> <INDENT> current_city = nearest_neighbor(tsp,cities_to_travel,current_city) <NEW_LINE>... | Construct a tour through all cities in a TSP by following the nearest
neighbor heuristic | 625941f63c8af77a43ae3e02 |
def deactivate_action(self, request, objects): <NEW_LINE> <INDENT> for obj in objects.all(): <NEW_LINE> <INDENT> obj.is_active = False <NEW_LINE> obj.save() | Deactivate selected entries. | 625941f6ad47b63b2c50a5da |
def replace_all(self, replacements, serializing): <NEW_LINE> <INDENT> for placeholder in replacements: <NEW_LINE> <INDENT> self.replace(*placeholder.unpack(serializing)) | Easy way to accept all placeholders registered. | 625941f6a8370b7717052ef7 |
def test_negative_resolution(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, swarm_denovo_cluster, seq_path=self.file_read_seqs, d=-2, threads=1) | Swarm should raise a ValueError if the resolution
is negative | 625941f6be7bc26dc91cdc4e |
def print_first_and_last(sentence): <NEW_LINE> <INDENT> words = break_words(sentence) <NEW_LINE> print_first_word(words) <NEW_LINE> print_last_word(words) | Prints the first and last words of the sentence.
打印句子的第一个和最后一个单词 | 625941f6507cdc57c6307345 |
def setup(self): <NEW_LINE> <INDENT> look = self.TurnToGoal() .set_name("look") .set_parent(self) <NEW_LINE> lookaroundinplace1 = LookAroundInPlace(stop_on_exit=False) .set_name("lookaroundinplace1") .set_parent(self) <NEW_LINE> stopbehavior2 = StopBehavior() .set_name("stopbehavior2") .set_parent(self) <NEW_LINE> thin... | look: self.TurnToGoal() =C=> LookAroundInPlace(stop_on_exit=False) =T(5)=> StopBehavior() =C=> think
think: self.Think()
think =S=> go
think =F=> end
go: self.Go() =C=> look
end: self.Fin() =C=> ParentCompletes() | 625941f6fff4ab517eb2fa9b |
def get_all_node_list(self): <NEW_LINE> <INDENT> select_list = ["node_name", "node_domain", "node_region", "node_usernumber"] <NEW_LINE> return self.db.select({}, select_list) | 获取所有的节点信息 | 625941f6d8ef3951e3243b98 |
def current_part(): <NEW_LINE> <INDENT> name = thread_name() <NEW_LINE> if name in oa.util.legacy.hub.parts: <NEW_LINE> <INDENT> return oa.util.legacy.hub.parts[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> err = '%s Error: Cannot find a related part' %name <NEW_LINE> _logger.error(err) <NEW_LINE> raise Exception... | Return the part name which is associated with the current thread. | 625941f66e29344779a62c6c |
def _string_data(self, data): <NEW_LINE> <INDENT> reply = '' <NEW_LINE> for x in data: <NEW_LINE> <INDENT> reply_data = x <NEW_LINE> if reply_data: <NEW_LINE> <INDENT> reply += chr(reply_data) <NEW_LINE> <DEDENT> <DEDENT> print(reply) | This is a private message handler method.
It is the message handler for String data messages that will be
printed to the console.
:param data: message | 625941f6d18da76e23532b39 |
def GetRegions(self, *args): <NEW_LINE> <INDENT> return self.send({'cmd': 'GetRegions', 'args': args}) | Get information about one or more regions
call:
rarr = GetRegions(regions)
where:
- regions: which regions to retrieve
returns:
- rarr: array of region objects
Each returned region object contains the following properties:
- id: numeric region id (assigned by JS9 automatically)
- mode: 'add', 'remove' or '... | 625941f6b7558d58953c5560 |
def save_bindata(absolute_pathname, data): <NEW_LINE> <INDENT> out = open(absolute_pathname, 'wb') <NEW_LINE> out.write(data) <NEW_LINE> out.close() | 絶対パスにバイナリデータを保存 | 625941f667a9b606de4a8510 |
def rmsprop(x, dx, config=None): <NEW_LINE> <INDENT> if config is None: config = {} <NEW_LINE> config.setdefault('learning_rate', 1e-2) <NEW_LINE> config.setdefault('decay_rate', 0.99) <NEW_LINE> config.setdefault('epsilon', 1e-8) <NEW_LINE> config.setdefault('cache', np.zeros_like(x)) <NEW_LINE> next_x = None <NEW_LIN... | Uses the RMSProp update rule, which uses a moving average of squared
gradient values to set adaptive per-parameter learning rates.
config format:
- learning_rate: Scalar learning rate.
- decay_rate: Scalar between 0 and 1 giving the decay rate for the squared
gradient cache.
- epsilon: Small scalar used for smoothin... | 625941f64f88993c3716c6ba |
def copy_cols_from_mat_(self, M): <NEW_LINE> <INDENT> if self.dim != M.num_rows * M.num_cols: <NEW_LINE> <INDENT> raise ValueError("The number of elements of the input matrix ({}) " "should match the size of the vector ({})." .format(M.num_rows * M.num_cols, self.dim)) <NEW_LINE> <DEDENT> _kaldi_vector_ext._copy_cols_f... | Copies the elements from a matrix column-by-columm.
Args:
M (Matrix): The input matrix.
Raises:
ValueError: In case of size mismatch. | 625941f68a43f66fc4b546b8 |
def __eq__(self, other): <NEW_LINE> <INDENT> return self.type == other.type and self.value == other.value | Returns True if the types and values are the same. | 625941f656b00c62f0f14cb8 |
def choose_action(self, state, actions): <NEW_LINE> <INDENT> current_state = state <NEW_LINE> if random.random() < self.epsilon: <NEW_LINE> <INDENT> chosen_action = random.choice(actions) <NEW_LINE> return chosen_action <NEW_LINE> <DEDENT> qs = [self.getQ(current_state, a) for a in actions] <NEW_LINE> maxQ = max(qs) <N... | Return an action based on the best move recommendation by the current
Q-Table with a epsilon chance of trying out a new move | 625941f696565a6dacc8fd23 |
def segmentation_rgb(self, image, k = 2): <NEW_LINE> <INDENT> centroids = [] <NEW_LINE> clusters = {} <NEW_LINE> i=1 <NEW_LINE> while(len(centroids)!=k): <NEW_LINE> <INDENT> cent = image[np.random.randint(0, image.shape[0]), np.random.randint(0, image.shape[1])] <NEW_LINE> if(len(centroids)>=1): <NEW_LINE> <INDENT> if(... | Performs segmentation of a color input image using KMeans algorithm, using the intensity of the pixels (R, G, B)
as features
takes as input:
image: a color image
return an segemented image | 625941f6046cf37aa974d39b |
def copy_to(self, other): <NEW_LINE> <INDENT> ok = _api.ValueCopy(other, self) <NEW_LINE> self._throw_if(ok) <NEW_LINE> return self | Copy value to external SCITER_VALUE. | 625941f6a8ecb033257d3725 |
self.token.status_post(post, media_ids = media) <NEW_LINE> def wkati(): <NEW_LINE> <INDENT> m = MeCab.Tagger("-d /usr/lib/mecab/dic/mecab-ipadic-neologd") <NEW_LINE> words = "" <NEW_LINE> norns = ["サ変接続", "ナイ形容詞語幹", "一般", "引用文字列", "形容動詞語幹", "固有名詞", "接続詞的", "接尾", "動詞非自立的", "特殊", "副詞可能"] <NEW_LINE> adjectives = ["自立", "非... | 取得したtootのcontent類に分かち書きを行う。
必要な品詞だけ使用し、品詞よっては単語の原型を使用する。 | 625941f6d10714528d600346 |
def get_chembl_protein_equivalences(version: Optional[str] = None) -> pd.DataFrame: <NEW_LINE> <INDENT> if version is None: <NEW_LINE> <INDENT> version = bioversions.get_version("chembl") <NEW_LINE> <DEDENT> url = f"ftp://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/releases/chembl_{version}/chembl_uniprot_mapping.txt" ... | Get ChEMBL protein equivalences. | 625941f6d6c5a102081446ab |
def p_c_literal1(p): <NEW_LINE> <INDENT> leaf1 = create_children("LF_Charliteral", p[1]) <NEW_LINE> if(p[1] == 'True' or p[1] == 'False'): <NEW_LINE> <INDENT> temp_type = 'Boolean' <NEW_LINE> temp = newtemp() <NEW_LINE> tac1 = ['=,' + temp + ',' + p[1]] <NEW_LINE> <DEDENT> elif(p[1] == 'null'): <NEW_LINE> <INDENT> temp... | c_literal : TOK_string
| KW_true
| KW_false
| KW_null | 625941f607d97122c4178ef6 |
def CookieAuth(stream, user, cookie): <NEW_LINE> <INDENT> r = stream.GetResponse() <NEW_LINE> stream.log.debug("SEND: AUTH COOKIE %s %s" % (user, cookie)) <NEW_LINE> stream.Write("AUTH COOKIE %s %s" % (user, cookie), nolog=1) <NEW_LINE> r = stream.GetResponse() <NEW_LINE> if r.code == 1000: <NEW_LINE> <INDENT> return T... | Authenticate against a Store connection with a user cookie on socket s | 625941f6ff9c53063f47c84a |
def _player_to_dto(player: Player): <NEW_LINE> <INDENT> player_dto = {ID: player.identifier, MAZE_CARD_ID: player.piece.maze_card.identifier, SCORE: player.score, PIECE_INDEX: player.piece.piece_index, PLAYER_NAME: player.player_name} <NEW_LINE> if type(player) is bots.Bot: <NEW_LINE> <INDENT> player_dto[IS_BOT] = True... | Maps a player to a DTO
:param piece: an instance of model.Piece
:return: a structure whose JSON representation is valid for the API | 625941f626238365f5f0f4d1 |
def sitemap_file(path): <NEW_LINE> <INDENT> if path.endswith('.xml.gz'): <NEW_LINE> <INDENT> mime = 'application/x-gzip' <NEW_LINE> <DEDENT> elif path.endswith('.xml'): <NEW_LINE> <INDENT> mime = 'text/xml' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise HTTPError(http.NOT_FOUND) <NEW_LINE> <DEDENT> return send_fro... | Serves the sitemap/* files. | 625941f691af0d3eaac9c078 |
def test_article_reader_content_caching(self): <NEW_LINE> <INDENT> settings = self._get_cache_enabled_settings() <NEW_LINE> settings['READERS'] = {'asc': None} <NEW_LINE> context = get_context(settings) <NEW_LINE> generator = ArticlesGenerator( context=context.copy(), settings=settings, path=CONTENT_DIR, theme=settings... | Test raw article content caching at the reader level | 625941f6adb09d7d5db6cde6 |
def testStandardApiBase(self): <NEW_LINE> <INDENT> key = self.key_prefix + "StandardApi.Base" <NEW_LINE> self.to_delete.append(key) <NEW_LINE> data = "proba" <NEW_LINE> put(key, data, 0, None, False) <NEW_LINE> gdata = get(key, False) <NEW_LINE> self.assertEqual(data, gdata, u"Blad zwracanych danych z memoize: %s != %s... | Test dla funkcji put i get bez zadnych dodatkowych ustawien
| 625941f6dd821e528d63b7fe |
def draw(self, surface): <NEW_LINE> <INDENT> self.visible = True <NEW_LINE> if self.focus : <NEW_LINE> <INDENT> surface.blit(self.image_ovr, self.rect) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> surface.blit(self.image, self.rect) <NEW_LINE> <DEDENT> surface.blit(self.label, self.label_pos) | Draw the button to a surface | 625941f68e71fb1e9831de01 |
@transform(dominantVariants, regex(r"variants/(\S+).dominant.vcf"), r"variants/\1.dominant.table") <NEW_LINE> def tabulateDoms(infile, outfile): <NEW_LINE> <INDENT> genome = PARAMS["gatk_genome"] <NEW_LINE> columns = PARAMS["gatk_vcf_to_table"] <NEW_LINE> PipelineExome.vcfToTable(infile, outfile, genome, columns) | Tabulate dominant disease candidate variants | 625941f6aad79263cf3910a6 |
def deep_copy(mylist,index=0,newlist=[]): <NEW_LINE> <INDENT> if(index == len(mylist)): <NEW_LINE> <INDENT> return newlist <NEW_LINE> <DEDENT> if( type(mylist[index])==list ): <NEW_LINE> <INDENT> newlist.append(deep_copy(mylist[index],0,[])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newlist.append(mylist[index]) <N... | print("
coming inside")
print("mylis is ",mylist," and index : ",index)
print("current newlist is :",newlist)
| 625941f699cbb53fe679323f |
def test_propertygraph(): <NEW_LINE> <INDENT> g = PropertyGraph() <NEW_LINE> vid1 = g.add_vertex() <NEW_LINE> vid2 = g.add_vertex() <NEW_LINE> eid = g.add_edge((vid1, vid2)) <NEW_LINE> g.add_vertex_property("vtest") <NEW_LINE> assert len(list(g.vertex_property_names()))==1 <NEW_LINE> assert "vtest" in list(g.vertex_pro... | Test property graph | 625941f69f2886367277aee2 |
def lambda_handler(event, context): <NEW_LINE> <INDENT> if DEBUG_FLAG is True: <NEW_LINE> <INDENT> print("Time remaining (MS):", context.get_remaining_time_in_millis()) <NEW_LINE> <DEDENT> if "invokingEvent" in event: <NEW_LINE> <INDENT> invoking_event = json.loads(event["invokingEvent"]) <NEW_LINE> <DEDENT> else: <NEW... | Main. | 625941f6ec188e330fd5adeb |
def getStringSize(self, s, scale=DEFAULT_SCALE): <NEW_LINE> <INDENT> scale *= self.scale <NEW_LINE> try: <NEW_LINE> <INDENT> t, w, h = self.stringsCache.get(s) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> w, h = self.font.size(s) <NEW_LINE> <DEDENT> return (w * scale * self.aspectRatioFactor, h * scale) | Get the dimensions of a string when rendered with this font.
:param s: String
:param scale: Scale factor
:return: (width, height) tuple | 625941f65166f23b2e1a57b4 |
def __init__(self, model_type, model_fullpath=None, model_group=None, model_subset=None, model_args={}): <NEW_LINE> <INDENT> self.model_type = model_type <NEW_LINE> if self.model_type == 'word2vec': <NEW_LINE> <INDENT> if model_fullpath is None or re.search('GoogleNews-vectors-negative300.bin', model_fullpath): <NEW_LI... | initialize a model from a saved object file | 625941f616aa5153ce362ad4 |
def test_stack_of_multiple_pop(test_stack): <NEW_LINE> <INDENT> test_stack[2].pop() <NEW_LINE> assert test_stack[2]._stack.head.data is 4 | Test can pop on an stack of multiple. | 625941f64e696a04525c9aa9 |
def nmom(filename): <NEW_LINE> <INDENT> return nmom_arr(mom(filename)) | Get number of momenta from filename | 625941f6cad5886f8bd27633 |
def drodriguez(r): <NEW_LINE> <INDENT> theta = np.linalg.norm(r, 2) <NEW_LINE> if theta < 1e-15: <NEW_LINE> <INDENT> return np.random.randn(3, 3, 3)*1e-1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> k = r / theta <NEW_LINE> <DEDENT> sint = np.sin(theta) <NEW_LINE> cost = np.cos(theta) <NEW_LINE> """ w.r.t. theta and k... | Compute derivative of rodrigues rotation operator
Paramter:
---------
r: a 3d vector. theta = np.linalg.norm(r, 2) represent the angle.
k=r/theta represent the rotation axis.
Return:
-------
A: a matrix of shape [3, 3, 3].
A[:, :, i] = d rodriguez(r) / dr(i) | 625941f6236d856c2ad44e3f |
def test_rc(self): <NEW_LINE> <INDENT> self.assertEqual(self.RNA('UauCG-NR').rc(), 'YN-CGAUA') <NEW_LINE> self.assertEqual(self.DNA('TatCG-NR').rc(), 'YN-CGATA') <NEW_LINE> self.assertEqual(self.RNA('').rc(), '') <NEW_LINE> self.assertEqual(self.RNA('A').rc(), 'U') <NEW_LINE> self.assertRaises(TypeError, self.PROT('ACD... | Sequence rc should correctly reverse-complement sequence | 625941f6462c4b4f79d1dd2a |
def crosshair(self, cv_image): <NEW_LINE> <INDENT> cv2.line(cv_image, (self.tag_x, self.tag_y + 25),(self.tag_x, self.tag_y - 25),(255,255,0),2) <NEW_LINE> cv2.line(cv_image, (self.tag_x - 25, self.tag_y),(self.tag_x + 25, self.tag_y),(255,255,0),2) <NEW_LINE> cv2.circle(cv_image, (self.tag_x, self.tag_y), 10, ... | Draws a crosshair over the center of the bounding of the tag | 625941f6d4950a0f3b08c9a0 |
def get_one_piece_movable(self, x, y): <NEW_LINE> <INDENT> movable = [] <NEW_LINE> if self.out_of_bound(x, y) or self.get_piece(x,y) is ' ': <NEW_LINE> <INDENT> print("not valid coordinate") <NEW_LINE> raise Exception('coordinate not in range') <NEW_LINE> <DEDENT> if self.is_initial(): <NEW_LINE> <INDENT> if (x, y) == ... | get all the move of one piece given the coordinate of that piece
:parameter
x : x coordinate of the piece
y : y coodinate of the piece
:return
the set of all possible move for this piece | 625941f682261d6c526abb04 |
def register_for_kwarg(self, plugin, kwarg=None): <NEW_LINE> <INDENT> if kwarg is not None: <NEW_LINE> <INDENT> self.register(plugin) | Register a plugin for a plugin for a kwarg argument | 625941f65fcc89381b1e1d20 |
def _make_T(self, S: list, K: list, a: dict) -> np.array: <NEW_LINE> <INDENT> T_a = {} <NEW_LINE> for (theta_t_plus_one, (theta_t, action), probability) in self.state_transition: <NEW_LINE> <INDENT> theta_t_index = S.index(theta_t) <NEW_LINE> theta_t_plus_one_index = S.index(theta_t_plus_one) <NEW_LINE> if action not i... | Compute the conditional probability of state transition in POMDP.
T is an len(`S`)*len(`K`) x len(`S`)*len(`K`) dimensional block diagonal matrix of len(`K`) x len(`K`) blocks,
with T_a(k) as the kth diagonal sub-matrix. T_a(k) is the transition probability matrix when selecting action a(k).
Args:
S (list[str]): ... | 625941f696565a6dacc8fd24 |
def deactivate(self): <NEW_LINE> <INDENT> if self.current_pollers: <NEW_LINE> <INDENT> logging.debug('You still have active pollers at deactivation stage, I cleaned them up for you.') <NEW_LINE> self.current_pollers = [] <NEW_LINE> for timer in self.current_timers: <NEW_LINE> <INDENT> timer.cancel() <NEW_LINE> <DEDENT>... | Override if you want to do something at tear down phase (don't forget to super(Gnagna, self).deactivate()) | 625941f623849d37ff7b36e5 |
def testIssue314(self): <NEW_LINE> <INDENT> cleared = [] <NEW_LINE> class SelfReferencer: <NEW_LINE> <INDENT> def __del__(self): <NEW_LINE> <INDENT> cleared.append(id(self)) <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.db = apsw.Connection("") <NEW_LINE> self.db.setbusyhandler(self.refme) <NEW_LINE>... | Reference cycles between instance, Connection and instance.method | 625941f67d847024c06be91d |
def read_data(self, select_validation_percentage, select_test_percentage, works_per_composer, pace_events): <NEW_LINE> <INDENT> print('num genres:{}'.format(len(self.genres))) <NEW_LINE> ohe = LabelBinarizer() <NEW_LINE> ohe.fit(self.genres) <NEW_LINE> self.songs = {} <NEW_LINE> self.songs['validation'] = [] <NEW_LINE>... | read_data takes a datadir with genre subdirs, and composer subsubdirs
containing midi files, reads them into training data for an rnn-gan model.
Midi music information will be real-valued frequencies of the
tones, and intensity taken from the velocity information in
the midi files.
returns a list of tuples, [genre, co... | 625941f6e64d504609d74e9b |
def get_raw_data(self): <NEW_LINE> <INDENT> return self.data | Returns after data as numpy array | 625941f623e79379d52eebb6 |
def load_data(file_path): <NEW_LINE> <INDENT> f = open(file_path) <NEW_LINE> feature = [] <NEW_LINE> for line in f.readlines(): <NEW_LINE> <INDENT> feature_tmp = [] <NEW_LINE> lines = line.strip().split("\t") <NEW_LINE> feature_tmp.append(1) <NEW_LINE> for i in range(len(lines)): <NEW_LINE> <INDENT> feature_tmp.append(... | 导入测试数据
input: file_path(string):训练数据
output: feature(mat):特征 | 625941f61d351010ab856175 |
def convert_log_time_str_to_datetime(log_time_str): <NEW_LINE> <INDENT> import datetime <NEW_LINE> return datetime.datetime.strptime(log_time_str, "%Y-%m-%d %H:%M:%S%z") | Convert a log time string to a datetime object.
Args:
log_time_str (str): String format of the DateTime() object to be used in HDF5 files
Returns:
datetime_obj (DateTime()): Python DateTime() object | 625941f6de87d2750b8603f5 |
def find_min_swaps_to_sort_slightly_optimized(arr): <NEW_LINE> <INDENT> start = 1 <NEW_LINE> end = len(arr) <NEW_LINE> hmap = {} <NEW_LINE> for i, val in enumerate(arr): <NEW_LINE> <INDENT> hmap[val] = i <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> while start <= end: <NEW_LINE> <INDENT> if arr[start - 1] != start: <NEW_LINE> ... | This solution TLE'ed - we need to optimize this | 625941f65510c4643540fa2e |
def getdist_like(modelname, pname): <NEW_LINE> <INDENT> return XYfromdata(np.loadtxt(modelname+'_p_'+pname+'.dat')) | return XYfromdata(np.loadtxt(modelname+'_p_'+pname+'.dat')) | 625941f64428ac0f6e5bae54 |
def on_basic_qos_ok(self, _unused_frame): <NEW_LINE> <INDENT> self.logger.info('QOS set to: %d', self._prefetch_count) <NEW_LINE> self.start_consuming() | Invoked by pika when the Basic.QoS method has completed. At this
point we will start consuming messages by calling start_consuming
which will invoke the needed RPC commands to start the process.
:param pika.frame.Method _unused_frame: The Basic.QosOk response frame | 625941f67b25080760e39ab0 |
def test_CorrelationDistributionDecoder_smoke(testdata_laird, tmp_path_factory): <NEW_LINE> <INDENT> tmpdir = tmp_path_factory.mktemp("test_CorrelationDistributionDecoder") <NEW_LINE> testdata_laird = testdata_laird.copy() <NEW_LINE> features = testdata_laird.get_labels(ids=testdata_laird.ids[0])[:5] <NEW_LINE> decoder... | Smoke test for continuous.CorrelationDistributionDecoder. | 625941f62ae34c7f2600d78b |
def return_entity_collection(self, entities, request, environ, start_response, response_headers): <NEW_LINE> <INDENT> response_type = self.content_negotiation( request, environ, self.FeedTypes) <NEW_LINE> if response_type is None: <NEW_LINE> <INDENT> return self.odata_error( request, environ, start_response, "Not Accep... | Returns an iterable of Entities. | 625941f657b8e32f52483afb |
def parse_object(word_list): <NEW_LINE> <INDENT> skip(word_list, 'stop') <NEW_LINE> next_word = peek(word_list) <NEW_LINE> if next_word == 'noun': <NEW_LINE> <INDENT> return match(word_list, 'noun') <NEW_LINE> <DEDENT> elif next_word == 'direction': <NEW_LINE> <INDENT> return match(word_list, 'direction') <NEW_LINE> <D... | Ah finally, a branching in our parser, such complexity. | 625941f6d99f1b3c44c67bdd |
def add_news(self, news: str) -> None: <NEW_LINE> <INDENT> self.notify_observers(news) | Выпуск очередной новости | 625941f6293b9510aa2c38eb |
def run(self): <NEW_LINE> <INDENT> self._log.info('Starting Pulsar Search Interface') <NEW_LINE> authorizer = DummyAuthorizer() <NEW_LINE> authorizer.add_user(self._config['login']['user'], self._config['login']['psswd'], '.', perm=self._config['login']['perm']) <NEW_LINE> authorizer.add_anonymous(os.getcwd()) <NEW_LIN... | Start the FTP Server for pulsar search. | 625941f601c39578d7e75496 |
def glove2dict(src_filename, dim=300): <NEW_LINE> <INDENT> if '.300d' in src_filename: <NEW_LINE> <INDENT> line_parser = lambda line: line.rsplit(" ", 300) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> line_parser = lambda line: line.strip().split() <NEW_LINE> <DEDENT> data = {} <NEW_LINE> with open(src_filename, encod... | GloVe Reader.
Parameters
----------
dim : int
Full path to the GloVe file to be processed.
Returns
-------
dict
Mapping words to their GloVe vectors as `np.array`. | 625941f6046cf37aa974d39c |
def lookup_extension(typeinfo, default=None): <NEW_LINE> <INDENT> if typeinfo is None and default: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> if isinstance(typeinfo, basestring): <NEW_LINE> <INDENT> return _lookup_extension(typeinfo) <NEW_LINE> <DEDENT> if not hasattr(typeinfo, 'xml_type'): <NEW_LINE> <INDE... | Returns a stix.Entity class for that has been registered for the
`typeinfo` value.
Note:
This is for internal use only.
Args:
typeinfo: An object or string containing type information. This can be
either an xsi:type attribute value or a stix.bindings object.
default: Return class if typeinfo is No... | 625941f6be383301e01b5ad4 |
def smallestValue (dictionary1, dictionary2): <NEW_LINE> <INDENT> min1 = min(dictionary1.values()) <NEW_LINE> min2 = min(dictionary2.values()) <NEW_LINE> return min(min1, min2) | returns the smallest value between both dictionary1 and dictionary2 | 625941f6de87d2750b8603f6 |
def calculate(self, s): <NEW_LINE> <INDENT> s = s.replace(' ','') <NEW_LINE> p = [] <NEW_LINE> i = 0 <NEW_LINE> n = len(s) <NEW_LINE> while i < n: <NEW_LINE> <INDENT> if s[i] == '(': <NEW_LINE> <INDENT> p.append(i) <NEW_LINE> <DEDENT> if s[i] == ')': <NEW_LINE> <INDENT> front = p.pop() <NEW_LINE> a = (self.cal(s[front+... | :type s: str
:rtype: int | 625941f656ac1b37e626481d |
def GetSeason(self): <NEW_LINE> <INDENT> return _mc.ListItem_GetSeason(self) | GetSeason(self) -> int
Returns the season number for tv shows. | 625941f6956e5f7376d714c6 |
def __getitem__(self, user_index): <NEW_LINE> <INDENT> return self.data[user_index] | Get item.
Args:
user_index (int): User index [0, 942]
Returns:
tensor: (items) item's ranking for the user with index user_index | 625941f6a79ad161976cc7a1 |
def inconsistent_effects_mutex(self, node_a1: PgNode_a, node_a2: PgNode_a) -> bool: <NEW_LINE> <INDENT> for effect_add in node_a1.action.effect_add: <NEW_LINE> <INDENT> for effect_rem in node_a2.action.effect_rem: <NEW_LINE> <INDENT> if effect_add == effect_rem: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDE... | Test a pair of actions for inconsistent effects, returning True if
one action negates an effect of the other, and False otherwise.
HINT: The Action instance associated with an action node is accessible
through the PgNode_a.action attribute. See the Action class
documentation for details on accessing the effects and pre... | 625941f6bde94217f3683446 |
def set_return_type(self, return_fractions=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.__dict__['endmember_occupancies'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.return_fractions = return_fractions | Sets the return_type for the polytope object. Also deletes the cached
endmember_occupancies property.
Parameters
----------
return_fractions : boolean (default is False)
Whether the generated polytope object should return fractions or
floats. | 625941f6a934411ee3751cf1 |
def BridgeSettingFlush(): <NEW_LINE> <INDENT> return _x64dbgapi64.BridgeSettingFlush() | BridgeSettingFlush() -> bool | 625941f6e5267d203edce2f0 |
def descendants(self,v): <NEW_LINE> <INDENT> node = self.node(v) <NEW_LINE> for c in node: <NEW_LINE> <INDENT> if len(c) > 0: <NEW_LINE> <INDENT> yield c.label() <NEW_LINE> yield from self.descendants(c.label()) | EXAMPLES::
sage: list(SDecreasingTree(((0,2),{(2,1):1})).descendants(2))
[1]
sage: list(SDecreasingTree(((0,2),{(2,1):1})).descendants(1))
[]
sage: list(SDecreasingTree(((0,2,2),{(3,2):1})).descendants(3))
[1, 2]
sage: list(SDecreasingTree(((0,2,2),{(3,2):1})).descendants(2))
[]
sag... | 625941f61d351010ab856176 |
def test_outputers(): <NEW_LINE> <INDENT> global app <NEW_LINE> global lDB <NEW_LINE> lDB.cleanDB() <NEW_LINE> dConf = { "output" : [ { "engine": "debug", "parameters" : [], "active" : "True" }, { "engine" : "logstash", "parameters" : [ { "server" : "127.0.0.1", "port" : 55514, "transport" : "udp", "fields" : [ { "ES_... | coverage for outputers
| 625941f650812a4eaa59c976 |
def strStr(self, haystack, needle): <NEW_LINE> <INDENT> if needle == "": <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if len(haystack) < len(needle): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> for i in range(len(haystack)-len(needle)+1): <NEW_LINE> <INDENT> num = 0 <NEW_LINE> for j in range(len(needle)): <NE... | :type haystack: str
:type needle: str
:rtype: int | 625941f6c4546d3d9de73096 |
def randomPointAdd(self): <NEW_LINE> <INDENT> return _ndlml.ivm_randomPointAdd(self) | randomPointAdd(ivm self) -> unsigned int | 625941f6287bf620b61d40bb |
def globn(pathname): <NEW_LINE> <INDENT> from glob import glob <NEW_LINE> return sortn(glob(pathname)) | Like glob.glob but try to sort numerically. | 625941f638b623060ff0b448 |
def feature( description: str, dependencies: Set[Union[str, types.ModuleType]] = set(), name: Optional[str] = None) -> Feature: <NEW_LINE> <INDENT> return lambda func: Feature( func, name or func.__name__, description, { d.__name__.rsplit('.', 1)[-1] if isinstance(d, types.ModuleType) else d for d in dependencies}) | A decorator that registers a callable as a feature.
The returned values has the additional attribute ``checker`` which can be
applied as a decorator to a function checking whether the feature already
is installed.
:param description: A description of the feature.
:param dependencies: The names of features on which t... | 625941f6c432627299f052a7 |
def count_sessions(self): <NEW_LINE> <INDENT> return self.session_list.num_rows() | return the number of sessions available in the widget | 625941f667a9b606de4a8511 |
def get_input_number_players(self): <NEW_LINE> <INDENT> user_choice = input(GameView.game_menu()) <NEW_LINE> if user_choice.isdigit(): <NEW_LINE> <INDENT> user_choice = int(user_choice) <NEW_LINE> return self.validate_input_number_of_players(user_choice) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 | Get number of desired players
Query the user for number of desired players [2, 5] | 625941f68c3a873295158a1f |
def get_config(): <NEW_LINE> <INDENT> cfg = VersioneerConfig() <NEW_LINE> cfg.VCS = "git" <NEW_LINE> cfg.style = "pep440" <NEW_LINE> cfg.tag_prefix = "" <NEW_LINE> cfg.parentdir_prefix = "email_archive" <NEW_LINE> cfg.versionfile_source = "email_archive/_version.py" <NEW_LINE> cfg.verbose = False <NEW_LINE> return cfg | Create, populate and return the VersioneerConfig() object. | 625941f607f4c71912b11ae1 |
def predict(self, X): <NEW_LINE> <INDENT> y = super(BaseSVC, self).predict(X) <NEW_LINE> return self.classes_.take(np.asarray(y, dtype=np.intp)) | Perform classification on samples in X.
For an one-class model, +1 or -1 is returned.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
For kernel="precomputed", the expected shape of X is
[n_samples_test, n_samples_train]
Returns
-------
y_pred : array, shape = [n_sample... | 625941f6d53ae8145f87a8be |
def view_meats(): <NEW_LINE> <INDENT> inventory_listbox.delete(0, END) <NEW_LINE> for meat in inventory_mgr._meat: <NEW_LINE> <INDENT> inventory_listbox.insert(END, meat) | view_meats is called when the user clicks the view meats button.
The listbox is emptied of any previous contents, and all of the
meats from the inventory manager object
are inserted. | 625941f6d8ef3951e3243b99 |
def preprocess_switchboard_dataset_step2(dataset_dir_path, result_dir_path, max_duration=100, sample_rate=16000): <NEW_LINE> <INDENT> wav_names = [os.path.splitext(fn)[0] for fn in os.listdir(dataset_dir_path) if fn.endswith(WAV_EXTENSION)] <NEW_LINE> seg_names = [os.path.splitext(fn)[0] for fn in os.listdir(dataset_di... | Trim (slice) the conversations and their corresponding segmentations according
to some max duration set by max_duration (in seconds).
Note:
This should be called after calling 'preprocess_switchboard_dataset_step1' and
'dataset_dir_path' should be the result path of this step. | 625941f6167d2b6e312191f0 |
def verifyPath(fname): <NEW_LINE> <INDENT> if not os.path.isfile(fname): <NEW_LINE> <INDENT> print("Can't find " + fname) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | make sure file exists | 625941f650485f2cf553d3f8 |
@func() <NEW_LINE> def get_dataset(path=None, train=True, name=None, input_size=224, crop_ratio=0.875, jitter_param=0.4, scale_ratio_choice=[], *args, **kwargs): <NEW_LINE> <INDENT> resize = int(math.ceil(input_size / crop_ratio)) <NEW_LINE> transform = generate_transform(train, resize, _is_osx, input_size, jitter_para... | Method to produce image classification dataset for AutoGluon, can either be a
:class:`ImageFolderDataset`, :class:`RecordDataset`, or a
popular dataset already built into AutoGluon ('mnist', 'cifar10', 'cifar100', 'imagenet').
Parameters
----------
name : str, optional
Which built-in dataset to use, will override ... | 625941f6099cdd3c635f12b3 |
def _GetAttributeContainerSchema(self, container_type): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> schema = self._containers_manager.GetSchema(container_type) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> schema = {} <NEW_LINE> <DEDENT> return schema | Retrieves the schema of an attribute container.
Args:
container_type (str): attribute container type.
Returns:
dict[str, str]: attribute container schema or an empty dictionary if
no schema available. | 625941f6d10714528d600347 |
def _validate_challenges(self, domain, auth): <NEW_LINE> <INDENT> for challenge in auth['challenges']: <NEW_LINE> <INDENT> if self.challenge != challenge['type']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> uri = challenge['uri'] if self.version == 1 else challenge['url'] <NEW_LINE> challenge_response = {} <NEW_LI... | Validate the authorization provided in the auth dict. Returns True
when the validation was successful and False when it was not. | 625941f6dd821e528d63b7ff |
def grow(self): <NEW_LINE> <INDENT> world = self.world <NEW_LINE> neighbour_cells = neighbourhood(self.cells) <NEW_LINE> neighbour_cells &= world.free_space() <NEW_LINE> candidates = grid_to_index_tuples(neighbour_cells) <NEW_LINE> if len(candidates) == 0: <NEW_LINE> <INDENT> self.stuck = True <NEW_LINE> return <NEW_LI... | Extend the current area by a random adjacent cell. | 625941f69c8ee82313fbbdd4 |
def test_operation_url_for_internal(): <NEW_LINE> <INDENT> graph = create_object_graph(name="example", testing=True) <NEW_LINE> ns = Namespace(subject="foo") <NEW_LINE> @graph.route(ns.collection_path, Operation.Search, ns) <NEW_LINE> def search_foo(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> with graph.app.test_re... | Operations can resolve themselves via Flask's `url_for` and get internal URIs. | 625941f66fece00bbac2dda3 |
def update_domains(self, problem, assigned): <NEW_LINE> <INDENT> if len(assigned) == 0: <NEW_LINE> <INDENT> assigned = [ v for v in problem.variables if len(problem.variables[v]) == 1 ] <NEW_LINE> <DEDENT> for var1 in assigned: <NEW_LINE> <INDENT> for constraint in problem.var_constr_dict[var1]: <NEW_LINE> <INDENT> for... | we krijgen hier een probleem, waar variabelen al een assignment kunnen hebben. voor bovenstaande voorbeeldsudoku zou het volgende dus gelden:
problem.variables = {
(1,1) : [3]
(1,2) : [9]
(1,3) : [1,2,3,4,5,6,7,8,9]
.
... | 625941f6be7bc26dc91cdc4f |
def make_compat_bytes(in_str): <NEW_LINE> <INDENT> assert isinstance(in_str, str), str(type(in_str)) <NEW_LINE> return in_str.encode() | Converts to bytes, encoding to unicode. | 625941f6b830903b967e9f5f |
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: <NEW_LINE> <INDENT> if token_ids_1 is None: <NEW_LINE> <INDENT> return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] <NEW_LINE> <DEDENT> cls = [self.cls_token_id] <NEW_LINE> sep = [self.... | Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A PhoBERT sequence has the following format:
- single sequence: ``<s> X </s>``
- pair of sequences: ``<s> A </s></s> B </s>``
Args:
token_ids_0 (:obj:`List[int]`):
List of... | 625941f6aad79263cf3910a7 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PageState): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941f6d486a94d0b98e7a3 |
def solveAll(self): <NEW_LINE> <INDENT> print("Solving the whole board...") <NEW_LINE> measureStart("SolveAll") <NEW_LINE> countSidesSet = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> nextMove = self.getNextMove(doSort=False) <NEW_LINE> if nextMove is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> countSidesSet +=... | Solve the whole board. | 625941f6d6c5a102081446ac |
@qgl2decl <NEW_LINE> def t3(): <NEW_LINE> <INDENT> q1 = QRegister('q1') <NEW_LINE> a = 1 <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> a += 1 <NEW_LINE> <DEDENT> if a == 6: <NEW_LINE> <INDENT> X(q1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Y(q1) <NEW_LINE> <DEDENT> print('T3 a = %d' % a) | Correct result is X(q1) | 625941f67cff6e4e81117fe2 |
def read_doc_table(path, axis=0): <NEW_LINE> <INDENT> regex = re.compile('.*?识别[号]?.*|.*?代码.*|.*?行政相对人.*|.*?名称|.*?号') <NEW_LINE> if 'linux' in sys.platform: <NEW_LINE> <INDENT> outdir = '/'.join(path.split('/')[:-1]) <NEW_LINE> output = subprocess.check_output( ["/usr/bin/libreoffice6.3", "--headless", "--invisible", "... | 读取doc文件中的表格
axis=1按列索引读取
axis=0按行索引读取
:param path:
:param axis:
:return:dict | 625941f68e71fb1e9831de02 |
def commaNumber(num): <NEW_LINE> <INDENT> fullNumberStr = str(num) <NEW_LINE> strList = [] <NEW_LINE> numList = fullNumberStr.split('.') <NEW_LINE> intStr = numList[0] <NEW_LINE> while len(intStr) > 0: <NEW_LINE> <INDENT> strList.append(intStr[-3:]) <NEW_LINE> intStr = intStr[:-3] <NEW_LINE> <DEDENT> fStr = '' <NEW_LIN... | This function takes a numeric type (int/float) and returns a striing representation with commas seperating groups of three digits starting with the ones, tens, and hundreds place in the first (right-most) group | 625941f626068e7796caf345 |
def test_delete_alias_creator(self): <NEW_LINE> <INDENT> self._create_alias(self.test_user) <NEW_LINE> result = self.get_success( self.handler.delete_association( create_requester(self.test_user), self.room_alias ) ) <NEW_LINE> self.assertEquals(self.room_id, result) <NEW_LINE> self.get_failure( self.handler.get_associ... | An alias creator can delete their own alias. | 625941f65f7d997b871750fa |
def test_create_certificates_peer_item(self): <NEW_LINE> <INDENT> pass | Test case for create_certificates_peer_item
| 625941f656b00c62f0f14cba |
def interact(self, direction): <NEW_LINE> <INDENT> self.content.movementDelegate.direction = GetOppositeDirection(direction) <NEW_LINE> events = [self.message] <NEW_LINE> if self.content.isBattleable(): <NEW_LINE> <INDENT> events.append(BattleEvent(self.content.trainer)) <NEW_LINE> <DEDENT> if self.callback is not None... | Interact with the trainer | 625941f6bf627c535bc1382c |
def max3(x, y, z): <NEW_LINE> <INDENT> return max2(max2(x, y), z) | Returns the largest of three numbers
:x: First number
:y: Second number
:z: Third number
:returns: Largest number | 625941f63317a56b8693a2a4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.