query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
takes clean str from self.text and creats dict of word length freq.
def makeWordLengths(self): clean_s = self.cleanString(self.text) LoW = clean_s.split() for x in LoW: if len(x) not in self.wordlengths: self.wordlengths[len(x)] = 1 else: self.wordlengths[len(x)] += 1 return self.wordlengths
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def wordFreq(parseThis):\n \n freq = {}\n nono = ('\"', \"'\", '%', '$', '!', '.', '?', '-', ','\n , '\\n', '\\t', '\\r', ':', ';')\n\n for c in nono:\n parseThis = parseThis.replace(c, \" \")\n \n words = parseThis.split()\n \n for word in words:\n temp = word....
[ "0.72095066", "0.71612656", "0.71218807", "0.711714", "0.7092993", "0.7040645", "0.7019579", "0.6963053", "0.6958046", "0.6943951", "0.6904577", "0.68902737", "0.6876883", "0.6857476", "0.68253565", "0.68212354", "0.6773053", "0.6735119", "0.67350656", "0.668967", "0.6683868"...
0.6272309
57
takes clean str from self.text and creats dict of word freq.
def makeWords(self): clean_s = self.cleanString(self.text) LoW = clean_s.split() for x in LoW: if x not in self.words: self.words[x] = 1 else: self.words[x] += 1 return self.words
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def wordFreq(parseThis):\n \n freq = {}\n nono = ('\"', \"'\", '%', '$', '!', '.', '?', '-', ','\n , '\\n', '\\t', '\\r', ':', ';')\n\n for c in nono:\n parseThis = parseThis.replace(c, \" \")\n \n words = parseThis.split()\n \n for word in words:\n temp = word....
[ "0.74459994", "0.74220663", "0.7391444", "0.7324509", "0.7309391", "0.7289624", "0.7283719", "0.7226567", "0.722053", "0.7219711", "0.72076803", "0.7172384", "0.7164771", "0.7158287", "0.7152727", "0.7031354", "0.6992306", "0.69521797", "0.691885", "0.6871911", "0.68676853", ...
0.6263762
93
takes clean str from self.text and creats dict of stem freq.
def makeStems(self): clean_s = self.cleanString(self.text) LoW = clean_s.split() for x in LoW: if create_stem(x) not in self.stems: self.stems[create_stem(x)] = 1 else: self.stems[create_stem(x)] += 1 return self.stems
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_text(self, text, wordcount_dictionary=None):\n if not wordcount_dictionary:\n wordcount_dictionary = {}\n words = self.parse_regexp.findall(text)\n for word in words:\n new_word = stem(word.lower())\n if new_word not in self.stopwords:\n ...
[ "0.68903923", "0.6869947", "0.68236566", "0.6701824", "0.6560145", "0.6438137", "0.6392169", "0.63749504", "0.635293", "0.6312454", "0.62951475", "0.62908894", "0.6230646", "0.6177849", "0.61489856", "0.6128415", "0.6118843", "0.6098367", "0.6080806", "0.6080696", "0.6066174"...
0.6041122
22
takes clean str from self.text and creats dict of gerund/present participle freq.
def makeGerund(self): clean_s = self.cleanString(self.text) LoW = clean_s.split() for x in LoW: if 'ing' in x and x not in self.gerund: self.gerund[x] = 1 elif 'ing' in x and x in self.gerund: self.gerund[x] += 1 return self.gerund
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_frequency_dict(self, text):\n\t\t\tfrequency = {}\n\t\t\t#tomamos los numeros como caracteres entonces el diccionario solo tendra un rango (0,9) las ',' y '\\n'\n\t\t\tfor character in text:#O(len(row)*columns) \n\t\t\t\tif not character in frequency:#como frequency es un diccionario es de O(1)\n\t\t\t\t\...
[ "0.73105294", "0.6889312", "0.683538", "0.6775084", "0.6548403", "0.6505949", "0.65024614", "0.6410328", "0.6371125", "0.6328725", "0.6307117", "0.6296894", "0.625435", "0.6206774", "0.6178976", "0.61252326", "0.61038357", "0.6091284", "0.60814357", "0.6076231", "0.6062723", ...
0.60706675
20
two dictionaries nd1 and nd2 and return the smallest positive value
def smallestValue(self, nd1, nd2): minnd1 = min(nd1.values()) minnd2 = min(nd2.values()) totalmin = min(minnd1,minnd2) return totalmin
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def minInDict(dist):\r\n m = float('inf')\r\n for p in dist:\r\n for q in dist[p]:\r\n if dist[p][q] < m:\r\n m = dist[p][q]\r\n a,b = p,q\r\n return a,b", "def keywithsecondminval(d): \r\n if len(d) == 1:\r\n d = (d.keys())\r\n return d[0...
[ "0.69349235", "0.6200123", "0.6040021", "0.598441", "0.59417975", "0.59298074", "0.5921851", "0.5919063", "0.589691", "0.58484435", "0.5841207", "0.57669926", "0.575807", "0.57121885", "0.570274", "0.56867063", "0.5659589", "0.5648681", "0.5617436", "0.5614321", "0.56119514",...
0.78676057
0
return logprobability that dictionary d came from the distribution of data in the normalized dictionary nd1 and nd2
def compareDictionaries(self, d, nd1, nd2): normnd1 = self.normalizeDictionary(nd1) normnd2 = self.normalizeDictionary(nd2) total_log_prob1 = 0.0 total_log_prob2 = 0.0 epsilon = self.smallestValue(normnd1,normnd2)/2 for x in d: if x not in normnd1: total_log_prob1 += log(epsilon) else: total_log_prob1 += log(normnd1[x])*d[x] for x in d: if x not in normnd2: total_log_prob2 += log(epsilon) else: total_log_prob2 += log(normnd2[x])*d[x] return [total_log_prob1, total_log_prob2]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def log(d: D) -> NumDict:\n\n return d.log()", "def compare_dictionaries(d1, d2):\r\n score = 0\r\n gef = 0\r\n for z in d1:\r\n gef += d1[z]\r\n total = gef\r\n \r\n for x in d2:\r\n if x in d1:\r\n score += math.log(d1[x] / total) * d2[x] \r\n else:\r\n...
[ "0.65142924", "0.6498203", "0.6478609", "0.6398017", "0.63931054", "0.63005465", "0.6257267", "0.6251998", "0.6210485", "0.6205614", "0.618205", "0.61285675", "0.61219615", "0.6059671", "0.6059194", "0.59403294", "0.592365", "0.59173363", "0.59089893", "0.5902279", "0.5892993...
0.782096
0
creates all of the dictionaries from input string self.text
def createAllDictionaries(self): self.makeSentenceLengths() self.makeWords() self.makeStems() self.makeGerund() self.makeWordLengths()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_text(self, text: str) -> SectionDict:", "def initialize_gensim_dictionary(text):\n dct = Dictionary(text)\n return dct", "def convert_to_dict(text):\n content_dict = dict()\n content_dict['clean_text'] = text\n return content_dict", "def preprocess_text(text: str) -> Tuple[List[str],...
[ "0.6951967", "0.65007186", "0.6391913", "0.6171587", "0.6150453", "0.6135733", "0.60717666", "0.60355055", "0.5923922", "0.5921384", "0.5914638", "0.59050655", "0.59048057", "0.58697015", "0.5864588", "0.5859098", "0.58579123", "0.58231443", "0.5812766", "0.57927376", "0.5791...
0.624055
3
Compute in a simple way, but O(NLog(N)) complexity
def missing_integer_simple(l): n = len(l)-1 expected = n*(n+1)/2 found = 0 for num in l: if num is not None: found += num print(expected-found)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute(n):\n if n == 1:\n return 1\n else:\n i = find_i(n)\n return 2 * compute(n - i) + 2 ** i - 1", "def time_complexities():\n return \"Best Case: O(n), Average Case: O(n), Worst Case: O(n)\"", "def solution(number): # O(N)\n ...
[ "0.6677907", "0.6336799", "0.6260519", "0.6221236", "0.61503774", "0.6091918", "0.5895858", "0.587001", "0.586738", "0.58470577", "0.58414006", "0.5831377", "0.5762354", "0.5761957", "0.5754833", "0.57444394", "0.57410777", "0.5713722", "0.5712388", "0.5708484", "0.57046944",...
0.0
-1
Test default product price being 10.
def test_default_product_price(self): prod = product('Test Product') self.assertEqual(prod.price, 10) self.assertEqual(prod.weight, 20)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_default_product_price(self):\n prod = Product('Test Product')\n self.assertEqual(prod.price, 10)", "def test_default_product_price(self):\n prod = Product('Test Product')\n self.assertEqual(prod.price, 10)", "def test_default_product_price(self):\n prod = Product('Te...
[ "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.8738257", "0.87333673", "0.8580199", "0.7287374", "0.72686666", "0.72686666", "0.72686666", "0.72686666", "0.72686666", "0.72686666", "0.726349...
0.8610413
12
Mostly ripped from nc3tonc4 in netCDF4python. Added ability to skip dimension and variables. Removed all of the unpacking logic for shorts.
def clone(src, dst_path, skip_globals, skip_dimensions, skip_variables): if os.path.exists(dst_path): os.unlink(dst_path) dst = netCDF4.Dataset(dst_path, 'w') # Global attributes for attname in src.ncattrs(): if attname not in skip_globals: setattr(dst, attname, getattr(src, attname)) # Dimensions unlimdim = None unlimdimname = False for dimname, dim in src.dimensions.items(): # Skip what we need to if dimname in skip_dimensions: continue if dim.isunlimited(): unlimdim = dim unlimdimname = dimname dst.createDimension(dimname, None) else: dst.createDimension(dimname, len(dim)) # Variables for varname, ncvar in src.variables.items(): # Skip what we need to if varname in skip_variables: continue hasunlimdim = False if unlimdimname and unlimdimname in ncvar.dimensions: hasunlimdim = True filler = None if hasattr(ncvar, '_FillValue'): filler = ncvar._FillValue if ncvar.chunking == "contiguous": var = dst.createVariable(varname, ncvar.dtype, ncvar.dimensions, fill_value=filler) else: var = dst.createVariable(varname, ncvar.dtype, ncvar.dimensions, fill_value=filler, chunksizes=ncvar.chunking()) # Attributes for attname in ncvar.ncattrs(): if attname == '_FillValue': continue else: setattr(var, attname, getattr(ncvar, attname)) # Data nchunk = 1000 if hasunlimdim: if nchunk: start = 0 stop = len(unlimdim) step = nchunk if step < 1: step = 1 for n in range(start, stop, step): nmax = n + nchunk if nmax > len(unlimdim): nmax = len(unlimdim) idata = ncvar[n:nmax] var[n:nmax] = idata else: idata = ncvar[:] var[0:len(unlimdim)] = idata else: idata = ncvar[:] var[:] = idata dst.sync() src.close() dst.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self,filename='slices.000000',nvar=8,nbuf=3,field=None):\n\n #Open file\n f=tables.openFile(filename)\n\n #Dataset \"para_real\"\n self.time=f.root.para_real[0]\n self.dt =f.root.para_real[1]\n self.dx =f.root.para_real[2]\n self.dy =f.root.para_real...
[ "0.5600547", "0.54413694", "0.54308397", "0.5418377", "0.54078954", "0.53668946", "0.5344015", "0.5336579", "0.5290628", "0.52342385", "0.52231324", "0.51942706", "0.5134216", "0.5109639", "0.50503546", "0.50287384", "0.5022853", "0.5013268", "0.49844584", "0.496534", "0.4931...
0.5500222
1
Case 4 A node making multiple primary declarations for a particular node. Consider 4 nodes A, B, C and D. Lets say node B is malicious and is repeatedly declaring Node D as primary
def testPrimaryElectionCase4(case4Setup, looper): allNodes = case4Setup A, B, C, D = allNodes looper.run(checkNodesConnected(allNodes)) # Node B sends multiple declarations of node D's 0th protocol instance as # primary to all nodes for i in range(5): # B.send(Primary(D.name, 0, B.viewNo)) B.send(primaryByNode(D.name, B, 0)) # No node from node A, node C, node D(node B is malicious anyway so not # considering it) should have more than one primary declaration for node # D since node D is slow. The one primary declaration for node D, # that nodes A, C and D might have would be because of node B def x(): primDecs = [p[0] for p in node.elector.primaryDeclarations[0].values()] assert primDecs.count(D.name) <= 1 # also have to take into account the catchup procedure timeout = waits.expectedPoolNominationTimeout(len(allNodes)) + \ waits.expectedPoolCatchupTime(len(allNodes)) for node in (A, C, D): looper.run(eventually(x, retryWait=.5, timeout=timeout)) timeout = waits.expectedPoolElectionTimeout( len(allNodes)) + delaySelfNomination ensureElectionsDone(looper=looper, nodes=allNodes, customTimeout=timeout) # Node D should not have any primary replica assert not D.hasPrimary
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def primary(self):\n ...", "def assign_ids(ast):\n def f_either(obj, *child_results):\n id_ = slast.SlAst.id_\n obj.id_ = id_[0]\n id_[0] += 1\n\n # def f_either(obj, *child_results):\n # _id_dict = slast.SlAst._id_dict\n # id_ = slast.SlAst.id_\n # # FIXME:...
[ "0.5375646", "0.5154644", "0.51295924", "0.49382252", "0.4831968", "0.4788528", "0.4788528", "0.4756773", "0.4754792", "0.4708603", "0.4700092", "0.4677574", "0.46142638", "0.46059236", "0.45961127", "0.45947063", "0.45883384", "0.45769686", "0.45754498", "0.45723775", "0.455...
0.55320704
0
To convert tf.Tensor > json serializable np.ndarray > json serializable
def tf_tensor_2_serializable(obj): import tensorflow as tf import numpy as np # Tensor -> ndarray or object if isinstance(obj, tf.Tensor): if tf.__version__.startswith("1."): with tf.compat.v1.Session(): obj = obj.numpy() else: obj = obj.numpy() # ndarray -> serializable python object TYPES = (int, float, str) if isinstance(obj, np.ndarray): for _type in TYPES: # dtype of string/bytes ndarrays returned by tensor.numpy() # are both np.dtype(object), which are not json serializable try: obj = obj.astype(_type) except (UnicodeDecodeError, ValueError, OverflowError): continue break else: try: obj = np.vectorize(bytes_2_tf_b64)(obj) except ValueError: pass obj = obj.tolist() elif isinstance(obj, bytes): # tensor.numpy() will return single value directly try: obj = obj.decode("utf8") except UnicodeDecodeError: obj = bytes_2_tf_b64(obj) return obj
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_numpy(tensor):\n raise NotImplementedError", "def tensor_to_json(self, tensor_name):\n name = tensor_name\n tup = self.tensor_info[name]\n pert_list = tup[1]\n repr = tup[2]\n\n repr_data = repr.to_json() if repr is not None else None\n pert_data = [o.to_js...
[ "0.68428576", "0.6705407", "0.6659738", "0.6618609", "0.6618609", "0.6618609", "0.6599845", "0.6567279", "0.64083153", "0.63227916", "0.63227916", "0.62989205", "0.628012", "0.6269711", "0.6266001", "0.6180537", "0.6166389", "0.61231035", "0.61231035", "0.61120456", "0.610484...
0.78063214
0
>>> lst = [ [1], [1, 2], [1, 2, 3], None, ] >>> concat_list(lst) [1, 1, 2, 1, 2, 3], [slice(0, 1), slice(1, 3), slice(3, 6), None]
def concat_list(lst, batch_flags=None): slices = [slice(0)] * len(lst) datas = [] row_flag = 0 for i, r in enumerate(lst): if r is None: slices[i] = None continue j = -1 if batch_flags is None or batch_flags[i]: for j, d in enumerate(r): datas.append(d) slices[i] = slice(row_flag, row_flag + j + 1) else: datas.append(r) slices[i] = row_flag row_flag += j + 1 return datas, slices
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def concat_list(in_list):\n return list(itertools.chain(*in_list))", "def concat_succ(L):\n if len(L) < 2:\n return L\n res = []\n last = L.pop()\n othe = L.pop()\n for i in last:\n for j in othe:\n if type(i) is list:\n if type(j) is list:\n ...
[ "0.71166927", "0.6419672", "0.6270731", "0.62562144", "0.6135522", "0.6087907", "0.6058204", "0.6038355", "0.6037199", "0.6023297", "0.59915894", "0.5978991", "0.5917092", "0.5858604", "0.5852147", "0.5850211", "0.584778", "0.58327496", "0.58193696", "0.58092976", "0.57957524...
0.74441135
0
listen for message event
async def on_message(self, msg: Message): try: cmsg = await WechatyMessage(msg) except NotImplementedError as e: logger.debug("[WX] {}".format(e)) return except Exception as e: logger.exception("[WX] {}".format(e)) return logger.debug("[WX] message:{}".format(cmsg)) room = msg.room() # 获取消息来自的群聊. 如果消息不是来自群聊, 则返回None isgroup = room is not None ctype = cmsg.ctype context = self._compose_context(ctype, cmsg.content, isgroup=isgroup, msg=cmsg) if context: logger.info("[WX] receiveMsg={}, context={}".format(cmsg, context)) self.produce(context)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _handle_message(self, msg):\n self.event('message', msg)", "def on_message(data):\n pass", "def event_in_cb(self, msg):\n self.event = msg.data", "def on_message(self, message):\n print \"Client %s received a message : %s\" % (self.id, message)", "def onMessage(self, message...
[ "0.8410868", "0.8254583", "0.7882204", "0.78618526", "0.7829602", "0.7802724", "0.773378", "0.7572389", "0.7512617", "0.74960405", "0.74841064", "0.74824226", "0.7457746", "0.7441775", "0.74085176", "0.73933196", "0.7379106", "0.7322716", "0.7322716", "0.730575", "0.729197", ...
0.68061733
59
all common punctuations in both Chinese and English, if any marker is not included, welcome to pull issues in github repo.
def filter_punctuation(input_str, remove_duplicate_space=True): ''' punctuation=string.punctuation + string.ascii_letters + \ '!?。"#$%&'()*+,-/:;<=>@[\]^_`' + \ '{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞' + \ '〟〰〾〿–—‘’‛“”„‟…‧﹏.·。《》' regex = re.compile('[%s]' % re.escape(punctuation)) ''' regex = re.compile(u'[^\u4E00-\u9FA5]')#非中文 if remove_duplicate_space: result = re.sub(' +', ' ', regex.sub(' ', input_str)) else: result = regex.sub(' ', input_str) result = re.sub("\d+", " ", result) result = strQ2B(result) return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_issue3625():\n nlp = Hindi()\n doc = nlp(u\"hi. how हुए. होटल, होटल\")\n assert [token.text for token in doc] == ['hi', '.', 'how', 'हुए', '.', 'होटल', ',', 'होटल']", "def clean_non_chinese_symbols(text):\n text = regex.sub('[!!]+', \"!\", text)\n text = regex.sub('[??]+', \"?\", text)\n ...
[ "0.65874964", "0.5815723", "0.57310444", "0.5641857", "0.5631367", "0.5505692", "0.55017436", "0.54730123", "0.54569554", "0.54323596", "0.5372543", "0.5367185", "0.5364872", "0.5327742", "0.52777237", "0.5227759", "0.5223804", "0.5223304", "0.51749724", "0.51537734", "0.5126...
0.49559984
50
Converting fullwidth characters to halfwidth characters
def strQ2B(ustring): rstring = "" for uchar in ustring: inside_code = ord(uchar) if inside_code == 12288: inside_code = 32 elif (inside_code >= 65281 and inside_code <= 65374): inside_code -= 65248 rstring += chr(inside_code) return rstring
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fullwidth(st):\n ret = \"\"\n if not st: return ret\n for c in st:\n i = ord(c)\n if c == \" \":\n ret += chr(0x3000)\n elif 0x21 <= i <= 0x7f:\n ret += chr(i - 0x21 + 0xff01)\n else:\n ret += c\n return ret", "def _full_to_half(s):\n ...
[ "0.72672564", "0.72366166", "0.72254", "0.72254", "0.7138966", "0.6003596", "0.58500266", "0.57598126", "0.56762266", "0.5665028", "0.5609316", "0.5608659", "0.5595366", "0.55903506", "0.55307037", "0.55272573", "0.55239594", "0.54834574", "0.5470254", "0.5453405", "0.5435975...
0.0
-1
utility to check if node names are unique
def check_onnx_node_name_uniqueness(onnx_model): onnx_node_names = [node.name for node in onnx_model.graph.node] assert len(onnx_node_names) == len(set(onnx_node_names)), f'list size mismatch, check if names are unique'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __has_conflicting_node_names(self):\n # check length of sets to determine if overlap exists\n return len({node.get_name() for node in self.get_nodeset()}) != len(self.get_nodeset())", "def checkNamesUniqueness(names):\n topNames, deeperNames = getLevelNames(names)\n## print topNames\n## ...
[ "0.73011124", "0.6985261", "0.6725731", "0.6644279", "0.6635118", "0.6553637", "0.6456373", "0.6453211", "0.6446892", "0.6387194", "0.6358027", "0.6313981", "0.62614363", "0.6214909", "0.6204638", "0.619209", "0.6174945", "0.6174945", "0.61397904", "0.6063441", "0.60601556", ...
0.8149716
0
test onxx based utility to find mapping between onnx node names and io tensors
def test_onnx_node_name_to_input_output_names_util(self): model = models.resnet18(pretrained=False) dummy_input = torch.randn(1, 3, 224, 224) torch.onnx.export(model, dummy_input, './data/resnet18.onnx') onnx_utils.OnnxSaver.set_node_names('./data/resnet18.onnx', model, dummy_input, is_conditional=False, module_marker_map={}) onnx_model = onnx.load('./data/resnet18.onnx') # Get Dict mapping node name to the input and output names node_to_io_dict,_ = onnx_utils.OnnxSaver.get_onnx_node_to_io_tensor_names_map(onnx_model) node_0 = onnx_model.graph.node[0] assert node_0.input == node_to_io_dict[node_0.name].inputs assert node_0.output == node_to_io_dict[node_0.name].outputs
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def onnx_extract_operator(node, model, nodes_dict):\n op_type = node.op_type\n input_tensors = []\n output_tensors = []\n\n \"\"\" input_tensors\n each input_tensor has its own soure op, but same dest op\n so both have single string\n \"\"\"\n input_names = []\n # name list\n input_te...
[ "0.65607023", "0.6310749", "0.6268617", "0.6265941", "0.6193158", "0.60374105", "0.5948364", "0.5849513", "0.57718235", "0.57630116", "0.5761633", "0.5725777", "0.57182246", "0.56293416", "0.5621835", "0.56069314", "0.55362374", "0.55332834", "0.5524223", "0.5512426", "0.5477...
0.7777733
0
test onxx based utility to find mapping between onnx node names and io tensors when more than one onnx node maps to the same torch module
def test_single_pytorch_module_mapping_to_many_onnx_nodes(self): AimetLogger.set_level_for_all_areas(logging.DEBUG) class TwoLayerLstmModel(torch.nn.Module): """ Model using torch.nn.LSTM module """ def __init__(self): super(TwoLayerLstmModel, self).__init__() self.lstm = torch.nn.LSTM(input_size=3, hidden_size=5, num_layers=3) def forward(self, x, hx=None): return self.lstm(x, hx) model_name = 'multilayer_lstm' model = TwoLayerLstmModel() dummy_input = torch.randn(10, 1, 3) torch.onnx.export(model, dummy_input, './data/' + model_name + '.onnx') onnx_utils.OnnxSaver.set_node_names('./data/' + model_name + '.onnx', model, dummy_input, is_conditional=False, module_marker_map={}) onnx_model = onnx.load('./data/' + model_name + '.onnx') lstm_nodes = [node for node in onnx_model.graph.node if node.op_type == 'LSTM'] assert 3 == len(lstm_nodes) node_to_io_dict, _ = onnx_utils.OnnxSaver.get_onnx_node_to_io_tensor_names_map(onnx_model) assert isinstance(node_to_io_dict['lstm#root_node'], list) assert 3 == len(node_to_io_dict['lstm#root_node'])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_onnx_node_name_to_input_output_names_util(self):\n model = models.resnet18(pretrained=False)\n dummy_input = torch.randn(1, 3, 224, 224)\n torch.onnx.export(model, dummy_input, './data/resnet18.onnx')\n onnx_utils.OnnxSaver.set_node_names('./data/resnet18.onnx', model, dummy_in...
[ "0.75095046", "0.6466577", "0.64522165", "0.6451405", "0.6420626", "0.6097081", "0.5859226", "0.5858057", "0.5838287", "0.57737774", "0.5742301", "0.5723268", "0.56167114", "0.55878025", "0.558724", "0.55839914", "0.5539161", "0.5493296", "0.5454495", "0.5449514", "0.5327194"...
0.69601613
1
Test that node names are set correctly for linear ops turned into matmul/add in onnx.
def test_set_node_name_for_matmul_add_linear(self, export_args): class Linear(torch.nn.Module): def __init__(self): super(Linear, self).__init__() self.linear = torch.nn.Linear(3, 2) def forward(self, inp): x = self.linear(inp) return x model = Linear() # Using an input to linear op with dimension != 2 causes torch to use matmul->add instead of gemm op onnx_path = './data/MyModel.onnx' onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input=torch.randn(1, 1, 3), onnx_export_args=copy.deepcopy(export_args)) onnx_model = onnx.load(onnx_path) expected_node_names = ['linear', 'linear#1.end'] actual_node_names = [node.name for node in onnx_model.graph.node] for name in expected_node_names: assert name in actual_node_names expected_param_names = ['linear.weight', 'linear.bias'] _, valid_param_set = onnx_utils.OnnxSaver.get_onnx_node_to_io_tensor_names_map(onnx_model) for name in expected_param_names: assert name in valid_param_set # Check that gemm still works as expected onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input=torch.randn(1, 3), onnx_export_args=copy.deepcopy(export_args)) onnx_model = onnx.load(onnx_path) actual_node_names = [node.name for node in onnx_model.graph.node] assert 'linear' in actual_node_names assert 'linear#1' not in actual_node_names expected_param_names = ['linear.weight', 'linear.bias'] _, valid_param_set = onnx_utils.OnnxSaver.get_onnx_node_to_io_tensor_names_map(onnx_model) for name in expected_param_names: assert name in valid_param_set self.check_onnx_node_name_uniqueness(onnx_model) if os.path.exists(onnx_path): os.remove(onnx_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_onnx_node_name_to_input_output_names_util(self):\n model = models.resnet18(pretrained=False)\n dummy_input = torch.randn(1, 3, 224, 224)\n torch.onnx.export(model, dummy_input, './data/resnet18.onnx')\n onnx_utils.OnnxSaver.set_node_names('./data/resnet18.onnx', model, dummy_in...
[ "0.6792893", "0.67721677", "0.65422505", "0.61988956", "0.6150528", "0.6148229", "0.5965357", "0.59260803", "0.5876603", "0.58762425", "0.584769", "0.5770553", "0.57376754", "0.5707993", "0.5700042", "0.5673199", "0.5655918", "0.56137747", "0.5602277", "0.5545079", "0.5532079...
0.7743685
0
Test that node names are uniquely set.
def test_set_unique_node_names(self): class TwoLayerLstmModel(torch.nn.Module): """ Model using torch.nn.LSTM module """ def __init__(self): super(TwoLayerLstmModel, self).__init__() self.lstm = torch.nn.LSTM(input_size=3, hidden_size=5, num_layers=3) def forward(self, x, hx=None): return self.lstm(x, hx) model = TwoLayerLstmModel() dummy_input = torch.randn(10, 1, 3) onnx_path = './data/MyModel.onnx' torch.onnx.export(model, dummy_input, onnx_path) onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input) onnx_model = onnx.load(onnx_path) self.check_onnx_node_name_uniqueness(onnx_model) if os.path.exists(onnx_path): os.remove(onnx_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_onnx_node_name_uniqueness(onnx_model):\n onnx_node_names = [node.name for node in onnx_model.graph.node]\n assert len(onnx_node_names) == len(set(onnx_node_names)), f'list size mismatch, check if names are unique'", "def __has_conflicting_node_names(self):\n # check length of sets ...
[ "0.77317005", "0.7141291", "0.70312846", "0.6989006", "0.65257645", "0.65124905", "0.6434736", "0.64302534", "0.6336855", "0.6324279", "0.6158565", "0.6136917", "0.6109544", "0.60242057", "0.5961925", "0.5955324", "0.5897734", "0.58906686", "0.58848387", "0.5879582", "0.58682...
0.61442566
11
Test that node names are uniquely set.
def test_non_leaf_module_names(self): class Net(torch.nn.Module): """ Model using multiply as functional and module at different depths """ def __init__(self): super().__init__() self.layer = HierarchicalMultiplyModule() def forward(self, x): return self.layer(x) model = Net() dummy_input = torch.randn(10, 1, 3) onnx_path = './data/MyModel.onnx' torch.onnx.export(model, dummy_input, onnx_path) onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input) onnx_model = onnx.load(onnx_path) onnx.checker.check_model(onnx_model) self.check_onnx_node_name_uniqueness(onnx_model) expected_names = [ # names compatible with torch 1.9.1 version (should be removed in the future) 'layer.mul1.mul', 'layer.mul1.Mul_7', 'layer.mul2.mul', 'layer.mul2.Mul_15', 'layer.Mul_18', # names compatible with torch 1.13.1 version '/layer/mul1/Mul', '/layer/mul2/Mul', '/layer/Mul' ] for node in onnx_model.graph.node: assert 'Constant' in node.name or node.name in expected_names if os.path.exists(onnx_path): os.remove(onnx_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_onnx_node_name_uniqueness(onnx_model):\n onnx_node_names = [node.name for node in onnx_model.graph.node]\n assert len(onnx_node_names) == len(set(onnx_node_names)), f'list size mismatch, check if names are unique'", "def __has_conflicting_node_names(self):\n # check length of sets ...
[ "0.77317005", "0.7141291", "0.70312846", "0.6989006", "0.65257645", "0.65124905", "0.6434736", "0.64302534", "0.6336855", "0.6324279", "0.6158565", "0.61442566", "0.6136917", "0.6109544", "0.60242057", "0.5961925", "0.5955324", "0.5897734", "0.58906686", "0.58848387", "0.5879...
0.0
-1
Test that adversial case when the first input is feed to last node in onnx subgraph
def test_model_with_input_last_onnx_node(self): roi_model = RoiModel(height=7, width=7, scale=0.25) x = torch.rand(1, 1, 6, 6) rois = torch.tensor([ [0, -2.0, -2.0, 22.0, 22.0], ]) dummy_input = (x, rois) onnx_utils.OnnxSaver.set_node_names('./data/roi.onnx', roi_model, dummy_input, is_conditional=False, module_marker_map={}, onnx_export_args=(onnx_utils.OnnxExportApiArgs(opset_version=11)) ) onnx_model = onnx.load('./data/roi.onnx') end_nodes = [ n.name for n in onnx_model.graph.node if 'end' in n.name] assert len(end_nodes) == 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_degree_relative_to_subgraph(self, dim):\r\n g = nx.disjoint_union(nx.complete_graph(dim), nx.complete_graph(dim + 1))\r\n g.add_edge(dim, dim - 1)\r\n subgraph = list(range(dim + 1))\r\n assert clique.shrink(subgraph, g) == list(range(dim))", "def are_pad_on_graph(self, subgr...
[ "0.61481655", "0.5825503", "0.575738", "0.5744691", "0.5741752", "0.5737737", "0.57052994", "0.57017195", "0.5676081", "0.56566423", "0.5643218", "0.5618495", "0.5523244", "0.5501655", "0.5474851", "0.54511756", "0.5438007", "0.54232174", "0.5415555", "0.53765196", "0.5337164...
0.0
-1
test dictionary input and output layers
def test_export_dict_input_output(self): class Net(torch.nn.Module): """ Model using multiply as functional and module at different depths """ def __init__(self): super().__init__() self.layer = InputOutputDictModel() def forward(self, x): return self.layer(x) model = Net() # Add an empty dictionary as the last element to not treat as named arguments. # see torch.onnx.export() API for more details. dummy_input = ( {'a': torch.randn(1, 10, 10, 10), 'b': torch.randn(1, 10, 10, 10), 'c': torch.randn(1, 10, 10, 10) }, {} ) onnx_path = './data/MyModel.onnx' torch.onnx.export(model, dummy_input, onnx_path) onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input) onnx_model = onnx.load(onnx_path) onnx.checker.check_model(onnx_model) self.check_onnx_node_name_uniqueness(onnx_model) for node in onnx_model.graph.node: print(node.name) assert node.name.startswith('layer')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_kwargs_input_dict_output(self):\n\n class KwargModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.mul = aimet_torch.elementwise_ops.Multiply()\n\n def forward(self, a, b, c):\n ab = a * b\n bc =...
[ "0.65281624", "0.62313795", "0.6157317", "0.5946783", "0.59059757", "0.58558685", "0.5855444", "0.58469844", "0.58335406", "0.5805809", "0.57551163", "0.57410544", "0.5736132", "0.5734934", "0.5715027", "0.5689544", "0.5608706", "0.5605638", "0.55747133", "0.55457956", "0.553...
0.6687717
0
test dictionary input as kwargs in an intermediate layer
def test_kwargs_input_dict_output(self): class KwargModel(torch.nn.Module): def __init__(self): super().__init__() self.mul = aimet_torch.elementwise_ops.Multiply() def forward(self, a, b, c): ab = a * b bc = b * c ca = self.mul(c, a) return {'ab': ab, 'bc': bc, 'ca': ca} class Net(torch.nn.Module): """ Model using multiply as functional and module at different depths """ def __init__(self): super().__init__() self.layer = KwargModel() def forward(self, x): return self.layer(**x) model = Net() # Add an empty dictionary as the last element to not treat as named arguments. # see torch.onnx.export() API for more details. dummy_input = ( {'a': torch.randn(1, 10, 10, 10), 'b': torch.randn(1, 10, 10, 10), 'c': torch.randn(1, 10, 10, 10) }, {} ) onnx_path = './data/MyModel.onnx' torch.onnx.export(model, dummy_input, onnx_path) onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input) onnx_model = onnx.load(onnx_path) onnx.checker.check_model(onnx_model) self.check_onnx_node_name_uniqueness(onnx_model) for node in onnx_model.graph.node: assert node.name.startswith('layer') or node.name.startswith('/layer') if os.path.exists(onnx_path): os.remove(onnx_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_kw_args_with_dict():\n arg_dict = {'visited_color': 'blue',\n 'link_color': 'red',\n 'back_color': 'yellow',\n 'fore_color': 'orange'}\n assert arguments.fun_opt_kw_params(**arg_dict) == ('orange', 'yellow',\n ...
[ "0.68380266", "0.6642572", "0.6544952", "0.6419672", "0.64001125", "0.63954014", "0.63548684", "0.6272449", "0.6210259", "0.6194217", "0.61427027", "0.6134622", "0.61176914", "0.61130285", "0.61014044", "0.6090693", "0.60874087", "0.6078532", "0.60526466", "0.5990979", "0.597...
0.6957905
0
test naming works for model have large number of sequential nodes
def test_naming_for_model_with_deep_graph(self): model = models.resnet152(pretrained=False) dummy_input = torch.randn(1, 3, 224, 224) onnx_path= './data/' + model.__class__.__name__ + '.onnx' with onnx_simply(True): onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input, is_conditional=False, module_marker_map={}) onnx_model = onnx.load(onnx_path) onnx.checker.check_model(onnx_model) self.check_onnx_node_names(onnx_model) counts = defaultdict(int) top_level_nodes = tuple(['conv1', 'bn1', 'relu', 'maxpool', 'avgpool', 'Flatten_', '/Flatten', 'fc']) for node in onnx_model.graph.node: if node.name.startswith(top_level_nodes): continue elif '.' in node.name: layer_name = '.'.join(node.name.split('#')[0].split('.')[:-1]) counts[layer_name] += 1 elif node.name.startswith('/'): layer_name = '.'.join(node.name.split('/')[1:-1]) counts[layer_name] += 1 for name, counts in counts.items(): if 'downsample' in name: assert counts == 2 else: print(name, counts) assert counts == 10 if os.path.exists(onnx_path): os.remove(onnx_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_set_unique_node_names(self):\n class TwoLayerLstmModel(torch.nn.Module):\n \"\"\"\n Model using torch.nn.LSTM module\n \"\"\"\n def __init__(self):\n super(TwoLayerLstmModel, self).__init__()\n self.lstm = torch.nn.LSTM(input...
[ "0.75483245", "0.6777502", "0.6655101", "0.6572657", "0.63191295", "0.6208426", "0.61246103", "0.6104829", "0.6082704", "0.6061295", "0.5965343", "0.59363145", "0.5935405", "0.5920117", "0.5828375", "0.56998265", "0.56853604", "0.5650619", "0.5605244", "0.55901146", "0.556722...
0.6890959
1
Given the output tensor, the dataset at hand and the current task, masks the former by setting the responses for the other tasks at inf. It is used to obtain the results for the taskil setting.
def mask_classes(outputs: torch.Tensor, dataset: ContinualDataset, k: int) -> None: outputs[:, 0:k * dataset.N_CLASSES_PER_TASK] = -float('inf') outputs[:, (k + 1) * dataset.N_CLASSES_PER_TASK: dataset.N_TASKS * dataset.N_CLASSES_PER_TASK] = -float('inf')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def task_none(input_array, dummyfactor):\n return(input_array)", "def output_mask(self):\n output = self.output\n if isinstance(output, list):\n return [getattr(x, '_keras_mask', None) for x in output]\n else:\n return getattr(output, '_keras_mask', None)", "def _compute_masked_targets(se...
[ "0.5656326", "0.5581794", "0.55620676", "0.55582994", "0.54249823", "0.54239273", "0.54085124", "0.5390853", "0.5355018", "0.5309503", "0.5292148", "0.52734554", "0.5234446", "0.5234446", "0.5234446", "0.5234446", "0.5184564", "0.51844215", "0.51771903", "0.5147717", "0.51107...
0.5071202
26
Evaluates the accuracy of the model for each past task.
def evaluate(model: ContinualModel, dataset: ContinualDataset, last=False) -> Tuple[list, list]: status = model.net.training model.net.eval() accs, accs_mask_classes = [], [] for k, test_loader in enumerate(dataset.test_loaders): if last and k < len(dataset.test_loaders) - 1: continue correct, correct_mask_classes, total = 0.0, 0.0, 0.0 for data in test_loader: inputs, labels = data inputs, labels = inputs.to(model.device), labels.to(model.device) if 'class-il' not in model.COMPATIBILITY: outputs = model(inputs, k) else: outputs = model(inputs) _, pred = torch.max(outputs.data, 1) correct += torch.sum(pred == labels).item() total += labels.shape[0] if dataset.SETTING == 'class-il': mask_classes(outputs, dataset, k) _, pred = torch.max(outputs.data, 1) correct_mask_classes += torch.sum(pred == labels).item() accs.append(correct / total * 100 if 'class-il' in model.COMPATIBILITY else 0) accs_mask_classes.append(correct_mask_classes / total * 100) model.net.train(status) return accs, accs_mask_classes
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def evaluate(eval_ds, model, task):\n\n print('==========EVAL==========')\n # Testing contrastive accuracy\n if task['name'] == 'contrastive_accuracy':\n ds = eval_ds.map(data_utils.pretrain_preprocess)\n ds = ds.batch(128)\n test_contrast_acc = tf.keras.metrics.Accuracy(name='test_co...
[ "0.7057116", "0.69941413", "0.6860783", "0.6805387", "0.67818636", "0.67300326", "0.67083573", "0.6631807", "0.6592348", "0.6574836", "0.6571399", "0.65261126", "0.65081304", "0.6490171", "0.64706427", "0.64673305", "0.64662796", "0.64637923", "0.64597434", "0.6442338", "0.64...
0.0
-1
Evaluates the accuracy of the model for each past task.
def evaluate_nlp(model: ContinualModel, dataset: ContinualDataset, last=False) -> Tuple[list, list]: status = model.net.training model.net.eval() accs, accs_mask_classes = [], [] # todo: change the mask recorder for k, test_loader in enumerate(dataset.test_loaders): if last and k < len(dataset.test_loaders) - 1: continue correct, correct_mask_classes, total = 0.0, 0.0, 0.0 for data in test_loader: xs, ys, x_token_idxs, x_token_masks, y_token_idxs, y_token_masks, y_idxs = data x_token_idxs = x_token_idxs.to(model.device) x_token_masks = x_token_masks.to(model.device) y_token_idxs = y_token_idxs.to(model.device) y_token_masks = y_token_masks.to(model.device) y_idxs = y_idxs.to(model.device) task_id = torch.tensor(k, dtype=torch.int64) task_id = task_id.to(model.device) # todo: change the label recorder if 'class-il' not in model.COMPATIBILITY: outputs = model(x_token_idxs, x_token_masks, task_id) else: outputs = model.forward_nlp(x_token_idxs, x_token_masks, task_id) _, pred = torch.max(outputs.data, 1) correct += torch.sum(pred == y_idxs).item() total += y_idxs.shape[0] if dataset.SETTING == 'class-il': mask_classes(outputs, dataset, k) _, pred = torch.max(outputs.data, 1) correct_mask_classes += torch.sum(pred == y_idxs).item() accs.append(correct / total * 100 if 'class-il' in model.COMPATIBILITY else 0) accs_mask_classes.append(correct_mask_classes / total * 100) model.net.train(status) return accs, accs_mask_classes
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def evaluate(eval_ds, model, task):\n\n print('==========EVAL==========')\n # Testing contrastive accuracy\n if task['name'] == 'contrastive_accuracy':\n ds = eval_ds.map(data_utils.pretrain_preprocess)\n ds = ds.batch(128)\n test_contrast_acc = tf.keras.metrics.Accuracy(name='test_co...
[ "0.7057116", "0.69941413", "0.6860783", "0.6805387", "0.67818636", "0.67300326", "0.67083573", "0.6631807", "0.6592348", "0.6574836", "0.6571399", "0.65261126", "0.65081304", "0.6490171", "0.64706427", "0.64673305", "0.64662796", "0.64637923", "0.64597434", "0.6442338", "0.64...
0.0
-1
The training process, including evaluations and loggers.
def train(model: ContinualModel, dataset: ContinualDataset, args: Namespace) -> None: model.net.to(model.device) results, results_mask_classes = [], [] model_stash = create_stash(model, args, dataset) if args.csv_log: csv_logger = CsvLogger(dataset.SETTING, dataset.NAME, model.NAME) if args.tensorboard: tb_logger = TensorboardLogger(args, dataset.SETTING, model_stash) model_stash['tensorboard_name'] = tb_logger.get_name() dataset_copy = get_dataset(args) for t in range(dataset.N_TASKS): model.net.train() _, _ = dataset_copy.get_data_loaders() if model.NAME != 'icarl' and model.NAME != 'pnn': random_results_class, random_results_task = evaluate(model, dataset_copy) print(file=sys.stderr) for t in range(dataset.N_TASKS): model.net.train() train_loader, test_loader = dataset.get_data_loaders() if hasattr(model, 'begin_task'): model.begin_task(dataset) if t: accs = evaluate(model, dataset, last=True) results[t - 1] = results[t - 1] + accs[0] if dataset.SETTING == 'class-il': results_mask_classes[t - 1] = results_mask_classes[t - 1] + accs[1] for epoch in range(args.n_epochs): for i, data in enumerate(train_loader): if hasattr(dataset.train_loader.dataset, 'logits'): inputs, labels, not_aug_inputs, logits = data inputs = inputs.to(model.device) labels = labels.to(model.device) not_aug_inputs = not_aug_inputs.to(model.device) logits = logits.to(model.device) loss = model.observe(inputs, labels, not_aug_inputs, logits) else: inputs, labels, not_aug_inputs = data inputs, labels = inputs.to(model.device), labels.to( model.device) not_aug_inputs = not_aug_inputs.to(model.device) loss = model.observe(inputs, labels, not_aug_inputs) progress_bar(i, len(train_loader), epoch, t, loss) if args.tensorboard: tb_logger.log_loss(loss, args, epoch, t, i) model_stash['batch_idx'] = i + 1 model_stash['epoch_idx'] = epoch + 1 model_stash['batch_idx'] = 0 model_stash['task_idx'] = t + 1 model_stash['epoch_idx'] = 0 if hasattr(model, 'end_task'): model.end_task(dataset) accs = evaluate(model, dataset) results.append(accs[0]) results_mask_classes.append(accs[1]) mean_acc = np.mean(accs, axis=1) print_mean_accuracy(mean_acc, t + 1, dataset.SETTING) model_stash['mean_accs'].append(mean_acc) if args.csv_log: csv_logger.log(mean_acc) if args.tensorboard: tb_logger.log_accuracy(np.array(accs), mean_acc, args, t) if args.csv_log: csv_logger.add_bwt(results, results_mask_classes) csv_logger.add_forgetting(results, results_mask_classes) if model.NAME != 'icarl' and model.NAME != 'pnn': csv_logger.add_fwt(results, random_results_class, results_mask_classes, random_results_task) if args.tensorboard: tb_logger.close() if args.csv_log: csv_logger.write(vars(args))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def training_phase(self):\r\n self.train_dataloader = self.get_dataloader(\r\n hdf_path=self.train_h5_path,\r\n data_description=\"training set\"\r\n )\r\n self.valid_dataloader = self.get_dataloader(\r\n hdf_path=self.valid_h5_path,\r\n data_descrip...
[ "0.78187734", "0.766623", "0.7507915", "0.74226147", "0.7411162", "0.7411162", "0.7411162", "0.7411162", "0.7411162", "0.73725444", "0.7329948", "0.7323073", "0.73172176", "0.72957176", "0.7275571", "0.72495633", "0.7228919", "0.7227007", "0.72220093", "0.7217784", "0.7202225...
0.0
-1
The training process, including evaluations and loggers.
def train_nlp(model: ContinualModel, dataset: ContinualDataset, args: Namespace) -> None: model.net.to(model.device) results, results_mask_classes = [], [] model_stash = create_stash(model, args, dataset) if args.csv_log: csv_logger = CsvLogger(dataset.SETTING, dataset.NAME, model.NAME) if args.tensorboard: tb_logger = TensorboardLogger(args, dataset.SETTING, model_stash) model_stash['tensorboard_name'] = tb_logger.get_name() dataset_copy = get_dataset(args) for t in range(dataset.N_TASKS): model.net.train() _, _ = dataset_copy.get_data_loaders() if model.NAME != 'icarl' and model.NAME != 'pnn': # for forward transfer calculation random_results_class, random_results_task = evaluate_nlp(model, dataset_copy) print(file=sys.stderr) # start time start_time = time.time() for t in range(dataset.N_TASKS): model.net.train() train_loader, test_loader = dataset.get_data_loaders() if hasattr(model, 'begin_task'): model.begin_task(dataset) if t: accs = evaluate_nlp(model, dataset, last=True) results[t - 1] = results[t - 1] + accs[0] if dataset.SETTING == 'class-il': results_mask_classes[t - 1] = results_mask_classes[t - 1] + accs[1] for epoch in range(args.n_epochs): for i, data in enumerate(train_loader): if hasattr(dataset.train_loader.dataset, 'logits'): # todo: to add logits pass else: xs, ys, x_token_idxs, x_token_masks, y_token_idxs, y_token_masks, y_idxs = data x_token_idxs = x_token_idxs.to(model.device) x_token_masks = x_token_masks.to(model.device) y_token_idxs = y_token_idxs.to(model.device) y_token_masks = y_token_masks.to(model.device) y_idxs = y_idxs.to(model.device) task_id = torch.tensor(t, dtype=torch.int64, requires_grad=False) task_id = task_id.to(model.device) if model.require_task_id: loss = model.observe(inputs=x_token_idxs, inputs_mask=x_token_masks, labels=y_idxs, labels_name=y_token_idxs, labels_mask=y_token_masks, task_labels=task_id) else: loss = model.observe(inputs=x_token_idxs, inputs_mask=x_token_masks, labels=y_idxs, labels_name=y_token_idxs, labels_mask=y_token_masks) progress_bar(i, len(train_loader), epoch, t, loss) if args.tensorboard: tb_logger.log_loss(loss, args, epoch, t, i) model_stash['batch_idx'] = i + 1 model_stash['epoch_idx'] = epoch + 1 model_stash['batch_idx'] = 0 model_stash['task_idx'] = t + 1 model_stash['epoch_idx'] = 0 if hasattr(model, 'end_task'): model.end_task(dataset) # reduce the running freq # if (t+1) % args.eval_freq == 0: accs = evaluate_nlp(model, dataset) results.append(accs[0]) results_mask_classes.append(accs[1]) mean_acc = np.mean(accs, axis=1) print_mean_accuracy(mean_acc, t + 1, dataset.SETTING) # prob_model if args.prob_all_tasks: if args.prob_type != "": for prob_l in range(12): prob_l += 1 if args.prob_type == "proto": p_accs = prob_proto_nlp(model, dataset, prob_l=prob_l) else: p_accs = prob_final_nlp(model, dataset, prob_l=prob_l) p_mean_acc = np.mean(p_accs, axis=1) print("task {} prob_l {}: mean_acc {}, masked_mean_acc {}".format(t + 1, prob_l, round(p_mean_acc[0], 2), round(p_mean_acc[1], 2))) if args.csv_log: csv_logger.log_task_prob(p_mean_acc, t) model_stash['mean_accs'].append(mean_acc) if args.csv_log: csv_logger.log(mean_acc) if args.tensorboard: tb_logger.log_accuracy(np.array(accs), mean_acc, args, t) running_time = time.time() - start_time # prob_model if args.prob_type != "" and not args.prob_all_tasks: for prob_l in range(12): prob_l += 1 if args.prob_type == "proto": accs = prob_proto_nlp(model, dataset, prob_l=prob_l) else: accs = prob_final_nlp(model, dataset, prob_l=prob_l) mean_acc = np.mean(accs, axis=1) print("prob_l {}: mean_acc {}, masked_mean_acc {}".format(prob_l, mean_acc[0], mean_acc[1])) if args.csv_log: csv_logger.log_prob(mean_acc) if args.csv_log: csv_logger.add_bwt(results, results_mask_classes) csv_logger.add_running_time(running_time) csv_logger.add_forgetting(results, results_mask_classes) if model.NAME != 'icarl' and model.NAME != 'pnn': csv_logger.add_fwt(results, random_results_class, results_mask_classes, random_results_task) if args.tensorboard: tb_logger.close() if args.csv_log: csv_logger.write(vars(args))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def training_phase(self):\r\n self.train_dataloader = self.get_dataloader(\r\n hdf_path=self.train_h5_path,\r\n data_description=\"training set\"\r\n )\r\n self.valid_dataloader = self.get_dataloader(\r\n hdf_path=self.valid_h5_path,\r\n data_descrip...
[ "0.78187734", "0.766623", "0.7507915", "0.74226147", "0.7411162", "0.7411162", "0.7411162", "0.7411162", "0.7411162", "0.73725444", "0.7329948", "0.7323073", "0.73172176", "0.72957176", "0.7275571", "0.72495633", "0.7228919", "0.7227007", "0.72220093", "0.7217784", "0.7202225...
0.0
-1
Test the gateway can connect and have an empty dict of devices
def test_connect(self, gateway): assert not gateway._devs
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_get_devices(self):\n pass", "def test_get_devices(self):\n pass", "def test_verify_connection_to_a_device():", "def test_verify_list_of_devices_in_my_network():", "def test_gwservice_listdevices(self, setup_controller):\n resp = setup_controller.request(\"gw\", \"devices\", \"...
[ "0.6762325", "0.6762325", "0.672721", "0.6718752", "0.66731656", "0.6479616", "0.64170194", "0.64170194", "0.6373689", "0.6370904", "0.63623434", "0.6293659", "0.62630945", "0.6125039", "0.6104315", "0.60881805", "0.6080881", "0.6077714", "0.60736173", "0.6019352", "0.6019352...
0.81306255
0
Test the gateway returns an error if the ip is wrong
def test_connect_fail(self): with pytest.raises(InstrumentGatewayError): with InstrumentGateway(addr='an invalid ip!'): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_functional_good_ip(self, url):\n response = requests.get(\"http://localhost:80/ip2w/{url}\".format(url=url))\n if response.status_code != BAD_GATEWAY:\n print(\"\\nGATEWAY is OK\")\n self.assertEqual(response.status_code, OK)\n content = response.json()\n ...
[ "0.76661813", "0.71126264", "0.7094155", "0.69302577", "0.6852113", "0.6760333", "0.671132", "0.6597866", "0.65174395", "0.6418101", "0.64037704", "0.6371887", "0.63335603", "0.632763", "0.6314457", "0.6295242", "0.62879497", "0.6277039", "0.62159216", "0.6197408", "0.6167424...
0.64550585
9
Test the gateway fixture contains drivers that were loaded from files
def test_device_add_from_file(self, gateway_with_devs): assert 'daq' in gateway_with_devs._devs assert 'pel' in gateway_with_devs._devs assert 'sg' in gateway_with_devs._devs assert 'not_a_driver' not in gateway_with_devs._devs
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fixtures():", "def fixture_example_data():\n import_example_data()", "def _fixture_setup(self):\n pass", "def test_load_configs_testing(self):\n global locator, config_paths\n locator.load_config(config_paths[0])\n\n self.assertEqual(locator.config['routines'], ['debug'])\n...
[ "0.6442319", "0.6338353", "0.63182837", "0.61462885", "0.61180353", "0.60295516", "0.5985679", "0.5983612", "0.5970922", "0.5935132", "0.593162", "0.5924928", "0.5904823", "0.59045386", "0.5870761", "0.5864663", "0.58519274", "0.58161414", "0.5772585", "0.5764369", "0.573519"...
0.650908
0
Test the gateway can restart and remove devices
def test_device_mgmt(self, gateway_with_devs): gateway_with_devs.restart('daq') assert gateway_with_devs.daq gateway_with_devs.remove('daq') with pytest.raises(AttributeError): gateway_with_devs.daq
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_delete_device(self):\n pass", "def test_delete_device(self):\n pass", "def clean_rebind_test(**kwargs):\n if 'verify_traffic' not in kwargs:\n kwargs['verify_traffic'] = False\n prepare_subscriber_traffic(**kwargs)\n device_id = kwargs.get('device_id', bbe.get_devices(dev...
[ "0.6643423", "0.6643423", "0.64361143", "0.6349524", "0.63331807", "0.6297916", "0.6297916", "0.620502", "0.6202497", "0.6154049", "0.6146571", "0.6097684", "0.60750765", "0.6045645", "0.6028808", "0.6019024", "0.6019024", "0.5986632", "0.59689575", "0.5868066", "0.58662766",...
0.7743327
0
Return longest Unicode IPA prefix of a word
def longest_one_seg_prefix(self, word, normalize=True): if normalize: word = FeatureTable.normalize(word) last_found_length = 0 node = self.seg_trie for pos in range(len(word) + 1): if pos == len(word) or word[pos] not in node: return word[:last_found_length] node = node[word[pos]] if self.TRIE_LEAF_MARKER in node: last_found_length = pos + 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def longest_word_length(words):", "def find_longest_word(s):\n return sorted(map(lambda si: (si, len(si)), s.split()), key=lambda item: item[1], reverse=True)[0][0]", "def longest_prefix_length(s, i, j):\n l = 0\n while (i+l < len(s)) and (j+l < len(s)):\n if s[i+l] != s[j+l]:\n brea...
[ "0.7097997", "0.676997", "0.6517193", "0.6514086", "0.6458476", "0.6410171", "0.63811177", "0.6330309", "0.63036937", "0.6231064", "0.62217957", "0.61553735", "0.6102581", "0.60974884", "0.6072236", "0.6067233", "0.6035597", "0.60004765", "0.5977789", "0.5977576", "0.59734416...
0.66873753
2
Returns a list of segments from a word
def ipa_segs(self, word, normalize=True): if normalize: word = FeatureTable.normalize(word) return self._segs(word, include_invalid=False, normalize=normalize)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def segment(text: str) -> List[str]:\n\n if not text or not isinstance(text, str):\n return []\n\n return _cut_subword(_cut_etcc.word_tokenize(text))", "def segment(text, WORDS) -> List[Word]:\n Pword = Bag(WORDS)\n if not text: \n return []\n else:\n candidates = ([first] + s...
[ "0.7337489", "0.685515", "0.6529718", "0.6501038", "0.6476964", "0.6460025", "0.6404536", "0.63770807", "0.6358619", "0.6294323", "0.6254505", "0.6179965", "0.6169267", "0.61554486", "0.6085695", "0.6055628", "0.60535055", "0.60130686", "0.59985685", "0.5980995", "0.59705424"...
0.63645136
8
Returns True if `word` consists exhaustively of valid IPA segments
def validate_word(self, word, normalize=True): return not self._segs(word, include_valid=False, include_invalid=True, normalize=normalize)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_word(self, word):\n first_letter, rest = word[0], word[1:]\n\n for possible_start in self._find_letter(first_letter):\n if self._check_word(possible_start, rest):\n return True\n\n return False", "def is_valid(text):\n return is_all_word_segment_in_text...
[ "0.7004589", "0.6847744", "0.6789878", "0.6735888", "0.6684416", "0.6627616", "0.651143", "0.6505042", "0.6428736", "0.6355093", "0.63382703", "0.63290393", "0.63254887", "0.63188684", "0.631191", "0.6290618", "0.62664974", "0.626073", "0.6243883", "0.62189406", "0.6189003", ...
0.69290006
1
Return a list of Segment objects corresponding to the segments in word.
def word_fts(self, word, normalize=True): return [self.fts(ipa, False) for ipa in self.ipa_segs(word, normalize)]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def segment(text: str) -> List[str]:\n\n if not text or not isinstance(text, str):\n return []\n\n return _cut_subword(_cut_etcc.word_tokenize(text))", "def ipa_segs(self, word, normalize=True):\n if normalize:\n word = FeatureTable.normalize(word)\n return self._segs(word, ...
[ "0.6500796", "0.64950335", "0.6456525", "0.6327646", "0.63106126", "0.626178", "0.6221559", "0.61808854", "0.6148151", "0.6108368", "0.60761374", "0.6001049", "0.5893235", "0.58411497", "0.5838696", "0.5827947", "0.58147967", "0.57902044", "0.57790804", "0.5765505", "0.571087...
0.5958538
12
Return a nparray of features namd in ft_name for the segments in word
def word_array(self, ft_names, word, normalize=True): return numpy.array([s.numeric(ft_names) for s in self.word_fts(word, normalize)])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def features_from_labels(audio_file, segments):\n segments_features = []\n #for each segment\n for segment in segments:\n features = features_from_label(audio_file, segment)\n #and append it to the list\n segments_features.append(features)\n return segments_features", "def word_f...
[ "0.62442225", "0.62187326", "0.60698456", "0.6069478", "0.5983086", "0.5907946", "0.58122337", "0.5752974", "0.56823516", "0.5657387", "0.5654542", "0.5639809", "0.5626534", "0.5601375", "0.55624735", "0.55408305", "0.55369127", "0.55353904", "0.5529067", "0.55137616", "0.549...
0.5945811
5
Return a vector in which each dimension is the number of times a featurevalue pair occurs in the word
def bag_of_features(self, word, normalize=True): word_features = self.word_fts(word, normalize) features = [v + f for f in self.names for v in ['+', '0', '-']] bag = collections.OrderedDict() for f in features: bag[f] = 0 vdict = {-1: '-', 0: '0', 1: '+'} for w in word_features: for (f, v) in w.items(): bag[vdict[v] + f] += 1 return numpy.array(list(bag.values()))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def countize(word, ind, count_words, features):\n word = clean(word)\n word = word.split()\n if len(word)>1:\n for i in range(1,len(word)):\n bigram = (word[i-1],word[i])\n count_words[ind].append(bigram)\n features.append(bigram)\n if len(word)>2:\n for i...
[ "0.7089016", "0.66866636", "0.6684821", "0.6607445", "0.6593285", "0.65438855", "0.6478012", "0.6474119", "0.64096224", "0.6368129", "0.6366926", "0.633694", "0.6299358", "0.62755966", "0.62697554", "0.6268828", "0.62654084", "0.6255192", "0.6243507", "0.62417585", "0.624167"...
0.6490124
6
Return True if `segment` is in segment features database
def seg_known(self, segment, normalize=True): if normalize: segment = FeatureTable.normalize(segment) return segment in self.seg_dict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __contains__(self, feature):\n return feature in self.features", "def isSegmentFile(self, segment):\n return os.path.isfile(\"{wd}/{jn}-run/{seg}.rst7\".format( wd=self.workdir, jn=self.jobname, seg=segment.getNameString()))", "def check_segment_for_agent(self, segment, agent):\n mappi...
[ "0.6365108", "0.59316486", "0.57967645", "0.5662152", "0.55408937", "0.55408937", "0.5423819", "0.54050773", "0.53360146", "0.5335236", "0.53037214", "0.529815", "0.529553", "0.5255767", "0.52465856", "0.524252", "0.5228098", "0.522067", "0.5215083", "0.5206038", "0.52032894"...
0.75535554
0
Return a list of segments (as strings) from a word Characters that are not valid segments are included in the list as individual characters.
def segs_safe(self, word, normalize=True): if normalize: word = FeatureTable.normalize(word) return self._segs(word, include_invalid=True, normalize=normalize)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def segment(text: str) -> List[str]:\n\n if not text or not isinstance(text, str):\n return []\n\n return _cut_subword(_cut_etcc.word_tokenize(text))", "def slice(self, word):\n # Short words aren't hyphenated.\n if len(word) <= 4:\n return [word]\n # If the word is a...
[ "0.68789977", "0.6741519", "0.65025", "0.6010337", "0.6006612", "0.5996679", "0.5950866", "0.5939301", "0.5936155", "0.5838023", "0.58029926", "0.5797689", "0.5774421", "0.572342", "0.5713739", "0.57017034", "0.5683238", "0.56335175", "0.5613616", "0.5602126", "0.55915654", ...
0.59464043
7
Given list of strings, return only those which are valid segments
def filter_segs(self, segs, normalize=True): return list(filter(lambda seg: self.seg_known(seg, normalize), segs))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def illegal_indirect_horizontal_intervals(a_list):\n allowed_intervals = ['1', 'b2', '2', 'b3', '3', '4', '5', 'b6', '6']\n intervals = indirect_horizontal_intervals(a_list)\n return [x for x in intervals if x[0][0] not in allowed_intervals]", "def segment(raw_sents:List[str], segment=\"jieba\") -> List...
[ "0.60316664", "0.57880795", "0.5696511", "0.56766254", "0.5634419", "0.5569252", "0.55591166", "0.54737127", "0.5471725", "0.5424363", "0.5422917", "0.5396598", "0.52901965", "0.52557975", "0.5253024", "0.5238155", "0.52132607", "0.52100533", "0.5209123", "0.5185486", "0.5150...
0.59074974
1
Return a string like the input but containing only legal IPA segments
def filter_string(self, word, normalize=True): return ''.join(self.ipa_segs(word, normalize))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compact(number):\n number = clean(number, ' ').upper().strip()\n if number.startswith('AL'):\n number = number[2:]\n if number.startswith('(AL)'):\n number = number[4:]\n return number", "def dummy_junction14():\n return \"junction:chr1:176-324:+\"", "def defangIPaddr(address):...
[ "0.54550743", "0.54391927", "0.53663737", "0.5322689", "0.5241737", "0.52362967", "0.5214989", "0.52047104", "0.519561", "0.51782346", "0.5152315", "0.51449424", "0.51403505", "0.5121869", "0.50963056", "0.506933", "0.50592506", "0.5054341", "0.5052699", "0.5051405", "0.50455...
0.5909749
0
Return a Segment object containing the features shared by all segments
def fts_intersection(self, segs, normalize=True): return reduce(lambda a, b: a & b, [self.fts(s, normalize) for s in self.filter_segs(segs, normalize)])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def segments(self):\r\n return Segments(self)", "def segments(self):\n return (self._subset((i,i+1)) for i in range(len(self)-1))", "def get_all(self):\n return self._segments", "def segments(self):\n L = len(self.vertices)\n return itertools.chain((self._subset((i,i+1)) fo...
[ "0.6147264", "0.5819718", "0.5776346", "0.56910527", "0.5669777", "0.5641783", "0.5624703", "0.55444694", "0.5516832", "0.5491789", "0.54492235", "0.543769", "0.5422729", "0.53894347", "0.5386809", "0.53521913", "0.53349394", "0.5276735", "0.52644706", "0.5250516", "0.5229773...
0.556224
7
Return `True` if all segments in `inv` matches the features in fts
def fts_match_all(self, fts, inv, normalize=True): return all([self.fts(s, normalize) >= fts for s in inv])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fts_match_any(self, fts, inv, normalize=True):\n return any([self.fts(s, normalize) >= fts for s in inv])", "def fts_intersection(self, segs, normalize=True):\n return reduce(lambda a, b: a & b,\n [self.fts(s, normalize) for s in self.filter_segs(segs, normalize)])", "def...
[ "0.7694182", "0.6534538", "0.611552", "0.59962875", "0.56264204", "0.55972457", "0.5396527", "0.53882056", "0.5361637", "0.52219254", "0.5220756", "0.5129794", "0.5123007", "0.5102911", "0.5101226", "0.506148", "0.5042564", "0.5027478", "0.50159997", "0.5011232", "0.5005611",...
0.78391874
0
Return `True` if any segments in `inv` matches the features in fts
def fts_match_any(self, fts, inv, normalize=True): return any([self.fts(s, normalize) >= fts for s in inv])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fts_match_all(self, fts, inv, normalize=True):\n return all([self.fts(s, normalize) >= fts for s in inv])", "def fts_intersection(self, segs, normalize=True):\n return reduce(lambda a, b: a & b,\n [self.fts(s, normalize) for s in self.filter_segs(segs, normalize)])", "def...
[ "0.76956517", "0.6445244", "0.6092043", "0.603439", "0.5596667", "0.55699706", "0.5360697", "0.53144646", "0.52958703", "0.52827823", "0.51305246", "0.51228803", "0.50828075", "0.50755215", "0.50623965", "0.50345546", "0.5033701", "0.502957", "0.50193626", "0.5012903", "0.501...
0.7692603
1
Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`.
def fts_contrast(self, fs, ft_name, inv, normalize=True): inv_segs = filter(lambda x: x >= fs, map(lambda seg: self.fts(seg, normalize), inv)) for a in inv_segs: for b in inv_segs: if a != b: if a.differing_specs(b) == [ft_name]: return True return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fts_match_any(self, fts, inv, normalize=True):\n return any([self.fts(s, normalize) >= fts for s in inv])", "def seg_known(self, segment, normalize=True):\n if normalize:\n segment = FeatureTable.normalize(segment)\n return segment in self.seg_dict", "def fts_match_all(self,...
[ "0.5811271", "0.57281613", "0.5448158", "0.5358385", "0.53195685", "0.53195685", "0.52680486", "0.52578926", "0.52107763", "0.5175667", "0.5123594", "0.5117304", "0.5098134", "0.5091532", "0.50853395", "0.5074376", "0.50618905", "0.5061141", "0.50536674", "0.50494987", "0.504...
0.67574793
0
Return the count of segments in an inventory matching a given feature mask.
def fts_count(self, fts, inv, normalize=True): return len(list(filter(lambda s: self.fts(s, normalize) >= fts, inv)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getSegmentCount(self) -> int:\n ...", "def get_ingredient_count(cls, requestform):\n\n count = 0\n for r in requestform:\n if r[0:4] == 'item':\n count += 1\n return count", "def intersection_count(G=None, min_streets=2):\n spn = streets_per_node(G)\...
[ "0.60189056", "0.57778174", "0.5745941", "0.5679098", "0.562681", "0.5572302", "0.54622877", "0.5433682", "0.5416207", "0.5405498", "0.5370428", "0.5358139", "0.5354548", "0.5344947", "0.5300131", "0.5284212", "0.5281979", "0.527662", "0.525905", "0.5236418", "0.52358586", ...
0.49445313
57
Implements fixedwidth pattern matching. Matches just in case pattern is the same length (in segments) as the word and each of the segments in the pattern is a featural subset of the corresponding segment in the word. Matches return the corresponding list of feature sets; failed matches return None.
def match_pattern(self, pat, word, normalize=True): segs = self.word_fts(word, normalize) if len(pat) != len(segs): return None else: if all([s >= p for (s, p) in zip(segs, pat)]): return segs
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def all_segs_matching_fts(self, ft_mask):\n matching_segs = [ipa for (ipa, fts) in self.segments if fts >= ft_mask]\n return sorted(matching_segs, key=lambda x: len(x), reverse=True)", "def better_matching(self, pattern, offsets=False, slice_len=5):\n first_occurencies, counts_at = self.setu...
[ "0.55103326", "0.5505358", "0.5503776", "0.54771847", "0.5460074", "0.53849596", "0.536037", "0.5330876", "0.5322131", "0.52336895", "0.5171854", "0.51623005", "0.51623005", "0.5151723", "0.51417255", "0.510438", "0.50986654", "0.5090402", "0.5082829", "0.50758904", "0.507350...
0.6005872
0
Implements limited pattern matching. Matches just in case pattern is the same length (in segments) as the constituent and each of the segments in the pattern is a featural subset of the corresponding segment in the word.
def match_pattern_seq(self, pat, const, normalize=True): segs = [self.fts(s, normalize) for s in const] if len(pat) != len(segs): return False else: return all([s >= p for (s, p) in zip(segs, pat)])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def match_pattern(self, pat, word, normalize=True):\n segs = self.word_fts(word, normalize)\n if len(pat) != len(segs):\n return None\n else:\n if all([s >= p for (s, p) in zip(segs, pat)]):\n return segs", "def is_segment(pattern):\n return (type(patt...
[ "0.6140303", "0.5622849", "0.56000507", "0.5588581", "0.5576052", "0.5576052", "0.5569588", "0.5569588", "0.55573744", "0.55385894", "0.55361515", "0.5330484", "0.5278464", "0.5258368", "0.5252977", "0.5252737", "0.5247074", "0.5231641", "0.52287656", "0.52200884", "0.5199797...
0.54910386
11
Return segments matching a feature mask, a dict of features
def all_segs_matching_fts(self, ft_mask): matching_segs = [ipa for (ipa, fts) in self.segments if fts >= ft_mask] return sorted(matching_segs, key=lambda x: len(x), reverse=True)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_seg_features(string):\n seg_feature = []\n for word in jieba.cut(string):\n if len(word) == 1:\n seg_feature.append(0)\n else:\n tmp = [2] * len(word)\n tmp[0] = 1\n tmp[-1] = 3\n seg_feature.extend(tmp)\n return seg_feature", ...
[ "0.5785783", "0.57444733", "0.56591356", "0.5636957", "0.5626444", "0.5615696", "0.5559518", "0.5535667", "0.55190414", "0.5504409", "0.54510874", "0.5436337", "0.54250914", "0.5373862", "0.5363101", "0.5299349", "0.5298827", "0.52629185", "0.52567637", "0.52518916", "0.52425...
0.61812437
0
Given a string describing features masks for a sequence of segments, return a compiled regex matching the corresponding strings.
def compile_regex_from_str(self, pat): s2n = {'-': -1, '0': 0, '+': 1} seg_res = [] for mat in re.findall(r'\[[^]]+\]+', pat): ft_mask = {k: s2n[v] for (v, k) in re.findall(r'([+-])(\w+)', mat)} segs = self.all_segs_matching_fts(ft_mask) seg_res.append('({})'.format('|'.join(segs))) regexp = ''.join(seg_res) return re.compile(regexp)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_regex_search(search_string):\n\n sspat = None\n valid_flags = {\n 'i': re.IGNORECASE\n }\n if search_string:\n try:\n search_string, flag_letters = re.match(r'^(.+?)(?:/([a-z]+))?$', search_string).groups()\n flags = 0\n # if flags are given,...
[ "0.5923782", "0.5887709", "0.5868116", "0.5849082", "0.57891506", "0.5740547", "0.5644862", "0.56026363", "0.55648553", "0.55601627", "0.5549869", "0.5541171", "0.55295944", "0.5511487", "0.54896027", "0.54493785", "0.54365784", "0.5426857", "0.54144484", "0.5406572", "0.5356...
0.6694643
0
Given a Unicode IPA segment, return a list of feature specificiations in canonical order.
def segment_to_vector(self, seg, normalize=True): return self.fts(seg, normalize).strings()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_seg_features(string):\n seg_feature = []\n for word in jieba.cut(string):\n if len(word) == 1:\n seg_feature.append(0)\n else:\n tmp = [2] * len(word)\n tmp[0] = 1\n tmp[-1] = 3\n seg_feature.extend(tmp)\n return seg_feature", ...
[ "0.61101604", "0.6075151", "0.55478764", "0.54786366", "0.5440633", "0.5432097", "0.5407608", "0.53747076", "0.53084356", "0.5303873", "0.5279023", "0.5274519", "0.52741605", "0.5229276", "0.520493", "0.5192467", "0.5183173", "0.51240844", "0.5107907", "0.5059009", "0.5028215...
0.5639854
2
Return a list of feature vectors, given a Unicode IPA word.
def word_to_vector_list(self, word, numeric=False, xsampa=False, normalize=True): if xsampa: word = self.xsampa.convert(word) segs = self.word_fts(word, normalize or xsampa) if numeric: tensor = [x.numeric() for x in segs] else: tensor = [x.strings() for x in segs] return tensor
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def creating_feature_vector():\r\n\twordlist = []\r\n\tlabel = \"\"\r\n\tfw = open(\"feature_vector.txt\", \"w+\", encoding = \"utf-8\")\r\n\twith open(\"D:\\\\Python_Prac\\\\wordstag\\\\modules\\\\HI_EN_TRAIN.txt\", \"r\", encoding = \"utf-8\") as f:\r\n\t\tfor line in f:\r\n\t\t\twordlist.append(line)\r\n\t\tfor...
[ "0.6246148", "0.62410086", "0.6116035", "0.6115346", "0.5932024", "0.59269047", "0.5920939", "0.5908701", "0.58761644", "0.58152443", "0.5796711", "0.5752887", "0.574728", "0.57368666", "0.5726028", "0.5711519", "0.57040584", "0.570145", "0.568096", "0.5660981", "0.56468755",...
0.61455387
2
Keep track of machine activity with time stamps.
def updateMachine(self, machine, raw_cpu, filtered_cpu): stamp = time.time() - self.initTime raw_cpu = float(raw_cpu) filtered_cpu = float(filtered_cpu) if machine in self.activity.keys(): self.activity[machine]["filtered activity"].append(filtered_cpu) self.activity[machine]["raw activity"].append(raw_cpu) self.activity[machine]["time"].append(stamp) else: self.activity[machine] = {"filtered activity" : [filtered_cpu], "raw activity" : [raw_cpu], "time" : [stamp]}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def internal_event(self):\n # log activity\n self.log_activity(LogEntry(\n sys_time=time(),\n logical_time=self.logical_clock,\n action=\"work\"\n ))", "def noteActivity(): \r\n global lastActivity\r\n lastActivity = millis()", "def noteActivit...
[ "0.69313186", "0.63031006", "0.62680084", "0.6137144", "0.6080439", "0.58535415", "0.58349663", "0.580419", "0.57930464", "0.57846797", "0.57673466", "0.57643175", "0.57618624", "0.57599396", "0.57484883", "0.5720372", "0.5714929", "0.57034856", "0.5640119", "0.5619169", "0.5...
0.5073809
79
Record start time of a process as well as its host machine.
def updateProcess(self, machine, process): stamp = time.time() - self.initTime if machine in self.activity.keys(): if (("processes" in self.activity[machine].keys()) and (process in self.activity[machine]["processes"].keys())): self.activity[machine]["processes"][process].append(stamp) else: self.activity[machine]["processes"] = {process : [stamp]} else: self.activity[machine] = {"filtered activity" : [], "raw activity" : [], "time" : [], "processes" : {process : [stamp]}}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def start_time(self):\n pass", "def start_time(self) -> float:\r\n ...", "def getStartTime(self):\n assert not self.isWaitingToStart(), \"Too early to tell: %s\" % self\n return \"%s\" % self.__rawInfo.startTime", "def start_time(self):\n return self.__start", "def set_start_time...
[ "0.65806735", "0.6416755", "0.6403931", "0.6389469", "0.6377402", "0.6365346", "0.62822706", "0.6281774", "0.6281774", "0.6281774", "0.623706", "0.623706", "0.623706", "0.623706", "0.623706", "0.623706", "0.623706", "0.623706", "0.62240183", "0.62178797", "0.61842185", "0.6...
0.0
-1
Convert to numpy arrays and pickle to the specified file.
def save(self): # make a clone to preserve the original in case it's still needed clone = {} for machine in self.activity.keys(): data = self.activity[machine].copy() data["filtered activity"] = np.array(data["filtered activity"], dtype=np.float) data["raw activity"] = np.array(data["raw activity"], dtype=np.float) data["time"] = np.array(data["time"], dtype=np.float) clone[machine] = data out = open(self.filename, "wb") pickle.dump(clone, out) out.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pickle(array, file):\r\n\timport cPickle\r\n\tfo = open(file,'wb')\r\n\tcPickle.dump(array,fo)\r\n\tfo.close()", "def save(file, arr, allow_pickle=True, fix_imports=True):\n\n return numpy.save(file, array_create.array(arr, bohrium=False), allow_pickle, fix_imports)", "def save_to_file(samps, filename, ...
[ "0.69759345", "0.69321483", "0.6812905", "0.67736834", "0.6720767", "0.66823816", "0.6668173", "0.66250736", "0.66020155", "0.6568645", "0.65596145", "0.6404797", "0.6398163", "0.6341175", "0.6324566", "0.6324464", "0.626959", "0.623348", "0.6216238", "0.6199442", "0.61983526...
0.0
-1
Return a list containing the predicted output for each frame image from the retrained CNN model
def predict_on_frames(frames): frame_predictions = [] print("Total Number of Frames ",len(frames)) count = 0 #for i, frame in tqdm(enumerate(frames)): for frame in tqdm(frames): filename = frame[0] label = frame[1] frameCount = frame[2] if(count%200 == 0): print(count) prediction = label_image.get_prediction(filename) frame_predictions.append([prediction, label, frameCount]) count = count + 1 return frame_predictions
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def predict(model, images):\n return model.predict_classes(images)", "def predict_batch(model, images):\n if images is not None:\n y_predicted = model.predict(images)\n predicted_classes = np.argmax(y_predicted, axis=1)\n return predicted_classes.tolist()\n else:\n return []", ...
[ "0.6863064", "0.6837647", "0.67098725", "0.66824293", "0.658928", "0.65756834", "0.65547824", "0.6550675", "0.65452987", "0.6542417", "0.6496417", "0.6496279", "0.64936125", "0.64826065", "0.6478494", "0.6471331", "0.6459123", "0.64511555", "0.64502", "0.6362195", "0.6349084"...
0.64555985
17
Returns list of elements with length "num" that are found to be equally spaced in the sequence provided
def takespread(sequence, num): length = float(len(sequence)) for i in range(num): yield sequence[int(ceil(i * length / num))]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def takespread(sequence, num):\n length = float(len(sequence))\n for i in range(num):\n yield sequence[int(np.ceil(i * length / num))]", "def makespread(sequence, num):\n length = float(len(sequence))\n seq = np.array(sequence)\n return seq[np.ceil(np.arange(num) * length / num).astype(int)...
[ "0.6423416", "0.61214864", "0.6046932", "0.5743309", "0.5673493", "0.55953926", "0.54691815", "0.54635596", "0.54383546", "0.5431269", "0.5416143", "0.5397969", "0.53908265", "0.53346854", "0.53308976", "0.5270804", "0.5267939", "0.5258385", "0.5253757", "0.5242062", "0.52373...
0.63344747
1
Reads in the labelled frames and saves output from CNN model in pickle file
def main(input_file_name,output_file_name,video_length): length_of_video = video_length with open(input_file_name + '.pkl', 'rb') as fin: frames = pickle.load(fin) sorted_frames = list(list(x[1]) for x in itertools.groupby(frames, operator.itemgetter(1))) final_dict = dict() for element in sorted_frames: for f in element: name = f[0] video_name = name[name.rindex("/")+1:name.rindex("frame")-1] if video_name not in final_dict: final_dict[video_name] = [] final_dict[video_name].append(f) new_frames = [] for key in final_dict: #elements = takespread(final_dict[key],length_of_video) new_frames.extend(final_dict[key]) print("size:", len(new_frames)) predictions = predict_on_frames(new_frames) with open(output_file_name + '.pkl', 'wb') as fout: pickle.dump(predictions, fout)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_labels():\n filename = os.path.join(config['inference']['model_dir'], 'output_labels.txt')\n global labels\n labels = [line.rstrip() for line in tf.gfile.FastGFile(filename)]", "def extract_labels(nlabels,filename, one_hot=False):\n print('Extracting', filename,'bbbccicicicicib')\n\n labels=num...
[ "0.6610099", "0.6471816", "0.6420202", "0.6321379", "0.6279507", "0.6236104", "0.62183523", "0.6211333", "0.6210031", "0.61808336", "0.61574364", "0.6154807", "0.61260164", "0.6123372", "0.6122588", "0.6109854", "0.60853416", "0.60820115", "0.6063963", "0.60560757", "0.604818...
0.0
-1
group([0,3,4,10,2,3], 2) => iterator Group an iterable into an ntuples iterable. Incomplete tuples are padded with Nones e.g. >>> list(group(range(10), 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
def group(lst, n): iters = tee(lst, n) iters = [iters[0]] + [chain(iter, repeat(None)) for iter in iters[1:]] return izip( *[islice(iter, i, None, n) for i, iter in enumerate(iters)])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def grouper(iterable: Iterable, n: int, fillvalue: Any = None) -> Iterator[tuple]:\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n # pylint: disable=invalid-name\n args = [iter(iterable)] * n\n # pylint: enable=invalid-name\n return itertools.zip_longest(*args, fillvalue=fillvalue)", "def group...
[ "0.80415297", "0.8012354", "0.7891814", "0.78612876", "0.7830936", "0.7768379", "0.77457225", "0.774194", "0.774194", "0.7739891", "0.7731009", "0.7731009", "0.7730615", "0.7714614", "0.7697723", "0.76915014", "0.76890963", "0.76890963", "0.76738936", "0.76717544", "0.7668773...
0.71935266
33
Defines the initial bounds and labels for the plotter.
def set_up_plotter(self, n_levels: int, param_labels: List[str]): self.ax.set_ylim(0, n_levels) self.ax.set_zlim(0, 5) self.ax.set_xlim(0, 1) self.ax.invert_xaxis() self.ax.set_zlabel(param_labels[0], labelpad=5) self.ax.set_ylabel("Optimization level", labelpad=10) self.ax.set_xlabel(param_labels[1], labelpad=10) self.fig.show() self.fig.canvas.draw()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initWidgets(self):\n self.loctext.setText(\"{0:g}\".format(self.loc))\n self.scaletext.setText(\"{0:g}\".format(self.scale))", "def set_up(self):\n self.h, = self.ax.plot(self.x, lw=2)\n self.ax.set_ylim(0,100)\n self.ax.set_xlim(0,100)\n self.ax.title.set_text(self....
[ "0.66450757", "0.65903693", "0.64363885", "0.6421661", "0.64124984", "0.6323452", "0.6308811", "0.6259724", "0.6237798", "0.6225696", "0.61938274", "0.61938274", "0.614099", "0.6140022", "0.61156905", "0.6096484", "0.60959345", "0.6092208", "0.6075896", "0.6053978", "0.604405...
0.6262071
7
Draws the bounds for a level's parameter space.
def add_bounds_to_ax(self, x: np.ndarray, y: np.ndarray, z: int) -> None: width = max(y) - min(y) height = max(x) - min(x) p = Rectangle( (min(y), min(x)), width, height, edgecolor="black", facecolor="none", linestyle="--", ) self.ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=z, zdir="y") self.draw()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_bounds():\n\n pass", "def bounds(self, pos):", "def write_bounds(self):\n optimized_par_df = \\\n self.parameter_df.loc[self.parameter_df.estimate == 1\n & (~self.parameter_df.index.isin(\n self.amici_model.getFixedParameterI...
[ "0.7272382", "0.62937915", "0.6163484", "0.6021445", "0.5926308", "0.5803722", "0.57488054", "0.57488054", "0.57488054", "0.57488054", "0.57488054", "0.57488054", "0.57488054", "0.57488054", "0.5734198", "0.5685604", "0.56679", "0.5640129", "0.5524533", "0.55184925", "0.55161...
0.48262188
89
Convert the passed values to colormap.
def get_colormap(level_values: np.ndarray) -> np.ndarray: color_dimension = level_values # change to desired fourth dimension color_min, color_max = color_dimension.min(), color_dimension.max() norm = colors.Normalize(color_min, color_max) m = plt.cm.ScalarMappable(norm=norm, cmap="Spectral_r") m.set_array([]) face_colors = m.to_rgba(color_dimension) return face_colors
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __value2color(self, v):\n if np.isscalar(v):\n r = self.cmap(self.norm(np.asarray([v])))\n else:\n r = self.cmap(self.norm(v))\n return r.flatten()", "def get_colormap(values, cmap='jet', colorbar=True, log=False):\n by_value = not isinstance(values, int)\n if...
[ "0.7223537", "0.70907754", "0.6728139", "0.6724819", "0.66896755", "0.66573834", "0.65715116", "0.64982826", "0.6465033", "0.6465033", "0.6465033", "0.6465033", "0.6443659", "0.6338098", "0.63217264", "0.6303877", "0.6251594", "0.6230061", "0.62153965", "0.6132751", "0.609306...
0.6442322
13
Plots the cell trajectories in 2D as a line and a point at the last coordinate.
def plot_trajectories_2d(trajectories: pd.DataFrame, ax: Optional[plt.Axes] = None): if ax is None: fig, ax = plt.subplots() for cell in trajectories: ax.plot(cell["position_x"].values, cell["position_y"].values) ax.scatter( cell["position_x"].values[-1], cell["position_y"].values[-1], marker="o" ) return ax
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def plot_lines(self):\n self.plot(3)", "def trajectoire(self):\n trajx = []\n trajy = []\n for i in range(0, len(self.pos)):\n trajx.append(self.pos[i].x)\n trajy.append(self.pos[i].y)\n plt.plot(trajx, trajy) # color=self.color)\n plt.show()", "...
[ "0.6842867", "0.68287706", "0.65767425", "0.65242386", "0.648994", "0.6471235", "0.6305497", "0.62960494", "0.6275145", "0.6269169", "0.6093281", "0.6079582", "0.60568917", "0.6041457", "0.60041326", "0.59778225", "0.5945811", "0.5943831", "0.5938332", "0.59359473", "0.588435...
0.6549081
3
Plots the cell trajectories in 3D as a line and a point at the last coordinate.
def plot_trajectories_3d(trajectories: pd.DataFrame, ax: Optional[plt.Axes] = None): if ax is None: fig = plt.figure() ax = fig.add_subplot(projection="3d") for cell in trajectories: ax.plot( cell["position_x"].values, cell["position_y"].values, cell["position_z"].values, ) ax.scatter( cell["position_x"].values[-1], cell["position_y"].values[-1], cell["position_z"].values[-1], marker="o", ) return ax
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def plot3d(self):\n plot_rupture_wire3d(self)", "def plot_lines(self):\n self.plot(3)", "def plot_results_traj_3d(p_x, p_y, p_z, xmin, xmax, ymin, ymax, zmin, zmax):\n fig, ax = plt.subplots(2 , 2, figsize = (10, 10))\n \n for p in np.arange(0, p_x.shape[0], step = 1): \n for t in...
[ "0.7024431", "0.6795507", "0.66586065", "0.6364133", "0.6340602", "0.63186383", "0.61583287", "0.61494225", "0.613501", "0.6111204", "0.6093264", "0.60898846", "0.6077247", "0.60679746", "0.6041715", "0.5961347", "0.59601736", "0.5956387", "0.59558564", "0.5903093", "0.589808...
0.66579044
3
Initializes the class with n and raises error if id is too big
def __init__(self, n): if n >= 52: raise Exception("This card does not exist") self.n = n
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, n):\n self.n = n", "def __init__(self, n):\n self.n = n", "def __init__(self, N):\n pass", "def __init__(self, id=None):\n if id is not None:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects", ...
[ "0.74003464", "0.74003464", "0.7096325", "0.6966253", "0.6966253", "0.6966253", "0.6966253", "0.6960996", "0.6900746", "0.6753491", "0.6679413", "0.66501856", "0.66501856", "0.66501856", "0.66501856", "0.6589031", "0.6516931", "0.6489422", "0.64609724", "0.6439665", "0.640466...
0.67713875
9
Returns a card according to it's rank and symbol by comparing the suit to sym and rank to rank_sym
def __repr__(self): return (str(self.rank_sym[self.rank()]) + self.sym[self.suit()])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getCard(self, rank, suit):\r\n for card in self.cards:\r\n if card.rank == rank and card.suit == suit:\r\n return card\r\n return None", "def card_factory(rank,suit):\n pass", "def get_card(self, suit, face):\n for card in self.deck:\n if card.su...
[ "0.7077452", "0.66447884", "0.6558589", "0.65260136", "0.6487388", "0.64388734", "0.6393751", "0.6229948", "0.61175305", "0.60968053", "0.6085358", "0.60536987", "0.6034691", "0.59970397", "0.5968616", "0.5967686", "0.5961493", "0.596145", "0.5949978", "0.5949622", "0.5888988...
0.55325085
41
Returns the comparison of which is greater based on id
def __lt__(self,other): return self.n < other.n
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compare(self) -> int:", "def compare_to(self, other) -> int:\n if self.id == other.id:\n return 0\n if self.status != other.status:\n return -1 if self.status < other.status else 1\n if self.last_played != other.last_played:\n return -1 if self.last_played < other.last_played else 1\n...
[ "0.6579224", "0.64989537", "0.62860954", "0.6273539", "0.6266201", "0.6231986", "0.62169814", "0.6210893", "0.6201532", "0.6189547", "0.61581546", "0.61234397", "0.61148363", "0.608585", "0.607456", "0.6059237", "0.6042042", "0.6005502", "0.59676754", "0.596216", "0.5961682",...
0.0
-1
Finds the rank of the card and returns rank
def rank(self): rank = self.n % 13 return rank
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def rank():\n return 0", "def get_rank() -> int:\n return collective.get_rank()", "def get_rank(self) -> int:\r\n return self.rank", "def get_rank(self):\r\n return self.rank", "def __int__(self):\n return Card.ranks.index(self.rank) + Card.suits.index(self.suit) * len(Card.ranks...
[ "0.7572013", "0.7296982", "0.7268319", "0.7267528", "0.7215522", "0.7210751", "0.7199964", "0.7196077", "0.718358", "0.71687156", "0.71248996", "0.71213835", "0.7119498", "0.7068738", "0.7030133", "0.7003381", "0.6978734", "0.6972577", "0.6972085", "0.6957598", "0.6882679", ...
0.6873474
21
Finds the suit of the card and returns suit
def suit(self): suit = self.n // 13 return suit
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def suit(self):\n return self._suit", "def suit(self):\n return self._suit", "def get_suit(self):\r\n return self.suit", "def get_num_suit(self):\n if self.suit == \"Diamonds\":\n return 0\n if self.suit == \"Clubs\":\n return 1\n if self.suit =...
[ "0.7840655", "0.7840655", "0.76949203", "0.74996036", "0.71775246", "0.7047003", "0.7040735", "0.69748276", "0.68587106", "0.6670335", "0.6659063", "0.6624975", "0.6460083", "0.6283954", "0.6283012", "0.6268685", "0.6239651", "0.6238502", "0.6206122", "0.6204729", "0.6155964"...
0.78034705
2
Returns the point value of the card based on the point_sysm
def points(self): if self.rank() >= 9: return self.point_sysm[self.rank()] else: return 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_points(self):\n return self.card_points", "def points(self):\r\n\t\tif self.rank() in self.point_sysm:\r\n\t\t\treturn self.point_sysm[self.rank()]\r\n\t\telse:\r\n\t\t\treturn (self.rank() + 2)", "def get_value(self) -> float:\n return self.points[0, 0]", "def get_value(self):\n ...
[ "0.62925595", "0.62118644", "0.61739796", "0.6122231", "0.60565126", "0.6052252", "0.59305984", "0.5907347", "0.5907347", "0.58484674", "0.583888", "0.5818497", "0.57965267", "0.57405937", "0.57035714", "0.56290007", "0.5627985", "0.56179416", "0.5547793", "0.55453503", "0.55...
0.6351527
0
Returns True if the self rank is higher than the other rank
def __lt__(self,other): return self.rank() < other.rank()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __gt__(self, other):\n return int(self.rank) > int(other.rank)", "def __ge__(self, other):\n return int(self.rank) >= int(other.rank)", "def __le__(self, other):\n return int(self.rank) <= int(other.rank)", "def __gt__(self, other):\n return self.eval_score < other.eval_sc...
[ "0.8275582", "0.79964995", "0.7796771", "0.72897935", "0.716286", "0.714543", "0.7067061", "0.7035331", "0.7034307", "0.70110303", "0.69910157", "0.69268256", "0.6925097", "0.69192606", "0.6889218", "0.68517315", "0.68517315", "0.6849785", "0.6836221", "0.6831901", "0.6809451...
0.69531363
11
Returns the point value for the card based on Blackjack scoring rules
def points(self): if self.rank() in self.point_sysm: return self.point_sysm[self.rank()] else: return (self.rank() + 2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calculate_points(card):\n for value in scores.keys():\n if value == card.value:\n card_score = scores[card.value]\n return card_score", "def hand_points(hand):\n points = [[]]\n branch = 1\n for card in hand:\n if not card[\"is_hidden\"]:\n if card[\"value\"].isnumeric():\n...
[ "0.811599", "0.7140242", "0.71156716", "0.7035238", "0.6973796", "0.6955599", "0.6876456", "0.6845327", "0.6747479", "0.6636815", "0.6617078", "0.66109943", "0.6589633", "0.6580763", "0.65789396", "0.65678483", "0.654564", "0.65092874", "0.65078074", "0.6452383", "0.64124787"...
0.0
-1
Finds the total points that the hand h has and returns that value
def total(h): return sum(i.points() for i in h)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calculate_points(self):\n points = 0\n for power in self.stats['powers']:\n points += self.stats['powers'][power]\n return points", "def calculate_points(hand): \r\n hand_value = 0\r\n ace_count = 0 \r\n \r\n #Finds value of non-Ace cards, and counts number ...
[ "0.69434226", "0.69146436", "0.6852298", "0.6826466", "0.6719616", "0.67074096", "0.66723466", "0.6659441", "0.65662277", "0.6562473", "0.6524262", "0.6511739", "0.64851105", "0.64222765", "0.6378741", "0.63757426", "0.636187", "0.63509446", "0.6337169", "0.6326228", "0.63157...
0.76675487
0
Returns a deck full of a cards that are defined by the cla class
def new_deck(cla): return [cla(i) for i in range(52)]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_deck(self):\n\t\tsuits = [\"hearts\", \"spades\",\"diamonds\",\"clubs\"]\n\t\tcards = []\n\n\t\tfor suit in suits:\n\t\t\tif self.ace_as_eleven:\n\t\t\t\tace = Card(\"Ace\", 11, suit)\n\t\t\telse:\n\t\t\t\tace = Card(\"Ace\", 1, suit)\n\t\t\tcards.append(ace)\n\n\t\t\ttwo = Card(\"Two\", 2, suit)\n\t\...
[ "0.7541672", "0.71924794", "0.7061139", "0.69914514", "0.6714803", "0.666234", "0.664922", "0.6637694", "0.66035664", "0.657957", "0.6567809", "0.6554334", "0.6484326", "0.6472026", "0.6435984", "0.64274347", "0.6413029", "0.6395127", "0.63739616", "0.63564146", "0.635381", ...
0.76038283
0
Pushes records to the server
def _push(self, server): defns = [self.get_id(ident) for ident in list(self.ids)] #for ident in list(self.ids): # defn = self.get_id(ident) if len(defns) == 0: return self.app.logger.info(f"Updating {server} with {len(defns)} records") url = f"{server}/add_record" try: resp = requests.post(url, json=defns) except Exception as e: self.app.logger.error(str(e)) return if not resp.ok: self.app.logger.error(f"{resp.reason} {resp.content}") return self._server_updated[server] = True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _es_push_results(self, query_name, records):\n logger.debug(f\"Pushing {query_name}: {records}\")\n for c in self.es_clients:\n c.send_to_es(query_name, records)", "def _push_to_server(self) -> None:\n timestamp = int(arrow.get().float_timestamp * 1000)\n\n datapoints: ...
[ "0.6992219", "0.6472381", "0.6440058", "0.6413171", "0.6410277", "0.64007604", "0.6349231", "0.6322149", "0.61902606", "0.61212903", "0.60770565", "0.60610574", "0.60589975", "0.599316", "0.5989526", "0.5989526", "0.5933634", "0.5901903", "0.5889706", "0.5877791", "0.58750814...
0.7575993
0
Fetch a url and BeautifulSoupify the returned doc
def _url2soup(self, url, qsdata={}, postdata=None, headers={}): logger.info("Fetching: %s" % url) ua = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11' headers.update({'User-Agent': ua}) params = urlencode(qsdata) if params: if '?' in url: url = "%s&%s" % (url,params) else: url = "%s?%s" % (url,params) req = Request(url,postdata,headers) doc = urlopen(req) data = doc.read() soup = BeautifulSoup(data) return soup
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_url(url):\n try:\n soup = bs(urlopen(url).read(), 'html.parser')\n return soup\n except:\n print \"Couldnot download the content from the URL\", url\n return \"\"", "def get_document(url):\n req = requests.get(url)\n doc = BeautifulSoup(req.content, \"html.parser...
[ "0.7806457", "0.7470853", "0.73826766", "0.7287493", "0.72475606", "0.71778685", "0.7014653", "0.69928056", "0.6990505", "0.69898975", "0.6983415", "0.6978702", "0.6976216", "0.69470924", "0.68931305", "0.6890334", "0.68858266", "0.6878703", "0.6874414", "0.68655133", "0.6827...
0.6243189
66
Function to mixup data.
def mixup(batch: Tuple[torch.Tensor, torch.Tensor], alpha: float = 1.0) -> Tuple: data, targets = batch lam = np.random.beta(alpha, alpha) if alpha > 0 else 1 indices = torch.randperm(data.shape[0]) mixed_data = lam * data + (1 - lam) * data[indices, :] target_a, target_b = targets, targets[indices] targets = (target_a, target_b, lam) return mixed_data, targets
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def concatenate_data():", "def data_unification(self, data1, data2):\r\n data = data1 + data2\r\n return data", "def mixup_data(self, data_ratio_produce=2, alpha=0.2):\n real_samples_idx = np.argwhere(self.data['real']).ravel()\n n_training_samples = real_samples_idx.shape[0]\n ...
[ "0.68712044", "0.62400174", "0.6233847", "0.61989665", "0.6126787", "0.6072504", "0.5922656", "0.59136444", "0.5769046", "0.5631745", "0.5611928", "0.56094086", "0.5598539", "0.55601525", "0.55570143", "0.547382", "0.54204816", "0.5399414", "0.5374631", "0.53570753", "0.53064...
0.595715
6
Function to crop random bboxes.
def random_bbox(data, lam): img_h, img_w = data.shape[2:] cx = np.random.uniform(0, img_w) cy = np.random.uniform(0, img_h) w = img_w * np.sqrt(1 - lam) h = img_h * np.sqrt(1 - lam) x0 = int(np.round(max(cx - w / 2, 0))) x1 = int(np.round(min(cx + w / 2, img_w))) y0 = int(np.round(max(cy - h / 2, 0))) y1 = int(np.round(min(cy + h / 2, img_h))) return x0, x1, y0, y1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def random_crop_bbox(fs_im, fs_mask, bbox, scale_factor_range):\n # Convert bbox floats to ints.\n bb_x1, bb_y1, bb_x2, bb_y2 = bbox\n # When going from continuous float coordinates to pixel index coordinates, need to subtract 1 from x2 and y2.\n bb_x1, bb_y1, bb_x2, bb_y2 = int(bb_x1), int(bb_y1), int...
[ "0.7094237", "0.6923021", "0.6707568", "0.6556093", "0.6494876", "0.64902526", "0.6450483", "0.6424151", "0.6415657", "0.64077026", "0.6321483", "0.62812304", "0.62280124", "0.62280124", "0.61862594", "0.61374986", "0.61367637", "0.60897416", "0.60772663", "0.6062564", "0.605...
0.0
-1
Function to perform cutmix.
def cutmix(batch: Tuple[torch.Tensor, torch.Tensor], alpha: float = 1.0) -> Tuple: data, targets = batch indices = torch.randperm(data.size(0)) shuffled_data = data[indices] shuffled_targets = targets[indices] lam = np.random.beta(alpha, alpha) if alpha > 0 else 1 x0, x1, y0, y1 = random_bbox(data, lam) data[:, :, y0:y1, x0:x1] = shuffled_data[:, :, y0:y1, x0:x1] targets = (targets, shuffled_targets, lam) return data, targets
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cutmix(input: T, *args: Any, **kwargs: Any) -> T:\n ...", "def cut_sig(self):\n c = TCut(self.cut_both)\n c += TCut(self._return_if('_cut_sig'))\n return c", "def Cut(self, *args):\n return _BRepAlgo.BRepAlgo_BooleanOperations_Cut(self, *args)", "def cut_bkg(self):\n ...
[ "0.7247407", "0.6177565", "0.60966194", "0.60773325", "0.6003204", "0.5993062", "0.59929186", "0.59459716", "0.58568937", "0.5730637", "0.5683153", "0.5636909", "0.5531246", "0.550214", "0.54731303", "0.5415715", "0.54061943", "0.5387309", "0.5360789", "0.5356992", "0.5317929...
0.51037717
41
Constructor Class for MixCriterion.
def __init__(self, criterion: Callable): self.criterion = criterion
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.condition = None", "def __init__(self, **kwargs: Any):\n self.multiclass_te_co = 3\n self.top_intersections = 5\n self.max_intersection_depth = 3\n self.subsample = 10000\n self.random_state =...
[ "0.6095481", "0.60818535", "0.60206497", "0.60206497", "0.5973565", "0.5949284", "0.5945663", "0.57841676", "0.5744737", "0.5706614", "0.56997925", "0.5673495", "0.5635301", "0.5579832", "0.5573683", "0.55335826", "0.55186737", "0.5517108", "0.5516155", "0.5516155", "0.551615...
0.6339344
0
Method to calculate loss.
def __call__(self, preds: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: if isinstance(targets, (list, tuple)): target_a, target_b, lam = targets loss = lam * self.criterion(preds, target_a) + (1 - lam) * self.criterion(preds, target_b) else: loss = self.criterion(preds, targets) return loss
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute_loss(self):", "def compute_loss(self, **kwargs):\n raise NotImplementedError", "def _compute_loss(self, parameters, inputs, ground_truth):\n predictions = self.network_forward(parameters, inputs)\n loss = np.mean((ground_truth - predictions) ** 2)\n return loss", "def ...
[ "0.8619422", "0.8097837", "0.8058278", "0.8058278", "0.8057582", "0.80512774", "0.80417025", "0.80136496", "0.80118436", "0.80016685", "0.7976173", "0.7873951", "0.78684396", "0.7850407", "0.7773674", "0.7736192", "0.773443", "0.7730767", "0.7681916", "0.7677627", "0.7675766"...
0.0
-1
Constructor for CustomCollate class.
def __init__(self, mixer: Callable, alpha: float = 1.0): self.alpha = alpha self.aug = mixer
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, *args, **kwargs):\n super(AudioDataLoader, self).__init__(*args, **kwargs)\n self.collate_fn = _collate_fn", "def __init__(self, **kwargs):\n super(Converter, self).__init__()\n self._specfile = kwargs.get(\"specfile\", None)\n self._parsed = False\n s...
[ "0.64296454", "0.6141736", "0.59631157", "0.59013855", "0.5901021", "0.5887784", "0.5874038", "0.58196646", "0.5807004", "0.57944214", "0.5786476", "0.57478714", "0.5736771", "0.57238066", "0.57140934", "0.5711623", "0.5707364", "0.56902254", "0.5678276", "0.5651362", "0.5638...
0.0
-1
Method to create collate_fn for dataloader.
def get_collate_fn(mixer_name: str, alpha: float) -> Callable: fn = cutmix if mixer_name == "cutmix" else mixup collate_fn = CustomCollate(alpha=alpha, mixer=fn) return collate_fn
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _init_collate(self, cfg: ConfigType) -> Callable:\n try:\n with FUNCTIONS.switch_scope_and_registry(self.scope) as registry:\n collate_fn = registry.get(cfg.test_dataloader.collate_fn)\n except AttributeError:\n collate_fn = pseudo_collate\n return coll...
[ "0.72403246", "0.6569447", "0.6355525", "0.6254008", "0.6132644", "0.59491956", "0.58509344", "0.58122337", "0.57363015", "0.57224447", "0.5562954", "0.55518824", "0.55403864", "0.5461661", "0.54195124", "0.54195124", "0.53915864", "0.53042173", "0.526494", "0.52282083", "0.5...
0.6172216
4
Loads yaml file. Arguments
def load(path: str='config.yaml'): file = Path(path).open() result = yaml.safe_load(file) debug(f'YAML file {path} loaded and parsed succesful') return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def loadFromFile(self,filename):\n path = os.path.dirname(__file__)+\"/\"+filename\n if os.path.exists(path) and os.path.isfile(path):\n self.load(yaml.load(open(path, 'r')))", "def load_yaml(filename):\n try:\n f = file(filename, 'r')\n data = yaml.load(f)\n return data\n e...
[ "0.77729696", "0.7398894", "0.73696256", "0.73671806", "0.7323886", "0.7295187", "0.7261868", "0.72600996", "0.7254409", "0.72472084", "0.722904", "0.7219554", "0.7214941", "0.7211812", "0.7204388", "0.716829", "0.7168116", "0.71676886", "0.71614975", "0.7131892", "0.71218497...
0.6669963
61
Reads from file environment.yaml values and changes environment variables.
def change_environment_variables(): values = load('environment.yaml') for key in values.keys(): os.environ[key] = values[key] info(f'Changed environment variables to {values}')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_evironment():\n environment = Utility.load_yaml(os.getenv(\"system_file\", \"./system.yaml\"))\n for key in environment:\n if key in os.environ:\n environment[key] = os.getenv(key)\n Utility.environment = environment", "def load_envs_from_file(file_path=con...
[ "0.7406269", "0.69363457", "0.66602415", "0.6634683", "0.65131164", "0.64999026", "0.649091", "0.6366587", "0.63470614", "0.6244345", "0.61629504", "0.6037942", "0.6028842", "0.5990134", "0.5982547", "0.59603816", "0.59407336", "0.59406185", "0.5874832", "0.5864534", "0.58374...
0.8063575
0
Initialize the Referee. Creates a turn order based on the ages of the players. If none of the players given have colors, then colors are assigned to the players. Otherwise, the colors of the players are used. If the players have colors, then they must be unique. Creates a Fish game board for the players to play on.
def __init__(self, players, board_size, board=None, timeout=10): if not 2 <= len(players) <= 4: raise ValueError("Invalid number of players provided.") if board is None: board = Board(*board_size) self.__check_board_is_valid(board, players) self.board = board self.__set_colors(players) self.players = {p.get_color(): p for p in players} self.state = State([BoardPlayer(p.get_color()) for p in players], board) self.violators = [] self.timeout = timeout
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, player1, player2):\n # # players of the game {player1name: {color: , red_marbles:}}\n # self._players = {player1[0]: {\"name\": player1[0], \"color\": player1[1]},\n # player2[0]: {\"name\": player2[0], \"color\": player2[1]}}\n # # empty board, no m...
[ "0.7091265", "0.7042805", "0.6867666", "0.6535027", "0.6531117", "0.6422226", "0.6401937", "0.6389531", "0.6383958", "0.6380879", "0.6368232", "0.63284415", "0.6323319", "0.63110787", "0.6310818", "0.6294931", "0.6289826", "0.6264066", "0.62364113", "0.62338966", "0.6192807",...
0.6177999
21
Check that the board used is large enough and has enough valid tiles for the given list of players, raises a ValueError if any of these conditions are not met.
def __check_board_is_valid(self, board, players): total_tiles = board.get_rows() * board.get_cols() # check the board is big enough if total_tiles < (6 - len(players)) * len(players): raise ValueError("Board specified by board_size is too small.") # check that the board has enough active tiles if len(players) == 3 and total_tiles - board.get_holes_in_board() < 9: raise ValueError("Too many holes to place all penguins") elif total_tiles - board.get_holes_in_board() < 8: raise ValueError("Too many holes to place all penguins")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_valid_board(board):\n valid = len(board) == 9\n valid &= -1 <= sum(board) <= 1\n valid &= reduce(lambda x, y: x and y, [utils.is_valid_player(p) for p in board])\n return valid", "def test_generate_board_too_many_mines_errors(self):\n # arrange\n game = minesweeper.Minesweeper()\...
[ "0.6559245", "0.65429807", "0.6363457", "0.63405097", "0.6310487", "0.61935323", "0.61810786", "0.61345714", "0.60889655", "0.6072533", "0.5982412", "0.5976069", "0.5964283", "0.59554005", "0.5949775", "0.59412664", "0.59252197", "0.5920554", "0.59201723", "0.5910528", "0.589...
0.8507374
0
Set the colors of the players, if needed. If all players have unique colors, return the players asis.
def __set_colors(self, players): colors = set() for p in players: if p.get_color() is None: continue colors.add(p.get_color()) if len(colors) != 0 and len(colors) != len(players): raise ValueError("Each player does not have a unique assigned color.") if len(colors) == 0: for i, p in enumerate(players): p.set_color(BoardPlayer.POSSIBLE_COLORS[i])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_player_colors() -> List[Tuple[float, float, float]]:\n return PLAYER_COLORS", "def init_players(self):\n complain = \"\"\n players_turn = random.sample(range(self.n_players), self.n_players)\n players_created = {}\n picked_colors = []\n for x in range(self.n_players)...
[ "0.6983501", "0.661778", "0.65605044", "0.6559854", "0.65476024", "0.65333056", "0.64143264", "0.613175", "0.6107858", "0.60999984", "0.6061564", "0.59373385", "0.58590215", "0.58403534", "0.58192056", "0.57921976", "0.5781316", "0.5771787", "0.5770856", "0.5764907", "0.57404...
0.848916
0
Remove a player of a given color from the game along with his penguins and add him to the violator list.
def __remove_player(self, color): self.state.remove_player(color) self.violators.append(self.players[color])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def removePlayer(self, color):\n if type(color) not in (player.Player, int):\n raise TypeError(\"Input to removePlayer must be of type int or Player.\")\n if type(color) is player.Player:\n color = color.getColor()\n if color not in self.__colordict__:\n raise ...
[ "0.7096801", "0.6246487", "0.6242192", "0.59200877", "0.5919842", "0.5817426", "0.57871246", "0.57752347", "0.57319325", "0.57220024", "0.57121086", "0.5706811", "0.5705507", "0.5691792", "0.56409585", "0.564011", "0.5619549", "0.5613825", "0.55753464", "0.5562794", "0.551482...
0.8311631
0
Helper to put threaded function return value in a queue. Puts None in the queue if an exception occurs.
def __player_thread(self, func, arg, queue): try: queue.put(func(arg)) except Exception as exc: #print(exc) queue.put(None)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ReturnWrapper(queue, fn):\n queue.put(fn())", "def queue_wrapper(result_queue, wid,\n func, args):\n result_queue.put((wid, func(*args)))", "def putting_on_queue(*args):\n results.put(main_func(*args))", "def run(self, arg: _T) -> queue.Queue[Tuple[Optional[_R], Optional[Excepti...
[ "0.77862006", "0.6819761", "0.63104945", "0.62345034", "0.61928016", "0.6103177", "0.6083798", "0.6009036", "0.593441", "0.5919444", "0.59155446", "0.5880543", "0.58595", "0.58402306", "0.5773026", "0.5739314", "0.57106704", "0.5703303", "0.56909806", "0.5687329", "0.5681928"...
0.7133484
1
Perform a single turn of the game of fish. If the game is over, the function exits before the referee makes any calls to the game state.
def run_turn(self): all_placed = self.state.all_avatars_placed() color = self.__get_next_turn(all_placed) if color is None: return if not all_placed: # placement round func = self.players[color].make_placement else: # movement round func = self.players[color].make_move queue = Queue() thread = Thread(target=self.__player_thread, args=[func, deepcopy(self.state), queue]) thread.daemon = True thread.start() thread.join(self.timeout) if thread.is_alive(): #print("The " + str(color) + " player timed out and will be removed.") self.__remove_player(color) return action = queue.get() if action == None: #print("The " + str(color) + " player crashed and will be removed.") self.__remove_player(color) return if not all_placed: if self.state.valid_placement(action, color): self.state.place_avatar(action, color) else: #print("The " + str(color) + " player has attempted an invalid placement and will be removed.") self.__remove_player(color) else: if self.state.valid_move(*action): self.state.move_avatar(*action) else: #print("The " + str(color) + " player has attempted an invalid move and will be removed.") self.__remove_player(color)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run(self):\n while True:\n if self.is_game_over():\n break\n self.run_turn()", "def run(self):\n while not self.turn_over:\n self.go()", "def play_game(self):\n # need everyone to pass to move to next phase?\n self.deal_cards()...
[ "0.70215684", "0.6675281", "0.6568159", "0.6531183", "0.6502724", "0.6469548", "0.6381622", "0.63657147", "0.6328124", "0.6289508", "0.62504184", "0.62501085", "0.6250065", "0.6247987", "0.62212396", "0.61608124", "0.6129432", "0.6125374", "0.6121029", "0.6068085", "0.6057488...
0.0
-1
Pass the turn in the current game state to the next player. Return the color of the player, or None if the game is over.
def __get_next_turn(self, all_placed): game_over = self.is_game_over() if all_placed: if game_over: return None else: self.state.pass_turn_if_applicable() color = self.state.whose_turn().get_color() return color
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getTurn(self):\r\n return self.players[self.getCurrentPlayer()].getColor()", "def user_to_move_in_game(game):\n if game.finished:\n return None\n black_or_white = go.next_color(game.sgf)\n next_in_game = {go.Color.black: game.black,\n go.Color.white: game.white}[black...
[ "0.7333892", "0.70925194", "0.6907869", "0.68132323", "0.6679578", "0.6647104", "0.6575999", "0.65741646", "0.6515778", "0.64863414", "0.6473067", "0.63014096", "0.6287772", "0.62448686", "0.6174598", "0.6149186", "0.61185074", "0.598921", "0.592801", "0.589623", "0.58790624"...
0.69213134
2
Begin the game of Fish. The referee will begin the game and start taking moves from players. The game will continue until it has ended. Players who attempt invalid placements or movements, take too long to respond, or otherwise crash will be ejected from the game and their penguins will be removed.
def run(self): while True: if self.is_game_over(): break self.run_turn()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def play_game(self):\n # need everyone to pass to move to next phase?\n self.deal_cards()\n self.plant_food()", "def start_game(self):\n while self.can_deal:\n self.take_turn()", "def start(self):\n self.save_checkpoint(\"setup\")\n\n logging.info(\"Starting gam...
[ "0.63546705", "0.59987706", "0.5944259", "0.5863334", "0.58432084", "0.5839499", "0.5821344", "0.5808416", "0.57779545", "0.5738902", "0.57381016", "0.5735922", "0.5734481", "0.57334346", "0.5728595", "0.5717012", "0.5702629", "0.5669737", "0.5666819", "0.5664399", "0.5663105...
0.5274436
86
Get the player scores.
def get_scores(self): return [(self.players[p.get_color()], p.get_score()) for p in self.state.get_players()]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_scores(self):\n return self.score", "def get_score(self, player):\n if player in self.player_scores:\n return self.player_scores[player]\n else:\n raise Exception(\"Player not in score list\")", "def score(self):\n return self.client.call('GET', self.na...
[ "0.81142956", "0.7553951", "0.738606", "0.7267321", "0.719919", "0.71760154", "0.7120312", "0.704196", "0.6985496", "0.6970983", "0.6936181", "0.6799197", "0.6795344", "0.6784494", "0.6777752", "0.67771673", "0.6773122", "0.6722797", "0.6709587", "0.66867256", "0.66849506", ...
0.8255623
0
Get the victor(s) if the game is over. Players in the violators list are not eligible for victory.
def get_victors(self): if self.is_game_over(): scores = [p.get_score() for p in self.state.get_players()] if len(scores) == 0: return [] max_score = max(scores) victors = [] for p in self.state.get_players(): if p.get_color() not in self.violators and p.get_score() == max_score: victors.append(self.players[p.get_color()]) return victors else: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def CheckVictoryCondition(self):\n opponentVictory = True\n for char in self.screen.characters:\n if char.team == 1 and char.leader and not char.dead:\n opponentVictory = False\n if opponentVictory:\n self.screen.refresh()\n self.music.stop()\n ...
[ "0.59914505", "0.5907969", "0.58250535", "0.5708909", "0.5472831", "0.54458094", "0.5445035", "0.5442779", "0.5384571", "0.5359108", "0.5300459", "0.5299243", "0.5299243", "0.5279039", "0.52614534", "0.52344775", "0.5208366", "0.5185099", "0.5184724", "0.5178754", "0.516631",...
0.75721735
0
Is the game over?
def is_game_over(self): return self.state.all_avatars_placed() and self.state.is_game_over()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def isGameOver(self):\n pass", "def gameOver(self):\n\t\treturn self.lives == 0", "def is_game_over(self):\r\n\r\n if self.winner != 0:\r\n return True\r\n\r\n return False", "def game_over(self) -> bool:\n return self.rstate.game_over()", "def is_game_over(self) -> bool:\n ...
[ "0.88837326", "0.83810914", "0.83710665", "0.8281846", "0.82191014", "0.8210489", "0.82002926", "0.80712324", "0.80512774", "0.8045562", "0.7989821", "0.79308355", "0.7928047", "0.7927743", "0.7903066", "0.7842491", "0.7819719", "0.77655524", "0.77628475", "0.7760699", "0.775...
0.7849975
15