query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
A wrapper to fit a gp using the dataset. | def fit_se_gp_with_dataset(dataset, method='slice'):
options = load_options(euclidean_gp_args)
options.kernel_type = 'se'
if method is not None:
options.hp_tune_criterion = 'post_sampling'
options.post_hp_tune_method = method
ret_fit_gp = (EuclideanGPFitter(dataset[0], dataset[1],
... | [
"def fit(self, X):\n self.sgd.fit(X, y)",
"def fit_matern_gp_with_dataset(dataset, nu=-1.0, method='slice'):\n options = load_options(euclidean_gp_args)\n options.kernel_type = 'matern'\n options.matern_nu = nu\n if method is not None:\n options.hp_tune_criterion = 'post_sampling'\n options.post_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A wrapper to fit a GP with a matern kernel using the dataset. | def fit_matern_gp_with_dataset(dataset, nu=-1.0, method='slice'):
options = load_options(euclidean_gp_args)
options.kernel_type = 'matern'
options.matern_nu = nu
if method is not None:
options.hp_tune_criterion = 'post_sampling'
options.post_hp_tune_method = method
ret_fit_gp = (EuclideanGPFitter(data... | [
"def fit_nngp_with_dataset(dataset, kernel_type, dist_type):\n options = load_options(nn_gp.nn_gp_args, '')\n options.kernel_type = kernel_type\n options.dist_type = dist_type\n gp_fitter = nn_gp.NNGPFitter(dataset[0], dataset[1], dataset[-1],\n options=options, reporter=None)\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests for prediction on a test set with an SEGP using slice sampling. | def test_se_prediction_slice(self):
self.report('Prediction for an SE kernel using slice sampling. '
'Probabilistic test, might fail.')
self._prediction_test(build_se_gp_with_dataset, fit_se_gp_with_dataset,
'naive', 'sampling-fit', 'direct-fit', 'se') | [
"def test_matern_prediction_slice(self):\n self.report('Prediction for an Matern kernel using slice sampling. '\n 'Probabilistic test, might fail.')\n self._prediction_test(build_matern_gp_with_dataset, fit_matern_gp_with_dataset,\n 'naive', 'sampling-fit', 'direct-fit'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests for prediction on a test set with an SEGP using nuts sampling. | def test_se_prediction_nuts(self):
self.report('Prediction for an SE kernel using nuts sampling. '
'Probabilistic test, might fail.')
self._prediction_test(build_se_gp_with_dataset, fit_se_gp_with_dataset,
'naive', 'sampling-fit', 'direct-fit', 'se', 'nuts') | [
"def test_se_prediction_slice(self):\n self.report('Prediction for an SE kernel using slice sampling. '\n 'Probabilistic test, might fail.')\n self._prediction_test(build_se_gp_with_dataset, fit_se_gp_with_dataset,\n 'naive', 'sampling-fit', 'direct-fit', 'se')",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests for prediction on a test set with an Matern GP using slice sampling. | def test_matern_prediction_slice(self):
self.report('Prediction for an Matern kernel using slice sampling. '
'Probabilistic test, might fail.')
self._prediction_test(build_matern_gp_with_dataset, fit_matern_gp_with_dataset,
'naive', 'sampling-fit', 'direct-fit', 'matern... | [
"def test_se_prediction_slice(self):\n self.report('Prediction for an SE kernel using slice sampling. '\n 'Probabilistic test, might fail.')\n self._prediction_test(build_se_gp_with_dataset, fit_se_gp_with_dataset,\n 'naive', 'sampling-fit', 'direct-fit', 'se')",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests for prediction on a test set with an Matern GP using nuts sampling. | def test_matern_prediction_nuts(self):
self.report('Prediction for an Matern kernel using nuts sampling. '
'Probabilistic test, might fail.')
self._prediction_test(build_matern_gp_with_dataset, fit_matern_gp_with_dataset,
'naive', 'sampling-fit', 'direct-fit', 'matern',... | [
"def test_se_prediction_nuts(self):\n self.report('Prediction for an SE kernel using nuts sampling. '\n 'Probabilistic test, might fail.')\n self._prediction_test(build_se_gp_with_dataset, fit_se_gp_with_dataset,\n 'naive', 'sampling-fit', 'direct-fit', 'se', 'nuts')",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates with predefined patterns and sets an email attribute for user object | def email(self, value):
match = email_pattern(value)
if match:
self._email = value
return
assert 0, 'Invalid email' | [
"def validate_email( self ):\n if self.email_verified_lower != self.email_pending_lower:\n if self.email_verified:\n # Remove the old unique email value\n values = [ '%s.%s:%s' % ( self.__class__.__name__, 'email',\n self.email... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates with predefined patterns and sets password attribute for user object | def password(self, value):
match = password_pattern(value)
if match:
self._password = Bcrypt().generate_password_hash(value).decode()
return
assert 0, 'Invalid password' | [
"def validate_password(self, value):\n validate_password(value)\n return value",
"def update_password(self):\n\n user = CustomUser.objects.get(username=self.cleaned_data.get(\"username\"))\n if user is not None:\n # change the user's password to be the new password\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
defines passport attribute for user object | def passport(self):
return self._passport | [
"def set_admin_user(self, user, password):\n\n self.user = user\n self.password = password",
"def passport(self, passport):\n if (len(passport) == 6) and self.all_digits(passport):\n self.__passport = passport\n else:\n print(\"Error! Passport number has to be a s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reverses the move of the piece | def reverse_move(self):
self.arr = self.arr_old.copy()
self.position = self.position_old.copy() | [
"def reverse_move(self, show=False):\n\n last_move = self.moves.pop()\n self.state[last_move[1]] = 0 # Removes last move from board\n self.turn = next(self.player_iterator) # TODO: Only works for 2 player games!\n self.check_if_game_over()",
"def reverse_move(self, show=False):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the board adding piece array to board array | def update(self, piece):
x, y = piece.position[0], piece.position[1]
self.board[x:x+piece.arr.shape[0], y:y+piece.arr.shape[1]] += piece.arr | [
"def set_piece(x, y, new_val):\n # Want to edit the global copy\n global board\n\n board[x][y] = new_val",
"def update_pieces(self, new_pieces):\n self.pieces = new_pieces",
"def set_piece(self, row, col, new_piece):\n self.board[row][col] = new_piece",
"def update_pieces(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if there are any possible moves for the seleceted piece | def has_moves(self, piece):
# loop through all the moves and flag if any is possible
moves = [piece.move_left, piece.move_right, piece.rotate_clockwise, piece.rotate_counter_clockwise]
available = []
for move in moves:
move()
available.append(self.is_vali... | [
"def check_move(self):\n\n if self.DEBUG_PRINT_FUNCTIONS:\n pass;\n print \"check_move\"\n\n if len(self.square) != 1 or self.piece == None:\n if self.DEBUG:\n print \"missing piece or square!\"\n return 5\n sqr_cords = self.c.coords(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays the board on the screen with the current piece position | def show(self, piece):
x, y = piece.position[0], piece.position[1]
screen_board = self.board.copy()
# add the piece to the board array
screen_board[x:x+piece.arr.shape[0], y:y+piece.arr.shape[1]] += piece.arr
# prepare string representation of the array
screen = [''.joi... | [
"def drawBoard(self):\n\n # \"board\" is a list of 10 strings representing the board (ignore index 0)\n print(' | |')\n print(' ' + self.board[7] + ' | ' + self.board[8] + ' | ' + self.board[9])\n print(' | |')\n print('-----------')\n print(' | |')\n pri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tile age by the count value in df | def tile_age(df, year=None):
if year:
idx = df.date == pd.to_datetime(year)
population_age = df[idx].age.repeat(df[idx].value).reset_index(drop=True)
else:
population_age = df.age.repeat(df.value).reset_index(drop=True)
return population_age | [
"def age_pivot_table(age_df):\n # Group by heiarchical sorting.\n age_pivot_ser = age_df.groupby(by=['year', 'county', 'age',\n 'weight_indicator'\n ]\n ).birth_count.sum()\n\n # Unstack Series to ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace "Post study Work Rights with Graduate visa | def swap_pswr_graduate(visa_summary):
if visa_summary.index.str.lower().str.contains("post"):
index_values = pd.Series(visa_summary.index.values).replace({"post study work rights": "Graduate visa"})
visa_summary.index = index_values.values
return visa_summary | [
"def reducedPublication (\n\n self,\n text = None\n ) :\n\n text = self.separatorsToSpaces( text )\n\n if len( text ) == 0 : return \"\"\n\n result = \"\"\n\n # this is an acronym\n\n if ( text.isupper() ) and ( text.isalpha() ) and ( not \" \" in text ) :\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make an emacs buffer `window` can be one of `None`, 'current' or 'other'. | def _make_buffer(self, name, contents, empty_goto=True, switch=False,
window='other', modes=[], fit_lines=None):
new_buffer = lisp.get_buffer_create(name)
lisp.set_buffer(new_buffer)
lisp.toggle_read_only(-1)
lisp.erase_buffer()
if contents or empty_goto:
... | [
"def make_context(window):\n glfw.make_context_current(window)",
"def SoWindowElement_set(state: 'SoState', window: 'void *', context: 'void *', display: 'void *', action: 'SoGLRenderAction') -> \"void\":\n return _coin.SoWindowElement_set(state, window, context, display, action)",
"def change_focus(windo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate a confidence score for the search results given the search result vectors. The confidence score is given on the basis of cosine similarity among the vectors. If the standard deviation of the similarity is high, confidence score is low, and if it is low, confidence score is high. | def calc_confidence_score(vecs):
# calculate vector magnitudes for normalizing
norms_squared = 0.00001 + (vecs*vecs).sum(axis=1, keepdims=True)
# 2d matrix where element i,j is cosine similarity between
# vectors i and j
sims = np.dot(vecs, vecs.T) / norms_squared
# calculate the standard... | [
"def cosine_score(self):\n for i in self.all_results: \n length = 0\n for j in self.all_results[i]:\n\n length += self.all_results[i][j] ** 2\n length = math.sqrt(length)\n \n for j in self.all_results[i]:\n self.all_res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if an item is a Cooperative Patent Classification code. Should also work for IPC codes because they have same format. | def is_cpc_code (item):
if not isinstance(item, str):
return False
pattern = r'^[ABCDEFGHY]\d\d[A-Z]\d+\/\d+$'
return True if re.fullmatch(pattern, item) else False | [
"def test_code_to_category_non_patient(self):\n # Non-patient Object Storage, PS3.4 Annex GG\n c2c = code_to_category\n\n assert c2c(0x0000) == \"Success\"\n for code in [0xA700, 0xA900, 0xC000]:\n assert c2c(code) == \"Failure\"",
"def test_code_to_category_relevant_patient... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a string is a publication number for a patent or an application. | def is_patent_number (item):
if not isinstance(item, str):
return False
pattern = r'^[A-Z]{2}\d+[A-Z]\d?$'
return True if re.fullmatch(pattern, item) else False | [
"def isISBN(code):\n # first and last group should contain a single digit\n if code[1] != '-' or code[-2] != '-' or code[6] != '-' or code.count('-') != 3:\n return False\n code = code.split('-')\n code = ''.join(code)\n if not (\n len(code) == 10 and # code must contain 10 chara... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a given word is a generic word, e.g., 'the', 'of', etc. It is determined on the basis of a handpicked list of keywords determined as generic words commonly used in patents. | def is_generic(word):
return True if word in stopword_dict else False | [
"def is_word(word):\n return (True in (wordtype(word)))",
"def HasWord(self, word):\n ## use Pythons in keyword to do this\n return word in self.WORDS",
"def known(self, word):\n return word in self.word_dict",
"def containsKeyWords(keywords, enumeration):\n #flatten the enumera... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Split a text into paragraphs. Assumes paragraphs are separated by new line characters (\n). | def get_paragraphs(text):
return [s.strip() for s in re.split("\n+", text) if s.strip()] | [
"def _split_paragraphs(self, text):\n\n import re\n import textwrap\n\n text = textwrap.dedent(text).strip()\n text = re.sub('\\n\\n[\\n]+', '\\n\\n', text)\n\n last_sub_indent = None\n paragraphs = list()\n for line in text.splitlines():\n (indent, sub_in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the minimum of x, y | def min(self):
return self.x.min(), self.y.min() | [
"def min_by(f, x, y):\n return x if f(x) < f(y) else y",
"def min(x):\n\treturn np.min(x)",
"def minplus(x, y):\n if math.isnan(x) and math.isnan(y):\n return float(\"nan\")\n elif math.isnan(x):\n return y\n elif math.isnan(y):\n return x\n elif x < y:\n return x\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return subset of time series between x_lo and x_hi values. | def cut_x(self, x_lo, x_hi):
"""find indices of x_lo and x_hi, then call cut_ind"""
lo = self.x.searchsorted(x_lo)
hi = self.x.searchsorted(x_hi)
print(lo, self.x[lo], self.x[lo - 1])
self.xcx = self.x[lo:hi]
self.ycx = self.y[lo:hi]
return self.xcx, self.ycx | [
"def subset_data(self, data: List[DataPoint], start_time: datetime = None, end_time: datetime = None) -> List[\n DataPoint]:\n if len(data)>0:\n subset_data = []\n if start_time.tzinfo is None or start_time.tzinfo == \"\":\n start_time = start_time.replace(tzinfo=d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the results with Gnuplot. | def plot(self):
data = Gnuplot.Data(self.x, self.y, using = (1, 2)) #this ensures that t is used as x axis
g = Gnuplot.Gnuplot()
g('set ylabel "y-axis [arb. units]"')
g('set xlabel "x-axis [arb. units]"')
g('set style data lines')
g.plot(data) | [
"def demo(self):\n \n # A straightforward use of gnuplot. The `debug=1' switch is used\n # in these examples so that the commands that are sent to gnuplot\n # are also output on stderr.\n g = Gnuplot.Gnuplot(debug=1)\n g.title('A simple example') # (optional)\n g('set d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Downloads the given playlist into output_folder. You should make sure that the environment variables for the spotify and youtube module are set with valid keys and secrets. | def download_playlist(playlist, output_folder, simulate_mode, audio_quality):
user_id, playlist_id = spotify.parse_playlist_uri(playlist)
spotify_access_token = spotify.get_access_token()
print(' * Got access token')
playlist_name = spotify.get_playlist_name(user_id, playlist_id, spotify_access_token)
... | [
"def download_playlist(playlist):\n try:\n youtube_dl = os.path.join(settings.BASE, \"youtube-dl\")\n if len(settings.FFMPEG) > 0:\n args = [youtube_dl,\n \"--no-post-overwrites\",\n \"-x\",\n \"--ffmpeg-location\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. | def sumRegion(self, row1, col1, row2, col2):
if not self.matrix or not self.matrix[0]:
return 0
result = self.matrix[row2][col2]
if row1 > 0:
result -= self.matrix[row1 -1][col2]
if col1 > 0:
result -= self.matrix[row2][col1 - 1]
if col1 > 0 an... | [
"def sumRegion(self, row1, col1, row2, col2):\n return self.sums[row2 + 1][col2 + 1] - self.sums[row2 + 1][col1] \\\n - self.sums[row1][col2 + 1] + self.sums[row1][col1]",
"def sum_of_matr(matrix): \n total = sum([sum(x) for x in matrix])\n return total",
"def row_sums(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve list of shapes based on the shape type queried | def read_shape_list(db: Session = Depends(get_db), item_type: str = "",
skip: int = 0, limit: int = 100):
item_type = item_type.lower()
if item_type == "triangle":
shape_list = crud.triangle.get_multi(db, skip=skip, limit=limit)
elif item_type == "square":
shape_list = crud.s... | [
"def get_type_shapes(self):\n type_shapes = self.cpp_force.getTypeShapesPy()\n ret = [json.loads(json_string) for json_string in type_shapes]\n return ret",
"def create_shape_list():\n # list of shapes\n shapeList = []\n shapeCounter = {\"circle\": 0, \"square\": 0, \"cube\": 0}\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the shape based on the shape type queried | def create_shape(*, db: Session = Depends(get_db), item_type: str,
item_in):
item_type = item_type.lower()
if item_type == "triangle":
item_in: TriangleCreateUpdate
shape = crud.triangle.create(db_session=db, obj_in=item_in)
elif item_type == "square":
item_in: Squar... | [
"def create_shape():\n\n # shape_key = gen_random_shape()\n prompt_shape = \"Enter shape type: 0 FOR RECT or 1 FOR CIRCLE. default:0 >>> \"\n shape_key = collect_valid_input(prompt_shape,0,[0,1])\n\n if shape_key == 0:\n prompt_h = \"Enter height of RECT or SQUARE to be inserted. default:30,30 r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the shape based on the shape type and shape id queried | def update_shape(*, db: Session = Depends(get_db), item_type: str, item_id: int, item_in):
item_type = item_type.lower()
if item_type == "triangle":
item_in: TriangleCreateUpdate
shape = crud.triangle.get(db_session=db, obj_id=item_id)
if not shape:
raise HTTPException(status... | [
"def shape(self, new_shape):\n self.set_shape(new_shape)",
"def new_shape_name(self, type_name):\n ...",
"def _set_shape(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=shape.shape, is_container='container', presence=False, yang... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the pairwise distance (A2B & B2A) for all possible combinations of users appearent in users data frame | def cal_pairwise_distances(self):
all_combs = combinations(self.all_user_id, 2)
all_pairs = [p for p in all_combs]
self.all_distance = DataFrame(index=range(len(all_pairs)), \
columns = ["pair", "uid_a", "uid_b", "dist_a2b", "dist_b2a"])
if self.scorer_load_counter != self.dist... | [
"def computeNearestNeighbor(users, username):\n distances = []\n for user in users:\n if user != username:\n # distance = cosine(users[username],users[user])\n # distance = manhattan(users[username],users[user])\n distance = pearson(users[username],users[user])\n \n distances.append((u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the distribution of pairwise distance grouped by friends and nonfriends | def dist_distr_display(self):
bool_idx = self.all_distance.pair.apply(lambda x: True if x in list(self.friends.pair) else False)
nbool_idx = bool_idx.apply(lambda x: not x)
sim_a2b = self.all_distance.ix[bool_idx, "dist_a2b"]
sim_b2a = self.all_distance.ix[bool_idx, "dist_b2a"]
... | [
"def get_all_pairs_social_distances(self, graph):\n nodes = nx.nodes(graph)\n\n weights = {}\n\n for i in range(len(nodes)):\n for j in range(len(nodes[i+1:])):\n pair = (nodes[i], nodes[j])\n weight = self.__ratio_mutual_friends_product(graph, pair)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shorthand for 'assert np.allclose(a, b, rtol, atol), "%r != %r" % (a, b) | def ap_(a, b, msg=None, rtol=1e-5, atol=1e-5):
if not np.allclose(a, b, rtol=rtol, atol=atol):
raise AssertionError(msg or "{} != {}".format(a, b)) | [
"def assert_equal(a: float, b: float) -> None:\n msg = \"{} != {}\".format(a, b) \n assert a == b, msg",
"def assert_leq(x, y, atol=np.finfo(np.float64).eps, rtol=1e-7):\n mask = np.greater(x, y)\n np.testing.assert_allclose(x[mask], y[mask], atol=atol, rtol=rtol)",
"def assert_almost_equal(a: Any, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to setup MongoDB connection & `motor` client during setup. | def setup_mongodb(app: FastAPI) -> None:
client = AsyncIOMotorClient(local_config.MONGODB_URL, minPoolSize=0, maxPoolSize=100)
app.mongodb = client[local_config.DATABASE_NAME] | [
"def setup_mongodb():\n\n MONGODB_URI = os.environ.get('MONGODB_URI')\n # MONGODB_URI = TEST_MONGODB_URI\n if not MONGODB_URI:\n logger.error('The MONGODB_URI must be set')\n raise NotImplementedError\n\n mongo_client = pymongo.MongoClient(MONGODB_URI)\n database_name = \"housechores\"\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for existance of active user. | def active_user_exists() -> bool:
return session.query(ActiveUser).count() != 0 | [
"def user_exists():\n return 'adminId' in session and Admin.query.filter_by(\n id=session['adminId']).first() is not None",
"def has_user(self):\n return self.user is not None",
"def existing_user(self):\n\n user = User.query.filter_by(username=self.username).first()\n if user:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get name of the active user. | def get_active_user_name() -> str:
return session.query(ActiveUser).one().name | [
"def get_name(self, user):\n return user.display_name",
"def user_name(self):\n if self.user_mode == 'single':\n return self.config['USER_NAME']\n return None",
"def get_name(self) -> str:\n return self._user_display_name or self.load_name",
"def get_username(self):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Patch the given input to the given output | def patch(self, input_, output):
raise NotImplementedError | [
"def patch_one_to_all(self, input_):\n for output in range(1, self.OUTPUT_COUNT + 1):\n self.patch(input_, output)",
"def preproc_output(self, input: I, output: O) -> PO:\n raise Exception(\"Not implemented\")",
"def new_input(output):\r\n\t\tinput = int(output + .5)\r\n\t\t\r\n\t\treturn i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A list of patch instructions, each given as a tuple {input, output}. | def patch_pairs(self, patch_pairs):
if not isinstance(patch_pairs, list):
# Convert to a single-element list
patch_pairs = [patch_pairs]
for input_, output in patch_pairs:
self.patch(input_, output) | [
"def patch_one_to_all(self, input_):\n for output in range(1, self.OUTPUT_COUNT + 1):\n self.patch(input_, output)",
"def patch(self, input_, output):\n raise NotImplementedError",
"def apply_patches():\n with open(os.path.join(os.getcwd(), 'utils', 'sdk.patch'), 'r') as fin:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Patch the given input to every output | def patch_one_to_all(self, input_):
for output in range(1, self.OUTPUT_COUNT + 1):
self.patch(input_, output) | [
"def patch(self, input_, output):\n raise NotImplementedError",
"def patch_one_to_one(self):\n for i in range(0, self.OUTPUT_COUNT):\n self.patch((i % self.INPUT_COUNT) + 1, i + 1)",
"def preproc_output(self, input: I, output: O) -> PO:\n raise Exception(\"Not implemented\")",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Patch in 1 > out 1, in 2 > out 2, etc. If more outputs than inputs, wrap and start counting from 1 again. | def patch_one_to_one(self):
for i in range(0, self.OUTPUT_COUNT):
self.patch((i % self.INPUT_COUNT) + 1, i + 1) | [
"def patch_one_to_all(self, input_):\n for output in range(1, self.OUTPUT_COUNT + 1):\n self.patch(input_, output)",
"def patch(self, input_, output):\n raise NotImplementedError",
"def assemble_patches(patches, stride, out, fake):\n out_shape = np.zeros(3)\n out_shape[:] = out.sh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restore the given outputs from blackout. | def unblackout(self, outputs):
if not isinstance(outputs, list):
# Convert to a single-element list
outputs = [outputs]
for output in outputs:
raise NotImplementedError | [
"def unblackout_all(self):\n for output in range(1, self.OUTPUT_COUNT + 1):\n self.unblackout(output)",
"def blackout_all(self):\n for output in range(1, self.OUTPUT_COUNT + 1):\n self.blackout(output)",
"def restore_state(self):\n self._restore_input()\n self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Black out every output. | def blackout_all(self):
for output in range(1, self.OUTPUT_COUNT + 1):
self.blackout(output) | [
"def unblackout_all(self):\n for output in range(1, self.OUTPUT_COUNT + 1):\n self.unblackout(output)",
"def unblackout(self, outputs):\n if not isinstance(outputs, list):\n # Convert to a single-element list\n outputs = [outputs]\n for output in outputs:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restore every output from blackout. | def unblackout_all(self):
for output in range(1, self.OUTPUT_COUNT + 1):
self.unblackout(output) | [
"def blackout_all(self):\n for output in range(1, self.OUTPUT_COUNT + 1):\n self.blackout(output)",
"def restore_state(self):\n self._restore_input()\n self._restore_output()",
"def restore_output(cls):\n if None not in {\n cls.suppress_results,\n cls... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply a numbered preset patch from the preset controller | def apply_preset(self, preset_no):
self.patch_list(self.PRESET_CONTROLLER.get(preset_no)[1]) | [
"def set_preset(self, preset: params.Preset, /) -> GoProResp:",
"def ptz_preset(self, preset):\n preset -= 1\n preset = str(preset)\n payload = {\"act\": \"goto\", \"number\": preset}\n self.send('preset', payload)",
"def set_preset(self, preset_id, patchlist):\n self._presets... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function should raise when asked to perform more mutations than there are in the original string. | def testTooManyMutationsRequested(self):
error = "Cannot make 2 mutations in a string of length 1"
with six.assertRaisesRegex(self, ValueError, error):
mutateString("x", 2) | [
"def testReplacementLengthOneAppearsInOriginal(self):\n error = \"Impossible replacement\"\n with six.assertRaisesRegex(self, ValueError, error):\n mutateString(\"x\", 1, \"x\")",
"def testDuplicateReplacementLetter(self):\n error = \"Replacement string contains duplicates\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function should raise when given a replacement string that contains a duplicate letter. | def testDuplicateReplacementLetter(self):
error = "Replacement string contains duplicates"
with six.assertRaisesRegex(self, ValueError, error):
mutateString("x", 1, "aa") | [
"def testReplacementLengthOneAppearsInOriginal(self):\n error = \"Impossible replacement\"\n with six.assertRaisesRegex(self, ValueError, error):\n mutateString(\"x\", 1, \"x\")",
"def test_replace_exception(self):\n self.assertEqual(textlib.replaceExcept('123x123', '123', '000', [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function should raise when given a replacement string that contains just one letter if that letter also appears in the original. | def testReplacementLengthOneAppearsInOriginal(self):
error = "Impossible replacement"
with six.assertRaisesRegex(self, ValueError, error):
mutateString("x", 1, "x") | [
"def testDuplicateReplacementLetter(self):\n error = \"Replacement string contains duplicates\"\n with six.assertRaisesRegex(self, ValueError, error):\n mutateString(\"x\", 1, \"aa\")",
"def test_replace_with_shorter_string(self):\r\n text = \". I Bezwaar tegen verguning.\"\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function should return the original string when zero mutations are requested. | def testZeroReplacements(self):
self.assertEqual("acgt", mutateString("acgt", 0, "x")) | [
"def mirror(s):",
"def dup_string(self): # real signature unknown; restored from __doc__\n return \"\"",
"def empty_string():\n return ''",
"def makeEmpty(self, freeold: 'SbBool'=1) -> \"void\":\n return _coin.SbString_makeEmpty(self, freeold)",
"def erase_seq(s):\n if s is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
transform all tablespace info list in host to data line list | def transform_host_tablespace_info_dic(host_tablespace_info_dic):
host_format_info = {}
for hostname, tablespace_info_list in host_tablespace_info_dic.iteritems():
host_format_info[hostname] = {}
for tablespace_info in tablespace_info_list:
if tablespace_info.mount_on not in host_for... | [
"def show_tablespaces(self):\n sql = \"SELECT tablespace_name FROM dba_tablespaces ORDER BY 1\"\n self.cur.execute(sql)\n res = self.cur.fetchall()\n key = ['{#TABLESPACE}']\n lst = []\n for i in res:\n d = dict(zip(key, i))\n lst.append(d)\n pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prompts user for, error checks and returns number of sides in game | def get_num_sides(self):
done = False
while not done:
try:
num_sides = int(input("select number of teams: [0, 1 or 2] "))
choices = [0, 1, 2]
if num_sides > 2 or num_sides < 0:
raise Incorrect_Input_error
except Incorrect_Input_error:
print("Please select a... | [
"def get_num_rounds(self):\n\n valid_input = False\n\n while not valid_input:\n\n num_rounds = raw_input(\"Enter the number of rounds you would like to play: \")\n\n try:\n num_rounds = int(num_rounds)\n if num_rounds > 0:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prompts user for, error checks and returns specific information about each team. | def get_teams(self):
teams = [{
str("team_" + str(i)): {
"team_name": None,
"color": None,
"skill": None,
"strategy": None
}
} for i in range(self.num_sides)]
colors = [
"blue", "green", "red", "cyan", "magenta", "yellow", "black", "white"
]
for i ... | [
"def _team(self):\n team_name = req_input(help_text=\"name of Team\")\n if team_name in self._list_of_teams():\n team = \"OWN TEAM\"\n print \"Players in team %s:\" % team_name\n for playerline in self.csv:\n if team_name in playerline.get(team):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prompts user for, error checks and returns number of trials for this iteration of the game | def get_num_trials(self):
done = False
while not done:
try:
trials = int(
input("How many trials would you like to run? [1 - 1,000,000] "))
if trials > 10000000 or trials < 0 or not isinstance(trials, int):
raise Incorrect_Input_error
except Incorrect_Input_error... | [
"def get_num_rounds(self):\n\n valid_input = False\n\n while not valid_input:\n\n num_rounds = raw_input(\"Enter the number of rounds you would like to play: \")\n\n try:\n num_rounds = int(num_rounds)\n if num_rounds > 0:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the object coefficient The object coefficient means the factor of design variable(decision variable) of objective function The instance `object_coeff` has the N number of object coefficient accorinding to decision variable | def set_object_coeff(self, obj_list: list):
self.object_coeff = obj_list | [
"def SetObjective(self, obj):\n self.Objective = sympify(obj)\n self.RedObjective = self.ReduceExp(sympify(obj))\n # self.CheckVars(obj)\n tot_deg = Poly(self.RedObjective, *self.AuxSyms).total_degree()\n self.ObjDeg = tot_deg\n self.ObjHalfDeg = int(ceil(tot_deg / 2.))",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the name of decision variable | def set_decision_variable(self, decision_var: list):
self.decision_var = decision_var | [
"def _set_element_variable_name(self, element):\n ename = self._get_variable_name(element)\n if ename is not None:\n element.variable_name = ename\n element.name_is_set = True\n return True\n else:\n return False",
"def var(self, name: str):",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the list of rhs constraint | def set_constraint_rhs(self, rhs: list):
self.constraint_rhs = rhs | [
"def as_constraint(self, *args):\n return []",
"def set_cplex_constraint(self):\n self.cplex.objective.set_sense(self.direction_solution)\n self.cplex.variables.add(obj=self.object_coeff, ub=self.bound_ub, lb=self.bound_lb, names=self.decision_var)\n rows = self.get_row_lhs()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the constraint label | def set_constraint_label(self, label: list):
self.constraint_label = label | [
"def set_label(self, label):",
"def set_constraint(self, name):\n self.push_queue_put(MSG_CONSTRAINT(self.text.marker.id, name))\n return",
"def setConstraint (self, constraint):\n\n self.constraint = constraint",
"def set_label(self, label):\n # check label makes sense\n if not isins... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the constraint inequality. By the Cplex reference, G means the greater, L means the lower E means the equality. And the list of the constraint inequality is the string sequence of inequality characters which is defined by Cplex library | def set_constraint_inequality(self, inequal_list: str):
self.constraint_inequality = inequal_list | [
"def get_pyomo_equality_constraints(self):\n idx_to_condata = {i: c for c, i in self._condata_to_eq_idx.items()}\n return [idx_to_condata[i] for i in range(len(idx_to_condata))]",
"def inequality_constraint_names(self):\n inequality_constraints = self.get_pyomo_inequality_constraints()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the cplex object as cplex instance | def set_cplex(self):
self.cplex = cplex.Cplex() | [
"def set_cplex_constraint(self):\n self.cplex.objective.set_sense(self.direction_solution)\n self.cplex.variables.add(obj=self.object_coeff, ub=self.bound_ub, lb=self.bound_lb, names=self.decision_var)\n rows = self.get_row_lhs()\n self.cplex.linear_constraints.add(lin_expr=rows, senses=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the cplex constraint with SetSimplex instance The constraint set with rows method. | def set_cplex_constraint(self):
self.cplex.objective.set_sense(self.direction_solution)
self.cplex.variables.add(obj=self.object_coeff, ub=self.bound_ub, lb=self.bound_lb, names=self.decision_var)
rows = self.get_row_lhs()
self.cplex.linear_constraints.add(lin_expr=rows, senses=self.cons... | [
"def set_cplex(self):\n self.cplex = cplex.Cplex()",
"def set_assignment_cons(self):\n\n\t\tfor s in range(len(self.STUDENTS)):\n\t\t\tself.m.addCons(self.X[s,1] + self.X[s,2] + self.X[s,3] == 1)\n\n\t\tprint(\"Assignment Constraint Set\")",
"def setConstraint (self, constraint):\n\n self.constraint... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solve the problem and save the Linear programming model on filename | def solve(self, filename: str = "solution.lp"):
self.set_cplex_constraint
self.cplex.write(filename)
self.cplex.solve() | [
"def pickleModel(self):\n print 'Saving model to file...'\n logit = LogisticRegression(C=self.C, penalty='l1')\n logit.fit(self.X_mapped,self.y)\n \n with open('model','w') as myFile:\n pickle.dump({'logit':logit,'degree':self.degree,'useInverse':self.useInverse,'me... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the lhs constraint formated by rows method For example, The decision variable is ["x1","x2"."x3"] and the coefficient of lhs constraint is [[1,2,3], [4,5,6]] Return [ [["x1","x2"."x3"], [1,2,3]], [["x1","x2"."x3"], [4,5,6]] ] | def get_row_lhs(self):
global_mat = []
local_mat = []
for rows in self.lhs_coeff:
local_mat.append(self.decision_var)
local_mat.append(rows.tolist())
global_mat.append(local_mat)
local_mat = []
return global_mat | [
"def create_lhs(constraints, decision_variables, join_columns):\n constraints = pd.merge(constraints, decision_variables, 'inner', on=join_columns)\n constraints['coefficient'] = constraints['coefficient_x'] * constraints['coefficient_y']\n lhs = constraints.loc[:, ['constraint_id', 'variable_id', 'coeffic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize the solution. The format refer to HW2 | def visualize_solution(self):
numrows = self.cplex.linear_constraints.get_num()
numcols = self.cplex.variables.get_num()
print()
# solution.get_status() returns an integer code
print("Solution status = ", self.cplex.solution.get_status(), ":", end=' ')
# the following li... | [
"def display_solution(self):\n self.row_reduce().display_matrix()",
"def show_solution(self, fig=None):\n if self.initstate<3:\n raise Exception('The solution has not been initialized. Run init_solution() and step_solution() first.')\n if fig is None:\n fig = plt.figure(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run class setup for running Keystone Kerberos charm tests. | def setUpClass(cls):
super(CharmKeystoneKerberosTest, cls).setUpClass() | [
"def setUp(self):\n\n self.ks = KeyStone(environ=None, default_role=\"user\", create_default_role=True, target_domain_name='elixir',\n cloud_admin=True)",
"def test_keystone_kerberos_authentication(self):\n logging.info('Retrieving a kerberos token with kinit for admin user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate auth to OpenStack through the kerberos method. | def test_keystone_kerberos_authentication(self):
logging.info('Retrieving a kerberos token with kinit for admin user')
ubuntu_test_host = zaza.model.get_units('ubuntu-test-host')[0]
result = zaza.model.run_on_unit(ubuntu_test_host.name,
"echo password123 ... | [
"def authenticateKerberos(user, pwd):\n try:\n from sys import platform\n cmd = [\"kinit\", user]\n if platform == 'darwin':\n cmd = [\"kinit\", \"--password-file=STDIN\", user]\n\n procKinit = Popen(cmd, stdin=PIPE, stdout=PIPE)\n procKinit.stdin.write((\"%s\\n\" % ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Redefine this fixture to change the init parameters of Celery workers. This can be used e. g. to define queues the worker will consume tasks from. The dict returned by your fixture will then be used | def celery_worker_parameters() -> Dict[str, bool]:
return {
# For some reason this `celery.ping` is not registered IF our own worker is still
# running. To avoid failing tests in that case, we disable the ping check.
# see: https://github.com/celery/celery/issues/3642#issuecomment-369057682... | [
"def setUp(self):\n self.app_id = \"kj-10111213\"\n self.info_plugin = {\n \"monitor_plugin\": \"kubejobs\",\n \"expected_time\": 500,\n \"count_jobs_url\": \"mock.com\",\n \"number_of_jobs\": 1500,\n \"submission_time\": \"2017-04-11T00:00:00.000... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate two OAuth safe sha1 hashes | def oauth():
print _get_rand_hash()
print _get_rand_hash() | [
"def generate_secret_hash_3072_sha1(info):\n return rsa.encrypt(info, settings.PUB_KEY)",
"def oauth():\r\n print _get_rand_hash()\r\n print _get_rand_hash()",
"def test_00():\n hs1 = hashlib.sha256()\n hs2 = hashlib.sha256()\n\n # 해쉬는 바이너리로 진행해야 한다\n hs1.update(b\"Nobody inspects\")\n h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Successful response, just return JSON | def __success(response):
return response.json() | [
"def return_json_response():\n return jsonify({'this is': 'sample'})",
"def json_response(self, result):\n self.response.setHeader('Content-Type', 'application/json')\n return json.dumps(result)",
"def ok():\n return {\n \"statusCode\": 200,\n \"body\": dumps({\"message\": \"OK... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses link into base URL and dict of parameters | def _parse_link(self, link):
parsed_link = namedtuple('link', ['url', 'params'])
link_url, link_params = link.split('?')
params = self._link_params(link_params)
return parsed_link(link_url, params) | [
"def parse_link_header(link):\n links = {}\n linkHeaders = link.split(\", \")\n for linkHeader in linkHeaders:\n (url, rel) = linkHeader.split(\"; \")\n url = url[1:-1]\n rel = rel[5:-1]\n links[rel] = url\n return links",
"def parse_link(url):\n a = Article(url)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve X number of pages, returning a ``list`` of all entities. Rather than iterating through ``PagedResponse`` to retrieve each page (and its events/venues/etc), ``limit()`` will automatically iterate up to ``max_pages`` and return a flat/joined list of items in each ``Page`` | def limit(self, max_pages=5):
all_items = []
counter = 0
for pg in self:
if counter >= max_pages:
break
counter += 1
all_items += pg
return all_items | [
"def paginate(self, resource, page=1, page_size=100, **kwargs):\n\n response = resource(page=page, page_size=page_size, **kwargs)\n items = response[\"results\"]\n\n if response[\"page\"] * response[\"page_size\"] >= response[\"count\"]:\n return items\n else:\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves maximum pages in a result, returning a flat list. API limits paging depth to (page size) <= 1000 Use ``limit()`` to restrict the number of page requests being made. | def maximum(self):
max_pages = 49 # do not exceed allowed paging depth
all_items = []
counter = 0
for pg in self:
if counter >= max_pages:
break
counter += 1
all_items += pg
return all_items | [
"def limit(self, max_pages=5):\n all_items = []\n counter = 0\n for pg in self:\n if counter >= max_pages:\n break\n counter += 1\n all_items += pg\n return all_items",
"def paginate(self, resource, page=1, page_size=100, **kwargs):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get test data from The COVID Tracking Project, for testing data collected in the US region. Writes out to several dataFrames and saves to more .csvs as well | def get_covidtracking_test_data():
covidtracking_api_path = "https://covidtracking.com/api/"
perstates_timeseries_path = covidtracking_api_path + "v1/states/daily.csv"
perstates_current_values_path = covidtracking_api_path + "v1/states/current.csv"
us_whole_timeseries_path = covidtracking_api_path + "... | [
"def update_OxCGRT_tests():\n # source of latest Oxford data\n OXFORD_URL = 'https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv'\n # source of latest test data\n TESTS_URL = \"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/testing/covid-t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build lookup / bounds list from Spark DataFrame | def _lookup_from_spark(df, num_partitions, has_index, sort, partition_mapper):
lookups = sorted(
DawgLookup._prepare_spark(df, num_partitions, has_index, sort)
.mapPartitions(partition_mapper)
.collect(),
key=itemgetter(0, 1),
)
return lookups | [
"def avail(df):\r\n avail = DataFrame({\r\n 'start' : df.apply(lambda col: col.first_valid_index()),\r\n 'end' : df.apply(lambda col: col.last_valid_index())\r\n })\r\n return avail[['start', 'end']]",
"def dfcommon_bounds(datasets, cols):\r\n bounds = []\r\n for col ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build lookup / bounds list from local collection | def _lookup_from_local(xs, has_index, sort, partition_mapper):
try:
x, xs = peek(xs)
assert has_index or isinstance(x, str)
except StopIteration:
xs = []
return pipe(
DawgLookup._prepare_local(xs, has_index, sort), partition_mapper, list
) | [
"def bounds_vectors(bounds_cat, filternames, shapenames=Galaxy.SHAPE_COLS,\n reference_coordinates=[0., 0.]):\n lower, upper = [], []\n bcat = bounds_cat.copy()\n bcat[\"ra\"] -= reference_coordinates[0]\n bcat[\"dec\"] -= reference_coordinates[1]\n for row in bcat:\n lower.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
constructor sends the values for the object to be created from BaseModel | def __init__(self, **kwargs):
BaseModel.__init__(self, **kwargs) | [
"def _construct(self, model_config):\n pass",
"def __init__(self,kim_code,*args,**kwargs):\n super(Model,self).__init__(kim_code,*args,**kwargs)",
"def __init__(self,kim_code,*args,**kwargs):\n super(ModelDriver,self).__init__(kim_code,*args,**kwargs)",
"def __init__(self, data):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fills a given hashTable with a given string, text | def fill_from_string(hashTable, text):
split_up_test = re.split(r"[^\w{w}']+", text)
for s in split_up_test:
curr_string = remove_39(s.lower())
if curr_string == None:
continue
elif hashTable.contains(curr_string):
old_val = hashTable.get(curr_string) +... | [
"def _gen_table(self, text):\n\t\ttext_len = len(text)\n\t\tk_k1_len_substrings = [(text[i-1:i+self.k-1], text[i-1:i+self.k]) for i in range(text_len) if i+self.k-1 < text_len][1:]\n\t\tk_k1_len_substrings.append((text[-self.k:], text[-self.k:]+text[0]))\n\t\tif self.k > 1:\n\t\t\tfor char_index, char in enumerate(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns likes count of this post | def likes_count(self) -> int:
return len(self.likes) | [
"def count_likes(cls, post):\n count = 0\n likes = cls.all().filter(\"post = \", post)\n for like in likes:\n if like.do_like:\n count += 1\n return count",
"def like_count(self) -> int:\n return int(self.statistics.get('likeCount'))",
"def get_post_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates users according up to number of users setting | def _generate_users(self):
success_counter = 0
hunter_attempts = 0
hunter_max_attempts = 3
while success_counter < self.number_of_users:
try:
users = self._get_some_users()
except HunterError:
hunter_attempts += 1
i... | [
"def generate_users(self, x):\n for i in range(x):\n user = id_generator()\n self.create_user(user)",
"def create_n_users(size):\n users = []\n for i in range(size):\n users.append({\n \"first_name\": \"First%d\" % i,\n \"last_name\": \"First%d\" % i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates posts for the userlist | def generate_posts(self) -> None:
for i in range(len(self)):
self[i].generate_posts(
api=self.api,
max_posts=self.max_post_per_user
) | [
"def create_test_posts(self):\n self.test_posts = []\n for i in range(N_TEST_USERS):\n self.test_posts += [Post.objects.create(author=self.users[i], text=POSTS[i])]",
"def user_post(user_id):\n user_posts = Post.query.filter(Post.user_id == user_id).order_by(\n Post.created_date... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns id of the user that should like the post next | def get_id_of_next_user_to_post(self) -> Union[int, None]:
users_with_no_max_likes = [
i for i in sorted(self, key=lambda x: x.my_likes_count, reverse=True) # returns new list
if i.my_likes_count < self.max_likes_per_user
]
if len(users_with_no_max_likes) > 0:
... | [
"def post_like_toggle(request, slug):\n\n print(\"\\n\\n\\n\\nLIKE############UNLIKED\\n\\n\\n\\n\")\n\n post_qs = Post.objects.filter(slug=slug)\n user = request.user\n count = -1\n pk = -1\n if post_qs is None:\n # Post does not exist\n result = \"ERR\"\n\n else:\n # Post... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns indices of sorted users that should like the post next | def get_sorted_ids(self) -> Union[List[int], None]:
users_with_no_max_likes = [
i for i in sorted(self, key=lambda x: x.my_likes_count, reverse=True) # returns new list
if i.my_likes_count < self.max_likes_per_user
]
if len(users_with_no_max_likes) > 0:
ind... | [
"def get_id_of_next_user_to_post(self) -> Union[int, None]:\n users_with_no_max_likes = [\n i for i in sorted(self, key=lambda x: x.my_likes_count, reverse=True) # returns new list\n if i.my_likes_count < self.max_likes_per_user\n ]\n\n if len(users_with_no_max_likes) > 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
makes user with user id to like a post | def do_like(self, with_user_id):
logger.info(f">>>>>>>>>>>>>>>>>> begin liking algo <<<<<<<<<<<<<<<<<<<<<<<<")
# select user
user: User = self[with_user_id]
logger.info(f"{user} wants to like a post")
posts_this_user_already_liked = user.my_likes
# select all users whic... | [
"def like(request, content_type_id, object_id):\n\n content_type = get_object_or_404(ContentType, pk=content_type_id)\n obj = get_object_or_404(content_type.model_class(), pk=object_id)\n\n # generate a like by this user for the content object\n like = Like.objects.create(user=request.user, liked=obj)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If we are already done, do nothing Otherwise if we don't need a result and we didn't broadcast , set ourselves as done If we did broadcast and we don't need a result then wait for the next ack such that if we don't get another ack before our timeout, we mark ourselves as done | def add_ack(self):
self.last_ack_received = time.time()
if self.done():
return
if not self.request.res_required:
if self.did_broadcast:
self.schedule_finisher("last_ack_received")
else:
self.set_result([]) | [
"def _MaybeSendAck(self):\n if self._cant_send_ack.is_set():\n return\n # Using these extra variables because the line is too long otherwise\n total_bytes = self._total_bytes_received\n bytes_recv_and_ackd = self._total_bytes_received_and_acked\n window_size = utils.SUBPROTOCOL_MAX_DATA_FRAME_SI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether we should wait for a result If we expect both and ack and a result then we say yes only if it's been less than gap_between_ack_and_res since the ack if we have received one. If we expect a bound number of results and it's been less than gap_between_results since the last result, then say yes If we expect... | def wait_for_result(self):
if self.request.ack_required and self.request.res_required:
if self.last_ack_received is None:
return False
if self.results:
return True
return (time.time() - self.last_ack_received) < self.retry_gaps.gap_between_ac... | [
"def ackwait(self):\n\t\tif (self.emulate):\n\t\t\treturn True\n\t\tans = ''\n\t\twhile (1):\n\t\t\ttime.sleep(0.01)\n\t\t\tc = self.port.read(1)\n\t\t\tif c:\n\t\t\t\tans = ans + c\n\t\t\telse:\n\t\t\t\treturn None\n\t\t\tif (self.debug > 1):\n\t\t\t\tprint \"Radant: ans = '\" + ans + \"'\"\n\t\t\t#if (self.ack.se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to call when option is activated (ENTER key pressed) New Game start | def option_activated(self):
self._start_new_game() | [
"def show_start_menu(): # The startup menu\n print('MAIN MENU')\n print('\\t1. Start a new game.')\n accepted_answers = ['1', 'q']\n save = find_save()\n if save is not None:\n print('\\t2. Continue from existing save.')\n accepted_answers.append('2')\n print('\\tq. Quit.\\n')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method starts a new game and loads starting gear | def _start_new_game(self):
game = game_logic.Game() # start a new game
sg_file = open('data/starting_gear.json', 'r') # load starting gear
sg_dict = jsonpickle.loads(sg_file.read())
for item_id in sg_dict[self.options[self.selected]]:
game.player.add_item(item_id)
s... | [
"def start_game(self):\n\n self.time_up.start()\n self.pig.start_game()",
"def start_game():\n\n save.load_game()\n play_game()",
"def init_new_game(self):\n self.game = get_new_game(self.game_type, self.game_config, verbose=False)",
"def start_game(self) -> None:\n self.acti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Default action when button is pressed pop this scene | def _default_button_action(self):
self.director.pop_scene() | [
"def pop(self, poptop=1):\n if not self._onscreen_wid or not self._parent or not poptop:\n return\n self._onscreen_wid.SelectWindow()\n mw_globals.toplevel._mouseregionschanged()",
"def back_main_button(self) -> None:\n self.window.destroy()\n MainMenu.execute()",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Default action when button is pressed pop this scene | def _default_button_action(self):
self.director.pop_scene() | [
"def pop(self, poptop=1):\n if not self._onscreen_wid or not self._parent or not poptop:\n return\n self._onscreen_wid.SelectWindow()\n mw_globals.toplevel._mouseregionschanged()",
"def back_main_button(self) -> None:\n self.window.destroy()\n MainMenu.execute()",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that starts thread with location generation and transition Threading is needed to show Loading screen while generating a location | def _to_city_start_thread(self):
t = threading.Thread(target=self._to_desert_city)
t.start()
self.director.push_scene(LoadingScene(watch_thread=t)) | [
"def start(self):\n self.logger.debug(\"Starting location tracker...\")\n self.running = True\n self._thread.start()",
"def run_ant_tour(self):\n\n\t\twhile self.allowed_locations:\n\t\t\tnext_node = self._choose_next_node()\n\t\t\tself._move_to_node(self.current_location, next_node)\n\n\t\t#... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that starts raid to the Desert City. Now simply moves player to new 'ruins' location. | def _to_desert_city(self):
commands.command_enter_loc(game=self.game, new_loc=generation.generate_loc('ruins', None, 200, 200))
self.game.leave_camp()
director = self.director
while director.active_scene is not director.main_game_scene: # pop to main game scene
director.pop_... | [
"def raid():\n pass",
"def seat(self, player):\n player.thing.moveTo(self.container)\n player.thing.powerUp(self, IMovementRestriction)",
"def step(self):\n #Get random player\n players = [random.choice(list(self.G.nodes()))]\n # if this player has at least two neighbors, go into a tru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that sells treasure items to market and shows a report | def _to_market(self):
# treasures report section
report_text = ''
treasures = {}
sold = []
player = self.game.player
for item in player.inventory:
if 'relic' in item.categories: # if there'll be other types of treasure - add here
if isinstance... | [
"def soldout():",
"def display_stock():",
"def _buy(self):\r\n self._handleLogs(self.game.buy())\r\n self.redraw()",
"def stock_entry(doc, method):\n if doc.purpose == \"Material Transfer\":\n for d in doc.get('items'):\n\n soi_bloked_qty = frappe.db.sql('''SELECT sum(smi.bl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for height and enables/disables scrolling | def _scrolling_mode_check(self):
list_height = self.window_view.bounds.height - 2
if list_height < len(self.options):
self.scrolling_mode = True
self._scroll()
else:
self.scrolling_mode = False | [
"def _canscroll(self):\n return not not self._canvassize",
"def set_scrollbars(self):\n try:\n if len(self.row_labels) < 5:\n show_horizontal = wx.SHOW_SB_NEVER\n else:\n show_horizontal = wx.SHOW_SB_DEFAULT\n self.ShowScrollbars(show_ho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for scrolling the options list | def _scroll(self):
list_height = self.window_view.bounds.height - 2
if self.selected < self.scroll_pos:
self.scroll_pos = self.selected
elif self.selected > self.scroll_pos + list_height - 1:
self.scroll_pos = self.selected - list_height + 1
button_y = 0
f... | [
"def _scroll(self, *args):\n for current_list in self.lists:\n current_list.yview(*args)\n return 'break'",
"def scrolls(self , scroll):\n if(scroll.scroll_y <= MainWindow.distance):\n operations.load_more() \n scroll.scroll_to(content.ArticlesContainerCopy.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for height and enables/disables scrolling | def _scrolling_mode_check(self):
list_height = self.window_view.bounds.height - 2
if list_height < len(self.options):
self.scrolling_mode = True
self._scroll()
else:
self.scrolling_mode = False | [
"def _canscroll(self):\n return not not self._canvassize",
"def set_scrollbars(self):\n try:\n if len(self.row_labels) < 5:\n show_horizontal = wx.SHOW_SB_NEVER\n else:\n show_horizontal = wx.SHOW_SB_DEFAULT\n self.ShowScrollbars(show_ho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for scrolling the options list | def _scroll(self):
list_height = self.window_view.bounds.height - 2
if self.selected < self.scroll_pos:
self.scroll_pos = self.selected
elif self.selected > self.scroll_pos + list_height - 1:
self.scroll_pos = self.selected - list_height + 1
button_y = 0
f... | [
"def _scroll(self, *args):\n for current_list in self.lists:\n current_list.yview(*args)\n return 'break'",
"def scrolls(self , scroll):\n if(scroll.scroll_y <= MainWindow.distance):\n operations.load_more() \n scroll.scroll_to(content.ArticlesContainerCopy.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to drop item when option is activated (ENTER key pressed) | def option_activated(self, *args, **kwargs):
if isinstance(self.options[self.selected], game_logic.ItemCharges) and\
'stackable' in self.options[self.selected].categories and\
self.options[self.selected].charges > 1:
self.director.push_scene(Number... | [
"def drop_item(self, key):\n\t\tself.player.begin_drop_item()",
"def option_activated(self, *args, **kwargs):\n commands.command_use_item(self.game, self.options[self.selected], self.director.main_game_scene)\n super().option_activated(*args, **kwargs)",
"def dropEvent(self, event):\n click... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to split items stack and drop | def _split_stack_and_drop(self, text):
try: # check if text can be converted to int
split_num = int(text)
except ValueError:
self.director.pop_scene()
return
split_item = self.options[self.selected].split(split_num)
self.game.player.perform(actions.ac... | [
"def split(self, indice=None):\n self_size = self.size\n if self_size > 1:\n if not indice:\n mid = self_size // 2\n return Stack(cards=self[0:mid]), Stack(cards=self[mid::])\n else:\n return Stack(cards=self[0:indice]), Stack(cards=se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to use item when option is activated (ENTER key pressed) | def option_activated(self, *args, **kwargs):
commands.command_use_item(self.game, self.options[self.selected], self.director.main_game_scene)
super().option_activated(*args, **kwargs) | [
"def item_select(self):\r\n layout = [[sg.Text(\"Inventory:\", border_width=0)]]\r\n for i, item in enumerate(self.player.inventory):\r\n layout.append([sg.Button(item, key=i, size=(10, 1), border_width=0)])\r\n layout.append([sg.Button(\"Exit\", key=\"EXIT\", size=(10, 1), button_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to split items stack and pick up | def _split_stack_and_pick(self, text):
try: # check if text can be converted to int
split_num = int(text)
except ValueError:
self.director.pop_scene()
return
split_item = self.options[self.selected].split(split_num)
self.game.player.perform(actions.ac... | [
"def split(self, indice=None):\n self_size = self.size\n if self_size > 1:\n if not indice:\n mid = self_size // 2\n return Stack(cards=self[0:mid]), Stack(cards=self[mid::])\n else:\n return Stack(cards=self[0:indice]), Stack(cards=se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ask player before making a deal | def _enter_pressed(self):
director = self.director
total = self._get_buying_value() - self._get_selling_value()
if total + self.game.player.properties['money'] >= 0:
text = _('Confirm a deal?\nTOTAL: {total} coins.').format(total=total)
director.push_scene(MultiButtonMess... | [
"def deal():\n global outcome, in_play, deck, player_hand, dealer_hand, gamenum, score, xpos\n if not in_play:\n gamenum += 1\n outcome = \"Hit or stand?\"\n in_play = True\n deck = Deck()\n deck.shuffle()\n player_hand = Hand()\n dealer_hand = Hand()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Actually make a deal interact with inventories and money | def _make_deal(self):
total = self._get_buying_value() - self._get_selling_value()
for item in self.buying:
self.game.player.discard_item(item=item)
self.merchant.add_item(item=item)
for item in self.selling:
self.merchant.discard_item(item=item)
s... | [
"async def buy(self, ctx, *, auction_item: str):\n author = ctx.author\n await self._set_bank(author)\n i = 0;\n items = [item for item in self._shop[\"picitems\"] if item[\"name\"] in self.settings[\"user\"][str(author.id)][\"items\"]]\n for item2 in self._shop[\"picitems\"]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update middle view item description and prices | def _update_middle_view(self):
if self.active_tab == self.merchant_items_view:
self.descr_view.set_text(text=
_('{descr}\n\tBuy price: {price} coins.').format(
descr=self.merchant_items[self.merchant_items_view.selected].get_full_description(),
... | [
"def set_item(self, item):\n item = item.fillna(self.NO_DESCRIPTION)\n self.item = item\n \n #set the description QLabel\n if len(item) > 0:\n description = '{0}, {1}'.format(item.loc['manufacturer'], item.loc['category'])\n if item.loc['description'] != self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |