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
does this source image have any face alts yet
def hasAnyFaces(self, uri): return self.graph.queryd( 'ASK { ?uri pho:alternate ?alt . ?alt pho:tag "face" .}', initBindings={'uri':uri})
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def has_faces(self):\n return len(self._faces) > 0", "def check_availability(img_path):\n # loading gray image\n gray_image = cv2.imread(img_path, 0)\n\n # check whether img give empty list or not\n flag = face_recognition.face_locations(gray_image)\n if flag:\n return True\n retu...
[ "0.7674138", "0.72298473", "0.7020681", "0.6924796", "0.6771849", "0.67457414", "0.67417926", "0.66322297", "0.6547639", "0.6388487", "0.6315418", "0.6311557", "0.62890303", "0.6275695", "0.6254575", "0.62504184", "0.62351817", "0.6222348", "0.6187851", "0.6173235", "0.615440...
0.6130096
22
A helper function to getnerate quaternions from yaws.
def heading(yaw): q = euler2quat(0.0, 0.0, yaw) quat = Quaternion() quat.w = q[0] quat.x = q[1] quat.y = q[2] quat.z = q[3] return quat
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def euler_from_quaternion(x, y, z, w):\n t0 = +2.0 * (w * x + y * z)\n t1 = +1.0 - 2.0 * (x * x + y * y)\n roll_x = math.atan2(t0, t1)\n \n t2 = +2.0 * (w * y - z * x)\n t2 = +1.0 if t2 > +1.0 else t2\n t2 = -1.0 if t2 < -1.0 else t2\n pitch_y = math.asin(t2)\n ...
[ "0.5886946", "0.5821129", "0.57884336", "0.5761411", "0.57510763", "0.56554824", "0.55509216", "0.5486164", "0.5485171", "0.5455863", "0.5419014", "0.5404133", "0.53984076", "0.5394962", "0.53919274", "0.5354592", "0.5353793", "0.5328789", "0.5326809", "0.5319791", "0.5303704...
0.47717264
84
Search the corresponging page
def extract_table(path): re_ex = RE_EX pages = [] page_num = 1 with open(path, 'rb') as in_file: parser = PDFParser(in_file) doc = PDFDocument(parser) for page in PDFPage.create_pages(doc): rsrcmgr = PDFResourceManager() output_string = StringIO() device = TextConverter(rsrcmgr, output_string, laparams=LAParams()) interpreter = PDFPageInterpreter(rsrcmgr, device) interpreter.process_page(page) finder = re.search(re_ex, output_string.getvalue(), re.IGNORECASE) print('Searching table', '\tCurrent page:', page_num) if finder: print('Table finded.') pages.append(page_num) break page_num += 1 table = extract_text(path, pages) table = isolate(table) table = add_separations(table) return table
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def search_page(request):\n if request.method == \"GET\":\n page = request.GET.get('q')\n entries = util.list_entries()\n entries_set=set(entries)\n\n if page in entries_set:\n return render(request, \"encyclopedia/visit_entry.html\",{\n \"entry\": util.get...
[ "0.68104583", "0.6787762", "0.6677038", "0.6644082", "0.6601781", "0.65885496", "0.6568652", "0.64640963", "0.64026564", "0.6390516", "0.63853854", "0.6381454", "0.6347054", "0.63387513", "0.63099885", "0.62858623", "0.62771076", "0.6269942", "0.6268018", "0.6258665", "0.6254...
0.0
-1
Extract Raw text from PDF
def extract_text(path, pages): out = [] with open(path, 'rb') as file: pdftotext_string = pdftotext.PDF(file) for i in pages: out.append(pdftotext_string[i - 1]) return out
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extract_pdf(path):\n\n #only reading from pdf files\n\n text = textract.process(filename = path, encoding = \"ascii\")\n\n\n text.replace(\"\\n\", \" \")\n text.replace(\"\\t\", \" \")\n text.replace(\"\\r\", \" \")\n filter(lambda x: x in set(string.printable), text)\n\n return text", "...
[ "0.77171206", "0.75832546", "0.7520995", "0.7419466", "0.7063826", "0.7058838", "0.7054497", "0.7044647", "0.6961371", "0.681999", "0.6804874", "0.67496186", "0.6660395", "0.6636881", "0.66142976", "0.6598252", "0.65733755", "0.64733654", "0.64633906", "0.645397", "0.64384454...
0.6915857
9
A bad way to add row separations
def add_separations(pages, space_tolerance=3): return re.search(r' *ID +([\d|\.]+) *', pages[0]).groups()[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clean_row(row,i):\n # convert string\n char_array = np.array(list(row))\n\n #insert entry dividers, then split by them\n div_ix = (\n np.array([6, 34, 48, 51, 54, 60, 64, 67, 72, 80, 86, 94, 100,\n 107, 112, 119, 125, 137, 141, 145, 156]),\n )\n char_array[div_ix] = ',...
[ "0.62396944", "0.61622435", "0.5958048", "0.5942915", "0.5919921", "0.59172857", "0.5905476", "0.58589554", "0.5857645", "0.58561033", "0.58199805", "0.57991666", "0.57600623", "0.5754019", "0.5714601", "0.56919146", "0.5561975", "0.5558327", "0.5547988", "0.5547977", "0.5522...
0.0
-1
Save the DataSets as CSV
def save_datasets(ds, pdf_name, directory=''): print(f'{directory}{pdf_name.split("/")[-1].replace(".pdf", "")}_0..{len(ds)}.csv') list(map( lambda tb: tb[1].to_csv( f'{directory}{pdf_name.split("/")[-1].replace(".pdf", "")}_{tb[0]}.csv', index=False), enumerate(ds)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_to_csv(self):\n path = partial(os.path.join, 'datasets')\n save_name = self.name.lower().replace(' ', '_')\n self.df['values'].sum(axis=1).to_csv(path('{0}_values.csv'.format(save_name)))\n self.df['allocations'].to_csv(path('{0}_allocations.csv'.format(save_name)))\n se...
[ "0.7957732", "0.79157484", "0.7566766", "0.7396046", "0.73250043", "0.7290871", "0.72067684", "0.71864974", "0.71633387", "0.7068782", "0.7042488", "0.7025496", "0.70245546", "0.69767153", "0.69759953", "0.69569284", "0.69508433", "0.69366264", "0.68940073", "0.68940073", "0....
0.6633306
39
Extract a table from a pdf file and save the resulting dataset
def extract_and_save(file_path, out_dir=''): save_datasets( extract_table(file_path), file_path, out_dir)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extract_table(path):\n re_ex = RE_EX\n pages = []\n page_num = 1\n with open(path, 'rb') as in_file:\n parser = PDFParser(in_file)\n doc = PDFDocument(parser)\n for page in PDFPage.create_pages(doc):\n rsrcmgr = PDFResourceManager()\n output_string = Strin...
[ "0.7241174", "0.6659181", "0.65428925", "0.6456565", "0.63844985", "0.6363576", "0.6349044", "0.6338092", "0.6214082", "0.6197532", "0.6154468", "0.6104792", "0.6099473", "0.60386115", "0.6013377", "0.6007071", "0.60045767", "0.59880614", "0.595533", "0.5941718", "0.5934649",...
0.5661401
33
Create instance of PyRPS. redis_url Redis instance address (tuple containing (hostname, port)). namespace Namespace to separate Pub/Sub instance from another running on the same redis host.
def __init__(self, namespace, redis_url=("localhost", 6379)): self.namespace = namespace if isinstance(redis_url, tuple): self.redis = StrictRedis(host=redis_url[0], port=redis_url[1]) elif isinstance(redis_url, str): self.redis = StrictRedis(host=redis_url)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def connect_to_redis():\n return Redis(host=redis_host, port=redis_port, db=0)", "def __init__(self):\n try:\n config = redis_settings[\"REDIS_BACKEND\"]\n self.servers = config[\"servers\"]\n self.port = config[\"port\"]\n self.db = config[\"db\"]\n ...
[ "0.65858567", "0.6510327", "0.6420053", "0.6199663", "0.6159909", "0.61511815", "0.6020774", "0.5985737", "0.593212", "0.5925699", "0.5880181", "0.5879944", "0.5878096", "0.5852507", "0.5827931", "0.5803593", "0.5802949", "0.5757128", "0.56726545", "0.56652087", "0.5645896", ...
0.7303635
0
Subscribe to message queue. Yields messages as they appear in the queue. queue Queue name consumer_id Consumer name
def subscribe(self, queue, consumer_id): # Add myself to the list of consumers, if not already present. self.redis.sadd(self._ns_subscriptions(queue), consumer_id) return Subscription(self, queue, consumer_id)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def next_message(self):\n while self.queue.consuming:\n yield self.queue.channel._consume_message()", "def _consume(self):\n # HACK: run_in_executor is used as a workaround to use boto\n # inside a coroutine. This is a stopgap solution that should be\n # replaced once boto ...
[ "0.70663434", "0.70589", "0.6912972", "0.6792425", "0.67885274", "0.67721105", "0.67194426", "0.6707331", "0.6677362", "0.66220254", "0.6612172", "0.65917623", "0.64961404", "0.64757645", "0.6447494", "0.64265627", "0.6415559", "0.63817006", "0.6365126", "0.6331941", "0.63177...
0.6136618
27
Publish new message into queue. queue Queue name. message Message data. ttl How long the message should stay alive.
def publish(self, queue, message, ttl=3600): # Get next message ID message_id = self.redis.incr(self._ns_nextid()) # Push message to queue self.redis.setex(self._ns_message(queue, message_id), ttl, message) # List all consumers of given queue consumers = self.redis.smembers(self._ns_subscriptions(queue)) # Publish the message to all the consumers. for consumer in consumers: self.redis.rpush(self._ns_queue(queue, consumer), message_id)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def publish(self, queue, message):\n\n # Instead of passing a queue to the constructor, the publish checks if\n # the target queue exists. If not, it declares the target queue\n if not self.queue:\n self.channel.queue_declare(queue=queue)\n self.queue = queue\n\n s...
[ "0.66769063", "0.6397617", "0.627912", "0.61567104", "0.60542965", "0.5991828", "0.5984815", "0.59224325", "0.59119457", "0.5885555", "0.58437407", "0.5831145", "0.5831145", "0.57749146", "0.5731569", "0.572015", "0.57037824", "0.5698528", "0.5670229", "0.56518567", "0.563889...
0.81558275
0
Convinience method to retrieve names of redis keys including configured namespace.
def _ns(self, *args): return "%s.%s" % (self.namespace, ".".join([str(arg) for arg in args]))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def keys(self, redis_key: str):\n for k in self.client.keys(pattern=\"{}*\".format(redis_key)):\n deserialized_key = k.decode('utf-8')\n print(deserialized_key)", "def get_keys(self):\r\n\t\tlogger.debug(\"Getting the keys\")\r\n\t\t\r\n\t\treturn db.get_items('keys')", "async def ...
[ "0.6998844", "0.6847791", "0.6734126", "0.6710756", "0.6708418", "0.6673107", "0.6638886", "0.66124463", "0.6578463", "0.6555136", "0.64906746", "0.6471968", "0.6448839", "0.64258033", "0.63986486", "0.6351491", "0.63383114", "0.63130385", "0.631087", "0.6308451", "0.626402",...
0.0
-1
Return key for subscribers list for given queue.
def _ns_subscriptions(self, queue): return self._ns(queue, "consumers")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def key_for_name(name):\n return 'hotqueue:%s' % name", "def QueueId(self):\n\t\treturn self._get_attribute('queueId')", "def get_queue_items(self, queue_name):\n proc = start_proc([\"/usr/bin/sudo\", \"rabbitmqctl\", \"list_queues\"],\n shell=False)\n for ...
[ "0.6073377", "0.5581305", "0.55699074", "0.5561635", "0.55190897", "0.5469011", "0.540408", "0.5387118", "0.5387118", "0.5283115", "0.5264972", "0.5261164", "0.52112347", "0.51992536", "0.5160349", "0.5156108", "0.51445335", "0.5114686", "0.5114686", "0.5114686", "0.5114686",...
0.5925365
1
Return key for nextid counter.
def _ns_nextid(self): return self._ns("nextid")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def next_id(self):\n self.id_counter += 1\n return self.id_counter - 1", "def _GetNextId(self):\r\n ret = self.next_id\r\n self.next_id += 1\r\n return str(self.next_id)", "def next_id(self):\n next_id = self._nextid\n self._nextid += 1\n return next_id", "def getN...
[ "0.75374943", "0.7502265", "0.75013953", "0.7485256", "0.7304283", "0.72980666", "0.7239975", "0.7237588", "0.7237588", "0.7187678", "0.7133712", "0.71068776", "0.70844835", "0.7051308", "0.6975568", "0.69365454", "0.6920834", "0.6917348", "0.6893729", "0.68801874", "0.686860...
0.7051454
13
Return key for retrieving message.
def _ns_message(self, queue, message_id): return self._ns(queue, "messages", message_id)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_key(self):\n return self.key", "def get_key(self):\n return self.key", "def getKey(self):\n\t\treturn self.key", "def get_key(self):\n return self._determine_key()", "def getKey(self):\n return self.key", "def _GetKeyString(self):\n return self.__key_string", ...
[ "0.7373115", "0.7373115", "0.7311321", "0.730466", "0.7236075", "0.7196054", "0.7191205", "0.717894", "0.7138465", "0.7134151", "0.71263784", "0.7073601", "0.7052514", "0.70436716", "0.6997047", "0.6997047", "0.6997047", "0.6997047", "0.6997047", "0.6997047", "0.6997047", "...
0.0
-1
Return key for queue for one consumer.
def _ns_queue(self, queue, consumer_id): return self._ns(queue, consumer_id, "messages")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def key_for_name(name):\n return 'hotqueue:%s' % name", "def QueueId(self):\n\t\treturn self._get_attribute('queueId')", "def get_queue(self, task_name):\n for name, queue in self.queues.items():\n if task_name in queue:\n return name\n return self.default_queue", "...
[ "0.6709878", "0.6203875", "0.61977", "0.6167725", "0.61443627", "0.6122787", "0.61105525", "0.60962135", "0.60959727", "0.6090235", "0.6011632", "0.6011632", "0.59730965", "0.59651434", "0.5943122", "0.59121245", "0.59014606", "0.588179", "0.5877485", "0.5872953", "0.5849946"...
0.5564891
89
Create instance of Subscription. Do not call directly, use pyrps.subscribe().
def __init__(self, pyrps, queue, consumer_id): self.pyrps = pyrps self.queue = queue self.consumer_id = consumer_id
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def subscribe(receiver):", "def subscribe(receiver):", "def subscribe(receiver):", "def subscribe(self, subject):\n pass", "def subscribe(self, **subscription_request):\n return self.subscribe_impl(mode='subscribe', **subscription_request)", "def subscription(self, uuid):\r\n return ...
[ "0.70819134", "0.70819134", "0.70819134", "0.7014957", "0.6897221", "0.6896531", "0.68738085", "0.68679523", "0.68197066", "0.6760519", "0.6746346", "0.6731105", "0.6678667", "0.6670081", "0.6621244", "0.6589251", "0.6571883", "0.654773", "0.6535721", "0.6527079", "0.65072304...
0.0
-1
Wait for message to arrive and return it. Blocks if there is no message availalbe.
def consume(self, block=True, timeout=0): # We need to repeat this step, because there may be messages # that expired, and we expect this method to always return message. while True: # Retrieve last message ID if block: # Blocking query, wait until message is available. message_id = self.pyrps.redis.blpop(self.pyrps._ns_queue(self.queue, self.consumer_id), timeout) # blpop returns tuple(key, value), we need only value. message_id = message_id[1] else: # Non blocking query. Return if there is no message in queue. message_id = self.pyrps.redis.lpop(self.pyrps._ns_queue(self.queue, self.consumer_id)) # If there is no message in the queue, return None. if message_id is None: return None # Retrieve the message message = self.pyrps.redis.get(self.pyrps._ns_message(self.queue, message_id)) # If message still exists (no TTL has been reached), return it. if message is not None: return message
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def wait_for_messages(self):\n msg = self.inbox.get()\n return msg", "def wait_message(self):\n if self._state != states['open']:\n return False\n if len(self._read_queue) > 0:\n return True\n\n assert self._read_waiter is None or self._read_waiter.cancell...
[ "0.78191537", "0.7661847", "0.7064476", "0.69554555", "0.69036627", "0.68705696", "0.6781577", "0.6720875", "0.66924024", "0.66924024", "0.66751784", "0.6674056", "0.6660193", "0.6631681", "0.66040105", "0.6603838", "0.6585064", "0.65825886", "0.65714115", "0.6550374", "0.652...
0.60150254
67
Unsubscribe from message queue and destroy it. Do not call if you want persistent queues or if you access one queue from multiple processes.
def unsubscribe(self): # Unsubscribe self.pyrps.redis.srem(self.pyrps._ns_subscriptions(self.queue), self.consumer_id) # Remove message queue self.pyrps.redis.delete(self.pyrps._ns_queue(self.queue, self.consumer_id))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy_queue(self):\n response = self.queue.delete()\n if self._is_error_call(response):\n raise RuntimeError('SQS could not delete queue: %s' % response)\n self.queue, self.queue_name = None, None", "def __clear_message_queue(self):\r\n self.__lib.CC_ClearMessageQueue...
[ "0.7262633", "0.6581309", "0.6575992", "0.6442243", "0.6403433", "0.63751954", "0.63708746", "0.63472867", "0.6332669", "0.6327779", "0.6296495", "0.6264714", "0.6237197", "0.61690885", "0.61690885", "0.61690885", "0.61690885", "0.61690885", "0.61083573", "0.6106147", "0.6098...
0.8235168
0
Setup shapes and sprites (if we had any) and initialise the game class
def setup(self): # Create your sprites and sprite lists here self.game: Game = Game(SCREEN_WIDTH, SCREEN_HEIGHT, TILE_SIZE, 1, grid_layers = 4) self.game.game_message = "Lead the Rabbit home" # show the menu so that we see the instructions self.game.menu.button_list[0].text = "Start" self.game.menu.is_visible = True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setup(self):\n\n # Create the Sprite lists\n self.sprite_list = arcade.SpriteList()\n\n r = 60\n for x in rand_range(0, 100 * math.pi, scale=math.pi / 5):\n star = arcade.Sprite(\"../../resources/arcade/gold_1.png\")\n star.center_x = SCREEN_WIDTH / 2 + r * mat...
[ "0.726422", "0.72362995", "0.72362995", "0.721465", "0.7195567", "0.71046937", "0.7090733", "0.7078919", "0.70652205", "0.7000575", "0.6993204", "0.6991222", "0.6986432", "0.6951341", "0.69142735", "0.69040245", "0.68818647", "0.6844078", "0.6843965", "0.68359494", "0.6834616...
0.7013884
9
Instead of rendering each wall block, we create a single shape which can be drawn in a single call, rather than a call for each wall block
def create_wall_shape(self): self.shape_walls = arcade.ShapeElementList() self.shape_walls.center_x = 0 self.shape_walls.center_y = 0 self.shape_walls.angle = 0 point_list = [] color_list = [] # create the walls into a single shape walls = self.game.walls for wall in walls: points = self.get_entity_dimensions(wall) point_list.append(points[0]) point_list.append(points[1]) point_list.append(points[2]) point_list.append(points[3]) # as we have 4 points for i in range(4): color_list.append(COLOUR_MAP[wall.base_colour]) self.shape_walls.append( arcade.create_rectangles_filled_with_colors(point_list, color_list) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_walls(self):\n for x in range(self.width):\n self.add_thing(Wall(), (x, 0))\n self.add_thing(Wall(), (x, self.height - 1))\n\n for y in range(self.height):\n self.add_thing(Wall(), (0, y))\n self.add_thing(Wall(), (self.width - 1, y))", "def _draw...
[ "0.6985171", "0.6947199", "0.689782", "0.6734781", "0.6710795", "0.67082715", "0.66530377", "0.6573703", "0.6563552", "0.64633447", "0.64461184", "0.6377385", "0.63731766", "0.63545173", "0.6318463", "0.63116866", "0.6260402", "0.62379223", "0.6211161", "0.61905986", "0.61559...
0.7463419
0
Remap the coordinates from the grid to positions required by arcade. As 0,0 is the bottom left position in arcade, but the grid see's 0,0 as top left
def get_entity_dimensions(self, entity: Entity): top_left = list(entity.top_left) top_left[1] = SCREEN_HEIGHT - top_left[1] top_right = list(entity.top_right) top_right[1] = SCREEN_HEIGHT - top_right[1] bottom_left = list(entity.bottom_left) bottom_left[1] = SCREEN_HEIGHT - bottom_left[1] bottom_right = list(entity.bottom_right) bottom_right[1] = SCREEN_HEIGHT - bottom_right[1] return top_left, top_right, bottom_right, bottom_left
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gridalign(self):\n self.position.x = int(round(self.position.x))\n self.position.y = int(round(self.position.y))\n self.position.z = int(round(self.position.z))\n\n if self.fan:\n self.fan = (int(round(self.fan[0])),int(round(self.fan[1])),int(round(self.fan[2])))\n\n ...
[ "0.64815533", "0.6462513", "0.6450318", "0.6435964", "0.6428564", "0.6419576", "0.63170576", "0.626487", "0.6256797", "0.61810344", "0.618049", "0.61792535", "0.6100417", "0.60906714", "0.60497826", "0.60250664", "0.60003793", "0.5986764", "0.59801954", "0.5972718", "0.596463...
0.0
-1
Create/Update the sprite shape for an entity and add/update the entry for it in `self.entities_shapelist`
def update_shape_sprite(self, entity: Entity): shape_sprite: ShapeSprite = entity.shape_sprite if entity.id not in self.entities_shapelist: entity_shapelist = arcade.ShapeElementList() # we need to convert from general colours to arcade specific colours entity_shapelist.append(arcade.create_rectangles_filled_with_colors( shape_sprite.point_list, [COLOUR_MAP[x] for x in shape_sprite.color_list]) ) else: entity_shapelist = self.entities_shapelist[entity.id] entity_shapelist.center_x = shape_sprite.position_x entity_shapelist.center_y = SCREEN_HEIGHT - shape_sprite.position_y entity_shapelist.draw() self.entities_shapelist[entity.id] = entity_shapelist
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_entity(self, entity: Entity):\n \n if entity.shape_sprite:\n return self.update_shape_sprite(entity)\n \n left = (entity.x - entity.half_width)\n right = (entity.x + entity.half_width)\n # because arcade 0 on y is the bottom of the screen not the top\n ...
[ "0.61834466", "0.58497405", "0.5760513", "0.5680979", "0.55177814", "0.5469176", "0.5436238", "0.54036695", "0.5392178", "0.5378375", "0.53718156", "0.53654325", "0.53457034", "0.5342032", "0.5310451", "0.5253857", "0.5238692", "0.52258265", "0.5207183", "0.52023184", "0.5193...
0.82262385
0
Draw the entity as a block, converting the y pixels values for 0,0 being bottom left not top left
def draw_entity(self, entity: Entity): if entity.shape_sprite: return self.update_shape_sprite(entity) left = (entity.x - entity.half_width) right = (entity.x + entity.half_width) # because arcade 0 on y is the bottom of the screen not the top bottom = abs((entity.y + entity.half_height) - SCREEN_HEIGHT) # bottom = entity.y - entity.half_height - SCREEN_HEIGHT top = abs((entity.y - entity.half_height) - SCREEN_HEIGHT) # top = entity.y + entity.half_height - SCREEN_HEIGHT arcade.draw_lrtb_rectangle_filled( left = left, right = right, bottom = bottom, top = top, color = COLOUR_MAP[entity.base_colour], )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_block(position, color):\n x = position.col*DX+DX+2\n y = position.row*DY+DY+2\n width = DX-4\n height = DY-4\n pygame.draw.rect(screen, color, (x,y,width,height), 0)", "def draw_block_element(self, cr, x, y):\n cr.rectangle(\n self.wall_width+x*self.block_size, \n ...
[ "0.67088455", "0.66308796", "0.6437608", "0.64263946", "0.6355193", "0.6322639", "0.6320987", "0.6217817", "0.6151702", "0.6137533", "0.61204463", "0.61078066", "0.60902894", "0.60667974", "0.5956826", "0.58381814", "0.5831373", "0.57956904", "0.5794884", "0.57708657", "0.576...
0.5946452
15
Draw a path for visual debugging
def draw_path(self, path): for path_point in path: arcade.draw_lrtb_rectangle_filled( left = path_point[0] - 3, right = path_point[0] + 3, bottom = abs(path_point[1] + 3 - SCREEN_HEIGHT), top = abs(path_point[1] - 3 - SCREEN_HEIGHT), color = COLOUR_MAP[Colour.YELLOW.value], )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_path(self):\r\n if len(self.path) > 1:\r\n for i in range(1, len(self.path)):\r\n pg.draw.line(self.screen, (0, 150, 0),\r\n self.path[i - 1], self.path[i], 1)\r\n elif len(self.path) == 1:\r\n pg.draw.circle(self.screen, (0, 1...
[ "0.8075153", "0.7686856", "0.7620524", "0.75897986", "0.7136921", "0.71321875", "0.7040748", "0.6928706", "0.6872046", "0.6816004", "0.6803802", "0.6753854", "0.6660338", "0.6658249", "0.66199154", "0.64800495", "0.64625716", "0.6392342", "0.6385967", "0.6356068", "0.63288015...
0.7506927
4
All the logic to move, and the game logic goes here. Normally, you'll call update() on the sprite lists that need it.
def update(self, delta_time): # Call draw() on all your sprite lists below game = self.game if game.exit: arcade.close_window() if not game.is_running: return # if level has changed redraw walls if self.game.level != self.last_level: self.reset_level() self.last_level = self.game.level if not game.update_game(delta_time): return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run_logic(self):\n if not self.game_over:\n # Move all the sprites\n self.all_sprites_list.update()", "def update(self):\n self.moving_sprites.update() \n self.static_sprites.update()\n self.camera.update(self.player)", "def update(self):\r\n if self...
[ "0.81336796", "0.7562641", "0.7411709", "0.73849124", "0.7197949", "0.7156386", "0.7143857", "0.7113507", "0.70476794", "0.7022667", "0.69586724", "0.695298", "0.6948688", "0.6880869", "0.6738882", "0.67356026", "0.6731809", "0.67010486", "0.6692721", "0.66918117", "0.6690588...
0.0
-1
Called whenever a key on the keyboard is pressed.
def on_key_press(self, key, modifiers): if not self.game.is_running: return if key == arcade.key.R: self.reset_level() try: game_key = KEY_MAP[key] except KeyError: return self.game.on_key_press(game_key)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _on_key_press(self, event):", "def on_key_event(self, key):\n pass", "def key_press_event(self, event):\n pass", "def _on_key_release(self, event):", "def keyPressEvent(self, event):\n self.game_engine.input_manager.keyPressEvent(event)", "def on_press(key):\n try:\n # ...
[ "0.84874815", "0.8405655", "0.82012695", "0.81760395", "0.80712044", "0.799939", "0.79385316", "0.7934922", "0.7907901", "0.79031485", "0.78694284", "0.77583754", "0.7742568", "0.76565206", "0.7616181", "0.7597726", "0.75769305", "0.7515888", "0.73805565", "0.73772943", "0.73...
0.69576883
54
Called whenever the user lets off a previously pressed key.
def on_key_release(self, key, modifiers): try: game_key = KEY_MAP[key] except KeyError: return self.game.on_key_release(game_key)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _on_key_release(self, event):", "def off(key):\n # print(\"{0} released\".format(key), time.perf_counter())\n\n global keys, esc_count\n\n # caps, shift, etc. aren't automatically registered as strings\n if type(key) == Key:\n keys[esc_count].append((str(key), time.perf_counter(), \"releas...
[ "0.75300187", "0.72335577", "0.7176089", "0.71289796", "0.70359325", "0.6950214", "0.6945082", "0.69241786", "0.6912116", "0.6841378", "0.6836066", "0.6817194", "0.6815543", "0.6788287", "0.6781232", "0.6695377", "0.6695377", "0.6574853", "0.6572941", "0.6561654", "0.65368277...
0.0
-1
Get the current menu (if any) for display
def get_menu_for_display(self): game = self.game if not game.menu: return menu = game.menu if not menu.is_visible: return None return menu
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_current_menu(self) -> Optional[Menu]:\n return self.menu_pointer", "def menu(self):\n return self._menu", "def GetMenu(self):\n return self._menu", "def get_menu ( self, object ):\n return self.menu", "def get_menu(menu_name):\n\n pass", "def menu(self) -> CursesMen...
[ "0.8369181", "0.808696", "0.7934751", "0.7843155", "0.7731306", "0.7376547", "0.7319818", "0.73052615", "0.7292033", "0.7227728", "0.7197315", "0.71656644", "0.7100037", "0.7065015", "0.6940004", "0.6820579", "0.680545", "0.6757568", "0.6753027", "0.67357635", "0.67194587", ...
0.77827156
4
If the menu should be visible, then draw it
def draw_menu(self): menu = self.get_menu_for_display() if not menu: return menu_center_x, menu_center_y, menu_cords = self.get_menu_coords(menu) arcade.draw_rectangle_filled( menu_center_x, menu_center_y, menu.width, menu.height, COLOUR_MAP[menu.base_colour] ) text_height = menu_cords[0][1] - (menu.button_padding * 3) for text in menu.text_lines: arcade.draw_text( text, menu_center_x, text_height, arcade.color.BLACK, 12, align = "center", anchor_x = "center", anchor_y = "top", ) text_height = text_height - (menu.button_padding * 3) for button_index, button in enumerate(menu.button_list): self.draw_button( button, menu_cords[0][0], menu_cords[0][1], menu.width, menu.height, menu.selected_index == button_index )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw(self):\n self.menu_pointer.draw()", "def draw_menu(self):\n self.screen.fill(self.menu_color, self.rect)\n pygame.draw.rect(self.screen, self.border_color, self.rect, 5)\n self.screen.blit(self.title_image, self.title_image_rect)\n\n self.play_button.draw_button()", ...
[ "0.7788359", "0.75005126", "0.74821126", "0.7407488", "0.7399661", "0.7335653", "0.7126484", "0.70524067", "0.7018847", "0.6975471", "0.6741928", "0.6728081", "0.6551245", "0.6539362", "0.6494997", "0.6488301", "0.648804", "0.64400756", "0.6423215", "0.6423037", "0.641454", ...
0.68641776
10
Get the pixel positions for positioning a menu in the center of the screen
def get_menu_coords(self, menu): menu_center_x = (self.width // 2) menu_center_y = (self.height // 2) # get a mapping of the menu co-ordinates for relative positioning of things inside the menu menu_cords = ( (menu_center_x - (menu.width // 2), menu_center_y + (menu.height // 2)), (menu_center_x + (menu.width // 2), menu_center_y + (menu.height // 2)), (menu_center_x - (menu.width // 2), menu_center_y - (menu.height // 2)), (menu_center_x + (menu.width // 2), menu_center_y - (menu.height // 2)), ) return menu_center_x, menu_center_y, menu_cords
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getMenuItemPixels(cls):\n return cls.menuItemPixels", "def getCenter(self):\n return [self.tx/self.tw, self.ty/self.tw]", "def screen_coordinates(pos):\n\n return [int((pos[0] % screen_width) / px), screen_height - int((pos[1] % screen_height) / px)]", "def get_pix_pos(self):\r\n ...
[ "0.668973", "0.6660493", "0.65916294", "0.65874016", "0.65281975", "0.6518283", "0.64817595", "0.64489305", "0.64457977", "0.64295113", "0.64295113", "0.6412496", "0.64010537", "0.6398035", "0.6398035", "0.6398035", "0.6398035", "0.6364081", "0.63268316", "0.63001156", "0.628...
0.74038523
0
Draw a square for the button. If button is selected display an indicator (e.g. yellow triangle) next to it
def draw_button(self, button, relative_x, relative_y, menu_width, menu_height, is_selected): # adapted from http://arcade.academy/examples/gui_text_button.html#gui-text-button screen_button_center_x = (SCREEN_WIDTH - button.center_x - relative_x) screen_button_center_y = menu_height + (SCREEN_HEIGHT - button.center_y - relative_y) arcade.draw_rectangle_filled( screen_button_center_x, screen_button_center_y, button.width, button.height, COLOUR_MAP[button.face_color] ) if is_selected: selected_x = screen_button_center_x - (button.width // 2) - 25 selector_height = 10 selector_width = 16 arcade.draw_triangle_filled( selected_x, screen_button_center_y - selector_height, selected_x, screen_button_center_y + selector_height, selected_x + selector_width, screen_button_center_y, COLOUR_MAP[Colour.YELLOW.value] ) if not button.pressed: color = COLOUR_MAP[button.shadow_color] else: color = COLOUR_MAP[button.highlight_color] # Bottom horizontal arcade.draw_line(screen_button_center_x - button.width / 2, screen_button_center_y - button.height / 2, screen_button_center_x + button.width / 2, screen_button_center_y - button.height / 2, color, button.button_height) # Right vertical arcade.draw_line(screen_button_center_x + button.width / 2, screen_button_center_y - button.height / 2, screen_button_center_x + button.width / 2, screen_button_center_y + button.height / 2, color, button.button_height) if not button.pressed: color = COLOUR_MAP[button.highlight_color] else: color = COLOUR_MAP[button.shadow_color] # Top horizontal arcade.draw_line(screen_button_center_x - button.width / 2, screen_button_center_y + button.height / 2, screen_button_center_x + button.width / 2, screen_button_center_y + button.height / 2, color, button.button_height) # Left vertical arcade.draw_line(screen_button_center_x - button.width / 2, screen_button_center_y - button.height / 2, screen_button_center_x - button.width / 2, screen_button_center_y + button.height / 2, color, button.button_height) x = screen_button_center_x y = screen_button_center_y if not button.pressed: x -= button.button_height y += button.button_height arcade.draw_text(button.text, x, y, arcade.color.BLACK, font_size=button.font_size, width=button.width, align="center", anchor_x="center", anchor_y="center")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_button(self):\n # Draw the button's outline\n pg.draw.rect(self.screen, self.text_color, pg.Rect(self.rect.left - 1, self.rect.top - 1, self.rect.width + 2, self.rect.height + 2))\n\n # Draw the button\n pg.draw.rect(self.screen, self.button_color, self.rect)\n\n # Blit ...
[ "0.7021328", "0.701689", "0.6932498", "0.68985623", "0.6685321", "0.6384838", "0.6380278", "0.63643676", "0.63429385", "0.6320387", "0.6311006", "0.6310892", "0.6305261", "0.6301066", "0.6284226", "0.6218799", "0.61398274", "0.6080243", "0.60589015", "0.6042735", "0.60369974"...
0.70010066
2
Called whenever the mouse moves.
def on_mouse_motion(self, x, y, delta_x, delta_y): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def on_mouse_motion(self, x, y, delta_x, delta_y):\r\n pass", "def on_mouse_move(self, event: PointEvent):\n self.x = event.x\n self.y = event.y\n self.handle_mouse(self.x, self.y)", "def mouse_move_callback(self, event):\n # TODO drag and drop figuriek\n print(\"movin...
[ "0.8003781", "0.7950266", "0.7752839", "0.76657957", "0.76657957", "0.7528036", "0.7506672", "0.7437439", "0.7398488", "0.73642653", "0.73512393", "0.7318702", "0.73072326", "0.7295303", "0.72917354", "0.727809", "0.71965337", "0.7163269", "0.716054", "0.7160027", "0.7155508"...
0.77163106
3
Called when the user presses a mouse button.
def on_mouse_press(self, x, y, button, modifiers): menu: Menu = self.get_menu_for_display() menu_click_x, menu_click_y = self.get_menu_click(menu, x, y) if button == arcade.MOUSE_BUTTON_LEFT: if menu: menu.button_list.check_mouse_press_for_buttons( menu_click_x, menu_click_y, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def on_mouse_press(self, x, y, button):\n\n pass", "def handle_mouse_press(self, event):", "def on_mouse_press(self, x, y, button, key_modifiers):\r\n pass", "def mouse_press_event(self, x: int, y: int, button: int):\n pass", "def ev_mousebuttondown(self, event: MouseButtonDown) -> Non...
[ "0.8571433", "0.8407928", "0.8234308", "0.82193017", "0.8075841", "0.7850791", "0.7829097", "0.7808337", "0.77429193", "0.76497364", "0.74960554", "0.7452911", "0.7409987", "0.7394991", "0.73922163", "0.7388577", "0.73728776", "0.734544", "0.72436446", "0.7235839", "0.7232465...
0.70223546
31
Translate to the arcade screen pixel position to coordinate values relative to the menu. Used for determining if a button has been clicked.
def get_menu_click(self, menu, x, y): menu_click_x = None menu_click_y = None if menu: menu_center_x, menu_center_y, menu_cords = self.get_menu_coords(menu) menu_click_x = menu.width - (SCREEN_WIDTH - x - menu_cords[0][0]) menu_click_y = menu.height + (SCREEN_HEIGHT - y - menu_cords[0][1]) # Transform the values for out of bounds values if menu_click_x > menu.width or menu_click_x < 0: menu_click_x = None if menu_click_y > menu.height or menu_click_y < 0: menu_click_y = None return menu_click_x, menu_click_y
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _mouse_action(self, pos, pygame):\r\n surface = pygame.display.get_surface()\r\n\r\n width = surface.get_width()\r\n height = surface.get_height()\r\n # get window size\r\n\r\n button_width = width / 5\r\n button_height = height / 6\r\n # calculate button size\r...
[ "0.6537602", "0.6219583", "0.6192906", "0.6191912", "0.6028021", "0.6004765", "0.59921515", "0.59902275", "0.5902409", "0.58934194", "0.58909214", "0.58835", "0.5861542", "0.5846216", "0.5830137", "0.580614", "0.5786481", "0.57471406", "0.57405293", "0.5723758", "0.56889206",...
0.5523286
35
Called when a user releases a mouse button.
def on_mouse_release(self, x, y, button, modifiers): menu: Menu = self.get_menu_for_display() menu_click_x, menu_click_y = self.get_menu_click(menu, x, y) if button == arcade.MOUSE_BUTTON_LEFT: if menu: menu.button_list.check_mouse_release_for_buttons( menu_click_x, menu_click_y, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mouse_release_event(self, x: int, y: int, button: int):\n pass", "def on_mouse_release(self, x, y, button):\n pass", "def on_mouse_release(self, x, y, button, key_modifiers):\r\n pass", "def OnMouseUp(self, evt):\n self.ReleaseMouse()", "def release():\n gui.mouseUp()", ...
[ "0.84587985", "0.8265383", "0.8027847", "0.7779169", "0.7402796", "0.7354275", "0.7343987", "0.73079485", "0.7235595", "0.7149236", "0.7088489", "0.7049613", "0.70101506", "0.70101506", "0.6996034", "0.6911698", "0.6900314", "0.6800558", "0.6790865", "0.67554575", "0.673073",...
0.723252
9
Compute the NLL loss for this task
def nll( self, model: nn.Module, batch: TupleMiniBatch, reduction: str = "mean", predict: bool = False, ): device = list(model.parameters())[0].device batch = batch.to(device) inputs = batch.inputs # Extract features with the model features = model(*inputs) nlls = self.nll_on_features(features, batch, reduction) if predict: predictions = self.predict_on_features(features) return (nlls,) + predictions else: return nlls
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute_loss(self):", "def nll_loss(predictions, targets, weights, reduction, ignore_index):\n return cpp.nn.nll_loss(predictions, targets, weights, reduction, ignore_index)", "def _compute_loss(self, parameters, inputs, ground_truth):\n predictions = self.network_forward(parameters, inputs)\n ...
[ "0.7523511", "0.7353931", "0.73111176", "0.73111176", "0.71701425", "0.7164954", "0.713618", "0.71097046", "0.70807564", "0.7053136", "0.70448524", "0.70416677", "0.70341206", "0.70327586", "0.6955481", "0.6945738", "0.69216895", "0.69183487", "0.6891246", "0.6886024", "0.688...
0.0
-1
Compute the logits for this task
def logits(self, model, batch): device = list(model.parameters())[0].device batch = batch.to(device) inputs = batch.inputs # Extract features with the model features = model(*inputs) logits = self.logits_on_features(features, batch) return logits
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute_logits(self):\n # [num train labels, num classes] where each row is a one-hot-encoded label.\n one_hot_train_labels = tf.one_hot(self.data.train_labels, self.way)\n\n # Undocumented in the paper, but *very important*: *only* the support set\n # embeddings is L2-normalized, which means that ...
[ "0.7227106", "0.7013559", "0.6846142", "0.6814897", "0.6482821", "0.6459679", "0.644783", "0.6419121", "0.63484573", "0.6347733", "0.623671", "0.621699", "0.61936843", "0.6175315", "0.61261624", "0.612563", "0.60965395", "0.6087454", "0.60439134", "0.6013969", "0.6002376", ...
0.5934097
27
Computes logits based on features from the model
def logits_on_features(self, h, batch): batch = batch.to(h.device) # Extract features with the model features = h.view(batch.size, -1) # Log loss logits = self.head(features) return logits
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def logits(self, model, batch):\n device = list(model.parameters())[0].device\n batch = batch.to(device)\n inputs = batch.inputs\n # Extract features with the model\n features = model(*inputs)\n logits = self.logits_on_features(features, batch)\n return logits", "...
[ "0.7213141", "0.6972253", "0.6765194", "0.6761858", "0.67392176", "0.6513034", "0.64970493", "0.64832693", "0.6462769", "0.64080673", "0.6387591", "0.6311425", "0.6272004", "0.62515974", "0.62422395", "0.62104046", "0.62095785", "0.62022495", "0.61950845", "0.6186781", "0.618...
0.71031106
1
Compute the NLL loss given features h and targets y This assumes that the features have already be computed with the model
def nll_on_features(self, h, batch, reduction="mean"): batch = batch.to(h.device) y = batch.outputs # Extract features with the model features = h.view(batch.size, -1) # Log loss logits = self.head(features) log_probs = F.log_softmax(logits, dim=-1) nll_loss = F.nll_loss(log_probs, y, reduction=reduction) return nll_loss
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def loss(self, X, y=None):\n X = X.astype(self.dtype)\n mode = 'test' if y is None else 'train'\n\n # We are gonna store everythin in a dictionnary hidden\n hidden = {}\n hidden['h0'] = X.reshape(X.shape[0], np.prod(X.shape[1:]))\n\n for i in range(self.L):\n id...
[ "0.67652905", "0.6620769", "0.66202563", "0.6577398", "0.6380125", "0.6372819", "0.63684165", "0.63215613", "0.6316717", "0.6303203", "0.6277401", "0.62723595", "0.6269626", "0.62407196", "0.62390345", "0.6234942", "0.62235326", "0.6202289", "0.61824965", "0.61645675", "0.614...
0.72924393
0
Predict label on this batch
def predict(self, model, batch): device = list(model.parameters())[0].device batch = batch.to(device) inputs = batch.inputs # Extract features with the model h = model(*inputs) # predictions return self.predict_on_features(h)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def predict_label(self, src): # real signature unknown; restored from __doc__\n pass", "def predict(self, X, pred_batch_size=None):", "def predict(self, X): \n # Check is fit had been called\n check_is_fitted(self, ['X_', 'y_'])\n\n # Input validation\n X = check_array(X)\n\n...
[ "0.7966786", "0.78263235", "0.7803063", "0.7405601", "0.74039984", "0.7385424", "0.73802847", "0.73328096", "0.7332244", "0.73233455", "0.73233455", "0.73199046", "0.73199046", "0.73199046", "0.72741306", "0.72542346", "0.72518075", "0.72518075", "0.72518075", "0.72377795", "...
0.0
-1
Predict label given features from the model
def predict_on_features(self, h): logits = self.head(h.view(h.size(0), -1)) log_probs = F.log_softmax(logits, dim=-1) return log_probs, logits.argmax(dim=-1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def predict(model, features):\n result = model.predict(features)\n return result", "def predict(self, features):\n vec = vectorize(features, self.vocab,\n self.dpvocab, self.projmat)\n label = self.clf.predict(vec)\n # print label\n return self.labelmap[la...
[ "0.7955748", "0.78675884", "0.7786666", "0.76372766", "0.7480364", "0.74767727", "0.74300313", "0.7427345", "0.73632777", "0.73632777", "0.7309799", "0.7309799", "0.7309799", "0.72233385", "0.7213071", "0.72049874", "0.72049874", "0.72049874", "0.72035515", "0.71662915", "0.7...
0.0
-1
Score a collection of labels and predictions. Usually this is accuracy, but it depends on the task.
def score(self, y_hat, y): return (y_hat == y.to(y_hat.device)).float().mean().item()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def score(self, X_test: List[str], y_test: List[str]) -> int:\n predictions_count = 0\n right_predictions_count = 0\n\n for i in range(len(X_test)):\n label = self.predict(X_test[i].split())\n predictions_count += 1\n right_predictions_count += 1 if label == y_...
[ "0.71214116", "0.7117111", "0.71014607", "0.70404774", "0.70164144", "0.6998174", "0.6991339", "0.6985778", "0.69506323", "0.6912673", "0.69000816", "0.6899743", "0.6899066", "0.68485504", "0.6846754", "0.6846514", "0.684031", "0.6839982", "0.6834518", "0.6833685", "0.6827696...
0.0
-1
Return a head compatible with this task
def create_compatible_head( self, n_features: int, device: Optional[str] = None, ): head = nn.Linear(n_features, self.n_classes) xavier_initialize(head) if device is not None: head = head.to(device) return head
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def head(self) -> TaskHead:\n return self._model.head", "def head(self) -> tf.estimator.Head:\n\n task_type = self._problem_statement.tasks[0].type\n if task_type.HasField('one_dimensional_regression'):\n return tf.estimator.RegressionHead()\n num_classes = (\n self._tf_transform_outp...
[ "0.78820324", "0.7001775", "0.6367529", "0.6272498", "0.6272498", "0.6085029", "0.60775405", "0.60211575", "0.59077823", "0.58798844", "0.5837654", "0.578382", "0.5746318", "0.570547", "0.5696375", "0.56910676", "0.56888205", "0.56619275", "0.56599844", "0.5638932", "0.563865...
0.5274176
76
Build this task's classification head.
def build_head(self, n_features, device=None): # By default this is a linear layer self.head = self.create_compatible_head(n_features, device)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def head(self) -> tf.estimator.Head:\n\n task_type = self._problem_statement.tasks[0].type\n if task_type.HasField('one_dimensional_regression'):\n return tf.estimator.RegressionHead()\n num_classes = (\n self._tf_transform_output.num_buckets_for_transformed_feature(\n self.raw_labe...
[ "0.6749117", "0.60415906", "0.60092235", "0.5853955", "0.5802875", "0.5693355", "0.5665179", "0.5637631", "0.5628371", "0.5621177", "0.56188375", "0.56188375", "0.56188375", "0.55739766", "0.5559742", "0.55255944", "0.5508331", "0.5490201", "0.5489764", "0.5484875", "0.546793...
0.6520812
1
Evaluate a model on a dataset
def eval_model( self, model: nn.Module, batch_size: int = 32, data: Union[str, th.utils.data.Dataset] = "test", collate_fn: Optional[Callable] = None, by_example: bool = False, label_map: Optional[Callable] = None, nll: bool = False, ): # Set model to test mode mode = model.training model.train(mode=False) # Select dataset for evaluation dataset = data if isinstance(data, str): dataset = self.get_split(data) elif not isinstance(dataset, th.utils.data.Dataset): raise ValueError( "`data` must be a pytorch dataset or one of 'dev'/'valid'" f"/'test/'train', got {dataset.__class__.__name__} instead" ) # Dataloader data_loader = DataLoader( dataset, batch_size=batch_size, collate_fn=self.collate_fn if collate_fn is None else collate_fn, ) y, y_hat, all_nlls = [], [], [] for batch in data_loader: # Get model predictions with th.no_grad(): nlls, _, predicted = self.nll( model, batch, reduction="none", predict=True, ) # Track predictions and reference y.append(batch[-1]) y_hat.append(predicted) all_nlls.append(nlls) # Concatenate y = th.cat(y, dim=0).cpu() y_hat = th.cat(y_hat, dim=0).cpu() all_nlls = th.cat(all_nlls, dim=0).cpu() # Map predictions to labels (this is useful for single # head model evaluated on multiple tasks) if label_map: y_hat = th.tensor([label_map(y_hat_i.item()) for y_hat_i in y_hat]) # Task specific score if by_example: score = (y == y_hat).float() else: score = self.score(y_hat, y) nlls = nlls.mean() # Reset model to the original mode model.train(mode=mode) result = score if nll: result = (score, all_nlls) return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def evaluate(self, dataset):\n return self.model.evaluate(dataset.X_val, dataset.y_val)", "def evaluate(self, dataset):\n\t\tpass", "def evaluate(X_test, y_test):\n # batch size is 16 for evaluation\n batch_size = 16\n\n # Load Model\n model = load_model('model/model.h5')\n return model.e...
[ "0.7838396", "0.75702345", "0.75052845", "0.7403759", "0.7293109", "0.71893185", "0.7124573", "0.71120846", "0.7107418", "0.70945823", "0.70358276", "0.7014347", "0.7008108", "0.6981123", "0.69724715", "0.6952163", "0.69312906", "0.69263285", "0.68702364", "0.68674177", "0.68...
0.6675748
42
Make predictions on a dataset
def predict_dataset( self, model: nn.Module, batch_size: int = 32, data: Union[str, th.utils.data.Dataset] = "test", collate_fn: Optional[Callable] = None, ): # Set model to test mode mode = model.training model.train(mode=False) # Select dataset for evaluation dataset = data if isinstance(data, str): dataset = self.get_split(data) elif not isinstance(dataset, th.utils.data.Dataset): raise ValueError( "`data` must be a pytorch dataset or one of 'dev'/'valid'" f"/'test/'train', got {dataset.__class__.__name__} instead" ) # Dataloader data_loader = DataLoader( dataset, batch_size=batch_size, collate_fn=self.collate_fn if collate_fn is None else collate_fn, ) log_ps, y_hats = [], [] for batch in data_loader: # Get model predictions with th.no_grad(): log_p, y_hat = self.predict(model, batch) # Track predictions and log probabilities log_ps.append(log_p) y_hats.append(y_hat) # Concatenate log_ps = th.cat(log_ps, dim=0).cpu() y_hats = th.cat(y_hats, dim=0).cpu() # Reset model to the original mode model.train(mode=mode) return log_ps, y_hats
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def predict(self, data):\n\t\traise NotImplementedError", "def predict(self, data: List):", "def predict(self, X):", "def predict(self, X):", "def make_predictions(df):\n t_labels = get_labels(\"labels_pca\")\n # clean data\n df = clean_data(df)\n # engineer data\n df = engineer_features(df)...
[ "0.77277684", "0.7660498", "0.76100504", "0.76100504", "0.7579166", "0.75640804", "0.75640804", "0.75640804", "0.7563839", "0.7560296", "0.74923545", "0.7473842", "0.74510586", "0.743913", "0.7410133", "0.7398052", "0.731464", "0.7291085", "0.7289969", "0.7258649", "0.723932"...
0.0
-1
Number of classes for this task
def n_classes(self): raise NotImplementedError()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_num_classes(self):", "def n_classes(self):\n raise NotImplementedError", "def n_classes(self):\n raise NotImplementedError", "def num_classes(self):\n raise NotImplementedError", "def num_classes(self):\n\t\treturn 10", "def num_classes(self):\n\t\treturn len(self.classes)", ...
[ "0.85922784", "0.8439114", "0.8439114", "0.8354348", "0.8313837", "0.8283035", "0.8272501", "0.82022357", "0.82022357", "0.8197399", "0.8057032", "0.79937804", "0.7968803", "0.7952655", "0.7936278", "0.75892717", "0.74640423", "0.72919357", "0.72601396", "0.7232733", "0.71904...
0.8404323
3
Shape of the input for this task
def input_size(self): raise NotImplementedError()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def input_shape(self) ->torch.Size:\n pass", "def inputShape(self):\n return self.input_shape", "def input_shape(self):\n return [None, 32, 32, 1]", "def input_shape(self):\n return [None, 32, 32, 1]", "def input_shape(self):\n return [None, 32, 32, 1]", "def input_shape(self):\n ...
[ "0.7809569", "0.7646489", "0.7484749", "0.7484749", "0.7484749", "0.741397", "0.70947266", "0.69226736", "0.690702", "0.68537086", "0.6853561", "0.6770632", "0.6769456", "0.67648906", "0.66720814", "0.6651734", "0.6614571", "0.6614571", "0.6606001", "0.6606001", "0.6606001", ...
0.7097524
6
Training data for this task
def train_data(self): return self._train_data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def train(self, data):\n pass", "def train(self, training_data):\n pass", "def getTrainingData(self):\n raise NotImplementedError", "def train(self, trainData):\n pass", "def train(self):\n pass", "def train(self):\n pass", "def train(self):\n pass", "de...
[ "0.7985163", "0.79244554", "0.76018167", "0.7599324", "0.7536897", "0.7536897", "0.7536897", "0.7536897", "0.7536897", "0.7503888", "0.73865134", "0.73503995", "0.7335692", "0.7312381", "0.731068", "0.7301079", "0.7278077", "0.72348267", "0.72277933", "0.72013533", "0.7183543...
0.6909976
35
Validation data for this task
def valid_data(self): return self._valid_data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validate_dataset(self):\n pass", "def validate(cls, data, errors):", "def validate():", "def _validate(self):\n pass", "def validate(self, data):\n raise NotImplementedError(\"Inherit this class and override this method.\")", "def validate(self):\n pass", "def validate(s...
[ "0.7545616", "0.75082064", "0.7449879", "0.7382325", "0.7261222", "0.72052073", "0.72052073", "0.72052073", "0.72052073", "0.72052073", "0.72052073", "0.72052073", "0.72052073", "0.7128559", "0.71273035", "0.71273035", "0.7121654", "0.7115019", "0.70944667", "0.70944667", "0....
0.62555313
97
Test data for this task
def test_data(self): return self._test_data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getTestData(self):\n raise NotImplementedError", "def test_process_data(self):\n pass", "def test_data(self, data):\n print('-'*30)\n print('Starting test: {}'.format(data['name']))\n self.set_resolution(data['resolution']['width'], data['resolution']['height'])\n ...
[ "0.77121603", "0.74460846", "0.73213947", "0.7164332", "0.7164332", "0.7164332", "0.7164332", "0.714354", "0.7103978", "0.69678515", "0.68217576", "0.68121225", "0.6750978", "0.67116654", "0.67001045", "0.66699296", "0.6623456", "0.66211283", "0.6617969", "0.6593253", "0.6550...
0.75773656
1
Collater to make batches
def collate_fn(self, *args): return TupleMiniBatch(default_collate(*args))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _collater(batch):\n return batch[0]", "def collater(self, samples):\r\n raise NotImplementedError", "def produce_query_batches(self):\n pass", "def trivial_batch_collator(batch):\n return batch", "def trivial_batch_collator(batch):\n return batch", "def trivial_batch_collator(b...
[ "0.7257751", "0.64775294", "0.62918323", "0.62413275", "0.62413275", "0.62413275", "0.6130379", "0.6129091", "0.60867256", "0.6059193", "0.604119", "0.6024431", "0.60000926", "0.59829533", "0.59790826", "0.5951112", "0.590438", "0.5853374", "0.5758594", "0.5754777", "0.575146...
0.55312043
33
This is the reverse of `self.collate_fn`
def shatter_batch(self, batch): return [tuple([elem[i] for elem in batch]) for i in range(batch.size)]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def collate_fn(self, *args):\n return TupleMiniBatch(default_collate(*args))", "def build_collate_fn(\n cls, args: argparse.Namespace, train: bool\n ) -> Callable[[Sequence[Dict[str, np.ndarray]]], Dict[str, torch.Tensor]]:\n raise NotImplementedError", "def custom_collate_fn(data):\n ...
[ "0.7459662", "0.669416", "0.64607346", "0.63689786", "0.6184213", "0.61835617", "0.6163743", "0.59677935", "0.5942852", "0.5942852", "0.58277845", "0.58204836", "0.56743795", "0.56363", "0.5553087", "0.55181116", "0.54813635", "0.5477117", "0.54744", "0.5447483", "0.5447414",...
0.0
-1
Subsample the training data (for low resource experiments)
def subsample_training_set(self, k, seed=None): if seed is not None: rng_state = th.random.get_rng_state() with th.random.fork_rng(): th.manual_seed(seed) self._subsample_training_set(k) if any(th.random.get_rng_state() != rng_state): raise ValueError("Bad RNG state") else: self._subsample_training_set(k)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def subsample(self, dataset):\n sample_idx = np.random.choice(\n dataset.shape[0], self.sample_size, replace=True)\n sample = dataset[sample_idx,...]\n return sample", "def subsampleData(self, count):\n size = 0\n for block in self.blocks: size += len(block[1])\n subset = numpy.random.pe...
[ "0.7140998", "0.708751", "0.6995602", "0.68779194", "0.6740651", "0.66297245", "0.6604621", "0.65915847", "0.65746677", "0.6495264", "0.6429238", "0.6381866", "0.6375742", "0.6355722", "0.63405573", "0.6313042", "0.6300593", "0.629987", "0.623293", "0.62231666", "0.62195325",...
0.6540765
9
Dataloader type for this task
def dataloader(self): return DataLoader
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dataloader(self):\n\n # load / split data\n train_data = self.data.get_train_data()\n if self.args.use_dev:\n train_data, dev_data = self.data.split_data(train_data)\n test_data = self.data.get_test_data()\n\n #print(train_data[0])\n #print(dev_data[0])\n ...
[ "0.64198226", "0.6303011", "0.62908787", "0.6223448", "0.6176214", "0.6175871", "0.59194773", "0.59120303", "0.5911008", "0.59027666", "0.5870242", "0.584646", "0.5842133", "0.5794101", "0.57517266", "0.574646", "0.56932807", "0.5689548", "0.5668795", "0.5666431", "0.56519496...
0.67818266
0
Name of this task
def name(self): return self._name
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def task_name(self):\n pass", "def task_name(self) -> str:\n return self._task_name", "def getTaskName(self):\n return self._taskName", "def task(self) -> str:\n return self._task", "def task(self, name):\n pass", "def task_label(self) -> str:\n label = str(self....
[ "0.94787014", "0.8952571", "0.83853745", "0.80476105", "0.7959026", "0.7788897", "0.7784508", "0.75775784", "0.74878675", "0.748582", "0.7418969", "0.7418969", "0.7418969", "0.7418969", "0.74116933", "0.7375836", "0.73410845", "0.73359287", "0.7334646", "0.7334646", "0.730673...
0.0
-1
Concatenate two task's datasets
def concatenate_tasks( tasks, concat_train=True, concat_valid=True, concat_test=True, ): new_task = deepcopy(tasks[0]) new_task._name = "+".join(task.name for task in tasks) if concat_train: new_task._train_data = ConcatDataset( [task.train_data for task in tasks]) if concat_valid: new_task._valid_data = ConcatDataset( [task.valid_data for task in tasks]) if concat_test: new_task._test_data = ConcatDataset([task.test_data for task in tasks])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def concatenate_data():", "def concat(self: TAvalancheDataset, other: TAvalancheDataset) -> TAvalancheDataset:\n return self.__class__([self, other])", "def Concat(datasets):\n\n dataset_num = len(datasets)\n dataset = datasets[0]\n for i in range(1, dataset_num):\n dataset.concatenate(d...
[ "0.685715", "0.6508406", "0.6459176", "0.63558143", "0.63046694", "0.617627", "0.6152155", "0.5977995", "0.58850974", "0.58077186", "0.5803393", "0.57910776", "0.5675971", "0.5674531", "0.5653291", "0.5594489", "0.55606794", "0.55558187", "0.55526024", "0.5524445", "0.5524164...
0.7752744
0
Clean the cache before autotraining, which can avoid .
def _clean_cache(self): torch = import_optional_dependency("torch") if self.device == torch.device('cuda'): with torch.cuda.device(self.device): torch.cuda.empty_cache()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clean_cache(self):\n return", "def clear_model_cache():\n global __model_cache\n __model_cache = {}", "def clear_cache():\n # TODO\n pass", "def _clean_cache(self):\n del self._cache\n self._cache = {}", "def decache(self):", "def clear_cache(self):\n p...
[ "0.73841304", "0.7362195", "0.72837085", "0.725626", "0.72057503", "0.7171156", "0.7111482", "0.7094823", "0.7086294", "0.7061974", "0.69822985", "0.69769466", "0.6956917", "0.6934986", "0.6898216", "0.68953973", "0.68409723", "0.6832112", "0.6817994", "0.6815026", "0.6789414...
0.71076494
7
The exception of ValueError when format was unsupported.
def _raise_format_error(self, name: str, format_str: str, source_format: str): raise ValueError(f"The '{ name }' should be { format_str }, rather than { source_format }")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validate_format(self):\n raise NotImplementedError()", "def test_old_data_format_error(self):\n assert_raises(ValueError, get_data, self.testv1)", "def _unknown_format(self, format):\n\n raise errors.NotAcceptable('unknown data format: ' + format)", "def test_decode_raises_when_forma...
[ "0.7590254", "0.72390485", "0.721036", "0.6805415", "0.6779957", "0.6535371", "0.6451091", "0.6289927", "0.620279", "0.6175287", "0.61463153", "0.6133835", "0.60960364", "0.6054621", "0.6033631", "0.60062885", "0.6004486", "0.5990601", "0.59883577", "0.5986072", "0.5967362", ...
0.7319483
1
Initialize the Neural Network training process.
def __init__(self, model=None, train_dataset=None, eval_dataset=None, optimizer=None, criterion=None, cpu: bool = False): # import torch for initialization torch = import_optional_dependency("torch") # ============== basic parameters ============== # # the device that used to train models, which can automatically set self.device = torch.device("cuda" if torch.cuda.is_available() and not cpu else "cpu") # the optimizer of training self.optimizer = optimizer # the neural network model self.model = model.to(self.device) if model else None # the criterion of training self.criterion = criterion.to(self.device) if criterion else None # the dataset for training self.train_dataset = train_dataset # the dataset for evaluation self.eval_dataset = eval_dataset # the training process would show information if self.info is True self.info = True # ============== the parameters of training ============== # # the loss average meter for every epoch self.epoch_loss = AverageMeter() # the counter for training self.epoch = 0 # training process for iteration self.batch_process = None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize_network(self):\n self.sess = tf.InteractiveSession()\n sys.stderr.write(\"------\\n\")\n self.model.create_model()\n self._initialize_trainer()\n self.sess.run(tf.initialize_all_variables())\n self.saver = tf.train.Saver()", "def init():\n global neural...
[ "0.7842906", "0.769013", "0.75414234", "0.74997467", "0.7447813", "0.7415171", "0.73304015", "0.73236835", "0.7239312", "0.7162911", "0.71530294", "0.7108662", "0.706298", "0.70624375", "0.70430005", "0.70430005", "0.70291543", "0.70126384", "0.6987266", "0.69770414", "0.6969...
0.0
-1
A subfunction that ensuring the train mode.
def _set_train(self): if not self.model.__dict__['training']: self.model.train()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_training(self):\n return self.mode == \"train\"", "def is_training(self):\n return self.mode == \"train\"", "def train():\n pass", "def test(self):\n self.training = False", "def train(self):\n self.training = True", "def train(self)->None:", "def train(self, mode: boo...
[ "0.75731736", "0.75731736", "0.7269636", "0.7236012", "0.7080342", "0.70689183", "0.69955844", "0.6983821", "0.6983821", "0.6983821", "0.6983821", "0.6983821", "0.69157493", "0.69107115", "0.68860173", "0.68713254", "0.6867261", "0.68614346", "0.6843705", "0.68286896", "0.679...
0.64429736
41
A subfunction that ensuring the eval mode.
def _set_eval(self): if self.model.__dict__['training']: self.model.eval()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _should_eval(self):\n return False", "def eval(self):\n pass", "def eval(self):\n pass", "def eval(self):\n pass", "def test(self):\n self.eval()", "def eval(*args, **kwargs):\n\n pass", "def eval(*args, **kwargs)->Any:\n pass", "def eval(self):\n r...
[ "0.75202614", "0.6831532", "0.6831532", "0.6831532", "0.65361977", "0.64932793", "0.64039826", "0.6293743", "0.6179289", "0.60888994", "0.6082469", "0.6079987", "0.6057103", "0.598441", "0.5893379", "0.58848435", "0.586661", "0.5791171", "0.57718706", "0.57667834", "0.575287"...
0.5924793
14
The train function that executes a standard training flow per epoch.
def _batch_iter(self, source, target, i: int): # send data to device source = source.to(self.device) target = target.to(self.device) # the result and loss result = self.model(source) loss = self.criterion(result, target) # optimization and backward self.optimizer.zero_grad() loss.backward() self.optimizer.step() # update the loss self.epoch_loss.update(loss.item(), source.size(0)) # print the information if self.info: print(f"\rEpoch: { self.epoch } | Batch: { i } | loss: { self.epoch_loss.avg }", end="") # clean the data del source, target return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def train(self, training_steps=10):", "def train():\n pass", "def _train_epoch(self, epoch):\n raise NotImplementedError", "def _train_epoch(self, epoch):\n raise NotImplementedError", "def _train_epoch(self, epoch):\n raise NotImplementedError", "def _train_epoch(self, epoch)...
[ "0.8151526", "0.7828467", "0.7768698", "0.7768698", "0.7768698", "0.7768698", "0.7735363", "0.76838636", "0.7644439", "0.76343524", "0.7605618", "0.76051074", "0.7574267", "0.7563756", "0.7548235", "0.7517042", "0.7506631", "0.7495705", "0.7478745", "0.7474352", "0.74734735",...
0.0
-1
The train iterator that executes a standard training flow per batch.
def _train_batch(self): # start epoch for i, (source, target) in enumerate(self.train_dataset): result = self._batch_iter(source, target, i) # yield yield result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_train_iterator(self) -> Iterable[Batch]:\n if self._train_name not in self._datasets:\n raise ValueError(\"Training data not provided.\")\n return self.get_iterator(self._train_name)", "def train_batch_iter(self, batch_size, num_epochs):\n return self.batch_iter(0, batch_s...
[ "0.7524614", "0.7506505", "0.7341301", "0.7287756", "0.7240162", "0.71176016", "0.7104605", "0.70856947", "0.70841146", "0.6950423", "0.6944791", "0.6935007", "0.6922542", "0.6916224", "0.6903519", "0.68901885", "0.6874518", "0.68721944", "0.6839896", "0.68311983", "0.6816215...
0.79244447
0
A subfunction with a general weights initialization.
def _reset_weights(m): nn = import_optional_dependency("torch.nn") init = import_optional_dependency("torch.nn.init") if isinstance(m, nn.Conv1d): init.normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif isinstance(m, nn.Conv2d): init.xavier_normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif isinstance(m, nn.Conv3d): init.xavier_normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif isinstance(m, nn.ConvTranspose1d): init.normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif isinstance(m, nn.ConvTranspose2d): init.xavier_normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif isinstance(m, nn.ConvTranspose3d): init.xavier_normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif isinstance(m, nn.BatchNorm1d): init.normal_(m.weight.data, mean=1, std=0.02) init.constant_(m.bias.data, 0) elif isinstance(m, nn.BatchNorm2d): init.normal_(m.weight.data, mean=1, std=0.02) init.constant_(m.bias.data, 0) elif isinstance(m, nn.BatchNorm3d): init.normal_(m.weight.data, mean=1, std=0.02) init.constant_(m.bias.data, 0) elif isinstance(m, nn.Linear): init.xavier_normal_(m.weight.data) init.normal_(m.bias.data) elif isinstance(m, nn.LSTM): for param in m.parameters(): if len(param.shape) >= 2: init.orthogonal_(param.data) else: init.normal_(param.data) elif isinstance(m, nn.LSTMCell): for param in m.parameters(): if len(param.shape) >= 2: init.orthogonal_(param.data) else: init.normal_(param.data) elif isinstance(m, nn.GRU): for param in m.parameters(): if len(param.shape) >= 2: init.orthogonal_(param.data) else: init.normal_(param.data) elif isinstance(m, nn.GRUCell): for param in m.parameters(): if len(param.shape) >= 2: init.orthogonal_(param.data) else: init.normal_(param.data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def init_weights_(self):\n raise NotImplementedError", "def init_weight(w):\n shape = w.shape\n if len(shape) == 4:\n i, o, u, v = shape\n k = np.sqrt(6 / (i * u * v + o * u * v))\n w.data.uniform_(-k, k)\n elif len(shape) == 2:\n k = np.sqrt(6 / sum(shape))\n w.data.uniform_(-k, k)\n e...
[ "0.71588784", "0.6969171", "0.672849", "0.66897625", "0.66819024", "0.6635739", "0.66334575", "0.6569541", "0.65168756", "0.65055704", "0.6471483", "0.6467132", "0.64426", "0.6441045", "0.6407897", "0.64061683", "0.64002126", "0.63850623", "0.6382718", "0.6356592", "0.6353832...
0.0
-1
Show the information of training.
def __repr__(self): # info string info = self.model.__repr__() info += "\n=========================\n" info += f"Train data length:\t\t{ len(self.train_dataset) }\n" info += f"Eval sata length:\t\t{ len(self.eval_dataset) }\n" info += f"Optimizer:\t\t\t\t{ str(self.optimizer).split('(')[0] }\n" info += f"Criterion:\t\t\t\t{ str(self.criterion).split('(')[0] }\n" info += f"Training Environment:\t{ self.device.type }\n" info += f"Show information:\t\t{ 'True' if self.info else 'False' }\n" info += "=========================\n" return info
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def training_info(self):\n pass", "def show(self):\n print \"Name: \"+str(self.name)\n ss = self.y.shape[0]\n for i in xrange(ss):\n print \"Actual: \"+str(self.y[i])\n print \"Prediction: \"+str(self.a[i])\n print \"\"\n print \"\\n\"", "def ...
[ "0.8102564", "0.71761745", "0.6958835", "0.6510571", "0.65085834", "0.6437893", "0.6429031", "0.6424601", "0.64181775", "0.6403707", "0.6398665", "0.6397122", "0.63890433", "0.6379363", "0.6367299", "0.6364796", "0.6359014", "0.63058555", "0.63040435", "0.6300371", "0.6295759...
0.6441708
5
A auto training method for fast using. And the epoch and the location for saving models should be specified while using auto_train().
def auto_train(self, epoch: int, save_model_location: str, eval: bool = True, eval_interval: int = 1, info: bool = True, save_static_dicts: bool = True): # initialization self.info = info best_attempt = float("-inf") self._set_train() # clean the cache if cuda is available self._clean_cache() # start training for n in range(epoch): self.iter_epoch() if self.eval_dataset and eval and not (n + 1) % eval_interval: # eval start eval_loss, accuracy = self.eval() # save the best model if accuracy > best_attempt: best_attempt = accuracy if save_static_dicts: self.save_state_dict(save_model_location) else: self.save_model(save_model_location) print(f"The best model is saved to { self._set_save_location(save_model_location) }. " f"Best accuracy: { best_attempt }")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def train(self):\n self.epoch = 0\n self.step = 0\n self.start_time = time.time()\n for self.epoch in range(self.opt.num_epochs):\n self.run_epoch()\n if (self.epoch + 1) % self.opt.save_frequency == 0:\n self.save_model()", "def train(self):\n ...
[ "0.7835988", "0.765603", "0.73078525", "0.72385854", "0.71432185", "0.7102481", "0.7094969", "0.70912015", "0.70912015", "0.70912015", "0.70912015", "0.70906556", "0.7049515", "0.70454556", "0.70394707", "0.7019595", "0.69803166", "0.69772995", "0.6968585", "0.69661176", "0.6...
0.75473046
2
An function that would stop training per epoch for advanced calculation, plot, etc.
def iter_epoch(self): # set to train mode self._set_train() # start epoch for i, (source, target) in enumerate(self.train_dataset): self._batch_iter(source, target, i) if self.info: print(f"\rEpoch: { self.epoch } | Average loss: { self.epoch_loss.avg }") # update epoch and reset the epoch_loss self.epoch_loss.reset() self.epoch += 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def should_stop(self, epoch: int) -> bool:\n return False", "def should_stop(self, epoch: int) -> bool:\n raise NotImplementedError", "def end_training(self):\n self.training = False", "def choose_to_stop_early(self):\n # return self.cumulated_num_tests > 10 # Limit to make 10 predict...
[ "0.7741919", "0.7645692", "0.7291979", "0.7016654", "0.6997903", "0.69406444", "0.6906733", "0.6906342", "0.6895668", "0.68619394", "0.6835608", "0.6817015", "0.6703942", "0.66655344", "0.66614753", "0.6556472", "0.6510778", "0.6507846", "0.6417945", "0.6395246", "0.63713014"...
0.0
-1
An iterator that training per batch and return for advanced calculation, plot, etc.
def iter_batch(self): # model initialization self._set_train() if not self.batch_process: self.batch_process = self._train_batch() return self.batch_process.__next__() else: try: return self.batch_process.__next__() except StopIteration: # update the state if StopIteration if self.info: print(f"\rEpoch: { self.epoch } | Average loss: { self.epoch_loss.avg }") # update epoch and reset the epoch_loss self.epoch_loss.reset() self.epoch += 1 # reset the batch process del self.batch_process self.batch_process = self._train_batch() return self.batch_process.__next__()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _train_batch(self):\n\n # start epoch\n for i, (source, target) in enumerate(self.train_dataset):\n result = self._batch_iter(source, target, i)\n\n # yield\n yield result", "def __iter__(self):\n for batch in self.iterator:\n yield Batch.from_...
[ "0.7882153", "0.7777626", "0.7653529", "0.74618405", "0.7379885", "0.73270446", "0.72640824", "0.7249159", "0.7226248", "0.7225146", "0.72101283", "0.71956915", "0.71737856", "0.7097069", "0.70954365", "0.7068481", "0.7059343", "0.7055088", "0.70229006", "0.7015991", "0.70062...
0.7671514
2
The evaluation flow using test_dataset without grad.
def eval(self): # parameters initialize torch = import_optional_dependency("torch") eval_total = 0 eval_correct = 0 eval_loss = 0 self._set_eval() # display the information if self.info: print(f"\rEvaluating...", end="") # start eval part for i, (source, target) in enumerate(self.eval_dataset): # send data to device source = source.to(self.device) target = target.to(self.device) result = self.model(source) eval_loss += self.criterion(result, target).item() _, predicted = torch.max(result.data, 1) eval_total += target.size(0) eval_correct += (predicted == target).sum().item() accuracy = eval_correct / eval_total eval_loss = eval_loss / eval_total if self.info: print(f"\rEvaluation loss: { eval_loss } | Accuracy: { accuracy }") return eval_loss, accuracy
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def evaluate(self):\n self.training = False", "def test_step(self, x_test, y_test):\n\n print(\"Evaluation:\")\n\n input_x_op = self.session.graph.get_operation_by_name(\"input_x\").outputs[0]\n input_y_op = self.session.graph.get_operation_by_name(\"input_y\").outputs[0]\n glo...
[ "0.70532185", "0.69431454", "0.6933192", "0.6898252", "0.6769754", "0.6761503", "0.6628612", "0.65984225", "0.6573417", "0.6542276", "0.65251", "0.65153444", "0.6453402", "0.6376132", "0.6350992", "0.6338785", "0.6319733", "0.6301764", "0.62932855", "0.6274323", "0.62724113",...
0.0
-1
Reset the process of training, which includes the loss meter reset, epoch reset and model's weights reset.
def reset_train(self): self.model.apply(self._reset_weights) self.epoch_loss.reset() self.epoch = 0 del self.batch_process self.batch_process = None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset(self):\n self.train_loss.reset_states()\n self.train_accuracy.reset_states()\n self.val_loss.reset_states()\n self.val_accuracy.reset_states()\n self.train_mIoU.reset_states()\n self.val_mIoU.reset_states()", "def train_loop_begin(self):\r\n for _, train_los...
[ "0.80868524", "0.7918954", "0.7916748", "0.7766766", "0.7735061", "0.76176995", "0.7499007", "0.7421006", "0.7351169", "0.72698146", "0.7228589", "0.7210134", "0.71855277", "0.70681477", "0.701447", "0.6989159", "0.69768757", "0.6957746", "0.6951352", "0.6948265", "0.69307107...
0.9016183
0
Save only the state dict of the model.
def save_weights(self, location: str): # import torch torch = import_optional_dependency("torch") torch.save(self.model.state_dict(), self._set_save_location(location))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_state(self):\n pass", "def save_state(self) -> None:\n raise NotImplementedError(\"Save state is is not implemented.\")", "def saveState(self) -> None:\n # TODO: Saves State\n pass", "def save(self, *args, **kwargs):\n if self.state: self.state.save()", "def save...
[ "0.80469704", "0.7924474", "0.789037", "0.78862095", "0.7530521", "0.7401246", "0.7255777", "0.7228237", "0.72169715", "0.7137653", "0.7022203", "0.70193565", "0.7004299", "0.7002671", "0.69508386", "0.6921392", "0.6888518", "0.6883776", "0.68588847", "0.6837567", "0.6811201"...
0.0
-1
Save only the whole model.
def save_model(self, location: str): # import torch torch = import_optional_dependency("torch") torch.save(self.model, self._set_save_location(location))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_model(self):\n pass", "def save(self):\n self.presavemodel()\n self.dbm().model_save(self)\n self.set_isdirty(False)\n # we might be smart about flushing when there is no id, so that saving a new model gets it's unique id\n if (self.id == None):\n sel...
[ "0.81946814", "0.78372055", "0.77880627", "0.7760365", "0.7683972", "0.7658893", "0.7431407", "0.7427803", "0.73944384", "0.73944384", "0.73944384", "0.73944384", "0.73944384", "0.73874027", "0.7360161", "0.73583525", "0.7299202", "0.72941047", "0.72820115", "0.72592044", "0....
0.0
-1
A method for checking the parameters before training, in order to process the training correctly.
def check_parameters(self): torch = import_optional_dependency('torch') if not isinstance(self.model, torch.nn.Module): self._raise_format_error('self.model', 'torch.nn.Module', f'{ type(self.model) }') if not isinstance(self.optimizer, torch.optim.Optimizer): self._raise_format_error('self.optimizer', 'torch.optim.Optimizer', f'{ type(self.optimizer) }') if not isinstance(self.train_dataset, torch.utils.data.DataLoader): self._raise_format_error('self.train_dataset', 'torch.utils.data.DataLoader', f'{ type(self.train_dataset) }') if not isinstance(self.eval_dataset, torch.utils.data.DataLoader): self._raise_format_error('self.eval_dataset', 'torch.utils.data.DataLoader', f'{ type(self.eval_dataset) }')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check(self) -> None:\n # validate training config\n super().check()", "def _check_parameters(self, X):\n _, n_features = X.shape\n\n if self.weights_init is not None:\n self.weights_init = _check_weights(self.weights_init,\n ...
[ "0.766322", "0.7477992", "0.7417763", "0.7302848", "0.72800577", "0.72335196", "0.71856815", "0.7176553", "0.71609956", "0.71493304", "0.71282524", "0.71061707", "0.6990331", "0.69771767", "0.69568545", "0.68638104", "0.68232596", "0.68174267", "0.67853534", "0.6761448", "0.6...
0.6948363
15
Returns the tangent stiffness function, computed symbolically at runtime.
def make_symbolic(symfile_path="fung_Dsym",resym=False): # Construct the quadratic form as a flat list of independent entries q = np.array([sp.symbols('q_{}{}'.format(i,j)) for (i,j) in lin.utri_indices(6)]) # We also need its matrix form Q = np.empty((6,6),dtype=object) for (k,(i,j)) in zip(range(len(q)),lin.utri_indices(6)): Q[i,j] = q[k] Q[j,i] = Q[i,j] # Construct the Lagrangian strain (E) as a *vector* (e) f = np.array([sp.symbols('f_{i}'.format(i=i)) for i in range(9)]) F = np.reshape(f,(3,3)) J = sp.Matrix(F.tolist()).det() # TODO: Is this supposed to be J**(-4/3) or J**(-2/3)? E = 0.5*(J**sp.Rational(-2,3)*np.dot(F.T,F) - np.eye(3)) e = lin.utri_flat(E) # Expand the quadratic form's action on e Qee = np.dot(e,np.dot(Q,e)) # Attempt to load this from a pickle file try: Dsym = pickle.load(open(symfile_path+".pkl",'rb')) # Otherwise, just recompute it except Exception: # Construct the tangent stiffness as a symbolic expression # Calculate first derivatives dQ = np.empty(9,dtype=object) for i in range(9): print("Symbolic dQ_{}".format(i)) dQ[i] = sp.diff(Qee,f[i]) # Calculate second derivatives Dsym = np.empty((9,9),dtype=object) for (i,j) in lin.utri_indices(9): print("Symbolic ddQ_{0}{1}".format(i,j)) dQi = dQ[i] dQj = dQ[j] dQij = sp.diff(dQi,f[j]) Dsym[i,j] = dQi*dQj + dQij # Optimize the derivative by substituting for J print(" Simplifying...") print(" J ",end="") sys.stdout.flush() Dsym[i,j] = Dsym[i,j].subs(J,sp.symbols('J')) # Further optimize by replacing products of f compoenents if resym == True: for (k,l) in lin.utri_indices(9): print("f{}f{}".format(k,l),end=" ") sys.stdout.flush() pair_symbol = sp.symbols('ff_{0}{1}'.format(k,l)) Dsym[i,j] = Dsym[i,j].subs(f[k]*f[l],pair_symbol) # Since D will be symmetric, assign the symmetric components print("\n Symmetrizing...") Dsym[j,i] = Dsym[i,j] # This computation is pretty costly, so let's save it # frequently if resym == True: pickle.dump(Dsym, open(symfile_path+"_{}{}.pkl".format(i,j),'wb')) pickle.dump(Dsym, open(symfile_path+".pkl",'wb')) return Dsym
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def computeTangent(self):\n # return np.matmul(self.examples.T, self.gradAmbient)\n return self.gradAmbient + self.centroid * minkowskiDot(self.centroid, self.gradAmbient)", "def tangent(self, param, diff=0, xyz=False):\n return self.diff(param, diff=diff+1, xyz=xyz)", "def f(self,un,tn):\...
[ "0.66807896", "0.59414274", "0.5845319", "0.5835779", "0.5743613", "0.57013124", "0.56820303", "0.5665989", "0.5611205", "0.5600077", "0.55448455", "0.5506846", "0.5505399", "0.5466508", "0.54543483", "0.5423472", "0.54231364", "0.5411315", "0.5397401", "0.5387374", "0.538464...
0.51767015
46
Base of sett module
def base(request): return render(request, 'sett_base.html', {})
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set():", "def set():\n pass", "def Set(self) -> None:", "def __init__(self):\n self.set = set()", "def use(self):", "def set(x):\n pass", "def __init__(self, *args):\n _snap.TIntSet_swiginit(self, _snap.new_TIntSet(*args))", "def __init__(self, name: unicode, set: ghidra.util.gr...
[ "0.7038524", "0.70106906", "0.64644986", "0.62909436", "0.622287", "0.6137132", "0.60996884", "0.59956205", "0.594199", "0.593214", "0.593214", "0.5907629", "0.59012085", "0.5887358", "0.58760923", "0.5856856", "0.58564854", "0.5838827", "0.573239", "0.573239", "0.573239", ...
0.0
-1
UiView of sett module
def ui_view(request): return render(request, 'sett_ui_view.html', {})
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ui(self):\n return ui", "def init_ui(self):\n raise NotImplementedError", "def init_ui(self):\n raise NotImplementedError", "def prepare_UI(self):", "def view(self):", "def show(self):", "def updateSettingsUI(self):\n\n pass", "def __init__(self):\n self.view = ...
[ "0.7031982", "0.6457756", "0.6457756", "0.6440338", "0.64161724", "0.63023686", "0.6291685", "0.6243074", "0.61494553", "0.61151314", "0.6093119", "0.6090017", "0.6085131", "0.60317594", "0.60222656", "0.60190624", "0.60181403", "0.6016506", "0.5963193", "0.59621996", "0.5954...
0.7076183
0
Page of general settings
def general(request): return render(request, 'general.html', {})
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def printSettings():\n print \">>>\\n>>> SettingsTool: global variables:\"\n for variable, value in globals().items():\n if variable.count('__')>1: continue\n print \">>> %-16s = %s\"%(variable,value)\n print \">>>\"", "def showSettings():\n cq = dz()\n cq.abag()", "def setting...
[ "0.7047792", "0.68825513", "0.68671405", "0.67481273", "0.67089194", "0.670445", "0.6671479", "0.66425955", "0.6616734", "0.66150963", "0.65424526", "0.6488922", "0.64811325", "0.6472592", "0.6429102", "0.63903475", "0.6352831", "0.6333741", "0.63297915", "0.62845564", "0.625...
0.59287745
60
Calls open file dialog, possible to choose only '.xlsx .xls .xlsm .xlsb'
def callDialog(self): self.pathTuple = filedialog.askopenfilenames(filetypes=[("Excel files", ".xlsx .xls .xlsm .xlsb")]) self.fileNames = [basename(path.abspath(name)) for name in self.pathTuple]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def open_file():\n filepath = filedialog.askopenfilename(initialdir = \"./\",title = \"Seleccionar archivo\",filetypes = ((\"xls files\",\"*.xls\"),(\"xlsx files\",\"*.xlsx\")))\n if not filepath:\n return\n\n window.title(filepath)\n lbl_url[\"text\"] = filepath\n btn_generate['state'] = 'no...
[ "0.75951433", "0.7013304", "0.7009427", "0.6953197", "0.69224757", "0.6823879", "0.669363", "0.6688277", "0.66736335", "0.6672926", "0.66545457", "0.66527754", "0.6618524", "0.65777797", "0.6551159", "0.65394413", "0.65350693", "0.65235656", "0.6490343", "0.6485696", "0.64783...
0.7704559
0
Returns tuple of paths stored at class instance
def getPaths(self): return self.pathTuple
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def paths(self):\n return tuple(self._path)", "def get_paths(self):\n paths = []\n for f in dir(self):\n o = getattr(self, f)\n if callable(o) and hasattr(o, '_path'):\n paths.append(getattr(o, '_path'))\n return paths", "def get_class_paths(_cla...
[ "0.7493626", "0.72214353", "0.71332705", "0.6974973", "0.67577744", "0.6682504", "0.66712487", "0.66641986", "0.66585755", "0.66585755", "0.66517574", "0.6619837", "0.6619723", "0.66154474", "0.65316343", "0.6466854", "0.64451087", "0.63843393", "0.6338825", "0.6330856", "0.6...
0.7340977
1
This function will start the microphone and adjust the minimum energy required to detect a voice based on the ambiant noise.
def fine_tune(self, duration = 2): with sr.Microphone() as source: self.recorder.adjust_for_ambient_noise(source, duration=duration) return self.recorder.energy_threshold
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def StartMicrophone(self):\n if not os.path.exists('static'):\n os.mkdir('static')\n microphone = olpc.Microphone('static/sound.ogg')\n microphone.StartMicrophone()", "def speech_recognize_from_microphone():\n speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)...
[ "0.68419266", "0.64319956", "0.62581193", "0.6240901", "0.6077823", "0.6044454", "0.6029799", "0.5960143", "0.5955317", "0.59541893", "0.5915512", "0.5875549", "0.57656145", "0.56401867", "0.5621901", "0.56032926", "0.55882573", "0.5567367", "0.5551472", "0.55207324", "0.5511...
0.59551054
9
This function will start the microphone and listen for an answer to be provided and extract the answer from it.
def listen_and_predict(self, online = False, key=None, verbose=False): with sr.Microphone(sample_rate=48000) as source: audio = self.recorder.listen(source) # recognize speech using Sphinx print('predicting text') try: if online: text = self.recorder.recognize_google(audio, key=key) else: text = self.recorder.recognize_sphinx(audio) except sr.UnknownValueError: return 'Model could not understand the audio' except sr.RequestError as e: return 'Error when predicting the text' text_split = text.split() # acceptable responses for yes and no acceptable_yes = set(['yes', 'yet']) acceptable_no = set(['no', 'know']) if verbose: print(f'Model predicted: {text}') if bool(set(text_split).intersection(acceptable_yes)) and bool(set(text_split).intersection(acceptable_no)): return 'unkown' elif bool(set(text_split).intersection(acceptable_yes)): return 'yes' elif bool(set(text_split).intersection(acceptable_no)): return 'no' return 'unkown'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mic_input():\n try:\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print('Say something...')\n r.pause_threshold = 1\n r.adjust_for_ambient_noise(source, duration=1)\n audio = r.listen(source)\n try:\n command = r.recogni...
[ "0.71735287", "0.70460767", "0.702662", "0.69203657", "0.69143", "0.6879274", "0.68592507", "0.6835375", "0.6740074", "0.66967285", "0.6650779", "0.65125155", "0.6443816", "0.6381483", "0.6351039", "0.62422884", "0.6159692", "0.61501604", "0.6081473", "0.60642445", "0.6046894...
0.5937994
28
Triggers a manual build of the project.
async def trigger_build(self, *, branch=None, message=None):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def trigger_build(self, postdata):\n pass", "def build(self):\n logging.info('Build %s of %s (%s)', self._build, self.name,\n self.working_dir)\n self._build += 1\n self._event = None\n status = self._builder.execute_script(self.working_dir, self.script)\n ...
[ "0.69045925", "0.6808615", "0.6769827", "0.6756172", "0.65721595", "0.6517098", "0.6494844", "0.6461456", "0.6375029", "0.6318517", "0.6312991", "0.6210087", "0.6203009", "0.6105097", "0.60498416", "0.59993887", "0.5988052", "0.5903205", "0.5868917", "0.5858315", "0.5857097",...
0.690302
1
Gets a specific number of builds from the project.
async def get_builds(self, *, quantity=10):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getBuild(number):", "def getBuild(number):", "def getBuilds():", "def get_first_n_built_chunk_ids(self, number):\n try:\n conn = psycopg2.connect(\"dbname='{0}'\".format(DATABASE))\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"S...
[ "0.728129", "0.728129", "0.6382856", "0.62236434", "0.6215881", "0.6080445", "0.6080445", "0.59587866", "0.59204555", "0.57647854", "0.5759255", "0.5724999", "0.5719008", "0.56793606", "0.56029767", "0.5565936", "0.55610716", "0.5540158", "0.54715705", "0.54323786", "0.541285...
0.73818636
0
Makes a standard GET request.
async def _get_request(self, url): # Request the specific URL async with self.session.get(url, headers=self.headers) as resp: # Finally return the response return await resp.json()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_GET(self):\n self.http_method = 'GET'\n self.response()", "def get(self, *args, **kwargs):\n self.request(\"get\", *args, **kwargs)", "def get(self, *path, **data):\n\t\treturn self.request('GET', *path, **data)", "def get(self, *args, **kw):\n kw['method'] = 'GET'\n ...
[ "0.80039424", "0.80005825", "0.78939396", "0.78344136", "0.78143454", "0.7742659", "0.77352524", "0.7651303", "0.76458156", "0.7521482", "0.7480341", "0.7438129", "0.73957163", "0.7381664", "0.73425716", "0.7260178", "0.724971", "0.72437644", "0.72252953", "0.71955794", "0.71...
0.0
-1
Makes a standard POST request.
async def _post_request(self, url, data): # Request the specific URL async with self.session.post(url, headers=self.headers, data=data) as resp: # Finally return the response return await resp.json()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _post(self, *args, **kwargs):\n return self._request('post', *args, **kwargs)", "def post(self, *args, **kwargs):\n return self._requests_call(util.requests_post, *args, **kwargs)", "def do_POST(self,):\n self.http_method = 'POST'\n self.response()", "def http_method_post():\n ...
[ "0.79926836", "0.7943902", "0.77661425", "0.77203214", "0.7624726", "0.7573087", "0.7498776", "0.74799937", "0.74722564", "0.7380111", "0.7328185", "0.73026544", "0.7286208", "0.728303", "0.7274627", "0.7264573", "0.72540253", "0.721007", "0.7161422", "0.70747304", "0.7067027...
0.0
-1
Return `ret_value` `times` times. If generator will receive some value from outside, update `ret_value`
def exercise_gen(ret_val, times):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def counter_wrapper(generator):\n for value in generator:\n yield value", "def counter_wrapper_2(generator):\n yield from generator", "def _mc_gen():\r\n n = 1\r\n while True:\r\n yield n\r\n n += 1", "def random_values():\n while True:\n yield random()", "def Cou...
[ "0.6483438", "0.6218066", "0.6070627", "0.60574543", "0.5988066", "0.58443666", "0.5823438", "0.57975304", "0.5627555", "0.5625004", "0.5599266", "0.5565379", "0.55576694", "0.5519748", "0.5512081", "0.5501229", "0.54756796", "0.5460212", "0.5435833", "0.54218477", "0.5420322...
0.7192209
0
Update `exercise_gen`, so it will ignore all exceptions
def exercise2(): g1 = exercise_gen("I'll ignore errors", 300) assert next(g1) == "I'll ignore errors" assert g1.send('new val') == 'new val' assert g1.throw(Exception) == 'new val' assert next(g1) == 'new val'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def exercise_gen(ret_val, times):", "def experiment3():\n raise FAKE_ERROR", "def test_post_codegen_error_query(self):\n with tempfile.TemporaryDirectory() as tmpdirname:\n translator = AstUprootTranslator()\n with pytest.raises(GenerateCodeException):\n translato...
[ "0.5758369", "0.56753606", "0.5549753", "0.53802556", "0.53689146", "0.53568685", "0.5292572", "0.528666", "0.5275125", "0.5251637", "0.5170305", "0.51676023", "0.51614165", "0.51531315", "0.5127131", "0.5115587", "0.51139444", "0.5084856", "0.50776774", "0.50622576", "0.5061...
0.6592326
0
Token serializer encodes a JWT correctly.
def test_encode_token(token): assert token.count('.') == 2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def encode(self, payload):\n jwt_payload = payload.copy()\n if self.audience is not None:\n jwt_payload['aud'] = self.audience\n if self.issuer is not None:\n jwt_payload['iss'] = self.issuer\n\n token = jwt.encode(jwt_payload, self.signing_key, algorithm=self.algo...
[ "0.75908905", "0.7349595", "0.7172348", "0.713091", "0.7116758", "0.7112599", "0.70149577", "0.6970601", "0.69599897", "0.6854216", "0.67782104", "0.6765446", "0.6761364", "0.6754647", "0.6741674", "0.6682431", "0.6675914", "0.6661425", "0.6659169", "0.66204983", "0.6594343",...
0.0
-1
Token decoder decodes a JWT correctly.
def test_decode_token(token): payload = User.decode_auth_token(token) user = User.find_by_id(payload.get('id')) assert isinstance(user, User) is True assert user.email == 'adminuser@test.com'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def decode_token(token):\n decoded_token = jwt.decode(token, secret_key, algorithms=['HS256'])\n return decoded_token", "def decode(encoded_token):\n return jwt.decode(encoded_token, key=settings.JWT_AUTH['JWT_SECRET_KEY'])", "def decodeJWT(self, token):\n try:\n return jwt.decode(to...
[ "0.8136295", "0.80802256", "0.80535865", "0.8051602", "0.7912598", "0.76581925", "0.7536502", "0.73548025", "0.7299482", "0.725423", "0.71652126", "0.7159311", "0.71550864", "0.70829904", "0.70726466", "0.70687157", "0.7039805", "0.6997798", "0.69963163", "0.6974989", "0.6951...
0.5956171
51
Token decoder returns 'Invalid token' when it's been tampered with.
def test_decode_token_invalid(token): payload = User.decode_auth_token(f'{token}1337') assert isinstance(payload, User) is False assert 'Invalid token' in payload
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def decode_token(token):\n decoded_token = jwt.decode(token, secret_key, algorithms=['HS256'])\n return decoded_token", "def decode_token(token):\n\n return jwt.decode(\n token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGO])", "def decode_token(token):\n try:\n #...
[ "0.7511837", "0.74077404", "0.7329391", "0.7277755", "0.7243613", "0.72420645", "0.7237718", "0.721192", "0.7203428", "0.71465415", "0.71348214", "0.7133082", "0.7113959", "0.7102475", "0.69896144", "0.69554555", "0.6920015", "0.6862283", "0.68387103", "0.6809911", "0.6779272...
0.73733056
2
Compute the output value of the neuron
def compute_output(self, input_data, no_update_wsi=False): # compute weighted sum of inputs if not no_update_wsi: self.compute_wsi(input_data) # compute output based on initialization if self.activation_type == 'step': self.output = Neuron.step_function(self.wsi) elif self.activation_type == 'sigmoidal': self.output = Neuron.sigmoidal_function(self.wsi, self.af_param) elif self.activation_type == 'hyperbolic': self.output = Neuron.hyperbolic_function(self.wsi) elif self.activation_type == 'gaussian': self.output = Neuron.gaussian_function(self.wsi)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute_output(self):\n x, y = self.input_nodes\n self.output_value = backend.multiply(x.output_value, y.output_value)\n return self.output_value", "def compute_output(self):\n x, y = self.input_nodes\n self.output_value = backend.add(x.output_value, y.output_value)\n ...
[ "0.8310454", "0.7989595", "0.79795736", "0.7532791", "0.73399097", "0.70779973", "0.7050204", "0.70237565", "0.6919432", "0.6769719", "0.6748662", "0.6733867", "0.6672669", "0.6672669", "0.6672258", "0.6666061", "0.65460163", "0.6545946", "0.6545946", "0.6528449", "0.64545137...
0.7061461
6
Compute the weighted sum of input vectors
def compute_wsi(self, input_data, weights = None, theta_weight = None): if weights is None or theta_weight is None: self.wsi = self.theta_weight for index, value in enumerate(input_data): self.wsi = self.wsi + ( value * self.input_weights[index] ) else: self.wsi = theta_weight for index, value in enumerate(input_data): self.wsi = self.wsi + ( value * weights[index] )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def weighted_sum(W, X):\n\n if len(W) != len(X):\n print(\"Dimension of weight vector should be same as input vector.\")\n return\n\n else:\n H = 0\n\n for i in range(len(W)):\n H += (W[i] * X[i])\n \n return H", "def weighted_sum(self, inputs):\r\n weigh...
[ "0.82214683", "0.798617", "0.7376457", "0.7061534", "0.70244205", "0.70015985", "0.6983011", "0.6930713", "0.692332", "0.6872867", "0.68701", "0.686605", "0.6858394", "0.68492305", "0.6845547", "0.6835387", "0.6827912", "0.68278885", "0.6817227", "0.6780031", "0.672747", "0...
0.0
-1
Update weights based on last input/output and learning rate
def update_weights(self): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __update(self, learning_rate):\n for layer in self.layers:\n layer.weights.set_value((layer.weights - learning_rate * layer.dW).eval())\n layer.biases.set_value((layer.biases - learning_rate * layer.db).eval())", "def update_weights(self):\n\n\n self.w += self.learn_rate *...
[ "0.80830616", "0.7857255", "0.77221936", "0.75878155", "0.7544157", "0.75073385", "0.7503516", "0.74666196", "0.7415437", "0.7407029", "0.7364739", "0.7336763", "0.7227047", "0.721761", "0.7210267", "0.71573895", "0.7152569", "0.7145055", "0.7145055", "0.7090362", "0.7078788"...
0.7508802
5
console print, with color
def print_color(line, color=Colors.DEFAULT): sys.stdout.write("{}{}{}".format(color.value, line, Colors.DEFAULT.value))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def printcolor(color, text):\r\n pushcolor()\r\n setcolor(color)\r\n print text\r\n popcolor()", "def color_print(txt, foreground=PALETTE['white'], background=PALETTE['black']):\n print(color_text(txt, foreground, background))", "def color_print(message, color, newline='\\n'):\n sys.stderr.wr...
[ "0.77871144", "0.7595031", "0.7444135", "0.7422378", "0.73676646", "0.7366209", "0.72847176", "0.7264958", "0.7261931", "0.7220704", "0.7219369", "0.7175978", "0.7156872", "0.71309286", "0.70842475", "0.7082594", "0.7079263", "0.70496935", "0.6940176", "0.69390655", "0.693685...
0.75665677
2
setup function called before each test
def before_each_test(self, request): self.test_counter = Counter() self.check_ref = request.config.getvalue("check_ref") self.create_ref = request.config.getvalue("create_ref")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setUp(self):\n test_env_setup()", "def setUp(self):\r\n # nothing to do, all tests use different things\r\n pass", "def setUp(self):\n MainTests.setUp(self)", "def _fixture_setup(self):\n pass", "def setUp(self):\n pass #because we dont have anything to setup."...
[ "0.84756434", "0.83393013", "0.83271843", "0.83170396", "0.82956946", "0.8280618", "0.8280618", "0.8279627", "0.82470554", "0.82384115", "0.82242966", "0.82242966", "0.82242966", "0.82242966", "0.82242966", "0.82242966", "0.82242966", "0.82242966", "0.82242966", "0.82242966", ...
0.0
-1
Does nothing. Inherited from old Artemis where the kraken is stopped then started In Artemis NG, the kraken is restarted in 'kill_the_krakens'
def pop_krakens(cls): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def restart(self):", "def restart(self) -> None:", "def stopEngines():\n pass", "def _restart(self):\n pass", "def restart(self):\r\n pass", "def _kill_kernel(self):", "def restart(self):\n pass", "def restart(self):\n self.km.restart_kernel(now=True)", "def reboot(se...
[ "0.6768174", "0.67484814", "0.6615716", "0.6595835", "0.6585611", "0.6582545", "0.658062", "0.64321345", "0.63734066", "0.6317657", "0.62966824", "0.6273129", "0.6253487", "0.6223028", "0.6221627", "0.6221627", "0.62077504", "0.62009984", "0.6190042", "0.6188181", "0.6167238"...
0.0
-1
used to check misc API
def api(self, url, response_checker=default_checker.default_checker): return self._api_call(url, response_checker)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check():", "def check_eapi(self, eapi):\n\t\treturn True", "def test_api() -> bool:\r\n weather = False\r\n news = False\r\n covid = False\r\n if check_weather_version():\r\n logging.info(\"Weather API version is up to date (check_weather_version())\")\r\n weather = True\r\n el...
[ "0.6912855", "0.66411334", "0.64717084", "0.6467784", "0.64383173", "0.62957495", "0.6267212", "0.62266237", "0.6179696", "0.61172795", "0.6099899", "0.6095906", "0.6094198", "0.6077264", "0.6034731", "0.6029176", "0.60286736", "0.60286736", "0.60286736", "0.60286736", "0.598...
0.0
-1
call the api and check against previous results the query is written in a file
def _api_call(self, url, response_checker): self.request_compare(url)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_data( filepath_query, filepath_results ):\n with open( filepath_query, 'r' ) as query_file:\n query = json.load( query_file )\n \n query_text = query['query']['multi_match']['query']\n query_scores = query['nlp_scores']\n query_data = {\n 'query_text' : query_text,\n 'bi...
[ "0.6289538", "0.6239065", "0.6121396", "0.60783744", "0.6044701", "0.6038592", "0.6030916", "0.6013815", "0.5947279", "0.5914782", "0.5909344", "0.58337414", "0.5818949", "0.5799132", "0.57944274", "0.5789064", "0.5784416", "0.5783246", "0.5760673", "0.5746683", "0.570731", ...
0.0
-1
This function is coming from the test_mechanism.py file. We only use the part that generates the url. Other parts are calling test that fail because we do not have the whole navitia running. Thus, we do not need the "self" parameter, and response_checker is set to None. We have also added parts of other functions into it. Therefore, we only need to call journey and all the test are done from inside.
def journey( self, _from, to, datetime, datetime_represents="departure", first_section_mode=[], last_section_mode=[], forbidden_uris=[], direct_path_mode=[], **kwargs ): # Creating the URL with all the parameters for the query assert datetime query = "from={real_from}&to={real_to}&datetime={date}&datetime_represents={represent}".format( date=datetime, represent=datetime_represents, real_from=_from, real_to=to ) for mode in first_section_mode: query = "{query}&first_section_mode[]={mode}".format(query=query, mode=mode) for mode in last_section_mode: query = "{query}&last_section_mode[]={mode}".format(query=query, mode=mode) for mode in direct_path_mode: query = "{query}&direct_path_mode[]={mode}".format(query=query, mode=mode) for uri in forbidden_uris: query = "{query}&forbidden_uris[]={uri}".format(query=query, uri=uri) for k, v in six.iteritems(kwargs): query = "{query}&{k}={v}".format(query=query, k=k, v=v) # Override scenario if self.__class__.data_sets[0].scenario in [ "distributed", "experimental", "asgard", ]: overridden_scenario = "distributed" else: overridden_scenario = "new_default" query = "{query}&_override_scenario={scenario}".format( query=query, scenario=overridden_scenario ) # launching request dans comparing self.request_compare("journeys?" + query)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_tour_complete_url_redirect(self):\n # complete tour and try to go to first step\n self.tour1.load_tour_class().add_user(self.test_user)\n mock_request = Mock(user=self.test_user, path='mock1', method='get', GET={})\n mock_view = MockView(request=mock_request)\n response ...
[ "0.6109293", "0.6100165", "0.6068033", "0.60075814", "0.5958549", "0.5953743", "0.5904192", "0.5858552", "0.5848845", "0.5810708", "0.57947206", "0.57568485", "0.57560605", "0.5703684", "0.5696326", "0.56882894", "0.5676402", "0.5666247", "0.5610928", "0.5601853", "0.5570623"...
0.0
-1