query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
send_approved_withdrawals_to_paypal_wallets fetches all processed and approved withdrawals and schedule them for sending to the client paypal wallet address
def send_approved_withdrawals_to_paypal_wallets(self) -> Optional[List[Future]]: try: wallet_transactions: List[WalletTransactionsModel] = WalletTransactionsModel.query( WalletTransactionsModel.is_verified == True, WalletTransactionsModel.is_settled == False).fetch_async().get_result...
[ "def sync_all_pending_payments(db):\n payins = db.all(\"\"\"\n SELECT pi.*\n FROM payins pi\n JOIN payin_transfers pt ON pt.payin = pi.id\n JOIN exchange_routes r ON r.id = pi.route\n WHERE pt.status = 'pending'\n AND r.network = 'paypal'\n \"\"\")\n prin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
do_send_to_client_wallet send the deposit to client wallet
def do_send_to_client_wallet(self, transaction: WalletTransactionsModel) -> Future: # requesting the user wallet wallet_instance: WalletModel = WalletModel.query( WalletModel.organization_id == transaction.organization_id, WalletModel.uid == transaction.uid).get_async().get_result() ...
[ "def deposit(self, amount):\n self.wallet += amount", "async def deposit(self, ctx, amount):\n data = await BonfideCoin(self.bot).get(ctx.guild.id, ctx.author.id)\n if data is None:\n await self.add_to_db(ctx.guild.id, ctx.author.id)\n\n data = await BonfideCoin(self.bot).ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add_approved_deposits_to_wallet fetches all processed deposits which are not yet settled and then adding them to the client wallet
def add_approved_deposits_to_wallet(self) -> Optional[List[Future]]: try: wallet_transactions: List[WalletTransactionsModel] = WalletTransactionsModel.query( WalletTransactionsModel.is_verified == True, WalletTransactionsModel.is_settled == False).fetch_async().get_result() ...
[ "async def fetch_deposits(self, code: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):\n request = {\n 'token_side': 'DEPOSIT',\n }\n return await self.fetch_deposits_withdrawals(code, since, limit, self.extend(request, params))", "def sen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a random meme.
def meme_rand(): img = None quote = None img = random.choice(imgs) quote = random.choice(quotes) path = meme.make_meme(img, quote.body, quote.author) return render_template('meme.html', path=path)
[ "def meme_rand():\n\n img = random.choice(imgs)\n quote = random.choice(quotes)\n print(f'This are the {quote} in the file')\n path = meme.make_meme(system_path, img, quote.body, quote.author)\n return render_template('meme.html', path=path)", "def random_gen(self):\n\t\ttypes = [\"Normal\", \"Robo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rebuild a list of coordinates from the original collection of shapes and the points obtained from the square process
def get_shapes_from_new_points(self, original_shapes, new_points): unik_points = list(self.point_shapes) new_s = [] for l in original_shapes: #coords, is_poly = (l[0].coords, False) if l.geom_type == 'MultiLineString' else (l.exterior.coords, True) coords = get_coords(l) ...
[ "def generate_all_shape_coord(self):\r\n for rotation in range(self.max_rotations):\r\n self.shape_coord.append(list(self.generate_shape_coord(rotation)))", "def __returnCoordinatesReshaped(self, newShape):\n returnCoordinates = self.gridContainer['gridCoord']\n returnCoordinates.shape = newSh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the mutual information between a data column (x) and the labels (y). The data column is a single attribute over all the examples (n x 1). Mutual information is the difference between the entropy BEFORE the split set, and the weightedaverage entropy of EACH possible split.
def mutual_information(x, y, weight): # INSERT YOUR CODE HERE # raise Exception('Function not yet implemented!') entY = entropy(y, weight) unique_values_x, counts = np.unique(x, return_counts=True) probabilities_x = counts/len(x) mapping_of_probabilities = zip(probabilities_x,unique_values_x...
[ "def mutual_information(x, y, weights, entropy_y=None):\r\n if entropy_y is None:\r\n entropy_y = entropy(y, weights)\r\n partitioned_x = partition(x)\r\n total_values = weighted_length(weights)\r\n entropy_x = 0\r\n for val in partitioned_x.keys():\r\n labels_for_val = [y[i] for i in p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements the classical ID3 algorithm given training data (x), training labels (y) and an array of attributevalue pairs to consider. This is a recursive algorithm that depends on three termination conditions 1. If the entire set of labels (y) is pure (all y = only 0 or only 1), then return that label 2. If the set of ...
def id3(x, y, weight, attribute_value_pairs=None, depth=0, max_depth=5): # INSERT YOUR CODE HERE. NOTE: THIS IS A RECURSIVE FUNCTION. # raise Exception('Function not yet implemented!') unique_labels, count_unique_labels = np.unique(y, return_counts = True) if attribute_value_pairs is None: ...
[ "def id3(x, y, attributes, max_depth, weights: list =None, attribute_values: dict=None, depth: int=0) -> dict:\r\n if len(y) == 0:\r\n raise Exception(\"No data passed\")\r\n if weights is None:\r\n weights = [1/len(y)]*len(y)\r\n if attribute_values is None:\r\n attribute_values = get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predicts the classification label for a single example x using tree by recursively descending the tree until a label/leaf node is reached. Returns the predicted label of x according to tree
def predict_example(x, tree): # INSERT YOUR CODE HERE. NOTE: THIS IS A RECURSIVE FUNCTION. # raise Exception('Function not yet implemented!') for attribute_keys, sub_tree in tree.items(): attribute = attribute_keys[0] value = attribute_keys[1] decision = attribute_keys[2] if...
[ "def predict(tree, x, y = []):\n\n\t#conditions of continuous and discrete features\n\tnode_id = 1 #initialize node identifier as first node under the root\n\twhile 1:\n\t\tnodes = tree[node_id]\n\n\t\tif nodes[0][5] == \"c\":\n\t\t\tif x[nodes[0][1]] <= nodes[0][2]:\n\t\t\t\tindex, node_id = 0, nodes[0][0] #set id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the average error between the true labels (y_true) and the predicted labels (y_pred) Returns the error = (1/n) sum(y_true != y_pred)
def compute_error(y_true, y_pred): # INSERT YOUR CODE HERE sum=0 n=len(y_true) for x in range(n): if(y_true[x]!=y_pred[x]): sum= sum+1 err = sum/n return err
[ "def mean_squared_error(ys_true, ys_pred):\n return 1 / ys_true.shape[0] * np.sum(np.power(ys_true - ys_pred, 2))", "def error_squared(true_labels, predicted_labels):", "def mean_squared_error(y_true, y_pred):\n mse = np.mean(np.power(y_true-y_pred,2))\n return mse", "def relative_mean_squared_error(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function checks if user in current session is allowed to update an item associated with a user_id_to_check
def user_is_authorized_to_update_item(user_id_to_check): if "authorized_user_id" in login_session: if int(user_id_to_check) == int(login_session["authorized_user_id"]): lib.debug_print("authorized") return True lib.debug_print("not authorized") return False
[ "def test_func(self):\n profile_id = self.get_object().id\n if self.request.user.id == profile_id:\n # then we can allow updating\n return True\n return False", "def admin_chk(user_id):\n if user_id == str(137974469896437760) or user_id == str(148798654688395265): ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
On get returns "delete profile" page to confirm if user really wants to delete their profile. On post deletes user profile. Note all user's ads will be automatically deleted as well because this is how database is setup (there is an automatic delete cascade for user>ad objects).
def delete_user_profile(): user = flask_login.current_user delete_user_profile_form = FlaskForm() if request.method == 'POST' and delete_user_profile_form.validate_on_submit(): if not user_is_authorized_to_update_item(user.id): flash("You are not authorized to update this page") ...
[ "def delete_profile(request):\n if request.method == 'POST':\n form = RemoveUser(request.POST)\n\n if form.is_valid():\n request.user.delete()\n auth.logout(request)\n messages.success(request, 'You have successfully deleted your account')\n return render...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns JSON for a single ad
def get_ad_json(ad_id): ad = database.get_ad_by_id(ad_id) if ad: return jsonify(database.ad_to_dict(ad, serialize=True)) return jsonify({})
[ "def get(self):\n rs = Con.getad_info()\n return jsonify({'result': rs})", "def show_ads(template_name, user_id=None):\n ads_html = list()\n search_filtering_parameters = get_search_filtering_parameters_from_request(request)\n if user_id:\n search_filtering_parameters[\"user_id\"] = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns JSON for all ads in a city (as per city_id)
def get_city_ads_json(city_id): ads = database.get_ads_by_city(city_id) list_of_ads_dictionaries = [database.ad_to_dict(ad, serialize=True) for ad in ads] return jsonify(list_of_ads_dictionaries)
[ "def get_all_city_facts(request, city_id):\n try:\n city_facts = CityFact.objects.filter(city=city_id)\n except CityFact.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = CityFactSerializer(city_facts, many=True)\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get ads_data data structure to be displayed in the list of ads. Filtering parameters are extracted from request.
def show_ads(template_name, user_id=None): ads_html = list() search_filtering_parameters = get_search_filtering_parameters_from_request(request) if user_id: search_filtering_parameters["user_id"] = user_id ads, total_number_of_ads, min_ad_idx_displayed, max_ad_idx_displayed = \ database...
[ "def getAds(self):\n \n ids = [id for id in self.db]\n \n results = etree.Element(\"results\")\n for id in ids:\n if (id.find(\"_design\") != -1):\n continue\n \n result = etree.Element(\"result\")\n data = self.db[id]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Debug helper function prints fields and values of request form
def print_request_form(input_request): f = input_request.form for key in f.keys(): for value in f.getlist(key): print key, ":", value
[ "def debug_task(self):\n print('Request: {0!r}'.format(self.request))", "def print_html_form ():\n print(\"content-type: text/html\\n\")\n print(HTML_TEMPLATE % {'SCRIPT_NAME':os.environ['SCRIPT_NAME']})", "def show_parameters(self):\n for p in self.parameters:\n print p", "def get_para...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates ad object from passed form and saves it to the database
def update_ad_from_form_info(ad, form): ad.text = form["ad_text"] ad.price_cents = int((float(form["ad_price"]) * 100)) ad.contact_email = form["contact_email"] # default to email for now ad.primary_contact = ad.contact_email ad.contact_name = str(form["contact_name"]) ad.contact_phone = str...
[ "def _edit(request, id, Form, secret_key=None):\n\n if not secret_key and not request.user.pk:\n raise Http404\n\n try:\n object = Ad.objects.get(pk=id, is_deleted=False)\n\n if not request.user.is_staff and ((not secret_key and (object.author != request.user or object.secret_key)) or (se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Debug helper function prints all fields of current login_session
def print_current_session(printing_on = options.DEBUG_PRINT_ON): if not printing_on: return print "current login_session: " for i in login_session: print str(i) + " : " + str(login_session[i])
[ "def info(self):\n print \"---SESSION DETAILS---\"\n print \"URL\",self.session.get_full_url()\n print \"HEADERS\",self.session.header_items()\n print \"METHOD\",self.session.get_method()\n print \"DATA\",self.session.get_data()\n print \"TYPE\",self.session.get_type()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs application in deployed configuration on Heroku
def run_heroku(): app.secret_key = "secret key" # used to sign sessions, need to change it to a properly generated key in production if not create_database.table_exists("user"): create_database.connect_to_db_and_populate_initial_data() populate_database.populate_application_test_data() #app...
[ "def run_web_prod():\n\n _execvp([\n \"gunicorn\", \"--config\", \"python:src.gunicorn_cfg\", \"src.wsgi:app\"\n ])", "def deploy():\n\n puts(blue(\"Deploying to Heroku.\"))\n local('git push heroku HEAD:master')\n\n # Run collectstatic on Heroku with the staging environment\n set_staging...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs application with debug on, normally to be used for local debugging and development
def run_debug(): app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # debug option to be sure updates are applied right away app.debug = True app.secret_key = "secret key" # used to sign sessions, need to change it to a properly generated key in production if options.LOCAL_HOST == options.LOCAL_HOST_WINDOWS...
[ "def set_debug_on():\n global _debug\n _debug = True\n print 'Debug on.'", "def debug_cli():", "def on_runDebugMenuItem_activate(self,*args):\n self.run_mode = \"Debug\"\n self.set_run_menu(running=True,status=\"Debugging...\",debug=True)\n self._ui.interpreter = piedit.interpreter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function reads all xml files in given full directory path Tokenize the tweets and also proprocess the tweets
def read_user_tweets(dir_path): tweet_dict = {} words = [] tokenize_dict = {} user_tweets = "" i = 0 cachedStopWords = stopwords.words("english") # print(cachedStopWords) #print stop words # loop over the user files for filename in os.listdir(dir_path): #skip files if it's not ...
[ "def gettweets(self, path):\n #tweet_folder = 'tweets'\n tweet_folder = 'tweets_analyze'\n tweet_folder1 = 'tweets'\n for (root, dirs, files) in os.walk(path):\n if \"content\" in root and \"nytimes\" not in root:\n for f in files:\n idstr = f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function open the txt file in the dir_path directory and extrats real gender of users. Returns all gender of username by dictionary
def read_truth_gender(dir_path): file = open(dir_path+"truth.txt", "r") lines = file.readlines() file.close gender_dict = {} for line in lines: user, gender, country = line.split(":::") gender_dict[user] = gender return gender_dict
[ "def get_user_data():\n f = open(\"ml-100k/u.user\", 'r')\n users = []\n for line in f.readlines():\n u = line.split(\"|\")\n u[0] = int(u[0])\n u[1] = int(u[1])\n\n gender = 0\n if u[2] == \"M\":\n gender = 1\n\n if u[1] > ageRange[1]:\n ageR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to MCU via serial port, sends bitrate selection packet
def connect(self, serial_port, can_bitrate): self.serial = serial.Serial( port=str(serial_port), baudrate=250000, timeout=1 ) try: self.serial.setDTR(True) time.sleep(0.2) self.serial.setDTR(False) time.sleep(2) self.serial.write(chr(self.supported_can_bitrates.index(int(can_bitrate))))...
[ "def send_traffic(serialport, pack):\n pack[0] = 0x01\n pack[1] = 0x00\n # print(pack)\n serialport.write(pack)", "def initSerial(self, port, baud, filename):\n if not self.connected:\n try:\n self.s = serial.Serial(port, baud)\n except Exception as e:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in the learning rate return and make a plot of the learning rate
def plot_learning_rate(result): avg_result = result.mean(0) ind = np.arange(len(avg_result)) + 1 plt.plot(ind, avg_result) plt.show()
[ "def learningRate_plot(history):\n learningRates = np.concatenate([epoch.get('lrs', []) for epoch in history])\n plt.plot(learningRates)\n plt.xlabel('Batch no.')\n plt.ylabel('Learning rate')\n plt.title('Learning Rate vs. Batch no.')", "def draw_learning_curve(numbers):\r\n \r\n plt.xlabel(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function for plotting the cost to go function in the meta mountain car environment, given the ctg table.
def ctg_table_helper(table, savedir=None): # Process the data for plotting x_gran, y_gran = table.shape[0], table.shape[1] X = np.arange(-1.2, 0.6, 1.8/x_gran) Y = np.arange(-0.07, 0.07, 0.14/y_gran) X,Y = np.meshgrid(X,Y) # Plotting fig = plt.figure() ax = fig.add_subplot(111, projectio...
[ "def abatement_cost_plotter(directory, gwp=34, discount_rate=0, gas_price=0):\n npv, emissions, techs = results_analysis_functions.results_analysis(directory, discount_rate, gas_price)\n files = [f for f in listdir(directory) if isfile(join(directory, f)) if '.json' not in f if 'Frame.p' not in f]\n with o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an HL7 string to a dictionary
def hl7_str_to_dict(s, use_long_name=True): #s = s.replace("\n", "\r") print(s) try: m = parse_message(s) return hl7_message_to_dict(m, use_long_name=use_long_name) except ParserError: return dict()
[ "def convert_to_dictionary(self, string):\n return json.loads(string)", "def get_dict(string: str) -> Dict[str, int]:\n splited = string[1:-1].split(\", \")\n my_dict = {}\n for i in splited:\n key, value = i.split(\":\")\n if key[0] == \"'\" and key[-1] == \"'\":\n key = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an HL7 message to a dictionary
def hl7_message_to_dict(m, use_long_name=True): if m.children: d = {} for c in m.children: name = str(c.name).lower() if use_long_name: name = str(c.long_name).lower() if c.long_name else name dictified = hl7_message_to_dict(c, use_long_name=use_lo...
[ "def hl7_str_to_dict(s, use_long_name=True):\n #s = s.replace(\"\\n\", \"\\r\")\n print(s)\n try:\n m = parse_message(s)\n return hl7_message_to_dict(m, use_long_name=use_long_name)\n except ParserError:\n return dict()", "def parse_msg(msg):\n subject = msg.get(\"Subject\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new argument. Same usage as ArgumentParser.add_argument
def add_argument(self, *args, **kwargs): if self.__parser is None: raise AttributeError("Already parsed") else: self.__parser.add_argument(*args, **kwargs)
[ "def add_arg(self, *args, **kwargs) -> argparse.Action:\n return self.parser.add_argument(*args, **kwargs)", "def add_argument(self, argument):\n self.arguments.insert_argument(argument)", "def add_argument_cmd(self, *args, **kwargs):\n pass", "def add_arg(self, name, alias=None, **attrib...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Polynomial interpolation in a table. points Interpolation table. The x values are in the first column (column 0), and by default, the y values are in the second column (column 1). The x values must be in ascending order, with no duplicates. x The value to interpolate. degree The degree of the interpolating polynomial. ...
def interpolate (points, x, degree, ycol=1, regions=[], xcol=0): if len (points) < 2 or degree < 1: raise Exception ('bad args!') degree = min (degree, len (points) - 1) # START. FIND SUBSCRIPT IX OF X IN ARRAY. #ix = _bisect (points, x, lambda x, p, xcol=xcol: cmp (x, p[xcol]))# - 1 ...
[ "def polyvals(x0, y0, x, deg=0):\n import numpy as np\n return np.polyval(np.polyfit(x0, y0, deg), x)", "def polyinterp(points, x_min_bound=None, x_max_bound=None, plot=False):\n no_points = points.shape[0]\n order = np.sum(1 - np.isnan(points[:, 1:3]).astype(\"int\")) - 1\n\n x_min = np.min(points...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the weighted power spectral density matrix. It's also called covariance matrix. With the dim parameters you can change the sort of the dims of the observation and mask, but not every combination is allowed.
def get_power_spectral_density_matrix( observation, mask=None, sensor_dim=-2, source_dim=-2, time_dim=-1, normalize=True, ): # ensure negative dim indexes sensor_dim, source_dim, time_dim = ( d % observation.ndim - observation.ndim for d in (sensor...
[ "def compute_sigma_weights(self, dim: int) -> Tuple[torch.Tensor, torch.Tensor]:", "def compute_sigma_weights(self, dim: int) -> Tuple[torch.Tensor, torch.Tensor]:\n\n lambd = self.compute_lambda(dim=dim)\n\n # Create covariance weights\n weights_c = torch.full(\n size=(2 * dim + 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates an LCMV beamforming vector.
def get_lcmv_vector(atf_vectors, response_vector, noise_psd_matrix): response_vector = np.asarray(response_vector) # TODO: If it is a list, a list of response_vectors is returned. K, F, D = atf_vectors.shape assert noise_psd_matrix.shape == (F, D, D), noise_psd_matrix.shape Phi_inverse_times_H = n...
[ "def calculLwmVl(self):\r\n self.lwmVl = sommeEnergetique(self.lrwmVl,self.lmwmVl)", "def glvvec(w):\n if GLOVE_CACHE != None:\n return GLOVE_CACHE[w]\n if w in GLOVE_VOCAB:\n i = GLOVE_VOCAB.index(w)\n return GLOVE_MAT[i]\n else:\n return np.zeros(GLVVEC_LENGTH)", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Phase correction to reduce distortions due to phase inconsistencies. We need a copy first, because not all elements are touched during the multiplication. Otherwise, the vector would be modified in place.
def phase_correction(vector): # w = W.copy() # F, D = w.shape # for f in range(1, F): # w[f, :] *= np.exp(-1j*np.angle( # np.sum(w[f, :] * w[f-1, :].conj(), axis=-1, keepdims=True))) # return w vector = np.array(vector, copy=True) vector[..., 1:, :] *= np.cumprod( n...
[ "def apply_phase(self, a):\n self.state[:, self.n + a] = ((self.state[:, self.n + a]\n + self.state[:, a]) % 2)", "def RestartVector(v, Q):\n m, n = Q.shape\n q0 = numpy.zeros(m)\n for i in xrange(n):\n q0 = q0 + v[i]*Q[:,i]\n \n q0Norm = Vector2No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies a beamforming vector such that the sensor dimension disappears. Although this function may seem simple, it turned out that using it reduced implementation errors in practice quite a bit.
def apply_beamforming_vector(vector, mix): assert vector.shape[-1] < 30, (vector.shape, mix.shape) return np.einsum('...a,...at->...t', vector.conj(), mix)
[ "def action_scaling_vecs(self):\n vel_vec = np.arange(1, self.specs['velocity_limits'][1] + 1, 1)\n\n acc_pos_vec = self.calc_acceleration_from_power(\n vel_vec, self.specs['power_limits'][1])\n acc_neg_vec = self.calc_acceleration_from_power(\n vel_vec, self.specs['power_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the MVDR beamforming vector described in [Souden2010MVDR]. The implementation is based on the description of [Erdogan2016MVDR]. The ref_channel is selected based of an SNR estimate. The eps ensures that the SNR estimation for the ref_channel works as long target_psd_matrix and noise_psd_matrix do not contain in...
def get_mvdr_vector_souden( target_psd_matrix, noise_psd_matrix, ref_channel=None, eps=None, return_ref_channel=False ): assert noise_psd_matrix is not None phi = stable_solve(noise_psd_matrix, target_psd_matrix) lambda_ = np.trace(phi, axis1=-1, axis2=-2)[..., None,...
[ "def get_lcmv_vector_souden(\n target_psd_matrix,\n interference_psd_matrix,\n noise_psd_matrix,\n ref_channel=None,\n eps=None,\n return_ref_channel=False\n):\n raise NotImplementedError(\n 'This is not yet thoroughly tested. It also misses the response vector,'\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In "A Study of the LCMV and MVDR Noise Reduction Filters" Mehrez Souden elaborates an alternative formulation for the LCMV beamformer in the appendix for a rank one interference matrix. Therefore, this algorithm is only valid, when the interference PSD matrix is approximately rank one, or (in other words) only 2 speake...
def get_lcmv_vector_souden( target_psd_matrix, interference_psd_matrix, noise_psd_matrix, ref_channel=None, eps=None, return_ref_channel=False ): raise NotImplementedError( 'This is not yet thoroughly tested. It also misses the response vector,' 'thus ...
[ "def DP_Pitch_Estimation(f0_candidates,score,nonDPindices,DPindices):\r\n \r\n rows=len(f0_candidates)\r\n cols=len(f0_candidates[0])\r\n pitch = np.zeros((1,rows))\r\n indsmax=np.argmax(score,axis=1)\r\n f0_candidates_dp = np.zeros((rows,cols))\r\n for m in np.arange(0,len(nonDPindices)):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of `DecompilationTest` with the given settings.
def create(self, test_settings): return DecompilationTest(self.decomp, test_settings)
[ "def create_drop(config):\r\n _logger.debug(\"initialize test plan\")\r\n \r\n test_plan = Ats3TestPlan(config)\r\n component_parser = acp.Ats3ComponentParser(config)\r\n \r\n for tsrc in config.tsrc_paths:\r\n lst_check_harness = []\r\n _logger.info(\"inspecting tsrc path: %s\" ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if GCC is run in the given arguments.
def is_gcc(self, args): # On Windows, GCC is run via `sh.exe windows-gcc-32` instead of `gcc`. if on_windows(): return len(args[0]) > 1 and args[0][1] == 'windows-gcc-32.sh' return args[0][0] == 'gcc'
[ "def checkDragonegg(self):\n if not self.checkDragoneggPlugin():\n return False\n\n pfx = ''\n if os.getenv('LLVM_GCC_PREFIX') is not None:\n pfx = os.getenv('LLVM_GCC_PREFIX')\n\n cc = f'{self.path}{pfx}gcc'\n cxx = f'{self.path}{pfx}g++'\n\n return s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the tested method so it succeeds.
def run_method_so_it_succeeds(self): raise NotImplementedError
[ "def _succeed(self):\n print(self.test_case + ': succeeded')\n exit(0)", "def test_case_passed(self):\n self.__set_test_case_result(result='PASSED', message='')", "def perform_checks(self) -> None:", "def run_post_test(self):\n pass", "def test_patch_run(self):\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solve a regularized and weighted least squares problem. If weights is a 1D array it is converted to 2D array with weights on the diagonal. If the penalty matrix is not ``None`` and nonzero, there is a closed solution. Otherwise the problem can be reduced to a least squares problem.
def solve_regularized_weighted_lstsq( coefs: NDArrayFloat, result: NDArrayFloat, *, weights: Optional[NDArrayFloat] = None, penalty_matrix: Optional[NDArrayFloat] = None, lstsq_method: LstsqMethod = lstsq_svd, ) -> NDArrayFloat: lstsq_method = _get_lstsq_method(lstsq_method) if lstsq_me...
[ "def weighted_least_squares(self, spec, weights):\n ww = weights.T # nwave x ntrain\n wx = ww[:, :, None] * self.X # nwave x ntrain x nfeature\n\n b = np.dot(self.X.T, weights * spec).T # nwave x nfeature\n # This is the time suck\n a = np.matmul(self.X.T, wx) # nwave x nfeature x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that the required version for the pod is met.
def verify_required_version(self): if self.pod.grow_version is None: return sem_current = semantic_version.Version(self.current_version) spec_required = semantic_version.Spec(self.pod.grow_version) if sem_current not in spec_required: text = 'ERROR! Pod requires G...
[ "def verify(self):\n self.installed_version = Version(VERSION)\n\n return check_version(self.installed_version, self.operator, self.version)", "def test_version_valid():\n assert type(packaging.version.parse(ertai.__version__)) is packaging.version.Version", "def check_version(self, required_ve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a set of all known properties, granted or denied.
def known_properties() -> set[str]: return set(session.session.execute( select(Property.name).distinct() ).scalars())
[ "def _get_properties(self, force=False):\r\n return self._portal.get_properties(force)", "def get_registered_properties():\n return _metaschema_properties", "def _permissions():\n return getattr(g, '_request_permissions', {})", "def getProperties(self):\n props = list(self._db.keys())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Grants a property to a group.
def grant_property(group: PropertyGroup, name: str) -> Property: group.property_grants[name] = True return group.properties[name]
[ "def create_property_group(name):\n return _create_group(\"property_group\", name=name)", "def create_property(name, property_group, granted):\n new_property = Property(name=name, property_group=property_group,\n granted=granted)\n session.session.add(new_property)\n return prop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Denies a property to a group.
def deny_property(group: PropertyGroup, name: str) -> Property: group.property_grants[name] = False return group.properties[name]
[ "def remove_property(group: PropertyGroup, name: str) -> None:\n if not group.properties.pop(name, None):\n raise ValueError(f\"Group {group.name} doesn't have property {name}\")", "def grant_property(group: PropertyGroup, name: str) -> Property:\n group.property_grants[name] = True\n return group...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a property association (grant or denial) with a given group.
def remove_property(group: PropertyGroup, name: str) -> None: if not group.properties.pop(name, None): raise ValueError(f"Group {group.name} doesn't have property {name}")
[ "def delete_property_group(property_group_id):\n return _delete_group(property_group_id)", "def remove_group(self, group):\n self.groups.remove(group)", "def delete_property(self, p=None, graph=None):\n if p:\n graph = self._clean_graph(graph) if graph else \"db:schema\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a user member of a group in a given interval. If the given interval overlaps with an existing membership, this method will join the overlapping intervals together, so that there will be at most one membership for particular user in particular group at any given point in time.
def make_member_of( user: User, group: PropertyGroup, processor: User, during: Interval[DateTimeTz] = t.cast( # noqa: B008 Interval[DateTimeTz], UnboundedInterval ), ) -> None: if group.permission_level > processor.permission_level: raise PermissionError("cannot create a member...
[ "async def _set_user_in_group_rooms(\n app: web.Application, user_id: UserID, socket_id: SocketID\n) -> None:\n primary_group, user_groups, all_group = await list_user_groups(app, user_id)\n groups = [primary_group] + user_groups + ([all_group] if bool(all_group) else [])\n\n sio = get_socket_server(app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a user from a group in a given interval. The interval defaults to the unbounded interval, so that the user will be removed from the group at any point in time, removing all memberships in this group retroactively. However, a common use case is terminating a membership by setting ``during=starting_from(now)``.
def remove_member_of( user: User, group: PropertyGroup, processor: User, during: Interval[DateTimeTz] = t.cast( # noqa: B008 Interval[DateTimeTz], UnboundedInterval ), ) -> None: if group.permission_level > processor.permission_level: raise PermissionError("cannot delete a memb...
[ "async def leave_group(self, userid):\n raise NotImplementedError()", "def group_disconnect(self, user: User): \n self.groups[user.group_name].disconnect_user(user)", "def remove_uptime(self, end):\n query = f\"DELETE FROM {self._schema}.uptime WHERE time < %s\"\n self.execute...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function to get stock data and send to kafka producer instance of a kafka producer symbol symbol of the stock, string type none
def fetch_price(producer, symbol): logger.debug('Start to fetch stock price for %s', symbol) try: engine = HexunEngine() requester = Requester(engine) stock_obj = requester.request(symbol) #print stock_obj[0].as_dict() price = json.dumps(stock_obj[0].as_dict()) logger.debug('Get stock info %s', price) p...
[ "def main():\n\n if len(sys.argv) < 2:\n print \"Usage: ./kafka_producer_stock.py stock-topic\"\n sys.exit(1)\n\n if len(sys.argv) >= 3:\n wait_time = float(sys.argv[2])\n else:\n wait_time = 0\n\n # Set up kafka brokers\n ipfile = open(ipfile_path, 'r')\n ips = ipfile.read()[:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes pyton code and converts it to a node node is then dealt with by node_to_gast
def py_to_gast(python_input): input_ast = '' try: input_ast = ast.parse(python_input) except: # this will signal to translate that error occurred return None return py_router.node_to_gast(input_ast)
[ "def handle_nodes(nodes):\n\t# Assumptions: the node() line is all one one line\n\n\tsplit_nodes = []\n\tcurnode = -1\n\tfor m in nodes:\n\t\tsplit_nodes.append({})\n\t\tcurnode += 1\n\n\t\t# TODO: make this a function call or something so i can change the node language more easily\n\t\t# no need to error check thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads binary feature data from a file and converts each sample into a list.
def load_data_bin(filePath): dataFile = open(filePath) data = [] labels = [] for sample in dataFile: fields = sample.strip('\n').split('\t') fields = [int(x) for x in fields] labels.append(fields[0]) data.append(fields[1:]) dataFile.close() return da...
[ "def generate_data(filename):\r\n filedata = np.genfromtxt(filename, dtype=None, delimiter=\",\")\r\n\r\n features = []\r\n class_list = []\r\n\r\n # For each row, add the last index to the class list, and all other entries to the feature list\r\n for i in filedata:\r\n sample = list(i)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This endpoint /events is called by the datepicker (census/static/datepicker/js/datepicker.js) to retrieve a list of filtered events by selected date/month.
def get_events(data): query_params = data.GET.dict() if not query_params: # If no payload is passed to the request, simply fetch future approved events start_date = datetime.now(timezone(TIMEZONE)) # TODO: When the user first visits the homepage, all events occurring # in ...
[ "def get_events():\n req = request\n start_date = request.args.get(\"start_date\")\n end_date = request.args.get(\"end_date\")\n desc = request.args.get(\"event_desc\")\n sqlx, sqlx_count = DBAccess.bld_query_sql(start_date, end_date, desc)\n \n list_result = DBAccess.get_events(sqlx, sqlx_coun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebases the given procedure and any nested procedures.
def update (self, procedure: Instruction) -> None: self.__rebase_instruction (procedure) for inst in procedure.instructions (): self.update (inst)
[ "def rebase_source_info (procedure: Instruction) -> ProcedureRecord:\n\n rebaser = _LineRebaser ()\n rebaser.update (procedure)\n return ProcedureRecord (procedure=procedure, line_base=rebaser.base ())", "def propositional_skeleton_helper(self, map):\n root = self.root\n\n if is_unary(root)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modifies an individual instruction so that its line number is relative to the start of its containing procedure. If this is the first instruction of the procedure, then it establishes the base value to be subtracted from subsequent instructions.
def __rebase_instruction (self, inst: Instruction) -> None: locn = inst.locn () if locn is not None: assert isinstance (locn, SourceLocation) if self.__base is None: assert locn.line is not None self.__base = locn.line assert locn.line...
[ "def rebase_source_info (procedure: Instruction) -> ProcedureRecord:\n\n rebaser = _LineRebaser ()\n rebaser.update (procedure)\n return ProcedureRecord (procedure=procedure, line_base=rebaser.base ())", "def adjust_relative_base(state, relative_base_ix):\n state.relative_base += state.intcode[relativ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebases the sourceline correspondence for a procedure such that all of the instructions are relative rather than absolute. That is, the original line numbers can be recovered by adding the 'base' line number to the source lines store in the instruction's location.
def rebase_source_info (procedure: Instruction) -> ProcedureRecord: rebaser = _LineRebaser () rebaser.update (procedure) return ProcedureRecord (procedure=procedure, line_base=rebaser.base ())
[ "def adjust_relative_base(state, relative_base_ix):\n state.relative_base += state.intcode[relative_base_ix]", "def __rebase_instruction (self, inst: Instruction) -> None:\n\n locn = inst.locn ()\n if locn is not None:\n assert isinstance (locn, SourceLocation)\n if self.__b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of days in the year.
def NumberDaysYear(year): return 365 + IsLeapYear(year)
[ "def days_in_year(year):\n\n return days_in_year(year)", "def elapsed_days(cls, year):\n months_elapsed = quotient(235 * year - 234, 19)\n parts_elapsed = 12084 + 13753 * months_elapsed\n days = 29 * months_elapsed + quotient(parts_elapsed, 25920)\n return days + 1 if mod(3 * (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of days in the month. If any of the arguments is missing (month or year) the current month/year is assumed.
def NumberDaysMonth(month = None, year = None): if month is None: m = time.localtime()[1] else: m = month if year is None: y = time.localtime()[0] else: y = year if m == 2: if IsLeapYear(y): return 29 else: return 28 e...
[ "def daysOfMonth(year, month):\r\n d = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\r\n if isLeap(year):\r\n d[1] += 1\r\n return d[month-1]", "def get_num_days_in_month(year, month):\n range = calendar.monthrange(year, month)\n return range[1]", "def day_of_month(self) -> Optional[pul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The initializer has an optional argument, time, in the time module format, wether as in seconds since the epoch (Unix time) wether as a tuple (time tuple). If it is not provided, then it returns the current date.
def __init__(self, tm = None): if tm is None: t = time.localtime() else: if isinstance(tm, int): t = time.localtime(tm) else: t = tm self.year, self.month, self.day = t[:3]
[ "def get_time_initializer(self):\n (_hour, _minute, _seconds,\n _month, _day_of_month, _year,\n gmt_offset, _DAYLIGHT_SAVINGS_ENABLED) = self._get_time()\n date_string = \"20\" + str(_year).zfill(2) + \"-\" + \\\n str(_month).zfill(2) + \"-\" + \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deep copy of Date objects.
def copy(self): ret = Date() ret.year, ret.month, ret.day = self.year, self.month, self.day return ret
[ "def copy(self) -> \"DataArray\":\n return deepcopy(self)", "def __get_dict_deep_copy(self):\n return copy(dict(self))", "def copy(self):\n return self.__class__( self.first, self.last )", "def copy(self):\n chart = Chart.__new__(Chart)\n chart.date = self.date\n char...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the year day of a date.
def GetYearDay(self): ret = self.day for month in range(1, self.month): ret += NumberDaysMonth(month, self.year) return ret
[ "def get_day_of_year(time: datetime) -> int:\n return time.timetuple().tm_yday - 1", "def get_year():\n\ttoday = datetime.today()\n\tif today.month==1 and today.day<=7:\n\t\treturn(today.year+1)\n\telse:\n\t\treturn(today.year)", "def liturgical_year(date):\n if date <= liturgical_year_end(date.year):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a (signed) number of days to the date.
def __add__(self, n): if isinstance(n, int): #Calculate julian day number and add n. temp = self.ToJDNumber() + n #Convert back to date format. return DateFromJDNumber(temp) else: raise TypeError, "%s is not an integer." % str(n)
[ "def incr_date(self, num_days=1):\n self.currentDate += timedelta(days=num_days)", "def add_days(self, day, days):\n if days < 0:\n sign = -1\n look_forward = False\n else:\n sign = 1\n look_forward = True\n\n if self.weekends:\n w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a COM time directly into the Date format.
def DateFromCOM(t): return Date(int(t))
[ "def convertTime(self,date,time):\n #Creates a datetime from the paramatised date and time\n #Create time object\n timeSplit = [int(i) for i in time.split(':')]\n timeObj = datetime.time(timeSplit[0], timeSplit[1]); #hours, minutes\n #Create date object\n currDate = date\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the retries of this V1beta1PipelineTask.
def retries(self, retries): self._retries = retries
[ "def http_client_retry_max_retries(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"http_client_retry_max_retries\")", "def max_retries(self, max_retries):\n\n self._max_retries = max_retries", "def _retry(self):\n # TODO(dcramer): this needs to handle too-many-retries itse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the run_after of this V1beta1PipelineTask.
def run_after(self, run_after): self._run_after = run_after
[ "def after(self, func: Action) -> AsyncAction:\n setattr(self, 'run_after', wrap_async(func))\n return self.run_after", "def end_date_after(self, end_date_after):\n\n self._end_date_after = end_date_after", "def onRunTaskCompletedEvent(self, event):\n\n # Ignore all other events\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the task_ref of this V1beta1PipelineTask.
def task_ref(self, task_ref): self._task_ref = task_ref
[ "def assignTask(self, task, document_id):\n return", "def set_task(self, task):\n self._environment.set_task(task)\n self._assertions()", "def put(self, task):\n self._input_tube.put((task,0))", "def task_uuid_gt(self, task_uuid_gt):\n\n self._task_uuid_gt = task_uuid_gt", "def re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the task_spec of this V1beta1PipelineTask.
def task_spec(self, task_spec): self._task_spec = task_spec
[ "def set_task(self, task):\n self._environment.set_task(task)\n self._assertions()", "def post_task_spec(self, task_yaml: dict) -> dict:\n return task_yaml", "def build_task_inputs_spec(\n task_spec: pipeline_spec_pb2.PipelineTaskSpec,\n pipeline_params: List[_pipeline_param.PipelineParam],\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the workspaces of this V1beta1PipelineTask.
def workspaces(self, workspaces): self._workspaces = workspaces
[ "def set_workspace(self, ws):\n if len(ws) == 0:\n self._g.set_workspace(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)\n else:\n if len(ws) == 4:\n self._g.set_workspace(ws[0], ws[1], 0.0, ws[2], ws[3], 0.0)\n else:\n if len(ws) == 6:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[Lib] Item acquisition dialog
def talk_m10_34_x15(lot1=_, flag2=_): """State 0,1: Item acquisition dialog: Display""" SetEventFlag(flag2, 1) AwardItem(lot1, 1) assert ItemAwardDisplay() != 0 """State 2: Item acquisition dialog: Wait""" assert ItemAwardDisplay() != 1 """State 3: End state""" return 0
[ "def dialog_handler_cb(self, item, data) -> None:\n # Dialog box initialization event\n if item == KDialogInitEvent:\n vs.SetItemText(self.dialog, self.kWidgetID_fileName, self.parameters.excelFileName)\n # vs.SetItemText(self.dialog, self.kWidgetID_imageFolderName, self.settings...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Number of edges between two node sets. nbunches should be SETS for efficiency. If nbunch1==nbunch2, return double the number of edges.
def n_edges_between(g, nbunch1, nbunch2): n = 0 #nbunch2 = set(nbunch2) if len(nbunch1) > len(nbunch2): nbunch1, nbunch2 = nbunch2, nbunch1 for n1 in nbunch1: for neighbor in g.adj[n1]: if neighbor in nbunch2: n += 1 return n
[ "def numConnectedEdges(*args, **kwargs):\n \n pass", "def testNumberEdges(g1, g2):\n return len(g1.edges) == len(g2.edges)", "def number_of_edges(self) -> int:\n count = 0\n for vertice in self.__graph:\n count += len(self.__graph[vertice])\n return count // 2", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a networkx graph, add all 'nodes' to 'cmtyID'.
def cmtyAddFromList(g, cmtyID, nodes): #print cmtyID, nodes #for n in g.nbunch_iter(nodes): for n in nodes: g.node[n]['cmtys'].add(cmtyID)
[ "def from_nodecmtys(cls, nodecmtys, **kwargs):\n cmtynodes = { }\n for n, c in nodecmtys.iteritems():\n cmtynodes.setdefault(c, set()).add(n)\n return cls.from_dict(cmtynodes=cmtynodes, **kwargs)", "def nodecmtys(self):\n if hasattr(self, '_ncmtys'):\n return self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a binary quadratic model encoding an integer.
def binary_encoding(v: Variable, upper_bound: int) -> BinaryQuadraticModel: # note: the paper above also gives a nice way to handle bounded coefficients # if we want to do that in the future. if upper_bound < 2: raise ValueError("upper_bound must be greater than or equal to 2, " ...
[ "def _quadratic_form(self):\n K = self.number_field()\n if K.degree() == 2:\n from sage.quadratic_forms.binary_qf import BinaryQF\n gens = self.gens_reduced()\n if len(gens) == 1:\n u, v = K.ring_of_integers().basis()\n alpha, beta = gens[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to assert if API creates user successfully
def test_api_can_create_user(self): self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)
[ "def test_endpoint_creates_user(self):\n new_user = {\n \"username\": \"maina\",\n \"password\": \"password123\"\n }\n response = self.client.post('/api/v1/auth/register', data=new_user)\n # status CREATED\n self.assertEqual(response.status_code, 201)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implementing three learning algorithms. backpropagation ("BP") using entire batch of samples stohastic backpropagation ("SBP") learning sample by sample minibatch backpropagation ("MBBP") learning by batches of smaller size (20)
def learning_algortihms(eta, samples, neural_net, choose_algorithm="BP"): if choose_algorithm == "BP": return backpropagation(eta, samples, neural_net) elif choose_algorithm == "SBP": nn = neural_net for sample in samples: nn = backpropagation(eta, sample, nn) return nn elif choose_algorithm == "MBBP": ...
[ "def batch_backprop(self, alpha, lamb, batch_size):\n # init derivated function\n if self.activation_type==1:\n derivative = lambda a: 1-ny.square(a)\n else:\n derivative = lambda a: a*(1.0-a)\n\n # init deltas\n delta_W = []\n delta_b = []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creating neural network based on architecture given by arch_numbers.
def create_network_architecture(arch_numbers): list_of_layers = [] for layer_index, number in enumerate(arch_numbers): list_of_neurons = [] for neuron_idx in range(number): if layer_index == 0: neuron = InputNeuron(numpy.array([])) else: neuron = Neuron(list_of_layers[layer_index-1]) list_of_neur...
[ "def makeNetwork(inputCount, hiddensCount, outputCount, initSetup=None, activationFn=fnSigmoid(1)):\n inputs = [INode(activationFn=activationFn) for _ in range(inputCount)]\n hiddens = [[Node(activationFn=activationFn) for _ in range(hn)] for hn in hiddensCount]\n outputs = [ONode(activationFn=activationFn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getting output out of neural network.
def get_neural_net_output(input, neural_net): for layer_index, layer in enumerate(neural_net): for neuron_idx, neuron in enumerate(layer): if layer_index == 0: neural_net[layer_index][neuron_idx].input = input[neuron_idx] neural_net[layer_index][neuron_idx].output = input[neuron_idx] else: neurons_...
[ "def getOutputNeuron(self):\n return self.outputNeuron", "def calculate_output(self):\n output = reduce(lambda ret, conn: ret + conn.upstream_node.output * conn.weight, self.upstream, 0.0)\n\n self.output = sigmoid(output)", "def evaluate(self, neural_network: NeuralNetwork) -> np.ndarray:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reconstruct a missing fragment from a subset of available fragments.
def reconstruct(self, available_fragment_payloads, missing_fragment_indexes): return self.ec_lib_reference.reconstruct( available_fragment_payloads, missing_fragment_indexes)
[ "def test_preserveFragments(self):\n self.assertEqual(\n client._urljoin(b\"http://foo.com/bar#frag\", b\"/quux\"),\n b\"http://foo.com/quux#frag\",\n )\n self.assertEqual(\n client._urljoin(b\"http://foo.com/bar\", b\"/quux#frag2\"),\n b\"http://foo....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine which fragments are needed to reconstruct some subset of missing fragments.
def fragments_needed(self, reconstruction_indexes, exclude_indexes=None): if exclude_indexes is None: exclude_indexes = [] return self.ec_lib_reference.fragments_needed(reconstruction_indexes, exclude_indexes)
[ "def prune_non_seg(self):\n self.fullsequence = self.sequence # First back up the original sequence\n self.fullvariantset = self.variantset\n self.fullvariants = self.variants\n self.sequence = MultipleSeqAlignment([]) # Blank the sequence to be worked on\n\n print \"\\nPruning ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get opaque metadata for a fragment. The metadata is opaque to the client, but meaningful to the underlying library. It is used to verify stripes in verify_stripe_metadata().
def get_metadata(self, fragment, formatted=0): return self.ec_lib_reference.get_metadata(fragment, formatted)
[ "def _get_metadata(self, artifact_hash: str) -> dict:\n return self._send({\"name\": \"getMetadata\", \"args\": [artifact_hash]})", "def metadata(self):\r\n metadataurlpath = 'content/items/' + self.itemid + '/info/metadata/metadata.xml'\r\n try:\r\n return self._portal.con.get(me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get segmentation info for a given data length and segment size.
def get_segment_info(self, data_len, segment_size): return self.ec_lib_reference.get_segment_info(data_len, segment_size)
[ "def get_segment_info_byterange(self, ranges, data_len, segment_size):\n\n segment_info = self.ec_lib_reference.get_segment_info(\n data_len, segment_size)\n\n segment_size = segment_info['segment_size']\n\n sorted_ranges = ranges[:]\n sorted_ranges.sort(key=lambda obj: obj[0]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get segmentation info for a byterange request, given a data length and segment size. This will return a mapofmaps that represents a recipe describing the segments and ranges within each segment needed to satisfy a range request. Assume a range request is given for an object with segment size 3K and
def get_segment_info_byterange(self, ranges, data_len, segment_size): segment_info = self.ec_lib_reference.get_segment_info( data_len, segment_size) segment_size = segment_info['segment_size'] sorted_ranges = ranges[:] sorted_ranges.sort(key=lambda obj: obj[0]) re...
[ "def getSegmentRanges(fullSize, segmentSize):\n overlapRatio = 1.1\n if fullSize <= segmentSize:\n return [(0, fullSize)]\n firstCenter = int(segmentSize/2)\n lastCenter = fullSize - int(segmentSize/2)\n assert lastCenter > firstCenter\n flexSize = lastCenter - firstCenter\n numSegments ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logs a message to the command line
def log(message): print(message)
[ "def log(message: str, level: int = logging.INFO):\n pipe.send(LogMessage(message, level))", "def log(self, message, log_type = Constants.LOG_CONSOLE):\n \n self.view.log(message, log_type)", "def log(self, msg):\n self.logger.write(msg)", "def write_to_console(self, message):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test parse of table of negocios realizados, compare parsed values versus a manually curated file.
def test__parse_add_negocios_realizados(self): print("_parse_add_negocios_realizados") id_test_cases = [0, 1, 2, 3, 4, 5, 6] for id_test in id_test_cases: in_case = hio.import_object_as_literal( os.path.join( path_data, f"_pars...
[ "def test__parse_resumo_dos_negocios(self):\n print(\"_parse_resumo_dos_negocios\")\n id_test_cases = [0]\n for id_test in id_test_cases:\n in_case = hio.read_strings(\n os.path.join(path_data, f\"_parse_resumo_dos_negocios_{id_test}.in\")\n )\n o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test parse of table of resumo dos negocios.
def test__parse_resumo_dos_negocios(self): print("_parse_resumo_dos_negocios") id_test_cases = [0] for id_test in id_test_cases: in_case = hio.read_strings( os.path.join(path_data, f"_parse_resumo_dos_negocios_{id_test}.in") ) out_case = hio.im...
[ "def test__parse_add_negocios_realizados(self):\n print(\"_parse_add_negocios_realizados\")\n\n id_test_cases = [0, 1, 2, 3, 4, 5, 6]\n for id_test in id_test_cases:\n in_case = hio.import_object_as_literal(\n os.path.join(\n path_data,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test parse of table clearing.
def test__parse_clearing(self): print("_parse_clearing") id_test_cases = [0] for id_test in id_test_cases: in_case = hio.read_strings( os.path.join(path_data, f"_parse_clearing_{id_test}.in") ) out_case = hio.import_object_as_literal( ...
[ "def clear_table(self):\n self.takes_table.setRowCount(0)\n self.takes_table.clearContents()", "def clear_table(self):\n self.clearContents()\n self.setRowCount(0)", "def empty():\n\n return EmptyTable()", "def handle_clear_table(self):\n \n self.number_of_rows = 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the quality tests over the given tables.
def execute(self, context): postgres = PostgresHook(self._ddbb_conn_id) for table in self._tables: if table not in self._available_tables: tables = ', '.join(self._available_tables) message = 'Only these tables are supported: {}'.format(tables) ...
[ "def test_qual_tab(self):\n self.check_fails(\"Quality/error_qual_tab.fastq\", 4)\n self.check_general_passes(\"Quality/error_qual_tab.fastq\", 5)", "def run_all(self):\n\n self.fill_table()\n\n self.traceback()\n\n self.alignment()\n\n self.total_score()", "def quality...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the blktrace program on remote machines.
def execute(ctx, config): procs = [] testdir = teuthology.get_testdir(ctx) log_dir = '/home/ubuntu/archive/performance/blktrace'#.format(tdir=testdir) osds = ctx.cluster.only(teuthology.is_type('osd')) for remote, roles_for_host in osds.remotes.iteritems(): roles_to_devs = config['remote_to...
[ "def remote_main(cls, sys_args, group):\n args = sys_args[1:]\n if len(args) != len(cls.args):\n raise ValueError(\"Usage: %s %s\" % (\n sys_args[0], \" \".join(cls.args)))\n for gw in group:\n for line in cls.remote_op(gw, args):\n print \"[%...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the total distance to table cost. input waypoint, output scalar cost
def table_cost(self, waypt): feature = self.environment.table_features(waypt) feature_idx = self.feat_list.index('table') return feature*self.weights[feature_idx]
[ "def distance(self, start, goal):\n ### START: 1e\n return self.cost_map[start]\n ### END: 1e", "def evaluate_solution(self, route):\n dist_matrix = self.dist_matrix\n prev = route[-1]\n total = 0.0\n for node in route:\n total += dist_matrix[prev][node]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the total coffee (EE orientation) cost. input waypoint, output scalar cost
def coffee_cost(self, waypt): feature = self.environment.coffee_features(waypt) feature_idx = self.feat_list.index('coffee') return feature*self.weights[feature_idx]
[ "def get_total_cost(self):\n cost = self.pizza_base.cost\n for topping in self.toppings:\n cost += topping.cost\n return cost", "def _calculate_cost(self):\n self.destination.set_parking_cost()\n self.cost_to_park = self.destination.parking_cost \n return self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replan the trajectory from start to goal given weights.
def replan(self, start, goal, goal_pose, weights, T, timestep, seed=None): assert weights is not None, "The weights vector is empty. Cannot plan without a cost preference." self.weights = weights waypts = self.trajOpt(start, goal, goal_pose, traj_seed=seed) waypts_time = np.linspace(0.0, T, self.num_waypts) ...
[ "def set_recurrent_weights(self, weights):\n self.w_rec.weight = nn.Parameter(torchify(weights))", "def lerp(self, end, weight): # real signature unknown; restored from __doc__\n pass", "def lerp_(self, end, weight): # real signature unknown; restored from __doc__\n pass", "def plan(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the least divisor of a number, above some floor.
def least_divisor(num, floor=2): assert num >= floor trial = floor while num % trial != 0: trial += 1 return trial
[ "def floor(n: float) -> int:\n return (int(n//1))", "def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n low, high = 1, max(nums)\n smallest = float('inf')\n while low <= high:\n mid = (low + high) // 2\n s = sum(ceil(num / mid) for num in nums)\n if s <= threshold:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if a number has a nontrivial divisor.
def has_nontrivial_divisor(num): divisor = least_divisor(num) return bool(divisor < num)
[ "def is_deficient_number(number: int) -> bool:\n return get_sum_of_divisors(number) < number", "def divisible(number, divisor):\n try:\n number = int(number)\n divisor = int(divisor)\n return number % divisor == 0\n except:\n return False", "def isDivisible(dividend: int, di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a cache of factorizations and precompute primes. bound the bound of numbers that the factorizer is expected to deal with.
def __init__(self, bound=10**6): self.bound = bound self.cache = {} self._update_primes()
[ "def prime_factors(n):\n if n >= (prime_set_max*prime_set_max):\n # this algorithm doesn't work\n print('prime_factors fails. Insufficient precomputed primes')\n return None\n n0 = n\n d = {}\n P = []\n while (n0 > 1):\n found = False\n for p in prime_set:\n q,r = divmod(n0,p)\n if r == 0:\n # p divides...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the list and set of primes, up to some bound.
def _update_primes(self): from math import ceil, sqrt # we only need primes up to sqrt(bound) because if none of those primes divide a number under bound, then bound must be prime if hasattr(self, "list_primes") and self.list_primes[-1] ** 2 > self.bound: return self.list_pr...
[ "def _grow_primes():\n global _primes\n global _primes_len\n global _primes_max\n val = _primes_max\n not_found = True\n while not_found:\n val += 1\n if all(map(lambda x: val % x != 0, _primes)):\n _primes.append(val)\n _primes_len += 1\n _primes_max = val\n not_found = False", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore the original number from a factorization.
def restore_from_factorization(factorization): retval = 1 for _base, _power in factorization.items(): retval *= int(_base) ** int(_power) return retval
[ "def restore(self):\n self.cur_val = self.max", "def revert_value(self):\r\n\r\n self.value_var.set(self.previous)", "def restore_value(self):\n\n self._value = self._saved_value.detach().clone()", "def restore_state(self):\n self._restore_input()\n self._restore_output()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the number of different divisors given a factorization.
def get_num_divisors(factorization): from functools import reduce powers = list(factorization.values()) num_divisors = reduce(lambda x, y: x * y, [_p + 1 for _p in powers]) return num_divisors
[ "def num_divisors(n):\n pf = prime_factorization(n)\n fc = frequency_count(pf).values()\n return product(f + 1 for f in fc)", "def get_number_of_divisors(x):\n if x == 1:\n return 1\n elif is_prime(x):\n return 2\n\n prime_decomposition = get_prime_decomposition(x)\n prime = pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all the divisors of a number given its factorization.
def get_all_divisors(factorization): divisors = [1] for _base, _power in factorization.items(): divisors = [ _div * (_base**_p) for _p in range(0, _power + 1) for _div in divisors ] return divisors
[ "def find_proper_divisors(number):\n validate_integers(number)\n results = find_factors(number)\n results.discard(number)\n return results", "def find_factors(num):\n validate_integers(num)\n zero_divisors_error(num)\n factors = set()\n for potential_factor in range(1, int(num**.5) + 1):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the sum of proper divisors given a factorization.
def get_sum_proper_divisors(factorization): sum_divisors = 1 original_number = 1 for _base, _power in factorization.items(): factors = [_base**k for k in range(0, _power + 1)] sum_divisors *= sum(factors) original_number *= _base**_power return sum_divisors - original_number
[ "def get_num_divisors(factorization):\n from functools import reduce\n\n powers = list(factorization.values())\n num_divisors = reduce(lambda x, y: x * y, [_p + 1 for _p in powers])\n return num_divisors", "def sum_of_divisors(n):\n return reduce(mul, ((p ** (k + 1) - 1) / (p - 1) for p, k in fact...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a factorization dict, determine if the original number is a prime.
def is_prime_given_factorization(factorization): if len(factorization.keys()) == 1: if list(factorization.values())[0] == 1: return True return False
[ "def is_prime(number):\n division = 2\n while number % division != 0:\n division += 1\n if division == number:\n return True\n return False", "def is_factor(n, f):\n return n % f == 0", "def is_prime_power(n):\n if len(factor(n)) == 1:\n return True\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute all the prime numbers below a bound.
def all_primes_under(bound): def is_prime_with_cache(num, cache): """ This is a subroutine for dynamic programming. Given a cache of primes below the square root of a number, determine if it is prime. The cache must be of ascending order. """ from math import sqrt, c...
[ "def compute_primes(bound):\r\n \r\n answer = list(range(2, bound))\r\n for divisor in range(2, bound):\r\n for i in answer:\r\n if i % divisor == 0 and not i == divisor:\r\n answer.remove(i)\r\n\r\n return answer", "def main(bound):\n\n # Generates a list such that...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a subroutine for dynamic programming. Given a cache of primes below the square root of a number, determine if it is prime. The cache must be of ascending order.
def is_prime_with_cache(num, cache): from math import sqrt, ceil for _p in cache: if _p > ceil(sqrt(num)): break if num % _p == 0: return False cache.append(num) return True
[ "def isprime_generator_lazy(number):\n if number < 2: return False\n if number == 2: return True\n if number % 2 == 0: return False\n return not any(\n number % p == 0 \n for p in range(3, int(math.sqrt(number)) + 1, 2)\n )", "def is_probable_prime(n):\n # return all(solovay_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all permutations of digits between m and n, in string form.
def permutations_m_to_n_str(bound_m, bound_n): def add(perms, new_digit): """ Add a digit to existing permutations. Assumes that all existing permutations have the same length. """ # base case: no permutation so far if not perms: return [new_digit] ...
[ "def nth_lex_permutation(n, digits):\n\n perms = []\n result = \"\"\n\n # generate list of permutations\n for i in itertools.permutations(range(digits)):\n perms.append(i)\n\n # join the answer together\n for j in perms[n - 1]:\n result += str(j)\n\n return int(result)", "def ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a digit to existing permutations. Assumes that all existing permutations have the same length.
def add(perms, new_digit): # base case: no permutation so far if not perms: return [new_digit] # common case perm_length = len(perms[0]) retlist = [] for _perm in perms: new_perms = [ (_perm[:i] + new_digit + _perm[i:]) for i in ran...
[ "def add(tile):\n if tile not in permutation:\n permutation.append(tile)", "def nth_lex_permutation(n, digits):\n\n perms = []\n result = \"\"\n\n # generate list of permutations\n for i in itertools.permutations(range(digits)):\n perms.append(i)\n\n # join the answer toget...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the first n hexagonal numbers.
def get_hexagonals(num): return [int(i * (2 * i - 1)) for i in range(1, num + 1)]
[ "def create_hexagon_numbers(limit):\n hexagons = {0}\n increment = 1\n value = 0\n while True:\n value += increment\n increment += 4\n if value > limit:\n break\n hexagons.add(value)\n return hexagons", "def rand_hex_color(n=1):\n\n colors = [\n RGB_to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }