query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Sends the process an "EXECUTE" task message to run the task named 'task_name'.
def execute_task(self, task_name): self.busy = True self.pipe_start.send(("EXECUTE",task_name))
[ "def execute(self, task_name, **kwargs):\r\n return self._find_and_execute_task(task_name, **kwargs)", "def calltask(self, name, **vars):\n if name in self._tasks:\n for entry in self._tasks[name]:\n entry.execute(vars)\n else:\n raise Error(\"No such task...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the 'busy' flag in order to mark this task executor as busy (its associated process is performing a task)
def set_task_finished(self): self.busy = False
[ "def set_busy(busy=True):", "def set_busy(busy):\n queue.put((index, \"busy\", 1 if busy else 0))", "def _resume_busy(self):\r\n if self.state == STATE_BUSY:\r\n self.update_state(STATE_PAUSE)\r\n self.resume()", "def _pause_busy(self):\r\n if self.state != STATE_PAU...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a finalization message (forces the associated process to break the loop and end)
def finalize(self): self.busy = False self.pipe_start.send(("FINISH",None)) self.process.join() if self.process.is_alive(): self.process.terminate()
[ "def close():\n print (\"Sending TERMINATION_MESSAGE to output stream ...\")\n remote_log('Waiting for TASK_GEN_FINISH')\n output.send_to_output_stream(global_vars.TERMINATION_MESSAGE)\n global_vars.exit_gracefully()", "def end_run_loop(self):\n\t\tself.done = True", "def on_process_exit(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if this task runner has received a message from its associated process.
def has_an_incomming_message(self): return self.pipe_start.poll(1)
[ "def is_waiting_for_message(self):\r\n return self.waiting_for_message", "def check_command(self):\n return self.process is not None and self.process.poll() is None", "def is_running(self):\n if self._process:\n return self._process.poll() is None\n else:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Like in the SerialScheduler, this function tries to run all the tasks, checking their dependencies. In this case some processes will be spawned so that they can share the work of executing the tasks. This run function acts as the real scheduler, telling the 'task executor' objects which task to run. This kind of dynami...
def run(self): self.function_exec('scheduling_started', {"number_of_tasks":len(self.not_completed)}) # Create processes available_workers = self.number_of_processes task_runners = [] for i in range(available_workers): process_name = "TaskExecutor"+str(i) ...
[ "def _run_tasks(self, task_list, interactive):\n if not is_sequence(task_list):\n task_list = [task_list]\n\n verified_task_list = self._verified_tasks(task_list)\n debug(\"task_list: {tasks}\".format(tasks=task_list))\n debug(\"verified_task_list: {tasks}\".format(tasks=verif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a CreateGroupMessage from a protobuf As a requirement of all objects which inherit from Serializable, this method transforms a protobuf object into an instance of this class.
def _proto2object( proto: CreateGroupMessage_PB, ) -> "CreateGroupMessage": return CreateGroupMessage( msg_id=_deserialize(blob=proto.msg_id), address=_deserialize(blob=proto.address), content=json.loads(proto.content), reply_to=_deserialize(blob=prot...
[ "def _proto2object(\n proto: DeleteGroupMessage_PB,\n ) -> \"DeleteGroupMessage\":\n\n return DeleteGroupMessage(\n msg_id=_deserialize(blob=proto.msg_id),\n address=_deserialize(blob=proto.address),\n content=json.loads(proto.content),\n reply_to=_deseri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a GetGroupMessage from a protobuf As a requirement of all objects which inherit from Serializable, this method transforms a protobuf object into an instance of this class.
def _proto2object( proto: GetGroupMessage_PB, ) -> "GetGroupMessage": return GetGroupMessage( msg_id=_deserialize(blob=proto.msg_id), address=_deserialize(blob=proto.address), content=json.loads(proto.content), reply_to=_deserialize(blob=proto.reply_t...
[ "def _proto2object(\n proto: CreateGroupMessage_PB,\n ) -> \"CreateGroupMessage\":\n\n return CreateGroupMessage(\n msg_id=_deserialize(blob=proto.msg_id),\n address=_deserialize(blob=proto.address),\n content=json.loads(proto.content),\n reply_to=_deseri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a GetGroupsMessage from a protobuf As a requirement of all objects which inherit from Serializable, this method transforms a protobuf object into an instance of this class.
def _proto2object( proto: GetGroupsMessage_PB, ) -> "GetGroupsMessage": return GetGroupsMessage( msg_id=_deserialize(blob=proto.msg_id), address=_deserialize(blob=proto.address), content=json.loads(proto.content), reply_to=_deserialize(blob=proto.repl...
[ "def _proto2object(\n proto: GetGroupMessage_PB,\n ) -> \"GetGroupMessage\":\n\n return GetGroupMessage(\n msg_id=_deserialize(blob=proto.msg_id),\n address=_deserialize(blob=proto.address),\n content=json.loads(proto.content),\n reply_to=_deserialize(blo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a UpdateGroupMessage from a protobuf As a requirement of all objects which inherit from Serializable, this method transforms a protobuf object into an instance of this class.
def _proto2object( proto: UpdateGroupMessage_PB, ) -> "UpdateGroupMessage": return UpdateGroupMessage( msg_id=_deserialize(blob=proto.msg_id), address=_deserialize(blob=proto.address), content=json.loads(proto.content), reply_to=_deserialize(blob=prot...
[ "def _proto2object(\n proto: CreateGroupMessage_PB,\n ) -> \"CreateGroupMessage\":\n\n return CreateGroupMessage(\n msg_id=_deserialize(blob=proto.msg_id),\n address=_deserialize(blob=proto.address),\n content=json.loads(proto.content),\n reply_to=_deseri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a DeleteGroupMessage from a protobuf As a requirement of all objects which inherit from Serializable, this method transforms a protobuf object into an instance of this class.
def _proto2object( proto: DeleteGroupMessage_PB, ) -> "DeleteGroupMessage": return DeleteGroupMessage( msg_id=_deserialize(blob=proto.msg_id), address=_deserialize(blob=proto.address), content=json.loads(proto.content), reply_to=_deserialize(blob=prot...
[ "def _proto2object(\n proto: CreateGroupMessage_PB,\n ) -> \"CreateGroupMessage\":\n\n return CreateGroupMessage(\n msg_id=_deserialize(blob=proto.msg_id),\n address=_deserialize(blob=proto.address),\n content=json.loads(proto.content),\n reply_to=_deseri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a new access token if the old one already expired access_token token used to access the TD Ameritrade site expire_time time in seconds since epoch when the token will expire
def get_access(access_token='',expire_time=0): #Get a new access token if it expires or is five minutes away from exp#iration if (expire_time==0) or (len(access_token)==0) or (time.time()-expire_time>=-300): #API needed to authorize account with refresh token auth_url = 'https://api.tdamer...
[ "def get_access_token(self):\n token = self.access_token\n expire_time = self.access_token_expire_time\n curr_time = datetime.now()\n\n if expire_time < curr_time or token is None:\n self.perform_auth()\n return self.get_access_token()\n \n return toke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the user info and preferences for subscribing to the websocket and get the token timestamp as milliseconds access token used to get information on my account
def get_user_principals(access_token): #Make request to user info and preferences to get principals for login user_url = 'https://api.tdameritrade.com/v1/userprincipals' headers = {'Authorization': 'Bearer {}'.format(access_token)} params = {'fields':'streamerSubscriptionKeys,streamerConnectionInfo'...
[ "def ws_user_data(self):\n return self.ws_request(self.ws_request(self.start_userdata_stream()['listenKey']))", "async def websocket_endpoint(\n websocket: WebSocket,\n user_id: int,\n db: Session = Depends(dependencies.get_db),\n current_user: schemas.User = Depends(dependencies.get_current_us...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get orders for the account in the specified date range on TD Ameritrade access_token token used to access the TD Ameritrade site start_date beginning time period to get orders (includes start_date in returned orders) end_date ending time period to get orders (includes end_date in returned orders)
def get_orders(access_token,start_date,end_date,status): orders_url = 'https://api.tdameritrade.com/v1/orders' headers={'Authorization': 'Bearer {}'.format(access_token)} #Parameters for the order params = {'accountId':TDAuth_Info.account_num, 'fromEnteredTime': start_date, ...
[ "def get_orders_data(self, end_date):\n self.query_es = QueryES(port=self.port, host=self.host)\n self.query_es.date_queries_builder({\"session_start_date\": {\"lt\": end_date}})\n self.query_es.query_builder(fields=self.fields, boolean_queries=self.dimensional_query())\n self.data = pd....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a specific order access_token used to login to TD Ameritrade site order_ID the ID of the order we are getting
def get_order_by_id(access_token,order_ID): orders_url = 'https://api.tdameritrade.com/v1/accounts/{}/orders/{}'.format(TDAuth_Info.account_num,order_ID) headers={'Authorization': 'Bearer {}'.format(access_token)} #Make the get request to TD Ameritrade orders_data_json = requests.get(url=orders_...
[ "def get_orders(access_token,start_date,end_date,status):\r\n\r\n orders_url = 'https://api.tdameritrade.com/v1/orders'\r\n headers={'Authorization': 'Bearer {}'.format(access_token)}\r\n #Parameters for the order\r\n params = {'accountId':TDAuth_Info.account_num,\r\n 'fromEnteredTime': sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes orders on the TD Ameritrade Site access_token token used to access the TD Ameritrade site order_ID the ID of the order to delete
def delete_order(access_token,order_ID): orders_url = 'https://api.tdameritrade.com/v1/accounts/{}/orders/{}'.format(TDAuth_Info.account_num,order_ID) headers={'Authorization': 'Bearer {}'.format(access_token)} order_status = requests.delete(url=orders_url,headers=headers) return order_status
[ "def api_delete_order(request, id):\n\n close_old_connections()\n\n # Not marking it as served if it isn't even ready yet.\n if not request.user.is_authenticated:\n return HttpResponseForbidden(\"You're not authenticated.\")\n \n # Delete the order.\n Order.objects.get(id=id).delete()\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Posts an order to the TD Ameritrade website access_token token used to access the TD Ameritrade site json_request the order request in json format Returns the response to the post request
def post_order(access_token,json_request): orders_url = 'https://api.tdameritrade.com/v1/accounts/{}/orders'.format(TDAuth_Info.account_num) #The header for placing in order needs to define the input type (json) headers = {'Authorization':'Bearer {}'.format(access_token), 'Content-Type'...
[ "def replace_order(access_token,order_ID,json_request):\r\n orders_url = 'https://api.tdameritrade.com/v1/accounts/{}/orders/{}'.format(TDAuth_Info.account_num,order_ID)\r\n\r\n #The header for placing in order needs to define the input type (json)\r\n headers = {'Authorization':'Bearer {}'.format(access_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces an order on the TD Ameritrade website access_token token used to access the TD Ameritrade site order_ID ID of the order to replace json_request the new order request in json format to replace the old one Returns the response to the replace order request
def replace_order(access_token,order_ID,json_request): orders_url = 'https://api.tdameritrade.com/v1/accounts/{}/orders/{}'.format(TDAuth_Info.account_num,order_ID) #The header for placing in order needs to define the input type (json) headers = {'Authorization':'Bearer {}'.format(access_token), ...
[ "def replace_order(self, account_id: str, order_id: str, order: dict) -> str:\n _, headers = self._put(\n path=f\"/accounts/{q(account_id)}/orders/{q(order_id)}\",\n json=order,\n expect_response_body=False,\n )\n # The order ID can be found in the Location head...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a request to the TD Ameritrade API session trading session, 'Normal', 'AM', 'PM', 'SEAMLESS' for extended hours and day hours duration 'DAY' or 'GOOD_TO_CANCEL' orderType 'MARKET' or 'LIMIT' orderLegCollection contains instruction ('BUY' or 'SELL'), symbol, assetType, quantity, etc orderStrategy 'SINGLE', 'TRIGGE...
def build_order_request(session,duration,orderType,orderLegCollection,orderStrategy,price=''): #Build order request based on parameters order_request = { 'session':session, 'duration':duration, 'orderType':orderType, 'orderLegCollection':...
[ "def create_order_request(request: dict = None, *, action: int = None, magic: int = None,\n order: int = None, symbol: str = None, volume: float = None,\n price: float = None, stoplimit: float = None, sl: float = None, tp: float = None,\n devia...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get quote/price information for a stock access_token token used to access the TD Ameritrade site ticker the stock ticker symbol
def get_quote(access_token,ticker): quote_url = 'https://api.tdameritrade.com/v1/marketdata/{}/quotes'.format(ticker) #The header for getting a quote needs to define the input type (json) headers = {'Authorization':'Bearer {}'.format(access_token), 'Content-Type':'application/json'} ...
[ "def get_multi_quotes(access_token,tickers):\r\n quote_url = 'https://api.tdameritrade.com/v1/marketdata/quotes'\r\n\r\n #The header for getting a quote needs to define the input type (json)\r\n headers = {'Authorization':'Bearer {}'.format(access_token),\r\n 'Content-Type':'application/json'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets quotes for multiple ticker symbols access_token token used to access the TD Ameritrade site
def get_multi_quotes(access_token,tickers): quote_url = 'https://api.tdameritrade.com/v1/marketdata/quotes' #The header for getting a quote needs to define the input type (json) headers = {'Authorization':'Bearer {}'.format(access_token), 'Content-Type':'application/json'} #Pass ...
[ "def get_quote(access_token,ticker):\r\n quote_url = 'https://api.tdameritrade.com/v1/marketdata/{}/quotes'.format(ticker)\r\n\r\n #The header for getting a quote needs to define the input type (json)\r\n headers = {'Authorization':'Bearer {}'.format(access_token),\r\n 'Content-Type':'applica...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get price history of a stock looking back from today access_token token used to access the TD Ameritrade site ticker the stock ticker symbol periodType day, month, year, or ytd (default day) period the number of periods to show (default 10 days, 1 month, 1 year, 1 ytd) frequencyType the frequency of data to return; min...
def get_price_history_lookback(access_token,ticker,periodType,period,frequencyType,frequency): price_url = 'https://api.tdameritrade.com/v1/marketdata/{}/pricehistory'.format(ticker) #The header for getting a quote needs to define the input type (json) headers = {'Authorization':'Bearer {}'.forma...
[ "def get_historical_data(ticker):\n return Ticker.get_historical_data(ticker)", "def get_data(symbol_id='BTC', period_id='1DAY', request_limit=1000, tdelta=30):\n now = datetime.utcnow()\n month = timedelta(days=tdelta)\n past_month = (now - month).isoformat()\n\n parameters = {'symbol_id': symbol_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the prev link for the node.
def setPrev(self, prev): self.prev = prev
[ "def set_prev(self, new_prev):\n self.prev_node = new_prev\n if new_prev:\n new_prev.next_node = self", "def prev(self, prev):\n\n self._prev = prev", "def go_prev(self):\n # update current as the previous node\n self.current = self.current.prev_node", "def setPre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fills the list with information from a File, Assumes new line seperated.
def populate(self, fileName): #assuming a newline seperated with open(fileName, 'r') as inFile: for line in inFile: self.append(line.strip())#strip the \n
[ "def fill_list_file(list, file):\n # Local Variables\n # data = data from the file\n \n data = open(file)\n for line in data:\n for word in line.split():\n list.insert(word)", "def populate_list(self, file):\n with open(file, 'r') as test_file:\n test_list = test...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open and read the cache file if it exists
def __read_cache_file_if_exists(self) -> None: if os.path.exists(self.__cache_file): self.__config.open_file(self.__cache_file, "r", self.__process_cache)
[ "def _read_cache(self):\n\n if os.path.isfile(self._filepath()):\n # Read the file in using Pickle\n file_obj = open(self._filepath(), 'rb')\n data = pickle.load(file_obj)\n # print(data)\n # self._read_data_tuple(data)\n file_obj.close()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a `node` returns its target typename. For "call_method" node, return node.target which is the name of that method being called. This could potential lead to conflict but should be okay because normally it's on a tensor. For "call_function" node, return typename of node.target. For "call_module" node, return typen...
def get_node_target(submodules: Mapping[str, torch.nn.Module], node: pippy.fx.Node) -> str: assert node.op in CALLABLE_NODE_OPS, ( "Expect op types of " + ", ".join(CALLABLE_NODE_OPS) + f", but found {node.op}" ) if node.op == "call_module": assert isinstance(node.target, str) subm...
[ "def node_type(ast_node):\n if ast_node.__class__.__name__ == 'FunctionDef':\n return 'function'\n elif ast_node.__class__.__name__ == 'ClassDef':\n return 'class'\n elif ast_node.__class__.__name__ == 'Module':\n return 'file'\n elif ast_node.__class__.__name__ == 'Return':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the node output produces a Tensor or not.
def is_node_output_tensor(node: pippy.fx.Node) -> bool: type_ = node.meta.get("type", None) return type_ is not None and issubclass(type_, torch.Tensor)
[ "def is_tensor(self, x):\n\t\treturn isinstance(x, AbstractTensor)", "def _is_tensor(t):\n return isinstance(t, (tf.Tensor, tf.SparseTensor, tf.Variable))", "def _is_tensor(x: Any) -> bool:\n if has_tensorflow and isinstance(x, _TfTensor):\n return True\n if has_pytorch and isinstance(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace the graph of the given GraphModule with one that contains the same nodes as the original, but in topologically sorted order. This is used by the merge_matmul transformation below, which disturbs the topologically sorted order of its input GraphModule, so that this order is restored before further transformation...
def legalize_graph(gm: pippy.fx.GraphModule) -> pippy.fx.GraphModule: indeg = {node: 0 for node in gm.graph.nodes} new_graph = pippy.fx.Graph() # Track how many unfulfilled dependencies each node has for node in gm.graph.nodes: for user in node.users: indeg[user] += 1 queue: coll...
[ "def reorder_nodes(graph, mapping):\n return nx.relabel_nodes(\n graph, mapping={u: v for v, u in mapping.items()}, copy=True\n )", "def _reset_topological_order(self):\n self._topological_order = self._input_nodes[:]\n self.sorted = False", "def ReorderGraphMinOrder(dag):\n\n if not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the progress trait from the iteration.
def _setProgress(self): self.progress = (self.iteration, self.iterationCount)
[ "def set_progress(self, progress: float):", "def progress(self, progress):\n self._progress = progress", "def progress(self, progress):\n\n self._progress = progress", "def set_progress_step(self, progress_step: float):\n pass", "def _set_progress(self, value: float) -> None:\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disable any regions that can't be run. Currently only looks for VectorFileEffectors whose outputFile parameter is equal to 'No output file specified'.
def _disableRegions(self): effectors = [e for e in _getElements(self.network) if _isEffector(e)] for e in effectors: if e.getParameter('outputFile') == 'No outputFile specified': _disable(self.network, e.getName())
[ "def disable_vae_slicing(self):\n self.vae.disable_slicing()", "def test_disable_alot(self):\r\n self.linter.set_option('reports', False)\r\n self.linter.set_option('disable', 'R,C,W')\r\n checker_names = [c.name for c in self.linter.prepare_checkers()]\r\n for cname in ('desig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start running the network, and start the mainloop if necessary. numIterations Number of iterations to run for (optional). target Run until this condition is met (used by the Vision Framework). This is distinct from the userspecified target in the GUI, which simply tells the network when to pause. tier Tier being traine...
def start(self, numIterations=0, target=None, tier=0, stop=False, callback=None): #title() self._registerCallbacks() self.iterationCount = numIterations self.iteration = 0 self.stopTarget = target self.tier = tier self.pauseAtPhaseSetup = False if callback: callback() ...
[ "def trainNetwork(self):\n global nd, nt\n \n if (nd.trainingData is None):\n sys.stderr.write(\" ERROR: Must load training data!\")\n return\n \n nt = network_trainer.NetworkTrainer(nd)\n \n if (nd.holdoutTechnique == \"holdout\"):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Seek to the specified iteration.
def _seek(self, iteration): # Validate it if iteration < 1: iteration = 1 # Seek to one iteration before the specified iteration, then run the # network for one iteration, so the inspectors will show the right data self.iteration = iteration - 1 self.experiment.position.iter = iteration ...
[ "def rewind(self, i):\n self.goto(self.cur_index-i)", "def iteration(self, iteration):\n self._iteration = iteration", "def seek(self, position):\n if position < 0 or position >= self.tree_sequence.sequence_length:\n raise ValueError(\"Position out of bounds\")\n # This sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called automatically by Traits when the iteration updates. Update the progress bar and check the conditions to see whether to stop or pause.
def _iteration_changed(self): if self.showProgressBar: try: self._setProgress() except: # may fail when switching from training to inference from dbgp.client import brk; brk(port=9011) pass
[ "def updateProgressBar(self):\n while not self.abortProgressBar:\n time.sleep(0.05)\n cur = self.progressTracker\n if cur == None or cur.startTime == None:\n continue\n remaining = self.getEstimatedTime(cur)-(datetime.now()-cur.startTime)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine which FA environment (Dev/Uat/Prod) the script is running in. Returns the specified path contained in the FExtensionValue which differs for each environment. Also retrieves the list of trade filters separated by ';' in the FExtensionValue config file.
def retrieve_environment(env_config, filter_config): global path, filter_list_from_config arena_data_server = acm.FDhDatabase["ADM"].ADSNameAndPort().upper() configuration = acm.GetDefaultValueFromName( acm.GetDefaultContext(), acm.FObject, env_config) filter_list_from_config = acm.GetDefaultV...
[ "def get_current_environment():\n # Search for the environment variable set by the hutch python setup\n env = os.getenv('CONDA_ENVNAME')\n # Otherwise look for built-in Conda environment variables\n if not env:\n env = os.getenv('CONDA_DEFAULT_ENV')\n # Check the top level PYTHONPATH to see if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the trades already in the filter the global trades dictionary. The price is divided by 100 as per how business expects the output.
def add_trades(trdf): trade_list = trdf.Snapshot() if len(trade_list) > 0: main_dictStruct[str(trdf.Name())] = dict( (trade.Oid(), [trade.Oid(), trade.Quantity(), trade.Price() / 100, trade.TradeTime()]) for trade in trade_list)
[ "def __getPrices(self):\n\t\tprices=self.trades.GetPrices(\"transactions\")\n\t\tself.market_price=np.average(prices)\n\t\tself.min_price=min(prices)\n\t\tself.max_price=max(prices)", "def append_trade(self, trade: Trade) -> None:\n if trade.order.orderType == 'TRAIL':\n trade = self.set_trail_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Differential voltage v1 = voltage between inverting terminal and ground v2 = voltage between noninverting terminal and ground
def vd(v2,v1): return v2-v1
[ "def voltage(self) -> float:\n pass", "def voltage(self):\n return self.pos.voltage - self.neg.voltage", "def voltage_conversion(self):\r\n\t\tvoltage = ((self.data[0] * 256 + self.data[1]) / 65536.0) * 5.0\r\n\t\t\r\n\t\treturn {'v' : voltage}", "def velocity(df0, df1):\n velocity = df1 - df...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An amplifier with infinite openloop gain (v_o), infinite input resistance, and zero output resistance. Ideal op amp is an approximate analysis, but most modern amplifiers have such large gain and input impedances that the approximate analysis is a good one.
def idealOpAmp():
[ "def _amp_ ( self , x ) :\n v = self.amplitude ( x )\n #\n return complex( v.real () , v.imag () )", "def app(data_pupil,data_phase,oversize=4):\n complexr=app_complex(data_pupil,data_phase,oversize)\n amp=(abs(complexr)**2)\n return amp", "def lnlike_amp(params, data, model):\n visa = data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates entity's destination and returns lead time to arrive there in hours.
def set_destination(self): # TODO: consider new implementation with multiple paths possible. self.destination = self.network[self.current_node]['next'] lead_time = self.network[self.current_node]['path'].lead_time return datetime.timedelta(hours=lead_time)
[ "def travel_time_to_target(self) -> timedelta:\n destination = self.tot_waypoint\n total = timedelta()\n for previous_waypoint, waypoint in self.edges():\n if waypoint == self.tot_waypoint:\n # For anything strike-like the TOT waypoint is the *flight's*\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change password form for teachers
def change_password(request): emp = models.Teacher.objects.get(user=request.user) context_dict = {} if request.method == 'POST': form = AdminPasswordChangeForm(user=request.user, data=request.POST) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) context_dict["message"] = "P...
[ "def password():\n password_form = PasswordForm()\n if password_form.validate_on_submit():\n current_user.update_password(password_form.current_password.data,\n password_form.new_password.data)\n return redirect('/')\n return render_template('change_passwor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View to take email and mail the link to reset password.
def password_reset(request): context_dict = {} if request.method == 'POST': email = request.POST.get('email') if email: user = models.Teacher.objects.get( soft_delete=False, user__email=email ) if not user: context_dict["message"] = "Email ID does'nt exist, Enter Correct details" mail = { ...
[ "def send_reset_email(self):\n token = self.get_reset_token()\n msg = MailMessage(\n \"Password Reset Request\",\n recipients=[self.email],\n )\n msg.body = f\"\"\"To reset your password, visit the following link:\n\n{url_for('users.reset_token', token=token, _exter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For adding Exam name like semester 1 or trimester 2.
def addExamName(request): emp = models.Teacher.objects.get(user=request.user) if not emp.exam_permit: raise Http404 context_dict = {} if request.method == "POST": name = request.POST.get('ename') duplicate_check = models.ExamName.objects.filter( name=name, ).first() if duplicate_check: context_dict...
[ "def __str__(self):\n return \"Semester: {} {}\".format(self.get_id, self.get_name())", "def add_exam():\n errors = check_exams_keys(request)\n if errors:\n return raise_error(400, \"Invalid {} key\".format(', '.join(errors)))\n details = request.get_json()\n year_id = details['year_id']...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View to edit the already existing student in database by taking student_id.
def edit_student(request, student_id): emp = models.Teacher.objects.get(user=request.user) if not emp.student_permit: raise Http404 student = models.Student.objects.filter( pk=student_id, soft_delete=False ).first() if not student: raise Http404 context_dict = { "all_courses": context_helper.course_helpe...
[ "def student_update(request, id_student):\n student = get_object_or_404(Student, pk=id_student)\n form = StudentForm(request.POST or None, instance=student)\n context = {\n 'student_name': student.name,\n 'student_vorname' : student.vorname,\n 'student_id' : student.id_OD,\n 'st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edit details related to the subject / Meta data of subject.
def edit_subject(request,subject_id): emp = models.Teacher.objects.get(user=request.user) if not emp.subject_permit: raise Http404 subject = models.Subject.objects.filter( pk=subject_id, soft_delete=False ).first() if not subject: raise Http404 context_dict = { "all_courses": context_helper.course_helper...
[ "def edit_subject(request, subject):\n subject = get_object_or_404(Subject, slug=subject)\n if request.method == 'POST':\n subject_form = SubjectForm(instance=subject, data=request.POST, files=request.FILES)\n if subject_form.is_valid():\n subject_form.save()\n return redir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View students using data tables.
def view_students(request): context_dict = { 'title': 'All Students', } return render(request, "viewStudent.html", context_dict)
[ "def view_students():\n students = load_students()\n for student in students:\n print \"Name: {}\".format(student[\"name\"])", "def view_all_students():\n message = ''\n global conn\n with conn:\n rows = select_all_students(conn)\n for row in rows:\n message += str(row) + \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To add results of students / link results and students
def addResultMain(request): emp = models.Teacher.objects.get(user=request.user) if not emp.result_permit: raise Http404 context_dict = { "result_type": context_helper.result_type_helper(), "all_subjects": context_helper.subject_helper(), "all_exam_name": context_helper.exam_name_helper(), } if request.met...
[ "def relate_via_student_view(request, student_id):\n student = get_object_or_404(Student, pk=student_id)\n if request.method == \"POST\":\n lesson_form = LessonToStudentForm(request.POST)\n if lesson_form.is_valid():\n \n start_date = lesson_form.cleaned_data['date']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View Main results of students.
def view_result_main(request): context_dict = { 'title': 'All Results Main', } return render(request, "viewResultMain.html", context_dict)
[ "def view_students():\n students = load_students()\n for student in students:\n print \"Name: {}\".format(student[\"name\"])", "def view_students(request):\n\n\tcontext_dict = {\n\t\t'title': 'All Students',\n\t}\n\treturn render(request, \"viewStudent.html\", context_dict)", "def display_semester_results(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add result of attendance to the particular subject. Can also use this by taking subject ID not giving drop down for subjects.
def add_attendance(request): emp = models.Teacher.objects.get(user=request.user) if not emp.student_permit: raise Http404 context_dict = { "all_subjects": context_helper.subject_helper(), } if request.method == "POST": roll = request.POST.get('roll') subject = request.POST.get('subject_picker') attendan...
[ "def update_subject_click(self, widget):\n subject_info = dict() # output dict\n experiment_name = self.exp_info_dict['experiment_name'].get_value()\n # validate that there is an ID, and that it only contains numbers\n if self.info_dict['subject_ID'].get_value() == '':\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edit attendance of students subject wise.
def edit_attendance(request, attendance_id): emp = models.Teacher.objects.get(user=request.user) if not emp.student_permit: raise Http404 attendance = models.Attendance.objects.filter( pk=attendance_id, soft_delete=False ).first() print("1") context_dict = { "all_subjects": context_helper.subject_helper(),...
[ "def edit_subject(request,subject_id):\n\n\temp = models.Teacher.objects.get(user=request.user)\n\tif not emp.subject_permit:\n\t\traise Http404\n\tsubject = models.Subject.objects.filter(\n\t\tpk=subject_id, soft_delete=False\n\t).first()\n\tif not subject:\n\t\traise Http404\n\tcontext_dict = {\n\t\t\"all_courses...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View attendance of students.
def view_attendance(request): context_dict = { 'title': 'All Attendance', } return render(request, "viewAttendance.html", context_dict)
[ "def view_attendance(lesson_id):\n # Get the UserLessonAssociation for the current and\n # the given lesson id. (So we can also display attendance etc.)\n lesson = Lesson.query.filter(Lesson.lesson_id == lesson_id).first()\n\n # Ensure the lesson id/association object is found.\n if not lesson:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if height input without inches is extracted and converted into cm
def test_height_feet_only(self): result = height_to_cm("6'") self.assertEqual(result, 183)
[ "def test_inches_valid(self):\n result = inch_to_cm(\"72\\\"\")\n self.assertEqual(result, 183)", "def height_in_cm(feet=0, inches=0):\n inches_to_cm = inches * 2.54\n feet_to_cm = feet * 12 * 2.54\n return inches_to_cm + feet_to_cm", "def height_conversion(height):\n num_list = re.fin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if valid height input with feet and inches provided is extracted and converted into cm
def test_inches_valid(self): result = inch_to_cm("72\"") self.assertEqual(result, 183)
[ "def test_height_feet_only(self):\n result = height_to_cm(\"6'\")\n self.assertEqual(result, 183)", "def height_in_cm(feet=0, inches=0):\n inches_to_cm = inches * 2.54\n feet_to_cm = feet * 12 * 2.54\n return inches_to_cm + feet_to_cm", "def height_conversion(height):\n num_list = re.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start Hikvision event stream thread.
def start_hik(self, event): self.camdata.start_stream()
[ "def start(self):\r\n if self.running:\r\n warning('The event detector thread is already running')\r\n else:\r\n self.threads['running'] = new_thread(self.run)", "def start(self):\n\t\tself.stream.start_stream()", "def start(self):\n self.has_event = False\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return attribute list for sensor/channel.
def get_attributes(self, sensor, channel): return self.camdata.fetch_attributes(sensor, channel)
[ "def sensors(self) -> List[dict]:\n return self.items_by_domain(\"sensor\")", "def listattribute(self, varName):\n fName = \"\"\n if varName in self.statVars:\n fName = self.statVars[varName][0]\n elif varName in self.timeVars:\n fName = self.timeVars[varName][0][...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract sensor last update time.
def _sensor_last_update(self): return self._cam.get_attributes(self._sensor, self._channel)[3]
[ "def last_update(self: DetailedForecast) -> datetime:\n return self.update_time", "def _get_last_meas_time(self):\n\n #if flag for whole data regeneration is set\n if self._process_type == 'full_gen':\n return datetime.datetime(1900, 1, 1, 0, 0, 0)\n \n \n res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if sensor is on.
def is_on(self): return self._sensor_state()
[ "def is_on(self) -> bool:\n return self._device.is_on", "def is_on(self):\n return self._device.is_on()", "def is_on(self):\n return self.current_temperature != 32", "def is_on(self) -> bool:\n return self._device.fan_on", "def readerOn(self):\n return sensorReader.switch"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process the client reports by aggregating their weights.
async def process_reports(self): await self.aggregate_weights(self.updates) # Testing the global model accuracy if Config().clients.do_test: # Compute the average accuracy from client reports self.average_accuracy = self.accuracy_averaging(self.updates) loggi...
[ "def extract_client_updates(self, reports):\n\n # Extract the model weights from reports\n weights_received = [payload[0] for (__, payload) in reports]\n\n # Extract the update directions from reports\n self.update_directions_received = [\n payload[1] for (__, payload) in repo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrap up processing the reports with any additional work.
async def wrap_up_processing_reports(self): if hasattr(Config(), 'results'): new_row = [] for item in self.recorded_items: item_value = { 'global_round': self.current_global_round, 'round': se...
[ "def processReports(self):\n count = 0\n for r in self.reports:\n #need to change the next two lines so that the fields are not hard-coded\n self.currentCase = r.id\n self.currentText = r.impression.lower()\n self.analyzeReport(self.currentText,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create user and send activation emails.
def perform_create(self, serializer): user = serializer.save() signals.user_registered.send( sender=self.__class__, user=user, request=self.request ) context = get_email_context(user) to = [get_user_email(user)] if djconf.SEND_ACTIVATION_EMAIL: dj...
[ "def send_user_creation_email(user):\n\n # Don't email the created user about it\n admin_emails = list(\n get_user_model().objects.admins().exclude(pk=user.pk).values_list('email', flat=True))\n body = render_to_string(\n 'emails/user_created.txt',\n {\n 'user': user,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
append chart to list
def add_chart(self, chart: Chart): self.charts.append(chart)
[ "def add_chart(self, chart):\n\n chart._sheet = self\n self._charts.append(chart)", "def charts(self, charts):\n\n self.container['charts'] = charts", "def add_chart(self, chart, anchor=None):\n if anchor is not None:\n chart.anchor = anchor\n self._charts.append(ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resample coarse segmentation tensor to the given bounding box and derive labels for each pixel of the bounding box
def resample_coarse_segm_tensor_to_bbox(coarse_segm: torch.Tensor, box_xywh_abs: IntTupleBox): x, y, w, h = box_xywh_abs w = max(int(w), 1) h = max(int(h), 1) labels = F.interpolate(coarse_segm, (h, w), mode="bilinear", align_corners=False).argmax(dim=1) return labels
[ "def resample_fine_and_coarse_segm_tensors_to_bbox(\n fine_segm: torch.Tensor, coarse_segm: torch.Tensor, box_xywh_abs: IntTupleBox\n):\n x, y, w, h = box_xywh_abs\n w = max(int(w), 1)\n h = max(int(h), 1)\n # coarse segmentation\n coarse_segm_bbox = F.interpolate(\n coarse_segm, (h, w), mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resample fine and coarse segmentation tensors to the given bounding box and derive labels for each pixel of the bounding box
def resample_fine_and_coarse_segm_tensors_to_bbox( fine_segm: torch.Tensor, coarse_segm: torch.Tensor, box_xywh_abs: IntTupleBox ): x, y, w, h = box_xywh_abs w = max(int(w), 1) h = max(int(h), 1) # coarse segmentation coarse_segm_bbox = F.interpolate( coarse_segm, (h, w), mode="bilinear"...
[ "def resample_fine_and_coarse_segm_tensors_to_bbox(\n fine_segm: torch.Tensor, coarse_segm: torch.Tensor, box_xywh_abs: IntTupleBox\n):\n x, y, w, h = box_xywh_abs\n w = max(int(w), 1)\n h = max(int(h), 1)\n # coarse segmentation\n coarse_segm_bbox = F.interpolate(\n coarse_segm,\n (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert predictor output with coarse and fine segmentation to a mask.
def predictor_output_with_fine_and_coarse_segm_to_mask( predictor_output: Any, boxes: Boxes, image_size_hw: ImageSizeType ) -> BitMasks: H, W = image_size_hw boxes_xyxy_abs = boxes.tensor.clone() boxes_xywh_abs = BoxMode.convert(boxes_xyxy_abs, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS) N = len(boxes_xywh_...
[ "def predict_mask(model, img):\n assert len(img[0].shape) == 3, 'Input image must have channel dimension.'\n pred_result = model.detect(img, verbose=0)\n pred_mask = [p['masks'].astype(np.int).squeeze() for p in pred_result]\n return pred_mask", "def get_pred_mask(test_image, model):\n\n test_image...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method is playing morse code sounds depending on the input
def play_morse(tr_marks: list): play_morse_code = silence for mark in tr_marks: if mark == DOT: play_morse_code += sound play_morse_code += silence elif mark == COMMA: play_morse_code += sound play_morse_code += sound play_morse_code +=...
[ "def morse(self, message):\n # TODO: Adjust the wait and sleep values\n self.debug('Playing message: %s' % message)\n as_morse = string_to_morse(message)\n self.verbose('Morse repr: %s' % str(as_morse))\n freq = 1000\n for letter in as_morse:\n for m in letter:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call a tf_hub.Module using the standard blundell signature. This expects that `module` has a signature named `signature` which conforms to ('sequence', 'sequence_length') > output To use an existing SavedModel file you may want to create a module_spec with `tensorflow_hub.saved_model_module.create_module_spec_from_save...
def call_module(module, one_hots, row_lengths, signature): if signature not in module.get_signature_names(): raise ValueError('signature not in ' + six.ensure_str(str(module.get_signature_names())) + '. Was ' + six.ensure_str(signature) + '.') inputs = module.get_input_...
[ "def test_function_badsig(signature: str, systemcls: Type[model.System], capsys: CapSys) -> None:\n mod = fromText(f'def f{signature}: ...', systemcls=systemcls, modname='mod')\n docfunc, = mod.contents.values()\n assert isinstance(docfunc, model.Function)\n assert str(docfunc.signature) == '()'\n ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alternative constructor for Inferrer that is memoized.
def memoized_inferrer( savedmodel_dir_path, activation_type=tf.saved_model.signature_constants .DEFAULT_SERVING_SIGNATURE_DEF_KEY, batch_size=16, use_tqdm=False, session_config=None, memoize_inference_results=False, use_latest_savedmodel=False, ): return Inferrer( savedmodel_dir_...
[ "def get_inferrer_for(__call__, self, fn):\n tracking = getattr(fn, 'tracking_id', None)\n if tracking is None:\n return __call__(self, fn)\n if fn not in self.constructors:\n fn_generic = dc_replace(fn, tracking_id=None)\n inf = __call__(self, fn_generic)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the value of a variable from the graph.
def get_variable(self, variable_name): with self._graph.as_default(): return self._sess.run(self._get_tensor_by_name(variable_name))
[ "def get_variable(self, variable_name):\n with self._graph.as_default():\n return self._sess.run(variable_name)", "def get_value(name):\n var = Variable.query.filter(Variable.name == name).first()\n\n return var.value if var else None", "def visit_Variable(self, node):\n var_name = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the most recent savedmodel from a base directory path.
def latest_savedmodel_path_from_base_path(base_path): protein_export_base_path = os.path.join(base_path, 'export/protein_exporter') suffixes = [ x for x in tf.io.gfile.listdir(protein_export_base_path) if 'temp-' not in x ] if not suffixes: raise ValueError('No SavedModels found in %s' % prot...
[ "def get_last_saved_model(cls, model_dir) -> Tuple[Optional[Path], int]:\n return cls._get_first_model(model_dir, sort='step', desc=True)", "def fetch_last_model_file(self):\n try:\n filename = self.model_files[-1]\n return self.make_path(filename)\n except IndexError:\n return None", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serializes an inference result. This function is the opposite of deserialize_inference_result. The full format returned is a
def serialize_inference_result(sequence_name, activations): with io.BytesIO() as bytes_io: np.savez_compressed(bytes_io, **{sequence_name: activations}) return base64.b64encode(bytes_io.getvalue())
[ "def serialize_result(result: Any) -> Union[str, bytes]:\n if isinstance(result, Node):\n return result.serialize(how='default' if RESULT_FILE_EXTENSION != '.xml' else 'xml')\n else:\n return repr(result)", "def deserialize_inference_result(results_b64):\n bytes_io = io.BytesIO(base64.b64deco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deserializes an inference result. This function is the opposite of serialize_inference_result. The full format expected is a
def deserialize_inference_result(results_b64): bytes_io = io.BytesIO(base64.b64decode(results_b64)) single_pred_dict = dict(np.load(bytes_io)) if len(single_pred_dict) != 1: raise ValueError('Expected exactly one object in the structured np array. ' f'Saw {len(single_pred_dict)}') seque...
[ "def _decode_result(self, result):\n if isinstance(result, list):\n return [self._decode_result(r) for r in result]\n elif isinstance(result, SimpleString):\n return result.value\n elif isinstance(result, SimpleError):\n return self._decode_error(result)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses file of gzipped, newlineseparated inference results. The contents of each line are expected to be serialized as in `serialize_inference_result` above.
def parse_shard(shard_path): with tf.io.gfile.GFile(shard_path, 'rb') as f: with gzip.GzipFile(fileobj=f, mode='rb') as f_gz: for line in f_gz: # Line-by-line. yield deserialize_inference_result(line)
[ "def parse(path):\n data = gzip.open(path, 'rb')\n for byte_line in data:\n yield eval(byte_line) # return generator instance to save memory", "def parse_external_result(self, file):\n raise NotImplementedError", "def parse(fcontents, utf16=False): # TODO where does this conversion take pl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether connected and ACKed
def is_connected(self): if self.connected and self.connack_rec: return 1 return 0
[ "def connected(self):\n return bool(self.serial)", "def is_connected(self):\n return self.hw_connected", "def is_connected(self):\n return self.serial_connection.isOpen()", "def is_connected(self) -> bool:\n return is_socket_connected(self.immsocket)", "def is_connected(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders a list of historic batches
def view_batches(request): template = 'batch_list.html' context = { 'invalid_due_date': request.GET.get('invalid_due_date') } try: get_batches(request, context) except Exception as e: context['error'] = '{} {}'.format(e, traceback.format_exc()) # TODO: GO PAF - Start ...
[ "def build_list():\n build_list = history.fetch_n_last(10)\n return render_template('build_list.html', build_list=build_list)", "def build_all_list():\n build_list = history.fetch_all()\n return render_template('build_list.html', build_list=build_list)", "def list_history(request):\n history = Hist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Método responsavel em conectar e inicializar a base da dados no Cassandra
def init_cassandra(resource_dir, seeds = ["127.0.0.1"]): #conectar na base cluster = Cluster(seeds) session = cluster.connect() #cria a database with open(resource_dir + "/init.cql", "r") as schema_init: for line in schema_init: session.execute(line) #configura o keyspace correto da aplicação session.set_ke...
[ "def __cassandra_connect(self):\n self.cluster = Cluster()\n self.session = self.cluster.connect('demo')", "def setup_keyspace():\n\n try: \n # Make a connection to a Cassandra instance in the local machine (127.0.0.1)\n cluster = Cluster(['127.0.0.1']) \n # To establish conn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the number of timesteps needed to get the simulation past tmax
def num_sim_steps(self, dt, tmax): return int(np.ceil(tmax / dt))
[ "def get_max_time_steps (self):\n return self.degreedays.thawing.num_timesteps", "def n_timesteps(self) -> int:\n return len(self.time)", "def num_timesteps(self):\n return self._num_timesteps", "def max_steps(self) -> int:\n return pulumi.get(self, \"max_steps\")", "def get_max_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper around fast_pad_shift() in fastshift.c Works out the optimum number of indicies by which y2 needs to be shifted to have the minimum least squares error between the two
def fast_pad_shift(self, y1, y2): if len(y1) != len(y2): raise ValueError("Input sizes must be the same") y1_contig = np.ascontiguousarray(y1, dtype=np.float64) y2_contig = np.ascontiguousarray(y2, dtype=np.float64) y1_ptr = y1_contig.ctypes.data_as(ctypes.POINTER(ctypes.c_...
[ "def perfect_shift(y):\n return np.append([y[-1]],y[0:-1])", "def shift_right(ys, shift):\n res = np.zeros(len(ys) + shift)\n res[shift:] = ys\n return res", "def _shift(a, b, lag, dim='time'):\n if a[dim].size != b[dim].size:\n raise IOError(\"Please provide time series of equal lengths.\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts the number of times a pattern is in text.
def pattern_count(text, pattern): return len([i for i in range(0, len(text) - len(pattern) + 1) if text[i:i + len(pattern)] == pattern])
[ "def PatternCount(text, pattern):\n l_p = len(pattern)\n l_t = len(text)\n tot = 0\n for i in range(l_t - l_p + 1):\n if text[i:i+l_p] == pattern: tot += 1\n return tot", "def pattern_count(text: str, pattern: str) -> int:\n count = 0\n pattern_size = len(pattern)\n\n for i in rang...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the patterns(kmers) whose frequency of occurrence (count) is greater than t.
def frequent_words_t(text, k, t): frequent_patterns = [] count = {} for i in range(0, len(text)-k+1): pattern = text[i:i+k] count[i] = pattern_count(text, pattern) if count[i] >= t and pattern not in frequent_patterns: frequent_patterns.append(text[i:i+k]) return freq...
[ "def chunkedClumpFinder(sequence, k, L, t):\n\n frequentPatterns = set([])\n for i in range(len(sequence)):\n window = sequence[i:i + L]\n frequencies = {}\n\n for j in range(len(window)):\n pattern = window[j:j + k]\n if pattern not in frequencies:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns and array with all positions where the pattern is found within the text.
def find_position(pattern, text): positions = [] i = 0 while text[i:] and text[i:].find(pattern) != -1: position = text[i:].find(pattern) + i positions.append(position) i = position + 1 return positions
[ "def find_pattern_indexes(text, pattern):\n pattern_len = len(pattern)\n results = []\n for i in range(len(text) - pattern_len):\n\n window = text[i: i + pattern_len]\n if window == pattern:\n results.append(i)\n return results", "def find_all_indexes(text, pattern):\n # CO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A kmer can be arranged in a 4^k ordered array. This function returns an array of the frequency of each of the kmers in the text. The position of the array can be matched with the pattern using pattern_to_number and number_to_pattern.
def compute_freq(text, k): freq_array = [0 for i in range(0, 4**k)] for i in range(0, len(text) - k + 1): pattern = text[i:i + k] j = pattern_to_number(pattern) freq_array[j] += 1 # return ' '.join([str(i) for i in freq_array]) return freq_array
[ "def ComputingFrequencies(text, k, debug = False):\n\n\tkmer_dict = {}\n\tFreqArray = []\n\tfor i in range(4**k):\n\t\tFreqArray.append(0)\n\tif debug:\n\t\tprint \"freqArray is length:\", len(FreqArray)\n\t\t\n\tfor i in range(len(text)-k+1):\n\t\tPattern = text[i:i+k]\n\t\tj = PatternToNumber(Pattern)\n\t\tFreqAr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same that find_clumps but using the improved functions to find frequent patterns
def clumps_finding(text, k, t, L): frequent_patterns = [] clumps = [0 for i in range(0, 4**k)] for i in range(0, len(text) - L + 1): subtext = text[i:i + L] freq_array = compute_freq(subtext, k) for index, freq in enumerate(freq_array): if freq >= t: clump...
[ "def chunkedClumpFinder(sequence, k, L, t):\n\n frequentPatterns = set([])\n for i in range(len(sequence)):\n window = sequence[i:i + L]\n frequencies = {}\n\n for j in range(len(window)):\n pattern = window[j:j + k]\n if pattern not in frequencies:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function turns off agent learning.
def turn_off_learning(self): self.epsilon = 0 self.alpha = 0
[ "def disable_learning(self):\r\n\t\t\r\n\t\tself.learning = False", "def disableLearning(self):\n self.__learningEnabled = False\n return", "def disable_agent_discovery(self):\n self._agent_discovery_filter = None", "def enab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms a course run into our normalized data structure
def _transform_run(course_run): return { "run_id": course_run["courseware_id"], "title": course_run["title"], "start_date": _parse_datetime(course_run["start_date"]), "end_date": _parse_datetime(course_run["end_date"]), "enrollment_start": _parse_datetime(course_run["enrollme...
[ "def transform_courses(courses):\n return [_transform_learning_resource_course(course) for course in courses]", "def to_course(self):\n # parse spreadsheet of items and create chapter objects (with nested objects)\n course = Course(**self.course_params)\n\n for chapter_label, chapter_group...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms a list of courses into our normalized data structure
def transform_courses(courses): return [_transform_learning_resource_course(course) for course in courses]
[ "def cleanCourses(courses):\n curCourse = \"\"\n ret = []\n for c in courses[1:]:\n prefix = c[:4]\n if prefix == \"LEC \" or prefix == \"SEM \" or prefix == \"TUT \" or prefix == \"LAB \":\n if c[-2:] == \"80\" or c[-2:] == \"81\":\n ret.append(curCourse + ':' + pre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read through the text file to retrieve each word and its embedding. If a word starts with an alphabetic character, create a WordEmbedding object for that word and its embedding and insert it in its proper place in the BTree.
def buildBTree(T, file): for line in file: word_line = line.split(' ') word = word_line[0] embedding = word_line[1:] embedding = [float(i) for i in embedding] if word[0].isalpha(): word_emb_object = WordEmbedding.WordEmbedding(word, embedding) ...
[ "def buildBST(T,file):\r\n for line in file:\r\n word_line = line.split(' ')\r\n word = word_line[0]\r\n embedding = word_line[1:]\r\n embedding = [float(i) for i in embedding]\r\n if word[0].isalpha():\r\n word_emb_object = WordEmbedding.WordEmbedding(word, embeddin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If k, a word string, is in the BTree, determine the value of c, such that k must be in the subtree T.child[c]. This function helps search a word in the BTree by comparing it to the word in each WordEmbedding object in the node.
def findChildB(T,k): for i in range(len(T.data)): if k < T.data[i].word: return i return len(T.data)
[ "def search(T,k):\r\n for t in T.data:\r\n if k == t.word:\r\n return t\r\n if T.isLeaf:\r\n return None\r\n return search(T.child[findChildB(T,k)],k)", "def search(self, key): \n \n current_node = self.root \n length = len(key) \n for level in range(len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the WordEmbedding object from the node where k, a word string, is found in the BTree. If k is not in the tree, return None.
def search(T,k): for t in T.data: if k == t.word: return t if T.isLeaf: return None return search(T.child[findChildB(T,k)],k)
[ "def _get_node(self, word):\n node = self.root\n for letter in word:\n if letter not in node.edges:\n return None\n node = node.edges[letter]\n return node", "def get_embedding(self,word):\n return self.wv[word]", "def get_root(word):\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse through the entire BTree to calculate the number of nodes it has.
def numNodes(T): n = 1 if T.isLeaf: return n for i in range(len(T.child)): n += numNodes(T.child[i]) return n
[ "def count_nodes(self):\n if self.is_empty():\n return 0\n elif self.is_leaf():\n return 1\n else:\n if self.get_left():\n if self.get_right():\n return 1 + self.get_left().count_nodes() + self.get_right().count_nodes()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse through a single path of the BTree (from the root to a single leaf) to calculate its height.
def height(T): if T.isLeaf: return 0 return 1 + height(T.child[0])
[ "def height(self) -> int:\r\n if self.root is None: # If the tree is empty it returns a value of -1\r\n return -1\r\n if self.root.right is None and self.root.left is None: # If the tree only consists of a root node, it will\r\n # return a value of 0\r\n return 0\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that responsible for the iteration over the events returned from github api
def _iter_events(self) -> Generator: response = self.client.call() events: list = response.json() if not events: return [] while True: yield events last = events.pop() self.client.set_next_run_filter(last['@timestamp']) respon...
[ "def _events(self):\n try:\n latest_event = Event.objects.latest('start_time')\n last_update = latest_event.start_time\n except Event.DoesNotExist:\n last_update = timezone.make_aware(datetime.min,\n timezone.get_default_tim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
take a string and change all "a" in string to 1, "e" in to 2, "i" into 3, "o" into 4, "u" into 5 str > str
def modify(str1): str2 = "" for char in str1.lower(): if char == "a": str2 += "1" elif char == "e": str2 += "2" elif char == "i": str2 += "3" elif char == "o": str2 += "4" elif char == "u": str2 += "5...
[ "def abbreviate(i):\n return i[0:3] + i[3:].replace(\"a\", \"\").replace(\"e\", \"\").replace(\"i\", \"\").replace(\"o\", \"\").replace(\"u\", \"\")[0:3]", "def rotate_word(s,i):\n new_string = ''\n for letter in s:\n new_string += chr(ord(letter)+i)\n return new_string", "def accum1(s):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for create_response_descriptor_subscriptions_subscription_subscription_resource
def test_create_response_descriptor_subscriptions_subscription_subscription_resource(self): pass
[ "def test_modify_response_descriptor_subscriptions_subscription_subscription_resource(self):\n pass", "def test_create_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resource(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for create_response_descriptor_subscriptions_subscription_subscription_resource_spaces
def test_create_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self): pass
[ "def test_modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_index_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resour...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_on_background_response_descriptor_subscriptions_subscription_subscription_resource
def test_delete_on_background_response_descriptor_subscriptions_subscription_subscription_resource(self): pass
[ "def test_delete_on_background_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_delete_subscription(self):\n pass", "def test_issue_delete_subscription(self):\n pass", "def test_remove_subscription_pending_status_using_delete(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_on_background_response_descriptor_subscriptions_subscription_subscription_resource_spaces
def test_delete_on_background_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self): pass
[ "def test_delete_on_background_response_descriptor_projects_release_release_resource_spaces(self):\n pass", "def test_delete_on_background_response_descriptor_subscriptions_subscription_subscription_resource(self):\n pass", "def test_delete_on_background_response_descriptor_projects_project_trigge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for index_response_descriptor_subscriptions_subscription_subscription_resource
def test_index_response_descriptor_subscriptions_subscription_subscription_resource(self): pass
[ "def test_create_response_descriptor_subscriptions_subscription_subscription_resource(self):\n pass", "def test_modify_response_descriptor_subscriptions_subscription_subscription_resource(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resource(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for index_response_descriptor_subscriptions_subscription_subscription_resource_spaces
def test_index_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self): pass
[ "def test_create_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for list_all_response_descriptor_subscriptions_subscription_subscription_resource
def test_list_all_response_descriptor_subscriptions_subscription_subscription_resource(self): pass
[ "def test_list_all_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resource(self):\n pass", "def test_create_response_descriptor_subscriptions_subscription_subscription_resource(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for list_all_response_descriptor_subscriptions_subscription_subscription_resource_spaces
def test_list_all_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self): pass
[ "def test_index_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_modify_response_descriptor_subscriptions_subscription_subscription_resour...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for load_response_descriptor_subscriptions_subscription_subscription_resource
def test_load_response_descriptor_subscriptions_subscription_subscription_resource(self): pass
[ "def test_create_response_descriptor_subscriptions_subscription_subscription_resource(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_modify_response_descriptor_subscriptions_subscription_subscription_resource(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for load_response_descriptor_subscriptions_subscription_subscription_resource_spaces
def test_load_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self): pass
[ "def test_create_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_index_response_descriptor_subscriptions_subscription_subscription_reso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for modify_response_descriptor_subscriptions_subscription_subscription_resource
def test_modify_response_descriptor_subscriptions_subscription_subscription_resource(self): pass
[ "def test_create_response_descriptor_subscriptions_subscription_subscription_resource(self):\n pass", "def test_modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self):\n pass", "def test_load_response_descriptor_subscriptions_subscription_subscription_resource(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }