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 ... | [
"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... | [
"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 fr... | [
"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))]
... | [
"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=... | [
"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 ... | [
"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.... | [
"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_p... | [
"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))
... | [
"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:
... | [
"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.majo... | [
"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"... | [
"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.... | [
"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... | [
"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
... | [
"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(... | [
"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.Si... | [
"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 fie... | [
"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
... | [
"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)
... | [
"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] [batc... | [
"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, sel... | [
"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}... | [
"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)
)
# bu... | [
"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-Dispositi... | [
"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... | [
"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": "tot... | [
"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 ... | [
"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": ... | [
"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'... | [
"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
... | [
"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 ... | [
"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... | [
"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)
... | [
"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",
... | [
"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... | [
"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
... | [
"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: I... | [
"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]
... | [
"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... | [
"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(
meth... | [
"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)
... | [
"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"
]
]
}
} |