query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Returns True if there is a soldier in the army on position (x, y)
def isSoldier(army, x, y): return getDirectionByPosition(x, y, army) is not None
[ "def is_solved(self):\n return (khun := self.sorted_pieces()[0]).x() == self.goal[0] and khun.y() == self.goal[1]", "def is_solved(self):\n carName = 'X'\n squares = [(i, j) for i in range(6) for j in range(6) if self.board[i][j] == carName]\n edge = squares[1]\n return edge[1] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the (x, y) position on the map is a wall, otherwise return False.
def isWall(mapObj, x, y): if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]): return False # x and y aren't actually on the map. elif mapObj[x][y] in ('#', 'x'): return True # wall is blocking return False
[ "def is_wall(self, x, y):\n\t\treturn self.get_bool(x, y, 'wall')", "def is_wall(self, x, y):\n return self.get_tile(x, y) == Tile.wall", "def check_wall(self, pos):\n\t\tif(str(pos) in self.wall_map and self.wall_map[str(pos)]):\n\t\t\treturn True\n\t\treturn False", "def is_wall(self, row, col):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes any values matching oldCharacter on the map object to newCharacter at the (x, y) position, and does the same for the positions to the left, right, down, and up of (x, y), recursively.
def floodFill(mapObj, position, oldCharacter, newCharacter): # In this game, the flood fill algorithm creates the inside/outside # floor distinction. This is a "recursive" function. # For more info on the Flood Fill algorithm, see: # http://en.wikipedia.org/wiki/Flood_fill x, y = position if mapObj[x][y] == oldCharacter: mapObj[x][y] = newCharacter if x < len(mapObj) - 1 and mapObj[x + 1][y] == oldCharacter: floodFill(mapObj, (x + 1, y), oldCharacter, newCharacter) # call right if x > 0 and mapObj[x - 1][y] == oldCharacter: floodFill(mapObj, (x - 1, y), oldCharacter, newCharacter) # call left if y < len(mapObj[x]) - 1 and mapObj[x][y + 1] == oldCharacter: floodFill(mapObj, (x, y + 1), oldCharacter, newCharacter) # call down if y > 0 and mapObj[x][y - 1] == oldCharacter: floodFill(mapObj, (x, y - 1), oldCharacter, newCharacter) # call up
[ "def change_map(self, pos: int, char: str) -> None:\r\n map_list = list(self.map)\r\n map_list[pos] = char\r\n self.map = \"\".join(map_list)", "def updateBoard(board, row, col, character):\n pass", "def characterMap(mapMethod=\"string\", mapping=\"string\", unmapNode=\"string\", map...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the direction of soldier on (x, y) Return None if no soldier in the army is on (x, y)
def getDirectionByPosition(x, y, army): for soldier in army: if (x, y) == soldier.getPosition(): return soldier.direction return None
[ "def direction(x1, y1, x2, y2):\n\tif x1 == x2 and y2 > y1:\n\t\treturn NORTH\n\telif x1 == x2 and y2 < y1:\n\t\treturn SOUTH\n\telif y1 == y2 and x2> x1:\n\t\treturn EAST\n\telif y1 == y2 and x2 < x1:\n\t\treturn WEST\n\telse:\t\n\t\treturn None", "def isSoldier(army, x, y):\n return getDirectionByPosition(x,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a datashape instance into Aterm annotation >>> ds = dshape('2, 2, int32') >>> anno = dshape_anno(ds) dshape("2, 2, int32") >>> type(anno)
def annotate_dshape(ds): assert isinstance(ds, DataShape) return AAppl(ATerm('dshape'), [AString(str(ds))])
[ "def annotate(args):\n from .annotation.annotation import annotate as anno\n anno(args)", "def test_create_from_gds_type(self):\n _b = emdb_sff.biological_annotationType(\n name=self.name,\n description=self.description,\n number_of_instances=self.no,\n externa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the NCBImetaAnnotate application in concatenate mode for run completion
def test_annotate_concatenate_run(): # Use the test database test_db = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test.sqlite") test_annotfile = os.path.join( os.path.dirname(os.path.abspath(__file__)), "test_annot.txt" ) # If the test_db doesn't alread exist, run the test cmd from test_ncbimeta if not os.path.exists(test_db): test_ncbimeta.test_ncbimeta_run() test_table = "BioSample" test_cmd = ( "ncbimeta/NCBImetaAnnotate --database " + test_db + " --table " + test_table + " --annotfile " + test_annotfile + " --concatenate" ) # test NCBImetaAnnotate through a subprocess returned_value = subprocess.call(test_cmd, shell=True) # If it returns a non-zero value, it failed assert returned_value == 0
[ "def test_annotate_replace_run():\n # Use the test database\n test_db = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"test.sqlite\")\n test_annotfile = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"test_annot.txt\"\n )\n # If the test_db doesn't already exist, run ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the NCBImetaAnnotate application for run completion
def test_annotate_replace_run(): # Use the test database test_db = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test.sqlite") test_annotfile = os.path.join( os.path.dirname(os.path.abspath(__file__)), "test_annot.txt" ) # If the test_db doesn't already exist, run the test cmd from test_ncbimeta if not os.path.exists(test_db): test_ncbimeta.test_ncbimeta_run() test_table = "BioSample" test_cmd = ( "ncbimeta/NCBImetaAnnotate --database " + test_db + " --table " + test_table + " --annotfile " + test_annotfile ) # test NCBImetaAnnotate through a subprocess returned_value = subprocess.call(test_cmd, shell=True) # If it returns a non-zero value, it failed assert returned_value == 0
[ "def test_annotate_concatenate_run():\n # Use the test database\n test_db = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"test.sqlite\")\n test_annotfile = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"test_annot.txt\"\n )\n # If the test_db doesn't alread exist, r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse table to MADX sequence and return it as a string. Returns str MADX sequence
def parse_table_to_madx_sequence_string(self) -> str: return parse_table_to_madx_sequence_string(self.name, self.len, self.table)
[ "def parse_table_to_madx_line_string(self) -> str:\n self.add_drifts()\n defstr = _parse_table_to_madx_definitions(self.table)\n linestr = \"{}: LINE=({});\".format(\n self.name,\n \",\\n\\t\\t\".join(\n [\",\".join(c) for c in list(self.chunks(self.table.na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse table to MADX sequence and write it to file.
def parse_table_to_madx_sequence_file(self, filename: str) -> None: parse_table_to_madx_sequence_file(self.name, self.len, self.table, filename)
[ "def parse_table_to_madx_line_file(self, filename: str):\n save_string(self.parse_table_to_madx_line_string(), filename)", "def parse_table_to_madx_sequence_string(self) -> str:\n return parse_table_to_madx_sequence_string(self.name, self.len, self.table)", "def parse_table_to_tracy_file(self, fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse table to Elegant lattice and return it as a string. Returns str Elegant Lattice
def parse_table_to_elegant_string(self) -> str: self.add_drifts() return parse_table_to_elegant_string(self.name, self.table)
[ "def lattice2str(lattice):\n latticeStr = []\n for i in range(len(lattice)):\n latticeStr.append(elem2str(lattice[i]))\n return latticeStr", "def parse_table_to_tracy_string(self) -> str:\n return parse_table_to_tracy_string(self.name, self.table)", "def parse_table_to_madx_line_string(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse table to Elegant lattice and write it to file.
def parse_table_to_elegant_file(self, filename: str) -> None: self.add_drifts() parse_table_to_elegant_file(self.name, self.table, filename)
[ "def parse_table_to_tracy_file(self, filename: str) -> None:\n parse_table_to_tracy_file(self.name, self.table, filename)", "def parse_table_to_madx_line_file(self, filename: str):\n save_string(self.parse_table_to_madx_line_string(), filename)", "def convert_lattice(file_in, file_out):\n open_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse table to Tracy lattice and return it as a string. Returns str Tracy Lattice
def parse_table_to_tracy_string(self) -> str: return parse_table_to_tracy_string(self.name, self.table)
[ "def lattice2str(lattice):\n latticeStr = []\n for i in range(len(lattice)):\n latticeStr.append(elem2str(lattice[i]))\n return latticeStr", "def parse_table_to_elegant_string(self) -> str:\n self.add_drifts()\n return parse_table_to_elegant_string(self.name, self.table)", "def par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse table to Tracy lattice and write it to file.
def parse_table_to_tracy_file(self, filename: str) -> None: parse_table_to_tracy_file(self.name, self.table, filename)
[ "def write_table(self):\n o = open(self.out_file, 'w')\n o.write(self.table)", "def _write_table(self, table, path):\n io.write(table, path)", "def parse_table_to_madx_line_file(self, filename: str):\n save_string(self.parse_table_to_madx_line_string(), filename)", "def parse_table...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return MADX string to install marker at start and end of the lattice. Returns str MADX install string that can be run with cpymad.
def madx_sequence_add_start_end_marker_string(self) -> str: return install_start_end_marker(self.name, self.len)
[ "def parse_table_to_madx_install_str(self) -> str:\n return parse_table_to_madx_install_str(self.name, self.table)", "def _create_cmd(self):\n comment = (\"#-------------------\\n\"\n \"# Install ANTs {}\\n\"\n \"#-------------------\".format(self.version))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to generate a MADX install element string based on the table. This string can be used by cpymad to install new elements. Returns str Install element string input for MADX.
def parse_table_to_madx_install_str(self) -> str: return parse_table_to_madx_install_str(self.name, self.table)
[ "def _create_cmd(self):\n comment = (\"#-------------------\\n\"\n \"# Install ANTs {}\\n\"\n \"#-------------------\".format(self.version))\n if self.use_binaries:\n chunks = [comment, self.install_binaries()]\n else:\n chunks = [commen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to generate a MADX remove element string based on the table. This string can be used by cpymad to remove elements.add() Returns str Remove element string input for MADX.
def parse_table_to_madx_remove_str(self) -> str: return parse_table_to_madx_remove_str(self.name, self.table)
[ "def removeElement(self):", "def on_remove_tid(self, event):\n if STATUS.currentSelectedFrame[STATUS.cur_workingtable] is None:\n return\n id_to_remove = ''\n ids = self.get_tid(event.widget.index)\n ids_array = ids.split(',')\n # Remove word_id in the trans entry :\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to convert the table to a MADX line definition lattice. Returns str MADX lattice definition string.
def parse_table_to_madx_line_string(self) -> str: self.add_drifts() defstr = _parse_table_to_madx_definitions(self.table) linestr = "{}: LINE=({});".format( self.name, ",\n\t\t".join( [",".join(c) for c in list(self.chunks(self.table.name.to_list(), 20))] ), ) return defstr + "\n\n" + linestr
[ "def to_linestringm_wkt(self):\n # Shapely only supports x, y, z. Therefore, this is a bit hacky!\n coords = \"\"\n for index, row in self.df.iterrows():\n pt = row[self.get_geom_column_name()]\n t = to_unixtime(index)\n coords += \"{} {} {}, \".format(pt.x, pt....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to convert table to madx line def lattice file string and write to file.
def parse_table_to_madx_line_file(self, filename: str): save_string(self.parse_table_to_madx_line_string(), filename)
[ "def parse_table_to_madx_line_string(self) -> str:\n self.add_drifts()\n defstr = _parse_table_to_madx_definitions(self.table)\n linestr = \"{}: LINE=({});\".format(\n self.name,\n \",\\n\\t\\t\".join(\n [\",\".join(c) for c in list(self.chunks(self.table.na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to return quadrupole strengths as a dict.
def get_quad_strengths(self) -> dict: return ( self.table.loc[self.table.family == "QUADRUPOLE", ["name", "K1"]] .set_index("name", drop=True) .to_dict()["K1"] )
[ "def _getSquaresDict(self) -> dict:\n squares = {}\n for y in range(0, len(self._map)):\n row = self._map[y]\n for x in range(0, len(row)):\n char = row[x]\n pos = array([x, y])\n if char in squares.keys():\n squares...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to return sextupole strengths as a dict
def get_sext_strengths(self) -> dict: if "SEXTUPOLE" in self.table.family.values: return ( self.table.loc[self.table.family == "SEXTUPOLE", ["name", "K2"]] .set_index("name", drop=True) .to_dict()["K2"] ) else: return {}
[ "def get_quad_strengths(self) -> dict:\n return (\n self.table.loc[self.table.family == \"QUADRUPOLE\", [\"name\", \"K1\"]]\n .set_index(\"name\", drop=True)\n .to_dict()[\"K1\"]\n )", "def x_threat_rating_map(self):\n return {\n '0': 'Threat Rating...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to load a dictionary with strength settings to the table. The col attribute is where the strengths will be loaded to.
def load_strengths_to_table(self, strdc: dict, col: str) -> None: self.history.put((deepcopy(self.name), deepcopy(self.len), deepcopy(self.table))) for k, v in strdc.items(): self.table.loc[self.table["name"] == k, col] = v
[ "def setTableattrs( self, indict ):\n\n for key in indict.keys():\n val = indict[key]\n tpair = \"\"\" %s=\"%s\" \"\"\" % (key,val)\n self.tabattr = self.tabattr + tpair", "def get_sext_strengths(self) -> dict:\n if \"SEXTUPOLE\" in self.table.family.values:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an authenticated SOAP client to access an SOAP service.
def _create_client(self, service): # We must specify service and port for Nuxeo client = suds.client.Client( '/'.join((self.settings.repository_url, service)) + '?wsdl', proxy=self.proxies, service=service, port=service + 'Port', cachingpolicy=1) if self.settings.repository_user: # Timestamp must be included, and be first for Alfresco. auth = suds.wsse.Security() auth.tokens.append(suds.wsse.Timestamp(validity=300)) auth.tokens.append(suds.wsse.UsernameToken( self.settings.repository_user, self.settings.repository_password)) client.set_options(wsse=auth) return client.service
[ "def _create_suds_client(self):\n\n self.client = Client(const.WSDLLOCAL)\n self.client.set_options(service = ApiClient._sdict[self.service][0],\n headers = {'user-agent': const.USERAGENT})\n\n # put username (and password if necessary) into the headers.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a test player.
def _test_gsplayer(name, money, shares_map, tiles): player = GameStatePlayer() player.name = name player.money = money player.shares_map = shares_map player.tiles = tiles return player
[ "def test_player_details_by_player(self):\n pass", "def create_player(name):\n if name.lower() == \"ai\":\n return Player(name.upper(), 'computer')\n else:\n return Player(name.title(), 'human')", "def new_player(self, client_id, player_id=None, player_type = None, is_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns whether this player has shares of given hotel
def has_shares_of(self, hotel): return self.shares_map[hotel] > 0
[ "def players_with_stocks(self, hotel):\r\n return [(p, p.shares_map[hotel])\r\n for p in self.players if p.has_shares_of(hotel)]", "def buy_stock(self, hotel):\r\n stock_price = self.board.stock_price(hotel)\r\n\r\n if stock_price is None:\r\n raise GameStateError(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes all hotel shares from this player
def remove_all_shares(self, hotel): self.shares_map[hotel] = 0
[ "def _remove_cheaters(self, board: Board) -> None:\n for player in self._cheaters:\n if player in self._players:\n del self._players[player]\n if player in board.live_players:\n board.remove_player(player)\n for observer in self._observers:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a [(player, share_count)] for players in this game with stocks in the given hotel to the number of stocks they have in that hotel
def players_with_stocks(self, hotel): return [(p, p.shares_map[hotel]) for p in self.players if p.has_shares_of(hotel)]
[ "def majority_stockholders(self, hotel):\r\n players_with_stocks = self.players_with_stocks(hotel)\r\n max_stocks = max([s for p, s in players_with_stocks])\r\n return set([p for p, s in players_with_stocks if s == max_stocks])", "def get_sellbacks(self, tile, hotel):\n if self.game_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the set of the players in this game with the most stocks in the given hotel
def majority_stockholders(self, hotel): players_with_stocks = self.players_with_stocks(hotel) max_stocks = max([s for p, s in players_with_stocks]) return set([p for p, s in players_with_stocks if s == max_stocks])
[ "def minority_stockholders(self, hotel):\r\n not_majority_shareholders = \\\r\n [(p, s) for p, s in self.players_with_stocks(hotel)\r\n if p not in self.majority_stockholders(hotel)]\r\n if len(not_majority_shareholders) == 0:\r\n return set([])\r\n max_stocks ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the set of the players in this game with the second most stocks in the hotel
def minority_stockholders(self, hotel): not_majority_shareholders = \ [(p, s) for p, s in self.players_with_stocks(hotel) if p not in self.majority_stockholders(hotel)] if len(not_majority_shareholders) == 0: return set([]) max_stocks = max([s for p, s in not_majority_shareholders]) return set([p for p, s in not_majority_shareholders if s == max_stocks])
[ "def majority_stockholders(self, hotel):\r\n players_with_stocks = self.players_with_stocks(hotel)\r\n max_stocks = max([s for p, s in players_with_stocks])\r\n return set([p for p, s in players_with_stocks if s == max_stocks])", "def get_sellbacks(self, tile, hotel):\n if self.game_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Places a tile for this game's current player at the given coord and updates a player with their new stock if there's a found. If not possible, raises a GameStateError.
def place_a_tile(self, coord, hotel=None): def _found(): """ This gamestate's current player makes a move to found the given hotel at the given coord, rewarding them with an appropriate amount of shares. """ if hotel in self.board.hotels_in_play: raise GameStateError("tried to found a hotel that's \ already in play" + hotel) else: self.board.found(coord, hotel) # TODO: What to do about the ELSE case here? # Relevant if players keep shares in acquired hotels # # currently is no stock is available # the founding player recieves nothing if self.shares_map[hotel] > FOUND_SHARES: self.current_player.add_shares(hotel, FOUND_SHARES) self.shares_map[hotel] -= FOUND_SHARES move_type = self.board.query(coord) if SINGLETON == move_type: if hotel is not None: raise GameStateError('Placing a singleton can not take a hotel') self.board.singleton(coord) elif FOUND == move_type: if hotel is None: raise GameStateError('found requires a hotel name') _found() elif GROW == move_type: if hotel is not None: raise GameStateError('Placing a grow should not take a hotel') self.board.grow(coord) elif MERGE == move_type: # DOES NOTHING FOR THE PAYOUT if hotel is None: raise GameStateError('merge requires a hotel name') self.board.merge(coord, hotel) elif INVALID == move_type: raise GameStateError("illegal tile placement") self.current_player.tiles.remove(coord)
[ "def place_player(self, gridpos=(0,0)):\n x,y = gridpos\n if x < 0 or x > self.gridsize-1 or y < 0 or y > self.gridsize-1:\n # Restrict movement to within the grid\n return\n tile = self.grid[x][y]\n if tile:\n if type(tile) == Wall:\n # Do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sell all stocks from given player back to the to the pool for each of the given hotels.
def sellback(self, name, sell_hotels, initial_state): player = self.player_with_name(name) for hotel in sell_hotels: if player.has_shares_of(hotel): hotel_price = initial_state.board.stock_price(hotel) # TODO: remove this assert hotel_price is not None stocks_amount = player.shares_map[hotel] player.money += hotel_price * stocks_amount self.shares_map[hotel] += stocks_amount player.remove_all_shares(hotel)
[ "def get_sellbacks(self, tile, hotel):\n if self.game_state.board.valid_merge_placement(tile, hotel):\n acquirees = self.game_state.board.acquirees(tile, hotel)\n\n all_sellbacks = \\\n map(list,\n chain(*[combinations(acquirees, c) for c in range(len(a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this game's current player buys a share of stock in the given hotel
def buy_stock(self, hotel): stock_price = self.board.stock_price(hotel) if stock_price is None: raise GameStateError("Cannot buy a hotel that is not in play") if self.shares_map[hotel] == 0: raise GameStateError("{0} has no shares to buy".format(hotel)) if self.current_player.money < stock_price: raise GameStateError("current player can't afford stock for "+hotel) self.shares_map[hotel] -= 1 self.current_player.money -= stock_price self.current_player.shares_map[hotel] += 1
[ "def sellback(self, name, sell_hotels, initial_state):\r\n player = self.player_with_name(name)\r\n for hotel in sell_hotels:\r\n if player.has_shares_of(hotel):\r\n hotel_price = initial_state.board.stock_price(hotel)\r\n\r\n # TODO: remove this\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a merger payout if the given tile, hotel constitute a merger.
def merge_payout(self, tile, maybeHotel, initial_state, end_of_game=False): if not initial_state.board.valid_merge_placement(tile, maybeHotel): return acquirer = maybeHotel acquirees = initial_state.board.acquirees(tile, acquirer) for acquiree in acquirees: stock_price = initial_state.board.stock_price(acquiree) # TODO: Remove this... assert stock_price is not None self.payout(acquiree, stock_price, initial_state)
[ "def payout(self, hotel, price, state):\r\n\r\n def to_current_player(player):\r\n \"\"\" returns the player from this gamestate with player's name \"\"\"\r\n return self.player_with_name(player.name)\r\n\r\n majority_stockholders = \\\r\n [to_current_player(p)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Payout the merger bonus for the given hotel at the given price
def payout(self, hotel, price, state): def to_current_player(player): """ returns the player from this gamestate with player's name """ return self.player_with_name(player.name) majority_stockholders = \ [to_current_player(p) for p in state.majority_stockholders(hotel)] minority_stockholders = \ [to_current_player(p) for p in state.minority_stockholders(hotel)] majority_payout = MAJORITY_PAYOUT_SCALE * price minority_payout = MINORITY_PAYOUT_SCALE * price if len(majority_stockholders) == 1: player = majority_stockholders.pop() player.money += majority_payout if len(minority_stockholders) == 1: player = minority_stockholders.pop() player.money += minority_payout elif len(minority_stockholders) > 1: payout = \ divide_and_round_integers(minority_payout, len(minority_stockholders)) for player in minority_stockholders: player.money += payout else: payout = \ divide_and_round_integers(majority_payout + minority_payout, len(majority_stockholders)) for player in majority_stockholders: player.money += payout
[ "def pay(self, cost):\n if self.is_affordable(cost):\n self.money -= cost", "def sell_to_bank(self, game):\n owner = self.find_owner(game=game)\n owner.liquid_holdings += self.price * 0.5\n owner.property_holdings.remove(self)\n game.bank.property_holdings.append(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
end the this game's current player's turn, allocating a tile if possible and moving on to the next player
def done(self, tile): if len(self.tile_deck) > 0: if tile in self.tile_deck: self._give_player_tile(self.current_player, tile) else: raise GameStateError("tile not in deck " + tile) else: raise GameStateError("tile_deck is empty") self.players.rotate(-1)
[ "def end_turn(self):\n for x in self.units.keys():\n x.tick()\n self.side1.tick()\n self.side2.tick()", "def end_turn(self, block):\n for i, j in block.call_shape():\n self._board[i][j] = 2\n self._occupied.append([i, j])\n self.game_over()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gives the player in this game the tile and removes it from the deck
def _give_player_tile(self, player, tile): player.tiles.add(tile) self.tile_deck.remove(tile)
[ "def remove_player(self, player_shot: Name):\n del self.players[player_shot]\n for name, player in self.players.items():\n player.remove_player(player_shot)", "def remove_player(self):\n if self.num_player > 0:\n self.num_player -= 1\n self.available_place += ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns whether we can we do a done move with the given tile
def is_valid_done(self, tile): return tile in self.tile_deck
[ "def check_if_next_tile_is_hit(self):\n board = self._board_object.get_board()\n if self._direction == 'down':\n if board[self._row + 1][self._column] == 'a' or board[self._row + 1][self._column] == 'h':\n return True\n if self._direction == 'up':\n if board...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates self.ticket_list with all tickets seen in a given view
def get_tickets_in_view(self): logger.info("Entered get_tickets_in_view") try: page_num = 1 while True: url_to_request = self.freshdesk_info['url'] + self.freshdesk_info['view_url'].format(self.freshdesk_info['view_number']) + str(page_num) logger.debug("Requesting {}".format(url_to_request)) r = requests.get(url_to_request, auth=(self.freshdesk_info['api_key'], "X")) returned_json = json.loads(r.text) logger.debug("We received json back: {}".format(returned_json)) # if we received no tickets, we break and stop requesting more if not returned_json: logger.debug("We broke out because no json was returned") break page_num += 1 self.ticket_list.extend(returned_json) time.sleep(self.sleep_time) except KeyboardInterrupt: raise except Exception as e: logger.warning("Error in get_tickets_in_view: {}".format(str(e))) raise
[ "def all_tickets(request):\n tickets = Ticket.objects.all()\n return render(request, \"tickets.html\", {'tickets': tickets})", "def test_view_all_tickets(app):\n for i in range(10):\n tick = Ticket(\n title=\"Ticket {}\".format(i),\n text=\"Text {}\".format(i),\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all tickets with original_status and changes to new_status If the revert argument is true, it will only change tickets found in the changed.txt file in the script directory. This is so we don't clobber views and only undo what we last did
def change_ticket_statuses(self, original_status, new_status, revert): def make_request(ticket_number): url_to_request = ticket_update_url + str(ticket_number) logger.debug("Sending request: {} with data: {}".format(url_to_request, send_data)) r = requests.put(url_to_request, auth=(self.freshdesk_info['api_key'], "X"), data=send_data, headers=headers) logger.info('Updated ticket {} with request {}'.format(ticket_number, url_to_request)) logger.info("Entered change_ticket_statuses") headers = {'Content-Type': 'application/json'} ticket_update_url = self.freshdesk_info['url'] + self.freshdesk_info['ticket_view'] send_data = json.dumps({'status': int(new_status)}) logger.debug("We have ticket list to check: {}".format(self.ticket_list)) if(revert): with open(path_to_changed_file, 'r') as changed_file: for ticket_number in changed_file: try: make_request(ticket_number) except requests.exceptions.RequestException as e: logger.warning("Requests exception when changing ticket status: {}".format(str(e))) pass except Exception as e: logger.error("Unhandled exception when reverting ticket status! {}".format(str(e))) print("Unhandled exception when changing ticket status! {}".format(str(e))) pass else: with open(path_to_changed_file, 'w') as changed_file: for ticket in self.ticket_list: try: changed = False logger.debug("Checking if ticket status {} matches original status {}".format(ticket['status'], original_status)) if str(ticket['status']) == str(original_status): make_request(ticket['display_id']) changed = True except requests.exceptions.RequestException as e: logger.warning("Requests exception when changing ticket status: {}".format(str(e))) pass except Exception as e: logger.error("Unhandled exception when changing ticket status! {}".format(str(e))) print("Unhandled exception when changing ticket status! {}".format(str(e))) pass else: # write ticket number to changed file if changed: changed_file.write(str(ticket['display_id']) + '\n')
[ "def _localChanges(repos, changeSet, curTrove, srcTrove, newVersion, root, flags,\n withFileContents=True, forceSha1=False,\n ignoreTransient=False, ignoreAutoSource=False,\n crossRepositoryDeltas = True, allowMissingFiles = False,\n callback=Updat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a value from the json config using dot accessor
def get(self, key): return self._get(self._config, key.split('.'))
[ "def jsonpath(ctx, **kwargs):\n kwargs[\"_get_value\"] = True\n run_command_with_config(ConfigCommand, ctx, **kwargs)", "def dotdictget(myjson, dotdict):\n if re_delim.match(dotdict):\n normalized_dotdict = dotdict\n else:\n normalized_dotdict = '.' + dotdict\n\n return _dotdictget(my...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unpacks the dictionary response from Boto3 and makes a nice dataclass with the some of the more useful details of the EC2 instance
def instance_from_response(response: Dict) -> List[EC2Instance]: ec2_instances = [] for reservation in response.get("Reservations"): for instance in reservation.get("Instances"): if dns := instance.get("PublicDnsName"): public_dns_name = dns else: public_dns_name = "NONE" if ip := instance.get("PublicIpAddress"): public_ip_address = ip else: public_ip_address = "NONE" ec2_instance = EC2Instance( image_id=instance.get("ImageId"), instance_id=instance.get("InstanceId"), instance_type=instance.get("InstanceType"), launch_time=instance.get("LaunchTime"), availability_zone=instance.get("Placement").get("AvailabilityZone"), private_dns_name=instance.get("PrivateDnsName"), private_ip_address=instance.get("PrivateIpAddress"), public_dns_name=public_dns_name, public_ip_address=public_ip_address, state=instance.get("State").get("Name"), subnet_id=instance.get("SubnetId"), vpc_id=instance.get("VpcId"), tags=instance.get("Tags"), ) ec2_instances.append(ec2_instance) return ec2_instances
[ "def get_instance():\n logging.debug(\"Querying cloud-init for instance-id\")\n instance_id = requests.get(\"http://169.254.169.254/latest/meta-data/instance-id\").text\n client = boto3.client('ec2')\n ec2_resource = boto3.resource('ec2')\n aws_instance = client.describe_instances(InstanceIds=[instan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints summary of EC2 instance details
def print_instance_summary(self, instance: EC2Instance): print(instance.instance_id) self.not_quiet("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") self.verbose_output(f" AMI: {instance.image_id}") self.not_quiet(f" Type: {instance.instance_type}") self.verbose_output(f" Launched: {instance.launch_time}") self.verbose_output(f" AZ: {instance.availability_zone}") self.verbose_output(f" Private DNS: {instance.private_dns_name}") self.verbose_output(f" Public DNS: {instance.public_dns_name}") self.not_quiet(f" Private IP: {instance.private_ip_address}") self.not_quiet(f" Public IP: {instance.public_ip_address}") self.verbose_output(f" Subnet Id: {instance.subnet_id}") self.verbose_output(f" VPC Id: {instance.vpc_id}") self.not_quiet(f" State: {instance.state}") self.verbose_output(f" Tags: {instance.tags}") self.not_quiet("\n")
[ "def do_printInstances(self,args):\n parser = CommandArgumentParser(\"printInstances\")\n parser.add_argument(dest='filters',nargs='*',default=[\"*\"],help='Filter instances');\n parser.add_argument('-a','--addresses',action='store_true',dest='addresses',help='list all ip addresses');\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
red slider event handler
def callback_red(*args): global red_int col = "red" str_val = str(r_slide_val.get()) red_int = code_shrtn(str_val, 20, 30, 60, 80, col) update_display(red_int, green_int, blue_int)
[ "def callback_blue(*args):\n global blue_int\n col = \"blue\"\n str_val = str(b_slide_val.get())\n blue_int = code_shrtn(str_val, 180, 30, 60, 80, col)\n update_display(red_int, green_int, blue_int)", "def slider_released(self):\n self.update_status(\"status\", \"Length Updated\")", "def c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
green slider event handler
def callback_green(*args): global green_int col = "darkgreen" str_val = str(g_slide_val.get()) green_int = code_shrtn(str_val, 100, 30, 60, 80, col) update_display(red_int, green_int, blue_int)
[ "def callback_blue(*args):\n global blue_int\n col = \"blue\"\n str_val = str(b_slide_val.get())\n blue_int = code_shrtn(str_val, 180, 30, 60, 80, col)\n update_display(red_int, green_int, blue_int)", "def callback_red(*args):\n global red_int\n col = \"red\"\n str_val = str(r_slide_val.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
blue slider event handler
def callback_blue(*args): global blue_int col = "blue" str_val = str(b_slide_val.get()) blue_int = code_shrtn(str_val, 180, 30, 60, 80, col) update_display(red_int, green_int, blue_int)
[ "def slider_released(self):\n self.update_status(\"status\", \"Length Updated\")", "def _on_slider_pressed(self):\n # This flag will activate fast_draw_slice_at_index\n # Which will redraw sliced images quickly\n self._slider_flag = True", "def slider_changed(self, indx):\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new object from meta information Id should be a unique number meta an array of length 2 containing constructor name and parameters dictionary
def createFromMeta(self, Id, meta): if len(meta) == 3: ctorname, props, alias = meta elif len(meta) == 2: ctorname, props = meta alias = None else: assert 'wrong meta' ctor = _findType(ctorname) if ctorname == 'marketsim.Side._SellSide': obj = Side.Sell elif ctorname == 'marketsim.Side._BuySide': obj = Side.Buy elif inspect.isclass(ctor): dst_properties = rtti.properties_t(ctor) converted = dict() for k,v in props.iteritems(): converted[k] = self._convert(dst_properties, k, v) obj = ctor(**converted) if alias is not None: obj._alias = alias else: assert inspect.isfunction(ctor) obj = ctor self._insertNew(Id, obj) return obj
[ "def create(cls, **kwargs):", "def do_create(self, arg):\n if len(arg) <= 0:\n print(\"** class name missing **\")\n else:\n arg = arg.split()[0]\n if arg in self.valid_class:\n new_obj = eval(arg)()\n new_obj.save()\n pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes an object with id = k_id
def visit(k_id): if k_id not in rv: # check that it hasn't been yet processed dumped = self.tojson(k_id) # getting dump representation rv[k_id] = dumped # storing it in the dictionary for p in dumped[1].itervalues(): # iterating its fields visit_if_ref(p)
[ "def visit(k_id):\r\n if k_id not in rv: # check that it hasn't been yet processed\r\n dumped = self.dump(k_id) # getting dump representation\r\n rv[k_id] = dumped # storing it in the dictionary\r\n if len(dumped) > 1: # if it has properti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes an object with id = k_id
def visit(k_id): if k_id not in rv: # check that it hasn't been yet processed dumped = self.dump(k_id) # getting dump representation rv[k_id] = dumped # storing it in the dictionary if len(dumped) > 1: # if it has properties for _,p in dumped[1].itervalues(): # iterating its fields visit_if_ref(p) if type(p) is list: # if a field is list (other sequences are to be processed in future) for e in p: # for each its element visit_if_ref(e)
[ "def visit(k_id):\r\n if k_id not in rv: # check that it hasn't been yet processed\r\n dumped = self.tojson(k_id) # getting dump representation\r\n rv[k_id] = dumped # storing it in the dictionary\r\n for p in dumped[1].itervalues(): # iter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load gallery image list
def read_gallery_list(self): pass
[ "def db_get_images(galleryname):\n \n return list_of_Img_objects", "def display_gallery():\n\n images = db.session.query(Image).all()\n\n return render_template('all_images.html',\n images=images)", "def test_core_get_gallery_images_v1(self):\n pass", "def loadImg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
VERY primitive implementation of NewtonRaphson method. Assumes guess is close to final results e always performs 100 iterations.
def newton(P, x0, niter, paramn): """ Needs improvement """ # Find a new initial guess closer to the desired pressure # m = -(paramn[1]/paramn[0]) # guess = (P/m) + x0 x = x0 - 5 while vinet(x, paramn[0], paramn[1], paramn[2]) < P: x0 = x0 - 5 x = x0 guess = 0.5 * (x + x0) for i in range(1, niter): x = guess - (vinet(guess, paramn[0], paramn[1], paramn[2]) - P) / dvinet(guess, paramn) guess = x return x
[ "def newton(x):\r\n\r\n # Initialize the tolerance and estimate\r\n tolerance = 0.000001\r\n estimate = 1.0\r\n\r\n # Perform the successive approximations\r\n while True:\r\n estimate = (estimate + x / estimate) / 2\r\n difference = abs(x - estimate ** 2)\r\n if difference <=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures the Celery APP for CPU, GPU, MPI mode.
def create_celery_app() -> Celery: bootmode = BootMode.CPU if start_as_mpi_node(): bootmode = BootMode.MPI elif config.FORCE_START_CPU_MODE: bootmode = BootMode.CPU elif config.FORCE_START_GPU_MODE or is_gpu_node(): bootmode = BootMode.GPU return configure_node(bootmode)
[ "def setup_app():\n cfg = get_config()\n print(cfg)\n backend = cfg['backend']\n broker = cfg['broker']\n app = Celery('nlp_server', broker=broker, backend=backend)\n\n if cfg.get('queues'):\n queue_list = []\n for queue in cfg.get('queues'):\n q = Queue(queue.get('name'),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the log of input probabilities masking divide by zero in log. Notes During the Mstep of EMalgorithm, very small intermediate start or transition probabilities could be normalized to zero, causing a
def log_mask_zero(a): a = np.asarray(a) with np.errstate(divide="ignore"): return np.log(a)
[ "def log_with_zeros(x):\n x = torch.max(x, torch.tensor(1e-10))\n return torch.log(x)", "def log_of_array_ignoring_zeros(M: np.ndarray) -> np.ndarray:\n log_M = M.copy()\n mask = log_M > 0\n log_M[mask] = np.log(log_M[mask])\n \n return log_M", "def p_log_p(p: torch.FloatTensor) -> torch.Fl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function returns a dictionary with definitions of output data produced the component.
def output_data_definitions(self): return { self.key_outputs: DataDefinition([-1, self.output_size], [torch.Tensor], "Batch of outputs [BATCH_SIZE x OUTPUT_SIZE]") }
[ "def outputs(self) -> Dict[str, TypeShape]:\n raise NotImplementedError()", "def _get_output_vars(self):", "def _getInitOutputValues(self):\r\n \r\n outputs = {}\r\n\r\n for attr_name, attr_data in self._output_plug_map.items():\r\n \r\n #---if atribute is array, se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Repeat the same feature vector over all spatial positions of a given feature map. The feature vector should have the same batch size and number of features as the feature map.
def tile_2d_over_nd(feature_vector, feature_map): n, c = feature_vector.size() spatial_size = feature_map.dim() - 2 tiled = feature_vector.view(n, c, *([1] * spatial_size)).expand_as(feature_map) return tiled
[ "def tile_2d_over_nd(feature_vector, feature_map):\n n, c = feature_vector.size()\n spatial_size = feature_map.dim() - 2\n tiled = feature_vector.view(n, c, *([1] * spatial_size)).expand_as(feature_map)\n return tiled", "def map_add_features(x, s):\n stride = s.tensor_stride\n coords = s.coords.long()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply any number of attention maps over the input.
def apply_attention(input, attention): n, c = input.size()[:2] glimpses = attention.size(1) # glimpses is equivalent to multiple heads in attention # flatten the spatial dims into the third dim, since we don't need to care about how they are arranged input = input.view(n, 1, c, -1) # [n, 1, c, s] [batch, 1, channels, height*width] [48, 1, 2048, 7*7] attention = attention.view(n, glimpses, -1) # [48, 2, 7*7] attention = torch.nn.functional.softmax(attention, dim=-1).unsqueeze(2) # [n, g, 1, s] [batch, multi_head, 1, height*width] [48, 2, 1, 7*7] weighted = attention * input # [n, g, c, s] [48, 2, 2048, 7*7] weighted_mean = weighted.sum(dim=-1) # [n, g, c] [48, 2, 2048] return weighted_mean.view(n, -1) # [48, 4096]
[ "def apply_attention(input, attention):\n # import pdb\n # pdb.set_trace()\n n, c = input.size()[:2]\n glimpses = attention.size(1)\n\n # flatten the spatial dims into the third dim, since we don't need to care about how they are arranged\n input = input.view(n, c, -1)\n attention = attention.view(n, glimpse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count the number of characters that differ between box1 and box2
def chars_different(box1, box2): diff = sum( 1 if i != j else 0 for i, j in zip(box1, box2) ) return diff
[ "def occurrences(text1, text2):\n num_text1 = {char:0 for char in text1}\n\n for char in text2:\n if char in num_text1:\n num_text1[char] += 1\n\n return sum(list(num_text1.values()))", "def _get_common_letters(box_id1: str, box_id2: str) -> str:\n # I can iterate through both the st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all common characters between box1 and box2 in order >>> common_chars('abcdef', 'abddeg') 'abde'
def common_chars(box1, box2): return ''.join(i if i == j else '' for i, j in zip(box1, box2))
[ "def _get_common_letters(box_id1: str, box_id2: str) -> str:\n # I can iterate through both the string and find out the diff in one iteration only.\n # below logic is O(n), n - min(length(boxid1), length(boxid2))\n common_letters: Iterable[str] = map(\n lambda e: e[0] if e[0] == e[1] else \"\", zip(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1. Remove all comments. 2. Separate program into list of substrings, each could represent a token. 3. Convert into list of actual tokens, or TokenList(). 4. Append EOF and return.
def lex(self): #These regexes defines all comments: (//comment\n). #Anything (.*) can go in comment, including nothing (hence * instead of +). comment_reg = '//.*\n' #Split prog around non-comment sections, then join to remove comments. new_inp = "".join(re.split(comment_reg, self.inp)) #Separate into list called 'items' of strings which will become tokens items = re.findall('\w+|[,+*/(){}\[\];-]|[<=>]+|"[^\'\r\n]*"', new_inp) tokens = TokenList([self.choose_tok(x) for x in items]) tokens.ls.append(Token(EOF, "eof")) #no end-of-file in string input return tokens
[ "def pp_tokenize(src, fname) :\n\tcmnts = map(lambda c: (c.start(), c.end()), re_cmnt.finditer(src))#XXX something more hitech?\n\ttoks = re_tok.finditer(src)\n\tlines = map(lambda c: (c.start(), c.end()), re_newln.finditer(src))\n\treturn map(lambda t: tok_wrap(t, toks, cmnts, lines, fname),\n\t\tifilter(lambda t:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses ``page`` (html as string), tries to find the correct link for date, get the index and then parse the menu with this index.
def parse_menu(page: str, date: datetime.date): menu = bs4.BeautifulSoup(page, 'html.parser') date_str = date.strftime('%d.%m.') date_idcs = {date_link.attrs['data-index'] for date_link in menu.select('.weekdays .nav-item') if date_link.select('.date')[0].text == date_str} if len(date_idcs) != 1: raise RuntimeError(f"No unique menu found for date={date_str} (found entries with " f"indices {date_idcs})") date_idx, = date_idcs menu_of_day = menu.select(f':not(.d-md-none) > div > .menu-plan .menu-item-{date_idx}') # first filter complete sections wrapped in <div class="menu-item ...> FILTER_SECTION_BLACKLIST_REGEX = ( 'Frühstück', ) def is_blacklisted(meal): return any(meal.find_all(string=re.compile(pattern)) for pattern in FILTER_SECTION_BLACKLIST_REGEX) menu_of_day = [meal for meal in menu_of_day if not is_blacklisted(meal)] # now filter <p> tags, small unnecessary comments FILTER_BLACKLIST_REGEX = ( #'Empfehlen Sie uns bitte weiter', #'Wir möchten', #'Unser Umweltzeichen', #'Produkte vom heimischen', #'Wir verwendent erstklassige', #'Unser Wochenangebot', #'in bisserl mehr sein', 'Tagesteller', 'Unsere Tagesgerichte', 'Unser Wochenangebot', 'Aus unserer My Mensa-Soup', 'darauf hinweisen, dass wir vorwiegend Produkte vom', 'Unser Umweltzeichen - welches wir in all', 'Empfehlen Sie uns bitte weiter...', 'M-Café', 'Tages-Empfehlung', 'Aus unserer My-Mensa Soup-Bar', 'Angebot der Woche', 'Herzlich Willkommen', 'im M-Café Biotech!', 'M-Cafe', 'Herzlich Willkommen', 'im M-Café Mendel', 'Gerne verwöhnen wir euch mit verschiedenen,', 'gefüllten Weckerln und Sandwiches,', 'hausgemachtem Blechkuchen und', 'täglich frisch gebackenem Gebäck!', 'Darf´s ein bisserl mehr se', 'im M-Café Mendel', 'Täglich frischer', '\*\*\*', '\*', ) for pattern in FILTER_BLACKLIST_REGEX: for meal in menu_of_day: for tag in meal.find_all(string=re.compile(pattern)): tag.parent.decompose() menu_of_day_items = [] for vegy_type, v_symbol_name in VEGY_TYPES.items(): for meal in menu_of_day: for v_image in meal.find_all('img', alt=vegy_type): v_symbol = menu.new_tag('p') v_symbol.string = v_symbol_name v_image.replace_with(v_symbol) # note: meal might contain multiple items/prices for meal in menu_of_day: # split by prices foods_prices = re.split('(€\s?\d+,\d+)', meal.text) foods = foods_prices[::2] prices = foods_prices[1::2] # replace new lines with spaces foods = [" ".join(food.split()) for food in foods] menu_of_day_items += [f"{food} {price}" for food, price in zip(foods, prices)] return menu_of_day_items
[ "def load_page_for_date(site: Site, date: datetime.date) -> Page:\n return site.pages[\"Freitagsfoo/{}\".format(date)]", "def _parse_page(url):\n html = urllib2.urlopen(url).read()\n soup = BeautifulSoup(html, 'lxml', from_encoding=\"utf-8\")\n #contents = [x.get('content') for x in soup('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make predictions using a single binary estimator.
def predict_binary(self,estimator, X): return sklearn.multiclass._predict_binary(estimator,X)
[ "def _fit_binary(estimator, X, y, classes=None, sample_weight=None):\n unique_y = np.unique(y)\n if len(unique_y) == 1:\n if classes is not None:\n if y[0] == -1:\n c = 0\n else:\n c = y[0]\n warnings.warn(\"Label %s is present in all train...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Active, verified organizations related to this incident. Handles current and legacy incident/s properties.
def organizations(self): from organization import Organization # avoid circular import # lookup using new incidents field orgs = list( Organization.all().filter('incidents', self.key()) .filter('org_verified', True) .filter('is_active', True) ) # build list of id and look for global admin org_ids = set() seen_global_admin = False for org in orgs: if org.is_global_admin: seen_global_admin = True org_id = org.key().id() if org_id not in org_ids: org_ids.add(org_id) # check legacy incident field legacy_field_orgs = Organization.all().filter('incident', self.key()) \ .filter('org_verified', True) \ .filter('is_active', True) for org in legacy_field_orgs: if org.key().id() not in org_ids: orgs.append(org) # prepend global admin if not encountered if not seen_global_admin: orgs = ( list(Organization.all().filter('name', 'Admin')) + orgs ) return orgs
[ "def organizations():", "def get_active_organization(self):\n return self._active_organization", "def get_organizations(self):\n url = \"{}/organizations\".format(self.API_URL)\n if self.debug:\n self.print(\"Sending GET request to URL {}\".format(url))\n r = self.session....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
formDataList is a list/(sequence) of (formName, formData) pairs for normal form fields, or (formName, fileType) or (formName, (filename, fileData)) for a file upload form element.
def __encodeMultipartFormdata(self, formDataList): boundary = str(time.time()).replace(".", "_").rjust(32, "-") lines = [] for formName, data in formDataList: lines.append("--" + boundary) if type(data) is types.StringType: cd = "Content-Disposition: form-data; name=\"%s\"" % formName lines.append(cd) else: dataType = type(data) if dataType is types.TupleType: filename, data = data elif dataType is types.FileType: filename = data.name data = data.read() else: print "Ignoring unsupported data type: %s" % dataType continue cd = "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"" % (formName, filename) lines.append(cd) lines.append("Content-Type: %s" % self.__getFileContentType(filename)) lines.append("") lines.append(data) lines.append("--" + boundary + "--") lines.append("") data = string.join(lines, "\r\n") contentType = "multipart/form-data; boundary=%s" % boundary return contentType, data
[ "def handle_form_data(self, data):\n\t\tif data is None:\n\t\t\treturn\n\t\t\n\t\t# medications?\n\t\tmeds = []\n\t\tif 'medications' in data:\n\t\t\torig = data['medications']\n\t\t\tdrugs = orig['drug'] if 'drug' in orig else []\n\t\t\tif not isinstance(drugs, list):\n\t\t\t\tdrugs = [drugs]\n\t\t\t\n\t\t\tfor dr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all date encoded subdirectories in the url
def get_dates(url, start_year, end_year): # all URLs of `url` dates = [] try: for year in range(start_year, end_year + 1): # domain name of the URL without the protocol # print("url ", url) content = url + str(year) + "/contents.html" # print("content ",content) days = get_href(content, "contents.html") # print("days ",days) for day in days: dates.append(day) except Exception as e: raise e return dates
[ "def parse_folder( self, url ):\n data = self.read_file( url )\n soup = BeautifulSoup( data, \"html.parser\" )\n result = []\n url_path = self.get_url_path( url )\n for a in soup.find_all( \"a\" ):\n href = a['href']\n if href.startswith( url_path ) or href.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets and cleans fuel poverty dataset.
def get_clean_fuel_poverty(): fuel_poverty = get_fuel_poverty() # fuel_poverty = fuel_poverty.rename( columns={ "Area Codes": "code", "Area name": "region_1", "Unnamed: 2": "region_2", "Unnamed: 3": "region_3", "Number of households1": "total_households", "Number of households in fuel poverty1": "fp_households", "Proportion of households fuel poor (%)": "fp_proportion", } ) # # Remove trailing spaces and fix capitalisation in region columns fuel_poverty["region_1"] = fuel_poverty["region_1"].apply(strip_and_titlecase) fuel_poverty["region_2"] = fuel_poverty["region_2"].apply(strip_and_titlecase) fuel_poverty["region_3"] = fuel_poverty["region_3"].apply(strip_and_titlecase) # # Merge the different 'region' columns into one and apply clean_names - # this allows for joining onto data in which local authorities # are only referred to by name and not ID fuel_poverty["clean_name"] = ( fuel_poverty["region_1"] .fillna(fuel_poverty["region_2"]) .fillna(fuel_poverty["region_3"]) .apply(clean_names) ) # Fill in NaN values in region columns so that all region_3 rows # have associated region_1 and region_2 data, # and all region_2 rows have associated region_1 data. # First copy region_1 values into region_2 then forward-fill region_2 - # the 'region_1's stop the filling from going too far fuel_poverty["region_2"] = ( fuel_poverty["region_2"].fillna(fuel_poverty["region_1"]).ffill() ) # Set the copied-over values in region_2 back to NaN fuel_poverty["region_2"].loc[~fuel_poverty["region_1"].isna()] = np.nan # Then forward-fill region_1 fuel_poverty["region_1"] = fuel_poverty["region_1"].ffill() # Filter out all of the region_1 rows - they are not local authorities fuel_poverty = fuel_poverty[~fuel_poverty["region_2"].isna()] # Additionally remove all Met Counties and Inner/Outer London - # these are rows that contain (Met County) or Inner/Outer London in region_2 # and have NA region_3 def not_la_condition(string): return ("(Met County)" in string) | (string in ["Inner London", "Outer London"]) # # not_las = [not_la_condition(string) for string in fuel_poverty["region_2"]] no_region_3 = list(fuel_poverty.region_3.isna()) both = [a and b for a, b in zip(not_las, no_region_3)] fuel_poverty = fuel_poverty.drop(fuel_poverty[both].index) # # Append rows for Greater London Authority and # Greater Manchester Combined Authority - # these are not LAs but some grants went to them combined_authorities = pd.DataFrame( [ [ np.nan, "London", "Greater London Authority", np.nan, np.nan, np.nan, np.nan, "Greater London Authority", ], [ np.nan, "North West", "Greater Manchester Combined Authority", np.nan, np.nan, np.nan, np.nan, "Greater Manchester Combined Authority", ], ], columns=fuel_poverty.columns, ) # fuel_poverty = fuel_poverty.append(combined_authorities, ignore_index=True) # return fuel_poverty
[ "def get_data():\n points = get_alameda_county_points()\n return filter_ranson_criteria(clean_data(get_weather_data(points)))", "def __get_data(self):\n try:\n self.data = self.hdulist[0].data\n except:\n self.hdulist = astropy.io.fits.open(self.map_name)\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets and cleans current LA majority party and model (e.g. county, district) data.
def get_clean_parties_models(): parties_models = get_parties_models() # parties_models = parties_models.rename( columns={ "model (C=county, D=district, 1=all-up, 3=thirds, etc.)": "model", } ) # 'Buckinghamshire' row in this dataset is incorrect - # it is labelled as a County council but it has become unitary # Manually replace with the correct data # Source: http://opencouncildata.co.uk/council.php?c=413&y=0 parties_models.loc[2] = ["Buckinghamshire", "U1", "CON"] # # Rename models to full names parties_models["model"] = parties_models["model"].apply(model_type) # # Apply clean_names to all names in parties/models data parties_models["clean_name"] = parties_models["name"].apply(clean_names) parties_models = parties_models.drop(columns="name") # return parties_models
[ "def get_data():\n points = get_alameda_county_points()\n return filter_ranson_criteria(clean_data(get_weather_data(points)))", "def _get_restriction_to_main(self) -> Tuple[pd.Series, np.ndarray]:\n\n # get the names of the main states, remove 'rest' if present\n main_names = self.lineage_prob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets and cleans data on grants received by LAs.
def get_clean_grants(): grants = get_grants() grants = grants.rename( columns={ "Local authority": "full_name", "GHG LADS 1a": "GHG_1a_individuals", "1a Consortium Leads": "GHG_1a_leads", "1a Consortium bodies": "GHG_1a_bodies", "GHG LADS 1b": "GHG_1b_individuals", "1b Consortium leads": "GHG_1b_leads", "1b Consortium bodies": "GHG_1b_bodies", "Social Housing Decarbonisation Fund - Demonstrator ": "SHDDF", "Total": "total_grants", } ) # # Some regions appear twice in the grants data duplicate_strings = ["Greenwich", "Lewisham", "Redbridge"] regex_exp = "|".join(duplicate_strings) clean_grants = grants[~grants["full_name"].str.contains(regex_exp, regex=True)] # for string in duplicate_strings: duplicate_df = grants[grants["full_name"].str.contains(string)] replacement_row = duplicate_df.iloc[0] + duplicate_df.iloc[1] replacement_row["full_name"] = string clean_grants = clean_grants.append(replacement_row, ignore_index=True) # # Babergh and Mid Suffolk are shown in one row in the grants data, # but they are actually two different LAs - the stated grants # apply to both individually babergh_ms = clean_grants[ [("Babergh and Mid Suffolk" in name) for name in clean_grants["full_name"]] ] babergh = babergh_ms.copy() babergh["full_name"] = "Babergh" ms = babergh_ms.copy() ms["full_name"] = "Mid Suffolk" clean_grants = ( clean_grants[ [ ("Babergh and Mid Suffolk" not in name) for name in clean_grants["full_name"] ] ] .append(babergh) .append(ms) .reset_index(drop=True) ) # # As before, apply clean_names in order to join data clean_grants["clean_name"] = clean_grants["full_name"].apply(clean_names) clean_grants = clean_grants.drop(columns="full_name") # return clean_grants
[ "def _downgrade_access_data():\n conn = op.get_bind()\n\n res = conn.execute(sa.text('SELECT COUNT(*) FROM events.menu_entry_principals WHERE type != :regforms'),\n regforms=_PrincipalType.registration_form)\n if res.fetchone()[0]:\n raise Exception('Cannot downgrade; some menu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes EPC dataset to obtain median EPC for each LA and counts/proportions of improvable social housing.
def get_clean_epc(): epc = get_epc() # # Calculate median energy rating for each LA: epc_medians = ( epc.groupby("LOCAL_AUTHORITY")["CURRENT_ENERGY_EFFICIENCY"] .apply(np.median) .reset_index(name="median_energy_efficiency") ) # # Calculate proportions of 'improvable' social housing # (socially rented dwellings that are currently EPC D or below, # and have the potential to be C or above) # # There are two different strings signifying socially rented # in the TENURE column of the EPC data: epc_social = epc.loc[epc["TENURE"].isin(["rental (social)", "Rented (social)"])] # epc_social["is_improvable"] = ( epc_social["CURRENT_ENERGY_RATING"].isin(["G", "F", "E", "D"]) ) & (epc_social["POTENTIAL_ENERGY_RATING"].isin(["C", "B", "A"])) # # Find the numbers of improvable / not improvable social houses in each LA potential_counts = ( epc_social.groupby(["LOCAL_AUTHORITY", "is_improvable"])[ ["LOCAL_AUTHORITY", "is_improvable"] ] .size() .reset_index(name="count") .pivot(index="LOCAL_AUTHORITY", columns="is_improvable", values="count") .rename(columns={True: "total_improvable", False: "total_not_improvable"}) ) # Calculate proportions potential_counts.columns.name = None potential_counts["total_social"] = potential_counts.sum(axis=1) potential_counts["prop_improvable"] = ( potential_counts["total_improvable"] / potential_counts["total_social"] ) potential_counts = potential_counts.reset_index()[ ["LOCAL_AUTHORITY", "total_improvable", "prop_improvable"] ] # Join to medians clean_epc = epc_medians.merge(potential_counts, on="LOCAL_AUTHORITY").rename( columns={"LOCAL_AUTHORITY": "code"} ) # return clean_epc
[ "def groupEnergy(data, en_type):\n df = data.loc[data[\"type\"] == en_type]\n df = GeneralFunctions.removeOutliers(df, \"annual_consume_corrected\")\n\n # create a column for the groupby\n df[\"Postcode4\"] = df[\"POSTCODE\"].str.extract(\"([0-9]+)\")\n\n df_mean = df.groupby([\"P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return prediction formatted according to the content type
def output_fn(prediction, content_type): return prediction
[ "def make_predictions(text, types, pipeline):\n types_order, preds, judgements = list(), dict(), dict()\n\n if \"toxic\" in types:\n preds[\"Toxicity\"], judgements[\"Toxicity\"] = pipeline.predict_toxicity_ulm(text)\n types_order.append(\"Toxicity\")\n if \"insult\" in types:\n preds[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the predicted value for all the vectors in X.
def predict(self, X): return predicted_value
[ "def predict(self, X):\n n = X.shape[0]\n m = self.num_obj\n Y_m = np.ndarray((n, m))\n Y_v = np.ndarray((n, m))\n for i in xrange(m):\n if self.denoised:\n if hasattr(self.surrogates[i],'likelihood') and hasattr(self.surrogates[i].likelihood,'variance'):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an integer list of tasks from an edge label.
def get_task_list(label): task_list = [] current = 0 in_range = False range_start = -1 for char in label: if char.isdigit(): current = current * 10 + int(char) elif char == '-': range_start = current current = 0 in_range = True elif char == ',' or char == ']': if in_range: range_end = current for i in range(range_start, range_end + 1): task_list.append(i) else: task_list.append(current) if char == ']': break in_range = False current = 0 range_start = -1 return task_list
[ "def query_edge_id_list(graph, label=None):\n travel = graph.E()\n if label:\n travel = travel.hasLabel(label)\n temp_id_list = travel.id().toList()\n id_list = list(map(lambda t: t.get('@value').get('relationId'), temp_id_list))\n return id_list", "def _get_ids_from_label(self, label):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate some picture values
def validate_image(self, picture): if picture: if picture.size > 2000000: raise ValueError('Max size allowed 2MB') if picture.image.width < 180: raise ValueError('Width should be min 180px') if picture.image.height < 180: raise ValueError('Height should be min 180px')
[ "def validate_base_image(value):\n if not value:\n return False\n\n filename, data = b64decode_file(value)\n\n # check size\n if len(data) > 1048576:\n raise Invalid(_(u'Image should be smaller than 1MB.'))\n\n img = Image.open(StringIO(data))\n\n # check format\n if img.format !=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
USAGE list_hb selection, [cutoff (default=3.2)], [angle (default=55)], [hb_list_name] e.g. list_hb 1abc & c. a &! r. hoh, cutoff=3.2, hb_list_name=abchbonds
def list_hb(selection,cutoff=3.2,angle=55,hb_list_name='hbonds'): cutoff=float(cutoff) angle=float(angle) hb = cmd.find_pairs("((byres "+selection+") and n;n)","((byres "+selection+") and n;o)",mode=1,cutoff=cutoff,angle=angle) # sort the list for easier reading hb.sort(lambda x,y:(cmp(x[0][1],y[0][1]))) for pairs in hb: for ind in [0,1]: cmd.iterate("%s and index %s" % (pairs[ind][0],pairs[ind][1]), 'print "%s/%3s`%s/%s/%s " % (chain,resn,resi,name,index),') print "%.2f" % cmd.distance(hb_list_name,"%s and index %s" % (pairs[0][0],pairs[0][1]),"%s and index %s" % (pairs[1][0],pairs[1][1]))
[ "def help_list_bookings():\n get_list_bookings_parser().print_help()", "def honeypot_tab(x):\n BURN_IN_HELL = r\"\"\"\n id: 2\n opt: ('progress-bar', )\n ui: '''\n type: 'text'\n value: 'How many?'\n %\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Wide Residual Network with specified parameters
def create_wide_residual_network(input, nb_classes=100, N=2, k=1, dropout=0.0, verbose=1): x = initial_conv(input) nb_conv = 4 for i in range(N): x = conv1_block(x, k, dropout) nb_conv += 2 x = MaxPooling3D((2,2,2))(x) for i in range(N): x = conv2_block(x, k, dropout) nb_conv += 2 #x = MaxPooling3D((2,2,2))(x) #for i in range(N): # x = conv3_block(x, k, dropout) # nb_conv += 2 x = AveragePooling3D((8,8,8))(x) # strides=(2,2,2) x = Flatten()(x) x = Dense(nb_classes, activation='softmax', W_regularizer=l2(weight_decay), bias=use_bias)(x) if verbose: print("Wide Residual Network-%d-%d created." % (nb_conv, k)) return x
[ "def resnetW(pretrained=False, **kwargs):\n model = ResNet(SATBlock, [1,3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model", "def net_builder(net_params: dict):\n import wrn as net\n\n # grab the builder class\n build...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
basic JSON message structure
def msg_structure(status="", msg=""): return { "status": status, "msg": msg }
[ "def create_JSON_message(message_type, body=None):\n clientID= partnerID+\"/\"+groupID+\"/\"+deviceID \n message= {\"clientID\" : clientID, \"type\": message_type, \"body\": body}\n return json.dumps(message)", "def create_json_message(county, state, rank, timestamp, creator_id, message_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
contains all mime types for HTTP request
def all_mime_types(): return { ".aac": "audio/aac", ".abw": "application/x-abiword", ".arc": "application/octet-stream", ".avi": "video/x-msvideo", ".azw": "application/vnd.amazon.ebook", ".bin": "application/octet-stream", ".bz": "application/x-bzip", ".bz2": "application/x-bzip2", ".csh": "application/x-csh", ".css": "text/css", ".csv": "text/csv", ".doc": "application/msword", ".docx": "application/vnd.openxmlformats-officedocument.\ wordprocessingml.document", ".eot": "application/vnd.ms-fontobject", ".epub": "application/epub+zip", ".gif": "image/gif", ".htm": ".htm", ".html": "text/html", ".ico": "image/x-icon", ".ics": "text/calendar", ".jar": "application/java-archive", ".jpeg": ".jpeg", ".jpg": "image/jpeg", ".js": "application/javascript", ".json": "application/json", ".mid": ".mid", ".midi": "audio/midi", ".mpeg": "video/mpeg", ".mpkg": "application/vnd.apple.installer+xml", ".odp": "application/vnd.oasis.opendocument.presentation", ".ods": "application/vnd.oasis.opendocument.spreadsheet", ".odt": "application/vnd.oasis.opendocument.text", ".oga": "audio/ogg", ".ogv": "video/ogg", ".ogx": "application/ogg", ".otf": "font/otf", ".png": "image/png", ".pdf": "application/pdf", ".ppt": "application/vnd.ms-powerpoint", ".pptx": "application/vnd.openxmlformats-officedocument.\ presentationml.presentation", ".rar": "application/x-rar-compressed", ".rtf": "application/rtf", ".sh": "application/x-sh", ".svg": "image/svg+xml", ".swf": "application/x-shockwave-flash", ".tar": "application/x-tar", ".tif": ".tif", ".tiff": "image/tiff", ".ts": "application/typescript", ".ttf": "font/ttf", ".vsd": "application/vnd.visio", ".wav": "audio/x-wav", ".weba": "audio/webm", ".webm": "video/webm", ".webp": "image/webp", ".woff": "font/woff", ".woff2": "font/woff2", ".xhtml": "application/xhtml+xml", ".xls": "application/vnd.ms-excel", ".xlsx": "application/vnd.openxmlformats-officedocument.\ spreadsheetml.sheet", ".xml": "application/xml", ".xul": "application/vnd.mozilla.xul+xml", ".zip": "application/zip", ".3gp": "video/3gpp", "audio/3gpp": "video", ".3g2": "video/3gpp2", "audio/3gpp2": "video", ".7z": "application/x-7z-compressed", ".pcap": "application/cap" }
[ "def mimetypes_for(self, m):\r\n if m not in self.methods:\r\n return []\r\n return self._string_to_list(self.methods[m]['mimetype'])", "def mime_types(self):\n return {attr.name: attr.mime_type for attr in self.attributes if attr.mime_type}", "def valid_content_types() -> List[s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find the root directory for web static files
def root_dir(): return os.path.join( os.path.join( os.path.dirname(os.path.dirname(__file__)), "web" ), "static" )
[ "def static_folder(self) -> str:\n return path.join(\"web\", \"static\")", "def static_dir():\n tests_dir = os.path.dirname(__file__)\n return os.path.join(tests_dir, 'static')", "def static_dir(self):\n return os.path.join('front', self.slug, 'static')", "def staticpath(self):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fix limit integer from user
def fix_limit(limit): if limit: try: if int(limit) > 10000: return 10000 return int(limit) except Exception: pass return 10
[ "def set_Limit(self, value):\n super(ListIncidentsInputSet, self)._set_input('Limit', value)", "def _render_limit(limit):\n if not limit:\n return ''\n\n return \"LIMIT %s\" % limit", "def get_number(prompt, error_prompt, limit_prompt, min_num=0 - float('inf'), max_num=float('inf'), valid_ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fix skip integer from user
def fix_skip(skip): if skip: try: return int(skip) except Exception: pass return 0
[ "def get_num():\n i = 0\n while (i > 127) or (i < 1):\n try:\n i = int(input(\"Enter ID # from 1-127: \"))\n except ValueError:\n pass\n return i", "def update_ignore(arg):\n args = arg.split(' ', 1)\n bp, err = breakpoint_by_number(args[0])\n if bp:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert a separator between menu items.
def add_menu_separator(self): if self._menu is None: self._create_menu() self._menu.addSeparator()
[ "def separator(self, menu):\n return menu.AppendSeparator()", "def addSeparator(self, *args) -> \"adsk::core::Ptr< adsk::core::ListItem >\" :\n return _core.ListItems_addSeparator(self, *args)", "def test_menu_separator(self):\n # Separators at the head and tail are ignored\n self.as...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function to be called for a mouse rightclick event.
def set_right_click(self, fcn): self.customContextMenuRequested.connect(fcn)
[ "def right_click(self):\n pass", "def right_click(self):\n self.node.right_click()", "def OnRightEvent(self, event):\n self.click = 'RIGHT'\n self.ProcessClick(event)", "def on_right_click(self, event):\n\n element, (x, y) = event\n parent = self.tree_viewer.control\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an column of value one to the right of `array`.
def _right_extend(array): ones = np.ones((array.shape[0], 1), dtype=array.dtype) return np.concatenate((array, ones), axis=1)
[ "def add_array_to_col( self, row, col, inarr, attrs=None ):\n\n arlen = len( inarr )\n\n for i in range( arlen ):\n self.setCellcontents( row+i, col, inarr[i], attrs )", "def add_column(x, fill_value=1):\n shape = list(x.shape)\n shape[-1] = 1\n values = np.ones(shape)\n if fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes tempo and gain of the recording with sox and loads it.
def augment_audio_with_sox(path, sample_rate, tempo, gain): with NamedTemporaryFile(suffix=".wav") as augmented_file: augmented_filename = augmented_file.name sox_augment_params = ["tempo", "{:.3f}".format(tempo), "gain", "{:.3f}".format(gain)] sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} {} >/dev/null 2>&1".format(path, sample_rate, augmented_filename, " ".join(sox_augment_params)) os.system(sox_params) y,_ = load_audio(augmented_filename) return y
[ "def detect_tempo(self):\n\n if (self.song.sr is None) or (self.song.waveform is None):\n raise ValueError(\"No song was loaded.\")\n\n # Detect tempo\n tempo, beat_frames = librosa.beat.beat_track(\n y=self.song.mono_waveform, sr=self.song.sr, tightness=100\n )\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Testrail API request instance. Note that this doesnt send the request until self.sendRequest() is run requestType is str "get", "post" etc. urlParams is the tail of the url payload is a dict that will be sent as a json files is a dict reference to a locale file
def __init__(self, requestType, urlParams, payload={}, files={}): self.baseUrl = os.getenv("TEST_RAIL_BASE_URL") self.username = os.getenv("TEST_RAIL_USERNAME") self.password = os.getenv("TEST_RAIL_API_KEY") # or password self.requestType = requestType self.urlParams = urlParams self.headers = {'Content-type': 'application/json'} self.payload = payload self.response = False
[ "def create_request(self, request_type, parameters):\n request = None\n if request_type == u'scripting_request':\n request = scripting.ScriptingRequest(\n self.current_id, self.json_rpc_client, parameters)\n logger.info(\n u'Scripting request id: {} ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the current instance for a response. To be used by internal methods that are going to act on self.response.
def checkResponse(self): if self.response == False: print("There is no response yet. Run self.sendRequest() first.") return False else: return True
[ "def _default_response_valid(self, response: requests.Response) -> bool:\n return response.status_code == 200", "def IsResponse(self,varName):\n\t\td=self.GetDeclaration(varName)\n\t\treturn isinstance(d,ResponseDeclaration)", "def _ensure_response_has_view(self):\n if not (self.response.original ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt the user with the message and only accept yes/no as input. Return true if they say yes.
def promptYesno(message): choice = "" while not choice: choice = input(message+" [y/n] ") if choice.lower() in ["yes", "y", "yep", "yup", "sure"]: return True elif choice.lower() in ["no", "n", "nope", "nah"]: return False else: print("ERROR: Input not recognized. Choose yes or no\n") choice = ""
[ "def prompt_yes_no(message):\n print(\"\\n-------------------------\")\n print(message)\n while True:\n answer = input(\"(y|n): \")\n if answer.lower() == \"y\":\n return True\n elif answer.lower() == \"n\":\n return False\n else:\n print(\"Inval...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt the user with the message and only accept numbers as input. Return the input.
def promptNum(message): choice = 0 while not choice: choice = input(message+" [number] ") try: int(choice) except: print("ERROR: Input not recognized. Choose a number\n") choice = 0 return choice
[ "def _needs_number(self, user_input):\n while not user_input.isdigit():\n user_input = input(\"You need to enter a number \")\n return int(user_input)", "def multiplier_prompt():\n while True:\n try:\n multiplier = re.sub(\"[, ]\", \"\", input(\"\\nMultiply donations ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt the user with the message and only accept text as input. Return the input.
def promptText(message): choice = "" while not choice: choice = input(message+" [text] ") try: str(choice) except: print("ERROR: Input not recognized. Choose text\n") choice = "" return choice
[ "def prompt_for_value(message_text):\n\n sys.stdout.write(f\"{message_text}: \")\n sys.stdout.flush()\n return sys.stdin.readline().rstrip()", "def fetch_user_input(self):\n user_text = self.entry.get()\n self.entry.delete(0, 'end')\n self.pipe_in_1(\"user_text\")\n return use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Report a result for testname to Testrail, based on test ID mapping in the testsList
def reportResult(testname, testsList, status, comment=False): # Testrail status codes mapped to human readable statusMap = { "pass": 1, "passed": 1, "blocked": 2, "untested": 3, "retest": 4, "fail": 5 } payload = { "status_id": statusMap[status] } if comment: payload["comment"] = comment addResult = testrailRequest("post", "/add_result/"+str(testsList[testname]["id"]), payload) addResult.sendRequest()
[ "def print_test_results(self):\n for n, (name, result) in enumerate(zip(self._test_names, self._test_results)):\n print('Test {} ({}): {}'.format(n+1, name, result))\n print('{} test failure(s)'.format(self.fail_cnt))", "def TestCaseReport(self, name, result, msg=''):\n self._WriteToRe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the requirement of getting `quantity` of the output chemical, return the list of all the input chemicals and their corresponding quantities to create the output If the reaction produces more than required, return also the leftover quantity
def reverse(self, quantity): batches = ceil(quantity / self.out_quantity) leftover = self.out_quantity * batches - quantity result = [] for inp_c, inp_q in self.inp_chemicals.items(): result.append((inp_c, batches * inp_q)) return result, leftover
[ "def required_parts(self):\n parts = []\n\n for item in self.part.bom_items.all():\n part = {'part': item.sub_part,\n 'per_build': item.quantity,\n 'quantity': item.quantity * self.quantity\n }\n\n parts.append(part)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all registered op proto from PaddlePaddle C++ end.
def get_all_op_protos(): protostrs = core.get_all_op_protos() ret_values = [] for pbstr in protostrs: op_proto = framework_pb2.OpProto.FromString(bytes(pbstr)) ret_values.append(op_proto) return ret_values
[ "def getCurrentProto(self) -> \"SoProto *\":\n return _coin.SoOutput_getCurrentProto(self)", "def getCurrentProto(self) -> \"SoProto *\":\n return _coin.SoInput_getCurrentProto(self)", "def generate_protos(session):\n # longrunning operations directory is non-standard for backwards compatibilit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert user's input to OpDesc. Only keyword arguments are supported.
def __call__(self, *args, **kwargs): if len(args) != 0: raise ValueError("Only keyword arguments are supported.") op_desc = framework_pb2.OpDesc() for input_parameter in self.__op_proto__.inputs: input_arguments = kwargs.get(input_parameter.name, []) if is_str(input_arguments): input_arguments = [input_arguments] if not input_parameter.duplicable and len(input_arguments) > 1: raise ValueError( "Input %s expects only one input, but %d are given." % (input_parameter.name, len(input_arguments)) ) ipt = op_desc.inputs.add() ipt.parameter = input_parameter.name ipt.arguments.extend(input_arguments) for output_parameter in self.__op_proto__.outputs: output_arguments = kwargs.get(output_parameter.name, []) if is_str(output_arguments): output_arguments = [output_arguments] if not output_parameter.duplicable and len(output_arguments) > 1: raise ValueError( "Output %s expects only one output, but %d are given." % (output_parameter.name, len(output_arguments)) ) out = op_desc.outputs.add() out.parameter = output_parameter.name out.arguments.extend(output_arguments) # Types op_desc.type = self.__op_proto__.type # Attrs for attr in self.__op_proto__.attrs: if attr.generated: continue user_defined_attr = kwargs.get(attr.name, None) if user_defined_attr is not None: new_attr = op_desc.attrs.add() new_attr.name = attr.name new_attr.type = attr.type if isinstance(user_defined_attr, np.ndarray): user_defined_attr = user_defined_attr.tolist() if attr.type == framework_pb2.INT: new_attr.i = user_defined_attr elif attr.type == framework_pb2.FLOAT: new_attr.f = user_defined_attr elif attr.type == framework_pb2.LONG: new_attr.l = user_defined_attr elif attr.type == framework_pb2.STRING: new_attr.s = user_defined_attr elif attr.type == framework_pb2.BOOLEAN: new_attr.b = user_defined_attr elif attr.type == framework_pb2.INTS: new_attr.ints.extend(user_defined_attr) elif attr.type == framework_pb2.FLOATS: new_attr.floats.extend(user_defined_attr) elif attr.type == framework_pb2.STRINGS: new_attr.strings.extend(user_defined_attr) elif attr.type == framework_pb2.BOOLEANS: new_attr.bools.extend(user_defined_attr) elif attr.type == framework_pb2.LONGS: new_attr.longs.extend(user_defined_attr) elif attr.type == framework_pb2.FLOAT64: new_attr.float64 = user_defined_attr elif attr.type == framework_pb2.FLOAT64S: new_attr.float64s.extend(user_defined_attr) # the code below manipulates protobuf directly elif attr.type == framework_pb2.SCALAR: scalar = make_scalar_proto(user_defined_attr) new_attr.scalar.CopyFrom(scalar) elif attr.type == framework_pb2.SCALARS: scalars = [ make_scalar_proto(item) for item in user_defined_attr ] for item in scalars: new_attr.scalars.MergeFrom(item) else: raise NotImplementedError( "A not supported attribute type: %s." % (str(attr.type)) ) for attr_name, defalut_val in self.__extra_attrs__.items(): user_defined_attr = kwargs.get(attr_name, None) if user_defined_attr is not None: attr_type = int( core.get_attrtibute_type(op_desc.type, attr_name) ) new_attr = op_desc.attrs.add() new_attr.name = attr_name new_attr.type = attr_type if isinstance(user_defined_attr, np.ndarray): user_defined_attr = user_defined_attr.tolist() if attr_type == framework_pb2.INT: new_attr.i = user_defined_attr elif attr_type == framework_pb2.FLOAT: new_attr.f = user_defined_attr elif attr_type == framework_pb2.LONG: new_attr.l = user_defined_attr elif attr_type == framework_pb2.STRING: new_attr.s = user_defined_attr elif attr_type == framework_pb2.BOOLEAN: new_attr.b = user_defined_attr elif attr_type == framework_pb2.INTS: new_attr.ints.extend(user_defined_attr) elif attr_type == framework_pb2.FLOATS: new_attr.floats.extend(user_defined_attr) elif attr_type == framework_pb2.STRINGS: new_attr.strings.extend(user_defined_attr) elif attr_type == framework_pb2.BOOLEANS: new_attr.bools.extend(user_defined_attr) elif attr_type == framework_pb2.LONGS: new_attr.longs.extend(user_defined_attr) elif attr.type == framework_pb2.FLOAT64: new_attr.float64 = user_defined_attr elif attr.type == framework_pb2.FLOAT64S: new_attr.float64s.extend(user_defined_attr) # the code below manipulates protobuf directly elif attr.type == framework_pb2.SCALAR: scalar = make_scalar_proto(user_defined_attr) new_attr.scalar.CopyFrom(scalar) elif attr.type == framework_pb2.SCALARS: scalars = [ make_scalar_proto(item) for item in user_defined_attr ] for item in scalars: new_attr.scalars.MergeFrom(item) else: raise NotImplementedError( "A not supported attribute type: %s." % (str(attr_type)) ) return op_desc
[ "def test_opdef_sig():\n from tensorflow.core.framework import op_def_pb2\n\n custom_opdef_tf = op_def_pb2.OpDef()\n custom_opdef_tf.name = \"MyOpDef\"\n\n arg1_tf = op_def_pb2.OpDef.ArgDef()\n arg1_tf.name = \"arg1\"\n arg1_tf.type_attr = \"T\"\n\n arg2_tf = op_def_pb2.OpDef.ArgDef()\n arg2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate op creation method for an OpProto.
def create_op_creation_method(op_proto): method = OpDescCreationMethod(op_proto) def __impl__(*args, **kwargs): opdesc = method(*args, **kwargs) return core.Operator.create(opdesc.SerializeToString()) extra_attrs_map = core.get_op_extra_attrs(op_proto.type) return OpInfo( method=__impl__, name=op_proto.type, inputs=[(var.name, var.duplicable) for var in op_proto.inputs], outputs=[(var.name, var.duplicable) for var in op_proto.outputs], attrs=[attr.name for attr in op_proto.attrs], extra_attrs=list(extra_attrs_map.keys()), )
[ "def _generate_doc_string_(\n op_proto, additional_args_lines=None, skip_attrs_set=None\n):\n\n if not isinstance(op_proto, framework_pb2.OpProto):\n raise TypeError(\"OpProto should be `framework_pb2.OpProto`\")\n\n buf = StringIO()\n buf.write(escape_math(op_proto.comment))\n buf.write('\\nA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
telnet_expect(list, timeout=None) Read until one from a list of a regular expressions matches.
def Telnet_expect(list, timeout=None): return;
[ "def expect(self, list, timeout=None):\r\n re = None\r\n list = list[:]\r\n indices = range(len(list))\r\n for i in indices:\r\n if not hasattr(list[i], \"search\"):\r\n if not re: import re\r\n list[i] = re.compile(list[i])\r\n while 1:\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write to Telnet Port
def PortWrite( data ): global gTelnetConn if gTelnetConn == None: OpenTelnet() gTelnetConn.write( data ) return;
[ "def _telnet_write(self, message):\n self.tn.write(message + \"\\r\\n\") # Writes telnet message to connected device, with termination chars added", "def writeBytes(port, toWrite):\n print(port, toWrite)", "def write(self, data):\n self.serial_device.write(data)", "def __sendTelnetCommand(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read from Telnet Port
def PortRead(): global gTelnetConn if gTelnetConn == None: OpenTelnet() data = gTelnetConn.read() return data;
[ "def _telnet_read(self):\n return self.tn.read_until(\"\\n\", self.timeout).rstrip('\\n') # Reads reply from device, strips termination char", "def readLine(port, timeout=5000, encoding='utf-8'):\n print(port, timeout, encoding)\n return ''", "def readBytes(port, numberOfBytes, timeout=5000):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Input > a list of integers. output > sorted list. Odd nums first, then even
def my_sort(a_list): sorted_list = [] sort_list(a_list) return odd_list(a_list) + even_list(a_list)
[ "def sort_numbers(lis):\n \n i = 0\n iterations = 0\n \n while iterations < len(lis):\n \n # if the integer is odd, bring it to the end of the list\n if lis[i]%2 != 0:\n \n integer = lis.pop(i)\n lis.append(integer)\n \n # we...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function prints the current time in isoformat, followed by the normal print.
def timeprint(*args, **kwargs: Any) -> None: print(datetime.now().isoformat(), *args, **kwargs)
[ "def get_iso_time() -> str:\n return datetime.now().isoformat()", "def isoformat(self):\r\n s = _format_time(self.__hour, self.__minute, self.__second,\r\n self.__microsecond)\r\n tz = self._tzstr()\r\n if tz:\r\n s += tz\r\n return s", "def time...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function clears contents within a list
def clear(List): print("Original list:",List) print("Cleared list:", [List.clear()])
[ "def clearList(self):\n\n del self.genomeList[:]", "def clear_list(self):\n self.active_list = []\n self.failed_list = []", "def clear(self):\n self.listwalker.clear()", "def ClearItems(self):\n for item in self.items:\n item.Destroy()\n for line in self.line...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine bounding box from child elements.
def determine_bounding_box(elements: List): x0, y0, x1, y1 = zip(*map(lambda e: e.bbox, elements)) bbox = (min(x0), min(y0), max(x1), max(y1)) return bbox
[ "def _compound_bounding_box(self, experiment):\n bounds = experiment.prepdata.bounds\n def wh(row):\n return self.where_is(row['bid'])\n\n bounds['node'] = bounds.apply(wh, axis=1)\n groups = bounds.groupby('node')\n bboxes = groups.agg({'x_min': min, 'x_max': max, 'y_m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an estimate to the number of distinct elements in items items a sequence of elements k number of hash functions
def estimate_distinct_elements(items, k): hll = HLL.HyperLogLog64(k) hll.extend(items) return hll.cardinality
[ "def estimate_distinct_elements_parallel(lists_of_items, k, spark_context):\n hll = spark_context.parallelize(lists_of_items) \\\n .mapPartitions(init_compute_hmaps(k)) \\\n .reduce(lambda x, y :x + y)\n return hll.cardinality", "def __hash__(self):\n # Sin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a method yielding hmaps from hll initialised with k hash functions
def init_compute_hmaps(k): def compute_hmaps(list_of_sequences): """ Iterator yielding 1 HyperLogLog.hmap per sequence in given iterable list_of_sequences - iterable of iterable """ for sequence in list_of_sequences: hll = HLL.HyperLogLog64(k) hll.extend(sequence) yield hll return compute_hmaps
[ "def compute_hmaps(list_of_sequences):\n for sequence in list_of_sequences:\n hll = HLL.HyperLogLog64(k)\n hll.extend(sequence)\n yield hll", "def hashFunctionTest():\n m = 128\n h = HashFunction(m)\n print(h)\n\n count = [0] * m\n for i in range(m*2):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }