query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Return RMSLE from the prediction and the expected answer. | def get_RMSLE(pred, truth):
assert len(pred) == len(truth)
diff_vect = np.log(pred + 1) - np.log(truth + 1)
diff_sum = np.sum(np.power(diff_vect, 2))
return np.sqrt(diff_sum / len(pred)) | [
"def calc_rmsle(y: np.ndarray, y_hat: np.ndarray) -> float:\n pass",
"def reserrorcalc(test_set, model):\n # Extracting X\n X = test_set[:,:-1]\n\n # Extracting labels\n Y = test_set[:,-1]\n residual_err = sum((model.predict(X) - Y) ** 2)\n return residual_err",
"def RMSE(prediction, actual):\n #sub... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract diagonal of ``(Jᵀ S) (Jᵀ S)ᵀ`` where ``J`` is the bias Jacobian. | def extract_bias_diagonal(module: Linear, S: Tensor, sum_batch: bool = True) -> Tensor:
additional_axes = list(range(2, module.input0.dim()))
if additional_axes:
JS = S.sum(additional_axes)
else:
JS = S
equation = f"vno->{'' if sum_batch else 'n'}o"
return einsum(equation, JS**2) | [
"def extract_diagonal(self, matrix: Array) -> Tuple[Array, List[Error]]:\n diagonal = matrix[:, :self.J].diagonal()\n return diagonal, []",
"def diag(B,s,H,ia,ib,ic,chia,chic):\n # Get a guess for the ground state based on the old MPS\n d = B[0].shape[0]\n theta0 = np.tensordot(np.diag(s[ia... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the path of the Bohrium systemwide configuration file | def config_file(self):
return join_path(self.prefix.etc.bohrium, "config.ini") | [
"def getConfigPath():\n if sys.platform == 'linux':\n configpath = os.path.normpath(os.path.expanduser('~/.config/phobos'))\n elif sys.platform == 'darwin':\n configpath = os.path.normpath(os.path.expanduser('~/Library/Application Support/phobos'))\n elif sys.platform == 'win32':\n con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a list of ranks that get harder to obtain as they approach the maximum | def generate_ranks(maximum: int, steps: int) -> List[int]:
ranks = []
for i in range(steps):
ranks += [maximum]
maximum = int(maximum * 0.75)
RANK_CUTOFFS = list(reversed(ranks))
return RANK_CUTOFFS | [
"def get_rankings(elos):\n #get expected scores (or probabilities)\n expected_scores = get_win_prob(elos)\n\n rankings = [] #will have rankings in order (1st, 2nd, ...)\n for i in range(len(elos)): #determine 1st, then 2nd, etc. in order\n total_weight = 1\n for player_index in rankings: \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the rank for a given number of points | def get_rank(points: int, cutoffs: List[int]) -> int:
rank = 0
for i, cutoff in enumerate(cutoffs):
if points < cutoff:
if i == 0:
break
else:
rank = i - 1
break
else:
rank = RANK_COUNT - 1
return rank | [
"def calculate_league_points(rank: int):\n points_dict = {\n 1: 10,\n 2: 7,\n 3: 5,\n 4: 3,\n 5: 1\n }\n if rank > 5:\n return 0\n else:\n return points_dict[rank]",
"def _get_rank(self,fitness):\n # infact you can get the order or rank by only o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
moves the target further out as a % of the screen | def move_target(self, distance_adjustment):
self.x = float(self.screen_rect.right - self.width)
self.x = self.x * distance_adjustment
self.rect.x = self.x | [
"def assign_upLimit():\r\n player.rect.y = 25",
"def move_target(self):\n\n global N\n\n if self.target[0] < 0.1 or self.target[0] > 1.1:\n N *= -1\n\n self.target[0] += N * 0.002\n self.target[1] += N * 0.002",
"def assign_downLimit():\r\n player.rect.y = 100",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks top to target to see if it hit top of screen | def check_top(self):
if self.rect.top <=0:
self.target_direction = 1 | [
"def _check_autos_top(self):\n\t\tscreen_rect = self.screen.get_rect()\n\t\tfor auto in self.autos.sprites():\n\t\t\tif auto.rect.top <= screen_rect.top:\n\t\t\t\t# Treat this the same as if the pigeon got hit.\n\t\t\t\tself._pigeon_hit()\n\t\t\t\tbreak",
"def is_on_top(self):\n return self.own_order == se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup strategies to use by the validator. These strategies can be provided | def _using(*args, validator: "DictValidator") -> "DictValidator":
def setup_strategy(validator, strategy) -> "DictValidator":
if isinstance(strategy, SortingStrategy):
validator.sorting = strategy
elif isinstance(strategy, FilteringStrategy):
validator.filtering = strategy
... | [
"def initialize_location_strategies(self):\n locator_manager.register_locators(\"sf\", lex_locators)\n locator_manager.register_locators(\"text\", \"Salesforce.Locate Element by Text\")\n locator_manager.register_locators(\"title\", \"Salesforce.Locate Element by Title\")\n\n # This does... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is an ADMM solver for the (Latent variable) Single Graphical Lasso problem (SGL). If ``latent=False``, this function solves | def ADMM_SGL(S, lambda1, Omega_0, Theta_0=np.array([]), X_0=np.array([]),
rho=1., max_iter=1000, tol=1e-7, rtol=1e-4, stopping_criterion='boyd',\
update_rho=True, verbose=False, measure=False, latent=False, mu1=None):
assert Omega_0.shape == S.shape
assert S.shape[0] == S.shape[1]
... | [
"def solve(self, Omega_0 = None, solver_params = dict(), tol = 1e-8, rtol = 1e-7, solver = 'admm', verbose = False):\n \n assert solver in [\"admm\"], \"Currently only the ADMM solver is supported as it is implemented for all cases.\"\n assert self.reg_params.get('lambda1') is not None, \"Regul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a wrapper for solving SGL problems on connected components of the solution and solving each block separately. See Witten, Friedman, Simon "New Insights for the Graphical Lasso" for details. It solves | def block_SGL(S, lambda1, Omega_0, Theta_0=None, X_0=None, rho=1., max_iter=1000,
tol=1e-7, rtol=1e-3, stopping_criterion="boyd",
update_rho=True, verbose=False, measure=False):
assert Omega_0.shape == S.shape
assert S.shape[0] == S.shape[1]
assert lambda1 > 0
(p, p) = S.sh... | [
"def solver_one(state):\n\n # Obtain the different state elements\n glb_idx, p_sets, hh, datasets, mappings = get_case_study_registry_objects(state)\n\n # Obtain parameters and their variation ranges (initially decoupled)\n params_list = get_parameters(state)\n\n # Map params to the objects where the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The argument p is assumed to be some permutation of 0, 1, ..., len(p)1. Returns an array s, where s[i] gives the index of i in p. | def invert_permutation(p):
s = np.empty_like(p)
s[p] = np.arange(p.size)
return s | [
"def invert_permutation(p):\n s = np.empty(p.size, p.dtype)\n s[p] = np.arange(p.size)\n return s",
"def _generate_pair_positions(self, s, p):\n r = np.random.choice(s + p, s, replace=False)\n paired = []\n unpaired = []\n i = 0\n for j in range(s + p):\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a HOOMD device given the parse arguments. | def make_hoomd_device(args):
if args.device == 'CPU':
device = hoomd.device.CPU()
elif args.device == 'GPU':
device = hoomd.device.GPU()
else:
raise ValueError(f'Invalid device {args.device}.')
if not args.verbose:
device.notice_level = 0
return device | [
"def initialize(self):\n self.ha_url = self.args.get(\"ha_url\", None)\n self.use_current_brightness = self.args.get(\"use_current_brightness\", False)\n self.condition = self.args.get(\"condition\")\n self.lights = self.args[\"lights\"]\n self.listen_state(self.change_lights_color, self.args[\"media... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute the benchmark and report the performance. | def execute(self):
print_verbose_messages = (self.verbose
and self.device.communicator.rank == 0)
# Ensure that all ops are attached (needed for is_tuning_complete).
self.run(0)
if print_verbose_messages:
print(f'Running {type(self).__name_... | [
"def run_benchmark(self):\n return 0",
"def execute_benchmark(self, benchmark_file):\n benchmark = Benchmark(benchmark_file, self.config,\n self.config.start_time or time.localtime())\n self.check_existing_results(benchmark)\n\n self.executor.init(self.conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make an ArgumentParser instance for benchmark options. | def make_argument_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--device',
type=str,
choices=['CPU', 'GPU'],
help='Execution device.',
required=True)
parser.add_arg... | [
"def make_argument_parser():\n parser = Benchmark.make_argument_parser()\n parser.add_argument('--skip-reference',\n action='store_true',\n help='Skip the reference simulation run.')\n return parser",
"def create_parser():\n parser = ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make an ArgumentParser instance for comparative benchmark options. | def make_argument_parser():
parser = Benchmark.make_argument_parser()
parser.add_argument('--skip-reference',
action='store_true',
help='Skip the reference simulation run.')
return parser | [
"def make_argument_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--device',\n type=str,\n choices=['CPU', 'GPU'],\n help='Execution device.',\n required=True)\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies default secthresh & exclusion radius constraints | def apply_default_constraints(self):
try:
self.apply_secthresh(pipeline_weaksec(self.koi))
except NoWeakSecondaryError:
logging.warning('No secondary eclipse threshold set for {}'.format(self.koi))
self.set_maxrad(default_r_exclusion(self.koi)) | [
"def apply_constraints(self):\n pass",
"def constraints(self):",
"def applyConstraints(self):\n pass",
"def _setSimplexWithinRangeBoundary(self, radius=None):\n x0 = self.population[0]\n #code modified from park-1.2/park/simplex.py (version 1257)\n if self._useStrictRange:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if provenance of property is SPE or AST | def use_property(kepid, prop):
try:
prov = kicu.DATA.ix[kepid, '{}_prov'.format(prop)]
return any([prov.startswith(s) for s in ['SPE', 'AST']])
except KeyError:
raise MissingStellarError('{} not in stellar table?'.format(kepid)) | [
"def isprop(v):\n return isinstance(v, property)",
"def isProp(node):\r\n #TODO: efficiency\r\n return isinstance(node,PropNode)",
"def _is_property(cls, member):\n return isinstance(member, property)",
"def hasProperty(self, p_str): # real signature unknown; restored from __doc__\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns star config object for given KOI | def star_config(koi, bands=['g','r','i','z','J','H','K'],
unc=dict(g=0.05, r=0.05, i=0.05, z=0.05,
J=0.02, H=0.02, K=0.02), **kwargs):
folder = os.path.join(KOI_FPPDIR, ku.koiname(koi))
if not os.path.exists(folder):
os.makedirs(folder)
config = ConfigObj(os... | [
"def get_config():\n return ImSimConfiguration()",
"def fpp_config(koi, **kwargs):\n folder = os.path.join(KOI_FPPDIR, ku.koiname(koi))\n if not os.path.exists(folder):\n os.makedirs(folder)\n config = ConfigObj(os.path.join(folder,'fpp.ini'))\n\n koi = ku.koiname(koi)\n\n rowefit = jrowe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns config object for given KOI | def fpp_config(koi, **kwargs):
folder = os.path.join(KOI_FPPDIR, ku.koiname(koi))
if not os.path.exists(folder):
os.makedirs(folder)
config = ConfigObj(os.path.join(folder,'fpp.ini'))
koi = ku.koiname(koi)
rowefit = jrowe_fit(koi)
config['name'] = koi
ra,dec = ku.radec(koi)
co... | [
"def get_config():\n return ImSimConfiguration()",
"def config(self):\n annotations = IAnnotations(self.context)\n return annotations.get(CONFIGURATION_KEY, {})",
"def get_epix10ka_config_object(env, src):\n cfg = env.configStore()\n o = cfg.get(_psana.Epix.Config10kaV2, src)\n if o is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predict a single batch of images, optionally with augmentation. Augmentations vectorized across the entire batch and predictions averaged. | def predict_batch(self, imgs_batch, augment=False):
if augment:
aug_funcs = [
lambda x: x, # identity
lambda x: x[:, ::-1, ...], # vlip
lambda x: x[:, :, ::-1], ... | [
"def warmup_predict(model, imgs, Npred):\n H = augmented_state_matrix(model[:-1], imgs, 0)\n h0 = H[-2]\n y0 = imgs[-1]\n return predict(model, y0, h0, Npred)",
"def batched_predict(model, batcher, batch_size, int_mapped_X, doc_labels):\n # Intialize batcher but dont shuffle.\n train_batcher = b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unstack batch dimension and split into channels and alpha mask. | def unstack_and_split(self, x, batch_size, num_channels=3):
unstacked = torch.reshape(x, [batch_size, -1] + list(x.shape)[1:])
channels, masks = torch.split(unstacked, [num_channels, 1], dim=2)
return channels, masks | [
"def make_grid(batch_img: torch.Tensor,\n batch_mask: torch.Tensor,\n img_denormalize_fn: Callable,\n mask_palette: Optional[Sequence] = default_palette,\n batch_gt_mask: Optional[torch.Tensor] = None):\n assert isinstance(batch_img, torch.Tensor) and isinstanc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Animals that can speak are correctly identified | def test_animals_can_speak(self):
self.assertEqual(self.lion, 'roar')
self.assertEqual(self.cat, 'meow') | [
"def print_humans_and_animals():",
"def print_animal_info(self):",
"def test_animals_can_speak(self):\r\n lion = Animal.objects.get(name=\"lion\")\r\n cat = Animal.objects.get(name=\"cat\")\r\n self.assertEqual(lion.speak(), 'The lion says \"roar\"')\r\n self.assertEqual(cat.speak(),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a urlsafe version of an Album key, get the actual key | def get_album_key_by_keystr(keystr):
attr_err = 'Keystrings must be an instance of base string, recieved: %s' % keystr
kind_err = 'Expected urlsafe keystr for kind %s but received keystr for kind %s instead.'
if not keystr or not isinstance(keystr, basestring):
raise RuntimeError(attr_err)
key ... | [
"def get_album_key(slug):\n err = 'Series slug must be defined and of of type basestring'\n\n if not slug or not isinstance(slug, basestring):\n raise RuntimeError(err)\n\n return ndb.Key(PHOTOALBUM_KIND, slug)",
"def get_key(url):\n digest = hashlib.md5(url.encode()).hexdigest()\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a ndb.Key given an Album slug | def get_album_key(slug):
err = 'Series slug must be defined and of of type basestring'
if not slug or not isinstance(slug, basestring):
raise RuntimeError(err)
return ndb.Key(PHOTOALBUM_KIND, slug) | [
"def build_key(cls, song_id):\n return ndb.Key(cls, song_id)",
"def get_album_key_by_keystr(keystr):\n attr_err = 'Keystrings must be an instance of base string, recieved: %s' % keystr\n kind_err = 'Expected urlsafe keystr for kind %s but received keystr for kind %s instead.'\n if not keystr or no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an album slug, fetch the album entity | def get_album_by_slug(slug):
album_key = get_album_key(slug)
album = album_key.get()
return album | [
"def get_album(album_id):\n return query_single(album_id, Album, album_schema)",
"def get_album(self):\n return self._album",
"def from_id(album_id):\n endpoint = album_endpoint + '/' + album_id\n response = api_call(endpoint)\n\n if response is None:\n return None\n \n parsed = js... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch a list of Albums | def get_album_list():
# TODO: Paginate this, etc
entities = PhotoAlbum.query().order(-PhotoAlbum.title).fetch(1000)
return entities | [
"def get_albums():\n return query_multiple(request.args, album_search, \\\n album_filter, Album, albums_schema)",
"def albums(self, albums, **kwargs):\n album_list = map(self._get_album_id, albums)\n return self._get(API.ALBUMS.value, ids=\",\".join(album_list), **kwargs)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempts a Redis DB connection and returns the DB Object | def dbConnect(self):
r = redis.StrictRedis()
try:
r = redis.from_url(os.environ.get("REDIS_URL"))
print("DB Connection seems okay!")
except Exception as error:
print ("Oops! An exception has occured:", error)
print ("Exception TYPE:", type(error))
... | [
"def establish_connection(self) -> Redis:\n try:\n conn = self.connection()\n conn.ping()\n except ConnectionError:\n log.error(\"Connection to DB could not be established\")\n return False\n return conn",
"def get_database_connection() -> redis.Red... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts short URL to an ID | def shortURLToId(self, shortURL):
id = 0
for i in shortURL:
val_i = ord(i)
if(val_i >= ord('a') and val_i <= ord('z')):
id = id*62 + val_i - ord('a')
elif(val_i >= ord('A') and val_i <= ord('Z')):
id = id*62 + val_i - ord('Z') + 26... | [
"def short_url(lastid):\n number = lastid +100000000000\n bs62encoded = base62.encode(number)\n return 'https://abc.com/{id}'.format(id=str(bs62encoded))",
"def get_id_shortlink(link = None):\n choppedLink = legacy_check(link)\n id = None\n try:\n id = choppedLink[3] # or -1 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
probably the wrost way to parse this captcha | def get_captcha_reply(captcha):
def get_char_at(pos, captcha):
char_chars = [line[pos-1:pos] for line in captcha.split(b'\n')]
key = ''.join([ str(s, 'ascii') for s in char_chars])
if key == ' | ':
return get_char_at(pos+2, captcha)
if key == ' | .\\ ':
... | [
"def baixa_captcha(self):\n url = \"https://www.receita.fazenda.gov.br/PessoaJuridica/CNPJ/cnpjreva/captcha/gerarCaptcha.asp\"\n pagina = self.sessao.get(url)\n open('teste.png','wb').write(pagina)\n imagem_data = (ndimage.imread('teste.png'))\n# plt.imshow(imagem_data)\n# ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The Amazon Resource Name (ARN) of the custom platform to use with the environment. | def platform_arn(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "platform_arn") | [
"def platform_arn(self) -> Optional[str]:\n return pulumi.get(self, \"platform_arn\")",
"def platform_arn(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"platform_arn\")",
"def PLATFORM_NAME(self) -> str:",
"def get_platform_name(cls):\n platform_info = Utility.get_plat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The name of an Elastic Beanstalk solution stack (platform version) to use with the environment. | def solution_stack_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "solution_stack_name") | [
"def solution_stack_name(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"solution_stack_name\")",
"def stack_name(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"stack_name\")",
"def stack_name(self) -> str:\n return jsii.get(self, \"stackName\")",
"def env_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specifies the tier to use in creating this environment. The environment tier that you choose determines whether Elastic Beanstalk provisions resources to support a web application that handles HTTP(S) requests or a web application that handles backgroundprocessing tasks. | def tier(self) -> Optional[pulumi.Input['EnvironmentTierArgs']]:
return pulumi.get(self, "tier") | [
"def tier(self) -> Optional['outputs.EnvironmentTier']:\n return pulumi.get(self, \"tier\")",
"def set_tier(self, tier):\n self.single_selection_from_static_kendo_dropdown(self.tier_kendo_dropdown_locator, tier)",
"def tier(self) -> Optional[pulumi.Input['InstanceTier']]:\n return pulumi.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an existing Environment resource's state with the given name, id, and optional extra properties used to qualify the lookup. | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'Environment':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = EnvironmentArgs.__new__(EnvironmentArgs)
__props__.__dict__["applicat... | [
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'Environment':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = EnvironmentArgs.__new__(EnvironmentArgs)\n\n __props__.__dict... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The Amazon Resource Name (ARN) of the custom platform to use with the environment. | def platform_arn(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "platform_arn") | [
"def platform_arn(self) -> Optional[str]:\n return pulumi.get(self, \"platform_arn\")",
"def platform_arn(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"platform_arn\")",
"def PLATFORM_NAME(self) -> str:",
"def get_platform_name(cls):\n platform_info = Utility.get_platf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The name of an Elastic Beanstalk solution stack (platform version) to use with the environment. | def solution_stack_name(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "solution_stack_name") | [
"def solution_stack_name(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"solution_stack_name\")",
"def stack_name(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"stack_name\")",
"def stack_name(self) -> str:\n return jsii.get(self, \"stackName\")",
"def env_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get global ip address | def get_global_ip():
network_info_providers = [
'http://api.ipify.org/',
'http://myip.dnsomatic.com',
'http://inet-ip.info/ip',
'http://v4.ident.me/',
]
random.shuffle(network_info_providers)
for url in network_info_providers:
try:
return requests.get(... | [
"def get_global_ip() -> str:\n return urllib.request.urlopen(\"https://icanhazip.com\").read().decode().strip()",
"def get_ip():\n return '219.45.143.143'",
"def get_local_host_ip(self) -> str:",
"def _get_local_ip():\n return netutils.get_my_ipv4()",
"def get_IP(): \n \n return socket.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get global ipv6 address | def get_global_ip_ipv6():
network_info_providers = [
'http://v6.ipv6-test.com/api/myip.php',
'http://v6.ident.me/',
]
random.shuffle(network_info_providers)
for url in network_info_providers:
try:
return requests.get(url).text.lstrip().rstrip()
except Exceptio... | [
"def get_main_ipv6():\n try:\n # No data is actually transmitted (UDP)\n s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n s.connect( ('2001:4860:4860::8888', 53) )\n real_ip = s.getsockname()[0]\n s.close()\n return real_ip\n except socket.error as e:\n logging.error(\"Cannot retrieve ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementation of binary operator between DataFrames on different indices. A new DataFrame representing an inmemory DolphinDB table is returned. It is garenteed that both DataFrames have no where_expr. | def _binary_op_on_different_indices(self, other, func, axis): # TODO: add axis check
def merge_columns(self_columns, other_columns):
"""
Align the input columns, filling the missing columns with None
--------
Examples
--------
... | [
"def _compare(query, targets, on_cols, func, suffix):\n on_index = targets.index\n table = pd.DataFrame(index=on_index)\n\n if on_cols is None:\n return table\n\n compared_cols = on_cols.copy()\n if type(compared_cols) == str:\n compared_cols = [compared_cols]\n assert isinstance(com... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open a window to compose an email, with the edi invoice dian template message loaded by default | def action_invoice_dian_resend(self):
self.ensure_one()
template = self.env.ref('l10n_co_e-invoice.email_template_edi_invoice_dian', False)
compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)
ctx = dict(
default_model='account.invoice',
de... | [
"def action_invoice_sent(self):\n self.ensure_one()\n template = self.env.ref('account.email_template_edi_invoice', False)\n compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)\n att = self._create_attachment()\n atts = []\n if template.attachment_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get preditors base on their distance The predictors are selected as following [1,2], [1,3], [1,4], [2,3], [2,4], [2,5], [2,6] | def getpredictors_distance( staname, distance):
distfromsta = distance[staname]
try:
del distfromsta[staname] # remove the station to be fill from the dataframe
except:
pass
distfromsta = distfromsta.sort_values()
stations = distfromsta.index
sel1 = [(i, e) for i, e in zip(st... | [
"def __getpredictors_distance(self, staname, distance):\n\n distfromsta = distance[staname]\n del distfromsta[staname] # remove the station to be fill from the dataframe\n distfromsta = distfromsta.sort_values()\n\n stations = self.network.getsta(distfromsta.index.values)\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DESCRIPTION Check every variable of every stations and try to fill them with the variables of the two nearest station for every time. INPUT | def fillstation(self, stanames, all=None, plot=None, summary=None, From=None, To=None, by=None,
how='mean', variables=None, distance=None, sort_cor=True, constant=True, cor_lim=None):
if all == True:
stations = self.network.getsta([], all=True).values()
else:
... | [
"def multilaterate(stations:list):\n assert len(stations) >= 3, 'I need >= 3 stations!'\n stations = np.array(stations)\n stations = stations[stations[:,1].argsort()]\n # We use the fixing with the shortest distance as initial guess\n x0 = stations[1,0].coordinates()\n # Simple OLS error function\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get preditors base on their distance The predictors are selected as following [1,2], [1,3], [1,4], [2,3], [2,4], [2,5], [2,6] | def __getpredictors_distance(self, staname, distance):
distfromsta = distance[staname]
del distfromsta[staname] # remove the station to be fill from the dataframe
distfromsta = distfromsta.sort_values()
stations = self.network.getsta(distfromsta.index.values)
# station... | [
"def getpredictors_distance( staname, distance):\n\n distfromsta = distance[staname]\n try:\n del distfromsta[staname] # remove the station to be fill from the dataframe\n except:\n pass\n distfromsta = distfromsta.sort_values()\n\n stations = distfromsta.index\n\n sel1 = [(i, e) fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a sorted selections by the correlation rsquared scores | def __sort_predictors_by_corr(self, station, selections, var, From, To, by, how, constant=True,
selectionsnames=None, sort_cor=True, cor_lim=None):
scores_corel = pd.DataFrame(index=np.arange(0, len(selections)), columns=['corel', 'selections', 'params',
... | [
"def corr_list(self):\n c = self.df.corr().abs()\n s = c.unstack()\n so = s.sort_values(ascending=False)\n i = int(len(so) ** (1/2))\n charts = so[i:]\n charts = charts[::2]\n if len(charts) > 3:\n charts = charts[:3]\n return charts.index, charts.v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a remote file of a bucket using a connection | def _get(conn, remote_file, bucket_name=BUCKET_NAME):
contents = None
try:
reply = conn.get(bucket_name, remote_file)
contents = reply.body
if reply.http_response.status != 200:
print 'Failed to fetch current_remote metadata'
contents = None
except:
co... | [
"def get(\n self, writer: protocols.ByteWriter, bucket_name: str = None, key_name: str = None\n ) -> None:\n s3_bucket, s3_key = self._fetch_bucket_and_key(bucket_name, key_name)\n\n if not self._isfile(s3_bucket, s3_key):\n raise exceptions.S3Error(\"Unable to fetch the remote fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Put some contents into a remote_file of a bucket usign connection conn. Optionally the headers can be specified. | def _put(conn, remote_file, contents, bucket_name=BUCKET_NAME, headers=None):
error_msg = 'Failed to upload to %s' % remote_file
try:
reply = conn.put(bucket_name, remote_file,
S3.S3Object(contents), headers)
if reply.http_response.status != 200:
print error_... | [
"def put_file(self, host, local_file, remote_file):\n LOG.info(\"Transferring local file %s to %s on host %s\", local_file, remote_file, host)\n return execute(self._transfer_file, put, local_file, remote_file, host=host)",
"def upload_file(conn, filename_local, filename_s3, gzip=False):\n\n file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Guess the content_type, by using its file descriptor | def _get_content_type(file_descriptor):
content_type = mimetypes.guess_type(file_descriptor.name)[0]
if not content_type:
content_type = 'text/plain'
return content_type | [
"def get_content_type(filename):\n return mimetypes.guess_type(filename)[0] or 'application/octet-stream'",
"def guess_content_type ( self, path_info ) :\n _type, _enc = guess_type ( path_info )\n return _type",
"def _get_content_type(url):\r\n scheme, netloc, path, query, fragment = url... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asserts if a given file (w/ name filename) can be compressed. content_type is optional and can speed up assertion. Should return True if it is a Text Type (CSS/JS) | def _file_can_be_compressed(filename):
content_type = ''
with open(filename, 'rb') as f:
content_type = _get_content_type(f)
return content_type in TEXT_TYPES | [
"def check_gzip_path(file_path):\n _, ftype = mimetypes.guess_type(file_path)\n return ftype == 'gzip'",
"def check_compressed_file(filename):\n\n recognized_exts = COMPRESSED_TYPES\n \n # Check the two last extensions\n # (to recognize also composed extensions such as tar.gz)\n filename_noex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compress the content string passed. Should be called when gzip is enabled to compress text types. There is no real advantage in using this with images, since most are already nicely compressed by some image processing algorithm. | def _compress_string(content):
zbuf = StringIO()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
zfile.write(content)
zfile.close()
return zbuf.getvalue() | [
"def compress(content):\n if isinstance(content, str):\n content = content.encode('utf-8')\n else:\n content = json.dumps(content , separators=(',', ':')).encode('utf-8')\n return gzip.compress(content, compresslevel=9)",
"def compress_string(string):\n return encoding.encode(compres... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build the metadata local file with all sha information about files. File location is computed based on home kwargument. | def _build_local_metadata_file(files, home=''):
filepaths = [os.path.join(home, f) for f in files]
shas = [_get_sha_metadata(f) for f in filepaths]
metadata = dict(zip(files, shas))
with open(LOCAL_METADATA_FILE, 'w') as f:
f.write(json.dumps(metadata)) | [
"def generate_metadata(self):\n self.metadata = {\n 'title': os.path.basename(self.source_file).rsplit('.', 1)[0],\n 'url': self.relative_destination_file,\n 'full_path': os.path.dirname(self.relative_destination_file),\n 'short_path': self.shorten_path(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads a file to S3 bucket. If gzip=True, compress and upload the gzipped version of the file instead of the original one. If gzip=True and it is not possible to compress, then quit the upload process (don't upload at all). So you should always pass the correct gzip info into this function, in order to get a upload. | def upload_file(conn, filename_local, filename_s3, gzip=False):
filename_s3 = filename_s3.lstrip('./')
file_descriptor = open(filename_local, 'rb')
content = file_descriptor.read()
content_type = _get_content_type(file_descriptor)
headers = _get_headers(content_type)
#should compress if the ... | [
"def s3_upload(upload_file=\"test\", args):\n REGION = args['REGION']\n BUCKET = args['BUCKET']\n ACCESS_KEY = base64.b64decode(args['ACCESS_KEY'])\n SECRET_KEY = base64.b64decode(args['SECRET_KEY'])\n TAR_FILE = args['TAR_FILE']\n\n session = Session(aws_access_key_id=ACCESS_KEY,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a recursive list of all files inside folder. The list element is a string w/ file path relative to folder. If any file is found with the same name as LOCAL_METADATA_FILE, then do not append it to the list. | def _get_file_list(folder):
tree = [x for x in os.walk(folder)]
files = [os.path.join(t[0], y) for t in tree for y in t[2]]
return [os.path.relpath(x, start=folder)
for x in files if x != LOCAL_METADATA_FILE] | [
"def _get_files(self, folder):\n folders = os.listdir(folder)\n return [\n f for f in folders if os.path.isfile(os.path.join(folder, f))\n ]",
"def files_in_folder(folder):\n files = []\n for f in glob.glob(folder):\n if os.path.isdir(f):\n files.extend(file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches the metadata remote file REMOTE_METADATA_FILE and returns the metadata dict equivalent. | def _fetch_current_remote_metadata(conn):
content = _get(conn, REMOTE_METADATA_FILE)
metadata = json.loads(content) if content else {}
return metadata | [
"def _get(conn, remote_file, bucket_name=BUCKET_NAME):\n contents = None\n try:\n reply = conn.get(bucket_name, remote_file)\n contents = reply.body\n if reply.http_response.status != 200:\n print 'Failed to fetch current_remote metadata'\n contents = None\n excep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches the metadata local file LOCAL_METADATA_FILE and returns the metadata dict equivalent. | def _fetch_current_local_metadata():
if not os.path.exists(LOCAL_METADATA_FILE):
return {}
with open(LOCAL_METADATA_FILE) as f:
return json.loads(f.read()) | [
"def _fetch_current_remote_metadata(conn):\n content = _get(conn, REMOTE_METADATA_FILE)\n metadata = json.loads(content) if content else {}\n return metadata",
"def get_metadata(base_dir, config):\n metadata_location = os.path.join(base_dir, config['PATH']['metadata_name'])\n with open(metadata_loc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Based on comparison of local and remote metada dictionaries, filter files to retain only the files which doesn't exist on remote metadata dict or have different content and same filename. Also, based on IGNORE_DIRS and IGNORE_EXTENSIONS, filter the net file list. | def _filter_file_list(files, local_metadata, remote_metadata):
def _is_tracked(filename, metadata):
"""
Is the filename tracked in the remote metadata dict.
The file may be not even locally tracked yet
"""
current_local_sha = local_metadata.get(filename, None)
current... | [
"def _filter_filesystem_files(files):\n filtered_files = []\n for path in files:\n relative_name = _remove_bundle_root(path)\n not_in_excludes = not any(\n [relative_name.startswith(e) for e in _LOCAL_WHITELIST_EXCLUDES])\n head_directory = relative_name.split(os.path.sep)[0]\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is the filename tracked in the remote metadata dict. The file may be not even locally tracked yet | def _is_tracked(filename, metadata):
current_local_sha = local_metadata.get(filename, None)
current_remote_sha = metadata.get(filename, None)
return current_local_sha is not None \
and current_remote_sha is not None \
and current_local_sha == current_remote_sha | [
"def is_remote_cached(cls, target_filename):\n is_cached = None\n cache = cls.CACHE_BACKEND()\n for file_name, file_id in cache.search():\n if file_name == os.path.basename(target_filename):\n is_cached = file_id\n logger.debug('File %r already cached at... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is the filename inside any of the IGNORE_DIRS list | def _is_inside_ignored_dir(filename):
ignore_dirs = ['./' + x for x in IGNORE_DIRS]
return any([filename.startswith(x) for x in ignore_dirs]) | [
"def is_in_ignored_directory(self, path):\r\n dirs = os.path.split(path)\r\n for dir in dirs:\r\n if dir in self.ignored_dirs:\r\n return True\r\n return False",
"def is_dir_ignored_file(file_name, cfg):\n if file_name:\n for pattern in cfg.options.dir_igno... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Walks through all the subfolders in static_root, and uploads everything valid found to S3. If Gzip is enabled, also tries to compress and upload the compressed version of the static asset. | def upload_all_to_s3(static_root):
conn = _get_connection()
files = _get_file_list(static_root)
_build_local_metadata_file(files, home=static_root)
local_metadata = _fetch_current_local_metadata()
remote_metadata = _fetch_current_remote_metadata(conn)
files_to_upload = _filter_file_list(files,... | [
"def test_upload(self):\n upload_static_assets.upload_static_files()\n\n s3 = boto3.resource('s3', region_name='us-east-1')\n for item in s3.Bucket(BUCKET).objects.all():\n self.assertTrue(item.key.startswith('static/base'),\n 'The only static files involve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a |random value| <= SHIFT_MAX_VAL | def get_shift() -> int:
return random.randint(low = -1 *SHIFT_MAX_VAL, high = SHIFT_MAX_VAL) | [
"def _rand_value(max_value):\n return randint(1, max_value)",
"def get_next_random(value, max_value, min_value, max_delta):\n # Determine if sensor delta should be added or substracted.\n if value == max_value:\n add = False\n elif value == min_value:\n add = True\n else:\n add... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load all of imagenet data as flat vector | def load_imagenet(directory):
path_train, path_val = directory + '/ILSVRC2012_img_train', directory + '/ILSVRC2012_img_val'
train_labels = os.listdir(path_train)
train_data = []
for label in train_labels:
imgs_path = os.path.join(path_train, label)
imgs = os.listdir(imgs_path)
fo... | [
"def loadData(path = \"../data/\"):\n A=[]\n for i in range(1,8):\n im = cv2.imread(path+\"input_\"+str(i)+\".tif\", -1) \n I_xyz =rgb2xyz(im)\n I_y=I_xyz[:,:,1].reshape(I_xyz.shape[0]*I_xyz.shape[1],1)\n A.append(I_y)\n A=np.asarray(A)\n I=A.reshape(A.shape[0],A.shape[1])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take as input a Keras ImageGen (Iterator) and generate random crops from the image batches generated by the original iterator. | def random_crop_generator(batches, crop_length):
while True:
batch_x, batch_y = next(batches)
batch_crops = np.zeros((batch_x.shape[0], crop_length, crop_length, 3))
for i in range(batch_x.shape[0]):
batch_crops[i] = random_crop(batch_x[i], (crop_length, crop_... | [
"def crop_generator(batch_generator, crop_length):\n while True:\n batch_x, batch_y = next(batch_generator)\n batch_crops = np.zeros((batch_x.shape[0], crop_length, crop_length, batch_x.shape[-1]))\n for i in range(batch_x.shape[0]):\n batch_crops[i] = random_crop(batch_x[i], (cro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To be used in conjunction with loss.binary_xentropy_with_sigmoid | def sigmoid_with_binary_xentropy(z):
return sigmoid(z) | [
"def test_sigmoid_cross_entropy(self):\n loss_op = pointwise_losses.SigmoidCrossEntropy()\n\n y_pred = loss_op.final_activation_op({\n \"logits\": self.logits,\n \"metadata\": {\n \"mask\": self.mask\n }\n })\n assert np.isclose(y_pred[0][0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To be used in conjunction with loss.xentropy_with_softmax | def softmax_with_xentropy(z):
return softmax(z) | [
"def cross_entropy_with_logits_loss(input, soft_target):\n return torch.sum(- soft_target * torch.nn.functional.log_softmax(input, 1), 1)",
"def test_softmax_cross_entropy(self):\n loss_op = listwise_losses.SoftmaxCrossEntropy()\n\n y_pred = loss_op.final_activation_op({\n \"logits\": ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the maximal score for a Yahtzee hand according to the upper section of the Yahtzee score card. | def score(hand):
max_score = []
for dice in hand:
max_score.append(hand.count(dice) * dice)
return max(max_score) | [
"def score(hand):\n summy = {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0}\n maxy = 0\n for ind in hand:\n summy[ind] = ind + summy[ind]\n for key in summy:\n if summy[key] > maxy:\n maxy = summy[key]\n return maxy",
"def score(hand):\n if (hand==()):\n return 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate all possible choices of dice from hand to hold. | def gen_all_holds(hand):
held_dice = [()]
for dice in hand:
for dummy_dice in held_dice:
held_dice = held_dice + [tuple(dummy_dice) + (dice, )]
return set(held_dice) | [
"def gen_all_holds(hand):\r\n possible_holds = set([()])\r\n \r\n for dice in hand:\r\n temp_holds = possible_holds.copy()\r\n for hold in temp_holds:\r\n temp_seq = list(hold)\r\n temp_seq.append(dice)\r\n possible_holds.add(tuple(temp_seq))\r\n \r\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the hold that maximizes the expected value when the discarded dice are rolled. | def strategy(hand, num_die_sides):
best_hold = (0.0, ())
current_score = 0
for held_dice in gen_all_holds(hand):
score = expected_value(held_dice, num_die_sides, len(hand) - len(held_dice))
if score > current_score:
current_score = score
best_hold =... | [
"def strategy(hand, num_die_sides):\n all_hold = list(gen_all_holds(hand))\n maxi_exp_val = 0\n print all_hold\n for hold in all_hold:\n if expected_value(hold, num_die_sides, len(hand) - len(hold)) >= maxi_exp_val:\n maxi_exp_val = expected_value(hold, num_die_sides, len(hand) - len(h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find names in a sentence based on a FIRST_NAMES file | def find_names(sentence=None, last_names_enabled=True, no_names_enabled=False):
if not sentence:
raise Exception(ParameterMissing, "This method requires sentence as input")
if not isinstance(sentence, str):
raise Exception(TypeError, "This method requires string as input")
first_names = ge... | [
"def find_names(text):\n\n names = []\n\n # spacy doc\n doc = nlp(text)\n\n # pattern\n pattern = [{'LOWER': 'prime'},\n {'LOWER': 'minister'},\n {'POS': 'ADP', 'OP': '?'},\n {'POS': 'PROPN'}]\n\n # Matcher class object\n matcher = Matcher(nlp.vocab)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find names position in a sentence based on a FIRST_NAMES file | def find_names_position(sentence=None, last_names_enabled=True, no_names_enabled=False):
if not sentence:
raise Exception(ParameterMissing, "This method requires sentence as input")
if not isinstance(sentence, str):
raise Exception(TypeError, "This method requires string as input")
names_f... | [
"def _findfirststart(starts, names):\n hout = []\n for hh in starts:\n for cc in names:\n if cc.startswith(hh):\n hout.append(cc)\n break\n return hout",
"def find_head(surnames):\n exp = \"(\\s?[A-ZÑÁÉÍÓÚ]{2,}(\\s[A-ZÑÁÉÍÓÚ]{1,})?(\\s[A-ZÑÁÉÍÓÚ]{1,})?(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display messages based on the window | def displayMessages(window,messages=['']):
# update messages text
message_in_line = ''
for msg in messages:
message_in_line += '\n'+msg
window['messages'].update(f'{message_in_line}') | [
"def display_messages(self, layout):",
"def show_message(self, txt):\n self.statusbar.showMessage(txt)",
"def show_msg(self, msg):\r\n self.statusbar.showMessage(msg)",
"def show_message(self, msg):\n try:\n if not self.msgs_shown[hash(msg)]: #If it haven't been shown yet.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalise an array between a given range. | def normalize_range(array, floor=0, ceil=1):
scaler = MinMaxScaler(feature_range=(floor, ceil), copy=True)
return scaler.fit_transform(array) | [
"def array_normalisation(self, array,new_min=0.0,new_max=1.0):\n\n array = array.astype(float)\n\n old_min = np.amin(array)\n old_max = np.amax(array)\n\n array = new_min + (array - old_min) * (new_max - new_min) / (old_max - old_min)\n\n return array",
"def normalize(arr):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalise an array by its maximum absolute value. Scales and translates each feature individually such that the maximal absolute value of each feature in the array will be 1.0. It does not shift/center the data, and thus does not destroy any sparsity. | def normalize_max_absolute(array):
scaler = MaxAbsScaler(copy=True)
return scaler.fit_transform(array) | [
"def max_normalization(array):\n return 1/np.max(array) * array.squeeze(axis=1)",
"def normalize(my_array: np.ndarray) -> np.ndarray:\n\n return np.abs(my_array)/np.max(np.abs(my_array))",
"def min_max_normalization_univariate(data) :\r\n\r\n scaled_data = [] #The data obtained afte scaling the given d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a diagonal mask computed from an array. Useful when the data is the same if you transpose the array, eg in a heatmap. | def get_diagonal_mask(data):
mask = np.zeros_like(data, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
return mask | [
"def makeMaskFromArray(array):\n if array is None: return None\n cls = globals()[\"Mask%s\" % suffixes[str(array.dtype.type)]]\n return cls(array)",
"def remove_diagonal(a):\n # TODO: parametrise dimensions\n return a[~np.eye(a.shape[0], dtype=bool)].reshape(a.shape[0], -1)",
"def row_as_diagonal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
|coro| Refetches the inventory. | async def update(self) -> None:
data = await self._state.http.get_user_inventory(self.owner.id64, self.game.app_id, self.game.context_id)
self._update(data) | [
"def fetchInventory(self, game):\n packetPipeline = game.getModInstance('ClientMod').packetPipeline\n packetPipeline.sendToServer(FetchInventoryPacket(game.player.name))",
"async def refresh_inventory(self) -> None:\n log.debug(\"Refreshing documentation inventory...\")\n\n # Clear the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve all instance of OSLicence | def find_all():
return ItopapiPrototype.find_all(ItopapiOSLicence) | [
"def get_socios(self):\n return self.__socios",
"def list_silos(self, kwargs):\n verbose = kwargs.get(\"verbose\", False)\n attributes = ALL if verbose else [\"cn\", \"objectClass\"]\n\n self.display(\n self.engine.query(\n self.engine.SILOS_FILTER(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the ItopapiOrganization corresponding to this server | def find_organization(self):
if self.org_id is not None:
ItopapiPrototype.get_itop_class('Organization').find(self.org_id)
return None | [
"def get_organization(self) -> dict:\n try:\n organizations = self.dashboard.organizations.getOrganizations()\n except meraki.exceptions.APIError as exception:\n print(f\"Error: Unable to get organizations: {exception}\")\n return None\n\n if not organizations:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether a Roman token is the next logical Roman token. This test is for Roman levels 3 or 6, and checks whether the next token is both a Roman numeral and the next bigger Roman numeral. For instance 'v' is a valid Roman numeral. But unless the current Roman evaluates to 4, the 'v' must be a level1 alpha marke... | def roman_surf_test(self, token, next_token):
if not token:
return False
for each in [token, next_token]:
if not roman_to_int(each):
return False
return roman_to_int(next_token) == roman_to_int(token) + 1 | [
"def roman_test(id_token):\n roman_int = roman_to_int(id_token)\n if not roman_int:\n return False\n if LEVEL_STATE.level() not in [3, 6]:\n return False\n if roman_int - 1 == roman_to_int(LEVEL_STATE.current_token()):\n return True",
"def is_roman(x):\n x = str(x).upper()\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch token from the server using the provided user, password resulting in subsequent web service requests for waveforms being authenticated for potential access to restricted data. | def _retrieve_jwt_token(self, user, password):
# force https so that we don't send around tokens unsecurely
url = 'https://{}/api/token'.format(urlparse(self.base_url).netloc)
# paranoid: check again that we only send the token to https
if urlparse(url).scheme != "https":
... | [
"def get_token(token_url, user_name, pass_word):\n # payload params for the post request\n print(\"Generating ArcGIS Online authentication token.\")\n params = {'f': 'pjson', 'username': user_name, 'password': pass_word,\n 'referer': referer, 'expiration': 1440}\n data = urllib.urlencode(pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A check if the jwt token is valid | def _validate_jwt_token(self):
# force https so that we don't send around tokens unsecurely
url = 'https://{}/api/token/verify'.format(urlparse(self.base_url).netloc)
# paranoid: check again that we only send the token to https
if urlparse(url).scheme != "https":
msg... | [
"def __token_is_valid(self):\n\n if not self.__login_token or len(self.__login_token) < 10:\n # Token is not set or totally invalid\n return False\n\n try:\n jwt.decode(self.__login_token, verify = False)\n return True\n except:\n # Most li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper method to fetch response via get_stations() and attach it to each trace in stream. | def _attach_responses(self, st):
netids = {}
for tr in st:
if tr.id not in netids:
netids[tr.id] = (tr.stats.starttime, tr.stats.endtime)
continue
netids[tr.id] = (
min(tr.stats.starttime, netids[tr.id][0]),
max(tr.s... | [
"def stations():\n print(\"server received request for stations data...\")\n return jsonify(stations_data)",
"async def _fetch_raw_stations(session: ClientSession, headers: dict, query_builder: BuildQuery) -> dict:\n # We don't know how many pages until our first call - so we assume one page to start wit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get full version information of webservice as a string. | def _get_webservice_versionstring(self, service):
version = self.get_webservice_version(service)
return ".".join(map(str, version)) | [
"def GetVersionString(self):\n return ConvertVersionToString(self.GetVersion())",
"def version_info(): \n return VERSION_s",
"def version_string(self):\n return self.server_version + ' ' + self.sys_version + ' ' + \"ToyWebResource/\"+str(__version__)",
"def version():\n version_info... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attaches the actually used dataselet URL to each Trace. | def _attach_dataselect_url_to_stream(self, st):
url = self._build_url("dataselect", "query")
for tr in st:
tr.stats._fdsnws_dataselect_url = url | [
"def add_data_url(self, url: str):\r\n if 'urls' in self.metadata:\r\n self.metadata['urls'].append(url)\r\n else:\r\n self.metadata['urls'] = [url]",
"def __traces_url(self):\n path = AGENT_TRACES_PATH % self.from_.pid\n return \"http://%s:%s/%s\" % (self.host, s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes any value and converts it to a string compliant with the FDSN webservices. Will raise a ValueError if the value could not be converted. >>> print(convert_to_string("abcd")) abcd >>> print(convert_to_string(1)) 1 >>> print(convert_to_string(1.2)) 1.2 >>> print(convert_to_string( \ UTCDateTime(2012, 1, 2, 3, 4, 5, ... | def convert_to_string(value):
if isinstance(value, str):
return value
# Boolean test must come before integer check!
elif isinstance(value, bool):
return str(value).lower()
elif isinstance(value, int):
return str(value)
elif isinstance(value, float):
return str(value)... | [
"def convert_to_str(value):\n if isinstance(value, basestring):\n return safe_unicode(value)\n else:\n return str(value)",
"def convert_to_str(value: Any) -> str:\n return get_convertor(value.__class__).to_str(value)",
"def make_str(value):\n if (sys.version_info > (3, 0)):\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test `construct_compose_dict` returns expected compose dict. | def test_construct_compose_dict(self):
expected_examplescraper_compose_dict = {
"version": "3",
"services": {
"scp1": {
"container_name": "scp1",
"environment": [
"TOR_PORT=9051",
"TOR... | [
"def test_construct_compose_dict_nonexisting_scraper(self):\n with self.assertRaises(ModuleNotFoundError):\n docker_compose.construct_compose_dict(\"nonexisting\")",
"def test_chemical_composition_trivial(self):\n expected = {\"U\": 1 / 3, \"Ag\": 2 / 3}\n self.assertDictEqual(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test `construct_compose_dict` raises `ModuleNotFoundError` for a nonexisting scraper. | def test_construct_compose_dict_nonexisting_scraper(self):
with self.assertRaises(ModuleNotFoundError):
docker_compose.construct_compose_dict("nonexisting") | [
"def test_construct_compose_dict(self):\n expected_examplescraper_compose_dict = {\n \"version\": \"3\",\n \"services\": {\n \"scp1\": {\n \"container_name\": \"scp1\",\n \"environment\": [\n \"TOR_PORT=9051\",\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the rating limit | def _testRatingLimit(self):
comment = models.Comment.objects.all()[0]
type = models.RatingType.objects.all()[0]
try:
val = type.limit + 10
rating = models.Rating(comment=comment, type=type, value=val)
rating.save()
assert rating.value == type.limi... | [
"def test_post_rating_greater_than_range(self):\n with self.login(self.test_user):\n response = self.post(\n \"pinax_ratings:rate\",\n content_type_id=ContentType.objects.get_for_model(self.forester).pk,\n object_id=self.forester.pk,\n da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test individual comment rating | def _testCommentRating(self):
try:
host = models.Host.objects.all()[0]
comment = models.Comment(text='test', host=host)
comment.save()
types = models.RatingType.objects.all()
items = []
for value, type in zip([3, 4, 5], types):
... | [
"def test_upvote_modifies_comment_score(self):\n comment = Comment.objects.get(body=\"987XYZ\")\n self.assertEqual(comment.score, DEFAULT_SCORE)\n vote = Vote.create(comment=comment, value=1, voter=self.user)\n comment = Comment.objects.get(body=\"987XYZ\")\n self.assertEqual(comm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test individual host rating | def _testHostRating(self):
try:
user = auth.User.objects.all()[0]
category = models.Category.objects.all()[0]
host = models.Host(user=user, category=category,
url='http://blah.com')
host.save()
comment = models.Comment(text='test', ho... | [
"def get_host_risk(self):",
"def test_get_dealer_ratings(self):\n pass",
"def test_ratings_by_different_users(self):\n\n self.signup('a@example.com', 'a')\n self.signup('b@example.com', 'b')\n\n self.login('a@example.com')\n csrf_token = self.get_csrf_token_from_response(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the different rating categories | def _testRatingCategories(self):
try:
user = auth.User.objects.all()[0]
category = models.Category.objects.all()[0]
host = models.Host(user=user, category=category,
url='http://blah.com')
host.save()
comment = models.Comment(text='te... | [
"def test_get_cat_score(self):\n classes = ['blue skin', 'pointy ears']\n negated_classes = []\n categories = ['ear feature', 'skin feature']\n\n categorical_score = self.annot_scorer._get_categorical_score(\n classes, negated_classes, categories,\n self.negation_we... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hit a BJcard and append it. Then, find all possible sums and the current hand. The current hand is defined as max. of possible sums The current hand should be 1 if burst | def hit(self, card):
self.append(card)
values=[]
values.append(card.value())
if values[0] < 2:
values.append(values[0]+ 10)
new_sums =set([v+s for v in values for s in self.possible_sums if v+s <=21])
new_sums =sorted(new_sums)
if len(new_sums) ==0:
... | [
"def calculate_hand(self):\n self.value = 0\n aces = 0\n for elem in self.cards:\n if elem[0] == \"J\" or elem[0] == \"Q\" or elem[0] == \"K\":\n self.value += 10\n elif elem[0] == \"A\":\n aces += 1\n else:\n self.value += elem[0]\n\n if aces > 0:\n if self.valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is current cards the Blackjack? | def is_blackjack(self):
if self.hand == 21 and len(list(self)) ==2:
print '%s = Blackjack'%self
return True | [
"def check_for_blackjack(self):\n if (self.dealer.hand.value + self.dealer.face_down.value) == 21:\n if self.player.hand.blackjack:\n return self.blackjack_push()\n else:\n return self.blackjack_dealer_win()\n\n if self.player.hand.blackjack():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restart another round. Check the remaining budget and leave the game if budget <= 0. Create new BJCards | def restart(self):
self.state ='active'
if self.budget <= 0:
return self.leave()
self.cards =BJCards()
self.bet_amount =0 | [
"def flop(self):\n for i in range(3):\n self.board.append(self.deck.deal_card())\n self.last_action = 0\n self.cur_bet = 0\n self.clean_state()",
"def play_a_game():\n\n # Create a new shuffled full deck\n deck = card.full_deck()\n random.shuffle(deck)\n\n # Start... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bet the amount of money. Cannot exceed player's budget | def bet(self, amount):
if amount >self.budget:
print 'you cannot bet because of little money'
else:
self.bet_amount = amount
print 'you bet %s' % (amount) | [
"def bet(self, amount):\r\n\r\n if self.players[self.active_player].credits < self.big_blind:\r\n message = \"Player {} won! Not enough money remaining.\".format(self.players[(self.active_player + 1) %\r\n len(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hit a card and check if bust | def hit(self, card):
self.cards.hit(card)
if self.cards.hand ==-1:
self.state ='burst' | [
"def hit(player):\n deal_random_card(player)",
"def hit(self, deck):\n self.showOneCard = False\n while self.getPoints() < 17:\n self.cards.append(deck.deal())",
"def deal_self(self):\n self.cards.hit(self.get_card())\n if self.cards.hand < 17 and self.cards.hand>=0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Face up dealer's hidden card and balance with players in the game | def showdown(self):
print "%s: %s" %(self.name, repr(self.cards)) # open dealer's cards
for player in self.game.players:
win = self.balance(player)
if win > 0:
print player.name, 'wins', win
elif win == 0:
print player.name, 'draw... | [
"def deal_cards(self):\n self.deck.shuffle(5)\n self.dealer.hand = self.deck.deal(1)\n self.dealer.value = self.dealer.calculate_value()\n for player in self.ingame:\n if player.bet != 0:\n player.hand = self.deck.deal(2)\n player.value = player.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dealer have no choice. Stand if hand >= 17, otherwise hit | def deal_self(self):
self.cards.hit(self.get_card())
if self.cards.hand < 17 and self.cards.hand>=0:
self.state = 'active'
elif self.cards.hand >= 17 and self.cards.hand <= 21:
self.state = 'stand'
elif self.cards.hand==-1:
self.state = 'burst' | [
"def stand(hand=bj.player1.hand):\r\n phv = bj.player1.hand_value_check(hand) # check player hand value\r\n phv = [x for x in phv if x <= 21]\r\n if hand == bj.player1.hand:\r\n if len(phv) > 0:\r\n bj.player1.final_hand_val = max(phv)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds valid positions for Tile mover in Skilaverkefni 8 Takes in current position of the game | def validpositions(tile):
if tile == 11 or tile == 21:
valid_pos = "n"
elif tile == 12:
valid_pos = "nes"
elif tile == 13:
valid_pos = "es"
elif tile == 22 or tile == 33:
valid_pos = "sw"
elif tile == 23:
valid_pos = "ew"
elif tile == 32:
valid_pos... | [
"def get_winning_move(state, player):\n position = []\n for i in range(16):\n if state.line_scoring[i] == player * 3:\n row, col = i // 4, i % 4\n for j in range(4):\n if not state[j, row, col]:\n position.append((j, row, col))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the tile according to what letter was put in a string Takes 2 arguments one for which direction was chosen and one for which tile it is currently located at Returns new tile | def tile_change(direction, tile):
lower_direction = direction.lower()
if lower_direction == "n":
tile += 1
elif lower_direction == "s":
tile -= 1
elif lower_direction == "e":
tile += 10
else:
tile -= 10
return tile | [
"def put_char(self, x, y, char, bg=None, fg=None):\r\n if 0 <= x < self.size[0] and 0 <= y < self.size[1]:\r\n tile = self.tiles[x][y]\r\n if (x,y) in self.dirty_tiles:\r\n tile = self.dirty_tiles[(x,y)]\r\n char = self.tile_set.get(char,self.tile_set[' '])\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize appointment's creation workflow; Pass to date definition | def create_appointment():
msg = render_template('date')
return question(msg) | [
"def test_cron_workflow_service_create_cron_workflow(self):\n pass",
"def create_appt(data):\r\n appt = objectify.Element(\"appointment\")\r\n appt.begin = data[\"begin\"]\r\n appt.uid = data[\"uid\"]\r\n appt.alarmTime = data[\"alarmTime\"]\r\n appt.state = data[\"state\"]\r\n appt.locat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set appointment's begin date; Pass to appointment's begin time | def appointment_date(begin_date):
session.attributes['begin_date'] = str(begin_date)
qs = render_template('time')
return question(qs) | [
"def set_begin_date(self, begin_date):\n self.set_value_into_input_field(self.begin_date_inputbox_locator, begin_date)",
"def begin_time(self, begin_time):\n self._begin_time = begin_time",
"def appointment_time(begin_time):\n\n session.attributes['begin_time'] = str(begin_time)\n msg = rend... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set appointment's begin_time; Pass to apppointment's end date | def appointment_time(begin_time):
session.attributes['begin_time'] = str(begin_time)
msg = render_template('end_date')
return question(msg) | [
"def appointment_date(begin_date):\n\n session.attributes['begin_date'] = str(begin_date)\n qs = render_template('time')\n return question(qs)",
"def begin_time(self, begin_time):\n self._begin_time = begin_time",
"def set_start_time(td, start_time):\n\n td.setStartTime(start_time)",
"def b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set appointment's end date; Pass to appointment's end time | def appointment_end_date(end_date):
session.attributes['end_date'] = str(end_date)
msg = render_template('end_time')
return question(msg) | [
"def end_date_time(self, end_date_time):\n\n self._end_date_time = end_date_time",
"def end_date(self, end_date):\n self._end_date = end_date",
"def appointment_end_time(end_time):\n\n session.attributes['end_time'] = str(end_time)\n form = AppointmentForm(session.attributes)\n form.submi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |