query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
generate the players base attack level no inputs or outputs makes use of self.xp and self.attack
def __setAttack(self): self.attack = self.attack + int(floor(sqrt(self.xp)))
[ "def attack(self):\n return randint(0, self.attack_strength)", "def attack(self):\n return random.randint((self.max_damage // 2), self.max_damage)", "def attack(self, other_pokemon):\r\n damage = 0\r\n # Check to make sure the pokemon isn't knocked out.\r\n if self.is_knocked_out == True:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the base self.defense no inputs or outputs but makes use of self.xp and self.attack. This will also make use of different racial characteristics when those are implemented
def __setDefense(self): self.defense = self.defense + int(ceil(sqrt(self.xp))) + floor(self.maxHealth/2)
[ "def __setAttack(self):\n\t\tself.attack = self.attack + int(floor(sqrt(self.xp)))", "def do_defense(self):\n for pirate in self.living_pirates:\n # if defense expiration is full and defense was activated this turn, start counting defense reload time\n if pirate.defense_expiration_tur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
used to set self.xp
def setXp(self,xp): self.xp = xp
[ "def xp(self, value: int):\n self.__xp = value\n while self.xp >= self.total_xp_needed_for_next_level():\n self.__xp = self.xp - self.total_xp_needed_for_next_level()\n self.level += 1", "def setLevel(self):\n\t\tself.level = int(floor(sqrt(self.xp)))", "def _gain_xp(self, en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the learning rate warmup factor at a specific iteration.
def _get_warmup_factor_at_iter( method: str, iter: int, warmup_iters: int, warmup_factor: float ) -> float: if iter >= warmup_iters: return 1.0 if method == "constant": return warmup_factor elif method == "linear": alpha = iter / warmup_iters return warmup_factor * (...
[ "def learning_rate(self, step):\n if self._lr_schedule is not None:\n with fastmath.use_backend(fastmath.Backend.NUMPY):\n return self._lr_schedule(step)\n opt = self._optimizer\n if callable(opt): # when optimizer is a function, like Adam, not Adam()\n opt = opt()\n params = opt._init...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a tolerance which is independent of the dataset
def _tolerance(X, tol): variances = np.var(X, axis=0) return np.mean(variances) * tol
[ "def set_tolerance():\n return 1e-5", "def getTolerance(self):\n return _core.CGPopt_getTolerance(self)", "def _YExcessEqualsExpected(self):\n yint_model = self.model.integral(self.xmin, self.xmax)\n y_model = self.model(self.x)\n return y_model * (self.yint / yint_model)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the state converting with supported values.
def native_value(self): state = super().native_value if state is not None: resolved_state = [ item for item in self.wolf_object.items if item.value == int(state) ] if resolved_state: resolved_name = resolved_state[0].name ...
[ "def to_state(self):\n return self._to_state", "def from_state(self):\n return self._from_state", "def test_conv(converter):\n def test_conv_converter(value, state = None):\n if state is None:\n state = states.default_state\n converted_value, error = converter(value, st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add test to the suite.
def add_test(self, test): test.parent_suite = self self._tests[test.name] = test
[ "def add(test):\n global _default_suite\n if _default_suite is None:\n _default_suite = make(\"default\", [])\n _default_suite.tests.append(test)", "def DoAddTest(testname, seqrand, wmix, bs, threads, iodepth, desc,\n iops_log, runtime):\n AddTest(testname, seqrand, wmix, b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a subsuite to the suite.
def add_suite(self, suite): suite.parent_suite = self self._suites.append(suite)
[ "def add_suites(self, suites):\n for suite in suites:\n self.add_suite(suite)", "def dfs_add_tests(chain):\n head = chain[-1]\n if head not in sub_packages:\n sub_package = import_sub_package(chain)\n print '\\t+ %s' % str(sub_package)\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the bluetooth settings for a wireless device
def getDeviceWirelessBluetoothSettings(self, serial: str): metadata = { 'tags': ['wireless', 'configure', 'bluetooth', 'settings'], 'operation': 'getDeviceWirelessBluetoothSettings' } resource = f'/devices/{serial}/wireless/bluetooth/settings' return self._sessi...
[ "async def getDeviceWirelessBluetoothSettings(self, serial: str):\n\n metadata = {\n 'tags': ['Bluetooth settings'],\n 'operation': 'getDeviceWirelessBluetoothSettings',\n }\n resource = f'/devices/{serial}/wireless/bluetooth/settings'\n\n return await self._session...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the bluetooth settings for a wireless device
def updateDeviceWirelessBluetoothSettings(self, serial: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'configure', 'bluetooth', 'settings'], 'operation': 'updateDeviceWirelessBluetoothSettings' } resource = f'/devices/{serial}/wireles...
[ "async def updateDeviceWirelessBluetoothSettings(self, serial: str, **kwargs):\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['Bluetooth settings'],\n 'operation': 'updateDeviceWirelessBluetoothSettings',\n }\n resource = f'/devices/{serial}/wireless/blueto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the radio settings of a device
def getDeviceWirelessRadioSettings(self, serial: str): metadata = { 'tags': ['wireless', 'configure', 'radio', 'settings'], 'operation': 'getDeviceWirelessRadioSettings' } resource = f'/devices/{serial}/wireless/radio/settings' return self._session.get(metadata,...
[ "def get_settings(self):\r\n\r\n settings = {'serial_device': self.__serial_device,\r\n 'baud_rate': self.__baud_rate,\r\n 'data_bits': self.__data_bits,\r\n 'stop_bits': self.__stop_bits,\r\n 'parity': self.__parity,\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the radio settings of a device
def updateDeviceWirelessRadioSettings(self, serial: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'configure', 'radio', 'settings'], 'operation': 'updateDeviceWirelessRadioSettings' } resource = f'/devices/{serial}/wireless/radio/sett...
[ "def modifyPhoneSettings(self):\r\n if core.FW_conf['should_stop']:\r\n return\r\n\r\n settingValues = \\\r\n ['\"./yapas/privacy/phone-lock-enabled\" false', # disable device-lock API\r\n '\"./yapas/keylock/autolock\" 3600000', # set screen saver ti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the Bluetooth settings for a network
def updateNetworkWirelessBluetoothSettings(self, networkId: str, **kwargs): kwargs.update(locals()) if 'majorMinorAssignmentMode' in kwargs: options = ['Unique', 'Non-unique'] assert kwargs['majorMinorAssignmentMode'] in options, f'''"majorMinorAssignmentMode" cannot be "{kwarg...
[ "def update(self, settings):\n names = getFieldNames(IZEOConnection)\n for key, value in settings.items():\n if key in names:\n setattr(self, key, value)", "def _handle_zbbridge_setting(self, payload):\n if not self.tasmota_zigbee_bridge.get('setting'):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List the wireless connectivity events for a client within a network in the timespan.
def getNetworkWirelessClientConnectivityEvents(self, networkId: str, clientId: str, total_pages=1, direction='next', **kwargs): kwargs.update(locals()) if 'band' in kwargs: options = ['2.4', '5'] assert kwargs['band'] in options, f'''"band" cannot be "{kwargs['band']}", & must ...
[ "def list_connected(self):\n client_macs = [client.mac for client in self.blue_node.clients.get_connected_clients()]\n self.connected_nodes = {key: value for key, value in self.usernames.items() if key in client_macs}\n self.gui_input_queue.put((ChatTypes.NETWORK, self.connected_nodes))", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the latency history for a client
def getNetworkWirelessClientLatencyHistory(self, networkId: str, clientId: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'monitor', 'clients', 'latencyHistory'], 'operation': 'getNetworkWirelessClientLatencyHistory' } resource = f'/ne...
[ "def client_detailed_list(request, timestamp=None, **kwargs):\n\n kwargs['interaction_base'] = Interaction.objects.interaction_per_client(timestamp).select_related()\n kwargs['orderby'] = \"client__name\"\n kwargs['page_limit'] = 0\n return render_history_view(request, 'clients/detailed-list.html', **kw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List the nonbasic RF profiles for this network
def getNetworkWirelessRfProfiles(self, networkId: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'configure', 'rfProfiles'], 'operation': 'getNetworkWirelessRfProfiles' } resource = f'/networks/{networkId}/wireless/rfProfiles' ...
[ "def profile_list():\n conf = api.Config()\n\n for profile in conf.profile_sections():\n data = conf._profile_general(profile)\n\n try:\n _print_profile(profile, data)\n except KeyError:\n print(\n log.format(\n f\"Invalid or incompl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new RF profile for this network
def createNetworkWirelessRfProfile(self, networkId: str, name: str, bandSelectionType: str, **kwargs): kwargs.update(locals()) if 'minBitrateType' in kwargs: options = ['band', 'ssid'] assert kwargs['minBitrateType'] in options, f'''"minBitrateType" cannot be "{kwargs['minBitra...
[ "def create_network_profile(self, context, network_profile, fields=None):\n np = network_profile[\"network_profile\"]\n self._validate_network_profile(np)\n with context.session.begin(subtransactions=True):\n net_profile = self._add_network_profile(db_session=context.session,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates specified RF profile for this network
def updateNetworkWirelessRfProfile(self, networkId: str, rfProfileId: str, **kwargs): kwargs.update(locals()) if 'minBitrateType' in kwargs: options = ['band', 'ssid'] assert kwargs['minBitrateType'] in options, f'''"minBitrateType" cannot be "{kwargs['minBitrateType']}", & mus...
[ "def update_profile(self):\n pass", "def update():\n return api.profile_set(**build_profile())", "def UpdateProfile(profile, profileElement):\r\n UpdateRatings(profile.completionRatings, profileElement.find('completionAwards'))\r\n UpdateRatings(profile.moveRatings, profileElement.find('moveAwar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the wireless settings for a network
def getNetworkWirelessSettings(self, networkId: str): metadata = { 'tags': ['wireless', 'configure', 'settings'], 'operation': 'getNetworkWirelessSettings' } resource = f'/networks/{networkId}/wireless/settings' return self._session.get(metadata, resource)
[ "def wifi_setting(self) -> WifiSettings:\n return self._api.wifi_setting", "def wireless(self) -> Optional[WirelessProperties]:\n return self._wireless", "def wireless_scan(self):\n values = []\n logging.info(\"Scanning for wireless networks...\")\n results, error = self.iface...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the wireless settings for a network
def updateNetworkWirelessSettings(self, networkId: str, **kwargs): kwargs.update(locals()) if 'upgradeStrategy' in kwargs: options = ['minimizeUpgradeTime', 'minimizeClientDowntime'] assert kwargs['upgradeStrategy'] in options, f'''"upgradeStrategy" cannot be "{kwargs['upgradeS...
[ "def _set_wifi(self, ssid, key, do_reboot=True):\n key_encoded = \"\".join(\"%\" + hex(ord(c))[2:].rjust(2, \"0\") for c in key)\n data = {\"ssid\": ssid, \"key\": key_encoded, \"security\": \"mixed\"}\n self._set(\"/common/set_wifi_setting\", data)\n if do_reboot:\n res = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the L3 firewall rules for an SSID on an MR network
def getNetworkWirelessSsidFirewallL3FirewallRules(self, networkId: str, number: str): metadata = { 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l3FirewallRules'], 'operation': 'getNetworkWirelessSsidFirewallL3FirewallRules' } resource = f'/networks/{networkId}...
[ "def getNetworkWirelessSsidFirewallL7FirewallRules(self, networkId: str, number: str):\n\n metadata = {\n 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l7FirewallRules'],\n 'operation': 'getNetworkWirelessSsidFirewallL7FirewallRules'\n }\n resource = f'/networks/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the L3 firewall rules of an SSID on an MR network
def updateNetworkWirelessSsidFirewallL3FirewallRules(self, networkId: str, number: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l3FirewallRules'], 'operation': 'updateNetworkWirelessSsidFirewallL3FirewallRules' ...
[ "def updateNetworkWirelessSsidFirewallL7FirewallRules(self, networkId: str, number: str, **kwargs):\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l7FirewallRules'],\n 'operation': 'updateNetworkWirelessSsidFirewallL7Firewal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the L7 firewall rules for an SSID on an MR network
def getNetworkWirelessSsidFirewallL7FirewallRules(self, networkId: str, number: str): metadata = { 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l7FirewallRules'], 'operation': 'getNetworkWirelessSsidFirewallL7FirewallRules' } resource = f'/networks/{networkId}...
[ "def getNetworkWirelessSsidFirewallL3FirewallRules(self, networkId: str, number: str):\n\n metadata = {\n 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l3FirewallRules'],\n 'operation': 'getNetworkWirelessSsidFirewallL3FirewallRules'\n }\n resource = f'/networks/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the L7 firewall rules of an SSID on an MR network
def updateNetworkWirelessSsidFirewallL7FirewallRules(self, networkId: str, number: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l7FirewallRules'], 'operation': 'updateNetworkWirelessSsidFirewallL7FirewallRules' ...
[ "def updateNetworkWirelessSsidFirewallL3FirewallRules(self, networkId: str, number: str, **kwargs):\n\n kwargs.update(locals())\n\n metadata = {\n 'tags': ['wireless', 'configure', 'ssids', 'firewall', 'l3FirewallRules'],\n 'operation': 'updateNetworkWirelessSsidFirewallL3Firewal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all Identity PSKs in a wireless network
def getNetworkWirelessSsidIdentityPsks(self, networkId: str, number: str): metadata = { 'tags': ['wireless', 'configure', 'ssids', 'identityPsks'], 'operation': 'getNetworkWirelessSsidIdentityPsks' } resource = f'/networks/{networkId}/wireless/ssids/{number}/identityPsks...
[ "def get_ssid_profiles(self):\n response = self.request(PATH_SSID_PROFILES)\n\n if response.status_code == requests.codes.ok:\n return response.json()\n else:\n print(\"Unrecognised status for fetch ssid profile\" + response.status_code)", "def print_ssid(interface, ssid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the splash page settings for the given SSID
def getNetworkWirelessSsidSplashSettings(self, networkId: str, number: str): metadata = { 'tags': ['wireless', 'configure', 'ssids', 'splash', 'settings'], 'operation': 'getNetworkWirelessSsidSplashSettings' } resource = f'/networks/{networkId}/wireless/ssids/{number}/sp...
[ "def showSettings():\n\n if self.Logger.logging:\n self.setToggleState(self.Logger.toggle())\n self.controller.showFrame(\"SettingsPage\")", "def splash_screen(vDict):\n\n wDict = vDict['windowDict']\n\n mainWindow = wDict['mainWindow']\n\n titleText = 'Trial of Astur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify the splash page settings for the given SSID
def updateNetworkWirelessSsidSplashSettings(self, networkId: str, number: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'configure', 'ssids', 'splash', 'settings'], 'operation': 'updateNetworkWirelessSsidSplashSettings' } resource = f...
[ "def getNetworkWirelessSsidSplashSettings(self, networkId: str, number: str):\n\n metadata = {\n 'tags': ['wireless', 'configure', 'ssids', 'splash', 'settings'],\n 'operation': 'getNetworkWirelessSsidSplashSettings'\n }\n resource = f'/networks/{networkId}/wireless/ssids/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the traffic shaping settings for an SSID on an MR network
def updateNetworkWirelessSsidTrafficShapingRules(self, networkId: str, number: str, **kwargs): kwargs.update(locals()) metadata = { 'tags': ['wireless', 'configure', 'ssids', 'trafficShaping', 'rules'], 'operation': 'updateNetworkWirelessSsidTrafficShapingRules' } ...
[ "def _set_wifi(self, ssid, key, do_reboot=True):\n key_encoded = \"\".join(\"%\" + hex(ord(c))[2:].rjust(2, \"0\") for c in key)\n data = {\"ssid\": ssid, \"key\": key_encoded, \"security\": \"mixed\"}\n self._set(\"/common/set_wifi_setting\", data)\n if do_reboot:\n res = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the contents of a PBO archive to stdout in tabular format.
def list_pbo(reader: pbo_reader.PBOReader, *, verbose: bool) -> None: if verbose: print("Headers:") print("--------") for key, value in reader.headers(): print(f"{key.decode(errors='replace')} = {value.decode(errors='replace')}") print() print(" Original Type ...
[ "def _printBin(bin_):\n print('Bin has %d items:' % len(bin_), file=sys.stderr)\n for i, hashInfo in enumerate(bin_, start=1):\n print(' Item %d:' % i, file=sys.stderr)\n for key, value in hashInfo.items():\n # The 16 below is the length of the longest key (subjectTrigPoint).\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample likelihood or observationspecific model parameters.
def _sample_likelihood_params(self): if self.marginalize: # We integrated out `beta` a la Bayesian linear regression. pass else: self._sample_beta()
[ "def _sample_model_params(self):\n self.initial_internal_params = dict()\n for k in self._all_internal_params_distribs[self.region].keys():\n self.initial_internal_params[k] = self._all_internal_params_distribs[self.region][k].sample()\n self._reset_model_params()", "def sample_par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the maximum a posteriori estimation of `beta`.
def _sample_beta(self): def _neg_log_posterior(beta_flat): beta = beta_flat.reshape(self.J, self.M + 1) LL = self.log_likelihood(beta=beta) LP = ag_mvn.logpdf(beta, self.b0, self.B0).sum() return -(LL + LP) resp = minimize(_neg_log_posterior, ...
[ "def get_beta(self, alpha):\n if self.train_embeddings:\n logit = self.rho(alpha.view(alpha.size(0) * alpha.size(1), self.rho_size)) # logit is K*T x V\n else:\n tmp = alpha.view(alpha.size(0) * alpha.size(1), self.rho_size)\n logit = torch.mm(tmp, self.rho.permute(1, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate MetropolisHastings proposal `W` using the log evidence.
def _evaluate_proposal(self, W_prop): if self.marginalize: return self.log_marginal_likelihood(self.X, W_prop) else: return self.log_likelihood(W=W_prop)
[ "def EvalW(self, J):\n return _nonlininteg.NeoHookeanModel_EvalW(self, J)", "def EvalW(self, J):\n return _nonlininteg.InverseHarmonicModel_EvalW(self, J)", "def approximate_structural_wavelet_embedding(self):\n self.G.estimate_lmax()\n self.heat_filter = pygsp.filters.Heat(self.G, t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute log posterior of `X`.
def _log_posterior_x(self, X): if self.marginalize: LL = self.log_marginal_likelihood(X, self.W) else: LL = self.log_likelihood(X=X) LP = self._log_prior_x(X) return LL + LP
[ "def log_posterior(p):\n\treturn log_flat_prior(p) + log_likelihood(p) # choose your prior here", "def _log_posterior(self, y, X, beta, prior_means, prior_stds): \n \n # Calculate a value proportional to the log-posterior.\n _log_posterior = (self._normal_log_prior(beta, prior_means, prior_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a tridiag solver object. The parameters which are also present on the tridiag function serve the identical purpose. Returns fullstorage solvers only
def get_tridiag(A, view=None, method='sp_hes', low_memory=True, max_cutoff=None, v0=None, stable=False): if method == 'sp_hes': return ScipyHessenberg(A, view=view) elif method == 'hou': return Householder(A, view=view) elif method == 'lan': if low_memory: return LowMemLa...
[ "def get_tridiag_from_special_sparse(side, diag, view=None, low_memory=True, max_cutoff=None, v0=None, stable=False):\n if low_memory:\n return LowMemLanczosSpecialSparse(side, diag, view=view, max_cutoff=max_cutoff, v0=v0, stable=stable)\n else:\n return LanczosSpecialSparse(side, diag, view=vi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a tridiag solver object. The parameters which are also present on the tridiag_from_diag function serve the identical purpose. Returns sparse solvers only (either one of the following LowMemLanczosDiag/ LanczosDiag)
def get_tridiag_from_diag(diag, view=None, low_memory=True, max_cutoff=None, v0=None, stable=False): if low_memory: return LowMemLanczosDiag(diag, view=view, max_cutoff=max_cutoff, v0=v0, stable=stable) else: return LanczosDiag(diag, view=view, max_cutoff=max_cutoff, v0=v0, stable=stable)
[ "def get_tridiag_from_special_sparse(side, diag, view=None, low_memory=True, max_cutoff=None, v0=None, stable=False):\n if low_memory:\n return LowMemLanczosSpecialSparse(side, diag, view=view, max_cutoff=max_cutoff, v0=v0, stable=stable)\n else:\n return LanczosSpecialSparse(side, diag, view=vi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a tridiag solver object. The parameters which are also present on the tridiag_from_special_sparse function serve the identical purpose. Returns sparse solvers only (either one of the following LowMemLanczosSpecialSparse/ LanczosSpecialSparse)
def get_tridiag_from_special_sparse(side, diag, view=None, low_memory=True, max_cutoff=None, v0=None, stable=False): if low_memory: return LowMemLanczosSpecialSparse(side, diag, view=view, max_cutoff=max_cutoff, v0=v0, stable=stable) else: return LanczosSpecialSparse(side, diag, view=view, max_c...
[ "def get_tridiag(A, view=None, method='sp_hes', low_memory=True, max_cutoff=None, v0=None, stable=False):\n if method == 'sp_hes':\n return ScipyHessenberg(A, view=view)\n elif method == 'hou':\n return Householder(A, view=view)\n elif method == 'lan':\n if low_memory:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test adding comment using POST request
def test_comment(self): data = {"parent_uid": self.post.uid, "content": "tested content for a question"} url = reverse('create_comment', kwargs=dict(uid=self.post.uid)) request = fake_request(url=url, data=data, user=self.owner) response = views.new_comment(request=request, uid=self.po...
[ "def test_moments_comment_post(self):\n body = CreateComment()\n response = self.client.open(\n '/moments/comment',\n method='POST',\n data=json.dumps(body),\n content_type='application/json')\n self.assert200(response,\n 'Respon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test comment rendering pages
def test_comment_traversal(self): # Create a couple of comments to traverse comment = models.Post.objects.create(title="Test", author=self.owner, content="Test", type=models.Post.COMMENT, root=self.post, parent=self.post) co...
[ "def test_comment_paging(self):\n for i in range(0, 20):\n self.place_comment(self.article, comment='hello world %s' % i,\n next=self.article_url)\n\n resp = self.client.get(reverse('article_detail_redo',\n args=[self.article.pk]))\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the ajax voting using POST request
def test_ajax_vote(self): # Create a different user to vote with user2 = User.objects.create(username="user", email="user@tested.com", password="tested") answer = models.Post.objects.create(title="answer", author=user2, content="tested foo bar too for", type=mo...
[ "def test_create_vote(self):\n\n res = self.client.post('/api/v1/votes', json=self.new_vote)\n data = res.get_json()\n\n self.assertEqual(data['status'], 201)\n self.assertEqual(data['message'], 'Success')\n self.assertEqual(res.status_code, 201)", "def test_vote(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test submitting answer through the post view
def test_post_answer(self): url = reverse("post_view", kwargs=dict(uid=self.post.uid)) # Get form data data = dict(content="testing answer", parent_uid=self.post.uid) request = fake_request(url=url, data=data, user=self.owner) response = views.post_view(request=request, uid=self...
[ "def test_post_answer(self):\n self.token = self.get_token()\n head = {'Content-Type': 'application/json', 'Authorization': 'JWT {}'.format(self.token)}\n\n self.test_client().post('/api/v1/questions', \\\n data=json.dumps(self.question), headers=head)\n\n post_answer = self.test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request that repair begin on this cluster as soon as possible.
async def begin_request_repair( self, resource_group_name: str, cluster_name: str, body: "_models.RepairPostBody", **kwargs ) -> AsyncLROPoller[None]: polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) ...
[ "async def do_start_cluster(self, cluster):\n raise NotImplementedError", "def resume_cluster(self) -> Optional[pulumi.Input['ScheduledActionTargetActionResumeClusterArgs']]:\n return pulumi.get(self, \"resume_cluster\")", "def onBeginRepair(self, inEvent: RealTimeEvent):\n\n player_id = in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
second hash function cannot produce 0 as it will be used as the step, if the hash is 0, hash is changed to 1
def _second_hash(self, key): value = 0 a = 59757 b = 64587 for ch in key: value = (a * value + ord(ch)) % len(self._array) a = a * b % len(self._array) return value or 6
[ "def hashFunctionTest():\n m = 128\n h = HashFunction(m)\n print(h)\n\n count = [0] * m\n for i in range(m*2):\n count[h.h(random.randint(-10000,10000))] += 1\n print count", "def rehash(prev_hash, first, last, d):\n return ((prev_hash - ord(first) * d) << 1) + ord(last)", "def test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a random meme.
def meme_rand(): img = random.choice(imgs) quote = random.choice(quotes) path = meme.make_meme(img, quote.body, quote.author) return render_template('meme.html', path=path)
[ "def meme_rand():\n img = None\n quote = None\n\n img = random.choice(imgs)\n quote = random.choice(quotes)\n\n path = meme.make_meme(img, quote.body, quote.author)\n return render_template('meme.html', path=path)", "def meme_rand():\n\n img = random.choice(imgs)\n quote = random.choice(qu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the get_profile_context function behaves as expected.
def test_get_profile_context(self, la_mock, lca_mock, lgsi_mock, get_char_mock): characters = MagicMock() get_char_mock.return_value = 'testchar' context = {'character_name' : 'testchar', 'level' : '1', 'game_saved' : [], 'zipped' : [], ...
[ "def test_oauthclientprofiles_get(self):\n pass", "def _get_test_profile(self):\n return self.__test_profile", "def _get_test_profile_params(self):\n return self.__test_profile_params", "def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the data, select the correct columns and normalises it to have mean zero and std one. When growth is True take the loggrowth of INF and IP. By default standardise to have zero mean and unit standardeviation. Other option is to standardise such that all values lie between a and b.
def prepareData(growth=True, standardiseMaxMin=False, a=-1, b=1, filterVars=None, filterValues=None): df=ReadData3.loadDataRec() if filterVars is not None: df=df.drop(df[(df[filterVars]>filterValues).any(axis=1)].index) if growth: df['INF']=np.log(df['INF'])-np.log(df['INF'].shift(1)) ...
[ "def feature_scale(self):\n \n #-------------------------------------------------------------------------\n # List of quantitative features to be standardized\n #-------------------------------------------------------------------------\n list_quant_feature = ['Quantity','UnitPrice']\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the losses from the model at index. Location is the full location except for the number indicating the model number.
def losses(index, location): with open(location+str(index), 'rb') as file: losses=dill.load(file) return losses
[ "def getLosses(self):\n\t\treturn np.array(self.__losses)", "def _get_and_write_losses(self, data, model_output):\n losses = {}\n for loss_function in self.loss_functions:\n if loss_function.weight <= 0.0:\n continue\n loss = loss_function(data, model_output) * l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the variables in df, except for the variables given by nonStandardised. Assumes the data in df is already standardised.
def plotStandardised(df, nonStandardised, style=None, axList=None, xlabel=None): if axList is None: axList=[] for i in range(len(df.columns)-len(nonStandardised)): fig,ax=plt.subplots() axList.append(ax) if style is not None: plt.style.use(style) dates=df.inde...
[ "def test_non_numeric_plots(self, test_df):\n analyser = Analyser(test_df.copy(deep=True))\n plot_dic = analyser.non_numeric_frequency_plot()\n if test_df.empty:\n plot_dic = \"No columns in data\"\n # verify non numeric variables\n else:\n for col, plots in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a contribution plot for the varaible given or for all variables if it equals None, excluding the factor, return and if given recession indicator. By default assume log sigma is moddeled.
def contributionPlot(model, df, locParameters, dfData, axList=None, variable=None, steps=250, factor='M', R='HML', recession=None, quantiles=[0.2, 0.4, 0.6, 0.8], bins=25, net=mod.FeedForwardLossLogSigma, combinationMatrix=None, modelName=None): minData=dfData.min() max...
[ "def plot_fraction(fit, color='m'):\n if ('FractionBallistic' in fit.parameter.values):\n frac = fit.parameters.loc['FractionBallistic']\n ylabel_str = \"Fraction moving ballistically\"\n elif ('Fraction1' in fit.parameter.values):\n frac = fit.parameters.loc['Fraction1']\n ylabel_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gives the average loss of the loss function according to negative log normal. Alpha is either a T vector or a 3xT matrix of alpha or alpah,beta,sigma. Not log sigma. If fracTrain is not 1 all variables are split in a training and validation set. The desired sample is then selected via sample.
def lossNormal(alpha, beta=None, sigma=None, R=None, factor=None, fracTrain=0.8, sample='validation'): if alpha.shape[1]>=3: R=beta if R is None else R factor=sigma if factor is None else factor beta=alpha[:,1] sigma=alpha[:,2] alpha=alpha[:,0] elif R is None or factor is...
[ "def mean_standardized_log_loss(\n pred_dist: MultivariateNormal,\n test_y: torch.Tensor,\n):\n combine_dim = -2 if isinstance(pred_dist, MultitaskMultivariateNormal) else -1\n f_mean = pred_dist.mean\n f_var = pred_dist.variance\n return 0.5 * (torch.log(2 * pi * f_var) + torch.square(test_y - f_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gives a generator for the powerset of list l. Empty part is ommitted.
def powerset(l): if len(l)<=0: yield [] if len(l)==1: yield l yield [] else: for item in powerset(l[1:]): yield [l[0]]+item yield item
[ "def powerset(U):\n for j in range(0,len(U)+1):\n for E in powersetj(U,j):\n yield E", "def powerset(self, iterable):\n s = list(iterable)\n return list(itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1)))", "def powerset(self, iterable):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a data frame with the importance measures according to method for the models in model. Shapley value is calculated in parallel using Pathos. By default it is assumed log sigma is moddeled. If combinationMatrix is not None the combination constructed by those weights is used.
def importanceDf(model, df, locParameters, dfTrainVal, method='importance', inputName='input', locShapley=os.getcwd()+'/Results/Estimates/Shapley', relative=True, draws=10, rng=None, outputSSD='loss', outputName='output', sample='whole', X=['DEF', 'TERM', 'RREL', 'D...
[ "def modelAveraging(models, df, locParameters, dfData, combination, net=mod.FeedForwardLossLogSigma,\n dictModel={}, dictCombination={}):\n extraOut={}\n #Select models\n if isinstance(models, list):\n extraOut['models']=models\n elif models=='add':\n models=modelsAdd(df,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of models for which the variable under variableNr is in l.
def filterParameter(hyperParams, variableNr, l): l= l if isinstance(l, list) else [l] res=[] for i in hyperParams: if i[variableNr] in l: res.append(i[-1]) return res
[ "def filter_values(fv, variables, model_vars):\n V = []\n for v,val in zip(variables,fv):\n if v in model_vars:\n V.append(val)\n return V", "def get_odoo_model_ids(self):\n print('Searching Odoo for sellable items with matching models')\n for model in self.models_to_searc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the data frame as a talbe. Either as a tex or txt file. If written as tex file, the caption is read from a file.
def table(df, name, locTable, formatters=None, tex=True, locCaption=None, escape=False, column_format=None, na_rep='', index=False, longtable=False, multirow=True, float_format=None, header=True): locCaption=locTable+'/Captions' if locCaption is None else locCaption if tex: with open(locTable...
[ "def write_to_stdout(\n stem: str, dfm: pd.DataFrame, show_index: bool = False, line_width: float = None\n) -> None:\n sys.stdout.write(f\"TABLE: {stem}\\n\")\n sys.stdout.write(dfm.to_string(index=show_index, line_width=line_width) + \"\\n\\n\")", "def display_df(df):\r\n\r\n console = Console()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the heatmaps for the df in dfList. Sets only one colorbar.
def heatmapMultiple(dfList, xlabels=None, ylabels=None, cbarlabel='Relative importance', variableNames=None, models=None, titles=None): n=len(dfList) fig,axes=plt.subplots(1, n, constrained_layout=True, tight_layout=False) xlabels=n*[None] if xlabels is None else xlabels ylabels=n*[N...
[ "def gcp_heatmap(df, categoricals, labels):\n\n # Create each plot individually\n main = go.Heatmap(z=df.values, x=df.columns, y=df.index,\n colorscale='RdBu', reversescale=True)\n side = go.Heatmap(z=labels.values, x=list(labels.columns), y=df.index.tolist(),\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standardises the dataframe such that each row lies between a and b.
def standardise(df, a=-1, b=1): dfNew=copy.deepcopy(df) for i,row in enumerate(df.itertuples()): minRow=min(row[1:]) maxRow=max(row[1:]) for j, value in enumerate(row[1:]): dfNew.iat[i,j]=a+(value-minRow)*(b-a)/(maxRow-minRow) return dfNew
[ "def standardize_df(df):\n return (df-df.mean())/df.std()", "def normalize_df(df):\n return (df-df.min())/(df.max()-df.min())", "def normalize(df):\n result = df.copy()\n for feature_name in df.columns:\n max_value = df[feature_name].max()\n min_value = df[feature_name].min()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Considers adding models for model averaging until the loss over sample has not decreased for p successive models, where the models are sorted based on lossType and averaged using combination.
def modelsAdd(df, locParameters, dfData, addCombination='mean', lossType='Loss k', lossFunction=lossNormal, net=mod.FeedForwardLossLogSigma, p=5, R='HML', factor='M', fracTrain=0.8, sample='validation'): candidates=df.sort_values(lossType).index selected=[candidates[0]] absn=ABSh...
[ "def modelAveraging(models, df, locParameters, dfData, combination, net=mod.FeedForwardLossLogSigma,\n dictModel={}, dictCombination={}):\n extraOut={}\n #Select models\n if isinstance(models, list):\n extraOut['models']=models\n elif models=='add':\n models=modelsAdd(df,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combines the matrices in absn weighted using the accuracy of each matrix
def combinationAccuracy(absn, dfData, lossFunction=lossNormal, R='HML', factor='M', fracTrain=0.8, sample='validation'): losses=np.zeros(len(absn)) for i,matrix in enumerate(absn): losses[i]=lossFunction(matrix, R=dfData[R], factor=dfData[factor], fracTrain=fracTrain, sample=sample) accuracy=(min(lo...
[ "def populate_score_matrices(self):\n ### FILL IN ###\n #careful to use len_alphabet_a vs. len(align_params.seq_a) for align_test\n #we dont specify seqa, only size of alphabet for testing update_ix, update_m, update_iy\n for i in range(0,len(self.align_params.seq_a)+1):\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combines the matrices in absn weighted using the inverse loss raised to the power k of each matrix
def combinationInverseLoss(absn, dfData, lossFunction=lossNormal, R='HML', factor='M', fracTrain=0.8, sample='validation', k=1): losses=np.zeros(len(absn)) for i,matrix in enumerate(absn): losses[i]=lossFunction(matrix, R=dfData[R], factor=dfData[factor], fracTrain=fracTrain, sample=sample) weights=...
[ "def _normalized_weights(Wk, Gk, Cm_inv_sq, reduce_rank, nn, sk):\n # np.dot Gk with Cm_inv_sq on left and right\n norm_inv = np.matmul(Gk.transpose(0, 2, 1),\n np.matmul(Cm_inv_sq[np.newaxis], Gk))\n\n # invert this using an eigenvalue decomposition\n norm = _pos_semidef_inv(nor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combines the models as selected by models and combines their output via combination.
def modelAveraging(models, df, locParameters, dfData, combination, net=mod.FeedForwardLossLogSigma, dictModel={}, dictCombination={}): extraOut={} #Select models if isinstance(models, list): extraOut['models']=models elif models=='add': models=modelsAdd(df, locParamete...
[ "def combine_models(models):\n final_model = ReactionModel()\n for i, model in enumerate(models):\n print('Ignoring common species and reactions from model #{0:d}...'.format(i + 1))\n nspec0 = len(final_model.species)\n nrxn0 = len(final_model.reactions)\n final_model = final_model...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the ABS curves for models in single figures. Also add the combinations as given by the list of ABS matrices in combinatinos.
def ABSOnePlot(models, df, locParameters, dfData, combinations=None, axes=None, fig=None, lossType='Loss k', cmapStyle='magma', linestyles=['-', '--', ':', '-.'], colors=['black', 'black', 'black', 'black'], net=mod.FeedForwardLossLogSigma, alpha=0.5, title=None, linewidth=1...
[ "def view_absorption_spectra(save_path=None):\n plt.figure(figsize=(11, 8))\n for spectrum in SPECTRAL_LIBRARY:\n plt.semilogy(spectrum.wavelengths,\n spectrum.values,\n label=spectrum.spectrum_name)\n ax = plt.gca()\n box = ax.get_position()\n ax.set_po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs OLS of 1~x on y, samples in rows. Returns estimated beta and sigma squared.
def OLS(x, y, CI=False): X=np.hstack((np.full((len(x),1),1), x)) n,k=x.shape beta=np.linalg.inv(X.T@X)@X.T@y eps=y-X@beta sigma2=eps.T@eps/(n-k) if CI: interval=[beta-1.95*np.sqrt(np.diag(np.linalg.inv(X.T@X)*sigma2)).reshape((-1,1)),beta+1.95*np.sqrt(np.diag(np.linalg.inv(X.T@X)*sigma2)...
[ "def eval_lin_model(beta, X_test, y_test):\n w = beta.T[:, 1:]\n y = beta.T[:, 0] + np.dot(X_test, w.T)\n MSE = np.sum((y - y_test)**2)/y_test.shape[0]\n\n return MSE, y", "def linear_model(X, y):\n results = sm.OLS(y, sm.add_constant(X)).fit()\n return results", "def linear_regression(X,y):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Smooth the edges of a text given as foreground mask or as grayscale image Smoothing an image is used to straightens the lines in the image. Smoothing is defined as a series of erosions and dilations after one another. smooth = erode(dilate(dilate(erode(mask)))) to be exact.
def smooth(foreground_mask: np.ndarray, kernel_size: int, kernel_shape: str = "rect") -> np.ndarray: def opening(img): # opening = erosion followed by dilation return dilate(erode(img, kernel_size, kernel_shape), kernel_size, kernel_shape) def closing(img): ...
[ "def edgeenhance(message, im):\n return im.filter(ImageFilter.EDGE_ENHANCE)", "def erode_and_smooth(image_mask, erode_kernel, threshold, gauss_width, bb_buffer):\n #First erode the mask\n eroded_mask = cv2.erode(image_mask, erode_kernel, iterations = 1)\n mask_blurred = cv2.GaussianBlur(eroded_mask, (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Printing the results of motif identification
def print_motifs(motifs): if motifs is None: print("Empty") return for m in motifs: print("{}\t{}\t{:.2f}\t{:.2e}\t{}".format( m['name'], m['motif'], m['enrichment'], m['pvalue'], m['mutations'])) print()
[ "def print_results(results):", "def display_stuff(self):\n # print(\"i1 | i2 | b | Net| O/p | Thresh\")\n #print(\"neuron display\")\n print(*self.inp_list, self.y, self.out, self.threshold, *self.weight_list, sep=\" | \")\n # print(\"Weights used are: \")\n # print(*self.weig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get_volumes_owned() Inverse of generate function; convert integers into humanreadable format (same as original input format)
def get_volumes_owned(self): if self.volumes_owned_readable == "": index = 0 first = -1 last = -1 none_owned = 1 for num in self.vol_arr: if num == 0: # no volumes in set of 32, no need to check bits if first != -1...
[ "def generate_volumes_owned(vol_list):\n # Check that input is valid\n pattern = r\"^\\d+(-\\d+)?(,\\s*\\d+(-\\d+)?)*\\s*$\"\n if not regexp(pattern, vol_list):\n print(\"Using default (empty series)\")\n return '0,0,0,0'\n\n volume_limit = Config().volume_limit\n arr_length = int(math....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts vol_arr to a single binary string listing all volumes
def get_volumes_owned_binary(self): vol_str = "" for val in self.vol_arr: vol_str += "{0:032b}".format(val)[::-1] return vol_str
[ "def list_vol(tag=None, device=None):\n conn = _ec2connect()\n vols = conn.get_all_volumes(filters=_get_filters(tag))\n if not vols:\n print('\\tNone.')\n return\n for v in vols:\n t = v.tags.get(TAG_NAME, 'root')\n s = v.attachment_state()\n z = v.size\n i = v....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add_series_to_database() Takes a series and adds it to the database if the database contains no entries with the same name as series. Returns True on success, False on failure.
def add_series_to_database(self, data_mgr): cur = data_mgr.query("SELECT name FROM Series WHERE name='{0}'" .format(self.name.replace("'", "''"))) entries = cur.fetchall() if not entries: data_mgr.query("INSERT INTO Series VALUES(" ...
[ "def addseries(connection, seriesname): ## Tested: SeriesCase_Base.test_addseries/bad\n if not isinstance(seriesname,str): raise ValueError(\"seriesname must be str.\")\n result = connection.execute(\"\"\"\nINSERT INTO \"series\" VALUES ();\"\"\")\n return result.lastrowid", "def add_new(self, name):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
edit() Allows user to modify all fields of a series. User selects field to modify from menu, continuing until user decides to save. Automatically updates dependent fields (ex. next volume) Returns True if the series has no volumes and the user chooses to delete it, False otherwise
def edit(self, data_mgr): reserved_words = ["unknown"] selection = '' while selection not in ('e', 'E'): selection = input("Edit: \n[N]ame / [V]olumes / [A]uthor / " "[P]ublisher \n[Alt]ernate Names /" "[C]ompletion Status ...
[ "def edit_volumes(self):\n change_volumes = input(\"[A]dd or [R]emove volumes, or leave \"\n \"blank if unchanged: \").strip()\n\n # Add Volumes\n if change_volumes in ('a', 'A'):\n volumes_to_add = input(\n \"Enter volumes to add (ex. 1, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standalone function for adding new volumes to a series. Takes input in the form of a commaseparated list of volumes or ranges of volumes, and adds the passed volumes to the series entry.
def add_volumes(self, volumes_to_add): volumes_to_add = generate_volumes_owned(volumes_to_add) vol_arr_to_add = [int(x) for x in volumes_to_add.split(",")] self.vol_arr = [x | y for x, y in zip(vol_arr_to_add, self.vol_arr)] # update rel...
[ "def add_volume(self, volume):\n self.volumes.append(volume)\n return self", "def test_volumes_add(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n self.assertEqual(len(svc.volumes), 8)\n svc.volume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standalone function for removing volumes from a series. Takes input in the form of a commaseparated list of volumes or ranges of volumes, and removes the passed volumes from the series
def remove_volumes(self, volumes_to_remove): volumes_to_remove = generate_volumes_owned(volumes_to_remove) vol_arr_to_remove = [int(x) for x in volumes_to_remove.split(",")] self.vol_arr = [~x & y for x, y in zip(vol_arr_to_remove, self.vol_ar...
[ "def test_volumes_remove(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n self.assertEqual(len(svc.volumes), 8)\n svc.volumes = filter(lambda r: r.resourcePath not in [\"zenjobs\", \"zenoss-export\"], svc.volumes)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
edit_volumes() Changes which volumes are marked as owned in the series object. Returns True if the series has no volumes and the user chooses to delete it, False otherwise.
def edit_volumes(self): change_volumes = input("[A]dd or [R]emove volumes, or leave " "blank if unchanged: ").strip() # Add Volumes if change_volumes in ('a', 'A'): volumes_to_add = input( "Enter volumes to add (ex. 1, 3-5): ") ...
[ "def test_volumes_replace(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n svc.volumes = [\n sm.Volume(\"foo\", \"bar\"),\n sm.Volume(\"bar\", \"baz\"),\n ]\n ctx.commit(OUTFILENAME)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update_database_entry() Updates all fields in database for series based on unique identifier; adds series to database if not currently in database
def update_database_entry(self, data_mgr): if self.rowid is None: self.add_series_to_database(data_mgr) return data_mgr.query("UPDATE Series SET " "name = '{0}', " "volumes_owned = '{1}', " "is_completed = {2},...
[ "def update_database(fn):\n fn = \"../data/weekly_updates/\"+fn\n data = fwf.read_data(fn)\n df = fwf.split_read_combine(data)\n df_2 = filter_df(df,2)\n #search and replace filing number\n delete_log(df_2)\n dump_df(df)\n return", "def updateCurrentDataDatabase(self):\n\n for (key,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
init_database() Initializes a DatabaseManager() object for use storing data for Series objects Passed as argument to DatabaseManager() constructor
def init_database(data_mgr, new_db_needed=True): data_mgr.query("SELECT name FROM sqlite_master " "WHERE type='table' AND name='Series'") if data_mgr.cur.fetchone() is None: data_mgr.query("CREATE TABLE Series(name TEXT, volumes_owned TEXT, " "is_completed INT,...
[ "def init_with_database(self):\n\n with self._lock:\n self._metrics.init_with_database()", "def init_db():\n\n with app.app_context():\n data = json.loads(urllib2.urlopen(DATA_URL).read())\n ds = DataSource(data['data'], data['meta']['view']['columns'])\n headers = ds.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the given volume list into a fourinteger string representation. Takes a string of numbers in a commaseparated list (ex. "1, 35, 7"), stores them bitwise in 32bit integers, then concatenates bitwise representations of them in a string and returns the result. Returns '0,0,0,0' by default if input is invalid or e...
def generate_volumes_owned(vol_list): # Check that input is valid pattern = r"^\d+(-\d+)?(,\s*\d+(-\d+)?)*\s*$" if not regexp(pattern, vol_list): print("Using default (empty series)") return '0,0,0,0' volume_limit = Config().volume_limit arr_length = int(math.ceil(volume_limit / 32)...
[ "def smart(list_):\n string = ''.join(map(str, list_))\n return pandigitial_product(int(string[:1]), int(string[1:])) \\\n + pandigitial_product(int(string[:2]), int(string[2:]))", "def listFormat(original_list):\n\n\tbuf = []\n\n\tfor i in original_list.split(','): # for each element in string s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
flatten a list of lists and returns a list of unique elements.
def flatten_list(list_of_lists): list_unique = list() for x in list_of_lists: for y in x: list_unique.append(y) list_unique = list(set(list_unique)) return(list_unique)
[ "def get_uniques_in_list_of_lists(input_list):\n return list({item for sublist in input_list for item in sublist})", "def unique_elements(a_list):\n result = []\n for elem in a_list:\n if not elem in result:\n result.append(elem)\n return result", "def flatten(l):\n return [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolve all partial paths with the specified base path.
def _resolve_class_paths(self, base_path: Path) -> None: for name, path_raw in self._get_members(instance_type=type(Path()), prefix=None): if not path_raw.is_absolute(): # type: ignore[attr-defined] setattr(self, name, base_path / path_raw) # type: ignore[operator] ...
[ "def resolve(self, *args):\n rtn = os.path.join(self.__base, *args)\n if not self.__exists(rtn):\n raise Exception(\"Bad path: %s (base: %s)\" % (rtn, self.__base))\n return rtn", "def base(path1, *paths):\n return config.BASE_DIR.relpathto(path1.joinpath(*paths)) # pylint: disable=no-value-for-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure `DoitGlobals` based on project directory.
def set_paths( self, *, path_project: Optional[Path] = None, ) -> None: if self._is_set: raise RuntimeError('DoitGlobals has already been configured and cannot be reconfigured') logger.info(f'Setting DG path: {path_project}', path_project=path_project, cwd=Path.cwd()) pa...
[ "def use_test_config():\n os.environ[\"TS_COLAB_CONFIG_DIR\"] = str(PROJECT_ROOT / \"tests\" / \".config\" / \"test\")", "def SetGlobals():\n global yaml_errors, appcfg, appengine_rpc, dev_appserver, os_compat\n from google.appengine.api import yaml_errors\n from google.appengine.dist import py_zipimport\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Init the Log View.
def initView(self): wx.Panel.__init__(self, self.parent, -1) self.log_ctrl = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE|wx.TE_READONLY) sizer = wx.BoxSizer() sizer.Add(self.log_ctrl, 1, wx.EXPAND) self.SetSizer(sizer)
[ "def __init__(self, request):\n super(PrettyView, self).__init__(request)\n\n # Set up logging\n self.log = logging.getLogger(__name__)", "def __init__ (self, log = list()):\n\n self.__log = log", "def _init_logger(self):\n #self._logger = logger_factory.make_logger(__name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the log target to text_ctrl.
def setLogTarget(self, use_timestamp=True): if use_timestamp: wx.Log.SetActiveTarget(wx.LogTextCtrl(self.log_ctrl)) else: wx.Log.SetActiveTarget(wx.LogTextCtrl(self.log_ctrl))
[ "def __init__(self, text_ctrl):\r\n self.output = text_ctrl", "def LogTarget(self, value: \"s\"):\n self.log_target = value", "def setText(self, textState):\r\n oldInsertionPoint = self.control.GetInsertionPoint()\r\n self.control.SetValue(textState)\r\n self.control.SetInsert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set a prompt string.
def setPrompt(self, prompt='>> '): self.prompt = prompt
[ "def setPrompt(self, args:list):\n\t\tif len(args) > 0:\n\t\t\tself.prompt_str = args[0]\n\t\telse:\n\t\t\t_globals._console.write(\n\t\t\t\t'Usage: prompt <string> Please supply a string.'\n\t\t)", "def prompt(self):\n\t\t_globals._console.write(f'{self.prompt_str} ')", "def set_prompt(self, prompt, prompt_is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates through a query_namesorted BAM file, groups all alignments with the same query name
def _get_alignments_grouped_by_query_name_generator( bam_file: str, cell_barcode_tag: str, molecule_barcode_tag: str, open_mode: str = "rb", ) -> Generator[ Tuple[str, Optional[str], Optional[str], List[pysam.AlignedSegment]], None, None ]: with pysam.AlignmentFil...
[ "def align_query_seqs(self, papara_runname=\"extended\"):\n cwd = os.getcwd()\n if not self._query_seqs_written:\n self.write_query_seqs()\n for filename in glob.glob('{}/papara*'.format(self.workdir)):\n os.rename(filename, \"{}/{}_tmp\".format(self.workdir, filename.spli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a count matrix from a sorted, tagged bam file Notes Input bam file must be sorted by query name. The sort order of the input BAM file is not strictly checked. If the input BAM file not sorted by query_name, the output counts will be wrong without any warnings being issued. This method returns counts that corre...
def from_sorted_tagged_bam( cls, bam_file: str, gene_name_to_index: Dict[str, int], chromosomes_gene_locations_extended: Dict[str, List[tuple]] = None, cell_barcode_tag: str = consts.CELL_BARCODE_TAG_KEY, molecule_barcode_tag: str = consts.MOLECULE_BARCODE_TAG_KEY, ...
[ "def convert_rnaseq(bam_file, output_directory, bgzip_path, tabix_path):\n # Assert that bgzip and tabix executables are both available\n if bgzip_path is None:\n raise FileNotFoundError('Path to a bgzip executable was not provided and could not be found in PATH')\n if tabix_path is None:\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the pymatgen EwaldSummation object.
def ewald_summation(self): ewald_summation = EwaldSummation( self._ewald_structure, real_space_cut=self._ewald_term.real_space_cut, recip_space_cut=self._ewald_term.recip_space_cut, eta=self._ewald_term.eta, ) return ewald_summation
[ "def ewald_matrix(self):\n matrix = self._ewald_term.get_ewald_matrix(self.ewald_summation)\n matrix = np.ascontiguousarray(matrix)\n return matrix", "def get_dw(model):\n\n resid = model.resid\n return dw(resid)", "def getRMSD(self):\n\n ensemble = self._ensemble\n indi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the electrostatic interaction matrix. The matrix used is the one set in the EwaldTerm of the given ClusterExpansion.
def ewald_matrix(self): matrix = self._ewald_term.get_ewald_matrix(self.ewald_summation) matrix = np.ascontiguousarray(matrix) return matrix
[ "def EC_matrix(self):\n Cmat = np.zeros((2, 2))\n CJ1 = 1. / (2 * self.ECJ1) # capacitances in units where e is set to 1\n CJ2 = 1. / (2 * self.ECJ2)\n CJ3 = 1. / (2 * self.ECJ3)\n Cg1 = 1. / (2 * self.ECg1)\n Cg2 = 1. / (2 * self.ECg2)\n\n Cmat[0, 0] = CJ1 + CJ3 + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute change in electrostatic energy from a set of flips.
def compute_property_change(self, occupancy, flips): return self.coefs * self.compute_feature_vector_change(occupancy, flips)
[ "def compute_feature_vector_change(self, occupancy, flips):\n occu_i = occupancy\n delta_energy = 0\n for f in flips:\n occu_f = occu_i.copy()\n occu_f[f[0]] = f[1]\n delta_energy += delta_ewald_single_flip(\n occu_f, occu_i, self.ewald_matrix, se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the feature vector for a given occupancy array. Each entry in the correlation vector corresponds to a particular symmetrically distinct bit ordering.
def compute_feature_vector(self, occupancy): ew_occu = self._ewald_term.get_ewald_occu( occupancy, self.ewald_matrix.shape[0], self._ewald_inds ) return np.sum(self.ewald_matrix[ew_occu, :][:, ew_occu])
[ "def features_as_vector(self):\r\n return self._features_as_vector_fcn()", "def compute_feature_vector_change(self, occupancy, flips):\n occu_i = occupancy\n delta_energy = 0\n for f in flips:\n occu_f = occu_i.copy()\n occu_f[f[0]] = f[1]\n delta_energ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the change in the feature vector from a list of flips.
def compute_feature_vector_change(self, occupancy, flips): occu_i = occupancy delta_energy = 0 for f in flips: occu_f = occu_i.copy() occu_f[f[0]] = f[1] delta_energy += delta_ewald_single_flip( occu_f, occu_i, self.ewald_matrix, self._ewald_in...
[ "def compute_property_change(self, occupancy, flips):\n return self.coefs * self.compute_feature_vector_change(occupancy, flips)", "def weight_dot_feature_vec(v,f):\n product = 0\n for x in f:\n product += v[x]\n return product", "def update(self, *args):\n return _vnl_vectorPython...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Links an Amenity object to a place according to their respective id
def link_an_amenity(place_id=None, amenity_id=None): if place_id is None or amenity_id is None: return abort(404) my_place = storage.get(Place, place_id) if my_place is None: return abort(404) my_amenity = storage.get(Amenity, amenity_id) if my_amenity is None: return abor...
[ "def link_amenity_to_place(place_id, amenity_id):\n place_obj = get_object(Place, place_id)\n amenity_obj = get_object(Amenity, amenity_id)\n if environ.get('HBNB_TYPE_STORAGE') != 'db':\n if amenity_id in place_obj.amenity_ids:\n return jsonify(amenity_obj.to_dict())\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a row to the download queue table
def add_row_download_queue_table(self, row_data): self.download_queue_progressbar_list.append(QtGui.QProgressBar()) self.download_queue_table_row_count = \ self.ui_single_file_download.shard_queue_table.rowCount() self.ui_single_file_download.shard_queue_table.setRowCount( ...
[ "def addRow( self, data ):\n self.tableData.append( data )", "def add_row(self, row):\n self.results_table_rows.append(row)", "def _additem(self):\n\n self.queue.put(self._genitem())", "def addRow(self, row_info):\n pass", "def add_database_entry(self, row):\n database = self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return random a, b and empty c with the same shape.
def get_abc(shape, constructor=None): np.random.seed(0) a = np.random.normal(size=shape).astype(np.float32) b = np.random.normal(size=shape).astype(np.float32) c = np.empty_like(a) if constructor: a, b, c = [constructor(x) for x in (a, b, c)] return a, b, c
[ "def unison_shuffled_copies(a, b, c):\n\n assert len(a) == len(b) == len(c)\n p = np.random.permutation(len(a))\n return a[p], b[p], c[p]", "def randomize_empty_blocks(empty):\n ret = []\n for x, y in empty:\n if random() < 0.5:\n ret.append((l, x, y + 1))\n ret.append(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Broadcast add between two 2dimensional tensors
def broadcast_add(shape1, shape2): assert len(shape1) == 2 and len(shape2) == 2, \ "broadcast tensors should both be 2-dimension" for i in range(len(shape1)): assert shape1[i] == shape2[i] or shape1[i] == 1 or shape2[i] == 1, \ "tensor shapes do not fit for broadcasting" A = te.p...
[ "def layer_op(self, tensor_a, tensor_b):\n crop_border = (tensor_a.shape[1] - tensor_b.shape[1]) // 2\n tensor_a = Crop(border=crop_border)(tensor_a)\n output_spatial_shape = tensor_b.shape[1:-1]\n tensor_a = Resize(new_size=output_spatial_shape)(tensor_a)\n return ElementWise('CO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return random tensors a, b and empty tensor c to store broadcast results between a and b
def get_bcast_data(shape1, shape2, constructor=None): np.random.seed(0) a = np.random.normal(size=shape1).astype("float32") b = np.random.normal(size=shape2).astype("float32") out_shape = (shape1[0] if shape2[0] == 1 else shape2[0], shape1[1] if shape2[1] == 1 else shape2[1]) c = np...
[ "def unison_shuffled_copies(a, b, c):\n\n assert len(a) == len(b) == len(c)\n p = np.random.permutation(len(a))\n return a[p], b[p], c[p]", "def generate_random_inputs(a, b):\r\n random_array = np.random.rand(a, b)\r\n return random_array", "def _broadcast(a, b, array1, array2):\n # Equivalent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the output size by given input size n (width or height), kernel size k, padding p, and stride s Return output size (width or height)
def conv_out_size(n, k, p, s): return (n - k + 2 * p)//s + 1
[ "def maxpool2d_out_dim(in_dim, kernel_size, padding=1, stride=1, dilation=1):\n out_dim = ((in_dim + 2*padding - dilation*(kernel_size-1) - 1)/stride) + 1\n return out_dim\n\n #TODO make a util function to calculate the output size of a layer given a input dim\n #ie get the input size of a linear layer ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the floating point operations in a convolution. The arguments are output channels oc, input channels ic, input size n, kernel size k, padding p and stride s.
def conv_gflop(oc, ic, n, k, p, s): on = d2ltvm.conv_out_size(n, k, p, s) return 2 * oc * ic * on * on * k * k / 1e9
[ "def conv_internal(conv_fn, inputs, filters, kernel_size, **kwargs):\n static_shape = inputs.get_shape()\n if not static_shape or len(static_shape) != 4:\n raise ValueError(\"Inputs to conv must have statically known rank 4.\")\n # Add support for left padding.\n if \"padding\" in kwargs and kwar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Benchmark pooling in TVM
def bench_pooling_tvm(func, sizes, target): def workload(nrepeats): timer = mod.time_evaluator(mod.entry_name, ctx=ctx, number=nrepeats) return timer(data, out_max).mean * nrepeats times = [] for size in sizes: sch, args = func(size) mod = tvm.build(sch, args, target) ...
[ "def bench_pooling_mxnet(pool_type, sizes, ctx='cpu'):\n return [d2ltvm.bench_workload(pooling_timer_mxnet(pool_type, c, n, k, ctx))\n for c, n, k in sizes]", "def test_staking_pool_get(self):\n pass", "def training_pool(self):", "def stress_test_mp():\n stress_test(processes=4, thread...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the execution times of MXNet pooling
def bench_pooling_mxnet(pool_type, sizes, ctx='cpu'): return [d2ltvm.bench_workload(pooling_timer_mxnet(pool_type, c, n, k, ctx)) for c, n, k in sizes]
[ "def get_timing(pool):\n sim.send_data(pool)\n\n start_raw = time.time()\n pool.imap(sim.get_forces_raw, range(sim.PARTICLE_COUNT))\n sim.get_results(pool)\n end_raw = time.time()\n\n start_tree = time.time()\n pool.imap(sim.get_forces_tree, range(sim.PARTICLE_COUNT))\n sim.get_results(pool)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The matrix multiplication timer for MXNet
def matmul_timer_mxnet(n, ctx): timer = timeit.Timer( setup='import d2ltvm\n' 'import mxnet as mx\n' 'a, b, c, = d2ltvm.get_abc((%d, %d), lambda x: mx.nd.array(x, ctx=mx.%s()))\n' 'mx.nd.waitall()' % (n, n, ctx), stmt='mx.nd.dot(a, b, out=c); c.wait_to_read()') return tim...
[ "def mul(self, matrix):", "def _matinterface(N0, Nl, t0):\n \n rp, rs, tp, ts = fresnel2(t0, N0, Nl)\n m1p = 1./tp\n m1s = 1./ts\n m2p = rp/tp\n m2s = rs/ts\n mp = (m1p, m2p, m2p, m1p)\n ms = (m1s, m2s, m2s, m1s)\n return mp, ms", "def element_mul(self, matrix):", "def runSequential...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Splitting an axis into factors
def split_axis(factors, sch, op, axis): ret = [] for i in range(0, len(factors)): ax0, ax1 = sch[op].split(axis, factor=int(np.prod(factors[i:]))) ret.append(ax0) axis = ax1 return ret + [axis]
[ "def scale_axis(axis_data, factor):\n scaled_axis = str(float(axis_data)*factor)\n return scaled_axis", "def _assign_axes(self, xarr):\n axes = ['']*len(xarr.dims)\n\n for axis in xarr.dims:\n axis_str = self._pydim_to_ijdim(axis)\n\n ax_type = Axes.get(ax...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert the users JWT has the required role(s). Assumes the JWT is already validated.
def has_roles(jwt: JwtManager, roles: List[str]) -> bool: if jwt.validate_roles(roles): return True return False
[ "def are_roles_sufficient(token, required_roles):\n\n if token is None:\n return False\n\n token = token.split(\" \")[1]\n\n if token == TEST_BEARER_TOKEN:\n if _is_test_bearer_enabled():\n return True\n else:\n return False\n\n if required_roles is None or len...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get allowed type of filing types for the current user.
def get_allowed(state: Business.State, legal_type: str, jwt: JwtManager): user_role = 'user' if jwt.contains_role([STAFF_ROLE, SYSTEM_ROLE, COLIN_SVC_ROLE]): user_role = 'staff' allowable_filings = ALLOWABLE_FILINGS.get(user_role, {}).get(state, {}) allowable_filing_types = [] for allowabl...
[ "def get_queryset(self):\n user_id = self.kwargs['user_id']\n get_object_or_404(User, pk=user_id)\n return RiskType.objects.filter(user_id=user_id)", "def allowed_types(self):\n ret = self._get_attr(\"allowedTypes\")\n return [MediumType(a) for a in ret]", "def typeduser(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Entrena los modelos de arima para temperatura y humedad en este caso no es necesario entrenar el modelo de nuevo si este ha sido creado con anterioridad
def train_arima(self): df = self.get_data() #Creo el directorio temporal si no existe if not os.path.exists('./modelos'): os.mkdir('./modelos') #Si el modelo de humedad no ha sido creado anteriormente se crea y se almacena if not os.path.exists('./modelos/Arima_humidity.pckl'): model = pm.auto_arim...
[ "def modelisation(vitesse_limite = 110, nb_voies = 3, scenario = 0, pas = 0.5, nb_vehicules_voulu = 20, debit = 0.5):\r\n #Initialisation\r\n \r\n #On cree les voies\r\n (liste_voie, sortie) = cvoie.creer_voies(nb_voies, vitesse_limite)\r\n \r\n #Initialisation de la liste de tous les vehicules cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }