query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Make DataFrame from blocks, each columns is a different field, each row is for a different file.
def make_dataframe(block_name, blocks): names = {} # store names corresponding to column ids all_rows = [] # store list of dicts of column_id: value for k, v in blocks.iteritems(): # to hold table info for this file info = {} for line in v: # split around the #. parts[0] ...
[ "def _parse_block(self,idx):\n block_tmp = self._block_list[idx]\n blocktype = self._paragraph_or_table[idx]\n paragraph_count = sum(self._paragraph_or_table[:idx+1])\n table_count = idx + 1 - paragraph_count\n df = DataFrame()\n # paragraph\n if blocktype==1:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Donate the item(s)/ send to NPO
def donate(self):
[ "async def donate(self):\n await self.bot.say(\"You can donate to me here:\\n<https://www.paypal.me/avrae>\\n\\u2764\")", "async def donate(self, ctx, amount: CoinConverter):\n await self.transfer(ctx.author.id, ctx.guild.id, amount)\n await ctx.send(f'\\N{MONEY WITH WINGS} `{ctx.author!s}` >...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When an IconScore receives some coins and calldata is None, fallback function is called.
def _fallback(context: 'IconScoreContext', score_address: 'Address'): icon_score = IconScoreEngine._get_icon_score(context, score_address) score_func = getattr(icon_score, ATTR_SCORE_CALL) score_func(STR_FALLBACK)
[ "def default_callback(self):\n raise ScoreExceededError(\"Score has been exceeded!\")", "def pickup_coin(self, x, y):\n \n # ADD CODE HERE\n if self.coins[y][x] > 0:\n coins = self.coins[y][x]\n self.coins[y][x] = 0\n return coins\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If progress has insreased sufficiently, log it to ``logger``. If ``new_ratio``, rounded to ``decimals`` differs from ``old_ratio``, log to logger with INFO level and return rounded new_ratio. Else return unmodified ``old_ratio``.
def _log_progress(new_ratio, old_ratio, logger, decimals=2): new_ratio = round(new_ratio, decimals) if new_ratio != old_ratio: logger.info('%s', '{}%'.format(new_ratio * 100)) return new_ratio else: return old_ratio
[ "def likelihood_ratio(self, new_dist_info, old_dist_info):\n LL_old = old_dist_info[0]\n LL_new = new_dist_info[0]\n LR = torch.exp(LL_new - LL_old)\n return LR", "def equalRatio(self):\n self.userPkmn.battleDelegate.stats[self.stat] = self.lvl\n self.targetPkmn.battleDel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log all uncaught exceptions in noninteractive mode. All python exceptions are handled by function, stored in ``sys.excepthook.`` By rewriting the default implementation, we can modify handling of all uncaught exceptions.
def _log_all_uncaught_exceptions(exc_type, exc_value, exc_traceback): # ignore KeyboardInterrupt if not issubclass(exc_type, KeyboardInterrupt): ROOT_LOGGER.error("", exc_info=(exc_type, exc_value, exc_traceback)) sys.__excepthook__(exc_type, exc_value, exc_traceback) return
[ "def setup_exceptionhook():\n\n def _pdb_excepthook(type, value, tb):\n if is_interactive():\n import traceback\n import pdb\n traceback.print_exception(type, value, tb)\n print()\n pdb.post_mortem(tb)\n else:\n lgr.warn(\"We cannot ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test band structure calculation by NaCl.
def test_band_structure(ph_nacl): ph_nacl.run_band_structure( _get_band_qpoints(), with_group_velocities=False, is_band_connection=False ) ph_nacl.get_band_structure_dict()
[ "def test_band_structure_bc(ph_nacl):\n ph_nacl.run_band_structure(\n _get_band_qpoints(), with_group_velocities=False, is_band_connection=True\n )\n ph_nacl.get_band_structure_dict()", "def test_band_structure_gv(ph_nacl):\n ph_nacl.run_band_structure(\n _get_band_qpoints(), with_group_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test band structure calculation with group velocity by NaCl.
def test_band_structure_gv(ph_nacl): ph_nacl.run_band_structure( _get_band_qpoints(), with_group_velocities=True, is_band_connection=False ) ph_nacl.get_band_structure_dict()
[ "def test_band_structure_bc(ph_nacl):\n ph_nacl.run_band_structure(\n _get_band_qpoints(), with_group_velocities=False, is_band_connection=True\n )\n ph_nacl.get_band_structure_dict()", "def test_band_structure(ph_nacl):\n ph_nacl.run_band_structure(\n _get_band_qpoints(), with_group_vel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test band structure calculation with band connection by NaCl.
def test_band_structure_bc(ph_nacl): ph_nacl.run_band_structure( _get_band_qpoints(), with_group_velocities=False, is_band_connection=True ) ph_nacl.get_band_structure_dict()
[ "def test_band_structure(ph_nacl):\n ph_nacl.run_band_structure(\n _get_band_qpoints(), with_group_velocities=False, is_band_connection=False\n )\n ph_nacl.get_band_structure_dict()", "def test_band_structure_gv(ph_nacl):\n ph_nacl.run_band_structure(\n _get_band_qpoints(), with_group_ve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse the request packet & create trip
def trip_get(reqdata): pass
[ "def _ParseProtoPayloadRequest(\n self,\n request: Dict[str, Any],\n timesketch_record: Dict[str, Any]) -> None:\n request_attributes = [\n 'name', 'description', 'direction', 'member', 'targetTags', 'email',\n 'account_id'\n ]\n for attribute in request_attributes:\n if a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read a messagepack file and return individual messages
def read_file(filename): with open(filename, 'rb') as file: unpacker = msgpack.Unpacker(file, raw=False) for msg in unpacker: yield msg
[ "def read_msgpack(path: PathType) -> Any:\n\n with copen(path, \"rb\") as fr:\n return unpack(fr, use_list=False, raw=False, strict_map_key=False, ext_hook=ext_hook)", "def read_messages (file_of_messages):\n line = file_of_messages.readline()\n collection_of_messages = []\n while (line != \"\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get pointcloud data from msg
def get_pointclouds(msg): return msg['pointclouds']
[ "def process_cloud(self, msg):\n with self.m:\n self.actualP = msg #Receive pointcloud", "def point_cloud_msg(self, points, stamp):\n ros_dtype = sensor_msgs.msg.PointField.FLOAT32\n dtype = np.float32\n itemsize = np.dtype(dtype).itemsize\n\n data = points.astype(dty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create test input tensor.
def create_test_input(batch_size, height, width, channels): if None in [batch_size, height, width, channels]: return tf.placeholder(tf.float32, (batch_size, height, width, channels)) else: return tf.to_float( np.tile( np.reshape( np.reshape(np.arange(height), [height, 1])...
[ "def gen_test_tensor_cpd():\n return TensorCPD(*gen_test_data())", "def _create_dummy_input(func_graph, template_tensor):\n with func_graph.as_default():\n return array_ops.placeholder(\n template_tensor.dtype, shape=template_tensor.shape)", "def new_tensor(data, is_batch=False, is_sequence=False,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the hairy graph vector space.
def __init__(self, n_vertices, n_loops, n_hairs, even_edges): self.n_vertices = n_vertices self.n_loops = n_loops self.n_hairs = n_hairs self.even_edges = even_edges self.sub_type = "even_edges" if even_edges else "odd_edges" # we count only the internal edges se...
[ "def __init_graph(self) -> None:\n self.graph = Graph()", "def __init__(self):\n self.g = nx.DiGraph()", "def zero(self):\n v = np.zeros(self.get_dimension())\n self.set_vector(v)", "def __init__(self, **kwargs):\n if not hasattr(self, \"graph\"):\n self.graph = -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produces all connected hairy graphs with nhairs hairs, that are the last vertices in the ordering. Graphs can have multiple hairs, but not tadpoles or multiple edges.
def get_hairy_graphs(self, nvertices, nloops, nhairs, include_novertgraph=false): # Idea: produce all bipartite graphs, the second color being either of degree 1 or 2. # Degree 1 vertices are hairs, degree 2 vertices are edges and are removed later. nedges = nloops + nvertices - 1 # number of i...
[ "def complete_to_chordal_graph(G):\n H = G.copy()\n alpha = {node: 0 for node in H}\n if nx.is_chordal(H):\n return H, alpha\n chords = set()\n weight = {node: 0 for node in H.nodes()}\n unnumbered_nodes = list(H.nodes())\n for i in range(len(H.nodes()), 0, -1):\n # get the node i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the contract edges differential with the underlying sum vector space.
def __init__(self, sum_vector_space): super(ContractEdgesD, self).__init__(sum_vector_space, ContractEdgesGO.generate_op_matrix_list(sum_vector_space))
[ "def __init__(self, sum_vector_space):\n super(DeleteEdgesD, self).__init__(sum_vector_space,\n DeleteEdgesGO.generate_op_matrix_list(sum_vector_space))", "def _init_distance_vector(self):\r\n for router in [self.sourceRouter]+list(self.neighbours.keys()):\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Await and return the message or None on timeout.
def waitForMsg(self): rospy.loginfo('Waiting for message...') if self.timeout is not None: timeout_time = rospy.Time.now() + rospy.Duration.from_sec(self.timeout) while self.timeout is None or rospy.Time.now() < timeout_time: self.mutex.acquire() if self.msg i...
[ "def recv(self, timeout=None):\n\n if message := self.recv_message(timeout):\n return message.payload\n return None", "async def send_command_and_await(self, message: str, timeout: int = None) -> DroneResponse:\n pass", "def recv_message(self, timeout=None):\n\n if self.su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the message for launchalert (doesn't include mention)
async def launchalertformatter(launch): launchtime_tz = launch.net utc = datetime.now(timezone.utc) T_minus = chop_microseconds(launchtime_tz - utc) T_plus = timedelta(0) T = T_minus if T_minus < timedelta(0): T_plus = chop_microseconds(utc - launchtime_tz) T = T_plus T_s...
[ "def get_message_alert(alert):\n measurement = get_measurement_from_rule(alert.alert)\n return \"At site %s \\n %s is %s %s%s\" % (alert.site, get_measurement_verbose_name(measurement),\n alert.alert.get_operator_display(), alert.alert.value,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tells information about next launch. n Notifies launch notify group. id Includes launch ID. d Includes mission description. v Includes video URL.
async def nextlaunch(self, ctx, *args): if not can_answer(ctx): return launches = launchlibrary.Launch.next(api, 1) if launches: launch = launches[0] launchname = launch.name launchtime_tz = launch.net utc = datetime.now(timezone.utc) ...
[ "async def launchbyid(self, ctx, *args):\n if not can_answer(ctx):\n return\n launchid = False\n for arg in args:\n if str(arg).isdigit():\n launchid = int(arg)\n if launchid:\n launch = launchlibrary.Launch.fetch(api, id=launchid)[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables launch alerts until next shutdown. Only authorities can use this. [int] Minutes before launch to alert. (default = 15, max = 99)
async def launchalert(self, ctx, alerttime='15'): author = ctx.author if author.guild_permissions.administrator or author.id in authorities: await ctx.send("Command currently disabled") # if len(alerttime) < 2: # alerttime = int(alerttime) # msg = ...
[ "def do_something_every_hour():\n sleep(5)", "def on_enable_notifier(self, widget):\n try:\n if widget.get_active():\n subprocess.run([\"systemctl\", \"--user\", \"enable\", \"mintupdate-automation-notifier.timer\"])\n else:\n subprocess.run([\"systemctl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tells information about launch with provided ID. [int] ID of the launch. r Includes holdreason and failreason v Includes video URL. d Includes mission description.
async def launchbyid(self, ctx, *args): if not can_answer(ctx): return launchid = False for arg in args: if str(arg).isdigit(): launchid = int(arg) if launchid: launch = launchlibrary.Launch.fetch(api, id=launchid)[0] launch...
[ "def get_launch(self, launch_id, count=1):\n assert count == 1\n record = self.launches.get(launch_id)\n if record:\n ret = json.loads(record)\n else:\n ret = None\n return defer.succeed(ret)", "def get_launch(self, launch_id, count=1):\n return self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tells information about launch with provided name. "str" Name of the launch. (always first) id Includes id of the launch. r Includes holdreason and failreason. v Includes video URL. d Includes mission description.
async def launchbyname(self, ctx, name, *args): if not can_answer(ctx): return for arg in args: if arg.startswith('-'): break else: name = name + ' ' + arg launches = launchlibrary.Launch.fetch(api, name=name) if launche...
[ "async def launchbyid(self, ctx, *args):\n if not can_answer(ctx):\n return\n launchid = False\n for arg in args:\n if str(arg).isdigit():\n launchid = int(arg)\n if launchid:\n launch = launchlibrary.Launch.fetch(api, id=launchid)[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lists launches with provided name. [int] The number of launches listed. Default is 5, max 10. s Include launch status. id Include the IDs of the launches.
async def listbyname(self, ctx, name, *args): if not can_answer(ctx): return num = 5 for arg in args: if arg.startswith('-'): break else: name = name + ' ' + arg for arg in args: if arg[1:].isdigit() and arg....
[ "async def launchbyname(self, ctx, name, *args):\n if not can_answer(ctx):\n return\n for arg in args:\n if arg.startswith('-'):\n break\n else:\n name = name + ' ' + arg\n launches = launchlibrary.Launch.fetch(api, name=name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tells information about rocket with provided name. "str" Name of the rocket. (always first) id Includes id of the rocket. fid Includes rocketfamily id. aid Includes agency id. p Includes pad ids. w Includes wikipedia URL.
async def rocketbyname(self, ctx, name, *args): if not can_answer(ctx): return rockets = launchlibrary.Rocket.fetch(api, name=name) if rockets: rocket = rockets[0] rocketname = rocket.name msg = '**__{0}__**\n' msg = msg.format(rocketna...
[ "def id_standard( obj_name ):\n # name, side (1=blue, 2=red)\n standards = {'feige34': 1, 'feige110' : 1, 'hz44' : 1, \n 'bd284211' : 1, 'g191b2b' : 1, 'bd174708' : 2,\n 'bd262606' : 2, 'hd84937' : 2, 'hd19445' : 2}\n \n # cleanup the input object name\n o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tells information about rocket with provided ID. [int] ID of the rocket. fid Includes rocketfamily id. aid Includes agency id. p Includes pad ids. w Includes wikipedia URL.
async def rocketbyid(self, ctx, *args): if not can_answer(ctx): return for arg in args: if arg.isdigit(): id = int(arg) rockets = launchlibrary.Rocket.fetch(api, id=id) if rockets: rocket = rockets[0] rocketname = rocket.nam...
[ "def get(self, redflag_id):\n redflag = RedFlagModel.find_redflag(redflag_id, DB)\n if redflag is not None:\n return {'status': 200, 'data': redflag}, 200\n return not_found('That redflag cannot be found')", "def lookup_rival(self, rival_id):\n uri = 'https://p.eagate.573.jp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find all the docs on the basis of list of MACS and time frame
def let_the_docs_out(self, post_data): doc_list = [] mac_list = post_data['mac'] if 'time' in post_data and post_data['time']: time_frame = post_data['time'] start_time = time_frame[0] end_time = time_frame[1] else: utc_1970 = datetime.da...
[ "def test_long_doc_lst(self):\n\n # Long document list - created manually for a unique test\n doc_lst = [\n {\n \"_id\": \"test1\",\n \"chebi\": \"CHEBI:1391\",\n },\n {\n \"_id\": \"test2\",\n \"pubchem\": \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a wall at grid[row][col]. Can't set a wall on top of the source/target square.
def setWall(self, row, col): if self.grid[row][col] != 2 and self.grid[row][col] != 3: self.grid[row][col] = 1 #print("Wall set at (", row, ", ", col, ")")
[ "def make_wall(width, height, wall_cell):\n # add your code here", "def create_wall(window, grid, mouse, wall, empty, start, end):\n\n x = int(mouse.x / (window.getWidth() / grid.get_length()))\n y = int(mouse.y / (window.getHeight() / grid.get_height()))\n if (x != start[0] or y != start[1]) and (x !...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Togggles the Source Tile. If the source is not set, sets it. If the source is set, removes it if Source == (row, col), or moves it to (row, col) otherwise.
def toggleSource(self, row, col): # if the source is not set, set it if self.getSource() == (None, None): self.setSource(row, col) # if the source is set else: # if the source is the current square, remove it if self.grid[row][col] == 2: ...
[ "def toggleTarget(self, row, col):\n # if the target is not set, set it\n if self.getTarget() == (None, None):\n self.setTarget(row, col)\n # if the target is set\n else:\n # if the target is the current square, remove it\n if self.grid[row][col] == 3:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Togggles the Target Tile. If the target is not set, sets it. If the target is set, removes it if Target == (row, col), or moves it to (row, col) otherwise.
def toggleTarget(self, row, col): # if the target is not set, set it if self.getTarget() == (None, None): self.setTarget(row, col) # if the target is set else: # if the target is the current square, remove it if self.grid[row][col] == 3: ...
[ "def movetarget(self):\n x, y = self.target[0], self.target[1]\n neigh = [(nx, ny) for nx in [x - 1, x, x + 1] for ny in [y - 1, y, y + 1] if (nx, ny) != (x, y) if\n (nx, ny) in self.cells]\n nextstep = neigh[randint(0, len(neigh) - 1)]\n self.target = nextstep", "def m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if Node = (row, col) is the target, else returns false.
def isTarget(self, node): return (node == self.target)
[ "def toBeLabeled(self, row, col):\n\n #must check to see if the square is black. If the square is black than\n #it cannot be labeled\n if self._grid[row][col].isBlack():\n return False\n\n #must check to see if the square is furthest left or on the top row,\n #which wi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a matrix of integers from a matrix of Nodes. Used after the backtracking algorithm is done to return a more common format of the sudoku board.
def node_to_arr(node_matrix): sol = [] for y in range(9): row = [] for x in range(9): row.append(node_matrix[y][x].value) sol.append(row) return sol
[ "def matrix_adjacency_directed(graph):\r\n nodes = get_nodes(graph)\r\n matrix = []\r\n\r\n for i in nodes:\r\n row = []\r\n for j in nodes:\r\n if [i, j] in graph:\r\n row.append(1)\r\n else:\r\n row.append(0)\r\n matrix.append(row)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the Nei & Gojobori (1986) section of the resuls. Nei_Gojobori results are organized in a lower triangular mattrix, with the sequence names labeling
def parse_ng86(lines, results): sequences = [] for line in lines: # Find all floating point numbers in this line line_floats_res = re.findall("-*\d+\.\d+", line) line_floats = [float(val) for val in line_floats_res] matrix_row_res = re.match("(.+)\s{5,15}",line) if matri...
[ "def parse_others(lines, results, sequences):\n # Example:\n # 2 (Pan_troglo) vs. 1 (Homo_sapie)\n\n # L(i): 143.0 51.0 28.0 sum= 222.0\n # Ns(i): 0.0000 1.0000 0.0000 sum= 1.0000\n # Nv(i): 0.0000 0.0000 0.0000 sum= 0.0000\n # A(i): 0.0000 0.0200 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the Yang & Nielsen (2000) part of the results. Yang & Nielsen results are organized in a table with each row comprising one pairwise species comparison. Rows are labeled by spequence number rather than by sequence name.
def parse_yn00(lines, results, sequences): # Example (header row and first table row): # seq. seq. S N t kappa omega dN +- SE dS +- SE # 2 1 67.3 154.7 0.0136 3.6564 0.0000 -0.0000 +- 0.0000 0.0150 # +- 0.0151 for line in lines: # Find all floati...
[ "def parse_others(lines, results, sequences):\n # Example:\n # 2 (Pan_troglo) vs. 1 (Homo_sapie)\n\n # L(i): 143.0 51.0 28.0 sum= 222.0\n # Ns(i): 0.0000 1.0000 0.0000 sum= 1.0000\n # Nv(i): 0.0000 0.0000 0.0000 sum= 0.0000\n # A(i): 0.0000 0.0200 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the results from the other methods. The remaining methods are grouped together. Statistics for all three are listed for each of the pairwise species comparisons, with each method's results on its own line. The stats in this section must be handled differently due to the possible presence of NaN values, which won'...
def parse_others(lines, results, sequences): # Example: # 2 (Pan_troglo) vs. 1 (Homo_sapie) # L(i): 143.0 51.0 28.0 sum= 222.0 # Ns(i): 0.0000 1.0000 0.0000 sum= 1.0000 # Nv(i): 0.0000 0.0000 0.0000 sum= 0.0000 # A(i): 0.0000 0.0200 0.0000 ...
[ "def parse_summarized_results(lines):\n result = BenchSummary([], [], [], [], [], [], [], [], [])\n # Begin iterating over lines\n for line in lines:\n if not line or line.startswith('#'):\n continue\n line = line.strip()\n values = line.split('\\t')\n result.label.ap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs a hillclimber with two random chosen houses. It takes two random chosen houses, checks if it is possible to switch and if the costs would be lower.
def hillclimber(map): for i in range(40000): house1 = map.houses[random.randrange(150)] house2 = map.houses[random.randrange(150)] battery1 = house1.connected battery2 = house2.connected if battery1 is not None and battery2 is not None: if battery1.id ==...
[ "def hill_climber(self, iterations):\n\n random_houses = list(self.houses.values())\n random_houses_2 = list(self.houses.values())\n iterations = int(iterations)\n count = 0\n misses = -iterations\n prices = []\n\n # Do untill we have <iterations> succesfull configurations\n while count < it...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main method of the 'Worker' layer of this project. This method starts the distributed working phase which will consume urls from the seed database and scrape apps data out of the html pages, storing the result into the apps_data collection on MongoDB
def scrape_apps(self): # Arguments Parsing args_parser = self.get_arguments_parser() self._args = vars(args_parser.parse_args()) # Log Handler Configuring self._logger = Utils.configure_log(self._args) # MongoDB Configuring if not Utils.configure_mongodb(self,*...
[ "def main():\r\n args = get_args()\r\n scrape_n_books(args.num_books, args.start_url, args.real_time)\r\n scrape_n_authors(args.num_authors, args.real_time)\r\n\r\n # Update after scraping\r\n # get path and store data in json\r\n if not args.real_time:\r\n curr_dir = os.path.dirname(os.pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read production capacities, either offline (locally) or online (from scenario explorer)
def get_production_capacities(conf, source='offline', verbose=True): # if offline source, read local data if source == 'offline': hourly_capacities = pd.read_csv('Input/ProductionCapacities.csv', index_col=0).iloc[conf['t_start']:conf['t_end'], :] # if online source, read data from ...
[ "def get_production_costs(conf, source='offline', verbose=True):\n\n # if offline source, read local data\n if source == 'offline':\n hourly_costs = pd.read_csv('Input/ProductionCosts.csv', index_col=0).iloc[conf['t_start']:conf['t_end'], :]\n # if online source, read data from openE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read production costs, either offline (locally) or online (from scenario explorer)
def get_production_costs(conf, source='offline', verbose=True): # if offline source, read local data if source == 'offline': hourly_costs = pd.read_csv('Input/ProductionCosts.csv', index_col=0).iloc[conf['t_start']:conf['t_end'], :] # if online source, read data from openENTRANCE sc...
[ "def get_detailed_costs(self):\n # TODO: Cache for a day\n # TODO: Generate path to cost csv\n today = datetime.date.today()\n csv_file = \"906142011005-aws-billing-detailed-line-items-with-resources-and-tags-%s-%02d.csv\" % (today.year, today.month)\n stringio = cStringIO.StringI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read initial demand, either offline (locally) or online (from scenario explorer)
def get_initial_demand(conf, source='offline', verbose=True): # if offline source, read local data if source == 'offline': initial_demand = pd.read_csv('Input/InitialDemand.csv', index_col=0).iloc[conf['t_start']:conf['t_end'], :] # if online source, read data from openENTRANCE scen...
[ "def get_current_demand(self, callback=None):\n xml_demand = self._query_eagle()\n current_demand = self._parse_demand(xml_demand)\n\n if callback:\n return callback(current_demand)\n else:\n return current_demand", "def get_demand(self, j=None):\n if j is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a parameterless function.
def parameterless(): return None
[ "def dummy_function(*args, **kwargs):\n return", "def example(param):\n\tassert param >0 \n\t# do stuf here...", "def __call__(self, *args, **kwargs): # real signature unknown; restored from __doc__\n pass", "def __special__(self):\n pass", "def __do_nothing(*args):\n pass", "def p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle changeset actions. Main function to interacte with changeset, use argument to control the actions. This function is using update_stack to handle all the dirty works as both functions are processing cloudformation arguments and having the same arguments.
def changeset_stack( profile: Union[str, bool] = False, region: Union[str, bool] = False, replace: bool = False, local_path: Union[str, bool] = False, root: bool = False, wait: bool = False, info: bool = False, execute: bool = False, delete: bool = False, extra: bool = False, ...
[ "def execute_change_set(self, change_set_name):\n self._protect_execution()\n change_set = self.describe_change_set(change_set_name)\n status = change_set.get(\"Status\")\n reason = change_set.get(\"StatusReason\")\n if status == \"FAILED\" and self.change_set_creation_failed_due_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
try to move to the room neighboring in {direction} of the players current room
def move_to(self, direction): if self.room.neighbor[direction]: #check if room in dir exists self.__set_room__(self.room.neighbor[direction]) return True else: return False
[ "def move(rooms, exits, direction):\n\n # Next room to go to\n return rooms[exits[direction]]", "def move(self, direction):\n if not self.dead:\n cells = self.cells\n\n if direction == 0:\n self.direction = 0\n for i in range(len(cells) - 1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Operation for efficiently calculating the dot product when one or all operands is sparse. Supported format are CSC and CSR. The output of the operation is dense.
def dot(x, y): if hasattr(x, 'getnnz'): x = theano.sparse.as_sparse_variable(x) if hasattr(y, 'getnnz'): y = theano.sparse.as_sparse_variable(y) x_is_sparse_variable = theano.sparse.basic._is_sparse_variable(x) y_is_sparse_variable = theano.sparse.basic._is_sparse_variable(y) if n...
[ "def safe_sparse_dot(a, b, dense_output=False):\n if type(a) == SparseLR and type(b) == np.ndarray:\n return a.dot(b)\n if type(b) == SparseLR and type(a) == np.ndarray:\n return (b.T).dot(a.T).T\n if type(a) == SparseLR and type(b) == SparseLR:\n raise NotImplementedError\n if spar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the cycle variable, which display the cycle entry.
def reset_cycle(self): self.cycle = None
[ "def reset(self):\n self.numb = self.starter", "def cycleDown(self):\n self.openVideo(self.cycle_vid.down(), self.image_holder.cur_idx)\n self.changeDescription()", "def reset(self) -> None:\n self.progress_text.set(\"\")\n self.progress_pct_value.set(0.0)\n self.progre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the stack list
def reset_stack(self): self.stack = []
[ "def clear(self):\n self.stack = list()", "def reset_stack(self):\n\n for i in range(0, self._num_players):\n self._obs_stacks[i].fill(0.0)", "def test_stack_reset(stack_with_content):\n stack_with_content.reset()\n\n assert stack_with_content.pop() is None", "def restore_state(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the traverse list
def reset_traverse(self): self.traverse = []
[ "def reset(self):\n self.fuse = []", "def reset(self):\n # A copy is necessary here so that the modifications to the list don't affect the traversal.\n for qubit in copy(self.live_qubits):\n self.free_qubit(qubit)\n qubit.resource_manager = None\n self.live_qubits...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Einzelne Client Verbindung funktion
def client_verbindung(client): name = client.recv(BUFFERSIZE).decode("utf8") willkommen = 'Willkomen %s! Um sich auszuloggen schreiben Sie bitte {quit}!' %name client.send(bytes(willkommen, "utf8")) msg = "%s hat sich Verbunden!" %name broadcast(bytes(msg, "utf8")) clients[client] = name whi...
[ "def connected(client):", "def __init__(self):\n self.socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.endereco = socket.gethostname()\n self.porta = 9997\n self.socket_client.connect((self.endereco, self.porta))\n self.menu = info\n self.apresenta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove quotes from a TensorFlow string.
def normalize_text(text): text = tf.strings.regex_replace(text,"'(.*)'", r"\1") return text
[ "def normalize_text(text):\n text = tf.strings.lower(text)\n text = tf.strings.strip(text)\n # text = tf.strings.regex_replace(text,\"'(.*)'\", r\"\\1\")\n return text", "def no_quote(s):\r\n return s", "def strip_quotes(value: Any) -> Any:\n if isinstance(value, str):\n value = value.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Authentication specified to Aroio with the username and password
def authenticate( aroio_name: str, aroio_password: str, username: str, password: str) -> bool: if username != aroio_name: return False if not Authentication.verify_password(plain=password,hashed=aroio_password): return False return True
[ "def instamojo_auth(self, username, password):\n res = self.instamojo_api_request(method='POST', path='auth/', username=username, password=password)\n if res['success']:\n self.mojo_token = res['token']\n return res", "def login(username, password):", "def __authenticate(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns cost of navigating between two nodes
def cost(self, node_1, node_2): (x_coord_1, y_coord_1) = node_1 (x_coord_2, y_coord_2) = node_2 return abs(x_coord_1 - x_coord_2) + abs(y_coord_1 - y_coord_2)
[ "def cost(self, from_node, to_node):\n return 1", "def new_cost(self, from_node, to_node):\n return from_node.cost + self.dist(from_node, to_node)", "def get_estimated_cost(start_node, destination_node):\r\n delta_x = abs(start_node.x - destination_node.x)\r\n delta_y = abs(start_nod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a farthest point given a node
def farthest_node(self, node_1): nodes = self.__flood_fill(node_1) highest_cost_node = (-1, -1) highest_cost = -1 for node_2 in nodes: cost = self.cost(node_1, node_2) if cost > highest_cost: highest_cost_node = node_2 highest_cost...
[ "def farthestPoint(pointList, p):\r\n return None", "def get_farthest(self):\n return self.__get_node(len(self.__neighbours) - 1)", "def get_nearest_node(self, point, return_dist=False):\n return ox.get_nearest_node(self.G_risk, point, return_dist=return_dist)", "def closest_point(self,graph, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure node is in bounds
def is_node_in_bounds(self, node): (x_coord, y_coord) = node if x_coord < 0 or x_coord >= self.width: return False elif y_coord < 0 or y_coord >= self.height: return False else: return True
[ "def CheckBounds(self, ):\n ...", "def outside_arena():\r\n return not (0 < node.x < bounds[0] and 0 < node.y < bounds[1])", "def is_out_of_bounds(self, agent):\n x = agent.x\n y = agent.y\n\n if x < 0 or x >= self.width:\n return True\n if y < 0 or y >= self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A description for the portal.
def portal_description(self) -> Optional[str]: return pulumi.get(self, "portal_description")
[ "def Description(self):\n portal_transforms = getToolByName(self, 'portal_transforms')\n data = portal_transforms.convertTo('text/plain', self.getBiography(), mimetype='text/html')\n if data:\n descr = data.getData()\n return '%s...' % (' '.join(descr.split(' ')[:140]))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ID of the portal.
def portal_id(self) -> Optional[str]: return pulumi.get(self, "portal_id")
[ "def id(self) -> int:\n return self._context.id", "def id(self):\n return self.getAttribute('id')", "def get_id(self):\n return self._hostID", "def getPortletId(self):\n random_id = md5.new()\n random_id.update(str(time.time()))\n return 'portletbanners-%s' % random_id.he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A friendly name for the portal.
def portal_name(self) -> Optional[str]: return pulumi.get(self, "portal_name")
[ "def get_name():\n return _(strings.bot_title)", "def title(self):\n msg = __(u\"Evenementiels portlet\")\n return self.portlet_title or msg", "def full_name(self):\n return '{} ({})'.format(\n self.name,\n self.location,\n )", "def title(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sa phase error. DIN/ISO Sa.
def Sa(self): return Sa(self.phase)
[ "def try_phase():\n global init_simp, smp_trace,aigs\n n = n_phases()\n print 'Phases = %d'%n\n## if ((n == 1) or (n_ands() > 45000) or init_simp == 0):\n if ((n == 1) or (n_ands() > 60000)):\n return False\n## init_simp = 0\n res = a_trim()\n## print hist\n print 'Trying phase abs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standard deviation of phase error.
def std(self): return std(self.phase)
[ "def stddev(self):\n m = self.mean()\n n = np.sum(self.counts)\n dx = self.axis().center - m \n return np.sqrt(np.sum(self.counts*dx**2)/n)", "def calculate_stdev(self):\n\n return np.array(self.data).std()", "def std(signal):\n return np.std(signal)", "def std(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Diameter of the data in x.
def diameter_x(self): return self.x[-1] - self.x[0]
[ "def diameter(self):\n\t\treturn self.r * 2", "def diameter(self):\n self._assertarrays_loaded()\n return self._check_nonempty_property('_diameter')", "def density(self) -> float:\n pass", "def get_width(self):\n\t\treturn self.x[1] - self.x[0]", "def density(self):\n return self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Diameter of the data in y.
def diameter_y(self): return self.y[-1] - self.x[0]
[ "def diameter(self):\n\t\treturn self.r * 2", "def diameter(self):\n self._assertarrays_loaded()\n return self._check_nonempty_property('_diameter')", "def get_pixel_size_y(self):\n y_pixel_size = 0.000075\n return y_pixel_size * 1000", "def density(self) -> float:\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Phase is the Z ("height" or "opd") data.
def phase(self): return self.data
[ "def phase_data(self):\n self.instrument.write(\"PHAS\") # Set display to phase format\n # time.sleep(5)\n try:\n start_time = time.perf_counter_ns()\n data_degree = self.instrument.query(\"OUTPFORM\") # Output format is a list of form (degrees, 0)\n end_time ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the CreateDatabase action. This should create all the tables that should exist in the database.
def test_create_database(self): # Setup the tables CreateDatabase.run(app=self.app) engine = create_engine(TestManagePy.postgresql_url) connection = engine.connect() for model in [User, Library, Permissions]: exists = engine.dialect.has_table(connection, model.__tab...
[ "def test_create_tables(self):\n self._db.create_tables()\n tables = json.loads(self._db.get_database_info())\n expected_tables = db_connection.Database.get_columns().keys()\n for table in expected_tables:\n assert table in tables.keys()", "def create_tables():\n with db:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the DestroyDatabase action. This should clear all the tables that were created in the database.
def test_destroy_database(self): # Setup the tables engine = create_engine(TestManagePy.postgresql_url) connection = engine.connect() Base.metadata.create_all(bind=self.app.db.engine) for model in [User, Library, Permissions]: exists = engine.dialect.has_table(conne...
[ "def tearDown(self):\n with database() as db:\n db.query('DROP TABLE test_data')", "def _reset_database(self):\r\n self._delete_tables()\r\n self._create_tables()", "def tearDown(self):\n\n\t\tdb.session.remove()\n\t\tdb.drop_all()", "def clearDatabase():\n Album.objects.all...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the DeleteStaleUsers action that propogates the deletion of users from the API database to that of the microservice.
def test_delete_stale_users(self): with self.app.session_scope() as session: # We do not add user 1 to the API database session.execute('create table users (id integer, random integer);') session.execute('insert into users (id, random) values (2, 7);') session.co...
[ "def test_delete_stale_users(self):\n\n with self.app.session_scope() as session:\n # We do not add user 1 to the API database\n session.execute('create table users (id integer, random integer);')\n session.execute('insert into users (id, random) values (2, 7);')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Debugging utility. Writes processed cut IDs to a file. Expects ``return_cuts=True`` to be passed to the Dataset class.
def cut_id_dumper(dataloader, path: Path): if not dataloader.dataset.return_cuts: return dataloader # do nothing, "return_cuts=True" was not set with path.open('w') as f: for batch in dataloader: for cut in batch['supervisions']['cut']: print(cut.id, file=f) ...
[ "def coverage_wrapper(dset_id, filtered_reads, utrfile_path):\n\n ## XXX This is a sin: I'm introducing a once-in-a-lifetime piece of code\n #here. It outputs the coverage \n\n # Rename path to 'covered_...'\n (dirpath, basename) = os.path.split(filtered_reads)\n out_path = os.path.join(dirpath, 'cov...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fast version of `ntp_bottle_to_cast`.
def _ntp_bottle_to_cast(sB, tB, pB, S, T, P, k, K, tol_p, eos, ppc_fn): if K - k > 1: # Trim data to valid range and build interpolant P = P[k:K] Sppc = ppc_fn(P, S[k:K]) Tppc = ppc_fn(P, T[k:K]) args = (sB, tB, pB, Sppc, Tppc, P, eos) # Search for a sign-change, ...
[ "def nodeCast(disableScriptJobCallbacks=bool, force=bool, disconnectUnmatchedAttrs=bool, copyDynamicAttrs=bool, swapValues=bool, swapNames=bool, disableAPICallbacks=bool):\n pass", "def _type_cast(self, item: str): # noqa: ANN\n for cast in self._casts:\n item = cast.type_cast(item)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate a neutral trajectory through a sequence of casts. Given a sequence of casts with hydrographic properties `(S, T, P)`, calculate a neutral trajectory starting from the first cast at pressure `p0`, or starting from a bottle prior to the first cast with hydrographic properties `(s0, t0, p0)`.
def neutral_trajectory( S, T, P, p0, vert_dim=-1, tol_p=1e-4, interp="linear", eos="gsw", grav=None, rho_c=None, ): eos = make_eos(eos, grav, rho_c) ppc_fn = make_pp(interp, kind="1", out="coeffs", nans=False) S, T, P = _process_casts(S, T, P, vert_dim) nc, nk =...
[ "def _generate_sample_path_no_absorption(self, \n times):\n if self.mu<=-1:\n print(\"Attn: mu must be greater than -1. It is currently %f.\"%self.mu)\n return\n else:\n if not self.conditional:\n x=self.startPo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get details with partner sales
def get_partner_details(self, start_date, end_date, partner, is_lpg): data_list = [] domain = [ ('order_id.date_order', '>=', start_date), ('order_id.date_order', '<=', end_date), ('order_id.partner_id', '=', partner.id), ] if is_lpg: domai...
[ "def display_sale_detail(self):\n sale = self.find_brokered_sale_by_id(self.lhs)\n self.msg(sale.display(self.caller))", "def get_sales():\n all_sales = Sales.get_all_sales()\n if all_sales:\n return all_sales, 200\n else:\n raise InvalidUsage('No sales added yet', status_code...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load WAV file and return its properties Load WAV file specified by the path (string), and return a list of 1/more numpy array(s) containing the data samples for each channel, the sampling frequency, the number of channels, and the number of samples per channel
def read_wav_file(path): # Parse the input file's extension extension = os.path.splitext(path)[1] # Load the WAV file and set the output parameters try: if extension.lower() == '.wav': [fs, x] = wavfile.read(path) num_samples = len(x) try: ...
[ "def read_wave(path):\n with contextlib.closing(wave.open(path, \"rb\")) as wf:\n num_channels = wf.getnchannels()\n assert num_channels == 1\n sample_width = wf.getsampwidth()\n assert sample_width == 2\n sample_rate = wf.getframerate()\n assert sample_rate in (8000, 16...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform linear interpolation Perform the linear interpolation between two equally space values (y1, y2)
def linear_interpolation(y1, y2, weight): # Return linearly interpolated data value return y1*(1.0-weight)+y2*weight
[ "def interpolate(x, y, x1):\r\n\tfor item in x:\r\n\t\titem = float(item)\r\n\tfor item in y:\r\n\t\titem = float(item)\r\n\tx1 = float(x1)\r\n\t \r\n\ty1 = y[0] + (x1 - x[0]) / (x[1] - x[0]) * (y[1] - y[0])\r\n\t\r\n\treturn y1", "def interpolate2(x, y, z, x1, y1):\r\n\ty11 = interpolate(x, z[0], x1)\r\n\ty22 =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform parabolic interpolation Perform the parabolic interpolation between three equally space values and
def parabolic_interpolation(alpha, beta, gamma, x): # Perform initial check if x == 0: return beta else: offset = alpha if (beta < offset): offset = beta if (gamma < offset): offset = gamma # Apply the offset offset = math.fabs(offse...
[ "def parab_interpolation(data, xi, yi):\n \n # get the maximum and the 4 neighbouring points \n z1, z2, z3 = data[yi-1:yi+2,xi] #@UnusedVariable\n z4, z2, z5 = data[yi,xi-1:xi+2]\n \n # parabolic interpolation at point (xi, yi)\n x0 = (z5-z4)/(4*z2 - 2*z4 - 2*z5)\n y0 = (z3-z1)/(4*z2 - 2*z1 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send msg size (with default size length) | \/ ack | \/ send msg
def send(self, msg): # send length send_only_msg(len(pickle.dumps(msg))) # wait for confirmation if (recv_only_msg() == 'ack'): # send msg send_only_msg(msg) # if didn't recv ack for some reason else: raise ConnectionRefusedError
[ "def send_message(conn, msg):\n\n print(\"sending:\", msg)\n\n data = msg.SerializeToString()\n size = encode_varint(len(data))\n conn.sendall(size + data)", "def send_by_size(self, s):\n self.sendall(str(len(s)).zfill(HEADER_SIZE) + s)", "def mqtt_msg(self, msg_size):\r\n if msg_size ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether a dtype is real.
def is_real_dtype(dtype: DType) -> bool: return snp.dtype(dtype).kind != "c"
[ "def is_real(dtype: DTypeLike) -> bool:\n dtype = _normalize_type(dtype)\n return numpy.issubdtype(dtype, numpy.floating)", "def isreal(self):\n return np.all(np.isreal(self.data))\n # return np.isrealobj(self._data)", "def isdouble(dtype):\n return dtype in ('float64', 'complex128')", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether a dtype is complex.
def is_complex_dtype(dtype: DType) -> bool: return snp.dtype(dtype).kind == "c"
[ "def is_complex(dtype: DTypeLike) -> bool:\n dtype = _normalize_type(dtype)\n return numpy.issubdtype(dtype, numpy.complexfloating)", "def _is_complex(data):\n return (NUMPY and numpy.iscomplex(data).any()) or (isinstance(data, complex))", "def complex_for(dtype: DTypeLike) -> \"numpy.dtype[Any]\":\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct the corresponding complex dtype for a given real dtype. Construct the corresponding complex dtype for a given real dtype, e.g. the complex dtype corresponding to `np.float32` is `np.complex64`.
def complex_dtype(dtype: DType) -> DType: return (snp.zeros(1, dtype) + 1j).dtype
[ "def complex_for(dtype: DTypeLike) -> \"numpy.dtype[Any]\":\n dtype = _normalize_type(dtype)\n if dtype == numpy.float32:\n return numpy.dtype(\"complex64\")\n if dtype == numpy.float64:\n return numpy.dtype(\"complex128\")\n raise ValueError(f\"{dtype} does not have a corresponding comple...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List comprehensions in Python 3 when handled as a closure. See if we can combine code.
def listcomp_closure3(node): p = self.prec self.prec = 27 code_obj = node[1].attr assert iscode(code_obj) code = Code(code_obj, self.scanner, self.currentclass) ast = self.build_ast(code._tokens, code._customize) self.customize(code._customize) # skip ov...
[ "def test_list_comprehension_func():\n source = FUNCTION_TEMPLATE.format('[self for i in range(10)]')\n win = compile_source(source, 'Main', namespace={'RUN_CHECK': IS_PY3})()\n assert win.call()", "def test_list_comprehension_operator():\n source = OPERATOR_TEMPLATE.format('[self for i in range(10)]'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle "classdef" nonterminal for 3.0 >= version 3.0 <= 3.5
def n_classdef3(node): assert 3.0 <= self.version <= 3.5 # class definition ('class X(A,B,C):') cclass = self.currentclass # Pick out various needed bits of information # * class_name - the name of the class # * subclass_info - the parameters to the class e.g. ...
[ "def CLASSDEF(self, node):\r\n for deco in node.decorator_list:\r\n self.handleNode(deco, node)\r\n for baseNode in node.bases:\r\n self.handleNode(baseNode, node)\r\n if not PY2:\r\n for keywordNode in node.keywords:\r\n self.handleNode(keywordNo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes blanks and newline characters in input_str and returns a string with those removed.
def remove_blanks(input_str): temp_str = input_str.replace(' ', '') temp_str = temp_str.replace('\n', '') return temp_str
[ "def remove_whitespace(input):\n return input.strip(\"\\0\\r\\n \")", "def strip_input(input):\n if input is None:\n return \"\"\n elif isinstance(input, basestring):\n return input.strip()\n else:\n return input", "def _remove_line_breaks(str):\n str2 = str\n str2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if input string is a DNA sequence.
def is_DNA(input_DNA): # Uses remove_blanks() method to remove any blanks and newline characters # in the input_DNA string DNA = remove_blanks(input_DNA) condition = True DNA_bases = 'AGTCagtc' # If one character in the input string DNA is not ...
[ "def is_valid_sequence(dna):\n\n valid = True\n for char in dna:\n if char not in 'ATCG':\n valid = False\n break\n\n return valid", "def seq_validator(sequence):\n\n # checks for ascii characters that should not appear in a fasta sequence\n seq_val = re.compile(\"[^ATK...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns the input DNA sequence into all caps.
def DNA_to_caps(DNA): # First uses is_DNA() method to check if input sequence is DNA; # this prevents proceeding on to use other methods (and wasting time # & resources) when the input sequence is not a DNA sequence. if RNA_pol.is_DNA(DNA): return DNA.upper()
[ "def RNA_to_caps(RNA):\n \n # First uses is_RNA() method to check if input sequence is RNA;\n # this prevents proceeding on to use other methods (and wasting time\n # & resources) when the input sequence is not an RNA sequence.\n if Ribosome.is_RNA(RNA):\n return RNA....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if input string is an RNA sequence.
def is_RNA(input_RNA): # Uses remove_blanks() method to remove any blanks and newline characters # in the input_RNA string RNA = remove_blanks(input_RNA) condition = True RNA_bases = 'AGUCaguc' # If one character in the input string RNA is not ...
[ "def seq_validator(sequence):\n\n # checks for ascii characters that should not appear in a fasta sequence\n seq_val = re.compile(\"[^ATKMBVCNSWD-GUYRHatkbbvcnswdguyrh]\")\n\n # if any illegal characters found return False\n if seq_val.search(sequence):\n return False\n\n return True", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns the input RNA sequence into all caps.
def RNA_to_caps(RNA): # First uses is_RNA() method to check if input sequence is RNA; # this prevents proceeding on to use other methods (and wasting time # & resources) when the input sequence is not an RNA sequence. if Ribosome.is_RNA(RNA): return RNA.upper() ...
[ "def DNA_to_caps(DNA):\n \n # First uses is_DNA() method to check if input sequence is DNA;\n # this prevents proceeding on to use other methods (and wasting time\n # & resources) when the input sequence is not a DNA sequence.\n if RNA_pol.is_DNA(DNA):\n return DNA.up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates an input RNA sequence to the corresponding protein.
def translate(RNA_seq): RNA = remove_blanks(RNA_seq) # Uses find_start_codon() method to find codon from which # translation will start counter = Ribosome.find_start_codon(RNA) codon = '' protein = '' # Assigns triplets of RNA sequence ...
[ "def translate_rna_to_protein(rna_seq):\n\n\t# dictionary containing each codon (3 base sequences) translation\n\tcodon_dict = {\"UUU\":\"F\",\"UUC\":\"F\",\"UUA\":\"L\",\"UUG\":\"L\",\n\t\t\t\t\t\"UCU\":\"S\",\"UCC\":\"S\",\"UCA\":\"S\",\"UCG\":\"S\",\n\t\t\t\t\t\"UAU\":\"Y\",\"UAC\":\"Y\",\"UAA\":\"Stop\",\"UAG\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display quantites of fasteners.
def quantites(total, count_imperial, count_metric, state="(Current state)"): print("{}".format(state)) print("Total number of fasteners: {}".format(total)) print(" - imperial: ............. {}".format(count_imperial)) print(" - metric : ............. {}\n".format(count_metric))
[ "def display_fps(self):\n caption = \"Score - {}, clicks - {}\".format(self.rezult_points, self.click_count)\n pygame.display.set_caption(caption)", "def visualize_spike_train_fast(trains):\r\n# -----------------------------------------------------------------------------\r\n length = len(trains)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a model is registered with auditlog.
def contains(self, model: ModelBase) -> bool: return model in self._registry
[ "def model_exists(self, tag):\n return tag in self._models", "def has_access(self, model):\n return True", "def can_log(self):\n return # boolean", "def is_model(self, model):\n if model is None:\n self.dump()\n raise Exception(\"Model is None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unregister a model with auditlog. This will not affect the database.
def unregister(self, model: ModelBase) -> None: try: del self._registry[model] except KeyError: pass else: self._disconnect_signals(model)
[ "def unregister_model(self, model):\n if model not in self._model_registry:\n raise NotRegistered('The model %s is not registered' % model)\n\n del self._model_registry[model]", "def unload_model(self, model_name):\n raise_error(\"Not implemented yet\")", "def unload_model(model_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect signals for the model.
def _connect_signals(self, model): for signal in self._signals: receiver = self._signals[signal] signal.connect( receiver, sender=model, dispatch_uid=self._dispatch_uid(signal, model) )
[ "def _connect_signals(self):\n # ui signals\n self._view.signal_browse_noice_app.connect(self.browse_noice_app)\n self._view.signal_add_aov.connect(self.add_aov)\n self._view.signal_window_close.connect(self.window_close)\n self._view.signal_remove_aov[list].connect(self.remove_ao...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disconnect signals for the model.
def _disconnect_signals(self, model): for signal, receiver in self._signals.items(): signal.disconnect( sender=model, dispatch_uid=self._dispatch_uid(signal, model) )
[ "def disconnectModelFromSignal(model: Any, connectedFunction: Callable) -> None:\n\n for fieldValue in recursive_field_iter(model):\n if isinstance(fieldValue, Signal):\n fieldValue.disconnect(connectedFunction)", "def disconnect_signal(self):\r\n if self.properties_signal is not None:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the messages output by the Paver task.
def task_messages(self): return tasks.environment.messages
[ "def get_outputs(self):\n output = ''\n if self.out:\n output = output + \"\\nOutput:\\n{}\".format(self.out)\n if self.err:\n output = output + \"\\nSTDERR:\\n{}\".format(self.err)\n return output", "def get_messages(self):\n\n running_job_messages = None\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current platform's root directory.
def platform_root(self): return os.getcwd()
[ "def sysroot_dir(self):\n\n return self._sysroot.sysroot_dir", "def get_mo_root_dir():\n return os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(os.path.realpath(__file__))), os.pardir))", "def get_root_path(self):\n mock_cmd = self._mock_cmd('--print-root-path')\n output = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to simulate an error when executing "npm install"
def fail_on_npm_install(): return 1
[ "def _install_npm_command(cmd):\n with settings(warn_only=True):\n version = npm_commands[cmd]['version']\n out = local('npm install -g {0}@{1}'.format(cmd, version), capture=True)\n if out.return_code != 0:\n print 'Using sudo'\n local('sudo npm install -g {0}@{1}'.for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the Tank, only if Tank already in form, if not form tank uses 'movePirate' to move Tank
def moveTank(self, dest): old_dest = dest dest = nearestPassableLoc(dest, caller_loc=self.findBaseLoc(), exclude_locations=[p.location for p in self.pirates]) path = createPath(self.baseLoc, dest, alternating=False, pirate=self.fi...
[ "def move(self):\n # spread pheromone\n self.spread()\n\n return super(DepositPheromones, self).move()", "def move(self):\r\n if not self.waitTurn(): # if no traffic from the opposite direction\r\n\t gui.Label.repaint(self.getCell(0))\r\n self.setWaiting(False) \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
export Tank class instance data to use in next turn
def exportData(self): global tankData resumeData = [self.baseLoc, self.tankFormations, self.last_path] # resumeData.append([p.id for p in self.pirates]) tankData[self.identifier] = resumeData
[ "def __init__(self):\n\n self.deck = Deck()\n self.keep_playing = True\n self.total_points = 300", "def __init__(self):\n self.history = []\n self.stochastic = \"random\" in inspect.getsource(self.__class__)\n self.tournament_length = -1\n if self.name == \"Player\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate positions to form Tank in current game radius (base is (0,0))
def calculateFormation(self): # Path-faced tank formation calculation: # ----------------------------------- starting_loc = (0, 0) direction_forms = [] for direction in xrange(4): # n, w, s, e goodloc = [] ...
[ "def domain_tank(self):\n \n assert (self.ntheta > 0), \"ntheta must be >0 to use the tank shape\" \n\n #Create the 'rectangle part' of the tank\n\n for j in range(0,self.Nptsy):\n for i in range(0,self.Nptsx):\n #nodes\n self.nodes[i+j*self.Nptsx,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Look up videos for youtubegeo.
def geo(): # ensure parameters are present if not request.args.get("location"): raise RuntimeError("missing youtube geodata") query = { 'q' : request.args.get('q'), 'location' : request.args.get('location'), 'locationRadius' : request.args.get('locationRadius'), 'maxResu...
[ "def search_youtube(text_to_search):\n # query = urllib.parse.quote(text_to_search)\n # url = \"https://www.youtube.com/results?search_query=\" + query\n videosSearch = VideosSearch(text_to_search, limit=2)\n results = videosSearch.result()\n results = results['result']\n\n #\n # try:\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show generate passwords window
def on_generate_button(self): self.password_generator.show()
[ "def gen_pass(self):\n\n length = int(self.mainwindow_gui.length_slider.value())\n password = \"\"\n\n if (self.mainwindow_gui.include_numbers.isChecked()):\n password = functions.generate_password(length=length, include_numbers=True)\n else:\n password = functions....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function which calculates execution time of arbitrary number of functions and rank them
def fun_exec_time(*func): times = dict() for f in func: # execute function and calculation of execution time with contextlib.redirect_stdout(io.StringIO()) as f_: start_time = time.time() f() times[f.__name__] = time.time() - start_time # write time in dict ...
[ "def timing_analysis(func, start, stop, inc, runs):\n\n for n in range(start, stop, inc): # for every input size n\n acc = 0.0 # initialize accumulator\n\n for i in range(runs): # repeat runs times:\n acc += timing(func, n) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the clock in/out entries for the 91
def test_case_2(self): ca = clock_adjustment.ClockInOutAdjustment() params = { # If time is not provided, default values are used instead. # One day instead of two is also accepted. "date" : [["06/6/2019", "02:25 AM"], ["06/26/2019", "11:59 PM"]], "employ...
[ "def _draw_digital_clock(self):\n self._draw_time_scale()\n self._draw_time()", "def clock_corrections(self,t):\n # TODO this and derived methods should be changed to accept a TOA\n # table in addition to Time objects. This will allow access to extra\n # TOA metadata which may ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates random date in the range '01/01/1981' '01/01/2100'
def random_date(self): stime = time.mktime(time.strptime('01/01/1981', '%m/%d/%Y')) etime = time.mktime(time.strptime('01/01/2100', '%m/%d/%Y')) ptime = stime + random.random() * (etime - stime) return time.strftime('%m/%d/%Y', time.localtime(ptime))
[ "def gen_date():\r\n return random.randint(DAY1, TODAY)", "def random_date_generator(start_date):\n\n\t\trange_in_days = current_date + np.timedelta64(-T, \"D\") - np.datetime64(start_date)\n\t\tdays_to_add = np.arange(1, range_in_days-1)\n\t\trandom_date = np.datetime64(start_date) + np.random.choice(days_to_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the value of mu_c with the Theorem 3.1.
def mu_c(self, d_p, d_c): return self.mu_p * (1 - self.phi(d_p)) / self.phi(d_c)
[ "def compute_mu_covar(feature_iterator):\n features = []\n for hi in feature_iterator: # hi is numpy with shape (512, )\n features.append(hi.reshape(1, -1))\n\n h = np.concatenate(features, axis = 0) # (set_size, 512)\n print(\"h.shape:\", h.shape)\n mu = np.mean(h, axis = 0) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot the average gain for different values of a. It should be a strict convex where the global minimum is at a = r, And the average gain should be non positive.
def graph(r, position): option = EuropeanOption(S_0, T, r, sigma, K_p, K_c) axes = fig.add_subplot(position) A = np.linspace(r - 0.1, r + 0.1, 15) E = [] V_minus = [] V_positive = [] for a in A: val = option.average_gain(a) E.append(val[0]) V_minus.append(val[0] - 1....
[ "def plot_alpha(ax, mu, se, sig_level=0.05, color='red'):\n\n right = alpha(mean=mu, se=se, sig_level=sig_level)\n ax.axvline(right, c=color, linestyle='--', alpha=0.5)", "def avg_Ao(self):\n ...", "def gain(self, g):\n return self.normalize(0, 1, scale=g)", "def get_average_gain(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create connection to OpenStack.
def create_connection(self): try: if self.USE_APPLICATION_CREDENTIALS: self.LOG.info("Using Application Credentials for OpenStack Connection") conn = connection.Connection( auth_url=self.AUTH_URL, application_credential_id=self....
[ "def getOpenstackConnection():\n\n connection = openstack.connect(\n region = parser.get('openstack', 'region'), \n auth = {\n 'auth_url': parser.get('openstack', 'auth_url'),\n 'domain_name': parser.get('openstack', 'domain_name'), \n 'password': parser.get('openstack', '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }