query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
test authenticating JWT token against user data
def test_authenticate_credentials(generate_token, django_user_model): access_token, user_data = generate_token jwt = JWTAuthentication() user, payload = jwt.authenticate_credentials(access_token) user_instance = django_user_model.objects.get( username=user_data['username'] ) assert user ...
[ "def test_returns_valid_token_on_successful_login(self):\n new_user = self.login_user()\n\n self.assertIn('token', new_user.data)\n\n payload = jwt.decode(\n new_user.data['token'], SECRET_KEY, algorithms=['HS256'])\n\n self.assertEqual(\n payload['email'],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calibrates the flux of an output image. Can either be a broadband image or a spectral cube depending on if the spectral flag is set. Assumes the broadband flux calibration is just multiplication by a single scalar number whereas spectral datacubes may have a separate calibration value for each wavelength
def calibrate_output(self, img, spectral=False, units="contrast"): if units == "contrast": if spectral: # spectral cube, each slice needs it's own calibration numwvs = img.shape[0] img /= self.dn_per_contrast[:numwvs, None, None] else: ...
[ "def apply_flux_calibration(frame, fluxcalib):\n log=get_logger()\n log.info(\"starting\")\n\n # check same wavelength, die if not the case\n mval=np.max(np.abs(frame.wave-fluxcalib.wave))\n if mval > 0.00001 :\n log.error(\"not same wavelength (should raise an error instead)\")\n sys.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new empty TypedDict with key_type and value_type as the types for the keys and values of the dictionary respectively.
def empty(cls, key_type, value_type): return cls(dcttype=DictType(key_type, value_type))
[ "def _make_dict(typingctx, keyty, valty, ptr):\n dict_ty = types.DictType(keyty.instance_type, valty.instance_type)\n\n def codegen(context, builder, signature, args):\n [_, _, ptr] = args\n ctor = cgutils.create_struct_proxy(dict_ty)\n dstruct = ctor(context, builder)\n dstruct.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the index of the correlation between an individual on the given index and the previous individual in the chain of individuals.
def _get_prev_correlation_index(self, index: int) -> int: pass
[ "def _get_next_correlation_index(self, index: int) -> int:\n pass", "def correlations(self, index: int) -> Tuple[int, int]:\n prev_index = self._get_prev_correlation_index(index)\n next_index = self._get_next_correlation_index(index)\n return self._correlation[prev_index], self._correl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the index of the correlation between an individual on the given index and the next individual in the chain of individuals.
def _get_next_correlation_index(self, index: int) -> int: pass
[ "def _get_prev_correlation_index(self, index: int) -> int:\n pass", "def correlations(self, index: int) -> Tuple[int, int]:\n prev_index = self._get_prev_correlation_index(index)\n next_index = self._get_next_correlation_index(index)\n return self._correlation[prev_index], self._correl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the individual on the specified index to the given individual and updates appropriate correlations and metrics.
def set_individual( self, index: int, individual: Individual, diff_nodes: List[int] ) -> None: old_individual = self._individuals[index] self._individuals[index] = individual self._update_correlation(index, old_individual, diff_nodes) self._update_metrics(index, old_individua...
[ "def mutate_index(individual, index):\n\n node_count = individual.grid_width * individual.grid_height\n if index >= node_count*3 + individual.constant_len:\n # Index defines one of individual's outputs\n individual.chromosome[index] = random.randrange(individual.input_len +\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the cumulative correlation of the population.
def cumulative_correlation(self) -> int: return self._cumulative_correlation
[ "def get_gc_correlation(self):\n return self.df[[\"cov\", \"gc\"]].corr().iloc[0, 1]", "def corr(self):\n op_func = self._multivariate_statistic_factory(\n lambda a: np.corrcoef(a, rowvar=False, ddof=0)\n )\n return op_func(self)", "def resid_corr(self):\n return se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns correlations between a given individual and the previous and next individual.
def correlations(self, index: int) -> Tuple[int, int]: prev_index = self._get_prev_correlation_index(index) next_index = self._get_next_correlation_index(index) return self._correlation[prev_index], self._correlation[next_index]
[ "def correlation(self, other):\n dates=self.get_dates(other.get_dates())\n #print(len(self.get_values(dates)))\n #print(len(other.get_values(dates)))\n #print(self.get_values(dates))\n r,p=stats.pearsonr(self.get_values(dates), other.get_values(dates))\n return r", "def S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute dictionary of letter probabilities of text for alphabet X
def compute_probabilities(text, X=alph): # Convert to lowercase (just to be sure) text = text.lower() # Make empty dictionary with letters as keys counts = {k: 0 for k in X} # Keep track of total length of legitimate characters total = 0 # Loop through text and update counts only for alp...
[ "def letter_freq( text ):\n\tchars = string.ascii_uppercase\n\ttext = text.upper()\n\tresult = get_letter_dict()\n\ttotal = 0\n\tfor char in chars:\n\t\tcount = text.count(char)\n\t\tresult[char] = count\n\t\ttotal += count\n\tif total != 0:\n\t\tfor char in chars:\n\t\t\tresult[char] = (result[char]*10000 / total)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute variational distance between P and Q for alphabet X
def var_dist(P, Q, X=alph): dist = 0.5 * sum([abs(P[x] - Q[x]) for x in X]) return dist
[ "def wcd(p, q, embeddings):\n m1 = np.mean(embeddings.T * p, axis=1)\n m2 = np.mean(embeddings.T * q, axis=1)\n return np.linalg.norm(m1 - m2)", "def distance(p, q):\n return norm(np.asarray(p) - np.asarray(q))", "def __qDist(self, x, q):\n return np.sqrt((self.nR(*x)[0]-q).dot((self.nR(*x)[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the collision probability of a distribution P for alphabet X
def col_prob(P, X=alph): return sum([P[x] ** 2 for x in X])
[ "def compute_probabilities(text, X=alph):\n\n # Convert to lowercase (just to be sure)\n text = text.lower()\n\n # Make empty dictionary with letters as keys\n counts = {k: 0 for k in X}\n\n # Keep track of total length of legitimate characters\n total = 0\n\n # Loop through text and update cou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all the available actions for the given board
def available_actions(board): actions = [] # Loop through the board for i in range(3): for j in range(3): if board[i][j] == None: actions.append((i, j)) return actions
[ "def actions(board):\n\n # If terminal board, then just return\n if terminal(board):\n return\n\n # Initialize an empty set of available actions\n actions = set()\n\n # Add coordinates to actions if empty\n for i in range(3):\n for j in range(3):\n if board[i][j] == EMPTY:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the action is valid
def is_valid_action(self, action): if self.board[action[0]][action[1]] == None: return True return False
[ "def validate_action(self, action):\n if not self.is_valid_action(action):\n raise InvalidActionException", "def is_valid_action(self, state: object, player: int, action: str) -> bool:\n return True", "def check_action_sanity(self):\n for action in crest.get_all_actions(self.mode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates heatmap by stitching patch_right on to patch_left Overlap region heatmap is the weighted sum of two patches
def stitch_to_right(self, patch_left, patch_right): overlap_cols = int( (self.patch_w - self.strides_cols) / self.out_stride) left, left_overlap = tf.split( patch_left, [-1, overlap_cols], axis=1) right_overlap, right = tf.split( patch_right, [overlap_cols, -1...
[ "def bbox_to_patch(bboxes, # bboxes\n shiftys, # sfhitys\n imgs_left, # imgori1\n imgs_overlap, # overlap region\n imgs_right, # imgori2\n width_stitch, # a set of stitched img patches\n images_w): # normal ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates heatmap by stitching patch_bottom on to patch_top Overlap region heatmap is the weighted sum of two patches
def stitch_to_bottom(self, patch_top, patch_bottom): overlap_rows = int( (self.patch_h - self.strides_rows) / self.out_stride) top, top_overlap = tf.split( patch_top, [-1, overlap_rows], axis=0) bottom_overlap, bottom = tf.split( patch_bottom, [overlap_rows, -...
[ "def taper_patch(patch):\n\n # construct the hanning window\n nx = patch.shape[0]\n han = np.hanning(nx)\n han2d = np.outer(han, han)\n\n patch *= han2d\n\n return patch", "def recreate_from_patches(data):\n overlap_height = (PATCHES * PATCH_HEIGHT - IMG_HEIGHT) // (PATCHES - 1) # Overlap of...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new output panel with the given `name` in the given `window`. If `kwargs` are given, they will be interpreted as for
def create( cls, window, name, *, force_writes=False, follow_cursor=False, unlisted=False, **kwargs ): validate_view_options(kwargs) window.destroy_output_panel(name) view = window.create_output_panel(name, unlisted) set_view_options(v...
[ "def create_window(self, *args, **kw):\n return self._create('window', args, kw)", "def createDisplayLayer(*args, **kwargs):\n\n pass", "def generate_widget(name, **kwargs):", "def outlinerPanel(*args, control: bool=True, copy: AnyStr=\"\", createString: bool=True,\n defineTemplate:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The output panel name, beginning with ``output.``. Generally, API methods specific to output panels will use `name`, while methods that work with any panels will use `full_name`.
def full_name(self): return "output.%s" % self.name
[ "def output_name_instruction(self) -> str:\n output_name_key = \"OutputName\"\n val = \"\"\n if output_name_key in self._instructions:\n val = self._instructions[output_name_key]\n self._log_instruction(output_name_key, val)\n return val", "def origin_output_name(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns ``True`` if the output panel is currently visible.
def is_visible(self): return self.window.active_panel() == self.full_name
[ "def is_visible(self):\n return self._switcher.isVisible()", "def is_visible(self):\n return self.container['is_visible']", "def is_visible(self):\n\n if self._element is None:\n try:\n self._set_element()\n\n except NoSuchUIElement:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the output panel, hiding any other visible panel.
def show(self): self.window.run_command("show_panel", {"panel": self.full_name})
[ "def display_output_panel():\n window = sublime.active_window()\n if window.active_panel() == 'output.YouTubeEditor Log':\n return\n\n # True for always, False for Never, number for Always (but autoclose);\n # thus if this is a boolean and it's False, we should leave. Otherwise,\n # we're good...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hides the output panel.
def hide(self): self.window.run_command("hide_panel", {"panel": self.full_name})
[ "def hide(self):\n self.visible = False", "def hideDisplay(self):\n if self._displayPjt:\n self._displayPjt.hide()\n if self._displayUsr:\n self._displayUsr.hide()\n if self._displayVtk:\n self._displayVtk.hide()", "def hide(self):\n self.showi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destroys the output panel.
def destroy(self): self.window.destroy_output_panel(self.name)
[ "def destroy(self):\n self.disable()\n self.removeNode()\n self.panel.destroy()\n if self.vgpanel:\n self.vgpanel.destroy()", "def _cleanup_panel(self, w):\n if self.registry:\n with self.registry.lock:\n print \"cleaning up panel for\", w.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Получить тип изображения (см. ImageTypes) из текста.
def parse_image_type(text): match = re.match('.*(content|style|result).*', text.lower()) if match is None: return None type = match.group(1) if type == 'content': return ImageTypes.CONTENT elif type == 'style': return ImageTypes.STYLE elif type == 'result': return ImageTy...
[ "def type(self):\n return _image.image_type(self)", "def find_img_type(strng):\n format=(strng.split(\",\",1)[0]).split(\"/\")[1][:-7]\n return format", "def get_type(ext):\n if ext.lower() in Asset.SUPPORTED_IMAGE_EXT['in']:\n return 'image'\n return 'file'", "def imgtyp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Получить id стандартного стиля (см. default_styles) из текста.
def parse_style_id(text): for id, style in default_styles.items(): # for name, age in dictionary.iteritems(): (for Python 2.x) match = re.match('^(' + style['name'].lower() + ')', text.lower()) if match is not None: return id
[ "def get_id(\n style: str,\n mode: GameMode,\n direction: Direction,\n orient: Orient,\n ) -> str:\n return f'{style.casefold()}:{mode.value}_{direction.value}_{orient.value}'", "def getHelpId(self) -> unicode:\n ...", "def _genNumberStyleName(self):\n # from ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export recipe to KRecipes XML string
def toKrecipesXml(self, author=None): sauthor = u'' if not empty(self.author): sauthor += '%s@' % self.author if author is None: sauthor += 'Cookboob' else: sauthor += author header = u'<?xml version="1.0" encoding="UTF-8" ?>\n' initi...
[ "def recipe_dump_fixture():\n\n def elts_process(elts, name):\n \"\"\"Nested element generator\"\"\"\n for i, elt in enumerate(elts):\n i += 1\n elt['id'] = i\n elt['name'] = '%s_%d' % (name, i)\n\n rv = post_recipe_fixture()\n rv['id'] = 1\n elts_process(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a recipe object from an ID.
def get_recipe(self, _id): raise NotImplementedError()
[ "def get_recipe(cls, recipeid):\n\n recipe = Recipe.query.filter_by(recipe_id=recipeid).one()\n\n return recipe", "def find_recipe(self, recipe_id):\n return self.find_doc('recipe', 'name', self.get_unique_recipe_name(recipe_id))", "def fetch_recipe(*, recipe_id: int) -> Any:\n\n result ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves diff encoder fn for image and 3D
def get_encoder_fn_separate(model_type, # e.g., model_type = 'resnet_fc3_dropout' encoder_fn_type = "Encoder_resnet_v2" ): encoder_fn = None threed_fn = None if 'resnet' in model_type: #encoder_fn = Encoder_resnet # added by CCJ encoder_fn = Encoder_resnet_v2...
[ "def get_encoder(self):", "def get_encoder_name(self):\n return \"P\" + str(self.parameters_common_index) + \".\" + str(self.parameters_fs_index) + \"_E\" \\\n + str(self.get_encoder_number())", "def encoder_net_func(num_layer, net_type='cnn'):\n ec_funct = []\n for i in range(num_lay...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
23 Discriminators on each joint + 1 for all joints + 1 for shape. To share the params on rotations, this treats the 23 rotation matrices
def Discriminator_separable_rotations( poses, shapes, weight_decay, ): data_format = "NHWC" with tf.name_scope("Discriminator_sep_rotations", [poses, shapes]): with tf.variable_scope("D") as scope: with slim.arg_scope( [slim.conv2d, slim.fully_connecte...
[ "def _create_inter_muscles_sensorimotor_connections(self):\n\n\t\tfor pathway in self._infoInterMuscSensorimotorConnections:\n\t\t\tconnections = self._infoInterMuscSensorimotorConnections[pathway][\"connections\"]\n\t\t\tmatrix = self._infoInterMuscSensorimotorConnections[pathway][\"matrix\"]\n\t\t\tif not len(mat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read mesh file and set mesh info
def read(self, mesh_path: str) -> None: reader = VtuReader(mesh_path) self.set_mesh_data(mesh=reader.mesh, bc=reader.bc, mpc=reader.mpc)
[ "def read_mesh(\n comm: MPI.Intracomm, file: Path, engine: str, ghost_mode: dolfinx.mesh.GhostMode\n) -> dolfinx.mesh.Mesh:\n adios = adios2.ADIOS(comm)\n io = adios.DeclareIO(\"MeshReader\")\n io.SetEngine(engine)\n infile = io.Open(str(file), adios2.Mode.Read)\n infile.BeginStep()\n\n # Get m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set mesh shape from coordinates and connectivity
def set_shape(self, *, coords: np.ndarray, connectivity) -> None: self._coords = coords self._n_dof, self._n_point = coords.shape if self._n_dof == 3: if np.max(np.abs(coords[2])) < 1.0e-30: self._n_dof = 2 self._n_dfdof = 3 if self._n_dof == 2 else 6 ...
[ "def setup_mesh(self, nmeshx, nmeshy, nmeshz, xlength, ylength, zlength):", "def set_mesh(self, mesh):\n \n self.mesh = mesh", "def __init__(self, coordinates, triangles,\n boundary=None,\n tagged_elements=None,\n geo_reference=None,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that getting a CallError will suppress Exception by default
async def test_suppress_call_error(base_central_system): call_error = CallError( unique_id="1337", error_code="GenericError", error_description="test_raise_call_error", ) await base_central_system.route_message(call_error.to_json()) payload = call.ClearCachePayload() await b...
[ "def test_checked_call_with_bad_call(monkeypatch):\n\n def _return_false():\n return False\n\n monkeypatch.setattr(\"pandas.io.clipboard.get_errno\", lambda: True)\n msg = f\"Error calling {_return_false.__name__} \\\\(Window Error\\\\)\"\n\n with pytest.raises(PyperclipWindowsException, match=ms...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if a given text consists of more nonswiss chars than allowed by the threshold
def check_sentences(text, threshold=80, print_only=False): non_white_text = re.sub(masks, "", re.sub(emojis, "", re.sub(punctuation, "", re.sub("\s", "", text)))) num_chars = len(non_white_text) num_non_swiss_chars = 0 for char in non_white_text: if char not in swiss_chars: num_non_s...
[ "def _is_over(text, word_max, char_max):\n word_over = len(ta.get_words(text)) > word_max\n\n char_over = len(text) > char_max\n\n return word_over or char_over", "def test_bad_chars_from_threshold(self):\r\n exp1 = [\r\n '\\t',\r\n '\\n',\r\n '\\r',\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process infile line by line. If text is below threshold it is written to outfile.
def process_file(path_in, path_out, threshold): infile = open(path_in, "r", encoding="utf-8") outfile = open(path_out, "w", encoding="utf-8") csv_reader = csv.reader(infile) csv_writer = csv.writer(outfile) for i, line in enumerate(csv_reader): try: text_id, text, masked, label_b...
[ "def preprocess_raw_text(source_file, output_file, min_length=5):\n STOP_WORDS = set(stopwords.words('english'))\n TOKENIZER = RegexpTokenizer(r'[a-zA-Z]{2,}')\n WORDS = set(nltk.corpus.words.words())\n\n total_sent = 0\n sent_count = 0\n write_file = open(output_file, 'a+')\n\n with open(sourc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the view with the specified model and screen.
def __init__(self, model, screen): self.model = model self.screen = screen
[ "def __init__(self, view, model):\n self.view = view\n self.view.set_controller(self)\n self.model = model", "def __init__(self, model, view):\n self._model = model\n self._view = view", "def __init__(self, model, screen):\n self.model = model\n self.mouse_pos = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queue a mail for delivery at the end of the transaction. We don't immediately call mailhost.send() here, but instead place mails to be sent in a queue that gets processed at the end of the transaction. We need to do this because mailhost.send() registers an IDataManager without savepoint support (zope.sendmail.delivery...
def send_mail(self, msg): mail_queue.put(msg)
[ "def queueMail(self, mail):\n if mail is not None:\n assert isinstance(mail, Message)\n self.mailQueue.put(mail)", "def queue_mail(self, x_ask_info=\"Message Queued\"):\n\n\t\tself.log.write(5, \" queue_mail(): x_ask_info = %s\" % x_ask_info)\n\t\tself.log.write(5, \" queue_mail()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instanciation de la grille remplie de 0
def __init__(self): self.grille = [] for i in range(3): self.grille.append([0, 0, 0])
[ "def __init__(self, *args):\n self.ruban = ['0'] * type(self).DIM\n if len(args) == 3:\n # la position de l'oeil est désignée\n p, n1, n2 = args\n if int(type(self).DIM / 2) < n1 + n2 + 4:\n sys.stderr.write(\"[ValueError] valeurs trop grandes\\n\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retourne le nombre de tours
def nbr_tours(self): nbr_tours = 0 for i in range(3): for j in range(3): if self.grille[i][j] != 0: nbr_tours += 1 return nbr_tours
[ "def getNbJoueurs(joueurs):\n return len(joueurs)-1", "def nbTresorsRestantsJoueur(joueurs,numJoueur):\n nbtresor=getNbTresorsRestants(joueurs['liste'][numJoueur])\n return nbtresor", "def numJoueurCourant(joueurs):\n return joueurs[0]", "def nomJoueur(joueurs,numJoueur):\n return joueurs[numJo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test si la partie a un vainqueur. Comme la grille est remplie de nombre et non de croix, cercle et vide, on multiplie le contenu des cases pour savoir s'il y a un vainqueur. Le résultat 1 signifie trois 1 d'alignés alors que 8 implique trois deux d'alignés. Sinon, le résultat serait 0. Cette fonction retourne le numéro...
def vainqueur(self): if (self.grille[0][0]*self.grille[0][1]*self.grille[0][2] == 1 or self.grille[1][0]*self.grille[1][1]*self.grille[1][2] == 1 or self.grille[2][0]*self.grille[2][1]*self.grille[2][2] == 1 or self.grille[0][0]*self.grille[1][0]*self.grille[2][0] ==...
[ "def est_plein(plateau):\n return nombre_cases_vides(plateau) == 0", "def test_case_vide(self):\n\n grille = jeu2048()\n grille.matrice = [2, 2, 0, 0,\n 2, 0, 2, 0,\n 2, 0, 0, 2,\n 0, 2, 8, 0]\n\n correction = len(g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retourne une grille copiée
def copier(self): # Instanciation d'une nouvelle grille grille_copiee = Grille() for i in range(3): for j in range(3): grille_copiee.grille[i][j] = self.grille[i][j] return grille_copiee
[ "def conseguir_grosor(self):\n return self.pluma.conseguir_grosor()", "def getCouleur(self):\r\n return ['pique', 'coeur', 'carreau', 'trefle' ][self.Couleur - 1] # Rectifié\r", "def ubicacion_cuadrado(posicion_del_mouse):\r\n for j in range(16):\r\n if Totalcuadrados[j].collide...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tourne de 90 degrés la grille du morpion
def tourner90(self): grille_copie = self.copier() for i in range(3): for j in range(3): #tour.x, tour.y = -(tour.y-1)+1, (tour.x-1)+1 self.grille[-j+2][i] = grille_copie.grille[i][j]
[ "def l_to_g(liter: float) -> float:\n return liter * 0.26417", "def get_range(self):\r\n\t\tif self.battery_size == 70:\r\n\t\t\trange = 240\r\n\t\telif self.battery_size == 83:\r\n\t\t\trange = 270\r\n\t\tmessage = \"This car can go approximately \" + str(range)\r\n\t\tmessage += \" miles on a full charge.\"\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tourne de 180 degrés la grille du morpion
def tourner180(self): self.tourner90() self.tourner90()
[ "def lng180(lng):\n newlng = float(lng)\n if lng <= -180:\n return lng + 360\n if newlng > 180:\n return lng - 360\n return lng", "def lon_convention(lon):\n if lon.min() < 0:\n return 180\n else:\n return 360", "def calor_latente(tmed):\n return 2.501-(2.361*tme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tourne de 270 degrés la grille du morpion
def tourner270(self): self.tourner180() self.tourner90()
[ "def widthToDeg(width):\n return ((width / 1920.0) * 360.0) - 180", "def heightToDeg(height):\n return ((height / 960) * 180) - 90", "def tourner90(self):\n grille_copie = self.copier()\n for i in range(3):\n for j in range(3):\n #tour.x, tour.y = -(tour.y-1)+1, (to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Vérifie que deux grilles sont équivalentes.
def __eq__(self, grille): grille_tmp = grille.copier() if self.grille == grille_tmp.grille: return 1 grille_tmp.tourner90() if self.grille == grille_tmp.grille: return 1 grille_tmp.tourner90() if self.grille == grille_tmp.grille: return...
[ "def __ge__(self, others):\r\n if self.__eq__(others): # Poligono uguali\r\n if self.__gt__(others): # Poligoni maggiori\r\n return (True)\r\n else:\r\n return (False)\r\n else:\r\n return (False)", "def __in__(self, grilles):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Vérifie qu'une grille ou une de ses équivalente sont dans une suite de grille
def __in__(self, grilles): for grille in grilles: if self == grille: return 1 return 0
[ "def checkGagnant(self, joueur):\r\n\r\n for i in range(3): #Lignes\r\n if self.grille.grille[i][0] == self.grille.grille[i][1] == self.grille.grille[i][2] == joueur:\r\n return joueur\r\n for j in range(3): #Colonnes\r\n if self.grille.grille[0][j] == self.grille....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ajoute un nouveau tour dans la partie seulement si la case est libre donc contient 0.
def nouveau_tour(self, tour): # Teste si la case est libre if self.grille.case(tour.x, tour.y) == 0: nbr_tour = len(self.tours)+1 # Calcul du nombre de tour tour.numero = nbr_tour if nbr_tour%2 == 1: # Décide du joueur du tour tour.joueur = 1 ...
[ "def jouerPartie(self):\n from TerminalView.PartieView import finPartie\n logger.info(\"Début de partie\")\n while not self.partie.estGagnee() or not self.partie.estPerdue():\n self.jouerTour()\n finPartie(self)\n return 0", "def jouerTour(self):\n logger.info(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copie la partie dans un autre objet
def copier(partie): # Instanciation d'une nouvelle partie partie_copiee = Partie() for tour in partie.tours: tour_tmp = Tour(tour.x, tour.y) # Instanciation d'un tour partie_copiee.nouveau_tour(tour_tmp) # Ajout du tour return partie_copiee
[ "def prepare(self):\n fname = self.getstyle(\"obj-filename\")\n if fname:\n self.obj = get_obj(fname)\n else:\n self.obj = None\n print \"ObjPart \",self._name,\"failed to load\",fname \n \n self.pieces = self.getstyle('obj-pieces')\n if sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tourne de 180 degrés la grille du morpion
def tourner180(self): self.tourner90() self.tourner90()
[ "def lng180(lng):\n newlng = float(lng)\n if lng <= -180:\n return lng + 360\n if newlng > 180:\n return lng - 360\n return lng", "def lon_convention(lon):\n if lon.min() < 0:\n return 180\n else:\n return 360", "def calor_latente(tmed):\n return 2.501-(2.361*tme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tourne de 270 degrés la grille du morpion
def tourner270(self): self.tourner180() self.tourner90()
[ "def widthToDeg(width):\n return ((width / 1920.0) * 360.0) - 180", "def heightToDeg(height):\n return ((height / 960) * 180) - 90", "def tourner90(self):\n grille_copie = self.copier()\n for i in range(3):\n for j in range(3):\n #tour.x, tour.y = -(tour.y-1)+1, (to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Une fois qu'un arbre est générer, on peut vouloir connaître son nombre de feuille. De plus on peut choisir les feuilles, donc les parties qui sont gagnées par un joueur spécifique et en un certain nombre de tours.
def lister_feuilles(self, vainqueur, nbr_tours): # On teste d'abord le nombre de parties filles de l'arbre. # Si ce nombre est nul, cela correspond à une feuille. # On vérifie le vainqueur et le nombre de tours avant de # conserver la feuille. # Si ce n'est pas une feuille, par r...
[ "def lister_feuilles_2(self, vainqueur, nbr_tours):\n if self.nbr_fils == 0:\n if (vainqueur == -1 and nbr_tours == -1):\n return [self.partie]\n elif (vainqueur == -1 and nbr_tours == len(self.partie.tours)):\n return [self.partie]\n elif (self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Identique à la fonction lister_feuilles mais ici on ne garde pas deux feuilles qui ont des grilles équivalentes.
def lister_feuilles_2(self, vainqueur, nbr_tours): if self.nbr_fils == 0: if (vainqueur == -1 and nbr_tours == -1): return [self.partie] elif (vainqueur == -1 and nbr_tours == len(self.partie.tours)): return [self.partie] elif (self.partie.gril...
[ "def lister_feuilles(self, vainqueur, nbr_tours):\n # On teste d'abord le nombre de parties filles de l'arbre.\n # Si ce nombre est nul, cela correspond à une feuille.\n # On vérifie le vainqueur et le nombre de tours avant de\n # conserver la feuille.\n # Si ce n'est pas une feui...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compose ad types, intended for dense a and sparse b
def compose(a,b,shape_factor=None): if isinstance(a,Dense.denseAD) and (isinstance(b,Sparse.spAD) or all(isinstance(e,Sparse.spAD) for e in b)): elem = None size_factor = np.prod(shape_factor) if shape_factor is None: if not isinstance(b,Sparse.spAD): raise ValueError("Compose error : unspecified shape_fa...
[ "def compose_types(a, b, *cs):\n mcls = (a, b) + cs\n return type(\n 'compose_types(%s)' % ', '.join(map(attrgetter('__name__'), mcls)),\n mcls,\n {},\n )", "def dot(self, adim, bdim, b, asdense=False):\n if hasattr(adim,'__iter__') and hasattr(bdim,'__iter__'):\n a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a list of field texts, convert to a list of lists of fields, where each list of fields is no more than 10 fields, and each field
def make_fields(self, ftext): fields = [{'type': 'mrkdwn', 'text': x} for x in ftext] return utils.chunks(fields, 10)
[ "def split_typed_field_list(field):\n\ttyped_fields = []\n\tfields = split_field_list(field)\n\tfor field in fields:\n\t\ttyped_fields.append(to_typed_field(field))\n\treturn typed_fields", "def _create_field_list(entities: List[Entity], features: List[Feature]) -> List[Field]:\n fields: List[Field] = []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return middleware wrangler for display module type.
def get_wrangler(cls): raise NotImplementedError()
[ "def get_wrangler(cls):\n return MethylWrangler", "def _llm_type(self) -> str:", "def get_maintype(self):\n return self.get_mimetype().split('/')[0]", "def get_wrangler(cls):\n return TaxaTreeWrangler", "def module(filter_):\n def decorator(module_fn):\n \"\"\"Decorates a module fun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enumerate which ToolResult modules a sample must have for this task to run.
def required_tool_results(): raise NotImplementedError()
[ "def required_tool_results():\n return [MethylResultModule]", "def required_tool_results():\n return [Metaphlan2ResultModule, KrakenResultModule, KrakenHLLResultModule]", "def test_modules_list(self):\n self.mods.pipeline_dir = None\n listed_mods = self.mods.list_modules()\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of hooks to run before transmission to the client.
def transmission_hooks(cls): return []
[ "def hooks(self):\n return tuple(self.__hooks.keys())", "def getHooks(self):\n return self.__hooks", "def extension_hooks(self, global_step):\n return []", "def get_hooks(self, type_: str) -> typing.Iterable:\n hooks = []\n if self._parent:\n hooks.extend(self._pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if this display module is dependent on a given Tool Result type.
def is_dependent_on_tool(cls, tool_result_cls): required_tools = cls.required_tool_results() return tool_result_cls in required_tools
[ "def _depend(self, deplst, verbose=False, stop_on_false=True):\n hooks = self.cse.runhooks\n info = self.info\n # check.\n metlst = []\n msglst = []\n for ahook in deplst:\n metlst.append(False)\n for obj in hooks:\n if isinstance(obj, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform my_query_result to data.
def get_data(cls, my_query_result): return my_query_result
[ "def unpack_query_response(self, query_result_array):\n result = []\n\n for row in query_result_array:\n result.append({\n 'case_id': row['f'][0]['v'],\n 'sample_id': row['f'][1]['v'],\n 'aliquot_id': row['f'][2]['v'],\n 'value': f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of hourly forecasts, returns a boolean specifying whether there is rain in tomorrow's forecast.
def is_raining_tomorrow(data): pendulum.now("utc").add(days=1).strftime("%Y-%m-%d") rain = [ w for forecast in data["list"] for w in forecast["weather"] if w["main"] == "Rain" and forecast["dt_txt"].startswith(tomorrow) ] if not bool(rain): raise SKIP("There is no...
[ "def contains_forecasts(self) -> bool:\n return self._forecasts is not None or len(self._forecasts) == 0", "def contains_holiday(dates: List[datetime.date]) -> bool:\n\n for date in dates:\n if date in us_holidays:\n return True\n return False", "def check_overlap(wrf_path,ts_now)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calls the scanPrices function to input item prices, calls the scanCoupons function to input coupon values. Calculates customer's balance and pass it to the makePayment function.
def main(): # Introduce program print("WAKE-MART SELF-CHECKOUT\n") print("This program will\n" "\t- obtain the number of items and the price for each;\n" "\t- calculate the total price for all items;\n" "\t- obtain the number of coupons;\n" "\t- calculate the...
[ "def order_icecream(coupon_disc=0):\n customer_name = input(\"Enter customer name: \")\n total_amount = 0.0\n total_orders = 0\n while True:\n total_quantity = 0\n while True:\n # get the ice cream from customer\n icecream = input(\"Choose the Ice cream you wish to en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate if the given admin_secret is the correct one
def validate_admin (admin_secret): try: admin_secret = admin_secret.encode() hashed = app.config['ADMIN_SECRET'].encode() return bcrypt.checkpw(admin_secret, hashed) except Exception as e: return False
[ "def validate_db_admin (db_secret):\n\n try:\n db_secret = db_secret.encode()\n hashed = app.config['DB_SECRET'].encode()\n return bcrypt.checkpw(db_secret, hashed)\n except Exception as e:\n return False", "def verify_admin_password(password: str) -> bool:\n # Ensure password...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate if the given db_secret is the correct one
def validate_db_admin (db_secret): try: db_secret = db_secret.encode() hashed = app.config['DB_SECRET'].encode() return bcrypt.checkpw(db_secret, hashed) except Exception as e: return False
[ "def validate_admin (admin_secret):\n\n try:\n admin_secret = admin_secret.encode()\n hashed = app.config['ADMIN_SECRET'].encode()\n return bcrypt.checkpw(admin_secret, hashed)\n\n except Exception as e:\n return False", "def validate_secret(self, secret):\n if secret and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sign the payload with jwt using secret key Return as API key Expiry = 100 days
def encode_payload(payload): jwt_secret = app.config['SECRET_KEY'] # expiry = 60 * 60 * 24 * 100 # 100 days # payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(seconds=expiry) encoded_jwt = jwt.encode(payload, jwt_secret, algorithm='HS256') return (encoded_jwt).decode()
[ "def sign_id_token(payload):\n signing_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(TESTING_JWT_KEYSET))\n return jwt_encode(\n payload,\n signing_key,\n algorithm=\"RS256\",\n headers={\"kid\": TESTING_JWT_KEYSET[\"kid\"]},\n )", "def _generate_jwt_token(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode the payload with jwt using secret key Return the payload if valid
def decode_payload(encoded_payload): jwt_secret = app.config['SECRET_KEY'] payload = jwt.decode(encoded_payload, jwt_secret, algorithms='HS256') return payload
[ "def decode(encoded_token):\n return jwt.decode(encoded_token, key=settings.JWT_AUTH['JWT_SECRET_KEY'])", "async def decode_auth_value(token):\n try:\n payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])\n except jwt.exceptions.DecodeError:\n raise ValidationError(error_msg=\"Inva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the API access of the given app
def update_api_access(info): try: file = open(PATH + "/../DB/access.json", 'r') accessData = json.load(file) except: raise try: accessData[info['application_name']] = { 'api_list': info['api_list'], 'timestamp': info['timestamp'] } except ...
[ "def FUNCTION_NAME(self, **kwargs):\n return self.send_request('/oauth/apps/{app_id}', 'put', **kwargs)", "async def update_app_oauth(self, app_id: str, data: dict) -> dict:\r\n return await self.put(API_APP_OAUTH.format(app_id=app_id), data)", "async def update_app(self, app_id: str, data: dict) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Revoke the API access of this application
def revoke_api_access(application): try: file = open(PATH + '/../DB/access.json', 'r') accessData = json.load(file) if (application in accessData): accessData.pop(application, None) with open(PATH + '/../DB/access.json', 'w') as f: f.write(json.dumps(accessDa...
[ "def revokePermission(self, request):\n pass", "def delete_api_key(api_key):\n api.delete(api_key)", "def revoke_user_access(self):\n self.test_runner.run_user_access_revoke()", "def revokePermission(self, request):\n self.send_revokePermission(request)\n self.recv_revokePermission()", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to print out error of LSE
def show_error(self): print('LSE Error : {}'.format(self._error))
[ "def print_gsl_errors () :\n \n gsl_cnt = Ostap.Utils.GslCount\n if 0 == gsl_cnt.size() : return ## No GSL errors \n \n ## get the summary \n table = gsl_cnt.table()\n rows = [] \n for tline in table :\n \n try: \n n , code , msg , reason , file , line = tline\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load requests' cookies from a file
def __loadCookies(self): with open(self.cookies_file, 'rb') as cookie_file: LOGGER.debug("Unpickling HTTP cookies from file: {0}".format(self.cookies_file)) session.cookies = requests.utils.cookiejar_from_dict(pickle.load(cookie_file))
[ "def load_cookies(filename):\n with open(filename, 'rb') as f:\n requests_cookiejar = pickle.load(f)\n return requests_cookiejar", "def load_cookies(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)", "def _load_cookies(filename):\n with open(filename, 'rb') as handl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given int, print digits in reverse order, starting with the ones place >>> print_digits(1) 1 >>> print_digits(314) 4 1 3 >>> print_digits(12) 2 1
def print_digits(num): # Given an integer, print each digit in reverse order, starting with the ones place. # # For example, if you were given 1 you should simply print 1, if given 314 you should print 4, 1, 3, and if given 12 you should print 2, 1: # Implement print_digits. Do not do this by just turnin...
[ "def digits(n, base=10):\n lst = rdigits(n, base)\n lst.reverse()\n return lst", "def reverse(n):\r\n if n < 10:\r\n return n\r\n else:\r\n return combine(n % 10 , reverse(n // 10))", "def reverse_digits(number: int):\n acc = 0\n\n while number != 0:\n acc *= 10\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate flooding destinations based on this DP's position. If a standalone switch, then flood to local VLAN ports. If a distributed switch, see the following example. Hosts |||| |||| ++ ++ ++ +1 | |1234| | 1+ Hosts +2 | | | | 2+ Hosts +3 | | | | 3+ +4 5++5 6++5 4+ ++ ++ ++ Root DP The basic strategy is floodtowardsro...
def _build_flood_rule_actions(self, vlan, exclude_unicast, in_port): local_flood_actions = self._build_flood_local_rule_actions( vlan, exclude_unicast, in_port) # If we're a standalone switch, then flood local VLAN if self.stack is None: return local_flood_actions ...
[ "def flood(self, msg):\r\n datapath = msg.datapath\r\n ofproto = datapath.ofproto\r\n\r\n for dpid in self.awareness.access_ports:\r\n for port in self.awareness.access_ports[dpid]:\r\n if (dpid, port) not in self.awareness.access_table.keys():\r\n d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add ``django_hipchat`` to ``INSTALLED_APPS`` Ensure ``django.template.loaders.app_directories.Loader`` is in your ``TEMPLATE_LOADERS``. >>> from django_hipchat.api import message >>> message("path/to/my_message.hipchat", {
def hipchat_message(template, context=None, fail_silently=app_settings.FAIL_SILENTLY): if not app_settings.ENABLED: return context = Context(context or {}) context['settings'] = settings def render(component): component_template = 'django_hipchat/%s' % component return rende...
[ "def add_message(self, request, level, message_template,\n message_context=None, extra_tags=''):\n if 'django.contrib.messages' in settings.INSTALLED_APPS:\n try:\n if message_context is None:\n message_context = {}\n message = re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Checks that cotraining parameters are valid. Throws AttributeError if estimators are invalid. Throws ValueError if any other parameters
def _check_params(self): # verify that estimator1 and estimator2 have predict_proba if (not hasattr(self.estimator1_, 'predict_proba') or not hasattr(self.estimator2_, 'predict_proba')): raise AttributeError("Co-training classifier must be initialized " ...
[ "def check_parameters(self):\n pass", "def check_parameters_func():\n\n # The model has not been set up.\n if not hasattr(cdp, 'params'):\n return RelaxError(\"The frame order model has not been set up, no parameters have been defined.\")\n\n # The model has been set up.\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Predict the classes of the examples in the two input views.
def predict(self, Xs): Xs = check_Xs(Xs, multiview=True, enforce_views=self.n_views) X1 = Xs[0] X2 = Xs[1] # predict each view independently y1 = self.estimator1_.predict(X1) y2 = self.estimator2_.predict(X2) # initi...
[ "def test_multifield_classify(self):\n self.model.fit(self.text_data_train, self.train_targets)\n self.assertTrue(self.model.is_classification)\n predictions = self.model.predict(self.text_data_valid)\n self.model.save(self.save_file)\n model = LanguageModelGeneralAPI.load(self.sa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increase linearly from initial to final over T then remain at final.
def linear(initial, final, T): def f(t): if t < T: r = t / float(T) p = (1 - r) * initial + r * final else: p = final return p return f
[ "def inc_tau_trans(self):\r\n self.num_tau_trans += 1", "def temp_update(self):\n a_w = self.k / self.dx\n a_e = self.k / self.dx\n a_n = self.k / self.dy\n a_s = self.k / self.dy\n a_p = a_w + a_e + a_n + a_s + self.rho * self.cp * self.dx / self.dt\n for i, j in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that get_category_data has access to Category model data
def test_category_has_access_to_model_data(): category = Category() category_data = category.get_category_data() assert type(category_data) is list assert len(category_data) > 1
[ "def test_get_category(self):\n response = client.get(self.category_url)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.data['name'], self.category.name)", "def test_get_categories(self):\n pass", "def test_get_category_details(self):\n category = sa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects labels in the file.
def detect_labels(path): client = vision.ImageAnnotatorClient() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.label_detection(image=image) labels = response.label_annotations #print('Labels:') #fo...
[ "def detect_labels(path):\r\n\r\n with io.open(path, 'rb') as image_file:\r\n content = image_file.read()\r\n\r\n image = vision.types.Image(content=content)\r\n\r\n response = client.label_detection(image=image)\r\n labels = response.label_annotations\r\n answer = 'There are ';\r\n for lab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects image properties in the file.
def detect_properties(path): client = vision.ImageAnnotatorClient() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.image_properties(image=image) props = response.image_properties_annotation return prop...
[ "def detect_properties(path):\n from google.cloud import vision\n import io\n client = vision.ImageAnnotatorClient()\n\n with io.open(path, 'rb') as image_file:\n content = image_file.read()\n\n image = vision.Image(content=content)\n\n response = []\n response = client.image_properties(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The minimum possible roll given the dice on this roller.
def minimum_roll(self): return self.number
[ "def maximum_roll(self):\n if self.dice_array is None:\n return self.number * self.sides\n else:\n return np.sum(self.dice_array)", "def get_damage_roll(self):\n\t\tif self.difficulty == 1:\n\t\t\treturn 4\n\t\tif self.difficulty == 2:\n\t\t\treturn 6\n\t\tif self.difficulty ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The maximum possible roll given the dice on this roller.
def maximum_roll(self): if self.dice_array is None: return self.number * self.sides else: return np.sum(self.dice_array)
[ "def max_dice(self):\n return self.check_cached_value(\"max_dice\", default_values.MAX_DICE)", "def roll_die(sides = 6, maxi = 6):\n d = 1000\n # discard highest roll(s)\n while d > maxi:\n d = random.randint(1,sides)\n return d", "def max_scoring_num_rolls(dice=six_sided):\n \"*** ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Roll all the dice present on this object. Rolls either each dice of sides self.sides for each self.number of dice, or a dice of each integer in the self.dice_array list.
def roll(self): rolls = [] if self.dice_array is not None: for dice in self.dice_array: rolls.append(np.random.randint(1, dice+1)) else: for _ in range(0,self.number): rolls.append(np.random.randint(1, self.sides+1)) #Fast way from ...
[ "def roll_the_dice(self, dice):\n if type(dice) == list:\n for die in dice:\n die.roll()", "def roll(self) -> 'Roll':\n rolls = {\n dice_size: [random.randint(1, dice_size) for _ in range(n)]\n for (dice_size, n) in self.dice.items()\n }\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute heat index given the temperature and humidity
def compute_heatindex(t,hum): a = -42.379 b = 2.04901523 c = 10.14333127 d = 0.22475541 e = 0.00683783 f = 0.05481717 g = 0.00122874 h = 0.00085282 i = 0.00000199 rh = hum/100 hi = (a+(b*t)+(c*rh)+(d*t*rh)+(e*t**2)+(f*rh**2)+(g*rh*t**2)+(h*t*rh**2)+(i*t**2*rh**2)) retur...
[ "def compute_heatindex(temperature, humidity):\n\n a = -42.379\n b = 2.04901523\n c = 10.14333127\n d = 0.22475541\n e = 0.00683783\n f = 0.05481717\n g = 0.00122874\n h = 0.00085282\n i = 0.00000199\n\n rh = humidity / 100\n\n heat_index = (a + (b * temperature) + (c * rh) + (d * t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse chess.Board() to a List[List[chr]]
def board_to_list_of_list(self): str_board = str(self.__board).replace(" ", "") list_board = str_board.split("\n") list_of_list_board1 =[line.split(",") for line in list_board] list_of_list_board =[utils.split_string_to_chars(l) for [l] in list_of_list_board1] return list_of_lis...
[ "def read_board(ascii_board):\n\tboard = []\n\trow = []\n\tcol_num = 0\n\tfor char in ascii_board:\n\t\tif(col_num < 10):\n\t\t\trow.append(char)\n\t\t\tcol_num += 1\n\t\telse:\n\t\t\tboard.append(row)\n\t\t\trow = []\n\t\t\tcol_num = 0\n\treturn board", "def prepare_board(board):\n board_array = []\n row =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decompose a square into a tuple (file, rank, x, y)
def parse_square_to_list_index_position(self, square: str): file = utils.split_string_to_chars(square)[0] rank = utils.split_string_to_chars(square)[1] x = 8 - int(rank) y = ord(file) - 97 # board_list = self.board_to_list_of_list() # Piece = board_list[x][y] ret...
[ "def toCoords(piece):\n return(piece.getRank()-1,piece.getFile()-1)", "def get_square(self, rank, file):\r\n\t\tif rank < 1 or rank > 8 or file < 1 or file > 8:\r\n\t\t\treturn None\r\n\t\treturn self.board[(rank - 1) * 8 + file - 1]", "def rank_and_file(piece):\n dimensions = piece.board_dimensions\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decompose a uci_move into a tuple of squares
def parse_move_to_square(self, uci_move: str): chars = utils.split_string_to_chars(uci_move) square_from = ''.join(chars[0] + chars[1]) square_to = ''.join(chars[2] + chars[3]) return square_from, square_to
[ "def _AN_to_coords(self, move: str):\n\n orig_move = move\n\n extra_info = \"\"\n\n # remove all characters that don't matter when parsing\n for pointless_char in \"x+#\":\n move = move.replace(pointless_char, \"\")\n\n # Handle castling\n if CASTLE_QUEENSIDE in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
display the board, and if PLAY is true, call generate()
def draw(): background(255) for i in range(COLS): for j in range(ROWS): if (BOARD[i][j] == 1): fill(0) else: fill(255) noStroke() # stroke(0) rect(i * CELL_SIZE, j * CELL_SIZE, CELL_SIZE, CELL_SIZE) if (PLAY): generate()
[ "def show_board(self):\n self._game_board.display()", "def display_board(self):\n if STANDARD_POSITION:\n position = games.STANDARD_GAME\n else:\n games_source = games.GamePositions()\n position = games_source.random_game()\n current_board = board.Board...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset board when 'r' is pressed Pause/Play when SPACE BAR is pressed
def keyPressed(): global PLAY if (key == ' '): PLAY = not PLAY if (key == 'r'): init()
[ "def reset_board(self):\n self.board = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n self.turn = 0\n\n self.change_button_img_to_null()\n\n #self.Score_Label.grid(row=0,column=1, ipadx=32)\n\n self.player_highlight()\n self.change_button_state('normal')\n self.update_score()", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fill board with random values 0 or 1
def init(): for i in range(COLS): for j in range(ROWS): BOARD[i][j] = int(random(2))
[ "def populate_random(self, prob=0.5):\n for row in range(self.height):\n for col in range(self.width):\n self.cells[row][col] = 1 if random.random() <= prob else 0", "def randomfill(self):\r\n for r in range(self.rows):\r\n for c in range(self.columns):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the transliteration mapping.
def __init__(self, encoding): self.trans = {} for char in u"ÀÁÂẦẤẪẨẬÃĀĂẰẮẴẶẲȦǠẠḀȂĄǍẢ": self.trans[char] = u"A" for char in u"ȀǞ": self.trans[char] = u"Ä" self.trans[u"Ǻ"] = u"Å" self.trans[u"Ä"] = u"Ae" self.trans[u"Å"] = u"Aa" for char in ...
[ "def __init__(self, mapping):\n if len(mapping) != 26:\n raise ValueError('SubstitutionCipher requires a 26-letter mapping.')\n self.charsets = [\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n 'abcdefghijklmnopqrstuvwxyz'\n ]\n self.mappings = [\n ''.join([...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a copy of given VarList. New vars_ depend on existing vars for initialization.
def copy(self): var_copies = [tf.Variable(var.initialized_value, name=var.op.name+"_copy") for var in self.vars_] return VarList(var_copies, name="copy_"+self.name)
[ "def _copy_vars(v_list):\n t_list = []\n for v in v_list:\n t_list.append(tf.identity(v))\n return t_list", "def VarListCopy(DestinationList, DesitnationStart, SourceList, SourceStart, NumToCopy=0):\n pass", "def createVars(self, *vars):\n for var in vars:\n if type(var) == list or ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates group of assign ops that copies value of current VarList to other VarList.
def assign(self, other): assert isinstance(other, VarList) assert len(self) == len(other) ops = [] for (my_var, other_var) in zip(self.vars_, other.vars_): ops.append(my_var.assign(other_var)) return tf.group(*ops, name="assign_"+self.name)
[ "def _restore_vars(v_list, t_list):\n ops = []\n for v, t in zip(v_list, t_list):\n ops.append(v.assign(t))\n return ops", "def assign_scope(from_scope, to_scope):\n assigns = []\n to_vars = variables.trainable_variables(to_scope)\n from_vars = variables.trainable_variables(from_scope)\n for dst, src in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an op that subtracts other from current VarList. sess.run(a.sub(b)) subtracts b from a
def sub(self, other, weight=one): assert isinstance(other, VarList) assert len(self) == len(other) ops = [] if isinstance(weight, VarStruct): weight = weight.var for (my_var, other_var) in zip(self.vars_, other.vars_): ops.append(my_var.assign_sub(weight*other_var)) retur...
[ "def __sub__(self, other):\n try:\n total = {self.var: 1, other.var: -1}\n return AutoDiffReverse(self.val - other.val, None, der=total)\n except AttributeError:\n return AutoDiffReverse(self.val - other, None, {self.var: 1})", "def __sub__(self, other):\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates all covariance/SVD info of correctable factors.
def update_stats(self): # todo: split into separate stats/svd updates s = self ops = [] # update covariances # s.grad.update() # TODO: not needed # s.grad2.update() for var in s: ops.append(s[var].A.cov_update_op) ops.append(s[var].B2.cov_update_op) with u.timeit(...
[ "def onUpdateFactors(self, evt):\n\t\tif self.blockFactorUpdate:\n\t\t\tprint \"Blocking factor update\"\n\t\t\treturn\n\t\tx, y, z = self.dataUnits[0].dataSource.getOriginalDimensions()\n\t\tfx = 1\n\t\tfy = 1\n\t\tfz = 1\n\t\ttry:\n\t\t\tfx = float(self.factorX.GetValue())\n\t\t\tfy = float(self.factorY.GetValue(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether given variable is getting kfac corrected.
def needs_correction(self, var): global matmul_registry if var in matmul_registry: return True else: return False
[ "def isgood(self):\n\t\tanswer = True\n\t\t\n\t\tif self.mes_flux <= 0.0:\n\t\t\tanswer = False\n\n\t\treturn answer", "def gammaTransportIsRequested(cs):\n return GAMMA in cs[\"globalFluxActive\"]", "def is_knot(self):\n return self.number_of_components() == 1", "def is_consistent(self, k):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts IndexedGrad object, produces corrected version.
def correct(self, grad): s = self vars_ = [] grads_new = [] assert list(grad) == self.model.trainable_vars dsize = get_batch_size(grad) for var in grad: vars_.append(var) A = s.extract_A(grad, var) # extract activations B = s.extract_B(grad, var)*dsize # extract b...
[ "def _inv_grad(x, y, name=None):\n result = _op_def_lib.apply_op(\"InvGrad\", x=x, y=y, name=name)\n return result", "def test_indexing(self, grad):\r\n x = np.tensor([[0, 1, 2], [3, 4, 5]], requires_grad=grad)\r\n\r\n assert isinstance(x[0], np.tensor)\r\n assert x[0].requires_grad is grad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize/reset all optimization related variables. This method initializes correction factors to identity and resets history of the optimization.
def reset(self): s = self s.step_counter = 0 # TODO: initialize first layer activations here, and not everywhere else # self.model.initialize_local_vars() # self.model.initialize_global_vars() ops = [] for var in self.model.trainable_vars: if self.needs_correction(var...
[ "def resetParams(self):\n self.prediction = cons.init_pred # Classifier payoff - initialized to a constant initial payoff value\n self.error = cons.init_err # Classifier error - initialized to a constant initial error value\n self.fitness = cons.init_fit # Classifier fitness ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replacement for sess.run which works with custom types.
def run(self, *ops): new_ops = [] for op in ops: if isinstance(op, VarStruct): new_ops.append(op.var) else: new_ops.append(op) if len(new_ops) == 1: return self.sess.run(new_ops[0]) return self.sess.run(new_ops)
[ "def sessrun(*args, **kwargs):\n global sess, run_metadata\n \n if not DO_TRACING:\n return sess.run(*args, **kwargs)\n \n run_metadata = tf.RunMetadata()\n kwargs['options'] = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n kwargs['run_metadata'] = run_metadata\n result = sess.run(*args, **kwargs)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process the a line from the file and create a student return student
def __createStudentFromLine(self, line): fields = line.split(' ') st = student(fields[0], fields[1]) return st
[ "def read_stu_file(filename):\n students = []\n \n f = open(filename, 'r')\n if f == None:\n print \"TT Error: read_stu_file could not open file:\", filename \n \n else:\n stud_count = 1\n for line in f:\n print line.strip()\n new_student = Student(stud_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load __students from file process file line by line
def __loadFromFile(self): fh = open(self.__fileName) for line in fh: if line.strip() == " ": continue # we have an empty line, just skip st = self.__createStudentFromLine(line) # invoke the store method from the base class StudentsRepo.sto...
[ "def file_read() -> list:\n list_of_students = []\n with open(\"students.txt\", \"r\") as file_object:\n file = file_object.readlines()\n for line in file:\n student_text = line.split()\n student_instance = Student(student_text[0], student_text[1], student_text[2], eval(student_text[3]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append a new line in the file representing the student st
def __appendToFile(self, st): fh = open(self.__fileName, "a") line = st.get_id_student() + " " + st.get_nume_student() fh.write("\n") fh.write(line) fh.close()
[ "def __appendToFile(self, sub):\n fh = open(self.__fileName, \"a\")\n line = sub.get_id_disciplina() + \" \" + sub.get_nume_disciplina() + \" \" + sub.get_profesor()\n fh.write(\"\\n\")\n fh.write(line)\n fh.close()", "def file_write(student_object: Student) -> bool:\n filena...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append a new line in the file representing the student st
def __appendToFile(self, sub): fh = open(self.__fileName, "a") line = sub.get_id_disciplina() + " " + sub.get_nume_disciplina() + " " + sub.get_profesor() fh.write("\n") fh.write(line) fh.close()
[ "def __appendToFile(self, st):\n fh = open(self.__fileName, \"a\")\n line = st.get_id_student() + \" \" + st.get_nume_student()\n fh.write(\"\\n\")\n fh.write(line)\n fh.close()", "def file_write(student_object: Student) -> bool:\n filename = \"students.txt\"\n # FileNotFo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute cluster centers based on PCA 3d data. We transform each data point in a 3d vector using PCA. Then, using the labels associated to a cluster solution, we compute the center of the cluster. Currently, we simply compute the average of each dimension. Other schemes can be explored.
def computeCenters3d(self, data): for i in range(self.nPoints): print("Label of point ", i, " is ", self.labels[i]) for j in range(3): self.centers[self.labels[i]][j] += data[i][j] for c in range(self.n): for j in range(3): self.cent...
[ "def centroid(arr):\n length = arr.shape[0]\n sum_x = np.sum(arr[:, 0])\n sum_y = np.sum(arr[:, 1])\n sum_z = np.sum(arr[:, 2])\n return sum_x / length, sum_y / length, sum_z / length", "def _compute_centroids(self):\n\n for i in range(0, self.k):\n cluster = np.argwhere(self.assi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Doc2Vec requires documents to be tokenized and, in addition, each doc should have a unique TAG. Note that, if the corpus has been preprocessed, each document is already tokenized. Therefore, some of the steps below can be skipped.
def transform4Doc2Vec(docs): # transform documents to be used by doc2Vec documents = [] analyzedDocument = namedtuple('AnalyzedDocument', 'words tags') for i, doc in enumerate(docs): # use first line if documents are not tokenized, otherwise next line # words = text.lower().split() ...
[ "def doc2vec(input_file_path, output_file_path):\n iterable = corpusIterable()\n logging.basicConfig( level=logging.INFO)\n logger = logging.getLogger(__name__)\n #train_corpus = list(read_corpus(input_file_path))\n logger.info('corpus built')\n model = gensim.models.doc2vec.Doc2Vec(size=100, min_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }