query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Remove an edit variable from the solver.
def removeEditVariable(self, variable: Variable, /) -> None: ...
[ "def remove_variable(self, var_id):\n pass", "def removeVariable(self, name, delete = True):\r\n if name in self.variables:\r\n self.variables.remove(name)\r\n if delete and hasattr(self, name):\r\n delattr(self, name)", "def remove(self, val):\n self.var_holder[self.var_name].remove(val)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the solver contains an edit variable.
def hasEditVariable(self, variable: Variable, /) -> bool: ...
[ "def is_edit(self):\n return self._tag == 'edit'", "def check_edit_var_input(name, store_vars, **kwargs):\n assert isinstance(name, str), 'The variable name should be a string!'\n check_and_set_bool(store_vars, 'store_previous_variables')\n for key, val in kwargs.items():\n if key not in ['...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Suggest a desired value for an edit variable.
def suggestValue(self, variable: Variable, value: int | float, /) -> None: ...
[ "def doEdit(var, value, target):\n currentValue = target.get(var, \"\")\n newValue = Simplifier.simplify(str(value).replace(f\"{{{var}}}\", str(currentValue)))\n target[var] = newValue", "def prompt_for_value(self, ctx):\n # Calculate the default before prompting anything to be stable....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the values of the solver variables.
def updateVariables(self) -> None: ...
[ "def variational_update(self):\n with self.elbo_check('update_p_allele_swap'):\n self.model.update_p_allele_swap()\n\n with self.elbo_check('p_cn'):\n self.model.update_p_cn()\n\n with self.elbo_check('p_breakpoint'):\n self.model.update_p_breakpoint()\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dump a representation of the solver internals to a string.
def dumps(self) -> str: ...
[ "def dump(self):\n outputs = [\"Code object : %s\" % self.name]\n outputs.append(\" Type : %s\" % self.object_type)\n for source_line in self.source:\n # Each line is a (line_number, code) pair\n outputs.append('%d: %s' % source_line)\n return \"\".join(outputs)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sorts agents in order of distance to exit and then steps
def step(self): try: self.agents.sort(key=lambda x: x.dist) except Exception as e: print(e) for agent in self.agents: try: agent.step() except Exception as e: print(e) # Removes agents if they reach ex...
[ "def sort_agents(self, receiver=False, dynamic=True, k_shot=100):\n if self.params.single_pool:\n att = \"agents\"\n else:\n att = \"receivers\" if receiver else \"senders\"\n\n values, agents = self.get_convergence(att, dynamic=dynamic, k_shot=k_shot)\n\n values, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return cns rates given current amounts and times.
def cns_growth(amounts, times): # Cannot have negative amounts. np.maximum(0, amounts, out=amounts) # Amounts of nutrients and signal. nutrients = amounts[1::3] signal = amounts[2::3] # Sums of nutrient and signal diffusion for each culture. N_diffusions = [sum([n...
[ "def currency_rate(self, init):\r\n\r\n curr = CurrencyRates()\r\n curr_rate = curr.get_rates(init)\r\n return curr_rate", "def get_rates(table_id):\n fields = [\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]\n for pos, name in enumerate(rates_key_list):\n full_table...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solve ODEs return amounts of C, N, and S. Args
def solve_model(init_amounts, times, neighbourhood, params): # init_amounts should be an array of length 3*no_cultures. growth_func = make_cns_model(params, neighbourhood) sol = odeint(growth_func, init_amounts, times) return np.maximum(0, sol)
[ "def _generic_ode_solve(r, psi0, tlist, e_ops, opt, progress_bar, dims=None):\n #\n # prepare output array\n #\n n_tsteps = len(tlist)\n output = Result()\n output.solver = \"sesolve\"\n output.times = tlist\n\n n_modes = len(psi0.dims[0])\n\n if psi0.isunitary:\n oper_evo = True\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of initial amounts for a plate of cultures. C0(t=0), N0(t=0), S0(t=0), C1(t=0), N1(t=0), S1(t=0), ...
def gen_amounts(no_cultures): # Init amounts C = 0.01 N = 1.0 S = 0.0 init_amounts = np.array([C, N, S]*no_cultures) return init_amounts
[ "def get_initial_units(self):\n return self._initials", "def construire_initiales(nb_lettres: int, chaîne_mots: list) -> str:\r\n\r\n initiales = \"\"\r\n for mot in chaîne_mots:\r\n initiales += mot[0].upper()\r\n return initiales", "def initial_money_amounts(self) -> List[float]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of parameters for a plate of cultures. kn, ks, b, a, r0, r1,...
def gen_params(no_cultures): # Plate level kn = 0.1 # Nutrient diffusion ks = 0.1 # Signal diffusion b = 0.05 # Signal on cells effect constant a = 0.05 # Signal secretion constant # Culture level # Growth rate constant r_mean = 1.0 r_var = 1.0 r_params = [max(0.0, ga...
[ "def find_weather_presets():\n rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')\n def name(x): return ' '.join(m.group(0) for m in rgx.finditer(x))\n presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]\n return [(getattr(carla.WeatherParameters, x), nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[Convert h5 format to pb format.]
def h5_to_pb(h5_model, output_dir, model_name, out_prefix="output_", log_tensorboard=True): if osp.exists(output_dir) == False: os.mkdir(output_dir) out_nodes = list() ## get all tensor node. for i in range(len(h5_model.outputs)): out_nodes.append(out_prefix+str(i+1)) ...
[ "def test_fil2h5_conversion():\n\n # Creating test file.\n bl.fil2h5.make_h5_file(voyager_fil, new_filename='test.h5')\n\n # Testing filename\n bl.fil2h5.make_h5_file(voyager_fil, new_filename='test')\n\n # Deleting test file\n os.remove('test.h5')", "def parse_h5py(path, file_name):\n def ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set whether to send notifications when the bot sends a message. Type must be a valid bool.
async def botmsg(self, ctx, type: bool): async with self.config.toggles() as toggles: if type: toggles["botmessages"] = True await ctx.send("Bot message notifications have been enabled.") else: toggles["botmessages"] = False ...
[ "def should_send_notifications(self, should_send_notifications):\n\n self._should_send_notifications = should_send_notifications", "def messaging(self, value: bool):\n if type(value) is not bool:\n raise TypeError(\"Value must be of type 'bool' ('{}' given)\".format(type(value)))\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PMs a person. Separate version of [p]dm but allows for guild owners.
async def pm(self, ctx, user_id: int, *, message: str): user = discord.utils.get(ctx.bot.get_all_members(), id=user_id) e = discord.Embed(colour=discord.Colour.red(), description=message) if ctx.bot.user.avatar_url: e.set_author( name=f"Message from {ctx.author} | {c...
[ "async def randping(self, ctx):\r\n while True:\r\n memb = random.choice(ctx.guild.members)\r\n if not memb.bot:\r\n break\r\n memb = memb.mention\r\n await ctx.send(memb)", "async def pm(self, string, *, update=False):\r\n said = False\r\n w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the number of partial permutations from choosing k objects from n.
def partial_permutations(n, k): return int((factorial(n) / factorial(n - k)) % 1000000)
[ "def num_subset_permutations(n, k):\n return math.factorial(n) / math.factorial(n - k)", "def permutations(n, k):\n num_permutations = 0\n if k == 0:\n num_permutations = factorial(n)\n n = 0\n while n >= 1:\n num_permutations += (factorial(n) / factorial(n - k))\n n -= 1\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the default linear reward vector.
def create_reward_vector(agent, locations, move_actions): world = agent.world features = [] features.append(ValueComparisonLinearRewardFeature( 'Before Middle', world, get_mission_seconds_key(), MISSION_PHASE_END_TIMES[MISSION_PHASES.index(MIDDLE_STR)], '<')) features.append(ValueCompar...
[ "def reward(self, arm):\n return np.dot(self.features[arm], self.real_theta) + self.local_random.normal(0, self.eta, 1)", "def __init__(self):\n self.total_reward = 0.0", "def get_reward_function(self):\n R_fn = np.zeros(self.n_states)\n R_fn[0] = 1.0\n\n return R_fn", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns a letter into a Tensor
def letterToTensor(letter): tensor = torch.zeros(1, n_letters) tensor[0][letterToIndex(letter)] = 1 return tensor
[ "def char_to_tensor(char, alphabet: List):\n tensor = [0 for i in range(len(alphabet))]\n for counter, element in enumerate(alphabet):\n if element == char:\n tensor[counter] = 1\n return tensor", "def text_to_tensor(alphabet: List, text: str):\n tensor = []\n for counter, char in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn a line into a , or an array of onehot letter vectors
def lineToTensor(line): tensor = torch.zeros(len(line), 1, n_letters) for li, letter in enumerate(line): tensor[li][0][letterToIndex(letter)] = 1 return tensor
[ "def line_to_one_hot_inference(self, line):\n tokens = tokenize_sentence(line)\n n_tokens = len(tokens)", "def hot(line):\n out = []\n encoder_dict ={'A':[1,0,0,0], 'T':[0,1,0,0], 'G':[0,0,1,0], 'C':[0,0,0,1]}\n for item in line:\n if item in encoder_dict.keys():\n out.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the topk as a python list
def topk(vec, k): vec = torch.topk(vec, k) return vec.view(-1).data.tolist()
[ "def _extract_topk(alist, k):\r\n scores = [t.score for t in alist]\r\n indices = np.argsort(alist)[:k]\r\n return [alist[idx] for idx in indices]", "def top_k(self, k = 1):\n\t if self.shapley_rank == {}:\n\t \treturn []\n\n\t n = self.nodes\n\t topknodes = []\n\t ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Small modification to NLTK wordpunct_tokenize Because NLTK's won't split on '_' or numbers
def wordpunct_space_tokenize(sent): return _rts.tokenize(sent)
[ "def word_tokenize(\n text: str, removePunctuation=False, removeNonDhivehiNumeric=False\n) -> list:\n sentences = sentence_tokenize(text)\n tokens = []\n for sentence in sentences:\n for token in sentence.split():\n if removeNonDhivehiNumeric:\n token = re.sub(r\"[^\\u07...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pads sequences to the same length. This function transforms a list of `num_samples` sequences (lists of integers) into a 2D Numpy array of shape `(num_samples, num_timesteps)`. `num_timesteps` is either the `maxlen` argument if provided, or the length of the longest sequence otherwise. Sequences that are shorter than `...
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.): if not hasattr(sequences, '__len__'): raise ValueError('`sequences` must be iterable.') lengths = [] for x in sequences: if not hasattr(x, '__len__'): raise Valu...
[ "def pad_sequences(sequences):\n max_len = max(s.shape[0] for s in sequences)\n padded = []\n for seq in sequences:\n zero_pad = np.concatenate(\n [seq, np.zeros((max_len - seq.shape[0], ) + seq.shape[1:])])\n padded.append(zero_pad[np.newaxis, :])\n\n return np.concatenate(padd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the bounding box for the detector named by detector_name
def getBBox(self, detector_name): if not hasattr(self, '_bbox_cache'): self._bbox_cache = {} if detector_name not in self._bbox_cache: dm_bbox = self._camera[detector_name].getBBox() dm_min = dm_bbox.getMin() dm_max = dm_bbox.getMax() cam_bbox...
[ "def get_bounding_box(current_building_contour):\n x, y, w, h, = cv.boundingRect(current_building_contour[0])\n return x, y, w, h", "def get_detection_bboxes(detector):\r\n with open('../datasets/AICity_data/train/S03/c010/det/det_' + detector + '.txt') as f:\r\n lines = f.readlines()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the central pixel for the detector named by detector_name
def getCenterPixel(self, detector_name): if not hasattr(self, '_center_pixel_cache'): self._center_pixel_cache = {} if detector_name not in self._center_pixel_cache: centerPoint = self._camera[detector_name].getCenter(FOCAL_PLANE) centerPixel_dm = self._camera[d...
[ "def getCcdDim(self, detectorName):\n\n return self._dimension[detectorName]", "def find_center(image_mask):\r\n edges = feature.canny(image_mask, sigma=3)\r\n edges = 1.0 * edges\r\n list_edge = np.nonzero(edges)\r\n center = np.array([0, 0])\r\n center[0] = np.average(list_edge[1]) # Wi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the file is a module file or not
def is_module(filename): if not os.path.exists(filename): return None if filename.endswith('.py'): # Assume the file is a module file return PY_MODULEFILE regex = re.compile(re.escape(r'#%Module')) if regex.search(open(filename).readline()): return TCL_MODULEFILE ret...
[ "def is_module(path: str) -> bool:\n return os.path.isfile(path) and path.endswith(\".py\")", "def is_module(path):\n\n fname, ext = os.path.splitext(path)\n if ext == \".py\":\n return True\n elif os.path.exists(os.path.join(path, \"__init__.py\")):\n return True\n else:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the given player state
def show_player_state(self, player): player_str = 'Player: {}'.format(player.name) sys.stdout.write(colorama.Fore.MAGENTA) print('-'*len(player_str)) print(player_str) print('-'*len(player_str)) sys.stdout.write(colorama.Fore.GREEN) print('Money: {}'.format(player...
[ "def display(self, state):\n \"\"\"Imprime o muestra el estado\"\"\"\n print(state)", "def show_state(self):\n print(\"I don't know how to show_state.\")", "def show_state(self):\n print \"I don't know how to show_state.\"", "def display(self, state):\n print(state)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows what's available at the market.
def show_market(self, player): print('Market') print('------') cards_available = self.game.market.cards_available() for card in sorted(cards_available.keys()): count = cards_available[card] if card.cost > self.game.current_player.money: sys.stdout....
[ "def display_available_items(self):\n count = 0\n print(\"Available Items:\")\n for item in self.item_list.values():\n if item.check_availability():\n count += 1\n print(item)\n if count == 0:\n print(\"No items are available\")", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
该方法可以将字符串中所有的用汉字表示的数字转化为用阿拉伯数字表示的数字 如"这里有一千两百个人,六百零五个来自中国"可以转化为 "这里有1200个人,605个来自中国" 此外添加支持了部分不规则表达方法 如两万零六百五可转化为20650 两百一十四和两百十四都可以转化为214 一六零加一五八可以转化为160+158 该方法目前支持的正确转化范围是099999999 该功能模块具有良好的复用性
def number_translate(cls, target): pattern = re.compile(u"[一二两三四五六七八九123456789]万[一二两三四五六七八九123456789](?!([千百十]))") match = pattern.finditer(target) for m in match: group = m.group() s = group.split(u"万") s = list(filter(None, s)) num = 0 ...
[ "def zh_num2digit(string):\n for match in zh_nums_iter(string):\n num_str = match.group(0)\n digit_num = parse_zh_num(num_str)\n if digit_num is None:\n continue\n string = string.replace(num_str, str(digit_num), 1)\n return string", "def numberate(strIn, convert):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrap a main function for proper twisted encapsulation and getting proper error feedback on the command line.
def wrapMain(func): def handleError(error): if error.type == SystemExit: log.msg('SystemExit: %s' % error.value) elif error.type == usage.UsageError: log.msg(error.value) else: error.printTraceback() log.startLoggingWithObserver(logObserver, setStdout...
[ "def run_main():\n main(sys.argv)", "def main():\n cause_a_bunch_of_exceptions_to_happen()", "def main(self, *args):\n pass", "def test_cli_catches_errors(self):\n main_module = main.__name__\n p1 = patch(\"{}.main.run\".format(main_module))\n p2 = patch(\"{}.parse_args\".forma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The lenght value of a string can be defined up to 5 bytes. Only lower 7 bits hold the lenght value. The most significant bit defines if there is another bit following the previous one with rest of the lenght value.
def _get_correct_string_size(self, fd): # store the lenght value bits size_bits = [] # the value can have max 5 bytes for _ in range(5): size = self.read_bytes_to_int(fd, 1) # if the length value is less then 128 it means its the last # byte with the l...
[ "def get_string_length(self):\n return int(self.read('H')[0])", "def _encoded_str_len(l):\n return (l << 2) / 3 + 2", "def read_variable_length_string(self):\n byte = 0x80\n length = 0\n bits_read = 0\n while byte & 0x80 != 0:\n byte = struct.pack(\"!B\", self.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all failed host, type_t default FC
def get_failed_dev(failed_dev_list, type_t="FC"): result_list = [] try: if failed_dev_list: for dev_info in failed_dev_list: type_temp = dev_info.get('type') if type_temp == type_t: host = dev_info.get('host') result_lis...
[ "def get_hosts_retry(self, target, listener_type):", "def get_hosts_fanout_retry(self, target, listener_type):", "def get_daysWithMostRequestErrors():", "def get_info_hosts():\n print(\"\\nMapeando...\")\n host_ip = socket.gethostbyname(socket.gethostname()).split('.')\n base_ip = \".\".join(host_ip[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when the given dictionary was built with invalid version, Lexpp() must raise an FileNotFoundError.
def test_dict_with_invalid_version(self): invalid_version_info = (-1, -1, -1) d = LexicalDictionary(invalid_version_info) with self.assertRaises(FileNotFoundError): lp = Lexpp(external_dict=d)
[ "def yaml_file_must_exist(cls, v: pathlib.Path):\n if not v.exists():\n raise ValueError(f\"Path object not found in filesystem : {v}\")\n return v", "def test_versioning_unknown_version(workflow_runner):\n with pytest.raises(WDL.Error.SyntaxError):\n workflow_runner(\"test_vers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test IMA measurement list verification
def test_measurment_verification(self): lines = MEASUREMENTS.splitlines() lists_map = ima.process_allowlists(ALLOWLIST, '') lists_map_empty = ima.process_allowlists(ALLOWLIST_EMPTY, '') self.assertTrue(ima.process_measurement_list(lines) is not None, "Validation ...
[ "def test_measurement(createAIAMap):\n assert createAIAMap.measurement.value in [171, 193]\n # aiaimg has 171, jp2path has 193.", "def test_measurement(eit_map):\n assert eit_map.measurement.value in [195, 171]", "def a_test_mh():\n model = ARIMAX(formula=\"y ~ x1\", data=data, ar=1, ma=1, family=Ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the signature verification
def test_signature_verification(self): curdir = os.path.dirname(os.path.abspath(__file__)) keydir = os.path.join(curdir, "data", "ima_keys") lines = SIGNATURES.split('\n') # empty keyring keyring = ima_file_signatures.ImaKeyring() self.assertTrue(ima.process_measurement...
[ "def _verify_signature(self):\n #FIXME\n return True", "def test_signature_validation(self):\n signature = app.utils.generate_signed_data(\n self._body,\n settings.PRIVATE_KEY\n )\n\n self.assertTrue(app.utils.validate_signed_data(\n self._body,\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test verification using allowlist and keys
def test_mixed_verfication(self): lists_map = ima.process_allowlists(ALLOWLIST, '') lists_map_wrong = ima.process_allowlists(ALLOWLIST_WRONG, '') lists_map_empty = ima.process_allowlists(ALLOWLIST_EMPTY, '') lists_map_exclude = ima.process_allowlists(ALLOWLIST, EXCLUDELIST) list...
[ "def test_trust_key(self):\n self.fail(\"test not implemented\")", "def test_allow_extra_keys(self):\n from natcap.invest import validation\n\n args = {'a': 'a', 'b': 'b'}\n spec = {\n 'a': {\n 'type': 'freestyle_string',\n 'name': 'a',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test reading and processing of the IMA allowlist
def test_read_allowlist(self): curdir = os.path.dirname(os.path.abspath(__file__)) allowlist_file = os.path.join(curdir, "data", "ima-allowlist-short.txt") allowlist_sig = os.path.join(curdir, "data", "ima-allowlist-short.sig") allowlist_bad_sig = os.path.join(curdir, "data", "ima-allow...
[ "def test_mixed_verfication(self):\n\n lists_map = ima.process_allowlists(ALLOWLIST, '')\n lists_map_wrong = ima.process_allowlists(ALLOWLIST_WRONG, '')\n lists_map_empty = ima.process_allowlists(ALLOWLIST_EMPTY, '')\n lists_map_exclude = ima.process_allowlists(ALLOWLIST, EXCLUDELIST)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solve for Q that satisfies the unitvector and orthogonality constraints on ih and jh.
def solve_Q(ih, jh): # Build A and b # Solve for c via least squares. # Form C from c # Solve for Q and return it. return None
[ "def solve(self):\n\n # Initialize Runge-Kutta firstorder ode\n methd = firstorder(self.eqn.get())\n r = methd.solve(np.double(self.ti.get()), np.double(self.yi.get()),\n np.double(self.t.get()), np.double(self.h.get()))\n # Obtain values of solution\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the SfM factorization on a set of points. points will be an array with shape (num_frames, num_points, 2)
def sfm(points): # Construct the required W/Rh/Sh matrices. # Get ih/jh from Rh and use them to find Q. # Use Q, Rh, and Sh to get R and S. # Extract the F 2x3 rotation matrices from R and form an (F,2,3) array of # rotation matrices. # Build an orthonormal matrix that rotates the first R m...
[ "def apply_transformation(self, points):\n assert (points.shape[0] == 3)\n n = points.shape[1]\n points_ = np.vstack((points, np.ones((1, n))))\n points_trans_ = np.matmul(self.pose_mat, points_)\n points_transformed = np.true_divide(points_trans_[:3, :], points_trans_[[-1], :])\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a set of images and 4 points for each image representing a quadrilateral planar region, extract a square texture of size texture_size containing the pixel values within the region averaged over all of the images You may use the imported OpenCV findHomography and warpPerspective functions.
def get_texture(images, region_points, texture_size=256): # Build a (4,2) array of X/Y texture coordinates for a # texture_size x texture_size square. The coordinates should # start at the top left (0,0) and proceed clockwise. for image, rect_points in zip(images, region_points): # Find a homo...
[ "def _nearest_voxel_sampling(images, mesh, affine, kind='auto', radius=3.,\n n_points=None, mask=None, inner_mesh=None,\n depth=None):\n proj = _projection_matrix(\n mesh, affine, images[0].shape, kind=kind, radius=radius,\n n_points=n_points, m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and print a formatted string of the Python JSON object
def jprint(obj): # text = json.dumps(obj, sort_keys=True, indent=4) print(text)
[ "def print_json(obj):\n print(json.dumps(obj, indent=2))", "def print_friendly_JSON_object(JSON_object):\n formatted_string = json.dumps(JSON_object, sort_keys=True, indent=4)\n print(formatted_string)", "def print_json(obj):\n print(json.dumps(obj, indent=4))", "def print_nice_json_format(json_):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove comments from the string column of FTL Translations and Entities, and source & target columns of FTL TranslationMemoryEntries. See bug 1501168 for more details.
def remove_comments_from_ftl_translations(apps, schema): parser = FluentParser() serializer = FluentSerializer() # Translations Translation = apps.get_model('base', 'Translation') translations = Translation.objects.filter(entity__resource__format='ftl') translations_to_update = [] for t in...
[ "def deleteComments(self: Self, event: Event = None) -> None:\n #@+<< deleteComments docstring >>\n #@+node:ekr.20171123135625.37: *3* << deleteComments docstring >>\n #@@pagewidth 50\n #@-<< deleteComments docstring >>\n c, p, u, w = self, self.p, self.undoer, self.frame.body.wrapper\n #\n # \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the intersection of multiple sets. Returns None if the sequence is empty (intersection is undefined in that case).
def intersection(seq: Iterable[AbstractSet[VT]]) -> Optional[Set[VT]]: it = iter(seq) try: ret = set(next(it)) except StopIteration: return None for elem in it: ret &= elem return ret
[ "def intersection(set1, set2):\n pass", "def intersection(sets):\n return functools.reduce(set.intersection, [s for s in sets])", "def intersection(*seqs):\n return (item for item in seqs[0]\n if all(item in seq for seq in seqs[1:]))", "def intersection(sets):\n\n return reduce(set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deal with the sections, parse tags that contains
def deal_with_sections(self): self.data_sections = [] self.create_parser_sections(self.soup)
[ "def parse_section(soup):\n section_tag = soup.find_all('a', {'class': 'advisory-severity-vote__message'})\n section_scale = [code.string for code in section_tag]\n section = section_scale[0] if section_scale else None\n\n section_comment_tags = soup.find_all('li', {'class': 'ipl-zebra-list__item'})\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the soup to a file to be analysed. This can be used during the debugging process.
def save_soup_to_file(self, filename='soup.html', prettify=True): with open(filename, 'w', encoding='utf-8') as fd_div: if prettify: fd_div.write(self.soup.prettify()) fd_div.write('\n') else: # for item in self.soup: # ...
[ "def save_soup(fname, soup):\n\n f = open(fname, 'w+')\n f.write(repr(soup))", "def serialize(self) -> None:\n filename = directory + self.full_title + \".htm\"\n with open(filename, 'w') as f:\n f.write(self.soup.prettify())\n self.filename = filename", "def save(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove tags from bs4 soup object using a list of bs4 rules to find_all()
def remove_tags(self, rules): for rule in rules: [s.extract() for s in self.soup.find_all(**rule)]
[ "def remove_tag(self, rules):\n for rule in rules:\n [s.extract() for s in self.soup.find_all(limit=1, **rule)]", "def remove_unwanted_tags(soup: bs4.BeautifulSoup):\n for tag in soup.find_all(['script', 'style']):\n tag.decompose()", "def remove_all_empty_tags(soup):\n return rem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the first found tag from bs4 soup object using a list of bs4 rules to find_all() Remove the first tag.
def remove_tag(self, rules): for rule in rules: [s.extract() for s in self.soup.find_all(limit=1, **rule)]
[ "def remove_tags(self, rules):\n for rule in rules:\n [s.extract() for s in self.soup.find_all(**rule)]", "def remove_unwanted_tags(soup: bs4.BeautifulSoup):\n for tag in soup.find_all(['script', 'style']):\n tag.decompose()", "def remove_empty_tags(soup, tag_name, recursive=False):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a tag inside a bs4 soup object from a selection using a rule.
def create_tag_from_selection(self, rule, name_new_tag, name_section='Abstract'): inside_tags = self.soup.find_all(**rule) section = self.soup.new_tag('section_{}'.format(name_new_tag)) heading = self.soup.new_tag('h2') heading.append(name_section) section.append(heading) ...
[ "def make_selection ( self ,\n tag , \n algotype ,\n inputs , \n *args ,\n **kwargs ) :\n sel_tag = '%s_Selection' % tag\n sel_name = 'Sel%sFor%s' % ( tag , se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return ``data`` (``bytes``) piped through Graphviz ``engine`` into ``format`` as ``bytes``.
def pipe(engine: str, format: str, data: bytes, renderer: typing.Optional[str] = None, formatter: typing.Optional[str] = None, quiet: bool = False) -> bytes: cmd = command(engine, format, renderer=renderer, formatter=formatter) kwargs = {'input': data} proc = run_check(cmd, captu...
[ "def get_raw(self, request):\n try:\n reqdict = request.get_dict()\n reqdict['format'] = 'raw'\n rawdata = self._get_data(reqdict)\n return rawdata\n except ConnectionError:\n raise\n except Exception, exc:\n raise DataFormatErro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return ``input_string`` piped through Graphviz ``engine`` into ``format`` as ``str``.
def pipe_string(engine: str, format: str, input_string: str, *, encoding: str, renderer: typing.Optional[str] = None, formatter: typing.Optional[str] = None, quiet: bool = False) -> str: cmd = command(engine, format, renderer=renderer, formatter=formatt...
[ "def pipe_lines_string(engine: str, format: str, input_lines: typing.Iterator[str],\n *, encoding: str,\n renderer: typing.Optional[str] = None,\n formatter: typing.Optional[str] = None,\n quiet: bool = False) -> str:\n cmd = com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Return ``input_lines`` piped through Graphviz ``engine`` into ``format`` as ``bytes``.
def pipe_lines(engine: str, format: str, input_lines: typing.Iterator[str], *, input_encoding: str, renderer: typing.Optional[str] = None, formatter: typing.Optional[str] = None, quiet: bool = False) -> bytes: cmd = command(engine, format, renderer=rendere...
[ "def pipe_lines_string(engine: str, format: str, input_lines: typing.Iterator[str],\n *, encoding: str,\n renderer: typing.Optional[str] = None,\n formatter: typing.Optional[str] = None,\n quiet: bool = False) -> str:\n cmd = com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Return ``input_lines`` piped through Graphviz ``engine`` into ``format`` as ``str``.
def pipe_lines_string(engine: str, format: str, input_lines: typing.Iterator[str], *, encoding: str, renderer: typing.Optional[str] = None, formatter: typing.Optional[str] = None, quiet: bool = False) -> str: cmd = command(engin...
[ "def pipe_lines(engine: str, format: str, input_lines: typing.Iterator[str],\n *, input_encoding: str,\n renderer: typing.Optional[str] = None,\n formatter: typing.Optional[str] = None,\n quiet: bool = False) -> bytes:\n cmd = command(engine, format, render...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return DOT ``source`` piped through Graphviz unflatten preprocessor.
def unflatten(source: str, stagger: typing.Optional[int] = None, fanout: bool = False, chain: typing.Optional[int] = None, encoding: str = ENCODING) -> str: if fanout and stagger is None: raise RequiredArgumentError('fanout given without stagger') ...
[ "def get_source(node):\n return compiler.walk(node,visitor()).src", "def preprocess(self, source, name, filename=None):\r\n return source", "def _deblend_source(source_data, source_segment, npixels, footprint, nlevels,\n contrast, mode):\n deblender = _Deblender(source_data, sour...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the version number tuple from the ``stderr`` output of ``dot V``.
def version() -> typing.Tuple[int, ...]: cmd = [DOT_BINARY, '-V'] log.debug('run %r', cmd) proc = run_check(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='ascii') ma = re.search(r'graphviz version' r' ' r'(\d+)\.(\d+)' r'(?:\.(\...
[ "def version():\n with settings(hide('running', 'warnings'), warn_only=True):\n res = local('vagrant --version', capture=True)\n if res.failed:\n return None\n line = res.splitlines()[-1]\n version = re.match(r'Vagrant (?:v(?:ersion )?)?(.*)', line).group(1)\n return tuple(_to_int(part)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return subprocess.STARTUPINFO instance hiding the console window.
def get_startupinfo(): startupinfo = subprocess.STARTUPINFO() # pytype: disable=module-attr startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # pytype: disable=module-attr startupinfo.wShowWindow = subprocess.SW_HIDE # pytype: disable=module-attr return startupinfo
[ "def 隐藏控制台窗口():\n whnd = ctypes.windll.kernel32.GetConsoleWindow()\n if whnd != 0:\n ctypes.windll.user32.ShowWindow(whnd, 0)\n # if you wanted to close the handles...\n # ctypes.windll.kernel32.CloseHandle(whnd)", "def offscreen(console: tcod.console.Console) -> tcod.console.Console:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return None for startupinfo argument of ``subprocess.Popen``.
def get_startupinfo() -> None: return None
[ "def get_startupinfo():\n startupinfo = subprocess.STARTUPINFO() # pytype: disable=module-attr\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # pytype: disable=module-attr\n startupinfo.wShowWindow = subprocess.SW_HIDE # pytype: disable=module-attr\n return startupinfo", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install a default admin user and add an admin role to it.
def install(): # check if admin exists from enferno.user.models import Role a = Role.query.filter(Role.name == 'admin').first() if a is None: r = Role(name='admin') try: db.session.add(r) db.session.commit() u = click.prompt('Admin Email?', default='a...
[ "def add_admin():\n admin_role = Role.query.filter_by(permissions=0xFF).first()\n admin = User.query.filter_by(email=current_app.config['PILI_ADMIN']).first()\n if not admin:\n admin_user = User(\n email=current_app.config['PILI_ADMIN'],\n username=curre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove .pyc and .pyo files recursively starting at current directory. Borrowed from FlaskScript, converted to use Click.
def clean(): for dirpath, dirnames, filenames in os.walk('.'): for filename in filenames: if filename.endswith('.pyc') or filename.endswith('.pyo'): full_pathname = os.path.join(dirpath, filename) click.echo('Removing {}'.format(full_pathname)) os....
[ "def _delete_compiled_python_files():\n for path, _, files in os.walk(os.getcwd()):\n for fname in [f for f in files if os.path.splitext(f)[1] == \".pyc\"]:\n try:\n os.remove(os.path.join(path, fname))\n except OSError:\n pass", "def clean_pyc():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot image of given depth
def imshow(self, depth): layer = self.cube[depth] img = [] for i in range(self.height): img.append([layer[i][j].value for j in range(self.width)]) plt.imshow(img, cmap='gray') plt.show()
[ "def display_depthmap(xyz):\n plt.figure()\n plt.imshow(\n xyz[:, :, 2],\n vmin=np.nanmin(xyz[:, :, 2]),\n vmax=np.nanmax(xyz[:, :, 2]),\n cmap=\"viridis\",\n )\n plt.colorbar()\n plt.title(\"Depth map\")\n plt.show(block=False)", "def depth(args):\n p = OptionPars...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
main entrypoint for pyout simple example
def main(): parser = get_parser() def help(return_code=0): """print help, including the software version and active client and exit with return code. """ print("\npyout v%s" % pyout.__version__) parser.print_help() sys.exit(return_code) # If an error oc...
[ "def main():\n\n\tst.title(\"Iris EDA App with streamlit\")\n\tst.subheader(\"Streamlit is Cool\")", "def main(self, *args):\n pass", "def main(self):\n pass", "def main():\n\tcli = Cli()\n\tcli.run()", "def main():\n Main()", "def main():\n tng.api.runner()", "def main(_args):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an input file and a delimiter, read it in and generate a pyout Tabular table to print to the console.
def generate_table(input_file, delim=",", header=True): input_file = os.path.abspath(input_file) if not os.path.exists(input_file): sys.exit("%s does not exist." % input_file) # Read in rows with user specified delimiter rows = read_rows(input_file, delim=delim) # Generate tabulars expecte...
[ "def read_table(self, infile, sep='\\t', fields_in_head=True,\n t1_col='t1', t2_col='t2', fields=None, skiplines=0,\n t1_start=None, t1_step=None):\n if t1_col is None and t1_start is None:\n t1_start = 0\n if t1_col is None and t1_step is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the empirical CDF of the sample 'x' and evaluate it at datapoints 'xi'. This function is called internally in RSA_thres.compute_indices and RSA_groups.compute_indices to calculate the input CDFs.
def empiricalcdf(x, xi): ########################################################################### # Check inputs ########################################################################### if not isinstance(x, np.ndarray): raise ValueError('"x" must be a numpy.array.') if x.dtype....
[ "def cdf(self, x, *args, **kwargs) -> float:\n return self.scipy_distribution.cdf(x, *args, **kwargs, **self.scipy_distribution_arguments)", "def cdf(self,x):\n coordinate = distribution1D.vectord_cxx(len(x))\n for i in range(len(x)):\n coordinate[i] = x[i]\n cdfValue = self._distribution.cdf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function produces scatter plots of X[i1] against X[i2]. The marker colour is proportional to the value of Y.
def scatter_plots_col(X, Y, i1, i2, ms=7, X_Labels=[], Y_Label='Y', ax=[]): # Options for the graphic pltfont = {'fontname': 'Bitstream Vera Sans', 'fontsize': 15} # font # Colorscale colorscale = 'jet' #colorscale = 'gray' # black and white plot #######################################...
[ "def scatterPlot(self, feature1, feature2):\r\n plt.figure(figsize=(7,7))\r\n if self.data.getReference() is None:\r\n plt.scatter(self.data.dataDict[feature1], self.data.dataDict[feature2], cmap='jet')\r\n else:\r\n plt.scatter(self.data.dataDict[feature1], self.data.data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function plot the empirical Cumulative Distribution Function (CDF) of a given sample (y).
def plot_cdf(Y, Y_Label='Y'): # Options for the graphic pltfont = {'fontname': 'Bitstream Vera Sans', 'fontsize': 15} # font lc = 'k' # line colour ########################################################################### # Check inputs ###############################################...
[ "def plot_discrete_cdf(ax, unc, x, y, xticklabels_on, ccdf):\n cats = sorted(set(x))\n n_cat = len(cats)\n for i in range(np.max(y) + 1):\n data_i = x[y == i]\n\n freqs = []\n for cat in cats:\n freq = data_i[data_i == cat].shape[0] / data_i.shape[0]\n freqs.appen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transductive PACBayesian bound obtained with a specified ''Dfunction''. See Theorem 5 of Begin et al. (2014) for details.
def compute_general_transductive_gibbs_bound(d_function, empirical_gibbs_risk, m, N, KLQP, delta=0.05, complexity_term=None): if complexity_term is None: complexity_term = compute_transductive_complexity_term(d_function, m, N) m_over_N = float(m)/N right_hand_side = ( KLQP + log( co...
[ "def b(alpha,s,j,p):\n\tassert type(p) == int, \"Laplace coefficient must have integer p value\"\n\treturn deriv(lambda x:b0(x,s,j),alpha,p)", "def get_ADP_fn(self):\n _logger.debug(f\"generating approximate dynamic programming functions\")\n from jax.ops import index, index_add, index_update\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure we can call drake_visualizer help in Bazel.
def test_help(self): bin_path = "tools/drake_visualizer" self.assertTrue(isfile(bin_path), bin_path) text = subprocess.check_output([bin_path, "--help"], encoding="utf8") # N.B. This should be kept in sync with # `drake_visualizer_installed_help_test`. print(text) ...
[ "def test_demo_runs():\n materials.plot_utils_demo.main()", "def test_vggmini_visualize(self):\n\t\tpass", "def _visualization_validation_warning():\n if constants.ENV_VARIABLES.LIVY_VERSION_ENV_VAR in os.environ:\n _log(\"Visualizations are not supported in Livy Sessions. \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate pg_num pg_num is generated as the number of OSDs across the cluster multiplied by 100, divided by Ceph replication factor, and rounded up to the nearest power of 2.
def _set_pg_count_storage_parameters(cls, data, nodes): osd_num = 0 osd_nodes = [node for node in nodes if 'ceph-osd' in node.all_roles] for node in osd_nodes: for disk in cls.get_node_volumes(node): for part in disk.get('volumes', []): ...
[ "def _estimate_ceph_pool_pg_num(self, num_osd):\n num_osd = max(len(num_osd), 1)\n max_chunk_size_allowed = num_osd * 100 - 1\n return 2 ** (int(math.log(max_chunk_size_allowed, 2)))", "def _num_gp(self):\n return int(float(self.volume) / self.spacing ** 3)", "def unit_ceph_qty()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if node disk requires checking
def _is_disk_checking_required(cls, node): if (node.status in (consts.NODE_STATUSES.ready, consts.NODE_STATUSES.deploying, consts.NODE_STATUSES.provisioned) or (node.status == consts.NODE_STATUSES.error and node.error_type ...
[ "def support_diskintensive(self):\n return self._support_diskintensive", "def check_disk_usage(disk):\n du = shutil.disk_usage(disk)\n free = du.free / du.total * 100\n return free > 20", "def _CheckMsrDevNodes():\n if not os.path.exists(MSR_DEV_FILE_PATH):\n print('Error: %s does not exist....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Marvin Probe ID for expect auto run.
def getMarvinProbeID(cableName, path_sn): # 处理未格式化的 cablename 字符串 cableName_0 = cableName if re.search("-", cableName_0): cableName_0 = cableName_0.split("-")[1] res, rev = readCMD(["%s/runMarvin.exp"%(script_path)], True, path_sn) for item in rev: if re.search(cableName_0, item): probeID=re.search("[0-9]...
[ "def getMarvinProbeID(cableName):\n\t# 处理未格式化的 cablename 字符串\n\tcableName_0 = cableName\n\tif re.search(\"-\", cableName_0):\n\t\tcableName_0 = cableName_0.split(\"-\")[1]\n\t# writeLogs(\"Python script current path = %s\" %script_path)\n\tres, rev = readCMD([\"%s/runMarvin.rep\"%(script_path)], False, 2)\n\tfor it...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Astris Probe ID for expect auto run.
def getAstrisProbeID(cableName, path_sn): # 处理未格式化的 cablename 字符串 cableName_0 = cableName if re.search("-", cableName_0): cableName_0 = cableName_0.split("-")[1] res, rev = readCMD([script_path+"/runAstrisID.exp"], True, path_sn) for item in rev: if re.search(cableName_0, item): probeID = re.search( "[0-9]{...
[ "def getAstrisProbeID(cableName):\n\t# 处理未格式化的 cablename 字符串\n\tcableName_0 = cableName\n\tif re.search(\"-\", cableName_0):\n\t\tcableName_0 = cableName_0.split(\"-\")[1]\n\t# writeLogs(\"Python script current path = %s\" %script_path)\n\tres, rev = readCMD([script_path+\"/auto_reset.rep\", \"-1\"], False)\n\tfor ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
收集ips log (KPCheck Panic)
def run_ips(cableName, sn): log = "" log_name = "" location_id = getLocId(cableName, sn) if not location_id: writeLogs("run_ips failed. Can not get location id for cableName:%s" % cableName, sn) print("ips=") exit(11) cmd = "ls /var/mobile/Library/Logs/CrashReporter/ | grep 'panic-*' | sort -r | head -n 1" ...
[ "def pulllog():\n\tpass", "def _log_ip_address(self, request):\n logged_ip = ip_address(request)\n request.session[\"LOGGED_IP\"] = logged_ip\n self.logger.info(\"LTI launch IP address logged: %s\" % logged_ip)", "def _handle_correct_ip(self, command):\n for queue in self.pools:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function verifies the relative controller_fs sizes.
def _check_relative_controller_multi_fs(controller_fs_new_list): chosts = pecan.request.dbapi.ihost_get_by_personality(constants.CONTROLLER) for chost in chosts: # Get the current backup size for the controller host backup_gib = 0 backup_gib_min = constants.BACKUP_OVERHEAD ho...
[ "def _check_relative_controller_fs(controller_fs_new, controller_fs_list):\n\n database_gib = 0\n platform_gib = 0\n\n chosts = pecan.request.dbapi.ihost_get_by_personality(\n constants.CONTROLLER)\n\n for chost in chosts:\n # Get the current backup size for the controller host\n ba...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function verifies the relative controller_fs sizes.
def _check_relative_controller_fs(controller_fs_new, controller_fs_list): database_gib = 0 platform_gib = 0 chosts = pecan.request.dbapi.ihost_get_by_personality( constants.CONTROLLER) for chost in chosts: # Get the current backup size for the controller host backup_gib = 0 ...
[ "def _check_relative_controller_multi_fs(controller_fs_new_list):\n\n chosts = pecan.request.dbapi.ihost_get_by_personality(constants.CONTROLLER)\n\n for chost in chosts:\n\n # Get the current backup size for the controller host\n backup_gib = 0\n backup_gib_min = constants.BACKUP_OVERHEA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function verifies the administrative, operational, availability of each controller.
def _check_controller_state(): chosts = pecan.request.dbapi.ihost_get_by_personality( constants.CONTROLLER) for chost in chosts: utils.is_host_state_valid_for_fs_resize(chost) return True
[ "def test_controller_initialization(self):\n for name in self.our_controllers:\n self.assertTrue(self.check_state(name, 'initialized'), \"{} is initialized correctly\".format(name))", "def test_all_nodes_could_be_controller(self):\n RolesPanel().controller.click()\n with Nodes()as ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check growth of ceph_mon in controller. There is additional items to check for controller_fs compared with check_node_ceph_mon_growth().
def _check_ceph_mon_growth(ceph_mon_gib): controller_fs_list = pecan.request.dbapi.controller_fs_get_list() cgtsvg_max_free_GiB = _get_controller_cgtsvg_limit() LOG.info("_check_ceph_mon_growth ceph_mon_gib = %s, " "cgtsvg_max_free_GiB = %s" % (ceph_mon_gib, cgtsvg_max_free_GiB)) _check_relat...
[ "def check_all_ceph_mon_growth(ceph_mon_gib, host=None):\n if host is not None:\n cgtsvg_max_free_gib = get_node_cgtsvg_limit(host)\n check_node_ceph_mon_growth(host, ceph_mon_gib, cgtsvg_max_free_gib)\n\n ceph_mons = pecan.request.dbapi.ceph_mon_get_list()\n for mon in ceph_mons:\n ce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check controller filesystem data and return growth
def _check_controller_multi_fs_data(context, controller_fs_list_new): cgtsvg_growth_gib = 0 lvdisplay_keys = [constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_DATABASE], constants.FILESYSTEM_LV_DICT[constants.FILESYSTEM_NAME_PLATFORM]] lvdisplay_dict = pecan.request.rpcapi.get...
[ "def _check_relative_controller_fs(controller_fs_new, controller_fs_list):\n\n database_gib = 0\n platform_gib = 0\n\n chosts = pecan.request.dbapi.ihost_get_by_personality(\n constants.CONTROLLER)\n\n for chost in chosts:\n # Get the current backup size for the controller host\n ba...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a list of controller_fs with detail.
def detail(self, isystem_uuid=None, marker=None, limit=None, sort_key='id', sort_dir='asc'): parent = pecan.request.path.split('/')[:-1][-1] if parent != "controller_fs": raise exception.HTTPNotFound expand = True resource_url = '/'.join(['controller_fs', 'de...
[ "def list_controller(cls, args, config):\n controllers = config.list_objects(kind='Controller')\n if len(controllers) == 0:\n return {'msg': \"No controllers configured\"}\n else:\n table_data = []\n for c in controllers:\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve information about the given controller_fs.
def get_one(self, controller_fs_uuid): if self._from_isystems: raise exception.OperationNotPermitted rpc_controller_fs = \ objects.controller_fs.get_by_uuid(pecan.request.context, controller_fs_uuid) return ControllerFs.conve...
[ "def do_host_fs_show(cc, args):\n ihost = ihost_utils._find_ihost(cc, args.hostnameorid)\n fs = fs_utils._find_fs(cc, ihost, args.fsnameoruuid)\n _print_fs_show(fs)", "def detail(self, isystem_uuid=None, marker=None, limit=None,\n sort_key='id', sort_dir='asc'):\n\n parent = pecan.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new controller_fs.
def post(self, controllerfs): raise exception.OperationNotPermitted
[ "def create_file_system(ClientRequestToken=None, FileSystemType=None, StorageCapacity=None, SubnetIds=None, SecurityGroupIds=None, Tags=None, KmsKeyId=None, WindowsConfiguration=None, LustreConfiguration=None):\n pass", "def new_of_controller(self, ofc_data):\n\n result, ofc_uuid = self.db.new_row('ofcs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an event callback for ending a modal dialog.
def EndModalClosure(self, dialog, code): def EndModal(evt): dialog.EndModal(code) return EndModal
[ "def on_close(self, callback):\n self._close_callback = callback", "def on_close(self, callback: Optional[PyGuiCallback]) -> Callable:\n if callback is not None:\n callback = wrap_callback(callback)\n self._on_close_callback = callback\n return callback", "def event_end_cb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bind events on our dialog. In the base class we only bind the Update (OK) and Cancel buttons. We define wx.ID_OK as the return of an 'Update'. self.dialog must have OK/Update and Cancel buttons.
def MakeBindingsOKCancel(self): dialog = self.dialog if hasattr(dialog, 'update_button'): ok_or_update_button = dialog.update_button else: ok_or_update_button = dialog.ok_button dialog.Bind(wx.EVT_BUTTON, self.EndModalClosure(dialog, wx.ID_OK), ok_or_update_button) dialog...
[ "def bind_controls(self):\n self.add_comment_button.Bind(wx.EVT_BUTTON, self.add_comment)\n self.del_comment_button.Bind(wx.EVT_BUTTON, self.remove_comment)\n self.upload_button.Bind(wx.EVT_BUTTON, self.upload_change)\n self.Bind(wx.EVT_CLOSE, self.on_close)", "def bind_controls(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns all children of the root XML document This is just an alias to self.soup.getchildren()
def getchildren(self): return self.root.getchildren()
[ "def getchildren(self):\n if self.parser == XML_node.etree:\n return [XML_node(a, self.parser) for a in self.data.getchildren()]", "def get_children_elements(self):\n\n pass", "def children(self, name=None):\n for child in [c for c in self._node.childNodes if c.nodeType == 1]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
First we get the id variable from our route. It will be present in the matchdict property of the request object (recall that the request object is created ????). All of our defined route args will end up there. After we get the entry id, it will be passed to BlogRecordService class method by_id() to fetch a specific bl...
def blog_view(request): blog_id = int(request.matchdict.get('id', -1)) entry = BlogRecordService.by_id(blog_id, request) if not entry: return HTTPNotFound return {'entry': entry}
[ "def journal_entry(entry_id):\n\ttry:\n\t\tentry = models.JournalEntry.get(models.JournalEntry.id == entry_id)\n\texcept models.DoesNotExist:\n\t\tabort(404)\n\telse:\n\t\treturn render_template('detail.html', entry=entry)", "def detail(request, blog_id):\n post = get_object_or_404(Blog, pk=blog_id)\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We implement a view callable that will handle new entries for us. create a new entry row and form object from BlogCreateForm the form will be populated by POST, if present if the request method is POST, the form gets validated If the form is validated, our form sets it values to the model instance and adds it to the da...
def blog_create(request): entry = BlogRecord() form = BlogCreateForm(request.POST) if request.method == 'POST' and form.validate(): form.populate_obj(entry) request.dbsession.add(entry) return HTTPFound(location=request.route_url('home')) return {'form': form, 'action': request.m...
[ "def entry_view(request):\n\n if request.method == 'GET':\n return {}\n if request.method == 'POST':\n if request.POST['title'] != '' or request.POST['body'] != '':\n new_date = datetime.now()\n new_title = request.POST['title']\n new_body = request.POST['body']\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The following view will handle updates to existing blog entries. Fetch the blog entry from the DB show a 404 Not Found page if the record requested is not present Create the form object, populating it from the POST params or from the actual blog entry, if we haven't POSTed any values yet. This approach ensures our form...
def blog_update(request): blog_id = int(request.params.get('id', -1)) entry = BlogRecordService.by_id(blog_id, request) if not entry: return HTTPNotFound() form = BlogUpdateForm(request.POST, entry) if request.method == 'POST' and form.validate(): del form.id # SECURITY: prevent ove...
[ "def update(request, blog_id, template_name='main/form.html'):\n if request.user.is_superuser:\n post = get_object_or_404(Blog, pk=blog_id)\n form = BlogForm(request.POST or None, instance=post)\n if form.is_valid():\n form.save()\n messages.success(request, 'Post has b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts dispatch type string into an enum constant
def parse_dispatch_type(dispatch_string: str): if not dispatch_string: return None dispatch_string = dispatch_string.lower().strip() if dispatch_string == "load": return DispatchType.LOAD if dispatch_string == "generating": return DispatchType.GENERATOR if dispatch_string...
[ "def from_str(type_string):\n\t\tglobal type_enum\n\t\tif type_string == \"V\":\n\t\t\treturn MoviesType.V\n\t\telif type_string == \"VG\":\n\t\t\treturn MoviesType.VG\n\t\telif type_string == \"TV\":\n\t\t\treturn MoviesType.TV\n\t\telse:\n\t\t\treturn MoviesType.M", "def from_string(cls, name: str) -> Enum:", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a BCMD Model.
def run_model(model): model.create_initialised_input() model.run_from_buffer() output = model.output_parse() return output
[ "def _run(self):\n self._check_call(self.lib.RunDLRModel(byref(self.handle)))", "def run_model(args):\n model_config = validate_config(args)\n\n try:\n builder = ModelRunBuilder()\n builder.construct(model_config)\n modelrun = builder.finish()\n except AssertionError as error:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read desired value from sysfs file
def _read_sysfs(filename): with open(filename) as sysfs: value = sysfs.readline().strip("\n") return value
[ "def read_node(self, *nodes):\n path = os.path.join(self._sysfs_path, *nodes)\n if not os.path.exists(path):\n raise NameError(\"Could not find sysfs node: {}\".format(path))\n with open(path, 'r') as fd:\n value = fd.read().strip()\n trace('read %s from %s', value,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the max power consumption of CPU
def _get_max_power_consumption(cpu): powercap_cpu_base = os.path.join( BASE_POWERCAP_PATH, "intel-rapl:{}".format(cpu.node_id)) try: path = os.path.join(powercap_cpu_base, "max_energy_range_uj") cons_max = int(_read_sysfs(path)) # uJ to J cons_max /= 1000000.0 except ...
[ "def maxcpu(self):\n return self._max_cpu['uid']", "def get_maximum_cpu_load():\n if psutil is not None:\n return max(psutil.cpu_percent(percpu=True))\n else:\n return get_random_cpu_load()", "def getMaxPower(self):\n return self.max_power", "def return_power_consumption(cpu_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receives two images in a list, in numpy array format and joins them horizontally
def join_images_horizontally(images): array = np.concatenate((images[0], images[1]), axis=1) return Image.fromarray(np.uint8(array))
[ "def _concatenate_images(images, rows, cols):\n assert len(images) == rows * cols\n col_images = []\n for r in range(rows):\n row_images = []\n for c in range(cols):\n image = images[r * cols + c]\n row_images.append(image.data)\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receives a panorama picture of 3600x1600 pixels aprox, slice the image in two parts horizontally, and resize each part to 480x360
def slice_and_resize(img_path): # read image img = Image.open(img_path) width, height = img.size #slice image in 2 parts horizontally, not looping image_parts = [] step = width/2 image_parts.append(img.crop((0, 0, step, height))) image_parts.append(img.crop((step, 0, step*2, height))) # resize imag...
[ "def get_and_save_image(pano_id, identif, size, vertical_tiles, horizontal_tiles, out_path, cropped=False, full=True):\n \n first_url_img = f'http://cbk0.google.com/cbk?output=tile&panoid={pano_id}&zoom=5&x={0}&y={0}'\n first = Image.open(requests.get(first_url_img, stream=True).raw)\n first...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a panorama image of 3600x1600 pixels aprox. and returns a path to a resized 960x360 image.
def get_normal_image(image_path): resized_images = slice_and_resize(image_path) normal_full_img = join_images_horizontally(resized_images) folder = "static/images/panorama" name = next(tempfile._get_candidate_names()) normal_path = "%s/%s_resized.png" % (folder, name) normal_full_img.save(normal_path) ...
[ "def panorama(lat, lng):\n if BAIDU_GEO_TOKEN is None:\n logger.info(\"error: Must config BAIDU_GEO_TOKEN in sachima_config.py\")\n raise \"Must config BAIDU_GEO_TOKEN in sachima_config.py\"\n\n url = \"http://api.map.baidu.com/panorama/v2\"\n values = {\"ak\": BAIDU_GEO_TOKEN, \"fov\": 180, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a normal image and a segmented image, and uses the segmented sky (gray) from segmented image to crop from the normal image. Save it and return the path.
def get_masked_image(normal_image, segmented_image): color = [128, 128, 128] # create boundaries, same color but needs two arguments later on lower = np.array(color, dtype="uint8") upper = np.array(color, dtype="uint8") # find the colors within the boundaries and apply the mask mask = cv2.inRange(segmented...
[ "def get_cropped_image(normal_path, segment_path):\n normal_img = cv2.imread(normal_path)\n segment_img = cv2.imread(segment_path)\n\n cropped_path = get_masked_image(normal_img, segment_img)\n\n return cropped_path", "def run_and_save(\n self,\n img_path,\n seg_path,\n save_folder...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets two paths for a normal and a segment image, and return a path to a cropped sky image.
def get_cropped_image(normal_path, segment_path): normal_img = cv2.imread(normal_path) segment_img = cv2.imread(segment_path) cropped_path = get_masked_image(normal_img, segment_img) return cropped_path
[ "def _segmentImage(self, imgPath, startX, endX, startY, endY):\n img = Image.open(imgPath)\n crops, segments = rect_to_squares.cutBoxesArray(img, startX, endX, startY, endY)\n img.close()\n return crops, segments", "def segment_image(image_path):\n image_array = cv2.imread(image_pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the average of a metric over all words in the thesaurus Words that not in the ground truth thesaurus are not used They are reported seperately
def average(thesaurus, ground_truth, function=precision, n=None): not_included = 0 cum_sum = 0 for word in thesaurus: if word in ground_truth and len(ground_truth[word]) != 0: words = thesaurus[word] if n is not None: words = words[:n] cum_sum += f...
[ "def _get_emb_wavg(g, lang, a=0.001):\n emb = np.zeros(emb_dims[lang])\n known_words_count = 0\n words = g.split()\n for w in words:\n if w in models[lang]:\n emb += a / (a + word_freqs[lang][w]) * models[lang][w]\n known_words_count += 1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modifies recent_sessions. If show_recent is True, leaves ended requests for OLD_INFO_EXPIRE_SECS after they end.
def clean_old_info(recent_sessions, include_ended): expire_secs = OLD_INFO_EXPIRE_SECS if include_ended else 0 now = time() i = 0 while i < len(recent_sessions): session = recent_sessions[i] if session.end and now - session.end > expire_secs: recent_sessions.pop(i) ...
[ "def update_recent_tracks(self):\n logger.debug('updating recent tracks')\n\n try:\n tracks = self.net.recently_played_tracks(response_limit=self.request_size)\n for track in tracks:\n if track.played_at not in [i.played_at for i in self.recent_tracks]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle an error; method called when accessing a nonexistent key. Automatically populate the given key with an instance of the factory.
def __missing__(self, key): self[key] = self.factory(key) return self[key]
[ "def test_get_factory_invalid(self):\n order_processor = OrderProcessor()\n self.assertRaises(KeyError,\n order_processor.get_factory('AppleRepublic'))", "def test_raises_key_error_with_no_default_factory(key: str) -> None:\n kdict = KeyDependentDefaultDict(None, {'red': ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert to bool; a helper is True if installed and False if not.
def __bool__(self): return self.installed
[ "def _is_plugin_installed(self):", "def is_helper(self):\n return self.__class__._helper_", "def is_installed(root, extension):", "def is_installed(self):\n return not self.dont_install", "def is_installed(cls):\n return find_spec_or_loader(cls.module) is not None", "def _local_instal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a URI for more information about this helper.
def info_uri(self): return self._info_uri
[ "def get_uri(self):\r\n return self.uri", "def uri(self) -> str:\n return self._uri", "def uri(self):\n return self._uri", "def display_uri(self) -> str:\n return pulumi.get(self, \"display_uri\")", "def get_info_url(self):\n return self.get_info(\"URL\")", "def help_uri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a RuntimeError or NotImplementedError for install trouble.
def unsure_how_to_install(self): msg = "Unsure how to install {0}.".format(self.name) if self.info_uri: msg += "\nRefer to {0} for information".format(self.info_uri) if platform.system() == 'Darwin': if 'brew' in self._provider_package and not helpers['brew']: ...
[ "def not_implemented_error():\n raise NotImplementedError('reliapy (Error 4) - this option is not implemented.')", "def check_for_setup_error(self):", "def raise_not_implemented_error():\n raise NotImplementedError('Method not implemented: %s' %\n inspect.stack()[1][3])", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Context manager for downloading and expanding a .tar.gz file. Creates a temporary directory, downloads the specified URL into the directory, unzips and untars the file into this directory, then yields to the given block. When the block exits, the temporary directory and its contents are deleted.
def download_and_expand_tgz(url): with TemporaryDirectory(prefix="cot_helper") as directory: logger.debug("Temporary directory is %s", directory) logger.verbose("Downloading and extracting %s", url) response = requests.get(url, stream=True) tgz = os.path.join(dire...
[ "def download_cookbook(fileurl, download_dir):\n\n # download and save file to download_dir\n logger.info('Downloading cookbook: %s' % fileurl)\n \n # get filename\n tarname = fileurl.split('/')[-1].split('?')[0]\n tarfilepath = download_dir + tarname\n\n logger.info('Writing cookbook file to %s' % tarfilepa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy the given src to the given dest, using sudo if needed.
def copy_file(src, dest): logger.debug("Copying %s to %s", src, dest) try: shutil.copy(src, dest) except (OSError, IOError) as exc: logger.debug('Installation error, trying sudo.') try: check_call(['sudo', 'cp', src, dest]) except H...
[ "def cp(src, dest):\n _shutil.copy2(native(src), native(dest))", "def copy_to(self, src, dest):\n logger.debug(\"copying %s from host to container at %s\", src, dest)\n cmd = [\"machinectl\", \"--no-pager\", \"copy-to\", self.name, src, dest]\n run_cmd(cmd)", "def copy(self, src, dst, la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install the requested package if needed.
def install_package(self, package): raise NotImplementedError("install_package not implemented!")
[ "def install_package(package):\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package])", "def install_if_not_installed(packages):\n\n for package in packages:\n if isinstance(package, tuple):\n package_name, package_package = package\n else:\n pac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }