query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Tests that if a rate can be returned, it is always formatted to two decimal places.
def test_rate_always_formatted_to_two_decimal_places(self): zipcode = '11111' cleaned_zipcode_data_input = {'11111': [('NY', '5')]} cleaned_plan_data_inputs = [ {('NY', '5'): ['294.24', '294']}, {('NY', '5'): ['294.24', '294.7']}, {('NY', '5'): ['294.24', '29...
[ "def formatRating(value):\n if value is None:\n return \"\"\n\n return f\"{value:,.2f}\"", "def _exchange_amount(amount, rate):\n return '%.2f' % round(float(amount) * float(rate), 2)", "def compare_data(myRate, myRateList):\n change = ( myRate * 100 / myRateList[-1]) - 100\n change = int...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
list all hangouts, supply keywords to filter by title
def hangouts(bot, event, *args): text_search = " ".join(args) lines = [] for convid, convdata in bot.conversations.get(filter="text:" + text_search).items(): lines.append("<b>{}</b>: <em>`{}`</em>".format(convdata["title"], convid)) lines.append(_('<b>Total: {}</b>').format(len(lines))) i...
[ "def hangouts(bot, event, *args):\n\n text_search = \" \".join(args)\n line = \"<b>List of hangouts with keyword:</b> \\\"{}\\\"<br />\".format(text_search)\n\n for conv in bot.list_conversations():\n conv_name = get_conv_name(conv)\n if text_search.lower() in conv_name.lower(): # For blank k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reload config and memory, useful if manually edited on running bot
def reload(bot, event, *args): yield from bot.coro_send_message(event.conv, "<b>reloading config.json</b>") bot.config.load() yield from bot.coro_send_message(event.conv, "<b>reloading memory.json</b>") bot.memory.load()
[ "def reload(bot, event, *args):\n bot.config.load()\n bot.memory.load()", "def reload_config(self):\n pass", "def reload_config(self):\n self.set_footer('Reloading configuration')\n self.config = Config()\n self.build_help()\n self.palette = self.config.get_palette()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a Map with the given number of buckets.
def new(num_buckets=256): aMap = [] #creating empty list aMap for i in range(0, num_buckets): aMap.append([]) #append num_buckets into aMap return aMap
[ "def new(num_buckets=256):\n\t#sets aMap variable to an empty list\n\t#then fills that list with the specified number of other empty lists ('buckets') \n\t#returns the new aMap\n\taMap = []\n\tfor i in range(0, num_buckets):\n\t\taMap.append([])\n\treturn aMap", "def new(num_buckets=256):\n aMap = []\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the index, key, and value of a slot found in a bucket. Returns 1, key, and default (none if not set) when not found.
def get_slot(aMap, key, default=None): bucket = get_bucket(aMap, key) for i, kv in enumerate(bucket): k, v = kv if key == k: return i, k, v return -1, key, default
[ "def get_slot(aMap, key, default=None):\n\t#now that we know which bucket the key could be in\n\t#we iterate through all the elements of that bucket until it finds the key\n\t\n\tbucket = get_bucket(aMap, key)\n\t\n\tfor i, kv in enumerate(bucket):\n\t#enumerate returns a tuple containing the count (starting at 0) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this keyword is used to grep keywords in a file, then return matching lines.\n filePath is the full path of the file.\n searchKeyWord is the keyword filter.\n isPattern is the flag indicate if searchKeyword is a normal search string or regular expression pattern.\n isCaseSensitive is the flag indicate if searchKeyword ...
def grep_local_file(filePath, searchKeyWord, isPattern=True, isCaseSensitive=True, Fromline=0, timeout=0, retry_interval=0): returnMatchLines = [] current = time.time() timout_value = float(timeout) maxtime = current + timout_value while (current <= maxtime): fileObj = open(filePath, "...
[ "def find_term(content_file, search_term, ignore_case=True,\n regex_syntax=False):\n pv.path(content_file, \"content file\", True, True)\n pv.string(search_term, \"search term\", True, None)\n\n content_file = os.path.abspath(content_file)\n list_matches = []\n regex = common.compile_reg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify the old contents to new contents.\n oldFile is the original file fullpath.\n newFile is the output file fullpath.\n case_insensitive is True or false.\n
def Modify_lines_matching_pattern(oldFile, newFile, modifydic, case_insensitive): fd = open(oldFile, "r") lines = fd.readlines() fd.close() for key in modifydic.keys(): if case_insensitive == True: pattern = re.compile(key, re.I) else: pattern = re.c...
[ "def filename_to_modify(self, filename):", "def _old2new(filename):\n f = open(filename, 'r')\n lines = f.readlines()\n f.close()\n os.rename(filename, filename + '.old')\n\n # perform substitutions:\n nchanges = 0\n for i in range(len(lines)):\n oldline = lines[i]\n # change fr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method to respond to the mouse not being over the element. Called AFTER mouse_out if that method gets called.
def mouse_not_over(self): pass
[ "def mouse_out(self):\n pass", "def on_unhover(self):\n pass", "def on_unhover(self) -> None:", "def mouse_out(self, event):\r\n self['background'] = self.defaultBackground", "def MouseOverItem(self,item):\r\n pass", "def _checkMouseOver(self):\n\t\tif not self:\n\t\t\t# Object...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method to respond to the mouse entering the element.
def mouse_enter(self): pass
[ "def on_mouse_enter(self, event):\n pass", "def enterEvent(self, event):\n\n #emit signal\n self.hover_enter.emit()\n #accept\n event.accept()", "def Entering(*args, **kwargs):\n return _core_.MouseEvent_Entering(*args, **kwargs)", "def __mouse_entered(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method if to respond to the mouse leaving the element.
def mouse_out(self): pass
[ "def leaveEvent(self, event):\n\n # Call a method in WalkLibraryUI to notify of the event\n self.ref.HoverEvent(False, self.prefix, self.index)", "def leaveEvent(self, event):\n\n #emit signal\n self.hover_leave.emit()\n #accept\n event.accept()", "def on_mouse_exit(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method to respond to the left mouse button being held down over the element.
def mouse_left_down(self): pass
[ "def leftButtonDown(self):\n\t\tautopy.mouse.toggle(True,autopy.mouse.LEFT_BUTTON)", "def left_release(self, event):\n self.left_mouse_pressed = False", "def mouse_right_down(self):\n pass", "def _left_pressed(self):\n pass", "def mouse_left_button_down(self, x=None, y=None):\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method to respond to the right mouse button being held down over the element.
def mouse_right_down(self): pass
[ "def mouse_right_up(self):\n pass", "def _right_pressed(self):\n pass", "def rightButtonDown(self):\n\t\tautopy.mouse.toggle(True,autopy.mouse.RIGHT_BUTTON)", "def right_release(self, event):\n self.right_mouse_pressed = False", "def mouse_right_button_down(self, x=None, y=None):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method to respond to the right mouse button being released on the element.
def mouse_right_up(self): pass
[ "def right_release(self, event):\n self.right_mouse_pressed = False", "def mouse_right_down(self):\n pass", "def mouse_release_event(self, x: int, y: int, button: int):\n pass", "def on_mouse_release(self, x, y, button):\n pass", "def _right_pressed(self):\n pass", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method to respond to the middle mouse button being held down over the element.
def mouse_middle_down(self): pass
[ "def mouse_right_up(self):\n pass", "def on_mouse_release(self, x, y, button):\n pass", "def on_mouse_release(event):\n pass", "def right_release(self, event):\n self.right_mouse_pressed = False", "def mouse_right_down(self):\n pass", "def OnMiddleDown(self, event):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override this method to respond to the mouse wheel spinning when the mouse is being held down over the element.
def mouse_wheel_down(self): if not self.scroll_element is None: self.scroll_element.mouse_wheel_down()
[ "def MouseWheelEvent(self, vtkContextMouseEvent, p_int):\n ...", "def ev_mousewheel(self, event: MouseWheel) -> None:", "def wheelEvent(self, ev):\n if ev.type() == QtCore.QEvent.Wheel:\n ev.ignore()", "def on_mouse_release(event):\n pass", "def __doScroll(self):\n\t\tGiz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the pointer to the GUI object that is under the screen coordinates passed in to the coordinates parameter. current_best should be None unless called from this method.
def handle_input(self, coordinates, current_best = None): if self.disable: return current_best if self.is_coords_in_bounds(coordinates): if current_best is None or self.z <= current_best.z: current_best = self else: if self._currently_...
[ "def current_gui(self):\n return self._current_gui", "def get_current_widget(*args):\n return _ida_kernwin.get_current_widget(*args)", "def getlocalbestcoordinate(self):\n return self.localbest.coordinate", "def get_widget_at_mouse():\n\n current_pos = QtGui.QCursor().pos()\n widget = QAp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Must be called at the start of the execute method. Make sure that image has been set before calling this. A None image will draw a generic button.
def gui_init(self): GUI_element.gui_init(self) self.hover_sound = False if not self.image is None: self.generic_button = False self.width = self.image.width if self.width == 0 else self.width self.height = self.image.height if self.height == 0 else s...
[ "def _update_image(self):\n button = self.buttons.checkedButton()\n if button is None:\n return\n\n button.click()", "def boutton(self,img1,x,y):\r\n self.button.append(self.creat_image(img1,x,y))", "def showBtnImg(*args, **kwargs):\n\targs[0].get_image().show()", "def m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the slider is dragged. Designed to be overridden to add custom behaviour.
def slider_dragged(self): pass
[ "def on_mouse_drag(self, event):\n pass", "def on_slider(self, instance, value):\n self.slider.bind(value=self.update_proxy)\n self.bind(pos=self.hack_position)\n self.slider.bind(pos=self.hack_position)", "def hook_drag(self):\n widget = self.widget\n widget.mousePress...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that ensures that the anime in user choosen listbox isn't in all anime listbox
def update_libox_all_anime(): ## print("update_libox_all_anime is runnig") a = libox_all_anime.get(0, END) ## print("the contents or a :", a) b = [] for x in a: ## print("this is x: ", x) b.append(x) ## print(x) for x in updated_your_anime(): if x in b: ...
[ "def canUnlockAll(boxes):", "def get_airports_from_selection(self, event):\n self.is_airport_in_list = False\n if not self.airport_1.get():\n self.airport_1.set(self.airport_cmbox.get())\n elif not self.airport_2.get() and not self.check_if_user_input_same_airport(self.airport_cmbo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up GenericRelations for a given actionable model. Needed because actstream's generic relationship setup functionality is brittle and unreliable.
def actstream_register_model(model): for field in ('actor', 'target', 'action_object'): generic.GenericRelation(Action, content_type_field='%s_content_type' % field, object_id_field='%s_object_id' % field, relate...
[ "def test_add_relation_types(self):\n pass", "def test_resource_relation_resource_add_relations_post(self):\n pass", "def test_add_relation_type(self):\n pass", "def _attach_to_model(self, model):\n super(RelatedFieldMixin, self)._attach_to_model(model)\n\n if model.abstract...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the name of the Subreddit.
def getSubredditName(self): return self.nameOfSubreddit
[ "def subreddit():\n return reddit.subreddit()", "def get_subreddit(self, subreddit_name):\n print(f\"Connecting to subreddit: r/{subreddit_name}...\")\n return self.reddit.subreddit(subreddit_name)", "def sub_reddit(url: str) -> str:\n return re.match(r\"https://www.reddit.com/r/(\\w+)/\", u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the subreddit name. Name of the subreddit you want to change to.
def setSubreddit(self, subredditName): self.nameOfSubreddit = subredditName self.subreddit = self.praw.subreddit(nameOfSubreddit)
[ "def update_name(self, name: str) -> str:\n pass", "def prompt_subreddit(self):\n prompt = 'Enter Subreddit: /r/'\n name = self.prompt_input(prompt)\n if name is not None:\n self.refresh_content(name=name)", "def subtask_name(self, subtask_name):\n self._subtask_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a lists of integers of scores of the posts.
def getScore(self): self.scoreList = [submissionsss.score for submissionsss in self.subreddit.top(time_filter = 'day', limit = self.limits)] return self.scoreList
[ "def extract_scores(self, values):\r\n return [values[idx] for idx in self.scores.keys()]", "def childScores(self):\n return [x.score for x in self.children]", "def get_scores(self):\n return [(self.players[p.get_color()], p.get_score()) for p in self.state.get_players()]", "def scores(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Buffer some data to a stream to a node's input. Whenever the node is available to read a value from the matching input, this will send the next value.
def buffer_input(self, node, direction, values): self.num_buffered_inputs += len(values) self.buffered_input.setdefault(node, {}).setdefault(direction, []).extend(values)
[ "def feed(self, data):\n self.buffer += data\n self.process()", "def process(self, data):\n if self.__head:\n self.__head.send(Element(\n stream_id=self.id,\n data=data))", "def data_received(self, data):\n self.read_buffer = self.read...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whether there are any buffered inputs remaining.
def has_buffered_inputs(self):
[ "def bufferIsFull(self):\n return len(self.buffer) == self.bufferSize", "def has_unlimited_buffer(self):\n return self._buffer_size < 0", "def isBufferFull(self):\n return self._length >= self._bufferSize", "def has_data_pending(self):\n return bool(self.__partial_output)", "def has_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in and returns hyperparameters as an array of the same length. The elements of are pairs [lower, upper], and the corresponding hyperparameter is sampled from a uniform distribution in the interval [lower, upper]. If instead of a pair we have a number in , then we assign that value as the appropriate hyperparamete...
def initBoundedParams(bounds, sn=[]): hypinit = { 'cov': np.zeros(len(bounds)), 'lik': np.atleast_1d(np.log(sn)), 'mean': np.array([]) } # Sample from a uniform distribution for idx, pair in enumerate(bounds): # Randomize only if bounds are specified if isinst...
[ "def randomHyperParamsForClassifier(params):\n return {p:(np.random.randint(value[0],value[1]) if isinstance(value[0],int)\n else np.random.uniform(value[0],value[1])) for p,value in params.items()}", "def discrete_uniform_sampler(upper_value):\n return int(np.random.random() * upper...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(i, j)번쨰 원소가 entry_fn(i, j)인 num_rows, num_cols 리스트를 반환
def make_matrix(num_rows : int, num_cols : int, entry_fn : Callable[[int, int], float]) -> Matrix: return [[entry_fn(i, j) # i 가 주어졌을 떄, 리스드를 생성한다. for j in range(num_cols)] # [entry_fn(i, 0), ...] for i in range(num_rows)] # 각 i 에 대해 하나의...
[ "def fcalc(col,row):\n#\n if row>200:row=200\n if col>20:col=20\n ftest=numpy.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],\n[1, 161.469, 199.493, 215.737, 224.5, 230.066, 234.001, 236.772, 238.949, 240.496, 241.838, 242.968, 243.88, 244.798, 245.26, 245.956, 246.422, 2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of coordinates in string.
def counting_coordinates(string): num_of_commas = string.count(',') num_of_cords = num_of_commas + 1 return num_of_cords
[ "def calc_length(linestring):\n tot_length = 0\n prev_long,prev_lat = linestring.coords[0]\n for cur_long,cur_lat in linestring.coords[1:]:\n distance = calc_distance(prev_lat, prev_long, cur_lat, cur_long)\n tot_length = tot_length + distance\n prev_long,prev_lat = cur_long,cur_lat\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy contents of arr1 to arr2.
def copy_arr1_to_arr2(arr1, arr2, k, num_of_cords): for i in range(k): for j in range(num_of_cords): arr2[i][j] = arr1[i][j]
[ "def assign(array1, array2):\n for i in range(len(array1)):\n array2[i] = array1[i]", "def swapArray( a1, a2 ):\n assert( len(a1) == len(a2) );\n for i in range( len( a1 ) ):\n tmp = a1[i];\n a1[i] = a2[i];\n a2[i] = tmp;\n # for - end", "def merge(arr1, arr2):\n\tres = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn all slots of currClusters to zero.
def make_all_zero(curr_clusters, k, num_of_cords): for i in range(k): for j in range(num_of_cords): curr_clusters[i][j] = 0
[ "def zero(self):\n for factor in self:\n factor.zero()", "def reset(self):\n self._clusters = {}\n self._clusters_val = {}\n self._centroids = {}\n self.store()", "def setAllZero(self):\n\n\t\tfor cal in self.calibrations:\n\t\t\tcal.setZero()", "def zero(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if clusters1 equals to clusters2, return True if so, or False if not.
def is_converged(clusters1, clusters2, k, num_of_cords): for i in range(k): for j in range(num_of_cords): if clusters1[i][j] != clusters2[i][j]: return False return True
[ "def clusters_are_identical(one, two):\n if not len(one) == len(two):\n return False\n for subA, subB in zip(one, two):\n if not subA.ipg or not subB.ipg:\n return False\n if subA.ipg != subB.ipg:\n return False\n return True", "def __eq__(self, other):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve an exchange from database by id
def get_exchange(self, id): return self.exch_repo.get(id)
[ "def get(self, id):\n exchange_data = self.connection.query(Connection.TYPE_SELECT, [Exchange.EXCHANGE_ID], [id])\n return self.create_model(exchange_data)", "def get_exchange_by_id(self, exchange_id):\n\n if not isinstance(exchange_id, int) or exchange_id < 0:\n raise InvalidTronE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new exchange in the database
def create_exchange(self, exchangename, public_key, private_key, user_id, uid = None, pw = None): if not exchangename or not public_key or not private_key: raise Exception("Exchangename, public key and private key must be given") else: return self.exch_repo.create(exchangename, p...
[ "def create(self, exchangename, public_key, private_key, user_id, uid, pw):\n self.connection.query(\n Connection.TYPE_INSERT,\n [\n Exchange.EXCHANGE_NAME,\n Exchange.EXCHANGE_PUBLIC,\n Exchange.EXCHANGE_PRIVATE,\n Exchange.EX...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete an existing exchange from the database
def delete_exchange(self, exchange_id): if exchange_id: self.exch_repo.delete(exchange_id=exchange_id) else: raise Exception("No exchange_id found for deleting exchange.")
[ "def delete(self, exchange_id):\n self.connection.query(\n Connection.TYPE_DELETE,\n [Exchange.EXCHANGE_ID],\n [exchange_id]\n )", "def _find_delete_qmf_exchange(self, qmf_broker, name, type, alternate, durable, auto_delete):\n e = self._find_qmf_exchange(qmf_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if an input pair is a valid one for given exchange
def is_valid_pair(self, pair, exchange): pairs = self.ccxt.get_pairs(exchange) print(pairs) return pair in pairs
[ "def validate_pairs(pairs, historical_pairs):\n if pairs is None:\n return False\n for p in pairs:\n if p in historical_pairs:\n return False\n return True", "def is_exchange_information_valid(exchange_info: Dict[str, Any]) -> bool:\n return exchange_info.get(\"trade_status\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches balance for a pair on an exchange through CCXT
def fetch_balance(self, exchange, pair): return self.ccxt.fetch_balance(exchange, pair)
[ "def balances():\n loop.run_until_complete(app.exchanges.fetch_balances())\n print(app.exchanges.balances_str)", "def get_balance(self, token_symbol):\n\n method = 'GET'\n endpoint = '/open/api/v2/account/info'\n\n headers = self.get_headers(request_type=method,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the trading fee for a certain pair on a certain exchange
def get_exchange_trading_fee(self, exchange, pair, type): return self.ccxt.get_exchange_trading_fee(exchange, pair, type)
[ "def get_fee(self, pair, order_type):\n fees = self.p_state._getvalue()['fees']\n if fees:\n\n return float(fees[self._handler[order_type]][pair]['fee'])\n\n else:\n\n return 0.0", "async def fetch_trading_fee(self, symbol: str, params={}):\n await self.load_marke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the market price for a certain pair on a certain exchange for a certain type(maker or taker)
def get_market_price(self, exchange, pair, type): return self.ccxt.get_market_price(exchange, pair, type)
[ "def get_price(self):\r\n try:\r\n self.price = self.exchange.symbol_ticker()\r\n except Exception as e:\r\n pass", "def get_price(coin, pairing):\n return client.get_ticker(symbol=coin+pairing)['lastPrice']", "def get_ticker(self, pair):\r\n method = self.public_en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Place an order through the ccxt library for a certain exchange, for a certain pair (BTC/USD), type as buy/sell, and amount in currency (if BTC/USD will be BTC)
def place_order(self, exchange, pair, type, amount, price = None): return self.ccxt.place_order(exchange, pair, type, amount, price)
[ "def place_order(self, asset, amount, order_type):\r\n \r\n pair = \"BTC_{}\".format(asset.ticker)\r\n\r\n if amount > 0:\r\n field = \"ask\"\r\n operation = \"buy\"\r\n else:\r\n field = \"bid\"\r\n operation = \"sell\"\r\n \r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the the data for a certain exchange for a given pair for the last 700 hours
def get_history_data(self, exchange, pair, timedelta): return self.ccxt.get_history_data(exchange, pair, timedelta)
[ "def get_historical_data(currency_pair, interval):\n logger.info('fetching historical data for {}'.format(currency_pair))\n b = exchange.return_chart_data(currency_pair, interval=interval, start=0, end=9999999999)\n return b", "def get_historical_order_book(api_key, url, exchange, pair, time):\n\n\t# set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used for loading in model and word2vec files from disk. Returns their objects.
def LoadSavedModels(main_model_path="main_model.pkl", cler_model_path="cler_model.pkl", word2vec_path='GoogleNews-vectors-negative300.bin'): model_main = joblib.load(main_model_path) model_cler = joblib.load(cler_model_path) word2vec = gensim.models.KeyedVector...
[ "def load_word2vec_model(self, filepath):\n self.word2vec_model = load_from_disk(filepath)", "def load_word2vec_vectors(self):\n logger.status_update(\"Loading vectors at {}...\".format(self.vector_file))\n model = KeyedVectors.load_word2vec_format(\n self.vector_file, binary=True\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predict a label using the main model (clinical, clerical or other). Input is a sentence, along w/ model object and word2vec object. These objects can either be loaded from disk using the LoadSavedModels function, or, if you have just completed training, they can be passed in from the Train.Trainer class. May also adjus...
def PredictLabel(sentence, model_main, word2vec, boundary=0.5): tokenized_sample = word_tokenize(re.sub("-"," ",sentence)) features = np.mean([word2vec.word_vec(w) for w in tokenized_sample if w in word2vec],axis=0) prediction = model_main.predict_proba(features.reshape(1,-1))[0] if model_main.clas...
[ "def PredictClerLabel(sentence, model_cler, word2vec):\n \n tokenized_sample = word_tokenize(re.sub(\"-\",\" \",sentence))\n features = np.mean([word2vec.word_vec(w) for w in tokenized_sample if w in word2vec],axis=0)\n prediction = model_cler.predict_proba(features.reshape(1,-1))[0]\n return model_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predict a label use the clerical model. Input is a sentence, along w/ model object and word2vec object. These objects can either be loaded from disk using the LoadSavedModels function, or, if you have just completed training, they can be passed in from the Train.Trainer class.
def PredictClerLabel(sentence, model_cler, word2vec): tokenized_sample = word_tokenize(re.sub("-"," ",sentence)) features = np.mean([word2vec.word_vec(w) for w in tokenized_sample if w in word2vec],axis=0) prediction = model_cler.predict_proba(features.reshape(1,-1))[0] return model_cler.classes_[p...
[ "def PredictLabel(sentence, model_main, word2vec, boundary=0.5):\n \n tokenized_sample = word_tokenize(re.sub(\"-\",\" \",sentence))\n features = np.mean([word2vec.word_vec(w) for w in tokenized_sample if w in word2vec],axis=0)\n prediction = model_main.predict_proba(features.reshape(1,-1))[0]\n if m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plots the fenics mesh as it is
def plot_fenics_mesh(mesh, new_fig=True): if(new_fig): plt.figure() plot(mesh) #plt.title("FEniCS mesh") plt.show(block=False) pass
[ "def DisplayMesh():\r\n \r\n # Load Surface Mesh Data and generate normals\r\n VTKString = OpenData('C:/Users/Tim/Documents/University/Year 4/Final Project/FinalYearProjectCode/TEH_Code/InputFiles','muscle_surface.vtk')\r\n header, Vertices, Triangles = CreateMatrixVTK(VTKString)\r\n \r\n fig = pl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plots the mesh/centroids of mesh as is expected in peridynamics either mesh or cell_cent is to be provided by user neither provinding mesh nor providing cell_cent is wrong
def plot_peridym_mesh(mesh=None, struct_grd=True, cell_cent=None, disp_cent=None, annotate=False): if struct_grd: cell_centroid_function = structured_cell_centroids else: cell_centroid_function = get_cell_centroids if mesh == None and len(np.shape(cell_cent)) == 0 and len(np.shape(disp_cent...
[ "def __init__(self, coordinates, triangles,\n boundary=None,\n tagged_elements=None,\n geo_reference=None,\n use_inscribed_circle=False,\n verbose=False):\n\n General_mesh.__init__(self, coordinates, triangles,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plots the displaced cell centroids after a solution step. Additionally retrns the final cell centroid after additon of displacement field in the orginal configuration
def get_displaced_soln(cell_cent, u_disp, horizon, dim, data_dir=None, plot_=False, save_fig=False, zoom=40): disp_cent = cell_cent + u_disp if plot_ or save_fig: dpi = 2 legend_size = {'size': str(6*dpi)} fig = plt.figure() if dim == 2: ax = fig.add_subplot(111) ...
[ "def plotcenterrange():\n plist1 = np.arange(0.02,0.1,0.02)\n plist = np.arange(0.1,1,0.1)\n infectlist = []\n for i in plist1:\n infectlist.append(checkinfectb(0.5,20000,30,200,p = i,q = np.sqrt(2/(20000*math.pi)),startcenter=True)[0])\n for i in plist:\n infectlist.append(checkinfectb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a structured cell centroids and cell volumes of square or cubic lattice using the fenics mesh by averaging appropriate number of 2D/3D triangles
def structured_cell_centroids(mesh): dim = mesh.topology().dim() stride = fact(dim) cents = get_cell_centroids(mesh) num_cells = int(mesh.num_cells()/stride) cell_cents_struct = np.zeros((num_cells,dim),dtype=float) for i in range(num_cells): start = int(stride*i) end = int(st...
[ "def __init__(self, coordinates, triangles,\n boundary=None,\n tagged_elements=None,\n geo_reference=None,\n use_inscribed_circle=False,\n verbose=False):\n\n General_mesh.__init__(self, coordinates, triangles,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates a 3D box mesh with tetrahedral elements with a cylindrical hole in it input
def box_mesh_with_hole(point1=Point(0,0,0), point2=Point(2,1,1), cyl_cent1 = Point(1, -10, 0.5), cyl_cent2= Point(1, 10, 0.5), cyl_rad=0.25, numpts=15): Router = mshr.Box(point1, point2) Rinner = mshr.Cylinder(cyl_cent1, cyl_cent2, cyl_rad, cyl_rad) domain = Router - Rinner mesh ...
[ "def make_box():\n vformat = GeomVertexFormat.get_v3n3t2()\n vdata = GeomVertexData('vdata', vformat, Geom.UHStatic)\n vdata.uncleanSetNumRows(24)\n\n vertex = GeomVertexWriter(vdata, 'vertex')\n normal = GeomVertexWriter(vdata, 'normal')\n tcoord = GeomVertexWriter(vdata, 'texcoord')\n\n axes ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the cell centroids lying within given geometric extents
def get_cell_centroid2(cents, extents): cells_in_ee = np.empty(0,int) for i in range(len(cents)): c = cents[i] if( (c > extents[0]).all() and (c <= extents[1]).all() ): cells_in_ee = np.append(cells_in_ee, [i], axis=0) return cells_in_ee
[ "def get_cell_centers(self):\r\n return np.mean(self.verts[:,:,:self.ndim], axis=1)", "def get_cell_center_spacings(self):\r\n dc = dc_min * np.ones(self.nedges, np.float64)\r\n for j in self.intern:\r\n ii = self.grd.edges[j]['cells'] # 2 cells\r\n xy = self.grd.cells[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a fenics mesh/mshr.mesh as argument, returns the centroid of the cells in the mesh input
def get_cell_centroids(mesh): num_els = mesh.num_cells() coords = mesh.coordinates() cells = mesh.cells() dim = len(coords[0]) cell_cent = np.zeros((num_els, dim), dtype=float, order='c') for i in range(num_els): pts = [coords[idx] for idx in cells[i]] cell_cent[i] = (1/(dim+1)...
[ "def get_cell_centers(self):\r\n return np.mean(self.verts[:,:,:self.ndim], axis=1)", "def structured_cell_centroids(mesh):\n dim = mesh.topology().dim()\n stride = fact(dim)\n cents = get_cell_centroids(mesh)\n num_cells = int(mesh.num_cells()/stride)\n cell_cents_struct = np.zeros((num_cel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a fenics mesh, this function returns the bounding_box that fits around the domain
def get_domain_bounding_box(mesh=None, cell_cent=None): def local_bbox_method(coords): dim = len(coords[0]) corner_min = np.zeros(dim ,float) corner_max = np.zeros(dim, float) for d in range(dim): corner_min[d] = min(coords[:,d]) corner_max[d] = max...
[ "def mesh_bounding_box(mesh):\n xyz = mesh.vertices_attributes(\"xyz\", keys=list(mesh.vertices()))\n return bounding_box(xyz)", "def get_mesh_bounding_box(self):\n return self.mesh.get_bounding_box()", "def bounds(self):\n return self._bboxes[0][0] #TODO: merge all coverages", "def get_boundin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a set of cell centroid beloning to regular (Square/Tri) discretization in 2D/3D, the method returns the edge length
def get_peridym_edge_length(cell_cent, struct_grd=False): dim = len(cell_cent[0]) el = np.zeros(dim, dtype = float) if(struct_grd): el_fact = 1.0 else: el_fact = 3.0 for d in range(dim): xx = np.unique(cell_cent[:,d]) el[d] = el_fact*np.max(np.abs(np.diff(xx[0:2])))...
[ "def edge_length(self):\n return 2 * self.cradius * sin(pi/self.edges)", "def calc_min_edge_length(self):\n min_edge_length = 10e10\n for elem in self.elems:\n a, b, c = elem\n ax = self.nodes[a][0]\n ay = self.nodes[a][1]\n bx = self.nodes[b][0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this method adds ghost layer to the mesh along the edges where bc is intended to be applied so that equivalent of peridynamic volume boundary condition is on the edge/bounary of the domain
def add_ghost_cells(mesh, bc_loc, num_lyrs,struct_grd=False): dim = mesh.topology().dim() dim_lst = [dd for dd in range(dim)] if(struct_grd): cell_cent = structured_cell_centroids(mesh) cell_vol = structured_cell_volumes(mesh) dist_fact = 1.0 mul = 1 #for struct grid ...
[ "def apply_boundary_conditions(self):\n E = self.__mesh.get_edge_list()\n\n # Top and bottom wall Dirichlet bcs (boundary_id = 21)\n \n e21_iterator = self.__mesh.edge_iterator(21)\n\n self.edge_center_value[e21_iterator[0]:e21_iterator[1]+1] = 0.0 \n \n # Left Dirichlet bc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns list of markers to be used for plt functions; max markers allowed = 18
def get_markers(num_markers): markers = ['^','o','P','X','*', 'd','<', '>', ',','|', '1','2','3','4','s','p','*','h','+'] if(num_markers>18): sys.exit("cannot create more than 18 markers, refactor your code; force exiting") return markers[0:num_markers]
[ "def get_markerstyles(n=None):\n all_markers = ['o', 'D', 's', '2', '*', 'h', '8', 'v', 'x', '+', 5, 'd', '>', 7, '.', '1', 'p', '3',\n 6, 0, 1, 2, 3, 4, '4', '<', 'H', '^']\n # Note: 0: 'tickleft', 1: 'tickright', 2: 'tickup', 3: 'tickdown', 4: 'caretleft', 'D': 'diamond', 6: 'caretup',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basic attach/detach IPv6 test with single UE
def test_attach_detach_ipv6(self): num_ues = 2 detach_type = [ s1ap_types.ueDetachType_t.UE_NORMAL_DETACH.value, s1ap_types.ueDetachType_t.UE_SWITCHOFF_DETACH.value, ] wait_for_s1 = [True, False] self._s1ap_wrapper.configUEDevice(num_ues) # Defaul...
[ "def test_mgre6(self):\n\n self.pg0.config_ip6()\n self.pg0.resolve_ndp()\n\n e = VppEnum.vl_api_tunnel_encap_decap_flags_t\n\n for itf in self.pg_interfaces[3:]:\n #\n # one underlay nh for each overlay/tunnel peer\n #\n itf.config_ip6()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Pandas DataFrame out of a .yaml file. Examples
def yaml_to_pandas(filename: str) -> Tuple[pd.DataFrame, Optional[str]]: # Read the yaml file with open(filename, 'r') as f: dict_ = yaml.load(f, Loader=yaml.SafeLoader) project = dict_.pop("__project__", None) # Convert the yaml dictionary into a dataframe data: Dict[str, Dict[Tuple[Hashab...
[ "def load_df(filename: str) -> dd.DataFrame:\n return dd.read_parquet(filename)", "def df_from_json(filepath):\n return pd.read_json(filepath)", "def test_init_project_yaml_dump(self):\n project_specs = pr.get_schema_specs('pysemantic')\n project = pr.Project(schema=project_specs)\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that all users belonging to an account are available in the .yaml input file. Raises a KeyError If one or more usernames printed by the ``accinfo`` comand are absent from df.
def validate_usernames(df: pd.DataFrame) -> None: _usage = check_output(['accinfo'], encoding='utf8') iterator = filter(None, _usage.splitlines()) for i in iterator: if i == "# Users linked to this account": usage = np.array(list(iterator), dtype=np.str_) break else: ...
[ "def load_users():\n try:\n # json file should be in the same file location as the function\n base_dir = os.path.dirname(__file__)\n abs_file = os.path.join(base_dir, 'users.json')\n\n with open(abs_file) as json_file:\n users = json.load(json_file, parse_float=Decimal)\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is our handler for the menu item. Our inItemRef is the refcon we registered in our XPLMAppendMenuItem calls. It is either +1000 or 1000 depending on which menu item is picked.
def MyMenuHandlerCallback(self, inMenuRef, inItemRef): if (self.DataRef != 0): """ We read the data ref, add the increment and set it again. This changes the nav frequency. """ X...
[ "def add_to_menu ( self, menu_item ):\r\n pass", "def customize_menu(self, menu, item):\n pass", "def _create_context_menu(self, menu, item):\n\n pass", "def getMenuItemID(self):\r\n return self.eventID", "def checkMenuItem(self):\r\n self.eventID, self.parameter, res = se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize the batch data, use coordinates of the block centered at origin,
def normalize_data(batch_data): B, N, C = batch_data.shape normal_data = np.zeros((B, N, C)) for b in range(B): pc = batch_data[b] centroid = np.mean(pc, axis=0) pc = pc - centroid m = np.max(np.sqrt(np.sum(pc ** 2, axis=1))) pc = pc / m normal_data[b] = pc ...
[ "def _normalize(self, dataset):\n if self.max is None: # if we are normalizing the training set\n self.max, self.min = dataset.max(), dataset.min() # find max, min value for each columns\n for row in dataset.index: # for each row in dataset\n for c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shuffle orders of points in each point cloud changes FPS behavior. Use the same shuffling idx for the entire batch.
def shuffle_points(batch_data): idx = np.arange(batch_data.shape[1]) np.random.shuffle(idx) return batch_data[:,idx,:]
[ "def shuffle_points(batch_data):\n idx = np.arange(batch_data.shape[1])\n np.random.shuffle(idx)\n return batch_data[:, idx, :]", "def shuffle_points(mutated_genome,index):\n random.shuffle(mutated_genome[index][2])", "def shuffle(self):\n self.inter_feat.shuffle()", "def shuffle(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomly shift point cloud. Shift is per point cloud.
def shift_point_cloud(batch_data, shift_range=0.1): B, N, C = batch_data.shape shifts = np.random.uniform(-shift_range, shift_range, (B,3)) for batch_index in range(B): batch_data[batch_index,:,:] += shifts[batch_index,:] return batch_data
[ "def shift(self):\n \"\"\"\n shift cluster randomly within bounds of im\n \"\"\"\n r = self.std\n mid = self.mid_pixel #center pixel index of 384x384 image\n delta = self.im_size - self.mid_pixel - r - 10\n \n x = np.random.randint(low=-1*delta,high=delta,size...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomly scale the point cloud. Scale is per point cloud.
def random_scale_point_cloud(batch_data, scale_low=0.8, scale_high=1.25): B, N, C = batch_data.shape scales = np.random.uniform(scale_low, scale_high, B) for batch_index in range(B): batch_data[batch_index,:,:] *= scales[batch_index] return batch_data
[ "def rand_scale(s):\n scale = np.random.uniform(low=1, high=s)\n if np.random.rand() > 0.5:\n return scale\n return 1 / scale", "def randomize_points(points, scale):\n randpoints = []\n\n for point in points:\n x, y, z = point[0], point[1], point[2]\n x = x + random.uniform(-sc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return list of id of unread emails
def get_unread_email_ids(gmail_client): response = gmail_client.users().messages().list(userId='me',q='is:unread').execute() if 'messages' in response: # messages key only exists if there are unread messages return [message['id'] for message in response['messages']] else: print("No unread m...
[ "def get_unread_email_ids(gmail_client):\n # response is [{'id':str, 'threadId':str},...]\n response = gmail_client.users().messages().list(userId='me', q='is:unread').execute()\n\n if 'messages' in response: # messages key only exists if there are unread messages\n ids = [message['id'] for message ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a k cluster data set with required separation. For the purposes of validating a proof, generate each cluster center such that it is at least 4 delta away from any other cluster for some value of delta > 0.
def gen_k_centers(k, dim): delta = abs(np.random.normal(0.0, 5.0)) eps = 0.001 centers = [] for i in range(k): c = np.random.multivariate_normal(np.zeros(dim), np.identity(dim)) if len(centers): c1 = centers[0] x = np.random.multivariate_normal(c1, np.identity(c1....
[ "def create_clusters(self):\n ex = 0\n print 'Iter - Purity Gini Index'\n while ex < self.MAX_ITERATION:\n new_clusters = np.zeros(self.centroids.shape)\n distances = euclidean_distances(self.vectors, self.centroids).argmin(axis=1)\n for i in ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a deltaseparated dataset. For each of the centers draw size number of points. No two points may be farther than delta away form each other. Thus, to generate each point, choosea random direction and random distance from the center (of up to 0.5 delta).
def _create_constrained_dataset(centers, delta, size): dataset = [] count = 0 for i, c in enumerate(centers): for j in range(size): x = np.random.multivariate_normal(c, np.identity(np.size(c))) - c direction = x / np.linalg.norm(x) magnitude = np.random.uniform(0....
[ "def generate_point_cloud(n:int, d:int = 2, seed=1234) -> np.ndarray:\n initial_seed = np.random.get_state()\n np.random.seed(seed)\n points = np.random.rand(n, d)\n np.random.set_state(initial_seed)\n return points", "def generate_data(points_number=1000, disk_radius=1.0 / (math.sqrt(2.0 * math.pi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a 5x5 grid of cluster centers. Create 25 cluster centers on the grid I^{[0, 4] x [0,4]}. Each center is a gaussian with standard covariance
def _5x5_grid_clusters(): return [mn(mean=np.array([i, j]), cov=np.array([[1.0, 0.0], [0.0, 1.0]])) for i in range(5) for j in range(5)]
[ "def _5x5_grid_clusters_spread():\n return [mn(mean=np.array([i * 25, j * 25]), cov=np.array([[1.0, 0.0],\n [0.0, 1.0]]))\n for i in range(5)\n for j in range(5)]", "def generate_centers(self):\n\t\tcenters = []\n\t\tsize = self.config....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a 5x5 grid of cluster centers. Create 25 cluster centers on the grid I^{[0, 4] x [0,4]}. Each center is a gaussian with standard covariance
def _5x5_grid_clusters_spread(): return [mn(mean=np.array([i * 25, j * 25]), cov=np.array([[1.0, 0.0], [0.0, 1.0]])) for i in range(5) for j in range(5)]
[ "def _5x5_grid_clusters():\n return [mn(mean=np.array([i, j]), cov=np.array([[1.0, 0.0],\n [0.0, 1.0]]))\n for i in range(5)\n for j in range(5)]", "def generate_centers(self):\n\t\tcenters = []\n\t\tsize = self.config.image_size\n\t\tfor i in ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create random cluster centers. Create n cluster centers randomly. Each cluster center is a draw from a gaussian distribution centered at (0,0) with standard covariance.
def _random_standard_centers(n=100): generator = mn(mean=np.array([0, 0]), cov=np.array([[1.0, 0.0], [0.0, 1.0]])) return [mn(mean=pt, cov=np.array([[1.0, 0.0], [0.0, 1.0]])) for pt in generator.rvs(size=n)]
[ "def random_centers(k,):\n #centr = np.random.random((k, pos.shape[1]))\n return", "def random_points_around_random_centroids(n, num_centroids, stdev, low, high):\n centroids = random_points(num_points=num_centroids, num_dimensions=2,\n low=low, high=high)\n\n for i in ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the path for userspecific blender scripts for all major platforms
def getScriptsPath(blenderversion): if sys.platform == 'linux': scriptspath = os.path.normpath( os.path.expanduser('~/.config/blender/{0}/scripts'.format(blenderversion)) ) elif sys.platform == 'darwin': scriptspath = os.path.normpath( os.path.expanduser( ...
[ "def getBlenderConfigPath(blenderversion):\n if sys.platform == 'linux':\n scriptspath = os.path.normpath(\n os.path.expanduser('~/.config/blender/{0}/config'.format(blenderversion))\n )\n elif sys.platform == 'darwin':\n scriptspath = os.path.normpath(\n os.path.exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the path for configuration data for all major platforms
def getConfigPath(): if sys.platform == 'linux': configpath = os.path.normpath(os.path.expanduser('~/.config/phobos')) elif sys.platform == 'darwin': configpath = os.path.normpath(os.path.expanduser('~/Library/Application Support/phobos')) elif sys.platform == 'win32': configpath = o...
[ "def _path_to_platform_data(self) -> VendorPlatformData:\n base = os.path.basename(self.xml_file).removesuffix('.xml')\n base = base.replace('capabilities', '').replace('capability', '').replace('netconf', '').strip('-')\n platform = base or 'Unknown'\n split_path = self.directory.split(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the configuration path for userspecific blender data.
def getBlenderConfigPath(blenderversion): if sys.platform == 'linux': scriptspath = os.path.normpath( os.path.expanduser('~/.config/blender/{0}/config'.format(blenderversion)) ) elif sys.platform == 'darwin': scriptspath = os.path.normpath( os.path.expanduser( ...
[ "def _config_path(self) -> str:\n return self._config_path_for(dir_path=self._dir_path)", "def config_file_and_path():\n return str(rmfriend_dir() / 'config.cfg')", "def get_config_file_location():\n\n return './' + CONFIG_FILE_NAME", "def get_data_path(name):\n js = open('config.json').read()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the area of each grid cell for a userprovided grid cell resolution. Area is in square meters, but resolution is given in decimal degrees.
def do_grid (resolution): # Calculations needs to be in radians lats = np.deg2rad(np.arange(-57,84, resolution)) r_sq = 6371000**2 n_lats = int(360./resolution) area = r_sq*np.ones(n_lats)[:, None]*np.deg2rad(resolution)*( np.sin(lats[1:]) - np.sin(lats[:-1])) return area.T
[ "def _define_area_of_grid_cells(self):\n for gloc in ['t','u','v','f']:\n self._arrays[\"cell_area_at_\" + gloc + \"_location\"] = \\\n self._arrays[\"cell_x_size_at_\" + gloc + \"_location\"] \\\n * self._arrays[\"cell_y_size_at_\" + gloc + \"_location\"]", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Integrate dy/dt = rhs_func from t=0 to t=num_days with y(0) = y0. Returns a list of state vectors, one for each day.
def integrate(rhs_func, y0, num_days, iterations_per_day): out = [y0.clone()] y = y0.clone() t = 0 dt = 1 / iterations_per_day for day in range(num_days): for it in range(iterations_per_day): y += dt * rhs_func(y, t) t += dt # y, t = RK4_step(rhs_func,y,...
[ "def integrateTransients(self, numdays=500):\n tend = numdays * 24.0\n\n r = sp.integrate.solve_ivp(self.derv, (0, tend), [0.7, 0.0, 0.0], t_eval=[tend], method='Radau')\n results_trans = np.transpose(r.y)\n\n return (results_trans[-1, :])", "def get_y(\n func: Callable[[int, SI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes a SOM or SO and goes through the individual spectra adjusting the bin contents by either multiplying or dividing by the bin widths or the bin centers taken from the individual spectra.
def fix_bin_contents(obj, **kwargs): import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: scale = kwargs["scale"] except KeyError: scale = False try: ...
[ "def bin_data(self, binsize):\n\n means = []\n stds = []\n bins = []\n nbins = []\n means_net = []\n stds_net = []\n\n for i in range(self.nfiles):\n # These need to be lists because there can be multiple entries\n # depending on bin size.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a feature vector for features given a certain task, model and similarity strategy
def _get_features(task, features, model, similarity_strategy=None): X = [] langs = analysis_utils.get_langs_for_task(task) for feature in features: if feature != "size": # this is a nested array X_feature = analysis_utils.load_lang2vec_vectors(task=task, features=feature) ...
[ "def create_feature_vector(self, task):\n vector = np.zeros(12)\n tmp = self.taskMap[task]\n premise_trees = tmp[1:]\n # more than two variables\n if len(tmp[0]) > 2:\n vector[0] = 1\n else:\n vector[0] = 0\n # check for literal premises\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that using a in filter with an empty list provided as input returns no objects.
def test_in_filter_with_empty_list(query): Pet.objects.create(name="Brutus", age=12) Pet.objects.create(name="Mimi", age=8) Pet.objects.create(name="Picotin", age=5) schema = Schema(query=query) query = """ query { pets (name_In: []) { edges { node { ...
[ "def is_empty(self,items):\n if type(items) == type([]):\n return len(items) == 0\n elif type(items) == type(Query()):\n return items.count() == 0\n else:\n assert False", "def test_only_nones(self):\n lst = [None, None, None]\n assert list_witho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test in filter o an choice field not using an enum (Film.genre).
def test_choice_in_filter_without_enum(query): john_doe = Reporter.objects.create( first_name="John", last_name="Doe", email="john@doe.com" ) jean_bon = Reporter.objects.create( first_name="Jean", last_name="Bon", email="jean@bon.com" ) documentary_film = Film.objects.create(genre="...
[ "def test_options(self):\r\n f = self.filters.BaseChoicesFilter(\"name\")\r\n f.get_choices = lambda: [(\"1\", \"one\")]\r\n\r\n self.assertEqual(f.options([\"values\"]), [(\"1\", \"one\")])", "def check_genres_filter(film_genres, filter_genres=None): \n if filter_genres is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test in filter on a choice field using an enum (Reporter.reporter_type).
def test_enum_in_filter(query): Reporter.objects.create( first_name="John", last_name="Doe", email="john@doe.com", reporter_type=1 ) Reporter.objects.create( first_name="Jean", last_name="Bon", email="jean@bon.com", reporter_type=2 ) Reporter.objects.create( first_name="Jane...
[ "def test_type_food_choices(self):\n self.report.type = FOOD\n self.assertEqual(self.report.get_type_display(), REPORT_TYPES[FOOD][1])", "def test_tipo_choices_feeling(self):\n self.report.type = FEELING\n self.assertEqual(self.report.get_type_display(), REPORT_TYPES[FEELING][1])", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle GET requests to park ProductCategorys resource
def list(self, request): product_category = ProductCategory.objects.all() # Support filtering ProductCategorys by area id # name = self.request.query_params.get('name', None) # if name is not None: # ProductCategories = ProductCategories.filter(name=name) serializer...
[ "def list_of_products_by_category(request, category_slug):\n\n categories = Category.objects.all()\n template = 'list_of_products_by_category.html'\n page = request.GET.get('page')\n category = get_object_or_404(Category, slug=category_slug)\n\n context = {'categories': categories,\n 'c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns True if event ends a possession, False otherwise
def is_possession_ending_event(self): pass
[ "def count_as_possession(self):\n if self.is_possession_ending_event:\n if self.seconds_remaining > 2:\n return True\n # check when previous possession ended\n prev_event = self.previous_event\n while prev_event is not None and not prev_event.is_poss...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns list of dicts with all stats for event
def event_stats(self): pass
[ "def event_stats(self):\n return self.base_stats", "def getEventAuditData(self):\n return {\n 'NewEvents': self.__stats_totalNewEvents, \n 'RemoveEvents': self.__stats_totalRemoveEvents\n }", "def event_dicts(self):\n events = []\n # We're assuming th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns team id for team on offense for event
def get_offense_team_id(self): pass
[ "def getSoccerEventTeamStatsID(self, eID):\r\n cursor = self.conn.cursor()\r\n query = \"\"\"\r\n SELECT id\r\n FROM soccer_event_team_stats\r\n WHERE event_id = %s and (is_invalid = false or is_invalid is Null);\r\n \"\"\"\r\n cursor....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns list of all events that take place as the same time as the current event
def get_all_events_at_current_time(self): events = [self] # going backwards event = self while event is not None and self.seconds_remaining == event.seconds_remaining: if event != self: events.append(event) event = event.previous_event # go...
[ "def get_curr_events(self):\n today = datetime.date.today()\n return self.s.query(Event).filter(Event.time > today).all()", "def getActiveEventsAtTime(self,time):\n\t\tres = []\n\t\tfor e in self.events:\n\t\t\tif(time-e.startTime>=0 and time-e.startTime<=e.duration ):\n\t\t\t\tres+=[e]\n\t\treturn ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns dict with list of player ids for each team with players on the floor for current event For all non subsitution events current players are just the same as previous event
def current_players(self): return self.previous_event.current_players
[ "def add_players_on_floor(self):\n for period in self.Periods:\n # set current players to be period starters\n current_players = period.Starters.copy()\n for pbp_event in period.Events:\n if pbp_event.is_substitution():\n coming_in = pbp_even...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the score margin from perspective of offense team before the event took place
def score_margin(self): if self.previous_event is None: score = self.score else: score = self.previous_event.score offense_team_id = self.get_offense_team_id() offense_points = score[offense_team_id] defense_points = 0 for team_id, points in score....
[ "def get_margin(self):\r\n return self.target - sum(self.cards)", "def Margin(self):\n s = self.margin\n assert s in range(1,6), \"Margin score out of bounds.\"\n if s == 1: return 'Poor'\n elif s == 2: return 'Near Poor'\n elif s == 3: return 'Medium'\n elif s =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns dict with lineup ids for each team for current event. Lineup ids are hyphen separated sorted player id strings.
def lineup_ids(self): lineup_ids = {} for team_id, team_players in self.current_players.items(): players = [str(player_id) for player_id in team_players] sorted_player_ids = sorted(players) lineup_id = "-".join(sorted_player_ids) lineup_ids[team_id] = line...
[ "def get_player_ids(self, lineup):\n return [p.player_id for p in self.get_players(lineup)]", "def _find_team_ids(self):\n\n url = self._match_url + self._summary_path\n response = urllib2.urlopen(url)\n html = response.read()\n soup = BeautifulSoup(html)\n\n # The charts...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the number of seconds that have elapsed since the previous event
def seconds_since_previous_event(self): if self.previous_event is None: return 0 if self.seconds_remaining == 720: # so that subs between periods for live don't have negative seconds return 0 if self.seconds_remaining == 300 and self.period > 4: # ...
[ "def time_remaining(self) -> float:\n\n return self.event.time - time.time()", "def secondsPassed(self)->int:\n return 0 if not self.used else int((datetime.utcnow() - self.firstAccessDate).total_seconds())", "def elapsed(self):\n return datetime.datetime.now() - self.start", "def seconds...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns True if the event takes place after an offensive rebound on the current possession, False otherwise
def is_second_chance_event(self): event = self.previous_event if isinstance(event, Rebound) and event.is_real_rebound and event.oreb: return True while not (event is None or event.is_possession_ending_event): if isinstance(event, Rebound) and event.is_real_rebound and eve...
[ "def is_possession_ending_event(self):\n pass", "def shooting(self):\r\n return not self.stopped", "def is_penalty_event(self):\n if hasattr(self, \"fouls_to_give\"):\n team_ids = list(self.current_players.keys())\n offense_team_id = self.get_offense_team_id()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns True if the team on offense is in the penalty, False otherwise
def is_penalty_event(self): if hasattr(self, "fouls_to_give"): team_ids = list(self.current_players.keys()) offense_team_id = self.get_offense_team_id() defense_team_id = ( team_ids[0] if offense_team_id == team_ids[1] else team_ids[1] ) ...
[ "def winningTeamPenalty(r):\n \n #Check if home or away had more goals at the 'event' time\n homecheck = int(r['about.goals.home'] > r['about.goals.away'])\n awaycheck = int(r['about.goals.away'] > r['about.goals.home'])\n \n #If home had more goals and the penalty was on the home team, set to 1\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns True if event is possession changing event that should count as a real possession, False otherwise. In order to not include possessions which a very low probability of scoring in possession counts, possession won't be counted as a possession if it starts with <= 2 seconds left and no points are scored before pe...
def count_as_possession(self): if self.is_possession_ending_event: if self.seconds_remaining > 2: return True # check when previous possession ended prev_event = self.previous_event while prev_event is not None and not prev_event.is_possession_endi...
[ "def is_possession_ending_event(self):\n pass", "def calc_is_new_position(self, game_state: dict):\n current_position = game_state['self'][3]\n if current_position in self.positions:\n return False\n else:\n return True", "def is_use_qps(self) -> bool:\n if self.qps > 0 and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print methods and doc strings. Takes module, class, list, dictionary, or string.
def info(object, spacing=10, collapse=1): methodList = [method for method in dir(object) if callable(getattr(object, method))] argList = [method for method in dir(object) if not callable(getattr(object, method))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "\n".join...
[ "def print_methods(obj: object) -> None:\n all_attributes = set(dir(obj))\n names_of_methods = set(\n filter(lambda atrr_name: callable(getattr(obj, atrr_name)), all_attributes)\n )\n methods = (getattr(obj, method_name) for method_name in names_of_methods)\n methods_names_and_docs = [(ful...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
download the HR2 from the sqlite DB
def download(self,connector,condition): c= connector.cursor() # condition = " WHERE DIF_ID=%d AND NUM=%d" % (difid,num) snew = buildSelect(self,'HR2',condition) # print snew c.execute(snew) lnames=[] for name,val in sorted(self.__dict__.iteritems()): lna...
[ "def download_hess_dr1_data():\n download_data_files(FILENAMES_HESS_DR1)", "def download():\r\n reader = GSODDataReader()\r\n year_list = range(2001, 2012)\r\n austin = reader.collect_data(year_list, exact_station=True,\r\n station_name='AUSTIN CAMP MABRY', state='TX', country='US')\r\n hous...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
download the DCC from the sqlite DB
def download(self,connector,condition): c= connector.cursor() snew = buildSelect(self,'DCC',condition) # print snew c.execute(snew) lnames=[] for name,val in sorted(self.__dict__.iteritems()): lnames.append(name) vobj=[] for row in c: # ...
[ "def dwnl_db(path):\n url = 'https://ftp.ncbi.nlm.nih.gov/blast/db/pdbaa.tar.gz'\n db_compressed = path + 'pdbaa.tar.gz'\n msg = \"Please note that downloading the database may take a while.\\n\\n\"\n msg += \"Click OK to start downloading the database.\"\n sg.popup(msg)\n # Download the Database\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
download the SETUP from the sqlite DB
def download(self,connector,condition): c= connector.cursor() snew = buildSelect(self,'SETUP',condition) # print snew c.execute(snew) lnames=[] for name,val in sorted(self.__dict__.iteritems()): lnames.append(name) vobj=[] for row in c: # ...
[ "def download_and_prepare(self):\n self._download_and_prepare()", "def download_and_preprocess(self):\n print('Preparing steering angle database.')\n print('Downloading...')\n self.download()\n print('Preprocessing...')\n self.preprocess()", "def setup_db(self):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the descriptor. `base_attr` is the name of an integer attribute that represents binary flags. `bitmask` is the binary value to toggle on `base_attr`.
def __init__(self, base_attr, bitmask): self.base_attr = base_attr self.bitmask = bitmask
[ "def flags(cls):\n\n assert cls.__bases__ == (object,)\n\n d = dict(cls.__dict__)\n new_type = type(cls.__name__, (int,), d)\n new_type.__module__ = cls.__module__\n\n map_ = {}\n for key, value in iteritems(d):\n if key.upper() == key and isinstance(value, integer_types):\n valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the backward pass of the hinge loss function
def test_hinge_loss_backward(): from your_code import HingeLoss X = np.array([[-1, 2, 1], [-3, 4, 1]]) w = np.array([1, 2, 3]) y = np.array([1, -1]) loss = HingeLoss(regularization=None) _true = np.array([-1.5, 2, 0.5]) _est = loss.backward(X, w, y) print(_est)
[ "def _backward(loss):\n\n loss.backward()", "def forward(self,y_out, y_truth): \n result = None\n #########################################################################\n # TODO: #\n # Implement the forward pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the forward pass of the squared loss function
def test_squared_loss_forward(): from your_code import SquaredLoss X = np.array([[-1, 2, 1], [-3, 4, 1]]) w = np.array([1, 2, 3]) y = np.array([1, -1]) loss = SquaredLoss(regularization=None) _true = 26.5 _est = loss.forward(X, w, y) print(_est)
[ "def forward(self,y_out, y_truth): \n result = (np.square(np.subtract(y_out, y_truth)))\n #########################################################################\n # TODO: #\n # Implement the forward pass and return the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the ability of the gradient descent algorithm to classify a linearly separable dataset.
def test_gradient_descent_blobs(): features, _, targets, _ = load_data('blobs') hinge = make_predictions(features, targets, 'hinge', None) # assert np.all(hinge == targets) # l1_hinge = make_predictions(features, targets, 'hinge', 'l1') # # assert np.all(l1_hinge == targets) # # l2_hinge =...
[ "def test_multiclass_gradient_descent_separable():\n from your_code import MultiClassGradientDescent\n\n np.random.seed(0)\n\n features = np.identity(4)\n targets = np.array(range(4))\n\n learner = MultiClassGradientDescent(loss='squared', regularization=None,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a client configured with the given MetaHttpClient
def __init__(self, metaHttpClient): self.httpClient = metaHttpClient
[ "def get_client_instance(opts={}, api_version=None):\n return get_client_class(api_version)(**opts)", "def get_httpx_client() -> httpx.Client:\n return httpx.Client(**CLIENT_PARAMETERS) # type: ignore", "def _obtain_http_client(hostname=METADATA_SERVER_HOSTNAME):\n return http.client.HTTPConnection(ho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Factory method to reate a new client from url and auth strategy.
def createClientFromUrl(url, authStrategy=None): return MetaClient(MetaHttpClient(url, authStrategy))
[ "def make_client(self, context):\n return Client(self.settings['client_routing'], context=context)", "def roster_client_factory(self):\r\n return RosterClient(self.settings)", "def make_client(instance):\n return None", "def create_client(self):", "def _get_suds_client(self, url,**kw):\r\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }